How to create session only once, when the server starts? - java

I'm creating a chatbot for a java application with Watson Assistant, the servlet code:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String sessionIdOut = "";
String question = req.getParameter("message");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Set up Assistant service.
IamOptions iamOptions = new IamOptions.Builder().apiKey("<apikey>").build();
Assistant service = new Assistant("2018-09-20", iamOptions);
service.setEndPoint("https://gateway-lon.watsonplatform.net/assistant/api/");
assistantId = "<assistantid>";
// Create session.
CreateSessionOptions createSessionOptions = new CreateSessionOptions.Builder(assistantId).build();
SessionResponse session = service.createSession(createSessionOptions).execute();
sessionId = session.getSessionId();
// Suppress log messages in stdout.
LogManager.getLogManager().reset();
// Initialize with an empty value to start the conversation.
String inputText = question;
// Send message to assistant.
MessageInput input = new MessageInput.Builder().text(inputText).build();
MessageOptions messageOptions = new MessageOptions.Builder(assistantId, sessionId)
.input(input)
.build();
MessageResponse response = service.message(messageOptions).execute();
// Print the output from the dialog if any. Assumes a single text response.
List<DialogRuntimeResponseGeneric> responseGeneric = response.getOutput().getGeneric();
if(responseGeneric.size() > 0) {
System.out.println(response.getOutput()/*.getGeneric().get(0).getText()*/);
String answer = response.getOutput().getGeneric().get(0).getText();
// set up the response
res.setContentType("text/html");
res.setHeader("Cache-Control", "no-cache");
// write out the response string
res.getWriter( ).write(answer);
}
// Prompt for next round of input.
System.out.print(">> ");
}
Currently, the servlet always creates a new session and sets up the assistant when the GET request arrives from the user interface. I want it to create a new session and set up assistant service only once when the server starts.
Tryed to solve the problem by adding init() function, and writing the session creation and assistant setup code inside that init() function like this:
#Override
public void init() throws ServletException {
// Set up Assistant service.
IamOptions iamOptions = new IamOptions.Builder().apiKey("<apikey>").build();
Assistant service = new Assistant("2018-09-20", iamOptions);
service.setEndPoint("https://gateway-lon.watsonplatform.net/assistant/api/");
assistantId = "<assistantid>";
// Create session.
CreateSessionOptions createSessionOptions = new CreateSessionOptions.Builder(assistantId).build();
SessionResponse session = service.createSession(createSessionOptions).execute();
sessionId = session.getSessionId();
super.init();
}
But it doesn't work, when I write a question in user interface, it sends me back 500 status code.

I solved the problem!
Working code looks like:
package com.jtypebot;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.ibm.watson.developer_cloud.assistant.v2.Assistant;
import com.ibm.watson.developer_cloud.assistant.v2.model.CreateSessionOptions;
import com.ibm.watson.developer_cloud.assistant.v2.model.DeleteSessionOptions;
import com.ibm.watson.developer_cloud.assistant.v2.model.DialogRuntimeResponseGeneric;
import com.ibm.watson.developer_cloud.assistant.v2.model.MessageInput;
import com.ibm.watson.developer_cloud.assistant.v2.model.MessageOptions;
import com.ibm.watson.developer_cloud.assistant.v2.model.MessageResponse;
import com.ibm.watson.developer_cloud.assistant.v2.model.RuntimeIntent;
import com.ibm.watson.developer_cloud.assistant.v2.model.SessionResponse;
import com.ibm.watson.developer_cloud.service.security.IamOptions;
import java.util.List;
import java.util.logging.LogManager;
#WebServlet("/JtypeBot")
public class JtypeBot extends HttpServlet {
private static final long serialVersionUID = 1L;
String sessionId;
String assistantId;
Assistant service;
/**
* #see HttpServlet#HttpServlet()
*/
public JtypeBot() {
super();
}
#Override
public void init() throws ServletException {
super.init();
// Set up Assistant service.
IamOptions iamOptions = new IamOptions.Builder().apiKey("<apiKey>").build();
service = new Assistant("2018-09-20", iamOptions);
service.setEndPoint("https://gateway-lon.watsonplatform.net/assistant/api/");
assistantId = "<assistantId>"; // replace with assistant ID
// Create session.
CreateSessionOptions createSessionOptions = new CreateSessionOptions.Builder(assistantId).build();
SessionResponse session = service.createSession(createSessionOptions).execute();
sessionId = session.getSessionId();
System.out.print(sessionId);
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String sessionIdOut = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String question = req.getParameter("message");
// Suppress log messages in stdout.
LogManager.getLogManager().reset();
// Initialize with empty value to start the conversation.
String inputText = question;
// Send message to assistant.
MessageInput input = new MessageInput.Builder().text(inputText).build();
MessageOptions messageOptions = new MessageOptions.Builder(assistantId, sessionId)
.input(input)
.build();
MessageResponse response = service.message(messageOptions).execute();
// Print the output from dialog, if any. Assumes a single text response.
List<DialogRuntimeResponseGeneric> responseGeneric = response.getOutput().getGeneric();
if(responseGeneric.size() > 0) {
System.out.println(response.getOutput()/*.getGeneric().get(0).getText()*/);
String answer = response.getOutput().getGeneric().get(0).getText();
// set up the response
res.setContentType("text/html");
res.setHeader("Cache-Control", "no-cache");
// write out the response string
res.getWriter( ).write(answer);
}
// Prompt for next round of input.
System.out.print(">> ");
}
}

Related

Erro google API

I'm trying to run the example code given by google and the following error appears:
"message" : "The request is missing a valid API key.",
"status" : "PERMISSION_DENIED"
I created a credential and own client id, but I do not know where to insert in the code
código de exemplo:
package javaapplication1;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.model.ValueRange;
import java.io.IOException;
import java.security.GeneralSecurityException;
public class JavaApplication1 {
public static void main(String args[]) throws IOException, GeneralSecurityException {
// The ID of the spreadsheet to retrieve data from.
String spreadsheetId = "1er12_Tp-m1IJNRfz-72VwVY14Gj10b-IexY60fzZiGg"; // TODO: Update placeholder value.
// The A1 notation of the values to retrieve.
String range = "a1:b4"; // TODO: Update placeholder value.
// How values should be represented in the output.
// The default render option is ValueRenderOption.FORMATTED_VALUE.
String valueRenderOption = ""; // TODO: Update placeholder value.
// How dates, times, and durations should be represented in the output.
// This is ignored if value_render_option is
// FORMATTED_VALUE.
// The default dateTime render option is [DateTimeRenderOption.SERIAL_NUMBER].
String dateTimeRenderOption = ""; // TODO: Update placeholder value.
Sheets sheetsService = createSheetsService();
Sheets.Spreadsheets.Values.Get request =
sheetsService.spreadsheets().values().get(spreadsheetId, range);
request.setValueRenderOption(valueRenderOption);
request.setDateTimeRenderOption(dateTimeRenderOption);
ValueRange response = request.execute();
// TODO: Change code below to process the `response` object:
System.out.println(response);
}
public static Sheets createSheetsService() throws IOException, GeneralSecurityException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
// TODO: Change placeholder below to generate authentication credentials. See
// https://developers.google.com/sheets/quickstart/java#step_3_set_up_the_sample
//
// Authorize using one of the following scopes:
// "https://www.googleapis.com/auth/drive"
// "https://www.googleapis.com/auth/drive.file"
// "https://www.googleapis.com/auth/drive.readonly"
// "https://www.googleapis.com/auth/spreadsheets"
// "https://www.googleapis.com/auth/spreadsheets.readonly"
static Urlshortener newUrlshortener() {
AppIdentityCredential credential =
new AppIdentityCredential(Arrays.asList(UrlshortenerScopes.URLSHORTENER));
return new Urlshortener.Builder(new UrlFetchTransport(), JacksonFactory.getDefaultInstance(), credential)
.build();
}
return new Sheets.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Google-SheetsSample/0.1")
.build();
}
}
the code is an example given by google, and I'm still learning, my only need is to read a spreadsheet from the google spreadsheet that has been filled up with forms answers from google
THanks

Error 500 response is not committed

I am trying to send a request to my jsp page i.e manufacturer details and get the attribute via session, but it throws a 500 error.
package com.osahub.disaster.controller;
import java.io.IOException;
import static com.osahub.disaster.controller.Ofymethodadmin.ofy;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.osahub.disaster.controller.SendMail;
#SuppressWarnings("serial")
public class admin extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setContentType("text/plain");
resp.getWriter().println("Data Saved!");
PrintWriter out = resp.getWriter();
String name= req.getParameter("name");
String address = req.getParameter("address");
String email = req.getParameter("email");
String website = req.getParameter("website");
String topex = req.getParameter("topex");
String topdes = req.getParameter("topdes");
String topmob = req.getParameter("topmob");
String year = req.getParameter("year");
String brand = req.getParameter("brand");
String factory = req.getParameter("factory");
String sector = req.getParameter("sector");
String contactpername = req.getParameter("contactpername");
String contactperdes = req.getParameter("contactperdes");
String contactpermob = req.getParameter("contactpermob");
HttpSession currentSession=req.getSession();
currentSession.setAttribute("name", name);
req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);
SendMail mail = new SendMail();
mail.send(email, "send Test mail from gae" , "this is the mail body");
ManufacturerDetails ad = new ManufacturerDetails(name,address,email,website,topex,topdes,topmob,year,brand,factory,sector,contactpername,contactperdes,contactpermob);
ofy().save().entity(ad);
ofy().clear();
List<ManufacturerDetails> li = ofy().load().type(ManufacturerDetails.class).list();
Iterator<ManufacturerDetails> iter = li.iterator();
while(iter.hasNext())
{
ManufacturerDetails ad1 = iter.next();
System.out.println(ad1.getName());
System.out.println(ad1.getAddress());
System.out.println(ad1.getEmail());
System.out.println(ad1.getWebsite());
System.out.println(ad1.getTopex());
System.out.println(ad1.getTopdes());
System.out.println(ad1.getTopmob());
System.out.println(ad1.getYear());
System.out.println(ad1.getBrand());
System.out.println(ad1.getFactory());
System.out.println(ad1.getSector());
System.out.println(ad1.getContactpername());
System.out.println(ad1.getContactpermob());
System.out.println(ad1.getContactperdes());
}
resp.sendRedirect("about.jsp");
}
}
A response with HTTP status code 500 can be caused by any exception.
However, it looks like in your case the exception is thrown because you call resp.sendRedirect("about.jsp"); after req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);.
You cannot do that, because once the call to forward() completes, the response is committed. However, it does not mean that doPost() method returns control, it keeps executing. Thus, resp.sendRedirect("about.jsp"); causes java.lang.IllegalStateException exception to be thrown, since the response is already closed.
You have to review your method, and introduce a conditional statement:
if (condition) {
// do something
req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);
} else {
// do something
resp.sendRedirect("about.jsp");
}
Another option is to introduce an explicit return after req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);.
500 exception occurs due to the server problem . It is cause because you can write both code - getRequestDispatcher and sendRedirect for execute . And this is not possible . You can not do this because after once send the request paramater it terminate . So you can write both code in if-else condition .

ArrayList issue in HTTP Servlet

I'm using Floodlight REST API in order to monitor a created virtual network in mininet. My goal is to display an arraylist of all the switches, hosts and statistics for the switches on a web browser using Apache Tomcat web server and HTTP Servlet. The application successfully displays all the switches and hosts, but fails when I'm adding the statistics for the switches.
When I'm mapping JSON string to java objects, the server returns the error in this line:
ArrayList<Switch> queues = mapper.readValue(queueJson, new TypeReference<ArrayList<Switch>>() {
});
The error is:
HTTP status 500 - can not deserialize instance of java.util.arraylist out of start_object token
I have testet it without the switch statistics (Queues) part (with only hosts and devices) and everything works fine, but when I'm adding the queues ArrayList, it returns the above mentioned error.
How can I solve this issue ?. My code is shown below. Thanks in advance
package core;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.restlet.data.MediaType;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import pojos.Device;
import pojos.Switch;
#WebServlet("/PrintInfo")
public class PrintInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
public PrintInfo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// create ClientResource object
// List at the switches in the network
ClientResource cResourceSwitches = new ClientResource("http://127.0.0.1:8080/wm/core/controller/switches/json");
StringWriter sWriterSwitches = new StringWriter();
// List all the devices (hosts) in the network
ClientResource cResourceDevices = new ClientResource("http://127.0.0.1:8080/wm/device/");
StringWriter sWriterDevices = new StringWriter();
// List the statistics of the switches in the network
ClientResource cResourceQueues = new ClientResource("http://127.0.0.1:8080/wm/core/switch/all/queue/json");
StringWriter sWriterQueues = new StringWriter();
// get JSON data about switches; the data is put in a string writer
try {
// Getting data from Floodlight as a JSON string
cResourceSwitches.get(MediaType.APPLICATION_JSON).write(sWriterSwitches);
cResourceDevices.get(MediaType.APPLICATION_JSON).write(sWriterDevices);
cResourceQueues.get(MediaType.APPLICATION_JSON).write(sWriterQueues);
} catch (ResourceException e) {
request.setAttribute("error", "Connection with FLoodLight failed!");
request.getRequestDispatcher("WEB-INF/connectionError.jsp").forward(request, response);
return;
}
// put data from string writer into a string object
String switchesJson = sWriterSwitches.toString();
String devicesJson = sWriterDevices.toString();
String queueJson = sWriterQueues.toString();
// map JSON data to Java objects
// ObjectMapper converts between JSON - Java
ObjectMapper mapper = new ObjectMapper();
ArrayList<Switch> switches = mapper.readValue(switchesJson, new TypeReference<ArrayList<Switch>>() {
});
ArrayList<Device> devices = mapper.readValue(devicesJson, new TypeReference<ArrayList<Device>>() {
});
ArrayList<Switch> queues = mapper.readValue(queueJson, new TypeReference<ArrayList<Switch>>() {
});
// put objects in the request so we can use them later in the JSP
request.setAttribute("switches", switches);
request.setAttribute("devices", devices);
request.setAttribute("queues", queues);
// redirect to the jsp
request.getRequestDispatcher("WEB-INF/showInfo.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
}
}
Solved. The Switch class in "ArrayList" can't be used for switch statistics. A new class has to be implemented, which returns the values in
http://127.0.0.1:8080/wm/core/switch/all/queue/json
URI.

Get parameter sent via jquery ajax in Java Servlet [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 5 years ago.
I search this topic on web but I can't get a example that worked.
I will be gladed with someone could give me a help.
this is what I testing.
$.ajax({
url: 'GetJson',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: {id: 'idTest'},
success: function(data) {
console.log(data);
}
});
in Sevlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String id2[] = request.getParameterValues("id");
String id3 = request.getHeader("id");
}
I'm getting null in everything.
I had the same issue with getParameter("foo") returning null in the servlet. Found a simple solution which might be useful to people here. Use the default value
contentType='application/x-www-form-urlencoded; charset=UTF-8'
or leave it out. This will automatically encode the request with the data in parameters.
Hope this helps...
The sort answer is that this data is hidden in the request InputStream.
The following servlet is a demo of how you can use this (I am running it on a JBoss 7.1.1):
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name="fooServlet", urlPatterns="/foo")
public class FooServlet extends HttpServlet
{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = req.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buf = new byte[32];
int r=0;
while( r >= 0 ) {
r = is.read(buf);
if( r >= 0 ) os.write(buf, 0, r);
}
String s = new String(os.toByteArray(), "UTF-8");
String decoded = URLDecoder.decode(s, "UTF-8");
System.err.println(">>>>>>>>>>>>> DECODED: " + decoded);
System.err.println("================================");
Enumeration<String> e = req.getParameterNames();
while( e.hasMoreElements() ) {
String ss = (String) e.nextElement();
System.err.println(" >>>>>>>>> " + ss);
}
System.err.println("================================");
Map<String,String> map = makeQueryMap(s);
System.err.println(map);
//////////////////////////////////////////////////////////////////
//// HERE YOU CAN DO map.get("id") AND THE SENT VALUE WILL BE ////
//// RETURNED AS EXPECTED WITH request.getParameter("id") ////
//////////////////////////////////////////////////////////////////
System.err.println("================================");
resp.setContentType("application/json; charset=UTF-8");
resp.getWriter().println("{'result':true}");
}
// Based on code from: http://www.coderanch.com/t/383310/java/java/parse-url-query-string-parameter
private static Map<String, String> makeQueryMap(String query) throws UnsupportedEncodingException {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for( String param : params ) {
String[] split = param.split("=");
map.put(URLDecoder.decode(split[0], "UTF-8"), URLDecoder.decode(split[1], "UTF-8"));
}
return map;
}
}
With the request:
$.post("foo",{id:5,name:"Nikos",address:{city:"Athens"}})
The output is:
>>>>>>>>>>>>> DECODED: id=5&name=Nikos&address[city]=Athens
================================
================================
{address[city]=Athens, id=5, name=Nikos}
================================
(NOTE: req.getParameterNames() does not work. The map printed in the 4th line contains all the data normally accessible using request.getParameter(). Note also the nested object notation, {address:{city:"Athens"}} → address[city]=Athens)
Slightly unrelated to your question, but for the sake of completeness:
If you want to use a server-side JSON parser, you should use JSON.stringify for the data:
$.post("foo",JSON.stringify({id:5,name:"Nikos",address:{city:"Athens"}}))
In my opinion the best way to communicate JSON with the server is using JAX-RS (or the Spring equivalent). It is dead simple on modern servers and solves these problems.

Java Spring User Image Uploader with Mongodb

I've created a basic user system, where people can register and login.
Its storing textual data at this time, but I would like to expand the code to allow users to upload images of themselves.
I am using a mongodb, so I can stash the user id as a folder when the user gets created, as they add images of themselves it will go into this folder.
1.How do I dynamically create these folders and where. I've read the folder would normally be stored in the WEB-INF.
Or should/could the images be stored as a blob file in the mongodb?
2.How do I copy/store the images into these folders correctly, in the correct place.
I've tried adapting code from here http://www.roseindia.net/tutorial/spring/spring3/web/spring-3-mvc-fileupload-example.html
Its currently not relating to the user, nor is it organising the images into folders. Eventually I'd like to auto scale/crop the images to produce various thumbnail sizes.
FileUpload.java
package net.fileupload;
import org.springframework.web.multipart.MultipartFile;
public class FileUpload {
MultipartFile file;
public void setFile(MultipartFile file){
this.file=file;
}
public MultipartFile getFile(){
return file;
}
}
FileUploadController.java
package net.fileupload;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.*;
import net.fileupload.FileUpload;;
public class FileUploadController extends SimpleFormController{
#Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
FileUpload fileUpload = (FileUpload)command;
MultipartFile multipartFile = fileUpload.getFile();
String fileName="";
// image type of file processing...
System.err.println("-------------------------------------------");
try {
InputStream inputStream = null;
OutputStream outputStream = null;
if (multipartFile.getSize() > 0) {
inputStream = multipartFile.getInputStream();
fileName = request.getRealPath("") + "/images/"+ multipartFile.getOriginalFilename();
System.out.println(fileName);
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[2000000];
while ((readBytes = inputStream.read(buffer, 0, 2000000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
// ..........................................
Map model = new HashMap();
model.put("fileName", multipartFile.getOriginalFilename());
model.put("filepath", "images/"+multipartFile.getOriginalFilename());
return new ModelAndView(getSuccessView(), model);
}
}
FileUploadValidator.java
package net.fileupload;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import net.fileupload.FileUpload;
public class FileUploadValidator implements Validator{
#Override
public boolean supports(Class clazz){
return FileUpload.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object target, Errors errors){
FileUpload fileUpload = (FileUpload)target;
if(fileUpload.getFile().getSize()==0){
errors.rejectValue("file", "error.empty.file", "Please Select File.");
}
System.out.println(fileUpload.getFile().getSize());
if(fileUpload.getFile().getSize() > 2000000){
errors.rejectValue("file", "error.empty.file", "File size more than 2000000 bytes ");
}
}
}
Retrieving the images.
In theory the following should return the list of images relevant to a user. May wish to return these images as a json array.
a gallery controller
import java.util.ArrayList;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class GalleryController{
public static List<DBObject> getGallery(){
//__Prepare response
List<DBObject> images = new ArrayList<DBObject>();
BasicDBObject results = new BasicDBObject();
BasicDBObject result = new BasicDBObject();
result.put("image1", "/images/Bannan.jpg");
result.put("image2", "/images/Koala.jpg");
result.put("image3", "/images/Monkey.jpg");
results.put("images", result);
images.add(results);
return images;
}
}
a listener controller
/*
* Gallery methods
*/
#RequestMapping(method=RequestMethod.GET, value={"/gallery"})
public ModelAndView galleryDisplay(
HttpServletRequest request,
HttpServletResponse response,
#RequestParam(value="mode", required=false) String mode
) {
String message = "search view for "+mode;
List<DBObject> images = GalleryController.getGallery();
System.out.println(images);
String viewPage = "gallery/galleryview";
return new ModelAndView(viewPage, "images", images);
}
My current user controller looks like this.
Would be great if I can hook into the images for the user at this level and provide it for the template.
My current mapping works well with id's as parameters. localhost:8080/user?id=1312321321
/*
* User
*/
#RequestMapping(method=RequestMethod.GET, value={"/user","/user/{id}"})
public ModelAndView profileDisplay(
HttpServletRequest request,
HttpServletResponse response,
#RequestParam(value="id", required=false) String id
) throws UnknownHostException, MongoException {
ServiceSerlvet.appendSesssion(request);
//get search ALL users
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", new ObjectId(id));
List<DBObject> searchResponse =
PersonController.searchUsers(searchQuery);
//System.out.println("response from search user method:
"+searchResponse);
return new ModelAndView("user", "people", searchResponse);
}

Categories

Resources