I developed my application using java GWT and I deployed my application on google app engine. my access url is sample.myappid.appspot.com I want to call this url through code so i did like this :-
URL url;
try {
url = new URL("http://sample.myappid.appspot.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
logger.log(Level.SEVERE,"Done okkkkkk");
} else {
// Server returned HTTP error code.
logger.log(Level.SEVERE,"Erorrrrrrr");
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This is not calling my url. so any other solution how can i call my url using code.
Any help?
You need to pay attention if/when making requests to your app right from inside your apps' request handlers as you can cause infinite recursive loops, making GAE attempt to spawn a new app instance in an attempt to serve each such request. Possibly related to your other question: while user inactivity of 2mins getting info "This request caused a new process to be started for your application".
There are several methods to access your app programatically from itself, internally, basically making requests to paths in your app's serving namespace (like /index.html, for example):
task queues
deferred tasks
cron/scheduled tasks
Requests initiated by these internal methods are internally generated, independent of external requests, and can be safely used to implement your app's logic (loops are still possible if misused, but only creating a great deal of activity, they're not infinite recusions/deadlocking in the sense of forcing GAE to spawn a new instance for every request).
You can also use generic URL access from your app (applicable to any URL, not only those of your app), just as an external user would access your app. These can be useful for automated testing of your app, but note that they can be more costly than the internal access methods, I wouldn't recommend them for actually implementing your app's logic:
using URL Fetch API
using java.net
These external access methods are also subject to infinite recursion problem, so use them with care.
Related
I'm currently building a REST API with Spring Boot. The idea is that users can have a "component" which can send and receive data to and from my API, I make the assumption that it has access to Wi-Fi via the user's router. A component has to implement certain endpoints that I define.
My REST API works similarly as something like "If This Then That". It supports three things: a component can send data to the platform, the platform can send actions to a component and the platform can request data from a component.
Currently I have the API (which is pretty far feature wise) and a dummy component I made in NodeJS which mimics a "real" component. The dummy component currently does a POST request to the platform with data, which the platform then checks for certain values. The platform can request data from the dummy component through a GET request and does a POST request to the component to perform an action.
I'm currently trying to figure out how to implement the communication between the platform and a component. I assume that there isn't much trouble with sending a POST request from a component to the web server, but I think that there's more trouble with doing a POST and GET request from the platform to a component.
My web server and dummy component currently both run on localhost. I currently define the IP address of the component, which the platform then uses to perform POST and GET requests on. This works fine for now, but when a component is behind a IP address outside localhost I assume that there's going to be trouble with firewalls and such, since a component is connected to the public web via an user's router.
Now my question is as follows: what is the best way to communicate with a component outside the network of the web server via HTTP.
For me the logical answer seems like web sockets, but should I be thinking about a different option? My knowledge of networking is limited to HTTP and sockets, so I would like to hear what others think and what I should research.
Thanks for reading!
Edit:
For reference this is the code I use to do a POST request from the platform to a component, I use Spring's RestTemplate for this:
DebugResponse responseToReturn;
try {
ResponseEntity<String> response = restTemplate.postForEntity(userComponent.getAddress() + restPath, request, String.class);
responseToReturn = new DebugResponse("Post Success");
} catch (HttpClientErrorException e) {
responseToReturn = new DebugResponse("HttpClientError");
} catch (HttpServerErrorException e) {
responseToReturn = new DebugResponse("HttpServerError");
} catch (RestClientException e) {
responseToReturn = new DebugResponse("RestClientException");
} catch (Exception e) {
responseToReturn = new DebugResponse("Generic POST exception");
}
return responseToReturn;
userComponent.getAddress() contains the IP address (localhost in this case) and restPath contains the path to send the data to (/action in this case). "request" has some JSON data it sends to the component. The dummy component uses Node's request library to send data to the IP of the platform.
I have the following lines of code that gathers the source code from a given URL:
URL url = new URL(websiteAddress);
URLConnection connection = url.openConnection(); // throws an IOException
connection.setConnectTimeout(timeoutInMilliseconds);
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
outputString += line;
}
However, the problem that I'm having is that wi-fi hotspots often redirect you to a page where you have to click "I Agree." If you run this code before you have clicked that checkbox, then it gathers the source code from the hotspot login page, rather than the intended page.
What I want to do is have some way of checking whether or not the intended page was reached. I was hoping that calling connection.getURL() after creating the InputStreamReader would show me the actual web page that was arrived, but no such luck. How can I determine whether or not the intended URL has been redirected?
One way would be to look for any specific element in your web page, and if its not there then you know that you may be in some other page (possibly redirected to some login page).
The only thing I can suggest is to have a server where you know what the response is, and query that first to ensure connectivity to at least that server. That will (typically) be enough to assume full connectivity.
You can then go on to query the url you're interested in.
The challenege is that if a computer asks for the page at some url, the way a lot of wifi hotspots work is to intercept that request and return the page. There's often no clue, form the computer's POV that the page returned is not the page requested.
One option would be to call setFollowRedirects(false). By default, a connection will quietly follow redirects and try to reach a page which returns a 200 HTTP response. Disabling redirect following will make confirming the expected page is returned easier, simply confirm the response is a 200.
That said, #rec's comment is worth taking into account - it isn't enough to simply check the response code, because there are many different ways a router could interrupt your request, many of which are not detectable. A malicious router could, for instance, intercept all your requests and change the responding content in a subtle but dangerous way - this is called a man-in-the-middle attack.
By definition you cannot avoid MitM attacks unless you can open a secure and trusted connection (generally, HTTPS) between yourself and the remote site, however assuming you aren't really concerned about attacks, the better tactic is simply to assume the data you get back could be broken in any number of ways, and instead make your scraping logic more robust to that possibility.
I can't speak directly to how you would make your logic more robust without understanding your use case and the issues you've run into, however the gist would be to add checks where issues might arise, and throw an exception that you then handle gracefully higher up the stack.
For instance, if your code was:
System.out.println(outputString.subString(outputString.indexOf('A'));
This would fail if outputString didn't actually have an'A'` character. So check that explicitly:
int aPos = outputString.indexOf('A');
if (aPos < 0) {
throw new InvalidParseException("Didn't find an 'A', cannot proceed");
}
System.out.println(outputString.subString(aPos);
And handle the InvalidParseException wherever makes the most sense for your use case.
I have asked variations of this question over the past couple of days. I am not understanding or making the proper connections etc. so I am getting really frustrated not understanding which path I should be on.
I have developed a XAMLX WCF workflow service and my windows clients interact with it just fine. I am new to android and java and thus basically a NOOB. My service uses BasicHttpBinding and expects a couple of string values (uid & pwd) in the request. The response is simply a string.
Now on the android I am totally lost. I have read to use the AsyncTask, I've heard it has major issues and to use RoboSpice. Looking at RoboSpice it looks very solid but very stiff learning curve. I've heard for the stiff learning curve to use LoopJ as it will be easier when starting out. Throw in there the people who want you to use JSON and yeah. I'm definitely lost.
So I have been pulled in a lot of different directions. I know that I need it to be Async so it doesn't lock the ui thread and I would like to get to a solid robust solution but for now a baby step of just interacting with the service even synchronously would be encouraging.
Here are my basics:
Send a request to the service.
Have the application pause/loop etc. A progress bar would be wonderful but a simple loop that doesn't hang would be just fine for now.
RX the response and continue processing.
This is so simple for me in .NET I thought it would be simple. Just goes to show that pride cometh before the fall.
TIA
JB
Direct Question
As has been commented there are several implied questions in my OP. That is because I don't know what to ask. So let's go with AsynchTask for now. Let's call that my baby step.
Here are my questions:
HOW do I associate values to populate the request? In .NET I would create an object that matches what the request expects. So my object would have a UserName property and Password property. I would assign them their values like obj.UserName = "Joe"; I would then call the service operation and pass it obj.
HOW do I ensure I am using the proper libraries? I have read that AsyncTask uses the Apache Http Client library. OK I google that to get the jar's and apparently it's end of life. But still available so I download the latest and put it in my lib folder....but I didn't have to because I can import org.apache.http.HttpResponse without it so which version am I using then and should I use an older one or the latest.
**Finally how do I get the app to pause because this code does something (although it never shows in the logs of my service machine) and while it is off doing something my code continues to execute and crashes when it reaches the point where it needs the data from the service.....but it's not there. A progress bar would be the bees knees.
Here is my code for the implementation:
public class AsyncHttpRequestManager extends AsyncTask<String, Boolean, String>
{
private static final String serviceUrl = "http://www.serviceurl.com/service.xamlx";
#Override
protected String doInBackground(String... params)
{
try
{
DefaultHttpClient client = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(serviceUrl);
putRequest.setHeader("Content-type", "text/plain");
putRequest.setHeader("Accept", "text/plain");
putRequest.setEntity(new StringEntity(params[0])); //This one is connected to my first question. How do I get the proper associations for the operations contract.
HttpResponse response = client.execute(putRequest);
InputStream content = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String result = "";
String s = "";
while ((s = buffer.readLine()) != null)
{
result += s;
}
return result;
}
catch (UnsupportedEncodingException e)
{
Log.e("AsyncOperationFailed", e.getMessage());
e.printStackTrace();
} catch (ClientProtocolException e)
{
Log.e("AsyncOperationFailed", e.getMessage());
e.printStackTrace();
} catch (IOException e)
{
Log.e("AsyncOperationFailed", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
Log.d("MESSAGE", result);
}
}
I call this like this:
new AsyncHttpRequestManager().execute("joe","asdf");
If more info is needed I will gladly post.
You should ask one question at a time, it's how SO is designed, and curated, to work.
For HTTP authentication
http://developer.android.com/reference/org/apache/http/auth/UsernamePasswordCredentials.html
E.g.
HttpClient client = new HttpClient();
client.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(new AuthScope("myhost", 80, AuthScope.ANY_REALM), defaultcreds);
Asynctask does not require any external libraries it's part of the Android platform. Don't get confused about HTTPClient and Asynctask. Asyntask is a generic class intended to call background processing on a separate thread from the main UI thread to avoid blocking. It just so happens that you are considering using an Asynctask to process your web request but they are not linked in any way.
Your question about "how to return data to my app" is best posed separately but, in essence, you're thinking sequentially. Your app should not pause. There are many methods, progress dialogs being one, to properly handle this.
One way that Steam lets users launch games and perform many other operations, is by using URI protocols, for example (from Valve developer community):
steam://run/<id> will launch the game that corresponds to the specified ID.
steam://validate/<id> will validate the game files of the specified ID.
How can I get Java to 'run' these? I don't even know what you call it, i.e. do you 'run' URIs, or 'execute' them, or what? Because persumably these URIs don't have anything to return, and the URI class in Java doesn't have anything related to 'executing' them, however URL does, but it doesn't work!
I've tried this:
...
try
{
URI testURI = URI.create("steam://run/240");
URL testURL = joinURI.toURL();
// URL testURL = new URL("steam://run/240") doesn't work either
joinURL.openConnection(); // Doesn't work
// joinURL.openStream() doesn't work either
}
catch (MalformedURLException e)
{
System.err.println(e.getMessage());
}
...
Each combination gives the error: unknown protocol: steam.
The system that Steam uses to handle the URIs is definitely working, because for example, I can type the above URI into Firefox and it works.
My eternal gratitude to the person who provides the answer!
Thanks
Try Desktop.browse(URI), this should start the "default action" which is the Steam client for a steam:// URI, e.g.
URI uri = new URI("steam://store/240");
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(uri);
}
The system that Steam uses to handle the URIs is definitely working, because for example, I can type the above URI into Firefox and it works.
It is working because Firefox (or other browsers) can associate unkown protocols with applications. When you load steam://xxx for the first time, Firefox asks you which application you want to open. If it didn't ask you, steam probably installed a browser plugin for that.
A Uniform Resource Identifier (URI) just identifies a resource, it doesn't necessarily describe how to access it. Moreover, for custom protocols, such as "steam" the vendor can define any underlying access conventions which compatible client programs must know to interact.
In order to "execute" a URI like this you need to know exactly how the protocol is implemented (is it over HTTP? TCP? UDP?) and how to speak with the server at the other end.
The Valve Developer Community wiki page might have some useful information.
Hi
I've done a lot of research on the best way to communicate between a java applet and MySql Database.
I have a tune player which I have students logging onto, it's a java applet with a speed slider. I want to save the speed that they play each tune at so it goes back to the same speed the next time they open that tune.
It seems I have a number of options, none of which seem very neat.
Use a javascript function to
periodically check the speed and
save it to a cookie, then each page
of the site would have to check
cookies relationg to each tune.
Make each link on the page call a
javascript function to check the
speed variable in the applet and add
it to a perameter in the url then
redirect so the next php page can
save the speed to a database. This
way when the user navigates away the
speed will be saved, but this won;t
work if the back button is used.
Is there a better way of doing this?
Use the JNLP API and the problems should be solved.
Since Java 1.6.0_10+, it is possible to use the Java Web Start API services (JNLP API) within an embedded applet. The JNLP API provides the PersistenceService. Here is a small demo. of the PersistenceService.
If the user hits the back button (or otherwise leaves the page), the destroy() method will be called. Override the destroy method and persist the data at that time.
No need to use JavaScript.
The java code below posts variables to a PHP script on the web server then
shows the server response on the console
private void post()
throws MalformedURLException, IOException
{ URL url;
URLConnection con;
OutputStream oStream;
String parametersAsString;
byte[] parameterAsBytes;
String aLine; // only if reading response
parametersAsString = "msg=hi&to=memo";
parameterAsBytes = parametersAsString.getBytes();
// send parameters to server
url = this.getCodeBase();
url = new URL(url + "scriptfile.php");
con = url.openConnection();
con.setDoOutput(true);
// setDoInput(true); // only if reading response
con.setDoInput(false);
con.setRequestProperty("Content=length", String.valueOf(parameterAsBytes.length));
oStream = con.getOutputStream();
oStream.write(parameterAsBytes);
oStream.flush();
// read response from server & show the server response on the Java console or whatever ...
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
aLine = in.readLine();
while (aLine != null)
{ System.out.println(line);
aLine = in.readLine();
}
in.close();
oStream.close();
}
I'd suggest you get the applet to update the database. Whenever the speed slider changes you can fire off an update to the database, or you might need to coalesce multiple changes into one request depending on usage.
When the applet changes tune it can also do its own lookup of the correct speed.
Note that the applet will probably not be able to hit the database directly - browsers should restrict what I/O operations are available to applets - but you should be able to get the applet to hit a URL on the server that will actually perform the update. Signing the applet may let you hit the database but you should read up on the applet security model and the various browser quirks first.
It's not really clear how all of this is set up since you don't have a lot of details. However, assuming that you have an actual Java applet, I'd say the following:
If the Java applet requires a login (that is, it knows who the user is) then it can store the preference on the server. To do this you could have the applet connect to the server using JDBC, which isn't generally a good idea for internet-facing applets, or you could have the applet send a message to a server process such as a web server. That process connects to the mysql server.
The applet can communicate directly with the browser using Javascript. So you can have the applet set the cookie when the slider changes, instead of having the Javascript set it.