Invoking a worklight adaptor from a stand alone java program - java

I can invoke the worklight adaptor procedure in my machine by using the below URL.
http://192.168.1.101:10080/AdaptorUI/dev/invoke?adapter=MySQLAdaptor&procedure=procedure1&parameters=[]
Now, i want to invoke this from a java program.
Code goes like this,
try {
URL myURL = new URL("http://192.168.1.101:10080/AdaptorUI /dev/invoke?adapter=MySQLAdaptor&procedure=procedure1&parameters=[]");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
System.out.println("Inside the MalformedURLException");
}
catch (IOException e) {
// openConnection() failed
// ...
System.out.println("IOException");
}
Somehow the above program is not working. Can you pls help ?

First, you should probably remove the /dev from the URL; /dev should be used only in a development environment.
Second, I suggest looking at the solution provided to this question: Java URL doesn't seem to connect, but no exception thrown
From the comments: Missing line of code:
BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));

Related

Mongo client {Mongo-Java-driver} creation hangs duration . No exception thrown

I have a cron-job running at a Linux machine running after every 5 minutes. The job executes a Java class.
private MongoClient createConnection(int retry,List<ServerAddress> host){
try {
System.out.println("Retrying----------"+retry);
MongoClient client = new MongoClient(host, MongoClientOptions.builder()
.connectionsPerHost(10)
.threadsAllowedToBlockForConnectionMultiplier(5)
.connectTimeout(5000).writeConcern(WriteConcern.NORMAL).build());
client.getDB("admin").command("ping").throwOnError();
retry = 0;
return client;
} catch (Exception e) {
retry++;
if (retry < retryLimit) {
createConnection(retry,host);
} else {
System.out.println("Connection could not be established to host-"+host);
}
return null;
}
}
retry is the integer value denoting how many times client creation can be tried in case host is unreachable.
The host list that i am passing is -
public static List<ServerAddress> HOST_SCRIPT = new ArrayList<ServerAddress>() {
private static final long serialVersionUID = 1L;
{
try {
add(new ServerAddress("PrimaryHost23", 27017));
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
};
Code is Stuck when i MongoClient is being created. It does not happen always. Code works fine and NEVER hangs when i run on my local machine. There is no exception thrown.
I recently upgraded Linux machine OS (from CentOS 5 to CentOS 6). Can this be responsible for this because this script was working fine earlier.
Please help.
Regards,
Vibhav
The thing what you can do is you can throw mongo exception try out that of mongo client is stuck you will get to know try out this https://api.mongodb.org/java/2.6/com/mongodb/MongoException.html
Yes of course, actually i was creating crawler in java which fetch all the links of any particular website and validate the css and html structure Using the Jsoup and jcabi api but when i used to store links to the database it was not throwing any exception and even not storing the data also. so i did this
catch (MongoException e){
System.err.print(e.getClass().getName()+": "+e.getMessage());
}
Have you checked the compatibility like of jar that you have uploaded for your project like before it was like Mongo mongo = new Mongo(host,port); but That is deprecated. Try to check that and even your MongoDb jar.

Android App unable to change Response Code for HTTP Connection in JAVA

I've been playing around with Android Studio and trying to establish a connection to a dev environment in which reponds back with JSON. I have tested my code and Eclipse (not ADK) and it works fine. I've added the permissions to the AndroidManifest.xml file for INTERNET and ACCESS_NETWORK_STATE so that has been covered. I dont know what else to do?
My Java:
public class GetClientDetails {
public void jsonResponse () {
try{
URL url = new URL("http://invsydmdev069:7080/IFXJSON?type=PartyRq&RqUID=123456789&PartyId=1093300");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Accept", "application/json");
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader (is, "UTF-8") );
try {
String preJsonObj = reader.readLine();
JSONObject jsonObj = new JSONObject(preJsonObj);
String strPartyId = jsonObj.getJSONObject("PartyRs").getJSONObject("PartyRec").getString("PartyId");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
catch(Exception e)
{
System.out.println("its fked");
}
}
}
The android.os.NetworkOnMainThreadException is self explainatory. You are not supposed to do any network operations on Main Thread which causes UI to be non-responsive. You need to run your network operations in an AsyncTask.
Check this post on SO.
Android 4.+ explicitly forbids network communication in the main thread (the thread that updates the user interface). It does that to avoid freezing the UI, causing a bad user experience.
Like bhargavg said, you should wrap that code in another thread, possibly using an AsyncTask or any other strategy that uses (or creates) a new thread.

How to check if URL is blocked by my firewall

I am trying to check if the URL is accessible or not. I am using HttpURLConnection for it. This is now I am implementing it.
public static boolean isUrlAccessible(final String urlToValidate)
throws WAGException {
URL url = null;
HttpURLConnection huc = null;
int responseCode = -1;
try {
url = new URL(urlToValidate);
huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
responseCode = huc.getResponseCode();
} catch (final UnknownHostException e) {
e.printStackTrace();
System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
return false;
} catch (final MalformedURLException e){
e.printStackTrace();
System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
return false;
} catch (ProtocolException e) {
e.printStackTrace();
System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
return false;
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
return false;
} finally {
if (huc != null) {
huc.disconnect();
}
}
return responseCode == 200;
}
When the Internet is down it throws an UnknownHostException, I wanted to know how do I check if a fire wall is blocking a URL and thats why I get an exception and not because that the URL is not accessible. Also, I am just checking for response code 200 to make sure that the URL is accessible. Are there any other checks I need to perform?
When the Internet is down it throws an UnknownHostException
No, it throws that when the DNS is down or the host isn't known to DNS.
I wanted to know how do I check if a fire wall is blocking a URL
You will get a connect timeout. In rare cases with obsolete hardware you may get a connection refusal, but I haven't heard of that this century. But you will also get a connect timeout if the host is down.
I am just checking for response code 200 to make sure that the URL is accessible. Are there any other checks I need to perform?
No. But URLs aren't blocked by firewalls. Ports are blocked by firewalls.
The exception I have usually seen when a firewall is blocking the connection is "java.net.NoRouteToHostException". Try catching that and see if it helps.
As others have said, the answer is "it depends".
Our perimeter firewall for example does a redirect, because we want to show the user a custom screen.
In this case, I would try to look into the HTTP Status code (30x).
I think it's hard to write a generic function for something like this, you need to tailor this to your setting or make it very configurable.
Just make sure to remain as generic as possible.
If your code for example assumes a redirect to a specific URL, this will beak once the infrastructure changes (which happens more often than anticipated).

Java HTTP Request Fail

I'm doing one java query with http on some search engines and here is the code of two classes:
public EventSearch(){
btsearch.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==btsearch){
try {
HttpRequest http = new HttpRequest(CatchQuery());
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "HTTP request failure.");
}
this.dispose();
}
}
public String CatchQuery(){
query=txtsearch.getText();
return query;
}
and
public class HttpRequest extends EventSearch
{
String query;
URL url;
public HttpRequest(String query) throws IOException{
// Fixed search URL; drop openConnection() at the end
try {
url = new URL("http://google.com/search?q="+query);
System.out.println(CatchQuery());
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "Unable to search the requested URL");
}
// Setup connection properties (this doesn't open the connection)
URLConnection connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
// Setup a reader
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// Read line by line
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println (line);
}
// Close connection
reader.close();
}
The thing is - There are no errors regarding the code but the request is stucked. I don't receive any sort of message on my console our debug. I'm thinking of any sort of memory error since I'm working with strings but anyone has any idea of whats going wrong on?
thank you
Edit One:
public String CatchQuery(){
query=txtsearch.getText();
return query;
}
CatchQuery Simple catch the query of the txtsearch (field).
Edit Two: [Topic Solved]
Two problems:
"http://google.com/search?q="+query should be "http://google.com/search?q="+URLEncoder.encode(query), query url needs to be encoded before opening a connection, so that unsupported characters are converted to url-friendly characters
Google does not accept bot connections, you should use the Google Java API to perform searches properly
UPDATE
Google does not accept connections without the User Agent header, so you have to edit the HttpRequest class to set the user agent after creating the connection:
// Setup connection properties (this doesn't open the connection)
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.8.1.6) Gecko/20070723 Iceweasel/2.0.0.6 (Debian-2.0.0.6-0etch1)");
connection.setRequestProperty("Accept-Charset", "UTF-8");
It works for me, test it and tell me if it works for you too.
Note: from Google ToS:
Automated queries
Google's Terms of Service do not allow the sending of automated queries of any sort to our system without express permission in advance from Google. Sending automated queries consumes resources and includes using any software (such as WebPosition Gold) to send automated queries to Google to determine how a website or webpage ranks in Google search results for various queries. In addition to rank checking, other types of automated access to Google without permission are also a violation of our Webmaster Guidelines and Terms of Service.

How to handle java.rmi.UnknownHostException

I'm working with Eclipse and the code below is the code that I use for RMI initialization.
public void init(String serviceName) throws RemoteException {
try {
String host = InetAddress.getLocalHost().getHostName();
String url = "rmi://"+ host + serviceName;
Naming.rebind(url,this);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
I'm getting an UnknownHostException.
Since I'm new to this issue, the question may be simple, but I could not handle it.
Thanks in advance.
UnknownHostException means it can't find that host at the network level. There's no handling this type of exception because it means something is broken. I'd print out the URL sent to RMI. It should look something like this:
//localhost/ServiceImTryingToAccess
If you didn't put a leading "/" on your service it might be:
//localhostServiceImTryingToAccess
And that certainly would create an UnknownHostException. You really don't need to use InetAddress.getLocalHost() as you could just simply do:
String url = "//localhost" + serviceName;
Also notice I dropped the rmi:// scheme portion of the URL. It's in the docs that's not needed.
http://docs.oracle.com/javase/1.4.2/docs/api/java/rmi/Naming.html

Categories