List of usage examples for javax.servlet.http HttpServletRequest getReader
public BufferedReader getReader() throws IOException;
BufferedReader
. From source file:org.thingsboard.server.service.security.auth.jwt.RefreshTokenProcessingFilter.java
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!HttpMethod.POST.name().equals(request.getMethod())) { if (log.isDebugEnabled()) { log.debug("Authentication method not supported. Request method: " + request.getMethod()); }/*w w w . j ava 2 s. co m*/ throw new AuthMethodNotSupportedException("Authentication method not supported"); } RefreshTokenRequest refreshTokenRequest; try { refreshTokenRequest = objectMapper.readValue(request.getReader(), RefreshTokenRequest.class); } catch (Exception e) { throw new AuthenticationServiceException("Invalid refresh token request payload"); } if (StringUtils.isBlank(refreshTokenRequest.getRefreshToken())) { throw new AuthenticationServiceException("Refresh token is not provided"); } RawAccessJwtToken token = new RawAccessJwtToken(refreshTokenRequest.getRefreshToken()); return this.getAuthenticationManager().authenticate(new RefreshAuthenticationToken(token)); }
From source file:org.apache.syncope.client.enduser.resources.UserSelfCreateResource.java
@Override protected ResourceResponse newResourceResponse(final Attributes attributes) { ResourceResponse response = new ResourceResponse(); response.setContentType(MediaType.TEXT_PLAIN); try {/*from ww w .ja va2 s. c om*/ HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest(); if (!xsrfCheck(request)) { LOG.error("XSRF TOKEN is not matching"); response.setError(Response.Status.BAD_REQUEST.getStatusCode(), "XSRF TOKEN is not matching"); return response; } String jsonString = request.getReader().readLine(); final UserTO userTO = MAPPER.readValue(jsonString, UserTO.class); if (!captchaCheck(request.getHeader("captcha"), request.getSession().getAttribute(SyncopeEnduserConstants.CAPTCHA_SESSION_KEY))) { throw new IllegalArgumentException("Entered captcha is not matching"); } if (isSelfRegistrationAllowed() && userTO != null) { LOG.debug("User self registration request for [{}]", userTO.getUsername()); LOG.trace("Request is [{}]", userTO); // check if request is compliant with customization form rules if (UserRequestValidator.compliant(userTO, SyncopeEnduserApplication.get().getCustomForm(), true)) { // 1. membership attributes management Set<AttrTO> membAttrs = new HashSet<>(); userTO.getPlainAttrs().stream().filter( attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR))) .forEachOrdered(attr -> { String[] simpleAttrs = attr.getSchema() .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR); MembershipTO membership = userTO.getMemberships().stream() .filter(memb -> simpleAttrs[0].equals(memb.getGroupName())).findFirst() .orElse(null); if (membership == null) { membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build(); userTO.getMemberships().add(membership); } AttrTO clone = SerializationUtils.clone(attr); clone.setSchema(simpleAttrs[1]); membership.getPlainAttrs().add(clone); membAttrs.add(attr); }); userTO.getPlainAttrs().removeAll(membAttrs); // 2. millis -> Date conversion for PLAIN attributes of USER and its MEMBERSHIPS SyncopeEnduserSession.get().getDatePlainSchemas().stream().map(plainSchema -> { millisToDate(userTO.getPlainAttrs(), plainSchema); return plainSchema; }).forEachOrdered(plainSchema -> { userTO.getMemberships().forEach(membership -> { millisToDate(membership.getPlainAttrs(), plainSchema); }); }); membAttrs.clear(); userTO.getDerAttrs().stream().filter( attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR))) .forEachOrdered(attr -> { String[] simpleAttrs = attr.getSchema() .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR); MembershipTO membership = userTO.getMemberships().stream() .filter(memb -> simpleAttrs[0].equals(memb.getGroupName())).findFirst() .orElse(null); if (membership == null) { membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build(); userTO.getMemberships().add(membership); } AttrTO clone = SerializationUtils.clone(attr); clone.setSchema(simpleAttrs[1]); membership.getDerAttrs().add(clone); membAttrs.add(attr); }); userTO.getDerAttrs().removeAll(membAttrs); membAttrs.clear(); userTO.getVirAttrs().stream().filter( attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR))) .forEachOrdered(attr -> { String[] simpleAttrs = attr.getSchema() .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR); MembershipTO membership = userTO.getMemberships().stream() .filter(memb -> simpleAttrs[0].equals(memb.getGroupName())).findFirst() .orElse(null); if (membership == null) { membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build(); userTO.getMemberships().add(membership); } AttrTO clone = SerializationUtils.clone(attr); clone.setSchema(simpleAttrs[1]); membership.getVirAttrs().add(clone); membAttrs.add(attr); }); userTO.getVirAttrs().removeAll(membAttrs); LOG.debug("Received user self registration request for user: [{}]", userTO.getUsername()); LOG.trace("Received user self registration request is: [{}]", userTO); // adapt request and create user final Response res = SyncopeEnduserSession.get().getService(UserSelfService.class) .create(userTO, true); buildResponse(response, res.getStatus(), Response.Status.Family.SUCCESSFUL.equals(res.getStatusInfo().getFamily()) ? "User[ " + userTO.getUsername() + "] successfully created" : "ErrorMessage{{ " + res.getStatusInfo().getReasonPhrase() + " }}"); } else { LOG.warn("Incoming create request [{}] is not compliant with form customization rules. " + "Create NOT allowed", userTO.getUsername()); buildResponse(response, Response.Status.OK.getStatusCode(), "User: " + userTO.getUsername() + " successfully created"); } } else { response.setError(Response.Status.FORBIDDEN.getStatusCode(), new StringBuilder().append("ErrorMessage{{") .append(userTO == null ? "Request received is not valid }}" : "Self registration not allowed }}") .toString()); } } catch (Exception e) { LOG.error("Unable to create userTO", e); response.setError(Response.Status.BAD_REQUEST.getStatusCode(), new StringBuilder().append("ErrorMessage{{ ").append(e.getMessage()).append(" }}").toString()); } return response; }
From source file:com.github.restdriver.clientdriver.unit.ClientDriverHandlerTest.java
/** * with an expectation set, and a request made, the handler checks for a match and returns the match if one is found *//*from w w w.j a v a2 s. c o m*/ @Test public void testExpectedRequest() throws IOException, ServletException { Request mockRequest = mock(Request.class); HttpServletRequest mockHttpRequest = mock(Request.class); HttpServletResponse mockHttpResponse = mock(HttpServletResponse.class); ClientDriverRequest realRequest = new ClientDriverRequest("yarr").withMethod(Method.GET).withParam("gooo", "gredge"); ClientDriverResponse realResponse = new ClientDriverResponse("lovely", "fhieow").withStatus(404) .withHeader("hhh", "JJJ"); when(mockHttpRequest.getMethod()).thenReturn("GET"); when(mockHttpRequest.getReader()).thenReturn(new BufferedReader(new StringReader(""))); when(mockHttpRequest.getInputStream()) .thenReturn(new DummyServletInputStream(new ByteArrayInputStream("".getBytes()))); when(mockRequestMatcher.isMatch((RealRequest) anyObject(), (ClientDriverRequest) anyObject())) .thenReturn(true); mockHttpResponse.setContentType("fhieow"); mockHttpResponse.setStatus(404); ByteArrayOutputStream baos = new ByteArrayOutputStream(); when(mockHttpResponse.getOutputStream()).thenReturn(new DummyServletOutputStream(baos)); sut.addExpectation(realRequest, realResponse); sut.handle("", mockRequest, mockHttpRequest, mockHttpResponse); assertThat(new String(baos.toByteArray()), equalTo("lovely")); }
From source file:org.apache.marmotta.platform.ldpath.webservices.LDPathWebService.java
/** * Evaluate the LDPath program send as byte stream in the POST body of the request starting at the contexts (array) * given as URL query arguments. Will return a JSON map with an entry for each context and its evaluation result. * The value of each entry will have the following format: * <ul>//from www.j a v a 2 s . c o m * <li><code>{ "type": "uri", "value": "..." }</code> for resources</li> * <li><code>{ "type": "literal", "value": "...", "language": "...", "datatype": "..."}</code> for literals (datatype and language optional)</li> * </ul> * * @HTTP 200 in case the evaluation was successful for all contexts * @HTTP 400 in case the LDPath program was invalid * @HTTP 404 in case one of the contexts passed as argument does not exist * @HTTP 500 in case there was an error accessing the repository or reading the POST body * * @param contextURI the URI of a single context to evaluate the program against * @param contextURIarr an array of URIs to use as contexts to evaluate the program against * @param request a POST request containing the LDPath program in the POST body * @return a JSON map with an entry for each context pointing to its evaluation result (another map with field/value pairs) */ @POST @Path("/debug") @Produces("application/json") public Response testProgram(@QueryParam("context") String[] contextURI, @QueryParam("context[]") String[] contextURIarr, @Context HttpServletRequest request) { final String[] cs = contextURI != null ? contextURI : contextURIarr; try { // 1. read in the program from the post stream String program = IOUtils.toString(request.getReader()); // 2. auto-register all namespaces that are defined in the triple store Map<String, String> namespaces = new HashMap<String, String>(); RepositoryConnection con = sesameService.getConnection(); try { con.begin(); for (Namespace ns : iterable(con.getNamespaces())) { namespaces.put(ns.getPrefix(), ns.getName()); } // 3. iterate over all context uris passed as argument and run the path query, storing the results // in a hashmap where the context uris are the keys and a result map is the value HashMap<String, Object> combined = new HashMap<String, Object>(); for (String context : cs) { if (ResourceUtils.isSubject(con, context)) { URI resource = con.getValueFactory().createURI(context); Map<String, List<Map<String, String>>> result = new HashMap<String, List<Map<String, String>>>(); try { for (Map.Entry<String, Collection<?>> row : ldPathService .programQuery(resource, program).entrySet()) { List<Map<String, String>> rowList = new ArrayList<Map<String, String>>(); for (Object o : row.getValue()) { if (o instanceof Value) { rowList.add(JSONUtils.serializeNodeAsJson((Value) o)); } else { // we convert always to a literal rowList.add(JSONUtils.serializeNodeAsJson(new LiteralImpl(o.toString()))); } } result.put(row.getKey(), rowList); } combined.put(context, result); } catch (LDPathParseException e) { log.warn("parse error while evaluating program {}: {}", program, e.getMessage()); return Response.status(Response.Status.BAD_REQUEST) .entity("parse error while evaluating program: " + e.getMessage()).build(); } } else { return Response.status(Response.Status.NOT_FOUND) .entity("resource " + context + " does not exist").build(); } } return Response.ok(combined).build(); } finally { con.commit(); con.close(); } } catch (RepositoryException ex) { handleRepositoryException(ex, LDPathWebService.class); return Response.serverError().entity("error accessing RDF repository: " + ex.getMessage()).build(); } catch (IOException ex) { return Response.serverError().entity("error reading program from stream: " + ex.getMessage()).build(); } }
From source file:Servlets.ServletMonitora.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String opcao = request.getParameter("opcao"); StringBuffer sb = new StringBuffer(); JSONParser parser = new JSONParser(); JSONObject produto = null;// ww w. j a v a 2 s .co m GerenciarProduto gerenciarProduto = new GerenciarProduto(); switch (opcao) { case "cadastrar": try { BufferedReader reader = request.getReader(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } try { produto = (JSONObject) parser.parse(sb.toString()); } catch (ParseException e) { e.printStackTrace(); } try { String nomeProduto = (String) produto.get("name"); String descricaoProduto = (String) produto.get("description"); String imagemProduto = (String) produto.get("image"); Long l = new Long((long) produto.get("price")); double precoProdutoModificado = l.doubleValue(); Integer codigoVendedor = (Integer) request.getSession().getAttribute("codigoVendedor"); //criando conexao gerenciarProduto.criarConexao(); gerenciarProduto.adicionarProduto(nomeProduto, precoProdutoModificado, imagemProduto, descricaoProduto, codigoVendedor); gerenciarProduto.fecharConexao(); } catch (Exception e) { e.printStackTrace(); } break; case "atualizar": try { BufferedReader reader = request.getReader(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } try { produto = (JSONObject) parser.parse(sb.toString()); } catch (ParseException e) { e.printStackTrace(); } try { Long longID = new Long((long) produto.get("id")); int id = longID.intValue(); String nomeProduto = (String) produto.get("name"); String descricaoProduto = (String) produto.get("description"); String imagemProduto = (String) produto.get("image"); Long l = new Long((long) produto.get("price")); double precoProdutoModificado = l.doubleValue(); Integer codigoVendedor = (Integer) request.getSession().getAttribute("codigoVendedor"); //criando conexao gerenciarProduto.criarConexao(); gerenciarProduto.atualizarProduto(id, nomeProduto, precoProdutoModificado, imagemProduto, descricaoProduto, codigoVendedor); gerenciarProduto.fecharConexao(); } catch (Exception e) { e.printStackTrace(); } break; case "deletar": try { BufferedReader reader = request.getReader(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } try { produto = (JSONObject) parser.parse(sb.toString()); } catch (ParseException e) { e.printStackTrace(); } try { Long longID = new Long((long) produto.get("id")); int id = longID.intValue(); //criando conexao gerenciarProduto.criarConexao(); gerenciarProduto.deletarProduto(id); gerenciarProduto.fecharConexao(); } catch (Exception e) { e.printStackTrace(); } break; } }
From source file:org.b3log.solo.processor.InitProcessorTestCase.java
/** * initSolo.//from w w w . j a v a 2 s . c om * * @throws Exception exception */ @Test(dependsOnMethods = "showInit") public void initSolo() throws Exception { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletContext()).thenReturn(mock(ServletContext.class)); when(request.getRequestURI()).thenReturn("/init"); when(request.getMethod()).thenReturn("POST"); final JSONObject requestJSON = new JSONObject(); requestJSON.put("userName", "test"); requestJSON.put("userEmail", "test@b3log.org"); requestJSON.put("userPassword", "1"); final BufferedReader reader = new BufferedReader(new StringReader(requestJSON.toString())); when(request.getReader()).thenReturn(reader); final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet(); dispatcherServlet.init(); final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); final HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(printWriter); dispatcherServlet.service(request, response); final String content = stringWriter.toString(); Assert.assertTrue(StringUtils.contains(content, "\"sc\":true")); }
From source file:org.sc.probro.servlets.RequestServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w w w .j a va2s.c o m UserCredentials user = new UserCredentials(); String contentType = getContentType(request); String content = null; String requestID = request.getRequestURI(); Broker broker = getBroker(); try { Request req = new Request(); if (contentType.equals(CONTENT_TYPE_JSON)) { BufferedReader reader = request.getReader(); int read = -1; StringBuilder sb = new StringBuilder(); while ((read = reader.read()) != -1) { sb.append((char) read); } content = sb.toString(); req.setFromJSON(new JSONObject(content), broker, user); } else if (contentType.equals(CONTENT_TYPE_FORM)) { Map<String, String[]> params = decodedParams(request); req.setFromParameters(params); } else { throw new BadRequestException(String.format("Illegal POST content type: %s", contentType)); } broker.update(user, requestID, req); } catch (JSONException e) { throw new BadRequestException(content); } finally { broker.close(); } response.sendRedirect("/"); } catch (BrokerException e) { handleException(response, e); } }
From source file:org.apache.marmotta.platform.sparql.webservices.SparqlWebService.java
/** * Execute a SPARQL 1.1 Update request using update via URL-encoded POST; * see details at http://www.w3.org/TR/sparql11-protocol/\#update-operation * // ww w .ja v a 2 s. co m * @param request the servlet request (to retrieve the SPARQL 1.1 Update query passed in the * body of the POST request) * @HTTP 200 in case the update was carried out successfully * @HTTP 400 in case the update query is missing or invalid * @HTTP 500 in case the update was not successful * @return empty content in case the update was successful, the error message in case an error * occurred */ @POST @Path(UPDATE) @Consumes({ "application/x-www-url-form-urlencoded", "application/x-www-form-urlencoded" }) public Response updatePostUrlEncoded(@Context HttpServletRequest request) { try { Map<String, String> params = parseEncodedQueryParameters(CharStreams.toString(request.getReader())); String q = StringUtils.defaultString(params.get("update")); String resultType = StringUtils.defaultString(params.get("output")); return update(q, resultType, request); } catch (IOException e) { return Response.serverError().entity(WebServiceUtil.jsonErrorResponse(e)).build(); } }
From source file:com.talis.platform.testsupport.VerifyableHandler.java
@Override public void handle(final String target, final HttpServletRequest req, final HttpServletResponse resp, final int dispatch) throws IOException, ServletException { try {// w w w . j av a 2 s .co m StubCallDefn defn = getExpectedCallDefn(target, req); if (defn == null) { assertionLog.append(String.format("Unexpected call: %s %s\n", req.getMethod(), target)); fail("fail test, no more handlers"); } assertEquals(defn.getExpectedPath(), target); assertEquals(defn.getExpectedMethod(), req.getMethod()); BufferedReader reader = req.getReader(); String entity = IOUtils.toString(reader); assertEquals(defn.getExpectedEntity(), entity); for (String key : defn.getHeaders().keySet()) { String expected = defn.getHeaders().get(key); String value = req.getHeader(key); assertEquals("Headers don't match for header " + key, expected, value); } resp.setStatus(defn.getExpectedReturnStatus()); resp.setHeader("Content-Type", defn.getExpectedReturnType()); Map<String, String> returnHeaders = defn.getReturnHeaders(); if (null != returnHeaders) { for (Entry<String, String> header : returnHeaders.entrySet()) { resp.setHeader(header.getKey(), header.getValue()); } } byte[] expectedReturnEntity = defn.getExpectedReturnEntity(); if (expectedReturnEntity != null) { resp.getOutputStream().write(expectedReturnEntity); } resp.flushBuffer(); } catch (RuntimeException t) { isOk.set(false); assertionLog.append(t.getStackTrace()); assertionLog.append('\n'); throw t; } catch (Error t) { isOk.set(false); assertionLog.append(t.getMessage()); assertionLog.append('\n'); throw t; } }
From source file:com.devnexus.ting.web.controller.CalendarController.java
@RequestMapping(value = "/{eventKey}/usercalendar/{id}", method = { RequestMethod.POST, RequestMethod.PUT }) @ResponseBody//from ww w .j a va2 s . c om public ResponseEntity<UserCalendar> updateCalendar(@PathVariable("eventKey") String eventKey, @PathVariable("id") String id, HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof String) { headers.add("WWW-Authenticate", "Google realm=\"http://www.devnexus.org\""); return new ResponseEntity<>(new UserCalendar(), headers, HttpStatus.UNAUTHORIZED); } User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); UserCalendar calendar = null; try { calendar = GSON.fromJson(request.getReader(), UserCalendar.class); calendar = calendarService.updateEntry(calendar.getId(), user, calendar); UnifiedMessage unifiedMessage = new UnifiedMessage.Builder().pushApplicationId(PUSH_APP_ID) .masterSecret(PUSH_APP_SECRET).aliases(Arrays.asList(user.getEmail())) .attribute("org.devnexus.sync.UserCalendar", "true").build(); javaSender.send(unifiedMessage); return new ResponseEntity<>(calendar, headers, HttpStatus.OK); } catch (IOException e) { Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e); } }