I have two message driven beans
#MessageDriven(name = "SubscribersTopicQueueMDB", activationConfig = {
#ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "jms/topic/Subscribers"),
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge")})
public class SubscribersTopicQueueMDB implements MessageListener {
private final static Logger LOGGER = Logger.getLogger(SubscribersTopicQueueMDB.class.toString());
public SubscribersTopicQueueMDB() {
System.out.println("Topic: SubscribersTopicQueueMDB INIT ");
}
and
#MessageDriven(name = "SubscribersTopicSecondMDB", activationConfig = {
#ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "jms/topic/Subscriber"),
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge")})
public class SubscribersTopicSecondMDB implements MessageListener {
private final static Logger LOGGER = Logger.getLogger(SubscribersTopicSecondMDB.class.toString());
public SubscribersTopicSecondMDB() {
System.out.println("TOPIC: SubscribersTopicSecondMDB (Second) INIT ");
}
When i am sending message to topic jms/topic/Subscriber only first MDB is received message, second MDB does not receive any message.
How can i improve this?
my simple client
public static void sendTextMessage(String message, String passedDestination) {
if (message == null || passedDestination == null) {
return;
}
Context namingContext = null;
try {
String userName = JMS_DEFAULT_USERNAME;
String password = JMS_DEFAULT_PASSWORD;
// Set up the namingContext for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, JMS_INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, JMS_PROVIDER_URL);
// env.put(Context.SECURITY_PRINCIPAL, userName);
// env.put(Context.SECURITY_CREDENTIALS, password);
namingContext = new InitialContext(env);
// Perform the JNDI lookups
String connectionFactoryString = JMS_DEFAULT_CONNECTION_FACTORY;
System.out.println("+##Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
ConnectionFactory connectionFactory = (ConnectionFactory) namingContext.lookup(connectionFactoryString);
System.out.println("+###Found connection factory \"" + connectionFactoryString + "\" in JNDI " + connectionFactory.toString());
String destinationString = passedDestination;
System.out.println("+##Attempting to acquire destination \"" + destinationString + "\"");
Destination destination = (Destination) namingContext.lookup(destinationString);
System.out.println("+###Found destination \"" + destinationString + "\" in JNDI");
int count = 2;
String content = message;
//System.out.println("userName " + userName);
//System.out.println("password " + password);
try (JMSContext context = connectionFactory.createContext()) {
System.out.println("***************Sending to " + destinationString + " messages with content: " + content + " *********************");
context.createProducer().send(destination, content);
}
//return true;
} catch (NamingException e) {
e.printStackTrace();
} finally {
if (namingContext != null) {
try {
namingContext.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
// return false;
}
found my mistake one topic listen jms/topic/Subscriber second jms/topic/Subscribers.improved.
Related
This is my service class, It has public method getFilesFromDirAndUploadtoHost() and inside that i have a reattempt() inside an if condition. I need to cover more codes by junit. What will be the modified test class, test class i mentioned below.*
#Service
public class FileTransferServiceImpl {
#Override
public Boolean getFilesFromDirAndUploadtoHost() throws SftpException {
List<String> files = Stream.of(new File(sourcePath).listFiles()).filter(file -> !file.isDirectory())
.map(File::getName).filter(file -> !file.endsWith("zip")).collect(Collectors.toList());
if(files.isEmpty()){
logger.info("No Files found to transfer");
return true;
}
ChannelSftp channelSftp = createChannelSftp();
Boolean result = false;
Integer attemptNo = 0;
Date date = new Date();
SimpleDateFormat formatDate = new SimpleDateFormat("dd-MM-yyyy HH mm ss z");
formatDate.setTimeZone(TimeZone.getTimeZone("IST"));
String dirName = formatDate.format(date);
if (channelSftp != null) {
// Create new folder in target
try {
channelSftp.mkdir("/" + dirName);
} catch (SftpException e) {
logger.error("Directory creation unsuccessful", e);
}
// Initial Attempt
List<ProcessFile> processFiles = copyFilestoTarget(channelSftp, files, attemptNo, dirName);
List<ProcessFile> failedFiles = processFiles.stream().filter(processFile -> !processFile.getSuccessfulYN())
.collect(Collectors.toList());
// If any Failed files found set to retry
if (!failedFiles.isEmpty()) {
reattempt(channelSftp, failedFiles, attemptNo, processFiles, dirName);
}
disconnectChannelSftp(channelSftp);
// populaate Process Run
populateAndSaveProcessRun(processFiles, files, dirName);
result = true;
}
return result;
}
private List<ProcessFile> copyFilestoTarget(ChannelSftp channelSftp, List<String> files, Integer attempNo,
String dirName) {
List<ProcessFile> processFiles = new ArrayList<>();
for (String fileName : files) {
try {
if (!channelSftp.isConnected()) {
channelSftp = recreateChannelSftp();
}
channelSftp.put(sourcePath + "/" + fileName, targetPath + "/" + dirName);
processFiles.add(populateProcessFiles(fileName, attempNo, dirName, true));
} catch (JSchException e) {
logger.error("Reconnection failed attempt No: " + attempNo);
processFiles.add(populateProcessFiles(fileName, attempNo, dirName, false));
} catch (SftpException e) {
logger.error("File : " + fileName + " Transfer Failed Attempt No: " + attempNo);
processFiles.add(populateProcessFiles(fileName, attempNo, dirName, false));
}
}
return processFiles;
}
private void reattempt(ChannelSftp channelSftp, List<ProcessFile> failedFiles, Integer attemptNo,
List<ProcessFile> processFiles, String dirName) {
attemptNo = 1;
List<ProcessFile> newFailedFile = failedFiles;
while (attemptNo <= 3) {
newFailedFile = copyFilestoTarget(channelSftp,
newFailedFile.stream().filter(processFile -> !processFile.getSuccessfulYN())
.map(processFile -> processFile.getFileName()).collect(Collectors.toList()),
attemptNo, dirName);
processFiles.addAll(newFailedFile);
if (newFailedFile.stream().filter(processFile -> !processFile.getSuccessfulYN())
.collect(Collectors.toList()).isEmpty()) {
attemptNo = 4;
} else {
attemptNo++;
}
}
}
}
This is my test class what i shoule modify here so that i can cover more lines. Here i am not sure how to do that. If any one can help it will be great.
#ExtendWith(MockitoExtension.class)
public class FileTransferServiceTest {
#InjectMocks
private FileTransferServiceImpl fileTransferService = new FileTransferServiceImpl();
#Mock
private ProcessFileService processFileService;
#BeforeEach
public void beforeClass() {
ReflectionTestUtils.setField(fileTransferService, "sourcePath", "F:\\Sample-sftp prjt\\needToTransfer");
ReflectionTestUtils.setField(fileTransferService, "host", "SDC-CDPGP01-test.com.au");
ReflectionTestUtils.setField(fileTransferService, "port", 2222);
ReflectionTestUtils.setField(fileTransferService, "username", "tester");
ReflectionTestUtils.setField(fileTransferService, "password", "password");
ReflectionTestUtils.setField(fileTransferService, "sessionTimeout", 15000);
ReflectionTestUtils.setField(fileTransferService, "channelTimeout", 15000);
ReflectionTestUtils.setField(fileTransferService, "targetPath", "/");
}
#Test
void uploadToAemo() throws SftpException {
assertNotNull(fileTransferService.getFilesFromDirAndUploadtoHost());
}
}
i have installed the Oracle Analytics Server 5.9(New version of Oracle BI) in my linux server and we migrate the configurations and the meta data and repository from old version to this one.
also we had a .NET app that work with the web service of Oracle BI to get and set the user and groups of security realm in the domain of BI.
but now in Oracle Analytics Server, the web service does not work properly.
in the local domain it does work properly but when we deploy on the server of Analytics Server, it does not work properly.
my source code is :
#WebService
public class UserGroupMemberCls {
private static JMXConnector jmxConnector = null;
private static MBeanServerConnection mBeanServerConnection = null;
private static String webLogicHostname = "192.168.24.63";
private static String webLogicPort = "9500";
private static String webLogicUsername = "weblogic";
private static String webLogicPassword = "123456";
.
.
.
.
#WebMethod(exclude = true)
public static List getListOfGroups() throws Exception {
ObjectName securityMBeanName1 = new ObjectName("Security:Name=myrealmDefaultAuthenticator");
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST2");
try {
initConnection(webLogicHostname, webLogicPort);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST13");
List<String> allUsers = new ArrayList();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST14");
String cursor =
(String) mBeanServerConnection.invoke(securityMBeanName1, "listGroups",
new Object[] { "*", Integer.valueOf(100) },
new String[] { "java.lang.String", "java.lang.Integer" });
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST15");
boolean haveCurrent =
((Boolean) mBeanServerConnection.invoke(securityMBeanName1, "haveCurrent", new Object[] { cursor },
new String[] { "java.lang.String" })).booleanValue();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST16");
while (haveCurrent) {
String currentName =
(String) mBeanServerConnection.invoke(securityMBeanName1, "getCurrentName", new Object[] { cursor },
new String[] { "java.lang.String" });
allUsers.add(currentName);
mBeanServerConnection.invoke(securityMBeanName1, "advance", new Object[] { cursor },
new String[] { "java.lang.String" });
haveCurrent =
((Boolean) mBeanServerConnection.invoke(securityMBeanName1, "haveCurrent", new Object[] { cursor },
new String[] { "java.lang.String" })).booleanValue();
}
mBeanServerConnection.invoke(securityMBeanName1, "close", new Object[] { cursor },
new String[] { String.class.getName() });
jmxConnector.close();
jmxConnector = null;
return allUsers;
} catch (Exception ex) {
ex.printStackTrace();
jmxConnector.close();
throw new RuntimeException(ex);
}
}
.
.
.
.
#WebMethod(exclude = true)
public static void initConnection(String hostname, String portString) throws IOException, MalformedURLException {
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST3");
Integer portInteger = Integer.valueOf(portString);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST4");
int port = portInteger.intValue();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST5");
String mserver = "/weblogic.management.mbeanservers.runtime";
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TES6");
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "hostname : " + hostname);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "port : " + port);
JMXServiceURL serviceURL =
new JMXServiceURL("service:jmx:iiop:///jndi/iiop://" + hostname + ":" + port + mserver);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "serviceURL : " + serviceURL);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST7");
Hashtable<Object, Object> h = new Hashtable<Object, Object>();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "h1 : " + h);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST8");
String[] credentials = { webLogicUsername, webLogicPassword };
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST9");
h.put("jmx.remote.credentials", credentials);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "h2 : " + h);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST10");
try {
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "(Map) h : " + (Map) h);
jmxConnector = JMXConnectorFactory.connect(serviceURL, (Map) h);
} catch (IOException ioe) {
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)
.log(Level.SEVERE,
"MESSAGE : " + ioe.getMessage() + " >>>> " + "STACKTRACE : " + ioe.getStackTrace() +
" >>>> " + " CAUSE : " + ioe.getCause());
// TODO: Add catch code
ioe.printStackTrace();
}
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "jmxConnector : " + jmxConnector);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST11");
mBeanServerConnection = jmxConnector.getMBeanServerConnection();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST12");
}
and the output is :
public void Deposite() throws Exception
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/bank";
Connection con = DriverManager.getConnection(url,"root","admin");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your A/c no. : " );
acNo = Integer.parseInt(br.readLine());
String sql = "SELECT Name,Ac_No,Balance FROM CUSTOMER WHERE Ac_No=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1,acNo);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
String name = rs.getString("Name");
int acNo = rs.getInt("Ac_No");
float bal = rs.getFloat("Balance");
System.out.println(" "+name+" "+acNo+" "+bal);
}
System.out.println("Current Bal : "+bal);
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Deposite Amt : ");
amt = Float.parseFloat(br1.readLine());
bal = bal + amt;
//System.out.println("Current Bal : "+bal);
String sql1 = "UPDATE CUSTOMER SET Balance = ? WHERE Ac_No =?";
ps = con.prepareStatement(sql1);
ps.setInt(1,acNo);
ps.setFloat(2,bal);
int i = ps.executeUpdate();
System.out.println("New Balance updated.... "+i);
System.out.println("Transaction Successful....");
ps.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
sir..i am not getting the the Balance after while loop...and when i try to up-date it...it shows zero value for balance in console...while it is still contains that value what i inserted at first during creating a/c...
plz hlp me......console output
mysql workbench o/p
Example code. Try-with-resources takes care of closing, even when an exception is thrown.
static class Customer {
int acNo;
String name;
BigDecimal bal;
}
public static void main(String[] args)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your A/c no. : " );
int acNo = Integer.parseInt(br.readLine());
String url = "jdbc:mysql://localhost:3306/bank";
try (Connection con = DriverManager.getConnection(url, "root", "admin")) {
Customer customer = loadCustomer(acNo);
if (customer == null) {
System.out.println("Wrong account");
} else {
System.out.printf("Current balance for %s, account %d: %12.2f%n",
customer.name, customer.acNo, customer.bal);
}
} catch (SQLException e) {
e.printStacktrace();
}
}
private static Customer loadCustomer(int accNo) throws SQLException {
String sql = "SELECT Name, Balance FROM CUSTOMER WHERE Ac_No = ?";
try (PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, acNo);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
Customer customer = new Customer();
customer.acNo = acNo;
customer.name = rs.getString(1);
customer.bal = rs.getBigDecimal(2);
return customer;
}
}
}
return null;
}
I want to upload a file( any type of file ) into a forlder using web services and spring mvc so I have a sever side and a client side.
On my client side this is the code
#RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST , produces="application/json")
public #ResponseBody
Boolean uploadMultipleFileHandler(
#RequestParam("name") MultipartFile[] files) {
MailService ms= new MailService();
Map<String, List<ByteArrayResource>>rval = new HashMap<String, List<ByteArrayResource>>();
String message = "";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
List<Object> files1 = new ArrayList<>();
List<Object> files2 = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
System.out.println(file.getOriginalFilename());
try {
byte[] bytes = file.getBytes();
files1.add(new ByteArrayResource(bytes));
files2.add(file.getOriginalFilename());
//System.out.println(map.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
map.put("files", files1);
map.put("names", files2);
System.out.println(map.get("files").toString());
RestTemplate restTemplate = new RestTemplate();
String SERVER_URI="http://localhost:8080/BackEndFinalVersion";
Boolean p=restTemplate.postForObject(SERVER_URI+"/uploadMultipleFile", map, Boolean.class);
System.out.println(p.toString());
//message = message + ms.encodeFileToBase64Binary( bytes);
//rval.put("success",message);
return true;
}
and the server side code is
#RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody Boolean uploadMultipleFileHandler(#RequestParam("files") List<Object> files , #RequestParam("names") List<Object> names) {
//MailService ms= new MailService();
//Map<String, Object> rval = new HashMap<String, Object>();
String message = "";
System.out.println("looool");
System.out.println(files);
System.out.println(names);
//System.out.println(files.get(0).toString());
for (int i = 0; i < files.size(); i++) {
System.out.println(files.get(i).getClass());
String file = (String)files.get(i);
try {
byte[] bytes = file.getBytes();
//FileUtils.writeStringToFile(new File("log.txt"), file, Charset.defaultCharset());
// Creating the directory to store file
String rootPath = "C:/Users/Wassim/Desktop/uploads";
File dir = new File(rootPath);
if (!dir.exists())
dir.mkdirs();
File serverFile = new File(dir.getAbsolutePath() + File.separator + ( names.get(i)));
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
//message = message + "You successfully uploaded file=" + ( (MultipartFile) files.get(i)).getOriginalFilename() + "<br />";
//FileUtils.writeByteArrayToFile(new File(dir.getAbsolutePath() + File.separator + files.get(i).getOriginalFilename()), ms.decodeFileToBase64Binary(ms.encodeFileToBase64Binary( bytes)));
//rval.put("success"+i, message);
System.out.println("noooo");
} catch (Exception e) {
message += "You failed to upload " + " => " + e.getMessage();
//rval.put("error", message);
return false;
}
}
return true;
My problem is that this code doesn't work only with .txt files
can any one support me ??
I write a publish/subscriber sample and deploy it on websphere application server in cluster environment.
but when I subscribe the message, each message only and only one time was read by MDB.
I configured durable subscription in websphere and MDB, also I set the Share durable subscriptions to always shared and set the Always activate MDBs in all servers.
each message was read only one time, I think it consumes or something else.
I set the #ActivationConfigProperty(propertyName = "useSharedSubscriptionInClusteredContainer",propertyValue = "false") in MDB (based on http://docs.oracle.com/cd/E18930_01/html/821-2438/gjzpg.html#MQAGgjzpg), but nothing happened.
I can not subscribe messages in all servers.
Also i set the messaging engine policy to High availability in the websphere bus.
the Default messaging provider is used.
where is the problem??
here is my publisher
#WebServlet("/publishServlet")
public class Testpublish extends HttpServlet {
#Resource(mappedName = "jms/ConnFact")
private static TopicConnectionFactory topicConnectionFactory;
#Resource(mappedName = "jms/topicJ")
private static Topic topic;
TopicConnection connection = null;
TopicSession session = null;
TopicPublisher publisher = null;
TextMessage message = null;
final int NUM_MSGS = 5;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
ServletOutputStream out = response.getOutputStream();
out.println("Start Testing");
System.out.println("Start Testing");
try {
connection = topicConnectionFactory.createTopicConnection();
session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
publisher = session.createPublisher(topic);
message = session.createTextMessage();
for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is testMessage " + (i + 1));
System.out.println("Sending testMessage: " + message.getText());
out.println("Sending testMessage: " + message.getText());
publisher.publish(message);
}
connection.close();
out.println("Finish Testing");
System.out.println("Finish Testing");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
and my subscriber
#MessageDriven(mappedName = "jms/topicJ", activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
#ActivationConfigProperty(propertyName = "subscriptionDurability",propertyValue = "Durable"),
#ActivationConfigProperty(propertyName = "clientId",propertyValue = "MyID"),
#ActivationConfigProperty(propertyName = "subscriptionName",propertyValue = "MySub")
})
public class testsubscribe implements MessageListener {
#Override
public void onMessage(Message message) {
TextMessage txtMessage = (TextMessage) message;
try {
System.out.println("---------MESSAGE RECIEVED------------" + txtMessage.getText()
+ " ..............");
} catch (JMSException e) {
e.printStackTrace();
}
}
}
I resolved the problem by disabling the messaging engine policy in the websphere bus. Now it works well.