HttpMessage.setMethod(HttpMessage.POST) is changed by GET, on BlockingSenderDestination - java

I am trying to migrate a Blackberry application from OS 6 to OS 7 (my app currently works on OS 6). Theoretically it should not cause any problems, but I found an issue that I still cannot resolve. When executing calls to web services (SOAP), I'm setting the HttpMessages to use the POST method, but when the call is executed, it arrives at the server as a GET. This is a big problem for me because the Sever with which am working doesn't support GET's (always results in an "Http 500 error"). This issue doesn't occur on the simulator, just on the device.
Do you know any workaround for this? Is it a problem with OS version? (See below for the code that I'm using).
Device
Model: Bold 9930
Carrier: Sprint
OS: 7.0 Bundle 1296 (v7.0.0.241, Platform 5.0.0.442)
Simulator (On the simulator side I don't have any problems)
Model: Bold 9930
OS: 7.0 Bundle 1962(v7.0.0.440, Sept_24_2011_signed, Platform 4.0.0.141)
public void run() {
context.setEnableBtnsend(false);
BlockingSenderDestination blockSendDest = null;
try {
URI uri = URI.create(URL_BASE);
blockSendDest
= (BlockingSenderDestination) DestinationFactory.getSenderDestination(
senderContext.getName(), uri);
if (blockSendDest == null) {
blockSendDest = DestinationFactory.createBlockingSenderDestination(
senderContext, uri);
}
ByteMessage requestMessage = blockSendDest.createByteMessage();
requestMessage.setTransportHeader("Content-Type", "text/xml;charset=UTF-8");
requestMessage.setTransportHeader("SOAPAction", "\"\"");
// getBodyRequest() -> Insert SOAP request, works fine, was tested on SOAP UI
requestMessage.setStringPayload(getBodyRequest());
((HttpMessage) requestMessage).setMethod(HttpMessage.POST);
blockSendDest.resume();
Message response = blockSendDest.sendReceive(requestMessage);
if (response != null) {
procesMessageResponse(response);
}
// ...
}
catch (Exception ex) {
handleException(ex);
}

Related

Is Desktop#browse supported on Linux platform just for Gnome desktop?

Running my Java application with this code:
if (Desktop.isDesktopSupported())
{
Desktop d = Desktop.getDesktop();
try
{
d.browse(new URI("someurl")); // someurl is just an example, I am opening real url
}
catch (IOException | URISyntaxException e)
{
logger.warn(ExceptionUtils.getStackTrace(e));
}
}
results in application not responding (probably deadlock) on Manjaro Linux KDE. While it works with no problem on Windows, I do not want to check for OS in my application and allow it just for Windows. I have not tried other platforms yet.
What i use:
Adoptium JDK 11
Manjaro kernel 5.10.83-1-MANJARO 64bit
KDE Plasma 5.23.4
Qt 5.15.2
Detailed deadlock location:
Desktop class:
public void browse(URI uri) throws IOException {
checkAWTPermission();
checkExec();
checkActionSupport(Action.BROWSE);
Objects.requireNonNull(uri);
peer.browse(uri); // <- goes here
}
Deadlock happens in XDesktopPeer class that implements DesktopPeer interface (peer) on method gnome_url_show(...):
private void launch(URI uri) throws IOException {
byte[] uriByteArray = ( uri.toString() + '\0' ).getBytes();
boolean result = false;
XToolkit.awtLock();
try {
if (!nativeLibraryLoaded) {
throw new IOException("Failed to load native libraries.");
}
result = gnome_url_show(uriByteArray); // <- deadlock / app not responding here
} finally {
XToolkit.awtUnlock();
}
if (!result) {
throw new IOException("Failed to show URI:" + uri);
}
}
So... is Desktop#browse supported on Linux platform just for Gnome desktop?
I am guessing this, because of that method name.
If yes, can I make a check for deadlock around my code, so I prevent this in my app? rather than checking for OS and distros?
There are already several questions on SO about that issue:
Desktop.getDesktop().browse Hangs
Desktop and desktop.browse are supported, but browse still hangs
Desktop browse does not work in java for Ubuntu
There is also this discussion:
https://bugs.launchpad.net/ubuntu/+source/openjdk-8/+bug/1574879
where someone says:
gnome_url_show is actually in libgnome-2-0 package
So, if the package is missing, Desktop.browse() will fail. There are 2 solutions to fix that.
Solution 1
Install the libgnome package.
Solution 2
Execute xdg-open to open the URL, e.g.:
Runtime.getRuntime().exec(new String[]{"xdg-open", someurl});

Google Play Install Referrer Library - Referrer Generation

I'm developing an android application in Java where I need to pass the referer information to an URL. I'm getting the referrer information using Play Install Referrer Library.
Here is my code:
InstallReferrerClient referrerClient = InstallReferrerClient.newBuilder(this).build();
referrerClient.startConnection(new InstallReferrerStateListener() {
#Override
public void onInstallReferrerSetupFinished(int responseCode) {
switch (responseCode) {
case InstallReferrerClient.InstallReferrerResponse.OK:
try {
Log.v("TAG", "InstallReferrer conneceted");
ReferrerDetails response = referrerClient.getInstallReferrer();
System.out.println("referrerUrl ID: " + response);
referrerClient.endConnection();
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED:
Log.w("TAG", "InstallReferrer not supported");
break;
case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE:
Log.w("TAG", "Unable to connect to the service");
break;
default:
Log.w("TAG", "responseCode not found.");
}
}
#Override
public void onInstallReferrerServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
Code is working fine and currently, the above snippet is inside my activity's onCreate method. which means it will start the new connection every time the user opens the activity.
In the library documentation, they have written that
Caution: The install referrer information will be available for 90
days and won't change unless the application is reinstalled. To avoid
unnecessary API calls in your app, you should invoke the API only once
during the first execution after install.
This is where I'm stuck, should I just call this thing when the application starts the first time?
If yes, I can store this referrer in the shared preference, but then how will I able to know that 90 days have been passed and I need to trigger that action again? Or it there something else that should I need to implement? Kindly help me with this issue.

Limit web service access to only one app

Right now I am working on a android app and I am totally new to this.
I want to make sure my web-service is only accessible via my app.
My background is PHP. In PHP I don't need to worry about anything like that, because everything runs on a server.
In case of Java and especially Android programming things are different. Even with encryption. Everybody can just open an APK and see how the web service gets accessed. So is there a way to hide or to obfuscate the access to a web service, so only my app will be able to use it?
For test purposes I didn't add any security or encryption. This is the basic call to a web server I am doing right now:
String url = "http://thisismyurl.com/a.php?action=get";
String result = Web.executeWeb(url);
public class Web {
public static String executeWeb(final String url) {
final StringBuilder sb = new StringBuilder();
Thread thread = new Thread(new Runnable() {
public void run()
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String result, line = reader.readLine();
result = line;
while((line=reader.readLine())!=null){
result+=line;
}
sb.append(result);
//System.out.println(result);
//Log.i("My Response :: ", result);
} catch (Exception e)
{
// TODO: handle exception
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
}
How would I hide this from the prying eyes of hackers? ;-) Is that even possible?
Thanks in advance!
Deploy client authentication using (self signed) certificates within TLS.
This kind of configuration can be enabled on most web servers and Java application servers, and you can normally also configure the web or application server in such a way that you can retrieve the certificate of the private key that the client used to authenticate itself.
Note that HTTPS uses SSL (or now TLS) before any web trafic, so you cannot program this in your application, it does require server configuration.
Check this link on how to configure for Apache 2.
Use your Application's ID ( like IMEI ) as parameter in your webservice call. You need to make a table in database at server side which will store all registered device. Now only these registered device can access your webservice. This is my idea, there should be other idea as well.

One API to handle adding and updating files

I'm using SVNKIT 1.8 with SVN 1.8.5 and the SVN protocol to attempt to add files in bulk to my SVN repository. I would like to have one method for adding and updating files and the below code successfully handles both when using the FILE protocol since the editor.addFile(file, null, -1) throws an SVNException. When I switch to the SVN protocol (desired protocol), the editor.addFile(file, null, -1); doesn't throw an exception. Instead the editor.closeEdit(); throws an exception which is not desired. Any ideas on how to use one API for both adding and updating files?
public void addFiles(Map<String, String> data) throws Exception {
TreeSet<String> filesToCreate = new TreeSet<String>(data.keySet());
SVNRepository repo = null;
ISVNEditor editor = null;
try {
repo = openSession();
editor = repo.getCommitEditor("Adding files.", null);
editor.openRoot(-1);
for (String file : filesToCreate) {
try {
editor.addFile(file, null, -1);
} catch (SVNException e) {
editor.openFile(file, -1);
}
editor.applyTextDelta(file, null);
SVNDeltaGenerator gen = new SVNDeltaGenerator();
String checksum = gen.sendDelta(file, new ByteArrayInputStream(data.get(file).getBytes()), editor, true);
editor.closeFile(file, checksum);
}
editor.closeEdit();
} catch (Exception ex) {
abort(editor);
throw new Exception(ex.toString(), ex);
} finally {
closeSession(repo);
}
}
This is a side effect of an optimization in the svn:// protocol. During an editor drive the server does not send any response unless there is an error and as such the client can't tell that a specific action succeeded. I haven't looked at SVNKit's code but I'd bet that you could potentially get the exception from any of the editor methods since the error will be detected in the next editor drive call after the server responds. In this case your changes are so small that the editor drive sending happens before the response from the server can be detected and so you end up seeing the error when you do closeEdit().
The svnmucc command in Subversion has a similar problem as what you're trying to solve. It has a put operation that adds or updates a file. It uses the same technique that Dmitry advised you to use on the svnkit-users mailing list (link1, link2). Specifically running a check_path before determining to add or create the file.
You're not going to be able to do anything better than this because of the way the protocol works.

Firefox, websockets and odd behaviours

Background:
Using WebSockets with JavaScript + Play! framework (2.2).
Can send and receive data fine in Chrome.
Can only receive data (from server) in Firefox as send() doesn't trigger any callbacks.
In addition to the send issue, and in Firefox only again, the tab for the page is always stuck on "connecting" while the spinner keeps spinning (see figure 1).
Misbehaving Browser:
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0)(Firefox 24.0)
(Figure 1. Firefox tab after page has loaded and data is shown)
Any time I refresh the web page, I receive the error below, attributed to the constant page loading behaviour I'm sure.
The connection to ws://localhost:9000/ was interrupted while the page was loading.
The entire JavaScript code:
$(function() {
var chatSocket = new WebSocket("#routes.Application.getMetaData().webSocketURL(request)");
var sendMessage = function() {
chatSocket.send(JSON.stringify({
id: "unique",
name: "a name",
age: 22
}));
}
var receiveEvent = function(event) {
var data = JSON.parse(event.data)
document.write(data.age);
document.write(data.name);
document.write(data.message);
document.write("\n");
sendMessage();
chatSocket.close();
}
chatSocket.onmessage = receiveEvent
})
Now In the past, I've been trying with MozWebSocket instead of the standard WebSocket, but I get nothing rendered on screen using that module therefore unless there is an angle I've missed, WebSocket is the better one to use.
The relevant Play! block:
public static WebSocket<JsonNode> getMetaData() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {
// For each event received on the socket,
in.onMessage(new Callback<JsonNode>() {
#Override
public void invoke(JsonNode jsonNode) {
System.out.println("Message Incoming!");
System.out.println(jsonNode.get("id"));
System.out.println(jsonNode.get("name"));
System.out.println(jsonNode.get("age"));
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
System.out.println("Disconnected");
}
});
ObjectNode node = Json.newObject();
node.put("message", "hello");
node.put("name", "client");
node.put("age", 1);
out.write(node);
//same result commented/uncommented
out.close();
}
};
}
So in Chrome, the flow would be:
document.write(...)
"Message Incoming!"
... JSON attributes
"Disconnected"
But in Firefox, the flow is:
document.write(...)
"Disconnected"
Any help in diagnosing these problems would be greatly appreciated. I have no intention of supporting IE, but having both Mozilla and Chrome working would be great.
Other JavaScript Warnings:
Below is a warning I occasionally get in Firefox's console while pointing at the "ws" protocol as the culprit. What its relevance is to my problem, I do not know.
Use of getPreventDefault() is deprecated. Use defaultPrevented instead.
You call document.write() after the document is loaded, which then implies document.open() which in turn replaces the document and by that unloads the old one and aborts stuff like timeouts or websockets.
Use something other than document.write() and you should be fine.

Categories