org.eclipse.jetty.http.MimeTypes Java Examples
The following examples show how to use
org.eclipse.jetty.http.MimeTypes.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebServerTestCase.java From htmlunit with Apache License 2.0 | 6 votes |
/** * Starts the web server on the default {@link #PORT}. * The given resourceBase is used to be the ROOT directory that serves the default context. * <p><b>Don't forget to stop the returned HttpServer after the test</b> * * @param resourceBase the base of resources for the default context * @throws Exception if the test fails */ protected void startWebServer(final String resourceBase) throws Exception { if (server_ != null) { throw new IllegalStateException("startWebServer() can not be called twice"); } final Server server = buildServer(PORT); final WebAppContext context = new WebAppContext(); context.setContextPath("/"); context.setResourceBase(resourceBase); final ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setResourceBase(resourceBase); final MimeTypes mimeTypes = new MimeTypes(); mimeTypes.addMimeMapping("js", MimeType.APPLICATION_JAVASCRIPT); resourceHandler.setMimeTypes(mimeTypes); final HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[]{resourceHandler, context}); server.setHandler(handlers); server.setHandler(resourceHandler); tryStart(PORT, server); server_ = server; }
Example #2
Source File: AssetServlet.java From dropwizard-configurable-assets-bundle with Apache License 2.0 | 6 votes |
/** * Creates a new {@code AssetServlet} that serves static assets loaded from {@code resourceURL} * (typically a file: or jar: URL). The assets are served at URIs rooted at {@code uriPath}. For * example, given a {@code resourceURL} of {@code "file:/data/assets"} and a {@code uriPath} of * {@code "/js"}, an {@code AssetServlet} would serve the contents of {@code * /data/assets/example.js} in response to a request for {@code /js/example.js}. If a directory * is requested and {@code indexFile} is defined, then {@code AssetServlet} will attempt to * serve a file with that name in that directory. If a directory is requested and {@code * indexFile} is null, it will serve a 404. * * @param resourcePathToUriPathMapping A mapping from base URL's from which assets are loaded to * the URI path fragment in which the requests for that asset * are rooted * @param indexFile the filename to use when directories are requested, or null * to serve no indexes * @param defaultCharset the default character set * @param spec the CacheBuilderSpec to use * @param overrides the path overrides * @param mimeTypes the mimeType overrides */ public AssetServlet(Iterable<Map.Entry<String, String>> resourcePathToUriPathMapping, String indexFile, Charset defaultCharset, CacheBuilderSpec spec, Iterable<Map.Entry<String, String>> overrides, Iterable<Map.Entry<String, String>> mimeTypes) { this.defaultCharset = defaultCharset; AssetLoader loader = new AssetLoader(resourcePathToUriPathMapping, indexFile, overrides); CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.from(spec); // Don't add the weigher if we are using maximumSize instead of maximumWeight. if (spec.toParsableString().contains("maximumWeight=")) { cacheBuilder.weigher(new AssetSizeWeigher()); } this.cache = cacheBuilder.build(loader); this.cacheSpec = spec; this.mimeTypes = new MimeTypes(); this.setMimeTypes(mimeTypes); }
Example #3
Source File: ServletResponseController.java From vespa with Apache License 2.0 | 6 votes |
/** * Async version of {@link org.eclipse.jetty.server.Response#sendError(int, String)}. */ private void sendErrorAsync(int statusCode, String reasonPhrase) { servletResponse.setHeader(HttpHeaders.Names.EXPIRES, null); servletResponse.setHeader(HttpHeaders.Names.LAST_MODIFIED, null); servletResponse.setHeader(HttpHeaders.Names.CACHE_CONTROL, null); servletResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, null); servletResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, null); setStatus(servletResponse, statusCode, Optional.of(reasonPhrase)); // If we are allowed to have a body if (statusCode != HttpServletResponse.SC_NO_CONTENT && statusCode != HttpServletResponse.SC_NOT_MODIFIED && statusCode != HttpServletResponse.SC_PARTIAL_CONTENT && statusCode >= HttpServletResponse.SC_OK) { servletResponse.setHeader(HttpHeaders.Names.CACHE_CONTROL, "must-revalidate,no-cache,no-store"); servletResponse.setContentType(MimeTypes.Type.TEXT_HTML_8859_1.toString()); byte[] errorContent = errorResponseContentCreator .createErrorContent(servletRequest.getRequestURI(), statusCode, Optional.ofNullable(reasonPhrase)); servletResponse.setContentLength(errorContent.length); servletOutputStreamWriter.sendErrorContentAndCloseAsync(ByteBuffer.wrap(errorContent)); } else { servletResponse.setContentLength(0); servletOutputStreamWriter.close(); } }
Example #4
Source File: PatchLogServer.java From rdf-delta with Apache License 2.0 | 6 votes |
/** Build a ServletContextHandler. */ private static ServletContextHandler buildServletContext(String contextPath) { if ( contextPath == null || contextPath.isEmpty() ) contextPath = "/"; else if ( !contextPath.startsWith("/") ) contextPath = "/" + contextPath; ServletContextHandler context = new ServletContextHandler(); context.setDisplayName("PatchLogServer"); MimeTypes mt = new MimeTypes(); addMimeType(mt, Lang.TTL); addMimeType(mt, Lang.NT); addMimeType(mt, Lang.TRIG); addMimeType(mt, Lang.NQ); addMimeType(mt, Lang.RDFXML); context.setMimeTypes(mt); ErrorHandler eh = new HttpErrorHandler(); context.setErrorHandler(eh); return context; }
Example #5
Source File: SSOCookieFederationFilter.java From knox with Apache License 2.0 | 6 votes |
@Override protected void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status, String error) throws IOException { /* We don't need redirect if this is a XHR request */ if (request.getHeader(XHR_HEADER) != null && request.getHeader(XHR_HEADER).equalsIgnoreCase(XHR_VALUE)) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType(MimeTypes.Type.TEXT_PLAIN.toString()); if(error != null && !error.isEmpty()) { final byte[] data = error.getBytes(StandardCharsets.UTF_8); response.setContentLength(data.length); response.getOutputStream().write(data); } } else { String loginURL = constructLoginURL(request); response.sendRedirect(loginURL); } }
Example #6
Source File: AddInServlet.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); if (!req.getPathInfo().startsWith(API_PATH)) { try (InputStream inputStream = AddInServlet.class.getResourceAsStream(RESOURCE_PATH + req.getPathInfo());) { if (inputStream != null) { if (MANIFEST_PATH.equals(req.getPathInfo())) { getManifest(M2DocUtils.VERSION, req.getServerName(), req.getServerPort(), inputStream, resp); } else { resp.setContentType(URLConnection.guessContentTypeFromName(req.getPathInfo())); try (ServletOutputStream outputStream = resp.getOutputStream();) { IOUtils.copy(inputStream, outputStream); } resp.setStatus(HttpServletResponse.SC_OK); } } else { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.setContentType(MimeTypes.Type.TEXT_HTML.toString()); resp.getWriter().print("<h1>404<h1>"); } } } else { doRestAPI(req, resp); } }
Example #7
Source File: WandoraWebAppServer.java From wandora with GNU General Public License v3.0 | 6 votes |
public WandoraWebAppServer(Wandora wandora){ this.wandora=wandora; jettyServer=new Server(); Options options=wandora.getOptions(); readOptions(options); requestHandler=new JettyHandler(); mimeTypes=new MimeTypes(); webApps=new HashMap<String,WandoraWebApp>(); ArrayList<WandoraWebApp> apps=scanWebApps(); for(WandoraWebApp app : apps){ webApps.put(app.getName(),app); } }
Example #8
Source File: JettyAppServer.java From selenium with Apache License 2.0 | 6 votes |
protected ServletContextHandler addResourceHandler(String contextPath, Path resourceBase) { ServletContextHandler context = new ServletContextHandler(); ResourceHandler staticResource = new ResourceHandler(); staticResource.setDirectoriesListed(true); staticResource.setWelcomeFiles(new String[] { "index.html" }); staticResource.setResourceBase(resourceBase.toAbsolutePath().toString()); MimeTypes mimeTypes = new MimeTypes(); mimeTypes.addMimeMapping("appcache", "text/cache-manifest"); staticResource.setMimeTypes(mimeTypes); context.setContextPath(contextPath); context.setAliasChecks(Arrays.asList(new ApproveAliases(), new AllowSymLinkAliasChecker())); HandlerList allHandlers = new HandlerList(); allHandlers.addHandler(staticResource); allHandlers.addHandler(context.getHandler()); context.setHandler(allHandlers); handlers.addHandler(context); return context; }
Example #9
Source File: WandoraJettyServer.java From wandora with GNU General Public License v3.0 | 5 votes |
public WandoraJettyServer(Wandora wandora){ this.wandora=wandora; Options options=wandora.getOptions(); readOptions(options); requestHandler=new JettyHandler(); mimeTypes=new MimeTypes(); extractorManager=new BrowserExtractorManager(wandora); }
Example #10
Source File: GerritRestClientTest.java From gerrit-rest-java-client with Apache License 2.0 | 5 votes |
public String startJetty(Class<? extends HttpServlet> loginServletClass) throws Exception { Server server = new Server(0); ResourceHandler resourceHandler = new ResourceHandler(); MimeTypes mimeTypes = new MimeTypes(); mimeTypes.addMimeMapping("json", "application/json"); resourceHandler.setMimeTypes(mimeTypes); URL url = this.getClass().getResource("."); resourceHandler.setBaseResource(new FileResource(url)); resourceHandler.setWelcomeFiles(new String[] {"changes.json", "projects.json", "account.json"}); ServletContextHandler servletContextHandler = new ServletContextHandler(); servletContextHandler.addServlet(loginServletClass, "/login/"); ServletContextHandler basicAuthContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY); basicAuthContextHandler.setSecurityHandler(basicAuth("foo", "bar", "Gerrit Auth")); basicAuthContextHandler.setContextPath("/a"); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] { servletContextHandler, resourceHandler, basicAuthContextHandler }); server.setHandler(handlers); server.start(); Connector connector = server.getConnectors()[0]; String host = "localhost"; int port = connector.getLocalPort(); return String.format("http://%s:%s", host, port); }
Example #11
Source File: BaseServlet.java From PeerWasp with MIT License | 5 votes |
protected void sendErrorMessage(HttpServletResponse resp, ServerReturnMessage msg) throws IOException { resp.setContentType(MimeTypes.Type.APPLICATION_JSON.asString()); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); Gson gson = new Gson(); String response = gson.toJson(msg); resp.getWriter().println(response); logger.error("Request failed: {} (Code {})", msg.getMessage(), msg.getCode()); }
Example #12
Source File: BaseServlet.java From PeerWasp with MIT License | 5 votes |
protected boolean checkContentTypeJSON(HttpServletRequest req, HttpServletResponse resp) throws IOException { // check content type: json if (req.getContentType() == null || !req.getContentType().contains(MimeTypes.Type.APPLICATION_JSON.asString())) { return false; } return true; }
Example #13
Source File: WandoraModulesServer.java From wandora with GNU General Public License v3.0 | 5 votes |
public WandoraModulesServer(Wandora wandora){ this.wandora = wandora; jettyServer = new Server(); rootLog = new Jdk14Logger("ModulesServlet"); log = rootLog; Options options = wandora.getOptions(); readOptions(options); mimeTypes = new MimeTypes(); initModuleManager(); readBundleDirectories(); }
Example #14
Source File: TestSupport.java From p3-batchrefine with Apache License 2.0 | 5 votes |
private int startTransformServer() throws Exception { URL transforms = EngineTest.class.getClassLoader().getResource( "transforms"); if (transforms == null) { Assert.fail(); } int port = findFreePort(); Server fileServer = new Server(port); ResourceHandler handler = new ResourceHandler(); MimeTypes mimeTypes = handler.getMimeTypes(); mimeTypes.addMimeMapping("json", "application/json; charset=UTF-8"); handler.setDirectoriesListed(true); handler.setBaseResource(JarResource.newResource(transforms)); HandlerList handlers = new HandlerList(); handlers.addHandler(handler); handlers.addHandler(new DefaultHandler()); fileServer.setHandler(handlers); fileServer.start(); return port; }
Example #15
Source File: BatchRefineTransformer.java From p3-batchrefine with Apache License 2.0 | 5 votes |
protected JSONArray fetchTransform(HttpRequestEntity request) throws IOException { String transformURI = getSingleParameter(TRANSFORM_PARAMETER, request.getRequest()); CloseableHttpClient client = null; CloseableHttpResponse response = null; try { HttpGet get = new HttpGet(transformURI); get.addHeader("Accept", "application/json"); client = HttpClients.createDefault(); response = performRequest(get, client); HttpEntity responseEntity = response.getEntity(); if (responseEntity == null) { // TODO proper error reporting throw new IOException("Could not GET transform JSON from " + transformURI + "."); } String encoding = null; if (responseEntity.getContentType() != null) { encoding = MimeTypes.getCharsetFromContentType(responseEntity.getContentType().getValue()); } String transform = IOUtils.toString(responseEntity.getContent(), encoding == null ? "UTF-8" : encoding); return ParsingUtilities.evaluateJsonStringToArray(transform); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(client); } }
Example #16
Source File: AssetServletTest.java From dropwizard-configurable-assets-bundle with Apache License 2.0 | 5 votes |
@Test public void defaultsToHtml() throws Exception { response = makeRequest(DUMMY_SERVLET + "foo.bar"); assertThat(response.getStatus()) .isEqualTo(200); assertThat(MimeTypes.CACHE.get(response.get(HttpHeader.CONTENT_TYPE))) .isEqualTo(MimeTypes.Type.TEXT_HTML_UTF_8); }
Example #17
Source File: PlaintextServlet.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletResponse response= (HttpServletResponse)res; response.setContentType(MimeTypes.Type.TEXT_PLAIN.asString()); response.getOutputStream().write(helloWorld); }
Example #18
Source File: AssetServletTest.java From dropwizard-configurable-assets-bundle with Apache License 2.0 | 5 votes |
@Test public void guessesMimeTypes() throws Exception { response = makeRequest(); assertThat(response.getStatus()) .isEqualTo(200); assertThat(MimeTypes.CACHE.get(response.get(HttpHeader.CONTENT_TYPE))) .isEqualTo(MimeTypes.Type.TEXT_PLAIN_UTF_8); }
Example #19
Source File: AssetServletTest.java From dropwizard-configurable-assets-bundle with Apache License 2.0 | 5 votes |
@Test public void servesCharset() throws Exception { response = makeRequest(DUMMY_SERVLET + "example.txt"); assertThat(response.getStatus()) .isEqualTo(200); assertThat(MimeTypes.CACHE.get(response.get(HttpHeader.CONTENT_TYPE))) .isEqualTo(MimeTypes.Type.TEXT_PLAIN_UTF_8); response = makeRequest(NOCHARSET_SERVLET + "example.txt"); assertThat(response.getStatus()) .isEqualTo(200); assertThat(response.get(HttpHeader.CONTENT_TYPE)) .isEqualTo(MimeTypes.Type.TEXT_PLAIN.toString()); }
Example #20
Source File: Response.java From onedev with MIT License | 5 votes |
@Override public String getCharacterEncoding() { if (_characterEncoding == null) { String encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType); if (encoding != null) return encoding; encoding = MimeTypes.getCharsetInferredFromContentType(_contentType); if (encoding != null) return encoding; return StringUtil.__ISO_8859_1; } return _characterEncoding; }
Example #21
Source File: DataExtractor.java From waltz with Apache License 2.0 | 5 votes |
default Object writeReportResults(Response response, Tuple3<ExtractFormat, String, byte[]> reportResult) throws IOException { String templateName = reportResult.v2; HttpServletResponse httpResponse = response.raw(); switch (reportResult.v1) { case XLSX: httpResponse.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); httpResponse.setHeader("Content-Disposition", "attachment; filename=" + templateName + ".xlsx"); httpResponse.setHeader("Content-Transfer-Encoding", "7bit"); break; case CSV: response.type(MimeTypes.Type.TEXT_PLAIN.name()); response.header("Content-disposition", "attachment; filename=" + templateName + ".csv"); break; default: break; } byte[] bytes = reportResult.v3; httpResponse.setContentLength(bytes.length); httpResponse.getOutputStream().write(bytes); httpResponse.getOutputStream().flush(); httpResponse.getOutputStream().close(); return httpResponse; }
Example #22
Source File: DirectQueryBasedDataExtractor.java From waltz with Apache License 2.0 | 5 votes |
private Object writeAsCSV(String suggestedFilenameStem, Select<?> qry, Response response) { String csv = qry.fetch().formatCSV(); response.type(MimeTypes.Type.TEXT_PLAIN.name()); response.header("Content-disposition", "attachment; filename=" + suggestedFilenameStem + ".csv"); return csv; }
Example #23
Source File: AddInServlet.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * Gets the evaluation in a HTML format. * * @param queryEnvironment * the {@link IReadOnlyQueryEnvironment} * @param uriConverter * the {@link URIConverter} * @param templateURI * the template {@link URI} * @param variables * the declared variable values * @param req * the {@link HttpServletRequest} * @param resp * the {@link HttpServletResponse} * @throws IOException * if the response can't be written */ private void getEvaluation(IReadOnlyQueryEnvironment queryEnvironment, URIConverter uriConverter, URI templateURI, Map<String, Object> variables, HttpServletRequest req, HttpServletResponse resp) throws IOException { final String expression = req.getParameter(EXPRESSION_PARAMETER); if (expression != null) { try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(uriConverter, templateURI)) { final QueryEvaluationEngine engine = new QueryEvaluationEngine((IQueryEnvironment) queryEnvironment); final Map<String, Object> allVariables = new HashMap<>(variables); allVariables .putAll(parseVariableValues(queryEnvironment, engine, allVariables, uriConverter, templateURI)); final IQueryBuilderEngine builder = new QueryBuilderEngine(queryEnvironment); final AstResult build = builder.build(expression); final EvaluationResult result = engine.eval(build, allVariables); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(MimeTypes.Type.TEXT_HTML_UTF_8.toString()); resp.getWriter().print(HTML_SERIALIZER.serialize(result.getResult())); } catch (IOException e) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.toString()); resp.getWriter().print(String.format(CAN_T_LOAD_TEMPLATE, e.getMessage())); } } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.toString()); resp.getWriter().print(String.format(PARAMETER_IS_MANDATORY, EXPRESSION_PARAMETER)); } }
Example #24
Source File: AddInServlet.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * Gets the validation. * * @param queryEnvironment * the {@link IReadOnlyQueryEnvironment} * @param uriConverter * the {@link URIConverter} * @param templateURI * the template {@link URI} * @param req * the {@link HttpServletRequest} * @param resp * the {@link HttpServletResponse} * @throws IOException * if the response can't be written */ private void getValidation(IReadOnlyQueryEnvironment queryEnvironment, URIConverter uriConverter, URI templateURI, HttpServletRequest req, HttpServletResponse resp) throws IOException { final String expression = req.getParameter(EXPRESSION_PARAMETER); if (expression != null) { try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(uriConverter, templateURI)) { final TemplateCustomProperties properties = new TemplateCustomProperties(document); final AstValidator validator = new AstValidator(new ValidationServices(queryEnvironment)); final Map<String, Set<IType>> variableTypes = properties.getVariableTypes(validator, queryEnvironment); variableTypes.putAll( parseVariableTypes(queryEnvironment, validator, variableTypes, uriConverter, templateURI)); IQueryValidationEngine engine = new QueryValidationEngine(queryEnvironment); final IValidationResult result = engine.validate(expression, variableTypes); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(MimeTypes.Type.APPLICATION_JSON_UTF_8.toString()); final List<Map<String, Object>> messages = new ArrayList<>(); for (IValidationMessage message : result.getMessages()) { final Map<String, Object> map = new HashMap<>(); messages.add(map); map.put("level", message.getLevel()); map.put("start", message.getStartPosition()); map.put("end", message.getEndPosition()); map.put("message", message.getMessage()); } resp.getWriter().print(JSON.toString(messages)); } catch (IOException e) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.toString()); resp.getWriter().print(String.format(CAN_T_LOAD_TEMPLATE, e.getMessage())); } } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.toString()); resp.getWriter().print(String.format(PARAMETER_IS_MANDATORY, EXPRESSION_PARAMETER)); } }
Example #25
Source File: GoServerLoadingIndicationHandler.java From gocd with Apache License 2.0 | 4 votes |
private String acceptHeaderValue(Request baseRequest) { List<String> qualityCSV = baseRequest.getHttpFields().getQualityCSV(HttpHeader.ACCEPT); return qualityCSV.isEmpty() ? MimeTypes.Type.TEXT_HTML.asString() : qualityCSV.get(0); }
Example #26
Source File: AssetServlet.java From dropwizard-configurable-assets-bundle with Apache License 2.0 | 4 votes |
public MimeTypes getMimeTypes() { return mimeTypes; }
Example #27
Source File: Response.java From onedev with MIT License | 4 votes |
@Override public PrintWriter getWriter() throws IOException { if (_outputType == OutputType.STREAM) throw new IllegalStateException("STREAM"); if (_outputType == OutputType.NONE) { /* get encoding from Content-Type header */ String encoding = _characterEncoding; if (encoding == null) { if (_mimeType != null && _mimeType.isCharsetAssumed()) encoding = _mimeType.getCharsetString(); else { encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType); if (encoding == null) { encoding = MimeTypes.getCharsetInferredFromContentType(_contentType); if (encoding == null) encoding = StringUtil.__ISO_8859_1; setCharacterEncoding(encoding, EncodingFrom.INFERRED); } } } Locale locale = getLocale(); if (_writer != null && _writer.isFor(locale, encoding)) _writer.reopen(); else { if (StringUtil.__ISO_8859_1.equalsIgnoreCase(encoding)) _writer = new ResponseWriter(new Iso88591HttpWriter(_out), locale, encoding); else if (StringUtil.__UTF8.equalsIgnoreCase(encoding)) _writer = new ResponseWriter(new Utf8HttpWriter(_out), locale, encoding); else _writer = new ResponseWriter(new EncodingHttpWriter(_out, encoding), locale, encoding); } // Set the output type at the end, because setCharacterEncoding() checks for it _outputType = OutputType.WRITER; } return _writer; }
Example #28
Source File: Response.java From onedev with MIT License | 4 votes |
private void setCharacterEncoding(String encoding, EncodingFrom from) { if (!isMutable() || isWriting()) return; if (_outputType != OutputType.WRITER && !isCommitted()) { if (encoding == null) { _encodingFrom = EncodingFrom.NOT_SET; // Clear any encoding. if (_characterEncoding != null) { _characterEncoding = null; if (_mimeType != null) { _mimeType = _mimeType.getBaseType(); _contentType = _mimeType.asString(); _fields.put(_mimeType.getContentTypeField()); } else if (_contentType != null) { _contentType = MimeTypes.getContentTypeWithoutCharset(_contentType); _fields.put(HttpHeader.CONTENT_TYPE, _contentType); } } } else { // No, so just add this one to the mimetype _encodingFrom = from; _characterEncoding = HttpGenerator.__STRICT ? encoding : StringUtil.normalizeCharset(encoding); if (_mimeType != null) { _contentType = _mimeType.getBaseType().asString() + ";charset=" + _characterEncoding; _mimeType = MimeTypes.CACHE.get(_contentType); if (_mimeType == null || HttpGenerator.__STRICT) _fields.put(HttpHeader.CONTENT_TYPE, _contentType); else _fields.put(_mimeType.getContentTypeField()); } else if (_contentType != null) { _contentType = MimeTypes.getContentTypeWithoutCharset(_contentType) + ";charset=" + _characterEncoding; _fields.put(HttpHeader.CONTENT_TYPE, _contentType); } } } }
Example #29
Source File: Response.java From onedev with MIT License | 4 votes |
@Override public void setContentType(String contentType) { if (isCommitted() || !isMutable()) return; if (contentType == null) { if (isWriting() && _characterEncoding != null) throw new IllegalSelectorException(); if (_locale == null) _characterEncoding = null; _mimeType = null; _contentType = null; _fields.remove(HttpHeader.CONTENT_TYPE); } else { _contentType = contentType; _mimeType = MimeTypes.CACHE.get(contentType); String charset; if (_mimeType != null && _mimeType.getCharset() != null && !_mimeType.isCharsetAssumed()) charset = _mimeType.getCharsetString(); else charset = MimeTypes.getCharsetFromContentType(contentType); if (charset == null) { switch (_encodingFrom) { case NOT_SET: break; case INFERRED: case SET_CONTENT_TYPE: if (isWriting()) { _mimeType = null; _contentType = _contentType + ";charset=" + _characterEncoding; } else { _encodingFrom = EncodingFrom.NOT_SET; _characterEncoding = null; } break; case SET_LOCALE: case SET_CHARACTER_ENCODING: { _contentType = contentType + ";charset=" + _characterEncoding; _mimeType = null; } } } else if (isWriting() && !charset.equalsIgnoreCase(_characterEncoding)) { // too late to change the character encoding; _mimeType = null; _contentType = MimeTypes.getContentTypeWithoutCharset(_contentType); if (_characterEncoding != null) _contentType = _contentType + ";charset=" + _characterEncoding; } else { _characterEncoding = charset; _encodingFrom = EncodingFrom.SET_CONTENT_TYPE; } if (HttpGenerator.__STRICT || _mimeType == null) _fields.put(HttpHeader.CONTENT_TYPE, _contentType); else { _contentType = _mimeType.asString(); _fields.put(_mimeType.getContentTypeField()); } } }
Example #30
Source File: Response.java From onedev with MIT License | 4 votes |
public void putHeaders(HttpContent content, long contentLength, boolean etag) { HttpField lm = content.getLastModified(); if (lm != null) _fields.put(lm); if (contentLength == 0) { _fields.put(content.getContentLength()); _contentLength = content.getContentLengthValue(); } else if (contentLength > 0) { _fields.putLongField(HttpHeader.CONTENT_LENGTH, contentLength); _contentLength = contentLength; } HttpField ct = content.getContentType(); if (ct != null) { if (_characterEncoding != null && content.getCharacterEncoding() == null && content.getContentTypeValue() != null && __explicitCharset.contains(_encodingFrom)) { setContentType(MimeTypes.getContentTypeWithoutCharset(content.getContentTypeValue())); } else { _fields.put(ct); _contentType = ct.getValue(); _characterEncoding = content.getCharacterEncoding(); _mimeType = content.getMimeType(); } } HttpField ce = content.getContentEncoding(); if (ce != null) _fields.put(ce); if (etag) { HttpField et = content.getETag(); if (et != null) _fields.put(et); } }