I have a following problem - we are using FormPanel which sends file to the Servlet which takes the arguments and tries to parse XML from this file. This works fine.
Problem is when the user uploaded a wrong file, so parsing ends with SAXException which I would like to propagate (or the exception's message) to client. I tried something like
catch (SAXException ex) {
response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
response.flushBuffer();
}
but it's not working, I always get empty tag pre (<pre></pre>). I am trying to catch this with
formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
String s = event.getResults();
});
I can use response.getWriter().write("Error"); in my Servlet but how the client will know if the error really occured or not?Using something like event.getResults().contains("error") doesn't seem to me as a correct solution.
So I am thinking about using RequestBuilder but I don't see a way how could I get the the uploaded file and push it to my servlet. Or maybe converting my message to JSON would help?
You should refer to this thread on the google gwt discussion group. The way you described, parsing the event.getResults() to determine if there was an error or the result in case of a success is the correct way to do it, even though it might seem barbaric.
As suggested in the linked discussion, you can look into GWT Upload for cleaner code, as well as upload progress information. I believe your only two options to upload files to a server from a web page are forms or Flash.
Related
I'm making an URL shortener with the Javalin framework and have this endpoint set up:
app.routes(()->{
path("",()->{
get("/:id", ctx->{
//do stuff
ctx.redirect("somewhere.com");
});
});
});
Problem is when I need to serve a javascript file to load into my html files. It tries to load from http://localhost:7000/qrcode.min.js but ends up going to the endpoint mentioned above. From what I read in the documentation this is normal behaviour, Javalin first runs the endpoint handler and then (if it doesn't find an endpoint) runs the file handler.
So how can I fix this? should I define a GET request at "/qrcode.min.js"?, I dont think the javalin context handler has a function that lets me return a .js file.
As Matt already suggested in a comment, it would be way cleaner if you'd prefix either path. That way, you could have /r/:id (or /u/:id with "u" for "URL") and the static files would not get in your way, or you could prefix your static files with e.g. /static/, or even just /s/ for brevity, and your shortened URLs would not get in your way.
If you, however, prefer to stick with your current scheme, you can simply filter out JavaScript files (or any other non-id request) in the handler and instead provide the file (however, if you previously had auto-generated ETags, you'd lose caching if you don't want to handle that yourself).
The latter solution would look like so:
app.routes (() -> {
path ("", () -> {
get ("/:id", ctx -> {
String id = ctx.pathParam ("id");
if (id.endsWith (".js")) {
String resourcePath = "your/classpath/resources/folder/" + id;
try {
InputStream resultStream = Thread.currentThread ()
.getContextClassLoader ()
.getResourceAsStream (resourcePath);
if (resultStream == null)
throw new NullPointerException ("Script not found");
ctx.contentType ("application/javascript");
ctx.result (resultStream);
} catch (NullPointerException e) { // script does not exist
e.printStackTrace (); // for development only!
ctx.status (404);
}
return;
}
// do stuff
ctx.redirect ("somewhere.com");
});
});
});
Depending on your preference, you can also handle the resultStream == null case where my code is currently throwing an NPE to be caught by the outer try/catch and omit the try/catch completely.
Setting the Content-Type is essential so that the browser knows that you're actually responding with JavaScript code. Also, I'm typically using Thread.currentThread ().getContextClassLoader () because we'd want the resource to be resolved based upon the current HTTP handler thread, which could, in theory, have a different class path/class loader than the class we're currently in.
Please note that, as stated above, this will not support client-side caching as the handler simply ignores all ETag headers sent with the request* and instead respond with the complete file which, with many requests in a short amount of time and large scripts, will certainly put way more stress on your disks and CPUs.
Thus, I'd actually recommend to prefix the static files route and let Javalin/Jetty handle all the caching and files magic.
* Actually, the header sent by the client is If-None-Match most of the time. The server would respond with an ETag to allow for caching in the browser.
I am working on converting a Struts 1 site to Struts 2, not easy task as everything have changed from one framework to the next.
I was hoping someone has used or know about the org.apache.struts.util.ResponseUtils specifically the write method.
We are using Struts 1.0 and we are currently using this line in the code:
ResponseUtils.write(pageContext, results.toString());
Has anyone seen this tag? use this tag? and then convert it to Struts 2?
I have searched online and found some good tutorials and I am also reading "Struts2 in Action" which I saw recommended here in other post. But, very few sites or posts talk about specific tags.
I will appreciate any advice or hint that can let me to the path of success.
Create your own ResponseUtils with the method
public void write(PageContext pageContext, String text)
throws JspException {
JspWriter writer = pageContext.getOut();
try {
writer.print(text);
} catch (IOException e) {
throw new JspException(e);
}
}
I am creatin an app in Java that checks if a webpage has been updated.
However some webpages dont have a "last Modified" header.
I even tried checking for a change in content length but this method is not reliable as sometimes the content length changes without any modification in the webpage giving a false alarm.
I really need some help here as i am not able to think of a single foolproof method.
Any ideas???
If you connect the whole time to the webpage like this code it can help:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class main {
String updatecheck = "";
public static void main(String args[]) throws Exception {
//Constantly trying to load page
while (true) {
try {
System.out.println("Loading page...");
// connecting to a website with Jsoup
Document doc = Jsoup.connect("URL").userAgent("CHROME").get();
// Selecting a part of this website with Jsoup
String pick = doc.select("div.selection").get(0);
// printing out when selected part is updated.
if (updatecheck != pick){
updatecheck = pick;
System.out.println("Page is changed.");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception occured.... going to retry... \n");
}
}
}
}
How to get notified after a webpage changes instead of refreshing?
Probably the most reliable option would be to store a hash of the page contet.
If you are saying that content-length changes then probably the webpages your are trying to check are dynamically generated and or not whatsoever a static in nature. If that is the case then even if you check the 'last-Modified' header it won't reflect the changes in content in most cases anyway.
I guess the only solution would be a page specific solution working only for a specific page, one page you could parse and look for content changes in some parts of this page, another page you could check by last modified header and some other pages you would have to check using the content length, in my opinion there is no way to do it in a unified mode for all pages on the internet. Another option would be to talk with people developing the pages you are checking for some markers which will help you determine if the page changed or not but that of course depends on your specific use case and what you are doing with it.
Can somebody give a simple example for java code of a native app passing a string to a website?
For example: when a string has the value Hello everybody, the text Hello everybody should get pasted into the Google search field.
For the most simple use, you can try:
public static void browseURL(Activity activity, String url)
{
try
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
}
catch (Exception e)
{
message(activity, "Sorry, failed to view the desired page.");
}
}
and then call:
browseURL("http://www.google.com/search?q=Hello+World")
Do you want to fill the fields and submit them? If so, just do the request with the request parameters filled, and parse the response given by the server. Look into Apache HttpClient.
You don't actually have to add text to the Google search field explicitly. You can send a URL with a query string.
Depending on the website the query string will always be different. For Google it is http://www.google.ca/search?q=something . Anything after a ? is considered a query string which any good web developer will include in a webpage. That query string takes custom commands in the form of ?command=query for command&command2=query for command 2.
Since this is tagged blackberry, I assume you want to implement a blackberry app, and you don't explicitly explain what you want to do, so you have two options,
Invoke the browser
On that page it describes how to open a browser session. So within the
browserSession.displayPage("http://http://www.google.ca/search?q=searching%20for%20something");
If you need a class for URL encoding, let me know and I'll send one your way.
Http Request to pull the html of the webpage into the code. To do that, you'll have to look at my blog this week as I'll be posting a full in code network class either tomorrow or tuesday, which I'll edit this post to contain a link to.
OR you can send me a message if you need it NOW and I can email the non-cleaned up code to you.
I am using google-api-translate-java-0.92.jar.
Translate.setHttpReferrer("http://translate.google.com/");
try {
String translation = Translate.execute("arrangement", Language.ENGLISH, Language.UKRANIAN);
System.out.println(translation);
} catch (Exception e) {
System.out.println(e.getMessage());
}
But I get only one translation.
I go to page http://translate.google.com/ and It gives me multiple translation.
How can I get multiple translation from my code?
I don't believe you can...
Looking at the soucre, it builds up the following URL:
http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=en|uk&q=arrangement
which when you look at the JSON response, returns:
{"responseData": {"translatedText":"Композиція"}, "responseDetails": null, "responseStatus": 200}
As you can see, this is only returning a single word. The dictionary lookup on the google translate page must be an additional call to a different service (not part of the translate service)
EDIT
Using firebug, you can see the request that is being made by the translate page, and you get this URL:
http://translate.google.com/translate_a/t?client=t&text=arrangement&hl=en&sl=en&tl=uk&multires=1&otf=2&pc=0&sc=1
Which returns this:
[[["Композиція","arrangement","Kompozytsiya"]],[["noun",["розташування","розміщення","домовленість","аранжування","упорядкування","механізм","оформлення","пристрій","систематизація","монтаж","пристосування","урегулювання","плани","згода","залагода","розв'язання","порозуміння"]]],"en"]
However, this extended URL format is not supported by the translate JAR you are using (at least I can't find it in the source on google code), is not part of the googleapis subdomain, and I'm not even sure it's for public consumption or that calling it directly doesn't violate Googles T&Cs.
But that's how they generate the dictinary list anyway...
From Google Translate API FAQ (checked: 16 November 2013)
Is it possible to get multiple translations of a word?
The answer:
No. This feature is only available via the web interface at
translate.google.com
source: https://developers.google.com/translate/v2/faq#technical
There is an open enhancement request for this functionality. So it doesn't look like you're doing anything wrong; the API just doesn't expose that functionality.