We currently handle the communication to/for backend api* and mobile (ios & android) apps.
For a stupid banner-like thingie, we should provide these apps with some HTML they'll render.
This is how it's done now:
String html ="<html>.....{somePlaceHolder}...</html>";
html = html.replace("{somePlaceHolder}", "We're good");
Gson gson = gsonBuilder.create();
gson.toJson(html);
This looks pretty bad to me. Wrapping html inside json is pretty useless.
I'm sure some templating engine can help us out here.
I was wondering what's the best way to do it.
I suppose I could have some HTML files that I could load up and then have my rest resource produce application/xhtml+xml or text/html this one time instead of json.
Anybody has suggestion on some best practices.
Thanks
*we use jax-rs/jersey
Not sure if I understand the whole problem correctly, but why do you want your RESTful service to return HTML in the first place.
I suppose the RESTful service should return JSON (or XML, for that matter) but the main point is, it should return only the actual data; no HTML at all, especially not HTML wrapped into JSON.
The application that calls the RESTful service should be responsible for the displaying of the data, that is wrapping the data into HTML.
Related
I need to upload a File / Files from a Java "Client" (which is actually a background proccess) to a node.js Server via GraphQL....
Im fully aware that there are (way) better ways of doing this, but that's (unfortunately) the setup I'm stuck with.
Been working on this for a couple days now - without any success...
What I know is, that I need to send a multipart request to my graphql mutation endpoint. But I'm either to bad at Java, to new to GraphQL and/or simply to stupid to do this...
What I gathered from the little ressources that are out there:
Server Side
On the Server Side im working with the Appollo-Express Server
From what I read in the official Docs, I need a Schema which's looking like the following:
[...]
type Query{
uploads:[File]
}
type Mutation {
singleUpload(file: Upload!): File!
}
type File {
filename: String!
mimetype: String!
encoding: String!
}
[...]
With a resolver looking somewhat like:
[...]
Mutation: {
async singleUpload(parent, { file }) {
const { stream, filename, mimetype, encoding } = await file;
*DO MAGIC*
}
}
[...]
Client Side
TBH, im at a loss... I tried multiple ways of creating a Multipart Form, appending the File, Filename and what not... Tried multiple ways of builing the Query, with or without a "variable" Tag, etc. etc. but I got the feeling, that I'm not even close to getting it right.
I know how to send Form Data via REST (well... with extensive use of google), but can't wrap my head around doing the same with a graphql call.
Does anyone have any clue on how this is doable? Or at least some hints as what I could do? Google aint helping me at all with this.
Cheers
I'm a Java Developer and couldn't find many resources to develop facebook apps on Java. Well I'm developing a Facebook app on Java which at some point, reads the inbox of a user. I was able to create a Login flow and get a long term access token. But as I'm very new to the JSON concepts, I could not able to parse the facebook response to get the required data.
I've read some tutorials and got to know basics of JSON and could able to write the code for parsing Simple JSON structures like:
{
"id": 1,
"firstname": "Brad",
"languages": [
{ "lang":"en" , "knowledge":"proficient" },
{ "lang":"fr" , "knowledge":"advanced" },
]
"job":{
"place":"Silicon Valley",
"name":"Microsoft",
} }
But, I was unable to parse the Facebook response as it looks so complex, and I have referred various places for any example or sample code to Parse the Facebook's response for /me/inbox request and couldn't find any.Here I'm looking for any sample code to parse the inbox JSON Object to get the required information for my App. Any effort is highly appreciated. Thank You.
Edit: I'm looking for a sample code in plain JSPs or Servelts.
Spring Social is your friend. Don't get bogged down in integrating with Spring Security (although there are a lot of examples) as the JavaScript login process will be sufficient to get an auth token for the user that you can then query Facebook's API with - just use Spring Social as a library to hide the complexity of the JSON and given you java objects to work with directly.
I ended up having to do it myself. The parent JSON element 'data' contained the data I was looking for. Then I used this tutorial to format it and display it in a Facebook-like way.
I had to actually pick out the data I actually needed. Hope this helps!
You have to use JSONObject and JSONArray, which you can get from getJSONObject() and getJSONArray(). Once you've gotten the JSONObject or JSONArray you need, use getJSONString() to get the desired value.
The tutorial mentioned above is for Android, but the general idea is still there. Let me know if you have any questions. I've done a bit in JSP and Java servlets as well.
I'm in over my head.
At the broadest level, I'm trying to expose an Odata interface to an existing pool of data exposed by a service written using Mule. When my Mule service is invoked, if I detect that the URL is Odata format, I want to delegate processing down to something written in Java and then feed the response from that component back to my caller.
I found the Olingo and OData4j libraries. My problem is that these start from building a Web service. But that's too far upstream for me. I have a Web service. What I need to understand are what components I need to implement in order to pass the URL (which I have in hand) onward to an Odata parser which will, in turn, invoke a data provider.
I'm a bit lost with this technology. Can someone point me to a very basic tutorial that clearly delineates this. Or, can they give me a couple steps like: "You have to implement A, B & C and then pass your URL into C.foo()"?
I've tried the Getting Started doc for both libraries but they both start with "first we'll implement a Web service" and don't clearly delineate (to me, at least) where that leaves off and pure Odata sets in.
Thanks.
The following is the code that will help you to get started for using data from a service exposing via OData.(using Apache Olingo).
URL url=new URL(/*your url*/);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty(HttpHeaders.ACCEPT,HttpContentType.APPLICATION_XML);
conn.connect();
InputStream content=conn.getInputStream();
Edm edm = EntityProvider.readMetadata(content, false);
After this you can use static methods of EntityProvider class for carrying out various operations like read,update,write
If you are using odata4j go with the following code
ODataConsumer demo_consumer= ODataConsumers.create(/*your URL*/);
Enumerable<EntitySetInfo> demo_entitySetList = demo_consumer.getEntitySets();
for (EntitySetInfo entitySet : entitySetList) {
System.out.println(entitySet.getHref());
}
this sounds very like how we read rss or other data feeds
Since you have a url, this can be read by a Http Connector or even a polling http connector.
The data can be streamed using a Java input stream the default behavior or converted to a string (object to string).
A simple java component using (OData4j) can process your content .. it sounds like 2 simple components on a mule flow.
R
Let us suppose there is a jsp that needs to display the list of files shared shared by a particular IP. Client opens that jsp on his local server and the request is sent to a remote server to fetch the list.
Servlet on the server processes the request and fetches the list of files shared by that IP. Now how do the servlet send that list to the jsp page that requested it ?
JSP :
connection.openConnection(); // Connection sends IP as the query parameter to the
// remote servlet
Servlet :
doGet(..parameters..) {
list = getList(forThatIP);
// NOW HOW DO I SEND THIS LIST ?
}
One method that I thought was to send the whole data as a query string to a servlet on the client side(running a server such as tomcat) and then stash that list onto some file.Later jsp can parse the file and display the data. But that doesn't seem to be a good option.
Note: JSP is invoked when a servlet forwards after successfully sending the IP to remote servlet
You can use request.setAttribute() in the Servlet. Then you can use a JSP tag to retrieve the value in JSP. Investigate a bit on that.
EDIT :
In the Servlet doGet method, you can set the an attribute, say listOfFiles as:
resquest.setAttribute("listOfFiles",list);
Then in the JSP you can retirieve it using the EL expression:
${listOfFiles}
which is an inbuilt feature of JSP.
Alternatively, you can access it using
<% request.getAttribute("listOfFiles")%>
but it is bad to embed Java scriptlets inside JSPs.
If you're passing complex data (lists etc.) over a connection, you can look into using JSON or XML. Your JSP code should be able to parse either easily with the right library.
Actually it depends on how the jsp is invoked.
Do you perform a post onto it ? Does the servlet perform a forward ? Or is a sendRedirect() ?
According to this there are many ways to send data to your jsp. One is using request attributes or better, using request scoped beans. One other can be posting some sort of rappresentation of your list as a post parameter (be it json, xml or some custom format of yours).
Another thing to consider is, what are you using ? JSF ? Some Spring library ? According to that there may be other better (or worse) ways to send datas.
If working with simple JSP/Servlet on a small project I'd personally go with the request.setAttribute() way, indeed this will force me to invoke the jsp via something like
request.setAttribute("myList", yourListObject);
request.getRequestDispatcher("yourjsp.jsp").forward(request, response);
then in the jsp you can:
<% Object myListObj = pageContext.getRequest().getAttribute("myList"); %>
When you call a servlet from code, the best way is to use an HttpServlet and mimic the browser behavior.
Passing the data in the URL is a GET request. Useful only with relatively small chunks of data, but the semantics look like you want ("get a bit of data"). Something like http://myremoteserver.com/myServlet?ip=.... You will need a proper encoding of the parameters (the Java API can handle that).
Passing the data by writting into the stream will be a POST request. It has no limit in the data passed to the server, but the semantics is different ("change something in the system"). You could pass your data as a parameter inside the contents written, I am not really sure how to decode that. Another alternative is using a Servlet (no HttpServlet) and just treat the raw data.
In both cases the response will be returned in the connection output stream. You can use whatever format you like (an standard one like JSON will probably be best, even that defining your own XML). In this case, a viable alternative would be filenames separated by a 'safe' character (like \n or |). Quick, but it will be less flexible in the future.
I would go for a GET request and JSON encoding.
I have a developed a Restlet application. I would like to return a JSP file on a URL request through Restlet. How can I achieve this without using a redirect?
i.e.
Let's say I have the file "contact.jsp" on mydomain.com and I want people to be able to access contact.jsp at http://mydomain.com/contact
Thus, in Restlet, I would have:
router.attach("/contact", MyResource.class);
But how can I return the "contact.jsp" page? I know that a redirect would work, but I don't want users to see the ".jsp" in "http://mydomain.com/contact.jsp"... or is there another strategy that would work without even using restlet? Maybe some modification of my web.xml file?
Edit (2009-08-14):
My answer posted below doesn't work on App-Engine and Restlet. It does work however, if I don't include Restlet, or allow Restlet to have a url-pattern of "/*"
What would be ideal is to have a subclass of the Router that allows me to do this:
router.attach("/contact", "/contact.jsp");
Thanks!
Edit (2009-08-17):
I'm surprised I haven't had any responses since I posted a bounty. Will someone comment and let me know if my question/problem isn't clear?
Edit (2009-08-17):
Interesting observation. When using the method described by "Rich Seller" below, it works when deployed on Google App-Engine and not locally. Additionally, If I call http://mydomain.com/contact.jsp on Google App-Engine it bypasses Restlet and goes straight to the JSP. But, locally, Restlet takes over. That is, http://localhost:8080/contact.jsp does not go to the JSP and goes to Restlet. Do deployed app-engine applications respond differently to URLs as their local counterpart?
Restlet doesn't currently support JSPs directly. They're difficult to handle outside of the servlet container.
There's a discussion on Nabble about this issue that you may find useful, at the moment it looks like you need to either return a redirect to the JSP mapped as normal in the web.xml, or hack it to process the JSP and return the stream as the representation.
The response dated "Apr 23, 2009; 03:02pm" in the thread describes how you could do the hack:
if (request instanceof HttpRequest &&
((HttpRequest) request).getHttpCall() instanceof ServletCall) {
ServletCall httpCall = (ServletCall) ((HttpRequest) request).getHttpCall();
// fetch the HTTP dispatcher
RequestDispatcher dispatcher = httpCall.getRequest().getRequestDispatcher("representation.jsp");
HttpServletRequest proxyReq = new HttpServletRequestWrapper(httpCall.getRequest());
// Overload the http response stream to grab the JSP output into a dedicated proxy buffer
// The BufferedServletResponseWrapper is a custom response wrapper that 'hijacks' the
// output of the JSP engine and stores it on the side instead of forwarding it to the original
// HTTP response.
// This is needed to avoid having the JSP engine mess with the actual HTTP stream of the
// current request, which must stay under the control of the restlet engine.
BufferedServletResponseWrapper proxyResp = new BufferedServletResponseWrapper(httpCall.getResponse());
// Add any objects to be encoded in the http request scope
proxyReq.setAttribute("myobjects", someObjects);
// Actual JSP encoding
dispatcher.include(proxyReq, proxyResp);
// Return the content of the proxy buffer
Representation rep = new InputRepresentation(proxyResp.toInputStream(),someMediaType);
The source for the BufferedServletResponseWrapper is posted a couple of entries later.
"I would like to return a JSP file on a URL request through Restlet" - My understanding is JSP's are converted to servlets. Since Servlets are orthogonol to Restlets not sure how you can return JSP file through Restlet.
Assuming you are asking for a way to use JSP in addition to Restlet, This is best achieved by mapping your restlets to a rootpath such as /rest instead of /* and using the .jsp as usual.
Looks like a simple web.xml configuration.
<servlet>
<servlet-name>contactServlet</servlet-name>
<jsp-file>/contact.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>contactServlet</servlet-name>
<url-pattern>/contact</url-pattern>
</servlet-mapping>
This works without Restlet in App-Engine. But once I include Restlet, it doesn't work if I set my Reslet url-pattern to "/*"