Not able to create JMS topic programatically in WebSphere - java

I'm not able to create SIB JMS topic or queue. I tried the below code. The code ran without any exception or error
public void createSIBJMSTopic(String topicName, String jndiName, String busName, String topicSpace) {
try {
String server = "server1";
String description = "abc";
Session session = new Session();
CommandMgr commandMgr = CommandMgr.getCommandMgr(client);
configService = new ConfigServiceProxy(client);
System.out.println("Commands list" + commandMgr.listAllCommands().toString());
AdminCommand cmd = commandMgr.createCommand("createSIBJMSTopic");
System.out.println(session);
ObjectName targetObject = configService.resolve(session, null, "Node=mbaastest40Node02,Server=server1")[0];
cmd.setTargetObject(targetObject);
cmd.setParameter("name", topicName);
cmd.setParameter("jndiName", jndiName);
cmd.setParameter("busName", busName);
cmd.setParameter("topicSpace", topicSpace);
System.out.println("Before Execute");
cmd.execute();
CommandResult result = cmd.getCommandResult();
System.out.println("after execute");
if (result.isSuccessful())
System.out.println(result.toString());
if (!result.isSuccessful())
throw new AdminException(result.getException());
System.out.println("done");
configService.save(session, true);
System.out.println("After save");
}
catch (Exception e) {
e.printStackTrace();
}
}

You need to link the AdminCommand with the config Session via:
AdminCommand cmd = commandMgr.createCommand("createSIBJMSTopic");
cmd.setConfigSession(session);
You should also note the recommendation to call configService.discard(session) when done:
Here's a good getting started article that may help too.

Related

java- how to retrieve resultset from database without using JDBC?

I am writing a program that acts as a service and picks up emails from the email queue table, processes them and sends them out. Here is something along how I did it, and it does work fine.
MySqlConnect con = new MySqlConnect();
public PreparedStatement preparedStatement = null;
public Connection con1 = con.connect();
//pick up queue and send email
public void email() throws Exception {
try {
while(true) {
String sql = "SELECT id,user,subject,recipient,content FROM emailqueue WHERE status='Pending' ";
PreparedStatement statement = con1.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
String subject = rs.getString("subject");
String recipient = rs.getString("recipient");
String content = rs.getString("content");
String id = rs.getString("id");
String username = rs.getString("user");
String emailStatus = "DONE";
String errormsg = sendEmail(recipient, subject, content, id,username);
if (!errormsg.equals("")) {
emailStatus = "FAILED";
}
TerminalLogger.printMsg("Status : " + emailStatus);
}
statement.close();
rs.close();
}
} catch(Exception e) {
e.printStackTrace();
TerminalLogger.printMsg("Exception: "+e.toString());
}
con1.close();
Thread.sleep(2000);
}
Now, I am clearly using JDBC to obtain the result set in the loop and process them as shown. Of course, I also need to specify my database connection in MySqlConnect.java properties. While all this works perfectly fine, I was wondering is there another way of achieving the same goal without using JDBC, i.e. specifying the connection properties?
I was thinking of Java Persistence. I am new to this.
Edit
I have been told to use JPA to achieve this and I have written it in this way:
public void email() throws Exception {
try {
while(true) {
String sql = "select p.id,p.user,p.subject,p.recipient,p.content from Emailqueue p where " +
"status='Pending'";
List<Object[]> list = em.createQuery(sql).getResultList();
for (Object[] obj : list) {
System.out.println(obj[0]);
System.out.println(obj[1]);
System.out.println(obj[2]);
System.out.println(obj[3]);
System.out.println(obj[4]);
}
}
} catch(Exception e) {
e.printStackTrace();
TerminalLogger.printMsg("Exception: " + e.toString());
}
From here, I would pass the parameters I want to the method. Is this way feasible?
Edit 2
Did it a bit different like below:
String id = ejbCon.getSettingsFacade().getid();
String username = ejbCon.getSettingsFacade().getUser();
String subject = ejbCon.getSettingsFacade().getSubject();
String recipient = ejbCon.getSettingsFacade().getRecipient();
String content = ejbCon.getSettingsFacade().getContent();
String errormsg = sendEmail(recipient, subject, content, id,username);
public String getContent() {
try {
String sql="Select content FROM emailqueue WHERE status='Pending'";
if (em == null) {
throw new Exception("could not found subject");
}
return (String) em.createNativeQuery(sql).getSingleResult();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Just a bit idea of how the method looks like, the other methods follow the same concept.
List<EmailQueue> emailList = em.createQuery(sql).getResultList();
for (EmailQueue obj : emailList) {
String emailStatus = "DONE";
String errormsg=sendEmail(obj.getRecipient(), obj.getSubject, obj.getContent(),obj.getId(),obj.getUsername());
if (!errormsg.equals("")) {
emailStatus = "FAILED"
}
TerminalLogger.printMsg("Status : " + emailStatus);
}
}
Before using JPA ,you must read about it WHY JPA
As discussed in the comments above, Spring Batch and Spring JPA is a good choice for your use-case,
you can follow and study about on the internet and follow the official document
Spring JPA tutorial link
Spring Batch tutorial link
Happy Learning, Hope more users would suggest other good options that you can choose from and apply to your use-case post evaluating their pros and cons

how to get message number that content type 's "multipart" from gmail?

I want to get the message number list that the content type is "multipart".I tried using javaxmail, it works but i don't want to get the messages and then do the filter.
try {
Session emailSession = Session.getDefaultInstance(this.setPropertiesParams());
Store store = emailSession.getStore("imaps");
store.connect(host, email, emailPassword);
Folder emailFolder;
emailFolder = store.getFolder("Documents");
emailFolder.open(Folder.READ_ONLY);
SearchTerm andTerm = searchMessageByDate(fromDate, toDate);
Message[] messages = emailFolder.search(andTerm);
Message[] finalMessages = emailFolder.search(new SubjectTerm("Scan de votre document"), messages);
for (Message message : finalMessages) {
String contentType = message.getContentType();
if (contentType.contains("multipart")) {
Integer messageNumber = message.getMessageNumber();
numberList.add(messageNumber);
}
}
emailFolder.close(false);
store.close();
How to do it. thanks for any help.
You can implement a new subclass of SearchTerm that does that, but the message would probably have to be fetched anyway. I don't think you can avoid it.
public class ContentTypeTerm extends SearchTerm {
#Override
public boolean match(Message msg) {
try {
return msg.isMimeType("multipart/*");
} catch (MessagingException ex) {
throw new RuntimeException(ex.getMessage());
}
}
}
UPDATE
You could actually use a HeaderTerm:
SearchTerm[] terms = {
searchMessageByDate(fromDate, toDate),
new HeaderTerm("Content-Type", "multipart/.*")
};
SearchTerm andTerm = new AndTerm(terms);

WebServiceException: Method beaInvoke is exposed as WebMethod

Below is the code Snippet.. that must call WSDL in other server dynamically
but in the moment of calling
(int i = webServiceModuleService.notificationRecieved("xyz");)
returned exception :(
note: i haven't any beaInvoke method in my service :|
public static void main(String[] args) {
java.sql.Connection conn = null;
InitialContext context;
try {
context = new InitialContext();
DataSource ds = (DataSource) context.lookup("jdbc/dataSourceDS");
conn = ds.getConnection();
} catch (SQLException e) {
} catch (NamingException e) {
}
QueryRunner run = new QueryRunner();
SampleResultSetHandler h = new SampleResultSetHandler();
Object[] res = null;
try {
res = run.query(conn, "select SERVER_IP,SERVER_PORT from SERVER where UPPER(SERVER_NAME)=? ", h, "test");
} catch (SQLException e) {
}
String ip = res[0].toString();
String port = res[1].toString();
String endpointURL = "http://" + ip + ":" + port + "/context-root/WebServiceModuleService";
try {
URL tmpURL = new URL(endpointURL + "?wsdl");
System.err.println(tmpURL);
WebServiceModuleService_Service webServiceModuleService_Service = new WebServiceModuleService_Service(tmpURL,
new QName("/org/parsisys/test/mina/model/services/common/",
"WebServiceModuleService"));
WebServiceModuleService webServiceModuleService = null;
webServiceModuleService = webServiceModuleService_Service.getWebServiceModuleServiceSoapHttpPort();
BindingProvider bp = (BindingProvider) webServiceModuleService;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
// Configure credential providers
Map<String, Object> requestContext = ((BindingProvider) webServiceModuleService).getRequestContext();
try {
setPortCredentialProviderList(requestContext);
} catch (Exception ex) {
ex.printStackTrace();
}
//Call WebService ... ==> Exception :(
int i = webServiceModuleService.notificationRecieved("xyz");
//logp("successfully call the webservice for [ip&port:" + ip + ":" + port + "] [transid : " +transid + "]");
} catch (Exception e) {
//log
//TODO: Clean This
System.err.println(e.getMessage());
e.printStackTrace();
return;
}
}
#Generated("Oracle JDeveloper")
public static void setPortCredentialProviderList(Map<String, Object> requestContext) throws Exception {
// TODO - Provide the required credential values
String username = "";
String password = "";
String clientKeyStore = "";
String clientKeyStorePassword = "";
String clientKeyAlias = "";
String clientKeyPassword = "";
String serverKeyStore = "";
String serverKeyStorePassword = "";
String serverKeyAlias = "";
List<CredentialProvider> credList = new ArrayList<CredentialProvider>();
// Add the necessary credential providers to the list
// Code commented out due to empty username/password value found in the credential.
// credList.add(getUNTCredentialProvider(username, password));
// Code commented out due to empty server keystore value found in the credential.
// credList.add(getBSTCredentialProvider(clientKeyStore, clientKeyStorePassword, clientKeyAlias, clientKeyPassword, serverKeyStore, serverKeyStorePassword, serverKeyAlias, requestContext));
credList.add(getSAMLTrustCredentialProvider());
requestContext.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credList);
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getSAMLTrustCredentialProvider() {
return new SAMLTrustCredentialProvider();
}
daynamic webservice call is generated with jdeveloper and it's works in clien't tester but in my module when i call webservice return exception :/
StackTrace is: ↓
Method beaInvoke is exposed as WebMethod, but there is no corresponding wsdl operation with name {/org/parsisys/test/mina/model/services/common/}beaInvoke in the wsdl:portType{/org/parsisys/test/mina/model/services/common/}WebServiceModuleService
javax.xml.ws.WebServiceException: Method beaInvoke is exposed as WebMethod, but there is no corresponding wsdl operation with name {/org/parsisys/test/mina/model/services/common/}beaInvoke in the wsdl:portType{/org/parsisys/test/mina/model/services/common/}WebServiceModuleService
at com.sun.xml.ws.model.JavaMethodImpl.freeze(JavaMethodImpl.java:382)
at com.sun.xml.ws.model.AbstractSEIModelImpl.freeze(AbstractSEIModelImpl.java:124)
at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:336)
at com.sun.xml.ws.db.DatabindingImpl.(DatabindingImpl.java:99)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:74)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:58)
at com.sun.xml.ws.db.DatabindingFactoryImpl.createRuntime(DatabindingFactoryImpl.java:120)
at com.sun.xml.ws.client.WSServiceDelegate.buildRuntimeModel(WSServiceDelegate.java:882)
at com.sun.xml.ws.client.WSServiceDelegate.createSEIPortInfo(WSServiceDelegate.java:899)
at com.sun.xml.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:862)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:451)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.internalGetPort(WLSProvider.java:1698)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$PortClientInstanceFactory.createClientInstance(WLSProvider.java:1769)
at weblogic.wsee.jaxws.spi.ClientInstancePool.takeSimpleClientInstance(ClientInstancePool.java:389)
at weblogic.wsee.jaxws.spi.ClientInstancePool.take(ClientInstancePool.java:243)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$3.apply(WLSProvider.java:1555)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$3.apply(WLSProvider.java:1517)
at weblogic.wsee.jaxws.spi.ClientIdentityRegistry.initClientIdentityFeatureAndCall(ClientIdentityRegistry.java:1456)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.getPort(WLSProvider.java:1513)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:420)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.getPort(WLSProvider.java:1477)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:402)
at javax.xml.ws.Service.getPort(Service.java:119)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service.beaInvokeSuper(WebServiceModuleService_Service.java)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service$beaVersion0_31.getWebServiceModuleServiceSoapHttpPort(WebServiceModuleService_Service.java:51)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service.getWebServiceModuleServiceSoapHttpPort(WebServiceModuleService_Service.java)
at org.parsisys.test.mina.files.notification.queue.NotificationQueueRecieved$beaVersion0_11.onMessage(NotificationQueueRecieved.java:330)
at org.parsisys.test.mina.files.notification.queue.NotificationQueueRecieved.onMessage(NotificationQueueRecieved.java)
at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:5107)
at weblogic.jms.client.JMSSession.execute(JMSSession.java:4775)
at weblogic.jms.client.JMSSession.executeMessage(JMSSession.java:4170)
at weblogic.jms.client.JMSSession.access$000(JMSSession.java:127)
at weblogic.jms.client.JMSSession$UseForRunnable.run(JMSSession.java:5627)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
please help me. tnx
For me this occurs when the WSDL does not agree with the generated classes.

Get PayPal account history using REST

I want to use Java PayPal SDK to get account history. I tried this simple code:
public void randomDatabaseData() throws SQLException, FileNotFoundException, IOException, PayPalRESTException {
String clientID = "test";
String clientSecret = "test";
String accessToken = null;
try {
Map<String, String> map = new HashMap<String, String>();
map.put("mode", "live");
try {
accessToken = new OAuthTokenCredential(clientID, clientSecret, map).getAccessToken();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(accessToken);
transactionSearch(accessToken);
} catch (Exception e) {
e.printStackTrace();
}
}
public TransactionSearchResponseType transactionSearch(String accessToken) {
TransactionSearchReq transactionSearchReq = new TransactionSearchReq();
TransactionSearchRequestType transactionSearchRequest = new TransactionSearchRequestType(
"2012-12-25T00:00:00+0530");
transactionSearchReq.setTransactionSearchRequest(transactionSearchRequest);
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
service.setTokenSecret(accessToken);
TransactionSearchResponseType transactionSearchResponse = null;
try {
transactionSearchResponse = service.transactionSearch(transactionSearchReq);
} catch (Exception e) {
System.out.println("Error Message : " + e.getMessage());
}
if (transactionSearchResponse.getAck().getValue().equalsIgnoreCase("success")) {
Iterator<PaymentTransactionSearchResultType> iterator = transactionSearchResponse
.getPaymentTransactions().iterator();
while (iterator.hasNext()) {
PaymentTransactionSearchResultType searchResult = iterator.next();
System.out.println("Transaction ID : " + searchResult.getTransactionID());
}
} else {
List<ErrorType> errorList = transactionSearchResponse.getErrors();
System.out.println("API Error Message : " + errorList.get(0).getLongMessage());
}
return transactionSearchResponse;
}
But I get his error stack when I run the code:
Error Message : configurationMap cannot be null
java.lang.NullPointerException
at com.crm.web.tickets.GenearateTicketsTest.transactionSearch(GenearateTicketsTest.java:161)
at com.crm.web.tickets.GenearateTicketsTest.randomDatabaseData(GenearateTicketsTest.java:139)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
How I can fix this code? I configure client ID and secret key into PayPal web site but still I get error.
I recommend you using TransactionSearch API to get the payment history based on your search date range.

workflow from java code suspended

i am running a workflow which has java code which in turn launches another oozie workflow. the main workflow is working fine but the workflow launched from the java code is always in suspended status. i am unable to resume it because the user for that is mapred and not me. any idea what might be the problem?
here's my main workflow
<java>
<job-tracker>${jobTracker}</job-tracker>
<name-node>${nameNode}</name-node>
<main-class>com.last.play.LaunchJob</main-class>
<arg>currentUser=${currentUser}</arg>
</java>
and here's the java code:
Map<String, String> commandArgs = getActionArgs(args);
Path appPropertyPath = new Path("/user/cmahajan/app.properties");
Path jobPropertyPath = new Path("/user/cmahajan/job.properties");
OozieClient wc = new OozieClient("http://host07.com:11000/oozie");
String userName = commandArgs.get("currentUser");
System.out.println("User Name recieved ::" + userName);
Configuration trial = new Configuration();
FileSystem fs = FileSystem.get(trial);
Properties conf = wc.createConfiguration();
Properties jobProperties = new Properties();
Properties appProperties = new Properties();
appProperties.load(fs.open(appPropertyPath));
String version = appProperties.getProperty("version");
jobProperties.load(fs.open(jobPropertyPath));
for (Object key : jobProperties.keySet()) {
String propValue = jobProperties.getProperty((String) key);
propValue = propValue.replaceAll("\\$\\{user.name\\}", userName);
conf.setProperty((String) key, propValue);
System.out.println("Key ::" + key);
System.out.println("Value ::" + propValue);
System.out.println(" ===================");
}
String appsRoot = "${wfsBasePath}/" + version + "/apps";
conf.setProperty("appsRoot", appsRoot);
try {
String jobId = wc.run(conf);
System.out.println("Workflow job submitted");
while (wc.getJobInfo(jobId).getStatus() == WorkflowJob.Status.RUNNING) {
System.out.println("Workflow job running ...");
Thread.sleep(10 * 1000);
}
System.out.println("Workflow job completed ...");
System.out.println(wc.getJobInfo(jobId));
} catch (OozieClientException oozieClientException) {
oozieClientException.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
You can use the UserGroupInformation to set the user.
UserGroupInformation ugi = UserGroupInformation.createRemoteUser(username);
ugi.doAs(new PrivilegedExceptionAction<MyMapReduceWrapperClass>() {
public Object run() throws Exception {
MyMapReduceWrapperClass mr = new MyMapReduceWrapperClass();
ToolRunner.run(mr, null);
return mr;
}
});

Categories