Codename one application is not able to connect with server using https request - codenameone

We have created codename one application which using https request.
I have not made any changes in code.
Earlier the request could be sent using https but now their is a problem and i am unable to connect to the server using https request but i am able to connect same https url using postman.
The connection code snippet is following please refer it
new APIHandler().PropertiesLoad();
ConnectionRequest req = new ConnectionRequest() {
protected void handleErrorResponseCode(int code, String message) {
if (code != 200) {
// do something
}
}
};
req.setUrl(properties.getProperty("https_url"));
req.setPost(true);
req.setTimeout(Constant.TIMEOUT);
req.addArgument("FirstName", fName;
req.addArgument("SecondName", sName);
req.addArgument("BirthDate", bDate);
req.addArgument("Password", pWord);
NetworkManager.getInstance().addErrorListener((e) -> e.consume());
NetworkManager.getInstance().addToQueueAndWait(req);
byte[] data = req.getResponseData();
if (data == null) {
}
result = new String(data);
} catch (Exception e) {
//get nullpointer exception because result get null
result = "";
}
return result;

Related

How to send FCM message from Appengine server on cloud code works local server

How to do it in cloud AppEngine without billing.
I am able to get Token from Javascript but sending messages to the server for notification. Create JSON object for downstream data/notification. On the server saying billing for the socket.
private void localappengine(HttpServletResponse response, String ENDPOINT_URL) throws IOException {
HttpClient client = new DefaultHttpClient();
Log.info("after client");
HttpPost post = new HttpPost(ENDPOINT_URL);
String deviceToken="cthG-hesotM:APA91bGg_tLg7TqvpY4aAvzHpyBK2mTTOT2KgO94tDFcLGPakcS9vmXkYEIe4Vh0Mo5ka1COfaXarUEJGWyqDdmVi_kujUfKDtE4C30eZwkPQATXnFrDPJxHxd8iouwsWuRcAk-ZYe_4";
PrintWriter out=response.getWriter();
response.getWriter().println("Hello from myservlet " );
// Create JSON object for downstream data/notification
JSONObject mainNotificationJsonObj = new JSONObject();
JSONObject outerBaseJsonObj = new JSONObject();
try {
// Notification payload has 'title' and 'body' key
mainNotificationJsonObj.put("title", "testing message");
mainNotificationJsonObj.put("body", "Hello I sent it");
// This will be used in case of both 'notification' or 'data' payload
outerBaseJsonObj.put("to", deviceToken);
// Set priority of notification. For instant chat setting
// high will
// wake device from idle state - HIGH BATTERY DRAIN
//outerBaseJsonObj.put(PRIORITY_KEY, PRIORITY_HIGH);
// Specify required payload key here either 'data' or
// 'notification'. We can even use both payloads in single
// message
outerBaseJsonObj.put("notification", mainNotificationJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
Log.info("before entity");
// Setup http entity with json data and 'Content-Type' header
StringEntity requestEntity = new StringEntity(outerBaseJsonObj.toString());
//(outerBaseJsonObj.toString(), APPLICATION_JSON);
String FIREBASE_SERVER_KEY= "key=AAAA6nN2BxI:APA91bHYotXML0siwL0Pm0LK5iXQ9Ik1kQtdB1ALbJrm5kseUk2zS5gJs6AMHVsX86exEE-JFsIF962YNY1yRyl3yFxGCyMBAH4OKwTn8Ff6vcd6vJMVXutNlP99X8AtOsW8_JIBkyEl";
// Setup required Authorization header
post.setHeader("Authorization", FIREBASE_SERVER_KEY);
post.setHeader("Content-Type", String.valueOf(APPLICATION_JSON));
Log.info("after header");
// Pass setup entity to post request here
post.setEntity(requestEntity);
// Execute apache http client post response
HttpResponse fcmResponse = client.execute(post);
Log.info("after client execute");
// Get status code from FCM server to debug error and success
System.out.println("RESPONSE_CODE" + fcmResponse.getStatusLine().getStatusCode());
// Get response entity from FCM server and read throw lines
BufferedReader rd = new BufferedReader(new InputStreamReader(fcmResponse.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
if (response != null) {
// Print out the response to webpage
PrintWriter out1;
out1 = response.getWriter();
out1.println(result);
System.out.println("This is Result - " + result);
}
}

How to access sqlite database from webserver and insert record using web services in codenameone

I am developing one application in CN1 that has to do with database, I want the user to enter a pin generated for them. once the user entered the valid pin, the apps will be activated for usage. The problem am having now is how to access the database using webservices. I have followed the webservices wizard tutorial, but all my effort was futile.
This is my snippet code.
private static final String DESTINATION_URL = "http://localhost:8085/CBT_PINS/folder/PINS.db";
ConnectionRequest req = new ConnectionRequest(DESTINATION_URL) {
#Override
protected void handleException(Exception err) {
Log.e(err);
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("An error occured while connecting to the server: " + err);
});
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("Error code from the server: " + code + "\n" + message);
});
}
};
req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);
Please help me out. I dont know what to do next. Thanks
This is because you aren't accessing a webservice. You are trying to open a database with an http URL:
SQLException: path to 'C:\Users\EMMY_OLUWASEGUN.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db'
Triggered by:
Database myDataBase = com.codename1.db.Database.openOrCreate(DESTINATION_URL);
The Database API is local to the device and not remote a webservice is something completely different.
Thanks for your response, Author of CN1. This is the full code below. I am using tomcat server on the local machine to test on the simulator. I am very sure if it works for me on the local machine's server, it will definitely work on the web server
private static final String DESTINATION_URL = "http://localhost:8085/CBT_PINS/folder/PINS.db";
ConnectionRequest req = new ConnectionRequest(DESTINATION_URL) {
#Override
Database myDataBase = com.codename1.db.Database.openOrCreate(DESTINATION_URL);
Cursor c = myDataBase.executeQuery("select pin from PIN_TABLE where id = 1" );
if (c.next()) {
Row r = c.getRow();
String pin = r.getString(0);
Dialog.show("valid pin", pin, "Ok", "Ok");
} else if (!c.next()) {
Dialog.show("Invalid pin", "keep off", "ok", "ok");
}
protected void handleException(Exception err) {
Log.e(err);
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("An error occured while connecting to the server: " + err);
});
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("Error code from the server: " + code + "\n" + message);
});
}
};
req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);
This is the error code generated for me when I ran the code:
WARNING: Apple will no longer accept http URL connections from applications you tried to connect to http://localhost:8085/CBT_PINS/folder/PINS.db to learn more check out https://www.codenameone.com/blog/ios-http-urls.html
java.sql.SQLException: path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
[Network Thread] 0:0:0,0 - Codename One revisions: 375ed2c938445450f0983f0d18235f61e793a7ee2004
[Network Thread] 0:0:0,0 - Exception: java.io.IOException - path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
Rendering frame took too long 187 milliseconds
at org.sqlite.SQLiteConnection.open(SQLiteConnection.java:156)
at org.sqlite.SQLiteConnection.<init>(SQLiteConnection.java:105)
at org.sqlite.JDBC.createConnection(JDBC.java:113)
at org.sqlite.JDBC.connect(JDBC.java:87)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at com.codename1.impl.javase.JavaSEPort.openOrCreateDB(JavaSEPort.java:7548)
at com.codename1.ui.Display.openOrCreate(Display.java:3690)
at com.codename1.db.Database.openOrCreate(Database.java:59)
at com.mycompany.myapp.MyApplication$1.readResponse(MyApplication.java:283)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:483)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.io.IOException: path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
at com.codename1.impl.javase.JavaSEPort.openOrCreateDB(JavaSEPort.java:7554)
at com.codename1.ui.Display.openOrCreate(Display.java:3690)
at com.codename1.db.Database.openOrCreate(Database.java:59)
at com.mycompany.myapp.MyApplication$1.readResponse(MyApplication.java:283)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:483)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

WCF: submitting to service twice

Just getting my head around WCF, so forgive me for the inelegant coding.
The issue I'm having is I seem to be submitting data twice to my service (see screenshot), even though (I think) I'm only doing it once.
Could someone please let me know what I might be doing wrong? Or even just suggest a better way to do it if I'm doing it inefficiently.
Code follows:
public void EndOfLevel()
{
GlobalVariable.TotalQuestionsAsked = 10;
GlobalVariable.CorrectDecimal = GlobalVariable.Correct / GlobalVariable.TotalQuestionsAsked;
//Show loading screen
UploadingScreen.Visibility = Visibility.Visible;
//Submit this levels results.
Service1Client client = null;
client = new Service1Client();
//Gather the results and details
Result thislevel = new Result();
thislevel.Datetime = DateTime.Now;
thislevel.result = GlobalVariable.CorrectDecimal;
thislevel.TimesTable = GlobalVariable.NeedsHelpWith;
//submit them
try
{
client.SubmitResultAsync(thislevel);
}
catch
{
MessageBox.Show("Error uploading data");
}
finally
{
client.Close();
Results r3 = new Results();
this.NavigationService.Navigate(r3);
}
}
WCF Test Client:
Cheers,
Nick
If I may, here's a pattern for managing our asynchronous calls between our WPF applications and our WCF Services.
In this section we have a public accessor to our service client that ensures that the connection to the client is open prior to calling a service method:
public static MyServiceClient Client
{
get
{
return GetMyServiceClient();
}
}
private static MyServiceClient client;
private static MyService.MyServiceClient GetMyServiceClient()
{
VerifyClientConnection();
return client;
}
private static void VerifyClientConnection()
{
if (client == null || client.State == System.ServiceModel.CommunicationState.Closed)
{
client = new MyService.MyServiceClient();
}
}
And in this section is an example of our asynchronous call and callback pattern (this example shows the delegate and callback we're using for passing exception data to our service):
public delegate void LogExceptionCompletedEvent();
public static LogExceptionCompletedEvent LogExceptionCompleted;
public static void LogExceptionAsync(SilverlightException exception)
{
string json = JsonConvert.SerializeObject(exception);
Client.LogExceptionCompleted -= client_LogExceptionCompleted;
Client.LogExceptionCompleted += client_LogExceptionCompleted;
Client.LogExceptionAsync(json);
}
private static void client_LogExceptionCompleted(object sender, AsyncCompletedEventArgs e)
{
if (LogExceptionCompleted != null)
{
LogExceptionCompleted();
}
}
In this example, a view model could attach an event handler to the LogExceptionCompleted delegate and in turn receive the result of the callback when it returns from the service.
We basically repeat this pattern for the asynchronous WCF service calls we need to make from our application and it keeps them very organized as well as unit testable.

How to achieve mp3 stream using java Servlet

Goal: build a servlet so that when I type http://xxx.com/servpage?a.mp3 in browser, I can instantaneously start the playing of this mp3 file. Previously if I put the file on goDaddy as a static file, I can do that. My software can play it right away.
Using Servlet, I can ignore what is after ?, just want this page to return the mp3 dynamically (because in the future I may return any other files). What I got is a long wait (>20 seconds), and then got the player to play it.
I followed some examples, and noticed "attachment" in the example. However, if I remove it, the mp3 won't got played even. I am usign Google App Engine though, but just use the input/outputstream to return the http request. Anyone can help?
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException ,IOException {
res.setContentType("audio/mpeg3");
OutputStream os = res.getOutputStream();
res.setHeader("Content-Disposition", "attachment; filename="" + "a.mp3";");
res.setContentLength(1000000);
FileService fileService = FileServiceFactory.getFileService();
boolean lockForRead = false;
String filename = "/gs/" + BUCKETNAME + "/" + FILENAME;
AppEngineFile readableFile = new AppEngineFile(filename);
try{
FileReadChannel readChannel = fileService.openReadChannel(readableFile, lockForRead);
InputStream is = Channels.newInputStream(readChannel);
int BUFF_SIZE = 1024;
byte[] buffer = new byte[BUFF_SIZE];
try {
do {
int byteCount = is.read(buffer);
if (byteCount == -1)
break;
os.write(buffer, 0, byteCount);
os.flush();
} while (true);
} catch (Exception excp) {
} finally {
os.close();
is.close();
}
readChannel.close();
} catch(Exception e){
}
}
Few notes:
You are not doing "streaming". Just a plain file download.
To do blob (file) serving, you do not need to read the blob from BlobStore as you do with AppEngineFile. Just serve it directly with blobstoreService.serve(blobKey). See Serving a Blob for an example.
You can get the BlobKey needed in 2. via fileService.getBlobKey(readableFile).
Update:
Just realized you are using Google Cloud Storage, not BlobStore.
In GS, if ACLs are properly set, files are publicly visible via: http://commondatastorage.googleapis.com/BUCKETNAME/FILENAME
Since you are not doing any authentication, you could publicly share the file on GS and then in your servlet just do a 301 redirect to public URL of the file.

Restlet GWT in a Google Gadget

I am developing a GWT app for the Google Apps marketplace. I am using AppEngine with Restlet on the server side. Client side I use the GWT edition of Restlet. This is a great combination. I have my domain objects shared between client and server and as such no need for DTO's or proxies and so on. On the client side I can simply call Restlet resources :
CustomerResourceProxy customerResource = GWT.create(CustomerResourceProxy.class);
customerResource.getClientResource().setReference("/customer");
customerResource.retrieve(new Result<Customer>() { .... }
No need to parse the underlying XML or use JSNI to interpret incoming JSON.
BUT... part of the app is a GMAIL contextual gadget, and I cannot simply use the above code because all communication between a Gadget and the server must pass through GadgetsIO makeRequest.
So... just for the gadget, I will have to make the effort of parsing the XML or using JSNI to interpret the incoming JSON.
Is it überhaupt possible to hack the Restlet GWT client to pass all communication via GadgetsIO and what would it take ? Any pointers very welcome !
K.
I managed to get Restlet resources to work within a Gadget using GWT by making some changes to the Restlet GWT edition :
In GwtClientCall I replaced the standard GWT requestbuilder by the GadgetRequestBuilder (which will IoProvider.makeRequest), like this :
public GwtClientCall(GwtHttpClientHelper helper, String method, String requestUri, boolean hasEntity) {
super(helper, method, requestUri);
Reference requestRef = new Reference(requestUri);
if (requestRef.isRelative() || requestRef.getScheme().startsWith("http")) {
this.requestBuilder = new GadgetsRequestBuilder(method, requestUri);
this.requestBuilder.setTimeoutMillis(getHelper().getSocketConnectTimeoutMs());
this.responseHeadersAdded = false;
} else {
throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
}
}
In the gadgetsrequestbuilder, I had to make some changes so it would pass the headers in the request :
private GadgetsRequest doSend(String requestData, final RequestCallback callback) throws RequestException {
final RequestOptions options = RequestOptions.newInstance();
options.setMethodType(methodType);
if (requestData != null && requestData.length() > 0) {
options.setPostData(requestData);
}
options.setAuthorizationType(AuthorizationType.SIGNED);
options.setContentType(ContentType.DOM);
setHeaders(options);
final GadgetsRequest gadgetsRequest = new GadgetsRequest(getTimeoutMillis(), callback);
gadgetsRequest.setPending(true);
IoProvider.get().makeRequest(getUrl(), new ResponseReceivedHandler<Object>() {
public void onResponseReceived(ResponseReceivedEvent<Object> event) {
gadgetsRequest.fireOnResponseReceived(event, callback);
}
}, options);
return gadgetsRequest;
}
the gadget container by default strips the response headers, so i manually add the MediaType.APPLICATION_JAVA_OBJECT_GWT
#Override
public Series<org.restlet.client.engine.header.Header> getResponseHeaders() {
final Series<org.restlet.client.engine.header.Header> result = super.getResponseHeaders();
if (!this.responseHeadersAdded && (getResponse() != null)) {
Header[] headers = getResponse().getHeaders();
for (int i = 0; i < headers.length; i++) {
if (headers[i] != null) {
result.add(headers[i].getName(), headers[i].getValue());
}
}
result.add(HeaderConstants.HEADER_CONTENT_TYPE, MediaType.APPLICATION_JAVA_OBJECT_GWT.toString());
this.responseHeadersAdded = true;
}
return result;
}
A lot of dialogboxes for debugging later, it works :-)

Resources