List of usage examples for javax.servlet.http HttpServletRequest getReader
public BufferedReader getReader() throws IOException;
BufferedReader
. From source file:gwap.game.quiz.PlayNRatingCommunicationResource.java
private UserPerceptionRating readOutJSONData(HttpServletRequest request) throws IOException { UserPerceptionRating userRecommendedRating = null; BufferedReader reader = request.getReader(); StringBuilder sb = new StringBuilder(); String line = reader.readLine(); while (line != null) { sb.append(line + "\n"); line = reader.readLine();/*from w w w . j av a 2 s.co m*/ } reader.close(); String data = sb.toString(); JSONParser parser = new JSONParser(); userRecommendedRating = new UserPerceptionRating(); Object obj; PerceptionPair[] perceptionPair = new PerceptionPair[5]; try { obj = parser.parse(data); JSONObject jsonObject = (JSONObject) obj; PerceptionPair p; for (Object k : jsonObject.keySet()) { Object value = jsonObject.get(k); String key = (String) k; if (key.equals("SID")) { this.sessionID = (String) value; } else if (key.equals("QuestionNumber")) { userRecommendedRating.setQuestionNumber(value); } else if (key.equals("LinearVsMalerisch")) { p = new PerceptionPair(); p.setPairname((String) k); p.setValue((Long) value); perceptionPair[0] = p; } else if (key.equals("FlaecheVsTiefe")) { p = new PerceptionPair(); p.setPairname((String) k); p.setValue((Long) value); perceptionPair[1] = p; } else if (key.equals("GeschlossenVsOffen")) { p = new PerceptionPair(); p.setPairname((String) k); p.setValue((Long) value); perceptionPair[2] = p; } else if (key.equals("VielheitVsEinheit")) { p = new PerceptionPair(); p.setPairname((String) k); p.setValue((Long) value); perceptionPair[3] = p; } else if (key.equals("KlarheitVsUnklarheitUndBewegtheit")) { p = new PerceptionPair(); p.setPairname((String) k); p.setValue((Long) value); perceptionPair[4] = p; } else if (key.equals("FillOutTimeMs")) { Long v; // for Java if (value instanceof Double) { v = ((Double) value).longValue(); // for HTML5 } else { v = (Long) value; } userRecommendedRating.setFillOutTimeMs(v); } } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassCastException e) { e.printStackTrace(); } userRecommendedRating.setPairs(perceptionPair); return userRecommendedRating; }
From source file:com.github.achatain.catalog.servlet.CollectionIdServlet.java
@Override protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { LOG.info("Edit the collection " + extractCollectionIdFromRequest(req)); final String userId = getUserId(req); final String colId = extractCollectionIdFromRequest(req); final CollectionDto collectionDto = gson.fromJson(req.getReader(), CollectionDto.class); Preconditions.checkArgument(collectionDto != null, "Request body is missing"); LOG.info(format("User [%s] to edit the collection [%s] with [%s]", userId, colId, gson.toJson(collectionDto))); collectionService.updateCollection(userId, colId, collectionDto); }
From source file:servlets.TestServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w ww . j a va2 s. com*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // Json handle part StringBuilder sb = new StringBuilder(); BufferedReader reader = request.getReader(); try { String line; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } String a = sb.toString(); JSONParser jp = new JSONParser(); Object o = jp.parse(a); JSONObject jo = (JSONObject) o; // JSON part , get values from json. String name = (String) jo.get("name"); String email = (String) jo.get("email"); String address = (String) jo.get("address"); String birthday = (String) jo.get("birthday"); // End of JSON part. out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("name: " + name + "<br>"); out.println("email: " + email + "<br>"); out.println("birthday: " + birthday + "<br>"); out.println("address: " + address + "<br>"); out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } catch (ParseException ex) { Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex); } finally { /* TODO output your page here. You may use following sample code. */ reader.close(); out.close(); } }
From source file:com.example.jumpnote.web.jsonrpc.server.JsonRpcServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean debug = isDebug(req); boolean prettyPrint = false; JSONTokener tokener = new JSONTokener(req.getReader()); JSONObject requestJson;// ww w . jav a 2 s.com JSONArray callsJson = null; JSONObject responseJson = new JSONObject(); JSONArray resultsJson = new JSONArray(); PersistenceManager pm = pmfInstance.getPersistenceManager(); UserService userService = UserServiceFactory.getUserService(); CallContext context = new CallContext(req, null, pm, userService); try { try { requestJson = new JSONObject(tokener); if (requestJson.has("pretty") && requestJson.getBoolean("pretty")) prettyPrint = true; callsJson = requestJson.getJSONArray("calls"); } catch (JSONException e) { responseJson.put("error", 400); responseJson.put("message", "Error parsing request object: " + e.getMessage()); } if (callsJson != null) { for (int i = 0; i < callsJson.length(); i++) { JSONObject callParamsJson = callsJson.getJSONObject(i); context.setParams(callParamsJson); JSONObject resultJson = new JSONObject(); try { Object dataJson = performCall(context); resultJson.put("data", (dataJson != null) ? dataJson : new JSONObject()); } catch (JsonRpcException e) { if (debug && e.getHttpCode() != 403) throw new RuntimeException(e); resultJson.put("error", e.getHttpCode()); resultJson.put("message", e.getMessage()); log.log(Level.SEVERE, "JsonRpcException (method: " + e.getMethodName() + ")", e); } resultsJson.put(resultJson); } } responseJson.put("results", resultsJson); resp.setContentType("application/json"); if (prettyPrint) resp.getWriter().write(responseJson.toString(2) + "\n"); else resp.getWriter().write(responseJson.toString() + "\n"); } catch (JSONException e) { if (debug) throw new RuntimeException(e); resp.setStatus(500); resp.setContentType("text/plain"); resp.getWriter().write("Internal JSON serialization error: " + e.getMessage()); log.log(Level.SEVERE, "JSONException", e); } finally { pm.close(); } }
From source file:org.everit.osgi.webconsole.configuration.ConfigServlet.java
private String requestBody(final HttpServletRequest req) throws IOException { StringBuilder sb = new StringBuilder(req.getContentLength()); String line;// w ww. java 2s. c o m BufferedReader reader = req.getReader(); while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); }
From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String requestPath = request.getRequestURI(); String queryString = request.getQueryString(); String method = request.getMethod(); String requestBody = IOUtils.toString(request.getReader()); requestBody = URLDecoder.decode(requestBody, "UTF-8"); //TODO String urlWithFullPath = StringUtils.isEmpty(queryString) ? requestPath : requestPath + "?" + queryString; String forwardUrl = getForwardUrl(urlWithFullPath); if (forwardUrl == null) { throw new IOException("Invalid forwardurl for : " + requestPath); }// w w w .j a va2 s.c o m URLConnection urlConnection = getUrlConnection(request, method, requestBody, forwardUrl); writeResponse(urlConnection, response); }
From source file:org.wso2.carbon.dataservices.google.tokengen.servlet.ConsentUrl.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { if (log.isDebugEnabled()) { log.debug("Request Received for consent URL"); }//from w w w . jav a 2 s . c o m StringBuffer jb = new StringBuffer(); JSONObject jsonObject; String line = null; String responseString; int responseStatus; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { jb.append(line); } jsonObject = new JSONObject(new JSONTokener(jb.toString())); String clientId = jsonObject.getString(DBConstants.GSpread.CLIENT_ID); String redirectURIs = jsonObject.getString(DBConstants.GSpread.REDIRECT_URIS); if (clientId == null || clientId.isEmpty()) { responseStatus = HttpStatus.SC_BAD_REQUEST; responseString = "ClientID is null or empty"; } else if (redirectURIs == null || redirectURIs.isEmpty()) { responseStatus = HttpStatus.SC_BAD_REQUEST; responseString = "Redirect URIs is null or empty"; } else { String[] SCOPESArray = { "https://spreadsheets.google.com/feeds" }; final List SCOPES = Arrays.asList(SCOPESArray); /* Security Comment : This response is trustworthy, url is hard coded in GoogleAuthorizationCodeRequestUrl constructor. */ responseString = new GoogleAuthorizationCodeRequestUrl(clientId, redirectURIs, SCOPES) .setAccessType("offline").setApprovalPrompt("force").build(); response.setContentType("text/html"); responseStatus = HttpStatus.SC_OK; } } catch (Exception e) { responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR; responseString = "Error in Processing accessTokenRequest Error - " + e.getMessage(); log.error(responseString, e); } try { PrintWriter out = response.getWriter(); out.println(responseString); response.setStatus(responseStatus); } catch (IOException e) { log.error("Error Getting print writer to write http response Error - " + e.getMessage(), e); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
From source file:io.fabric8.apiman.ui.LinkServlet.java
/** * Expects JSON data input of the form://from www . j a v a2 s . com * { * "access_token": "dXUkkQ7vX6Gv1-d9h1ZTqy_7OM0mAeHOYLV9odpA9r0", * "redirect": "http://localhost:7070/apimanui/api-manager/" * } * It then sets the authToken into the user's session and send * a 301 redirect to the supplied 'redirect' address within the apimanui. * The browser should follow this and the apimanui will load the * f8-config.js file. This file is served up from the AuthTokenParseServlet * that reads the token from user's session and sets it in the config.js * return, and SSO is accomplished. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { log.info(req.getSession().getId()); String authToken = (String) req.getParameter(ACCESS_TOKEN); String redirect = (String) req.getParameter(REDIRECT); if (authToken == null) { StringBuffer jb = new StringBuffer(); String line = null; BufferedReader reader = req.getReader(); while ((line = reader.readLine()) != null) jb.append(line); String data = jb.toString(); JSONObject json = new JSONObject(data); authToken = json.getString(ACCESS_TOKEN); redirect = json.getString("redirect"); } log.info("301 redirect to " + redirect); //Set the authToken in the session req.getSession().setAttribute("authToken", authToken); //Reply with a redirect to the redirect URL resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); resp.setHeader("Location", redirect); resp.sendRedirect(redirect); }
From source file:org.jahia.modules.saml2.admin.SAML2SettingsAction.java
/** * * @param request/*from www. j a va 2s. c o m*/ * @param renderContext * @param resource * @param session * @param parameters * @param urlResolver * @return * @throws Exception */ @Override public ActionResult doExecute(final HttpServletRequest request, final RenderContext renderContext, final Resource resource, final JCRSessionWrapper session, Map<String, List<String>> parameters, final URLResolver urlResolver) throws Exception { try { final String responseText = CharStreams.toString(request.getReader()); final JSONObject settings; final SAML2Settings serverSettings; final String siteKey = renderContext.getSite().getSiteKey(); // if payload has content, it means an update. if (StringUtils.isNotEmpty(responseText)) { settings = new JSONObject(responseText); final SAML2Settings oldSettings = saml2SettingsService.getSettings(siteKey); final Boolean enabled = getSettingOrDefault(settings, SAML2Constants.ENABLED, (oldSettings != null && oldSettings.getEnabled())); final String identityProviderUrl = getSettingOrDefault(settings, SAML2Constants.IDENTITY_PROVIDER_URL, (oldSettings != null ? oldSettings.getIdentityProviderUrl() : "")); final String relyingPartyIdentifier = getSettingOrDefault(settings, SAML2Constants.RELYING_PARTY_IDENTIFIER, (oldSettings != null ? oldSettings.getRelyingPartyIdentifier() : "")); final String incomingTargetUrl = getSettingOrDefault(settings, SAML2Constants.INCOMING_TARGET_URL, (oldSettings != null ? oldSettings.getIncomingTargetUrl() : "")); final String spMetaDataLocation = getSettingOrDefault(settings, SAML2Constants.SP_META_DATA_LOCATION, (oldSettings != null ? oldSettings.getSpMetaDataLocation() : "")); final String keyStoreLocation = getSettingOrDefault(settings, SAML2Constants.KEY_STORE_LOCATION, (oldSettings != null ? oldSettings.getKeyStoreLocation() : "")); final String keyStorePass = getSettingOrDefault(settings, SAML2Constants.KEY_STORE_PASS, (oldSettings != null ? oldSettings.getKeyStorePass() : "")); final String privateKeyPass = getSettingOrDefault(settings, SAML2Constants.PRIVATE_KEY_PASS, (oldSettings != null ? oldSettings.getPrivateKeyPass() : "")); if (enabled) { serverSettings = saml2SettingsService.setSAML2Settings(siteKey, identityProviderUrl, relyingPartyIdentifier, incomingTargetUrl, spMetaDataLocation, keyStoreLocation, keyStorePass, privateKeyPass); } else { serverSettings = null; } } else { serverSettings = saml2SettingsService.getSettings(siteKey); } final JSONObject resp = new JSONObject(); if (serverSettings != null) { resp.put(SAML2Constants.ENABLED, serverSettings.getEnabled()); resp.put(SAML2Constants.IDENTITY_PROVIDER_URL, serverSettings.getIdentityProviderUrl()); resp.put(SAML2Constants.RELYING_PARTY_IDENTIFIER, serverSettings.getRelyingPartyIdentifier()); resp.put(SAML2Constants.INCOMING_TARGET_URL, serverSettings.getIncomingTargetUrl()); resp.put(SAML2Constants.SP_META_DATA_LOCATION, serverSettings.getSpMetaDataLocation()); resp.put(SAML2Constants.KEY_STORE_LOCATION, serverSettings.getKeyStoreLocation()); resp.put(SAML2Constants.KEY_STORE_PASS, serverSettings.getKeyStorePass()); resp.put(SAML2Constants.PRIVATE_KEY_PASS, serverSettings.getPrivateKeyPass()); } resp.put("noConf", serverSettings == null); return new ActionResult(HttpServletResponse.SC_OK, null, resp); } catch (Exception e) { JSONObject error = new JSONObject(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("error while saving settings", e); } error.put("error", e.getMessage()); error.put("type", e.getClass().getSimpleName()); return new ActionResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, error); } }
From source file:com.appenginefan.toolkit.common.WebConnectionServer.java
/** * Dispatches an incoming request. This method can be called from a servlet * that wraps this object./*w w w . j a v a 2s .c o m*/ * @throws IOException * @return true if the incoming body was valid and the message has been processed */ public final boolean dispatch(Receiver receiver, HttpServletRequest req, HttpServletResponse resp) throws IOException { // First, read the content of the request into a string BufferedReader reader = req.getReader(); String body = null; try { StringBuilder sb = new StringBuilder(); for (int c = reader.read(); c >= 0; c = reader.read()) { sb.append((char) c); } body = sb.toString(); } finally { reader.close(); } // Can we parse the body? String meta = null; List<String> messages = null; try { // Is it valid JSON? JSONObject payload = null; payload = new JSONObject(body); // Does it have a meta tag and an array of messages? if (payload.has(WebConnectionClient.META)) { meta = payload.getString(WebConnectionClient.META); } JSONArray array = payload.getJSONArray(PayloadBuilder.TAG); // Extract all the messages out of the array messages = new ArrayList<String>(); for (int i = 0; i < array.length(); i++) { messages.add(array.getString(i)); } } catch (JSONException e) { return false; } boolean success = false; try { // New or existing connection? ServerEndpoint bus = null; boolean newBus = false; if (meta != null) { bus = server.loadServerEndpoint(req, meta); } if (bus == null) { bus = server.newServerEndpoint(req); newBus = true; } if (newBus) { bus.open(); } // Process the payload if (!newBus) { if (messages.isEmpty()) { try { receiver.onEmptyPayload(this, bus, req); } catch (Throwable t) { LOG.log(Level.WARNING, "Error while processing empty message", t); } } else { for (String message : messages) { try { receiver.receive(this, bus, message, req); } catch (Throwable t) { LOG.log(Level.WARNING, "Error while processing: " + message, t); } } } } // Now, put some data into the response and return server.writeState(req, bus, resp); success = true; } finally { // Commit all changes to the store, or roll them back if (success) { server.commit(req); } else { server.rollback(req); } } // Done return true; }