List of usage examples for javax.servlet.http HttpServletRequest getContentType
public String getContentType();
null
if the type is not known. From source file:org.eclipse.lyo.samples.sharepoint.adapter.ResourceCreatorService.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String title = request.getParameter("title"); //$NON-NLS-1$ String description = request.getParameter("description"); //$NON-NLS-1$ String filename = request.getParameter("file"); String collection = request.getParameter("collection"); //"Empire"; try {/* www.j a va 2 s.com*/ boolean isFileUpload = ServletFileUpload.isMultipartContent(request); String contentType = request.getContentType(); if (!isFileUpload && !IConstants.CT_RDF_XML.equals(contentType)) { throw new ShareServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE); } InputStream content = request.getInputStream(); if (isFileUpload) { // being uploaded from a web page try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); // find the first (and only) file resource in the post Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { // this is a form field, maybe we can accept a title or descr? } else { final SharepointConnector sc = SharepointInitializer.getSharepointConnector(); int rc = sc.createDocument(response, collection, item); //String content = compactDocument(resource); //System.out.println(content); //response.setContentType(IConstants.CT_OSLC_COMPACT); //response.setContentLength(content.getBytes().length); //response.setStatus(IConstants.SC_OK); //response.getWriter().write(content); //Get Response? //jsonResults.append( "\n] \n}" ); //$NON-NLS-1$ //response.setContentType(IConstants.CT_XML); //response.getWriter().write(is.toString()); //response.setStatus(IConstants.SC_OK); // all that may need to be done is to send a POST // to Sharepoint, with stream content, Slug set and content_type // slug = /Empire/name.doc //response.setHeader(IConstants.HDR_SLUG, "/Empire" + filename); //response.setHeader(IConstants.HDR_CONTENT_TYPE, contentType); //response.sendRedirect(response.encodeRedirectURL(SharepointInitializer.getSharepointUri() + "/Empire")); //RequestDispatcher rd = request.getRequestDispatcher(SharepointInitializer.getSharepointUri() + "/Empire"); //rd.forward(request, response); //response.setStatus(IConstants.SC_CREATED); //response.setHeader(IConstants.HDR_LOCATION, uri); //RequestDispatcher rd = request.getRequestDispatcher("/resource/Empire/5"); //$NON-NLS-1$ //rd.forward(request, response); } } } catch (Exception e) { throw new ShareServiceException(e); } } } catch (Exception e) { throw new ShareServiceException(e); } }
From source file:org.openehealth.ipf.platform.camel.lbs.http.process.AbstractLbsHttpTest.java
@Test public void testFileWithoutResourceExtract() throws Exception { PostMethod method = new PostMethod(ENDPOINT_NO_EXTRACT); method.setRequestEntity(new FileRequestEntity(file, "unknown/unknown")); mock.expectedMessageCount(1);/*w w w.j a va2 s . c o m*/ mock.whenAnyExchangeReceived(new Processor() { @Override public void process(Exchange received) throws Exception { // Must be done in here because the connection is only valid during // processing HttpServletRequest request = received.getIn().getBody(HttpServletRequest.class); assertNotNull(request); assertEquals("unknown/unknown", request.getContentType()); String body = received.getIn().getBody(String.class); assertEquals("blu bla", body); } }); httpClient.executeMethod(method); method.releaseConnection(); mock.assertIsSatisfied(); }
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 ww. j a v a 2 s. co 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:org.encuestame.core.security.CustomAuthenticationEntryPoint.java
/** * *///from w w w .j a v a2 s.c o m @Override public void commence(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException, ServletException { if (authException != null) { // you can check for the spefic exception here and redirect like // this logger.debug("respnse" + response.toString()); logger.debug("respnse" + response.getContentType()); logger.debug("request" + request.toString()); logger.debug("request" + request.getContentType()); //response.sendRedirect("403.html"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String redirectUrl = null; if (useForward) { if (forceHttps && "http".equals(request.getScheme())) { // First redirect the current request to HTTPS. // When that request is received, the forward to the login page // will be used. redirectUrl = buildHttpsRedirectUrlForRequest(httpRequest); } if (redirectUrl == null) { String loginForm = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException); if (logger.isDebugEnabled()) { logger.debug("Server side forward to: " + loginForm); } RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(loginForm); dispatcher.forward(request, response); return; } } else { // redirect to login page. Use https if forceHttps true redirectUrl = buildRedirectUrlToLoginPage(httpRequest, httpResponse, authException); } redirectStrategy.sendRedirect(httpRequest, httpResponse, redirectUrl); }
From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java
@Test public void testPutRequestFormat() throws Exception { HttpServlet servlet = new HttpServlet() { @Override//from w w w. j ava 2s . c o m protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ContentType contentType = ContentType.parse(req.getContentType()); if (!contentType.getMimeType().equals(EtcdClientImpl.FORM_URLENCODED.getMimeType())) { throw new IllegalArgumentException("wrong mime type"); } if (!contentType.getCharset().equals(EtcdClientImpl.FORM_URLENCODED.getCharset())) { throw new IllegalArgumentException("wrong content charset"); } String value = req.getParameter("value"); if (value == null) { throw new IllegalArgumentException("missing value parameter"); } String ttl = req.getParameter("ttl"); if (!"10".equals(ttl)) { throw new IllegalArgumentException("missing ttl parameter"); } res.setStatus(201); res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/action-3.json"))); } }; server1 = startServer(servlet, "/v2/keys/post/test"); buildEtcdClient(serverPort(server1)); KeyResponse response = etcdClient.putKey("/post/test", "test-data", Collections.singletonMap("ttl", "10")); Assert.assertNotNull(response); Assert.assertTrue(response.isAction()); }
From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java
@Test public void testPostRequestFormat() throws Exception { HttpServlet servlet = new HttpServlet() { @Override/* w w w . j a v a2s .co m*/ protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ContentType contentType = ContentType.parse(req.getContentType()); if (!contentType.getMimeType().equals(EtcdClientImpl.FORM_URLENCODED.getMimeType())) { throw new IllegalArgumentException("wrong mime type"); } if (!contentType.getCharset().equals(EtcdClientImpl.FORM_URLENCODED.getCharset())) { throw new IllegalArgumentException("wrong content charset"); } String value = req.getParameter("value"); if (value == null) { throw new IllegalArgumentException("missing value parameter"); } String ttl = req.getParameter("ttl"); if (!"10".equals(ttl)) { throw new IllegalArgumentException("missing ttl parameter"); } res.setStatus(201); res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/action-3.json"))); } }; server1 = startServer(servlet, "/v2/keys/post/test"); buildEtcdClient(serverPort(server1)); KeyResponse response = etcdClient.postKey("/post/test", "test-data", Collections.singletonMap("ttl", "10")); Assert.assertNotNull(response); Assert.assertTrue(response.isAction()); }
From source file:org.apache.solr.servlet.SolrRequestParserTest.java
License:asdf
public HttpServletRequest getMock(String uri, String contentType, int contentLength) { HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getHeader("User-Agent")).andReturn(null).anyTimes(); expect(request.getRequestURI()).andReturn(uri).anyTimes(); expect(request.getContentType()).andReturn(contentType).anyTimes(); expect(request.getContentLength()).andReturn(contentLength).anyTimes(); expect(request.getAttribute(EasyMock.anyObject(String.class))).andReturn(null).anyTimes(); return request; }
From source file:org.accada.epcis.repository.capture.CaptureOperationsServlet.java
/** * Implements the EPCIS capture operation. Takes HTTP POST request, extracts * the payload into an XML document, validates the document against the * EPCIS schema, and captures the EPCIS events given in the document. Errors * are caught and returned as simple plaintext messages via HTTP. * //from ww w . j av a 2 s.c om * @param req * The HttpServletRequest. * @param rsp * The HttpServletResponse. * @throws IOException * If an error occurred while validating the request or writing * the response. */ public void doPost(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { LOG.info("EPCIS Capture Interface invoked."); rsp.setContentType("text/plain"); final PrintWriter out = rsp.getWriter(); InputStream is = null; // check if we have a POST request with form parameters if ("application/x-www-form-urlencoded".equalsIgnoreCase(req.getContentType())) { // check if the 'event' or 'dbReset' form parameter are given String event = req.getParameter("event"); String dbReset = req.getParameter("dbReset"); if (event != null) { LOG.info("Found deprecated 'event=' parameter. Refusing to process request."); String msg = "Starting from version 0.2.2, the EPCIS repository does not accept the EPCISDocument in the HTTP POST form parameter 'event' anymore. Please provide the EPCISDocument as HTTP POST payload instead."; rsp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); out.println(msg); } else if (dbReset != null && dbReset.equalsIgnoreCase("true")) { LOG.debug("Found 'dbReset' parameter set to 'true'."); rsp.setContentType("text/plain"); try { captureOperationsModule.doDbReset(); String msg = "db reset successfull"; LOG.info(msg); rsp.setStatus(HttpServletResponse.SC_OK); out.println(msg); } catch (SQLException e) { String msg = "An error involving the database occurred"; LOG.error(msg, e); rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.println(msg); } catch (IOException e) { String msg = "An unexpected error occurred"; LOG.error(msg, e); rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.println(msg); } catch (UnsupportedOperationException e) { String msg = "'dbReset' operation not allowed!"; LOG.info(msg); rsp.setStatus(HttpServletResponse.SC_FORBIDDEN); out.println(msg); } } out.flush(); out.close(); return; } else { is = req.getInputStream(); try { captureOperationsModule.doCapture(is, req.getUserPrincipal()); rsp.setStatus(HttpServletResponse.SC_OK); out.println("Capture request succeeded."); } catch (SAXException e) { String msg = "An error processing the XML document occurred"; LOG.error(msg, e); rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.println(msg); } catch (InvalidFormatException e) { String msg = "An error parsing the XML contents occurred"; LOG.error(msg, e); rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.println(msg); } catch (final Exception e) { String msg = "An unexpected error occurred"; LOG.error(msg, e); rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.println(msg); } out.flush(); out.close(); } }
From source file:org.apache.solr.servlet.SolrRequestParsers.java
public SolrParams parseParamsAndFillStreams(final HttpServletRequest req, ArrayList<ContentStream> streams) throws Exception { String method = req.getMethod().toUpperCase(Locale.ENGLISH); if ("GET".equals(method) || "HEAD".equals(method)) { return new ServletSolrParams(req); }//from w w w . j a v a 2s .c o m if ("POST".equals(method)) { String contentType = req.getContentType(); if (contentType != null) { int idx = contentType.indexOf(';'); if (idx > 0) { // remove the charset definition "; charset=utf-8" contentType = contentType.substring(0, idx); } if ("application/x-www-form-urlencoded".equals(contentType.toLowerCase(Locale.ENGLISH))) { return new ServletSolrParams(req); // just get the params from parameterMap } if (ServletFileUpload.isMultipartContent(req)) { return multipart.parseParamsAndFillStreams(req, streams); } } return raw.parseParamsAndFillStreams(req, streams); } throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unsupported method: " + method); }