webservice client implementaion in axis2-1.6.2 in java - java

I have implemented webservice client in axis2-1.6.2 in java and I get response when I call first time and for subsequent second time I get below error
java.lang.NullPointerException
at org.apache.axis2.client.OperationClient.prepareMessageContext(OperationClient.java:293)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:180)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at org.apache.axis2.ccws.CustomerCareServiceStub.subscriberRetrieveLite(CustomerCareServiceStub.java:2380)
at Prepost.SubscriberRetrieveBalance.subscriberRetrieveLite(SubscriberRetrieveBalance.java:111)
at Prepost.CheckUser.doGet(CheckUser.java:149)
here is the API implementation class constructor which sets unique parameter which is same for all requests
public SubscriberRetrieveBalance(String url, String strCON_TimeOut, String strSO_TimeOut) {
try {
this.url = url;
stub = new CustomerCareServiceStub(url);
ServiceClient sClient = stub._getServiceClient();
Options options = sClient.getOptions();
options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);
options.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE);
//options.setTimeOutInMilliSeconds(2000);
TransportInDescription transportIn = new TransportInDescription("HTTP");
options.setTransportIn(transportIn);
options.setProperty(HTTPConstants.SO_TIMEOUT, Integer.parseInt(strSO_TimeOut));
options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, Integer.parseInt(strCON_TimeOut));
sClient.setOptions(options);
} catch (Exception e) {
if (e.getMessage().equals("Can not find the external id")) {
System.out.println("Exception ::" + e.getMessage());
}
}
}
and it is called in a servlet and for performance issue I make object of this class for different-2 states(urls) and saved these object to hashmap when first request comes for respective states then make new object and use that object for subsequent requests for that state
SubscriberRetrieveBalance objBal = null;
BalanceBean bal = new BalanceBean();
if (mapObj.isEmpty() || (mapObj.get(strIP) == null)) {
objBal = new SubscriberRetrieveBalance(url, strCON_TimeOut, strSO_TimeOut);
mapObj.put(strIP, objBal);
} else {
objBal = mapObj.get(strIP);
}
bal = objBal.subscriberRetrieveLite(strMsisdn, userId, token, strCircleId, strCircleName, strSessionId, strDlgId);
first time it gives response and then gives nullpointer exception and above error for all requests that belongs to that state
This code is working fine with axis2-1.5
Is there any change in axis2-1.6.2 version that every time it needs new object of API implemented class
Please suggest.

Related

How to swtich the state of workitem with tfs Java sdk

I try to swtich the state of a workitem from "New" to "Active" like follows:
WorkItemCollection co = tpc.getWorkItemClient().query("select xxxxxx...");
WorkItem newWorkItem = co.getWorkItem(0);
newWorkItem.getFields().getField(CoreFieldReferenceNames.STATE).setValue("Active");
but there is error reported like this :
Exception in thread "main" java.lang.IllegalArgumentException: field id [10112] does not exist in this collection (wi=5789377,size=9)
I assume there's something wrong with this method or this method doesn't support Azure Devops Server 2019U1 since this package is last published in 2018.
My Test code:
public class HelloJava {
public static void main(String[] args) {
// TODO Auto-generated method stub
URI serverURI = null;
try {
serverURI = new URI("xxxxxxxx");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Credentials credentials = new UsernamePasswordCredentials("xxx","xxx");
TFSTeamProjectCollection tpc = new TFSTeamProjectCollection(serverURI, credentials);
tpc.authenticate();
WorkItemClient myClient = tpc.getWorkItemClient();
WorkItemCollection myWorkitemCollection = myClient.query("SELECT [System.Id],[System.WorkItemType],[System.State] FROM workitems");
//Get workItem Task1
WorkItem myWorkItem = myWorkitemCollection.getWorkItem(0);
FieldCollection myFieldCollection = myWorkItem.getFields();
Field myField = myFieldCollection.getField(CoreFieldReferenceNames.STATE);
//Get workItem Task2
WorkItem myWorkItem2 = myWorkitemCollection.getWorkItem(1);
FieldCollection myFieldCollection2 = myWorkItem2.getFields();
Field myField2 = myFieldCollection2.getField(CoreFieldReferenceNames.STATE);
System.out.println(myField.getValue());
System.out.println(myField2.getValue());
myField2.setValue(myField.getValue()); //Where the error occurs.
System.out.println(myField.getValue());
System.out.println(myField2.getValue());
}
}
The Result:
The setValue() method will throw exception even when I'm trying to set Task1's state with Task2's state.
A strange thing is that it won't throw error if I give the current state as input... (If task1's state is To Do, it won't throw error for xx.setValue("To Do"). If I change the state to Doing via web portal, then the code throws error if I enter To Do next time!!!)
So I think you have to report this issue to the team of the sdk here to get a fix or share your feedback since maybe it just doesn't work for new Azure Devops Server 2019.

Using java mail receives another mail content type when it is called from a module

I have an Android project where I'm using java mail for receiving mails from a gmail account.
First, I implemented a class for handling the receiving of mails. I know, each mail has its own
type of content (String, MultiPart, ...). I'm only interested in mails with a content type of String.
Ok, so I instantiate my receiving class, call the receiving method and get all mails from my gmail account with a content type of String.
So far, so good. This works for me perfectly.
But, when I create an Android module (.aar file) from the receiving class (same code, no changes) and import it to another Android project, there is a strange behavior of receiving mails.
After I imported the Android module, I instantiate the receiving class, call the receiving method, I get the same mails as before, but now they have
a content type of QPDecoderStream.
For a better understanding, here is my receiving code:
public List<Mail> receive() {
List<Mail> mailList = new ArrayList<>();
try {
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", mConfig.getStoreProtocol());
Session session = Session.getInstance(properties, null);
mStore = session.getStore();
mStore.connect(mConfig.getImapHost(), mUsername, mPassword);
mInbox = mStore.getFolder(mConfig.getStoreFolder());
mInbox.open(Folder.READ_ONLY);
Message[] messages = mInbox.getMessages();
for (Message message : messages) {
String bodyPart = "";
Object content = message.getContent();
// Check for mail content type
if (content instanceof String) {
// This code is executed by "normal" method call within an Android class
Logger.info(MailReceiver.class, "Mail content is String");
bodyPart = (String) content;
} else if (content instanceof QPDecoderStream) {
// This code is executed by method call within an Android module
Logger.info(MailReceiver.class, "Mail content is QPDecoderStream");
BufferedInputStream in = new BufferedInputStream((InputStream) content);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
bodyPart = new String(out.toByteArray());
}
Mail mail = new Mail();
mail.setSubject(message.getSubject());
mail.setDate(message.getSentDate().toString());
mail.setContent(bodyPart);
mailList.add(mail);
}
} catch (Exception e) {
Logger.error(MailReceiver.class, "Exception occurred while receiving mail: " + e.getMessage());
} finally {
closeInbox();
closeStore();
}
return mailList;
}
I hope I could explain my problem sufficiently and I would be glad for some advices.
Thanks in advance.
Chris P.

Java : Using Spring remoting for getting objects from server

I am working on a JavaSE application in which I would like to connect to a Spring-MVC based server to get List of objects, Objects itself. I looked up on net, and came upon JSON. While I agree that it is working, but it is very inefficient as I have to go through the 2 while loops and seems not so sophisticated. For this reason I researched and found out I can use Spring remoting to achieve the task.
One thing I would like to do is to send over objects directly, instead of converting them by JSON, and sending.
I am pasting my code below for what I have with JSON, I would appreciate if I know this seems more better or is Spring remoting more sophisticated in long term too. A replacement code for the client side would be nice. Thanks.
Client code :
public void getCanvas(){
JsonFactory jsonFactory = new JsonFactory();
String canvas = "";
try {
JsonParser jsonParser = jsonFactory.createJsonParser(new URL(canvasURL));
JsonToken token = jsonParser.nextToken();
while (token!=JsonToken.START_ARRAY && token!=null){
token = jsonParser.nextToken();
if(token==null){break;}
System.out.println("Token is "+jsonParser.getText());
}
while (token!=JsonToken.END_ARRAY){
token = jsonParser.nextToken();
if(token == JsonToken.START_OBJECT){
canvas = jsonParser.toString();
System.out.println("Canvas is "+canvas);
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Canvas is "+canvas);
}
Server code :
#RequestMapping(value = "/getcanvas",method = RequestMethod.GET)
public #ResponseBody String getCanvasforFX(){
System.out.println("Canvas was requested");
Canvas canvas = this.canvasService.getCanvasById(10650);
canvas.setCanvasimage(null);
ObjectMapper objectMapper = new ObjectMapper();
try {
System.out.println("Canvas value is "+objectMapper.writeValueAsString(canvas));
return objectMapper.writeValueAsString(canvas);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
In the client-code I am getting the information, but again I have to read the fields, set them in object and update the UI, even though I am programming the server also, I want to directly receive an object, and cut out the middle-man(JSON). Thanks.

Printing the body of a message

I am trying to make a program that will neatly print all the bodies of the messages of my inbox yet exchange web services is making it difficult. I seem to have easy access to everything except the body of the message. This is what I'm doing right now
static final int SIZE = 10;
public static void main(String [] args) throws Exception {
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
ExchangeCredentials credentials = new WebCredentials("USERNAME","PASS");
service.setCredentials(credentials);
service.setUrl(new URI("https://MY_DOMAIN/ews/exchange.asmx"));
ItemView view = new ItemView (SIZE);
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Inbox, view);
System.out.println(findResults.getItems().size() + "Messages");
for (int i = 0; i < SIZE; ++i) {
try {
Item item = findResults.getItems().get(i);
System.out.println("SUBJECT: " + item.getSubject());
System.out.println("TO: " + item.getDisplayTo());
System.out.println("BODY: " + item.getBody().toString());
} catch (IndexOutOfBoundsException e) {
break;
}
}
Of course, I have my credentials and domain filled out fittingly for my code. When I run this I get this message though.
Exception in thread "main" microsoft.exchange.webservices.data.ServiceObjectPropertyException: You must load or assign this property before you can read its value.
at microsoft.exchange.webservices.data.PropertyBag.getPropertyValueOrException(Unknown Source)
at microsoft.exchange.webservices.data.PropertyBag.getObjectFromPropertyDefinition(Unknown Source)
at microsoft.exchange.webservices.data.Item.getBody(Unknown Source)
at Main.main(Main.java:26)
Line 26 is the line where I try to print the body. What am I doing wrong?
The FindItem operation doesn't return the Body of a Message so you need to make a separate GetItem Request to the server to get this. In the Managed API you should be able to use Load method to do this so just change
Item item = findResults.getItems().get(i);
item.Load()
Cheers
Glen
I've figured it out actually. It looks like ExchangeService will close the connection after it is done pulling the needed info. to fix this I made a function
private static ExchangeService getService() throws Exception {
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
ExchangeCredentials credentials = new WebCredentials("USERNAME","PASS");
service.setCredentials(credentials);
service.setUrl(new URI("DOMAIN"));
return service;
}
I then call load like so
getService().loadPropertiesForItems(findResults, itempropertyset);
Where I define itempropertyset as such
PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
itempropertyset.setRequestedBodyType(BodyType.Text);
view.setPropertySet(itempropertyset);

Fetch JSON Data from URL and Repeatedly Update SQLite Database

In my app, I create a SQLite database. Then I populate it with JSON data fetched from a URL using an instance of the HttpAsyncTask class in my main activity. That works fine, but I also want to update the database. New data (one row in the database) is added to the URL page once per day, and I want to implement a "synchronize" button in the app that updates the database with only the new information. Could I get some advice on how to do this? My HttpAsyncTask is below, if that helps - I'm thinking I might need an if/else clause in the onPostExecute() method that adds all the rows only if the database is getting created for the first time. I thought about trying to put an HttpAsyncTask class in my DatabaseHelper, but that doesn't really make sense.
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String...urls) {
return GET(urls[0]);
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject main = new JSONObject(result);
JSONObject body = main.getJSONObject("body");
JSONArray measuregrps = body.getJSONArray("measuregrps");
// get measurements for date, unit, and value (weight)
for (int i = 0; i < measuregrps.length(); i++) {
JSONObject row = measuregrps.getJSONObject(i);
// a lot of getting & parsing data happens
db.addEntry(new Entry(date, weight, null, null));
//adds all the lines every time this is run, but I only want to add all
//the lines once and then add new rows one by one from there
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static String GET(String url) {
InputStream is = null;
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse httpResponse = client.execute(get);
is = httpResponse.getEntity().getContent();
if (is != null)
result = convertInputStream(is);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("input stream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStream(InputStream is) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = "";
while((line = reader.readLine()) != null)
builder.append(line);
is.close();
return builder.toString();
}
Your implementation totally depends on the project requirements.
If there are continuously changes over the server, the right way to implement the synchronization process is:
1.
Implement the sync process, which works totally in background. This sync will be customized to call specific API calls/Service classes which will be required to sync.
2.
Server will prompt the mobile client for the data change.
3.
To get server updates, A continuously running service/Sync at some predefined intervals will be run and checks for the updates or implements the GCM.
Sync Adapter would be the best for the sync services.
Ohh, also don't forget to apply the content provider, as database calls would be concurrent from UI and background both.
Hope it may help to decide.
You have to check there is similar data available in the table if yes update the table and if no insert new data to table

Categories