List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
@Override public void post(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path, @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp, @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters) throws RestException, IOException { try {// w w w . j av a2 s. com if (userId == null) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.RELAY_NOT_ALLOWED, "A relay cannot add locations"); } User user = User.getUserByUserId(userId); if (user == null) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.NO_SUCH_USER, "An error occurred identifying the user record for this key"); } BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream())); StringBuilder source = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { source.append(line); source.append(" "); } String name = null, description = null, tz = null; JSONObject object = new JSONObject(source.toString()); if (object.has("name") && !object.isNull("name")) { name = object.getString("name"); } if (object.has("description") && !object.isNull("description")) { description = object.getString("description"); } if (object.has("timeZone") && !object.isNull("timeZone")) { tz = object.getString("timeZone"); } if (name == null || description == null) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA, "Required fields: name, description"); } TimeZone timeZone = (tz == null ? TimeZone.getTimeZone("UTC") : TimeZone.getTimeZone(tz)); Location location = Location.create(userId, name, description, timeZone); user.grant(location); resp.setStatus(HttpServletResponse.SC_CREATED); resp.getWriter().println((new JSONObject(toJSON(location))).toString()); resp.getWriter().flush(); } catch (JSONException e) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON, "Invalid JSON in request"); } catch (PersistenceException e) { throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR, e.getMessage()); } }
From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java
public byte[] procLogoutRequest(HttpServletRequest req) throws WsSrvException { LogoutResponse lresp;//w ww. j a v a 2s. c o m try { lresp = procLogoutRequest(req.getInputStream()); } catch (XMLParserException | UnmarshallingException | IOException | ValidationException e) { //-- 76 throw new WsSrvException(76, e); } // Return soap logout response Envelope evp = makeSoapEnvelope(lresp); Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(evp); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, Charset.forName("UTF-8")); try { XMLHelper.writeNode(marshaller.marshall(evp), writer); } catch (MarshallingException e) { //-- 77 throw new WsSrvException(77, e); } return out.toByteArray(); }
From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java
@Override protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta) throws ServletException, IOException { String tipo = requisicao.getContentType(); if (tipo == null || tipo.isEmpty()) tipo = "text/plain"; String codificacao = requisicao.getCharacterEncoding(); if (codificacao == null || codificacao.isEmpty()) codificacao = "UTF-8"; resposta.setCharacterEncoding(codificacao); PrintWriter saida = resposta.getWriter(); try {/*from w w w. jav a2 s. c o m*/ JSON json; if (tipo.contains("json")) { json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao)); } else { json = new JSON(); } Enumeration<String> parametros = requisicao.getParameterNames(); while (parametros.hasMoreElements()) { String chave = parametros.nextElement(); String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao); json.put(chave, valor); } if (tipo.contains("multipart")) { Collection<Part> arquivos = requisicao.getParts(); if (!arquivos.isEmpty()) { File diretorio = new File(uxiAmarelo.getDiretorio()); if (!diretorio.isAbsolute()) { diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator + uxiAmarelo.getDiretorio()); } if (!diretorio.exists()) diretorio.mkdirs(); String diretorioStr = diretorio.getAbsolutePath(); String url = uxiAmarelo.getDiretorioURL(); if (uxiAmarelo.isDiretorioURLRelativo()) { String url_esquema = requisicao.getScheme(); String url_servidor = requisicao.getServerName(); int url_porta = requisicao.getServerPort(); String url_contexto = requisicao.getContextPath(); url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url; } if (url.charAt(url.length() - 1) == '/') { url = url.substring(0, url.length() - 1); } Map<String, List<JSON>> mapa_arquivos = new HashMap<>(); for (Part arquivo : arquivos) { String chave = arquivo.getName(); String nome_original = getNome(arquivo, codificacao); String nome = nome_original; if (nome == null || nome.isEmpty()) { try (InputStream is = arquivo.getInputStream()) { String valor = IOUtils.toString(is, codificacao); valor = URLDecoder.decode(valor, codificacao); json.put(chave, valor); continue; } } if (uxiAmarelo.getArquivoNome().equals("uuid")) { nome = UUID.randomUUID().toString(); } while (new File(diretorioStr + File.separator + nome).exists()) { nome = UUID.randomUUID().toString(); } arquivo.write(diretorioStr + File.separator + nome); List<JSON> lista = mapa_arquivos.get(chave); if (lista == null) { lista = new LinkedList<>(); mapa_arquivos.put(chave, lista); } lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome)); } for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) { List<JSON> lista = entrada.getValue(); if (lista.size() > 1) { json.put(entrada.getKey(), lista); } else { json.put(entrada.getKey(), lista.get(0)); } } } } String copaiba = (String) json.remove("copaiba"); if (StringUtil.tamanho(copaiba) == 0) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String[] copaibaParam = copaiba.split("@"); if (copaibaParam.length != 3) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String comando = (String) json.remove("uxicmd"); if (StringUtil.tamanho(comando) == 0) comando = null; if (uxiAmarelo.isCookieEnviar()) { Cookie[] cookies = requisicao.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String nome = cookie.getName(); if (uxiAmarelo.cookieBloqueado(nome)) continue; if (!json.has(nome)) { try { json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { json.put(nome, cookie.getValue()); } } } } } if (uxiAmarelo.isEncapsulamentoAutomatico()) { final String sepstr = uxiAmarelo.getEncapsulamentoSeparador(); final char sep0 = sepstr.charAt(0); for (String chave : new HashSet<>(json.keySet())) { if (chave.indexOf(sep0) == -1) continue; String[] caminho = chave.split(sepstr); if (caminho.length > 1) { Util.encapsular(caminho, json.remove(chave), json); } } } String resultado; if (comando == null) { try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) { resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]); if (resultado == null) resultado = ""; } } else if (comando.equals("voltar")) { resultado = json.toString(); comando = null; } else { resultado = ""; } if (comando == null) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("application/json"); saida.write(resultado); } else if (comando.startsWith("redirecionar")) { resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado)); } else if (comando.startsWith("base64")) { String url = comando.substring("base64.".length()); resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8"))); } else if (comando.startsWith("html_url")) { HttpURLConnection con = (HttpURLConnection) new URL( Util.obterStringDeJSON("html_url", comando, resultado)).openConnection(); con.setRequestProperty("User-Agent", "Uxi-amarelo"); if (con.getResponseCode() != HttpServletResponse.SC_OK) throw new IOException("HTTP = " + con.getResponseCode()); resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); try (InputStream is = con.getInputStream()) { saida.write(IOUtils.toString(is)); } con.disconnect(); } else if (comando.startsWith("html")) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); saida.write(Util.obterStringDeJSON("html", comando, resultado)); } else { throw new IllegalArgumentException(comando); } } catch (Exception e) { resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resposta.setContentType("application/json"); saida.write(Util.gerarRespostaErro(e).toString()); } saida.flush(); }
From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ByteArrayOutputStream dupIn = null; if (dumpRequests) { String qs = req.getQueryString(); Logger.getAnonymousLogger().info(String.format("method: %s, requestUrl: %s", req.getMethod(), req.getRequestURL().append(qs != null ? "?" + URLDecoder.decode(qs, "UTF-8") : "").toString() ));// w ww .j a v a2 s . c o m dupIn = new ByteArrayOutputStream(); req = new AlternateInputHttpServletRequestWrapper(req, new InputStreamServletInputStream(new DuplicatingInputStream(req.getInputStream(), dupIn))); } long s = System.currentTimeMillis(); try { super.service(req, res); } finally { long d = System.currentTimeMillis() - s; if (displayProcessTime) { Logger.getAnonymousLogger().info("processTime: " + d + "ms."); } if (dupIn != null && dupIn.size() > 0) { Logger.getAnonymousLogger() .info(String.format("requestInput: %s", new String(dupIn.toByteArray(), "UTF-8"))); } } }
From source file:com.reachcall.pretty.http.ProxyServlet.java
@SuppressWarnings("unchecked") private void doPost(HttpPost method, HttpServletRequest req) throws IOException { copyHeaders(req, method);// www .j a va2 s.c om if (CONTENT_TYPE_FORM.equalsIgnoreCase(req.getContentType())) { Map<String, String[]> params = (Map<String, String[]>) req.getParameterMap(); List<NameValuePair> pairs = new LinkedList<NameValuePair>(); for (String name : params.keySet()) { String[] values = params.get(name); for (String value : values) { NameValuePair pair = new BasicNameValuePair(name, value); pairs.add(pair); } } method.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8")); } else { method.setEntity(new InputStreamEntity(req.getInputStream(), req.getContentLength())); } }
From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java
/** * {@inheritDoc}/*w w w.j a va2s . co m*/ */ public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad // happened, Upload // should be able to // take care of most // stuff String p = new String(req.getPathInfo().getBytes("ISO-8859-1"), "UTF-8"); DavPath path = new DavPath(p); try { InputStream data = req.getInputStream(); WikiContext context = m_engine.createContext(req, WikiContext.UPLOAD); String wikipage = path.get(0); errorPage = context.getURL(WikiContext.UPLOAD, wikipage); String changeNote = null; // FIXME: Does not quite work boolean created = executeUpload(context, data, path.getName(), errorPage, wikipage, changeNote, req.getContentLength()); if (created) { res.sendError(HttpServletResponse.SC_CREATED); } else { res.sendError(HttpServletResponse.SC_OK); } } catch (ProviderException e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (RedirectException e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:me.ywork.ticket.suite.controller.DingServiceController.java
/** * URL// w ww . ja v a2 s.c o m * 1.1 ?URL * 1.2 ?Ticket * 1.3 ?ISV??? * 1.4 ?ISV???? * 1.5"?" * 1.6"?" * 1.7"??" */ @RequestMapping(value = "/index/{suiteid}", method = RequestMethod.POST) public void isvReceive(@PathVariable("suiteid") String sid, HttpServletRequest request, HttpServletResponse response) { String msgSignature = request.getParameter("signature"); String timeStamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); try { // ?DingTalk?POST? InputStream inputStream = request.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); JSONObject jsonEncrypt = DingAPIHttpUtil.getBody(br); br.close(); inputStream.close(); // ?JSONencrypt String encryptStr = jsonEncrypt.getString("encrypt"); // ?ID:suiteIdID if (StringUtils.isEmpty(sid)) { sid = "suite4xxxxxxxxxxxxxxx"; } else if (sid.indexOf("?") > 0) { sid = sid.substring(0, sid.indexOf("?")); } // ???? DingTalkEncryptor dingTalkEncryptor = null; DingSuiteMain suite = dingSuiteMainService.getDingSuiteFromCache(sid); if (suite == null) { dingTalkEncryptor = dmap.get(DingTicketConfigure.defaultSuiteKey); if (dingTalkEncryptor == null) { dingTalkEncryptor = new DingTalkEncryptor(DingTicketConfigure.defaultToken, DingTicketConfigure.defaultAESKey, DingTicketConfigure.defaultSuiteKey); dmap.put(DingTicketConfigure.defaultSuiteKey, dingTalkEncryptor); } } else { dingTalkEncryptor = dmap.get(suite.getSuiteId()); if (dingTalkEncryptor == null) { dingTalkEncryptor = new DingTalkEncryptor(suite.getToken(), suite.getEncodingAESKey(), suite.getSuiteId()); dmap.put(suite.getSuiteId(), dingTalkEncryptor); } } // encrypt String plainText = dingTalkEncryptor.getDecryptMsg(msgSignature, timeStamp, nonce, encryptStr); // encrypt????eventType???? JSONObject plainTextJson = JSONObject.parseObject(plainText); String eventType = plainTextJson.getString("EventType"); logger.info("({})?{}", sid, eventType); switch (eventType) { case "suite_ticket": // (??)?Ticket doSuccessResponse(dingTalkEncryptor, response, "success", msgSignature, timeStamp, nonce); doSuiteTicket(sid, plainTextJson); break; case "tmp_auth_code": // ??? doSuccessResponse(dingTalkEncryptor, response, "success", msgSignature, timeStamp, nonce); doTmpAuthCode(sid, plainTextJson); break; case "change_auth": // ???? doSuccessResponse(dingTalkEncryptor, response, "success", msgSignature, timeStamp, nonce); doChangeAuth(sid, plainTextJson); break; case "check_create_suite_url": // ?URL doSuccessResponse(dingTalkEncryptor, response, plainTextJson.getString("Random"), msgSignature, timeStamp, nonce); break; case "check_update_suite_url": // "?"API doSuccessResponse(dingTalkEncryptor, response, plainTextJson.getString("Random"), msgSignature, timeStamp, nonce); break; case "suite_relieve": // "?" doSuccessResponse(dingTalkEncryptor, response, "success", msgSignature, timeStamp, nonce); doSuiteRelieve(sid, plainTextJson); break; case "check_suite_license_code": // "??""success",?? ??? boolean isValid = doCheckSuiteLicenseCode(plainTextJson); if (isValid) { doSuccessResponse(dingTalkEncryptor, response, "success", msgSignature, timeStamp, nonce); } break; default: break; } } catch (Exception e) { logger.error("?{}", e); } }
From source file:com.legstar.c2ws.servlet.C2wsProxy.java
/** {@inheritDoc} */ protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { long startTime = System.currentTimeMillis(); /* Use correlation id received in http header. This allows logs on * this side to be easily correlated with the mainframe logs. */ String requestID = request.getHeader(CORRELATION_ID_HDR); if (LOG.isDebugEnabled()) { LOG.debug("Start proxy request " + requestID + " from client " + request.getRemoteHost()); }/* ww w.jav a2 s .c o m*/ /* Make sure this is a Mainframe LegStar request. */ if (!isSupportedContentType(request)) { throw new ServletException("Content type " + request.getContentType() + " is not supported"); } try { /* Get all the bytes from the request in a byte array */ int requestBytesLen = request.getContentLength(); byte[] requestBytes = new byte[requestBytesLen]; InputStream in = request.getInputStream(); int offset = 0; int n; do { n = in.read(requestBytes, offset, requestBytesLen - offset); } while (n != -1); if (LOG.isDebugEnabled()) { LOG.debug("Request data from host:"); traceData(requestID, requestBytes, LOG); } /* Call the proxy getting a byte array back */ byte[] replyBytes = getServiceProxy().invoke(requestID, requestBytes); if (LOG.isDebugEnabled()) { LOG.debug("Reply data to host:"); traceData(requestID, replyBytes, LOG); } /* Push the reply byte array into the http response */ response.setContentType(request.getContentType()); response.getOutputStream().write(replyBytes); } catch (IOException e) { throw (new ServletException(e)); } catch (ProxyInvokerException e) { throw (new ServletException(e)); } long endTime = System.currentTimeMillis(); if (LOG.isDebugEnabled()) { LOG.debug("End proxy request " + requestID + " from client " + request.getRemoteHost() + " serviced in " + (endTime - startTime) + " msecs"); } }
From source file:com.erudika.para.rest.Signer.java
private Request<?> buildAWSRequest(HttpServletRequest req, Set<String> headersUsed) { Map<String, String> headers = new HashMap<String, String>(); for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements();) { String head = e.nextElement().toLowerCase(); if (headersUsed.contains(head)) { headers.put(head, req.getHeader(head)); }/*from w ww . j a va 2s . c o m*/ } Map<String, String> params = new HashMap<String, String>(); for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) { params.put(param.getKey(), param.getValue()[0]); } String path = req.getRequestURI(); String endpoint = StringUtils.removeEndIgnoreCase(req.getRequestURL().toString(), path); String httpMethod = req.getMethod(); InputStream entity; try { entity = new BufferedInputStream(req.getInputStream()); if (entity.available() <= 0) { entity = null; } } catch (IOException ex) { logger.error(null, ex); entity = null; } return buildAWSRequest(httpMethod, endpoint, path, headers, params, entity); }
From source file:com.github.restdriver.clientdriver.HttpRealRequest.java
public HttpRealRequest(HttpServletRequest request) { this.path = request.getPathInfo(); this.method = Method.custom(request.getMethod().toUpperCase()); this.params = HashMultimap.create(); if (request.getQueryString() != null) { MultiMap<String> parameterMap = new MultiMap<String>(); UrlEncoded.decodeTo(request.getQueryString(), parameterMap, "UTF-8", 0); for (Entry<String, String[]> paramEntry : parameterMap.toStringArrayMap().entrySet()) { String[] values = paramEntry.getValue(); for (String value : values) { this.params.put(paramEntry.getKey(), value); }//from ww w . j a va2s . c om } } headers = new HashMap<String, Object>(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); headers.put(headerName.toLowerCase(), request.getHeader(headerName)); } } try { this.bodyContent = IOUtils.toByteArray(request.getInputStream()); } catch (IOException e) { throw new RuntimeException("Failed to read body of request", e); } this.bodyContentType = request.getContentType(); }