Call a servlet using post request with large amount of data and open url in new tab [duplicate] - gwt

This question already has answers here:
Is it possible to download a file from server to my device having MGWT&GwtPhoneGap app?
(2 answers)
Closed 8 years ago.
I am using gwt canvas .
I am having 74kb string(image) data which I want to pass it to servlet. So that servlet process that data and throw the contents to the browser . In this way it will prompt user to download it.
From client side I am using RequestBuilder to call a servlet ,set request data to it ,data is large so I am using post request. It is hitting servlet also throwing contents on the browser but not showing anything downloading.
The current url having canvas .I thinks that's why it is not downloading anything this conclusion is because If am opening that servlet directly using http://localhost:8080/servlet then its downloading it property (In this case i am not proving any content from client side) but for the url having canvas its giving problem.
So is there any way where i can open a url in new tab and can call servlet using post request in gwt.

You can use a Form Panel for do the upload, the Form Panel will use a hidden iframe,
FormPanel form = new FormPanel();
form.setMethod(FormPanel.METHOD_POST);
form.setAction("/downloadServlet");
FlowPanel hiddenPanel = new FlowPanel();
hiddenPanel.add(new Hidden("name1", "value"));
hiddenPanel.add(new Hidden("name2", "value"));
form.setWidget(hiddenPanel);
RootPanel.get().add(form);
form.submit();
The content return by the servlet if you put the correct header will be downloaded by the user navigator.
public class ServletDownloadDemo extends HttpServlet{
private static final int BYTES_DOWNLOAD = 1024;
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException{
//Get Parameters
String name1 = request.getParameter("name1");
String name2 = request.getParameter("name2");
response.setContentType("text/plain");
response.setHeader("Content-Disposition",
"attachment;filename=downloadname.txt");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("/testing.txt");
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
}

Related

GWT: Response not coming back to Form onSubmitCompleteEvent when a servlet sends a file in response to browser

Code on client side :
#UiHandler("form")
void onFormSubmission(SubmitCompleteEvent event) {
hideProcessingPopUp();
if (event.getResults().contains("Exception")) {
// handle exception
}
}
Servlet code in doPost method:
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment;filename="
+ exportType + ".csv");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
response.getOutputStream(), "UTF-8"));
// Adding content
List<CustomObject> list = (List<CustomObject>) anonymousList;
for (CustomObject eachObject : list) {
writer.append(eachObject.getContent());
writer.newLine();
}
writer.flush();
// Gently close streams/writers.
close(writer);
return fileContent;
Servlet code is fine, as am getting expected data and file. Problem is with response not reaching the client side i.e., SubmitCompleteEvent. Please help me out, thanks in advance.
This is how browsers work; and the javadoc for FormPanel actually warns you about it:
The back-end server is expected to respond with a content-type of 'text/html', meaning that the text returned will be treated as HTML. If any other content-type is specified by the server, then the result HTML sent in the onFormSubmit event will be unpredictable across browsers, and the onSubmitComplete event may not fire at all.

How to call a GwtServiceImpl Servlet from external application?

I have developed a Gwt application and need now to call its remote service implementation
from another java application. Is there a method that given a List of Java Objects can transform them in a format suitable for invoking the get service servlet?something like:
myObject = .......
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://localhost:8080/ppp//org.yournamehere.Main/gwtservice");
String serialized = <somelibrary.serialize>(myObject);
StringEntity input = new StringEntity(serialize);
input.setContentType("text/x-gwt-rpc; charset=UTF-8");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
Although, I haven't tried it the following link seems to be what you are looking for
http://googlewebtoolkit.blogspot.com/2010/07/gwtrpccommlayer-extending-gwt-rpc-to-do.html

How do I handle/fix "Error getting response stream (ReadDone2): ReceiveFailure" when using MonoTouch?

I am using MonoTouch to build an iPhone app. In the app I am making Web Requests to pull back information from the web services running on our server.
This is my method to build the request:
public static HttpWebRequest CreateRequest(string serviceUrl, string methodName, JsonObject methodArgs)
{
string body = "";
body = methodArgs.ToString();
HttpWebRequest request = WebRequest.Create(serviceUrl) as HttpWebRequest;
request.ContentLength = body.Length; // Set type to POST
request.Method = "POST";
request.ContentType = "text/json";
request.Headers.Add("X-JSON-RPC", methodName);
StreamWriter strm = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
strm.Write(body);
strm.Close();
return request;
}
Then I call it like this:
var request = CreateRequest(URL, METHOD_NAME, args);
request.BeginGetResponse (new AsyncCallback(ProcessResponse), request);
And ProcessResponse looks like this:
private void ProcessResponse(IAsyncResult result)
{
try
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result)) // this is where the exception gets thrown
{
using (StreamReader strm = new System.IO.StreamReader(response.GetResponseStream()))
{
JsonValue value = JsonObject.Load(strm);
// do stuff...
strm.Close();
} // using
response.Close();
} // using
Busy = false;
}
catch(Exception e)
{
Console.Error.WriteLine (e.Message);
}
}
There is another question about this issue for Monodroid and the answer there suggested explicitly closing the output stream. I tried this but it doesn't solve the problem. I am still getting a lot of ReadDone2 errors occurring.
My workaround at the moment involves just re-submitting the Web Request if an error occurs and the second attempt seems to work in most cases. These errors only happen when I am testing on the phone itself and never occur when using the Simulator.
Whenever possible try to use WebClient since it will deal automatically with a lot of details (including streams). It also makes it easier to make your request async which is often helpful for not blocking the UI.
E.g. WebClient.UploadDataAsync looks like a good replacement for the above. You will get the data, when received from the UploadDataCompleted event (sample here).
Also are you sure your request is always and only using System.Text.Encoding.ASCII ? using System.Text.Encoding.UTF8 is often usedm, by default, since it will represent more characters.
UPDATE: If you send or receive large amount to byte[] (or string) then you should look at using OpenWriteAsync method and OpenWriteCompleted event.
This is a bug in Mono, please see https://bugzilla.xamarin.com/show_bug.cgi?id=19673

Liferay Portlet and JSF : Redirect during Render Phase

I have a problem to implement a simple HTTP redirection.
I use Liferay 6.0.6, our portlets are build with JSF2.0 / PortletFaces.
I want to call a redirection when a view is loaded (and not when an action is triggered). Currently, my function is called by the PreRenderView listener.
<f:metadata>
<f:event listener="#{myControler.dispatch}" type="preRenderView" />
</f:metadata>
In this function, i can check the permissions, do other stuff, and in some cases I want to redirect the user to a new page (not another view).
I tried several methods, unsuccessfully.
Specifically, I thought that this method would work :
getFacesContext().getExternalContext().redirect(url);
getFacesContext().responseComplete()
// => Can only redirect during ACTION_PHASE
This error is logical, but is there a solution to force the redirection.
It could be realized in another function, called otherwise, I only need the Hibernate Session (set at the beginning of the Render Phase)
Have you ideas to resolve this problem?
Thanks!
ps : <redirect /> or ?faces-redirect don't work with the portlets.
You can't do this in the render phase by design. Reasons:
It's possible that portlets are rendered asynchronously, so the page might already be displayed when your portlet is being rendered
It's possible that parts of the page are already delivered to the client, so that the HTTP Headers are already sent - for this reason, by design you don't have access to them in the render phase
What would be the expected outcome if two portlets rendered on the same page would decide that they'd like to forwards to another page? Who would win?
A hacky workaround is to render some javascript redirect, but this is veeeery un-portal-like and can mess up other's expectations (plus, parts of the page might already be rendered, causing your users to fill a form only to be redirected by your javascript routine.
Please rethink the problem and come up with a different solution - it's really worth doing this in a portal environment.
I use this and it works for me:
public void preRenderView() throws IOException {
if (!checkUtente()) {
FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, "errore.xhtml?faces-redirect=true");
fc.renderResponse();
}
}
Use the below method it will work
public static void redirect(final String url) throws IOException {
final javax.portlet.PortletResponse portletResponse
= getPortletResponse();
if (portletResponse instanceof ActionResponse) {
final javax.portlet.ActionResponse actionResponse
= (javax.portlet.ActionResponse) portletResponse;
actionResponse.sendRedirect(url);
} else if (portletResponse instanceof ResourceResponse) {
final FacesContext ctx = FacesContext.getCurrentInstance();
if (ctx.getPartialViewContext().isPartialRequest()) {
final ResourceResponse portletResResp
= (ResourceResponse) portletResponse;
PartialResponseWriter pwriter;
final ResponseWriter writer = ctx.getResponseWriter();
if (writer instanceof PartialResponseWriter) {
pwriter = (PartialResponseWriter) writer;
} else {
pwriter = ctx.getPartialViewContext()
.getPartialResponseWriter();
}
portletResResp.setContentType(Constants.CONTENT_TYPE);
portletResResp.setCharacterEncoding(Constants.ENCODING_TYPE);
// addResponseHeader("Cache-Control", "no-cache");
pwriter.startDocument();
pwriter.redirect(url);
pwriter.endDocument();
ctx.responseComplete();
} else {
throw new UnsupportedEncodingException(
"Can only redirect during RESOURCE_PHASE "
+ "if a Partial-(JSF AJAX)-Request has "
+ "been triggered");
}
} else {
throw new UnsupportedEncodingException(
"Can not redirect during the current phase: "
+ portletResponse.getClass().getSimpleName());
}
}

multiple pages with C# Web browser control

I am trying to download HTML content from any URL through webbrowser control in C#.net.
I choose webrowser to handle Javascript issues. I am using webbrowser control without placing
it on the form. It works great for one url, but when I call it for multiple urls I am unable
to download the page.
Here is the code
GetWebpage()
{
System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
wb.Navigate(sURI, false);
bDocumentLoaded = false;
while (!bDocumentLoaded)
{
Application.DoEvents();
Thread.Sleep(100);
}
sHTML = wb.DocumentText;
bDocumentLoaded = false;
}
Event:
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
System.Windows.Forms.WebBrowser webBrowser1;
webBrowser1 = sender as WebBrowser;
string strTit = webBrowser1.DocumentTitle;
string str = webBrowser1.DocumentText;
bDocumentLoaded = true;
}
Cheers,
Karthik
You can use webclient object to fetch data from some url.
Try using Downloading String
public static void DownloadString (string address)
{
WebClient client = new WebClient ();
string reply = client.DownloadString (address);
Console.WriteLine (reply);
}
You can also use ASYC method of same downloading string.
I think your problem is that some sites are detecting specific browsertype and then they are returning HTML
Try setting the HeaderProperty of WebClient Object this is a list of HttpWebRequest Object
For Example
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
Modify the useragent of HTTPWEBRequest then add to headers.
HTTPWEBRequest.UserAgent=".NET Framework Test Client";
You can check more information about this in MSDN Link
I might recommend using the mshtml and SHDocVW libraries and using approach found in the answer here:
Unable to to locate and click a submit button using mshtml.HTMLInputElement