Carry success message through redirect after blobstore upload? - google-app-engine

I'm saving an image as a blob using the following, but I'm not sure how to carry a message through the final redirect to display to the user:
JSP file:
<%
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String action = blobstoreService.createUploadUrl("/servletimg");
%>
<form method="POST" action="<%= action %>" enctype="multipart/form-data">
...
</form>
The target servlet:
public class ServletImg extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
{
saveImg(...);
req.setAttribute("msg", "worked ok!");
resp.sendRedirect("/");
}
}
The final jsp page we get redirected back to:
if (request.getAttribute("msg") == null) {
Log.e("Hey we're missing the expected attribute!!!");
}
It all works ok, my image gets saved etc, but I don't see the "msg" attribute when redirected back to the main jsp page. Is there a way to carry a message through, or do I have to append it as parameters in the redirect, like:
resp.sendRedirect("/?msg=it worked ok!");
Thanks

A redirect basically instructs the client to fire a new HTTP request to the server. The initial request (and response) will be garbaged, including all of the attributes set. So yes, you really need to pass a parameter along the redirect URL.
response.sendRedirect("index.jsp?msg=" + URLEncoder.encode("worked ok!", "UTF-8"));
and then in JSP
<p>Message: ${param.msg}</p>
Alternatively, you can instead also just forward to the resource in question, i.e.
request.setAttribute("msg", "worked ok!");
request.getRequestDispatcher("/index.jsp").forward(request, response);
and then in JSP (as a shorthand for the ugly and discouraged scriptlet with request.getAttribute("msg")):
<p>Message: ${msg}</p>
With a forward, the initial request will still be available in the targeted resource.

Related

Debugging RestEasy RestClient

I am using the framework in quarkus to build a rest client for the mandrill API
#RegisterRestClient
#Path("1.0")
#Produces("application/json")
#Consumes("application/json")
public interface MailService {
#POST
#Path("/messages/send-template.json")
JsonObject ping(JsonObject mandrillInput);
}
This is the relevant portion of my application.properties
com.example.service.MailService/mp-rest/url=https:/mandrillapp.com/api
And my example resource
#Path("/hello")
public class ExampleResource {
#Inject
#RestClient
MailService mailService;
#Produces(MediaType.TEXT_PLAIN)
#GET
public String hello() {
System.out.print("In the API");
JsonObject key = Json.createObjectBuilder().add("key", "ABCD").build();
System.out.println("The json built is "+key);
JsonObject response = mailService.ping(key);
System.out.println("The response is " + response);
return "hello";
}
}
What I saw is that if the API I am calling (Mandrill in this case) returns an error response (If my key is wrong for example), then the variable I am using to store the response doesnt get the response. Instead the REST API I am exposing to my application wrapping around this, gets populated with the response from Mandrill.
Is this expected behaviour? How can I debug the output of a rest client implementation in Quarkus?
The REST API being called is https://mandrillapp.com/api/docs/users.JSON.html#method=ping2
If you want to be able to get the body of the response when an error occurs, I suggest you use javax.ws.rs.core.Response as the response type.
You could also go another route and handle exceptions using ExceptionMapper

Problems for reading UTF-8 requests on Tomcat

I have an AngularJS app trying to submit a form to a Java backend deployed in a Tomcat 7.0.54. My AngularJS app seems to be submitting the form correctly. This is the content type header as recored by Chrome's inspector:
Content-Type:application/json;charset=UTF-8
The request payload, once again as recorded by Chrome's inspector, is:
{"newProject":{"title":"título","deadline":"30/Maio/2014", .....
That is, the AngularJS app is putting the request correctly in the wire. However, I',m unable to read this payload correctly in the server side. Characters like "í" are being printed as "?".
Just for the purpose of testing I modified my second filter in the chain (the first is Spring Security) for printing the content of the request. This is to be sure that neither my server side application nor any of the frameworks I'm using are interfering in my data.
#Override
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
try {
HttpServletRequest hsr = (HttpServletRequest)request;
if( "POST".equalsIgnoreCase( hsr.getMethod() ) && "http://localhost:8080/profile/createproject".equalsIgnoreCase( hsr.getRequestURL().toString() ) ) {
hsr.setCharacterEncoding( "UTF-8" );
BufferedReader reader = new BufferedReader( new InputStreamReader( request.getInputStream(), "UTF-8" ) );
System.out.println( reader.readLine() );
}
chain.doFilter( request, response );
} finally {
MDC.remove( CHAVE_ID_REQUEST );
}
}
Even reading the request in the second filter of the chain I'm getting "t?tulo" instead of "título". If the same AngularJS app submits to a node backend, then the payload is correctly read and printed in the terminal.
Does anyone have any glue about the reason Tomcat can't read my UTF-8 request correctly?
Seems like you already solved your particular problem, but wanted to add that a key reference for this kind of issue is http://wiki.apache.org/tomcat/FAQ/CharacterEncoding,
which is referenced in https://stackoverflow.com/a/470320/830737
In particular, I was able to solve a similar issue by setting URIEncoding="UTF-8" in my <Connector> in server.xml.

how glassware develop with json

From the sample app for google glass in java, I found it is working through JSP and servlet. So I can create a timelineitem and set text in to it
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
TimelineItem timelineItem = new TimelineItem();
timelineItem.setText("My Sample Project");
MirrorClient.insertTimelineItem(credential, timelineItem);
response.sendRedirect(WebUtil.buildUrl(request, "/second.jsp"));
}
and from jsp page i can catch the time line and get value from it, like
<%
if (timelineItems != null && !timelineItems.isEmpty()) {
for (TimelineItem timelineItem : timelineItems) {
%>
<div class="container">
<div class="row">
<div class="span4">
<h2>Timeline 2</h2>
<h3><%=StringEscapeUtils.escapeHtml4(timelineItem
.getText())%></h3>
</div>
</div>
</div>
<%
}
}
%>
So now I want to do something advance like bundle of timelines, set background image, custom menuitem, voice command etc.
But in tutorial for advance job i found it is using some JSON format like for menuitem
HTTP/1.1 201 Created
Date: Tue, 25 Sep 2012 23:30:11 GMT
Content-Type: application/json
Content-Length: 303
{
"text": "Hello world",
"menuItems": [
{
"action": "REPLY"
}
]
}
So how I do such of thing?
what should I write in servlet and how I get value from jsp page?
Should I generate json from servlet and directly write in response or something else
There are a couple of things in your code samples that are a bit misleading and confusing, so lets break them down.
Although the Java example uses a Servlet, which makes sense since it is intended as a server-side operation, it is not using JSP for the Glass portion itself. This is just for what is sent back to show the user.
In the first example, it is the call to MirrorClient.insertTimelineItem() that does the work of sending the card to Glass. You created this card by creating the TimelineItem and setting fields on this item.
You don't indicate where your third example comes from, exactly, although most Mirror API documentation includes examples for multiple languages, including the raw HTML with JSON (which you quoted) and Java. See, for example, https://developers.google.com/glass/v1/reference/timeline/insert#examples which has a more complete Java example that both sets text on the card and sets notification information. There are other getters for the various other attributes mentioned on that page as well.
The full JavaDoc for the Mirror API Java Library is at https://developers.google.com/resources/api-libraries/documentation/mirror/v1/java/latest/

Silverlight Upload file to MVC3 controller endpoint (Server Respose NotFound )

I'm developing a recorder in silverlight and I need to upload data from stream to the web server after recording process is completed.
On server side I'm using ASP.NET MVC 3, and I have created a Controller with method FileUpload.
public class FileUploaderController : Controller
{
[HttpPost]
public ActionResult FileUpload(string fileName)
{
....
}
}
In silverlight applet, the upload is made by parts, about 20000 bytes at time. Servers web config is configured to accept larger amount of data.
Server returns an exception "The remote server returned an error: NotFound.".
In this case the request have not reached the action and I can't understand why.
Example of code that is used to start upload:
UriBuilder httpHandlerUrlBuilder = new UriBuilder("http://localhost:37386/FileUploader/FileUpload/?fileName=" + Guid.NewGuid() + ".wav");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(httpHandlerUrlBuilder.Uri);
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data"; // This solved my problem
webRequest.BeginGetRequestStream(new AsyncCallback(WriteToStreamCallback), webRequest);
EDIT
My route configuration is by default:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
When the small amount of data is sent, everything goes well and server receives the requested data. But when data to be send is larger I'm just getting NotFound response. This doesn't make any sense to me, what I'm doing is:
HttpWebRequest to send 20000 bytes
close request stream (obtained from request.EndGetRequestStream)
wait for server response (from webRequest.EndGetResponse) This is where error occurs.
In my case, I never send more than 20000 bytes, which is strange this to work sometimes and others not.
I don't know a better way to explain this problem. If you need I can provide more code and more information.
Any help is very much appreciated.
With filddler I was able to get more detailed information regarding to the error. It was "upload file potentially dangerous Request.Form value was detected from the client...".
To solve this I've specified content-type of the webRequest to "multipart/form-data"

How to redirect browser from POST request to GET a new location? servlet

I'm using GAE with Java servlets.
I have a form POST request, and I have to redirect the browser to a new location with GET method. How can I do this?
I got solution:
http://en.wikipedia.org/wiki/Post/Redirect/Get
This is my code sample:
private void seeOther(HttpServletResponse resp, String pathOfOtherToSee)
{
resp.setStatus(HttpServletResponse.SC_SEE_OTHER);
resp.setHeader("Location", pathOfOtherToSee);
}

Resources