how glassware develop with json - google-mirror-api

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/

Related

Is it possible to serve a templated text file using spark? (java web framework)

I am using spark as the backend to a project I am working on. I noticed that spark has the ability to serve templated html, using a templating engine such as velocity, freemaker, etc.
However, this isn't quite what I want. Instead of serving an html template, I would like to serve a plaintext file, while still allowing me to insert parameters where needed. For context, I am trying to allow the user to download code examples based on the parameters they have supplied.
Does anything like this exist, or do I need to essentially build the desired file's content and return it as a string?
Example of what I am trying to do
// example.java
public class Example {
public static void main(String [] args) {
System.out.println( {{ param }} );
}
}
So this ^ would be the plain text template that I am attempting to serve... "param" would be passed to the backend via http request, and inserted into the file. Then I would serve the file to the frontend.
So, (as mentioned in the comment :), glad it helped) you can serve this content as HTML page (then you can use template manager) containing only this plaintext content only. Only exception will be the extension which will be .html instead of .java if the user saves the file.
You could declare a route whose return type is 'text/plain'
get(Main.API_PUBLIC + "/sourcecode", (req, res) -> {
res.status(200);
res.type("text/plain");
return " /* This will be the code snippet you'll be returning */ ";
});
Another alternative would be putting your source code files into the static files directory and link to them in your html.

Spring MVC - Display Blob images from Database

Firstly, I am new to Spring MVC and I am really sorry if this seems like a duplicated question however I am struggling to find a break down guide/tutorial on how to display images on a JSP page after receiving them as blobs from the database. Most of the responses I've read just give you small snippets which confuse me more.
I have a MySQL DB which has a table full of images stored as blobs. I have a Service which retrieves the blob images from the database and populates an arrays of CommonsMultipartFile. I also have a Controller which passes the array to the JSP page where a loop iterates over each image which I'm trying to display.
CONTROLLER
#RequestMapping(value = { "/my/images" }, method = RequestMethod.GET)
public String getAllImages(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
final List<CommonsMultipartFile> images = new ArrayList<CommonsMultipartFile>();
myService.getAllImages(images);
model.addAttribute("myImages", images );
return getUrl(request);
}
JSP
<c:forEach items="${myImages}" var="image">
<img src="${image}">
</c:forEach>
This is as far as I got. The images are not displaying. Please can someone help?
Many Thanks in advance!
The best is to save those binary-files to harddisk (using pk as filename) and directly serve them to the browser.
You can write a Servlet too but its quite hard to write asynchron Servlets.

Returning multiple items with Servlet

Good day, I'm working on a Servlet that must return a PDF file and the message log for the processing done with that file.
So far I'm passing a boolean which I evaluate and return either the log or the file, depending on the user selection, as follows:
//If user Checked the Download PDF
if (isDownload) {
byte[] oContent = lel;
response.setContentType("application/pdf");
response.addHeader("Content-disposition", "attachment;filename=test.pdf");
out = response.getOutputStream();
out.write(oContent);
} //If user Unchecked Download PDF and only wants to see logs
else {
System.out.println("idCompany: "+company);
System.out.println("code: "+code);
System.out.println("date: "+dateValid);
System.out.println("account: "+acct);
System.out.println("documentType: "+type);
String result = readFile("/home/gianksp/Desktop/Documentos/Logs/log.txt");
System.setOut(System.out);
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter outl = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object
outl.print(result);
outl.flush();
}
Is there an efficient way to return both items at the same time?
Thank you very much
HTTP protocol doesn't allow you to send more than one HTTP response per one HTTP request. With this restriction in mind you can think of the following alternatives:
Let client fire two HTTP requests, for example by specifyingonclick event handler, or, if you returned HTML page in the first response, you could fire another request on window.load or page.ready;
Provide your for an opportunity of choosing what he'd like to download and act in a servlet accordingly: if he chose PDF - return PDF; if he chose text - return text and if he chose both - pack them in an archive and return it.
Note that the first variant is both clumsy and not user friendly and as far as I'm concerned should be avoided at all costs. A page where user controls what he gets is a much better alternative.
You could wrap them in a DTO object or place them in the session to reference from a JSP.

Carry success message through redirect after blobstore upload?

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.

Caching contents of a page?

I'm generating page content like:
// index.jsp
<%
List<Horse> horses = database.getHorses();
for (Horse it : horses) {
%>
<div><%= it.getName() %></div>
<%
}
%>
is it possible to grab the entire page content at the end of the jsp file, and dump it into a String, like:
String page = this.getPrintWriter().toString();
I'm just curious if this is possible. I might try caching the page as a String, but would need to rewrite my page generation to build everything in one StringBuilder like:
StringBuilder sb = new StringBuilder();
sb.append("<div>"); sb.append(it.getName()); sb.append("</div>");
...
<%= sb.toString() %>
String cached = sb.toString();
Thanks
Since it's user-specific data, you can't use GAE's memcache for this. It's an application wide cache. I'd just store it in the session scope.
HttpSession session = request.getSession();
List<Horse> horses = (List<Horse>) session.getAttribute("horses");
if (horses == null) {
horses = database.getHorses();
session.setAttribute("horses", horses);
}
That said, try to avoid using scriptlets as much as possible. The above can perfectly be done in a Servlet class and you can display them using JSTL c:forEach as follows:
<c:forEach items="${horses}" var="horse">
<div>${horse.name}</div>
</c:forEach>
Capturing generated page content can't be done by simply calling PrintWriter#toString(). The StringBuilder idea is funny, but it's really not worth it. Caching dynamic content has very little benefits for the purposes as you mention.
Best what you in this case can do with regard to page caching is just to leverage the webbrowser's default task to cache GET requests.
See also
How to avoid Java code in JSP?
How to capture dynamically generated content?
I would create a HttpServlet which just retrieves page content from a real page (any kind of page, also JSP). Then cache it.
Next time the user makes the same request it would try to get the data from memcache and if present, retrieve only the mem cache content.
Of course you have to check parameters, user id, e.t.c. which would change the content on cached page.
This way you could also have a full control of cache size (you can set cache expiration during PUT, limit cached page count e.t.c.)
BTW.. the answer with session data storage won't work!!. Session data is persisted only on single server. As appengine is running on some seriously large cluster (many-many machines), it won't ensure that two same request, from the same client would be served by the same machine - therefore the session data won't be accessible!
Learned this the hard way when i tried to do progress bars ;)
EDIT
Seems like sessions are working now with appengine and are shared across all servers (as google states they are using memcache internaly)

Resources