codename one web services soap call not working - java

I want to consume SOAP based web services when click on a login button.
My code is as follows
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" CaterId : "+catererId.getText());
Log.p(" Username : "+loginId.getText());
Log.p(" Password : "+password.getText());
final String InputParameter = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">"
+" <soap:Header/>"
+" <soap:Body>"
+" <tem:AuthenticateSupervisor>"
+" <tem:username>TestAbhi</tem:username>"
+" <tem:password>TestAbhi</tem:password>"
+" <tem:caterer>calihanint</tem:caterer>"
+" </tem:AuthenticateSupervisor>"
+" </soap:Body>"
+"</soap:Envelope>";
ConnectionRequest r= new ConnectionRequest() {
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(InputParameter.getBytes("UTF-8"));
}
#Override
protected void postResponse() {
//super.postResponse();
}
#Override
protected void readResponse(InputStream input) throws IOException {
//super.readResponse(input);
XMLParser parser = new XMLParser();
Element elem = parser.parse(new InputStreamReader(input));
Log.p(" Came heer"+elem);
}
};
r.setUrl("http://192.168.10.224:8888/CXPPostScheduleService/Service.asmx");
r.setPost(false);
/*r.addArgument("username", "TestAbhi");
r.addArgument("password", "TestAbhi");
r.addArgument("caterer", "calihanint");*/
r.setContentType("application/soap+xml;charset=UTF-8");
NetworkManager.getInstance().addToQueueAndWait(r);
r.getResponseData();
}
});
It displays an html file as response. Could you please assist me to check what I'm doing wrong in this code.

I assume you need a post request try:
r.setPost(true);
If you are calling this from the device make sure the device is in the same network as the server otherwise the NAT local address will be unreachable. Notice that this will also apply to the simulator if the server is hosted elsewhere and not on your machine.
I also suggest checking the server logs, the error response code and post the error HTML. You can use the network monitor tool in the simulator to further debug this.

Related

WordAPI ApiException caught: Not Found

I'm following [this][1] documentation to connect to api, I want to build a JavaFX app that you can enter a word and it's retrieves it from api and I wanted to test the feature before displaying contents on GUI. Howerer I got this exception that the words is not found while I tested endpoint in their website and that word had definitions. I'm pretty new to using API perhaps I missed something that isn't shown in the documentation?
Here is my code:
public void testDetailsWords(String word,String detail) {
//String word = "lovely"; // Word
//String detail = "definitions"; // Detail
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
apiClient = Configuration.getDefaultApiClient();
apiClient.setBasePath("https://www.wordsapi.com/");
// configure authentications
Authentication auth;
auth = apiClient.getAuthentication("Default");
((ApiKeyAuth) auth).setApiKey(Apikey);
try {
WordsApi wordsApi = new WordsApi();
DetailsResponse response = wordsApi.details(word, detail);
System.out.println(response);
} catch (ApiException e) {
System.out.printf("ApiException caught: %s\n", e.getMessage());
}
}
Here is my Controller code :
#FXML
private void handleDefinitions(ActionEvent event) throws IOException {
String word =definitionsfield.getText();
String detail= "definitions";
apiCall.testDetailsWords(word,detail);
}
I would be grateful for the help.
[1]: http://restunited.com/docs/6vc24wq3ojpq
It's seems that tutorial that I tried following is very misleading which is very dissapoing, but I've learned my lesson now .
I decided to use Unirest to get request and it's worked perfectly.
If you stumble upon the link it's better not to follow that tutorial

Display web service results on a form (Codename One)

After watching these videos, I'm trying to do the same but I'm finding it very difficult as I'm using the old GUI Builder.
I created a form called Form A. I want those results from the web service to display on the form A and be able to navigate upon clicking any of those images just like what happened inside the video.
I'm using the following methods:
private Map response;
#Override
protected void beforeFormA(Form f) {
getattractive();
ArrayList arr = (ArrayList) response.get("results");
for (Object m:arr){
Map ma = (Map)m;
address =(String) ma.get("formatted_address");
findContainer(f).addComponent(new Label(""+ address ));
}
}
Connection Request:
private void getattractive(){
ConnectionRequest r= new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parse= new JSONParser();
response= parse.parseJSON(new InputStreamReader(input));
}
};
String doc="Johor";
r.setUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query="+doc+"+city+point+of+interest&language=en&key=api_key");
r.setPost(false);
r.setHttpMethod("GET");
InfiniteProgress prog=new InfiniteProgress();
Dialog dlg=prog.showInifiniteBlocking();
r.setDisposeOnCompletion(dlg);
NetworkManager.getInstance(). addToQueueAndWait(r);
}
First record from the webservice (Attached picture):
Please kindly help.
Regards,
IDE: NetBeans
Desktop OS: Windows 7
Simulator

How to create interactive USSD menu?

I am currently using map-api-2.1.0.jar and map-impl-2.1.0.jar for handling USSD string from mobile phone. This is working fine and user is receiving USSD response.
MapHandling Class
public class MapHandling implements MAPDialogListener,MAPServiceSmsListener,MAPServiceMobilityListener,MAPServiceCallHandlingListener,MAPSer viceSupplementaryListener{
#Override
public void onProcessUnstructuredSSRequest(ProcessUnstructuredSSRequest procUnstrReqInd)
{
try
{
logger.debug("dialogId: " +procUnstrReqInd.getMAPDialog().getLocalDialogId() + " USSD String:"+procUnstrReqInd.getUSSDString()+"MSISDN:"+procUnstrReqInd.getMAPDialog().getReceivedDestReference().getAddress());
} catch (Exception exp)
{
logger.error("USSD - error while loging ussd data ", exp);
}
ss7.request.UnstructuredSSRequest ussdRequest = new ss7.request.UnstructuredSSRequest(procUnstrReqInd);
Thread thr = new Thread(ussdRequest);
thr.start();
}
}
ss7.request.UnstructuredSSRequest Class
public class UnstructuredSSRequest extends SS7Operation implements Runnable {
ProcessUnstructuredSSRequest procUnstrReqInd;
public UnstructuredSSRequest(ProcessUnstructuredSSRequest procUnstrReqInd) {
this.procUnstrReqInd = procUnstrReqInd;
}
#Override
public void run() {
logger.debug("[" + refId + "] Sending USSD response");
sendUSSDResponse(validRequest);
}
private void sendUSSDResponse(boolean validRequest) {
MAPDialogSupplementary dialog = procUnstrReqInd.getMAPDialog();
USSDString ussdStrObj = MapProvider.getMAPParameterFactory().createUSSDString("Thank you for using CC service!");
dialog.addProcessUnstructuredSSResponse(procUnstrReqInd.getInvokeId(),procUnstrReqInd.getDataCodingScheme(), ussdStrObj);
dialog.close(false);
dialog.release();
}
}
Above code is running fine and I receive "Thank you for using CC service!" response when I dial USSD from my phone.
I want to change this into an interactive USSD handler, I want to take input from user when he dials USSD code instead of sending him response and closing the session.
Kindly help me how can I maintain a session for user and take his input.
I believe you are using Mobicents jSS7 project and above code is server side connected to HLR/MSC over SIGTRAN or E1.
If yes, you can see the sample code for server side at https://code.google.com/p/jss7/source/browse/map/load/src/main/java/org/mobicents/protocols/ss7/map/load/Server.java

Google App Engine HTTP ERROR 503 error

Ï am Taking data From server written in "C" using Sockets .
My java class name is ReceivingData, and here's the code for receiving the data and storing it in ArrayList and passing the ArrayList to other Class's Constructor.
package pack.exp;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ReceivingData implements Runnable
{
public static void main(String[] args)
{
Thread t = new Thread(new ReceivingData());
t.start();
}
public List<String> obj1;
#Override
public void run()
{
Socket s;
InputStream stream;
try
{
s = new Socket("10.9.211.22", 6870);
stream = s.getInputStream();
byte[] data = new byte[13];
int read;
String can_Id= null;
while((read = stream.read(data)) != -1)
{
String can_Data=
String.format("%02X:%02X:%02X:%02X,
data[0], data[1], data[2], data[3]);
List<String> obj1= new ArrayList<String>();
obj1.add(can_Data.substring(0, 2));
obj1.add(can_Data.substring(3, 5));
obj1.add(can_Data.substring(6, 8));
obj1.add(can_Data.substring(9, 11));
Receiving_At_Regular_IntervalServlet rari= new
Receiving_At_Regular_IntervalServlet(obj1);
Thread.sleep(3000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This is the Servlet which is receiving the data from ArrayList passed by the above File.
and storing this data from the arraylist in to the Entity for datastore and deploys it on the Google App engine.
package pack.exp;
#SuppressWarnings("serial")
public class Receiving_At_Regular_IntervalServlet extends HttpServlet
{
List<String> obj2= new ArrayList<String>();
public Receiving_At_Regular_IntervalServlet(List<String> obj2) throws
IOException
{
this.obj2= obj2;
System.out.println("Receiving in Web Project" + obj2);
System.out.println("");
System.out.println("");
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException
{
Key k1 = KeyFactory.createKey("C","0D F0 0800 1");
String parameter1 = obj2.get(0);
Entity can1 = new Entity(k1);
can1.setProperty("First Parameter", parameter1);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(can1);
Entity can11 = null;
try
{
can11= datastore.get(k1);
}
catch (EntityNotFoundException e)
{
e.printStackTrace();
}
String first_P= (String) can11.getProperty("First Parameter");
resp.setContentType("text/plain");
resp.getWriter().println("Parameter--- " + first_P);
}
}
The ReceivingData code evidently runs a thread and reads data from 10.9.211.22 port 6870 using Socket from a local computer. That's fine. It converts four bytes to a List and passes that to Receiving_At_Regular_IntervalServlet. Fine but not what you need.
This part might work on a development computer but won't work if deployed to the cloud. AppEngine servers does not permit developers to define main(), use Socket or communicate with private IP subnet 10. Forget about deploying that code to AppEngine.
Receiving_At_Regular_IntervalServlet has a custom constructor. AppEngine does not call your constructor because its servlet code expects only the default constructor. That is probably when your 503 error occurs.
With servlets the data is not supposed to come in via a constructor. Data must come in via members of the request parameter of the doGet method (though to be RESTful you should rather use doPut in this example). You insert the data into the request parameter but sending a correctly constructed http request to the server. Your code lacks that web application design.
Build your main program and your AppEngine code in separate projects and make main talk to servlet using http.
HTTP ERROR 503 error
You can't help anything when a server throws this error. It is only thrown when a service from the server is unavailable.
You need explicit handling on such error codes, other than 200 OK, in the client app and appropriate message has to be shown or as the alternate requirement suggestion.
Refer to:
Status Code definitions
Java - 503 - SC_SERVICE_UNAVAILABLE

Sending Email Using apache commons mail package from android

I am new to android. I am developing the new app with email sending option. To send a mail I have used gmail configurations host "smtp.gmail.com", port 465 with SSL true. To send an email I have apache commons API. OnTouch event mail sending method will call. Whenever touch button it shows following errors,
Error : Could not find class 'javax.naming.InitialContext', referenced from method org.apache.commons.mail.Email.setMailSessionFromJNDI
Warning: VFY: unable to resolve new-instance 955 (Ljavax/naming/InitialContext;) in Lorg/apache/commons/mail/Email;
Warning : org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
I have added uses-permission android:name="android.permission.INTERNET" in my manifest file.
Can i use all java files in android ?
My email code executed correctly as a stand alone java program.
Here is an example of what I am doing in an app. I have an app that has its own email account that sends an email to the user when they fill out a form and press the submit button.
Important make sure you have the libSMTP.jar file referenced in your app. I am using this library for the following code. Here is the following code being used, take from it what you'd like, hope this is useful:
Imports needed:
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
Submit button to make the request to send email
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//-- Submit saves data to sqlite db, but removed that portion for this demo...
//-- Executes an new task to send an automated email to user when they fill out a form...
new sendEmailTask().execute();
}
}
});
Email task to be preformed on seperate thread:
private class sendEmailTask extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPostExecute(Void result)
{
}
#Override
protected void onPreExecute()
{
}
#SuppressLint("ParserError")
#Override
protected Void doInBackground(Void... params)
{
try {
//--Note the send format is as follows: send(from, to, subject line, body message)
send("myAppName#gmail.com", "emailToSendTo#gmail.com", "Form Submitted", "You submitted the form.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Send function being used:
public void send(String from, String to, String subject, String text) throws IOException
{
SMTPClient client = new SMTPClient("UTF-8");
client.setDefaultTimeout(60 * 1000);
client.setRequireStartTLS(true); // requires STARTTLS
//client.setUseStartTLS(true); // tries STARTTLS, but falls back if not supported
client.setUseAuth(true); // use SMTP AUTH
//client.setAuthMechanisms(authMechanisms); // sets AUTH mechanisms e.g. LOGIN
client.connect("smtp.gmail.com", 587);
checkReply(client);
//--Note the following format is as follows: client.login("localhost", (...your email account being used to send email from...), (...your email accounts password ...));
client.login("localhost", "myAppName#gmail.com", "...myAppName email account password...");
checkReply(client);
client.setSender(from);
checkReply(client);
client.addRecipient(to);
checkReply(client);
Writer writer = client.sendMessageData();
if (writer != null)
{
SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
writer.write(header.toString());
writer.write(text);
writer.close();
client.completePendingCommand();
checkReply(client);
}
client.logout();
client.disconnect();
}
Check reply function being used:
private void checkReply(SMTPClient sc) throws IOException
{
if (SMTPReply.isNegativeTransient(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Transient SMTP error " + sc.getReplyCode());
}
else if (SMTPReply.isNegativePermanent(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Permanent SMTP error " + sc.getReplyCode());
}
}
From Apache Commons Net 3.3, you can just drop the jar in your classpath and start using the AuthenticationSMTPClient : http://blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android-with-apache-commons-net/

Categories