Reading request parameters in Google App Engine with Java [duplicate] - java

This question already has answers here:
GWT: Capturing URL parameters in GET request
(4 answers)
Closed 9 years ago.
I'm modifying the default project that Eclipse creates when you create a new project with Google Web Toolkit and Google App Engine. It is the GreetingService sample project.
How can I read a request parameter in the client's .java file?
For example, the current URL is http://127.0.0.1:8887/MyProj.html?gwt.codesvr=127.0.0.1&foo=bar and I want to use something like request.getParameter("foo") == "bar".
I saw that the documentation mentions the Request class for Python, but I couldn't find the equivalent for Java. It's listed as being in the google.appengine.ext.webapp package, but if I try importing that into my .java file (with a com. prefix), it says that it can't resolve the ext part.

Google App Engine uses the Java Servlet API.
GWT's RemoteServiceServlet provides access to the request through:
HttpServletRequest request = this.getThreadLocalRequest();
from which you can call either request.getQueryString(), and interpret the query string any way you desire, or you can call request.getParameter("foo")

I was able to get it to work using Window.Location via this answer:
import com.google.gwt.user.client.Window;
// ...
Window.Location.getParameter("foo") // == "bar"
Note that:
Location is a very simple wrapper, so not all browser quirks are hidden from the user.

Use java.net.URL to parse the URL and then String.split() to parse the query string.
URL url = new URL("http://127.0.0.1:8887/MyProj.html?gwt.codesvr=127.0.0.1&foo=bar");
String query[] = url.getQuery().split("&");
String foo = null;
for (String arg : query) {
String s[] = arg.split("=");
if (s[0].equals("foo"))
System.out.println(s[1]);
}
See http://ideone.com/Da4fY

Related

How to retrieve AWS Textract response JSON using the Java SDK

I am using AWS Textract to OCR images and create a searchable PDF as outlined in this AWS blog post.
The basic request code looks like this:
AmazonTextractClientBuilder builder = AmazonTextractClientBuilder.standard();
DetectDocumentTextRequest request = new DetectDocumentTextRequest()
.withDocument(new Document()
.withBytes(imageBytes));
DetectDocumentTextResult result = client.detectDocumentText(request);
List<Block> blocks = result.getBlocks()
This works out great however I would also like to write out and keep the original response JSON that contains all the information on what was detected where etc.
Is there a way to get to the response JSON using the JAVA SDK?
AWS doesn't return the response JSON to you in raw form. The assumption may have been that it wouldn't be required once it has been converted to a DetectDocumentTextResult object.
You are able to convert the DetectDocumentTextResult object to JSON (example) which should provide identical values. Note that the variable names will not be identical (e.g.: DocumentMetadata vs documentMetadata) but the values of those variables will be the same.

Generate Java class (Pojo) for parameters using WSDL url

I have a wsdl url using which I have to create a template file which has the list of the parameters for a particular API and create a pojo file for that request. I tried using soapui-api but I was unable to do so because of unable to fulfill the dependencies (Followed all the stackoverflow help to resolve the jar issues but it did not work):
Code:
WsdlProject project = new WsdlProject();
WsdlInterface[] wsdls = WsdlImporter.importWsdl(project, "http://XXXXX?wsdl");
WsdlInterface wsdl = wsdls[0];
for (com.eviware.soapui.model.iface.Operation operation : wsdl.getOperationList()) {
WsdlOperation wsdlOperation = (WsdlOperation) operation;
System.out.println("OP:"+wsdlOperation.getName());
System.out.println("Request:");
System.out.println(wsdlOperation.createRequest(true));
System.out.println("Response:"); System.out.println(wsdlOperation.createResponse(true));
}
Another approach in which I tried to parse the wsdl url using parser and get the list of names of the possible requests. I was able to get the request list but not the parameters required to create that request.
WSDLParser parser = new WSDLParser();
Definitions wsdl = parser.parse("http://XXXX?wsdl");
String str = wsdl.getLocalBindings().toString();
for(Message msg : wsdl.getMessages()) {
for (Part part : msg.getParts()) {
System.out.println(part.getElement());
}
}
Please help me on how to get the list of parameters from a wsdl url by either of the one approach.
well there are various stranded approach available for this , try and search for WS-import tool which is one of tools to do this .
This is the simple and best example here
WS_Import_tool
one more way of doing this is -
Apache_CFX
If you want to generate them using eclipse - that is also possible .
Check it out -
How do you convert WSDLs to Java classes using Eclipse?
What errors you are facing for SOAP UI
You can reffer this link for trouble shooting
Generate_java_from_Wsdl

Reading data from URL returning strange characters [duplicate]

This question already has answers here:
JSON URL from StackExchange API returning jibberish?
(3 answers)
Closed 9 years ago.
I am trying to grab the data from a json file through java. If I navigate to the URL using my browser, everything displays fine, but if I try to get the data using java I get get a bunch of characters that cannot be interpreted or parsed. Note that this code works with other JSON Files. Could this be a server side thing with the way the JSON file is created? I tried messing around with different character sets and that did not seem to fix the problem.
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.minecraftpvp.com/api/ping.json");
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
boolean hasLine = true;
while (hasLine) {
String line = in.readLine();
if (line != null) {
System.out.println(line);
} else {
hasLine = false;
}
}
}
The output I get from this is just a ton of strange characters that make no sense at all. Where if I change the url to something like google.com, it works fine.
EDIT: JSON URL from StackExchange API returning jibberish? Seemed to have answered my question. I tried searching before I asked to make sure the answer wasn't here and couldn't find anything. Guess I didn't look hard enough.
Yes that URL is returning gzip encoded content by default.
You can do one of three things:
Explicitly set the Accept-Encoding: header in your request. A web service should not return gzip compression unless it is listed as an accepted encoding in the request, so this website is not being very friendly. Your browser is setting it as accepted I suspect, that is why you can see it there. Just set it to an empty value and it should as per the spec return non-encoded responses, your mileage may vary on this one.
Or use the answer in this How to handle non-UTF8 html page in Java? that shows how to decompress the response. This should be the preferred option over #1.
And/or Ask the person hosting the service to implement the recommended scheme which is to only provide compressed responses if the client says it can handle them or if it can infer it from the browser fingerprint with high confidence.
Best of luck C.
You need to inspect the Content-Encoding header. The URL in question improperly returns gzip-compressed content even when you don't ask for it, and you'll need to run it through a decoder.

JSP/Servlet rewrite URL

I'd like to change the URL of some pages in my website in the same way as foursquare is doing:
from www.foursquare.com/v/anystring/venueid
to www.foursquare.com/v/venue-name/venueid
For example central park in new york:
https://foursquare.com/v/writeherewhatyouwant/412d2800f964a520df0c1fe3
becomes
https://foursquare.com/v/central-park/412d2800f964a520df0c1fe3
I'm developing a pure JSP/Servlet app, no frameworks, in a Tomcat container.
I'm thought of using tuckey's urlrewritefilter, but I don't see how can I use dynamic values coming from the servlet itself there (the venue name)
How can I accomplish this?
Off the top of my head, here's something you could try:
1) Create a servlet with a servlet-mapping matching the common (prefix) part of the URL (e.g. for foursquare the pattern would be /v/*).
2) In your servlet, retrieve the remaining part of the URL path using request.getPathInfo(). You can then parse it using regular string utilities and convert it to the new path you'd like.
3) Assuming your updated path is in a variable called newUrl, call response.sendRedirect(newUrl) to tell the browser to update its URL. This will also call your servlet again with the new path, so it needs to handle both cases.
See the javadoc for HttpServletResponse.sendRedirect() for more info about how it handles relative vs absolute paths, etc.

Show javascript visualization in java?

I want to use javascript libraries to make visualizations like D3 and many other cool ones. But my main application that generates the data is written in java. Is there a way to write a javascript in a java component and then display the visualization from java? Of course I need to pass the data from java to javascript in order to make the visualization.
Since Java 1.6 you can include JavaScript in Java using the ScriptEngine class. You can call functions from java, pass arguments and read results.
http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/
Short example of loading a javascript and calling a function:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("somejavascriptinthesamepackage.js"));
engine.eval(reader);
reader.close();
String result = (String) engine.eval("someFunction(" + <insert argement> + "));");
You should give more data about how the user is viewing the data, is it a web application, is the user viewing the data from a web browser and so on...
However, you can generate your data in java and then pass a JSON string to the js code. And the js code will take care of the display.
A good JSON lib is: Jackson.

Categories