/** * Set the {@link HttpHeaders#CONTENT_TYPE} header to the {@code httpHeaders} based on {@code mediaType} and * {@link #getEncoding() default encoding} defined in this processor. If {@code mediaType} defines encoding * then this encoding will be used otherwise the default processor encoding is used. The chosen encoding * is returned from the method. * * @param mediaType Media type of the entity. * @param httpHeaders Http headers. * @return Selected encoding. */ protected Charset setContentType(final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders) { final Charset encoding; final String charset = mediaType.getParameters().get(MediaType.CHARSET_PARAMETER); final MediaType finalMediaType; if (charset == null) { encoding = getEncoding(); final HashMap<String, String> params = new HashMap<>(mediaType.getParameters()); params.put(MediaType.CHARSET_PARAMETER, encoding.name()); finalMediaType = new MediaType(mediaType.getType(), mediaType.getSubtype(), params); } else { encoding = Charset.forName(charset); finalMediaType = mediaType; } final ArrayList<Object> typeList = new ArrayList<>(1); typeList.add(finalMediaType.toString()); httpHeaders.put(HttpHeaders.CONTENT_TYPE, typeList); return encoding; }
@Override public MediaType getMediaType() { final Object mediaTypeHeader = getHttpHeaders().getFirst(HttpHeaders.CONTENT_TYPE); if (mediaTypeHeader instanceof MediaType) { return (MediaType)mediaTypeHeader; } else if (mediaTypeHeader != null) { return MediaType.valueOf(mediaTypeHeader.toString()); } return null; }
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { final Response.StatusType responseStatus = responseContext.getStatusInfo(); final String requestPath = requestContext.getUriInfo().getAbsolutePath().getPath(); final List<MediaType> acceptableMediaTypes = requestContext.getAcceptableMediaTypes(); final boolean acceptsHtml = acceptableMediaTypes.stream() .anyMatch(mediaType -> mediaType.isCompatible(MediaType.TEXT_HTML_TYPE) || mediaType.isCompatible(MediaType.APPLICATION_XHTML_XML_TYPE)); final boolean isGetRequest = "get".equalsIgnoreCase(requestContext.getMethod()); if (isGetRequest && responseStatus == Response.Status.NOT_FOUND && acceptsHtml && !requestPath.startsWith("/" + HttpConfiguration.PATH_API)) { final String entity = indexHtmlGenerator.get(requestContext.getHeaders()); responseContext.setStatusInfo(Response.Status.OK); responseContext.setEntity(entity, new Annotation[0], MediaType.TEXT_HTML_TYPE); responseContext.getHeaders().putSingle("X-UA-Compatible", "IE=edge"); } } }
private boolean containsType( List<MediaType> mediaTypes, MediaType mediaType ) { for ( MediaType type : mediaTypes ) { if ( mediaType.getType().equals( type.getType() ) && mediaType.getSubtype().equals( type.getSubtype() ) ) { return true; } } return false; }
public static MediaType mediaTypeWithCharsetUtf8( MediaType mediaType ) { Map<String,String> parameters = mediaType.getParameters(); if ( parameters.isEmpty() ) { return new MediaType( mediaType.getType(), mediaType.getSubtype(), CHARSET ); } if ( parameters.containsKey( "charset" ) ) { return mediaType; } Map<String,String> paramsWithCharset = new HashMap<>( parameters ); paramsWithCharset.putAll( CHARSET ); return new MediaType( mediaType.getType(), mediaType.getSubtype(), paramsWithCharset ); }
private static MediaType create(MediaType mt) { return new MediaType(mt.getType(), mt.getSubtype(), Collections.singletonMap(Boundary.BOUNDARY_PARAMETER, Boundary.createBoundary())); }
@GET @Path("/{uri}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @ApiOperation(value = "getDocumentContent: return content of the specified Document") public Response getDocumentContent(@PathParam("uri") String uri, @Context HttpHeaders hh) { DocumentManagement docMgr = getDocManager(); try { Properties props = new Properties(); if (MediaType.APPLICATION_JSON_TYPE.equals(hh.getAcceptableMediaTypes().get(0))) { props.setProperty(pn_document_data_format, df_json); } else if (MediaType.APPLICATION_XML_TYPE.equals(hh.getAcceptableMediaTypes().get(0))) { props.setProperty(pn_document_data_format, df_xml); } DocumentAccessor doc = docMgr.getDocument(uri, props); String content = doc.getContent(); return Response.ok(content).build(); } catch (Exception ex) { logger.error("getDocumentContent.error", ex); throw new WebApplicationException(ex, Status.INTERNAL_SERVER_ERROR); //return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } }
@GET @Produces({"application/hocon", "text/x-java-properties", "text/plain"}) @Path("/v2/tables/{tableName}") @ApiOperation("Displays the configuration of a table") public Response readTableConfiguration(@PathParam("tableName") String tableName, @Context Request request) { TableConfig offlineTableConfig = _resourceManager.getTableConfig(tableName, CommonConstants.Helix.TableType.OFFLINE); TableConfig realtimeTableConfig = _resourceManager.getTableConfig(tableName, CommonConstants.Helix.TableType.REALTIME); Schema tableSchema = _resourceManager.getTableSchema(tableName); if (offlineTableConfig == null && realtimeTableConfig == null) { return Response.status(Response.Status.NOT_FOUND).build(); } CombinedConfig combinedConfig = new CombinedConfig(offlineTableConfig, realtimeTableConfig, tableSchema); String serializedConfig; List<Variant> variants = Variant.mediaTypes(APPLICATION_HOCON, TEXT_JAVA_PROPERTIES, MediaType.TEXT_PLAIN_TYPE).build(); Variant variant = request.selectVariant(variants); if (variant == null) { return Response.notAcceptable(variants).build(); } else if (APPLICATION_HOCON.equals(variant.getMediaType()) || MediaType.TEXT_PLAIN_TYPE .equals(variant.getMediaType())) { serializedConfig = Serializer.serializeToString(combinedConfig); } else if (TEXT_JAVA_PROPERTIES.equals(variant.getMediaType())) { serializedConfig = Serializer.serializeToPropertiesString(combinedConfig); } else { return Response.notAcceptable(variants).build(); } return Response.ok(serializedConfig, variant).header("Content-Disposition", "inline").build(); }
@PUT @Path("{id}") @RequireAdmin public Response createRequest(@PathParam("id") String requestId, Reader content, @Context HttpHeaders headers) throws URISyntaxException{ MediaType type = headers.getMediaType(); try { // remove charset information, since we already have the string representation type = removeCharsetInfo(type); // create or replace if already exists db.setRequestDefinition(Integer.parseInt(requestId), type.toString(), content); return Response.ok().build(); } catch (SQLException e) { log.log(Level.SEVERE, "Unable to create request definition", e); return Response.serverError().build(); } catch( NumberFormatException e ){ log.log(Level.SEVERE, "Unable to parse request id: "+requestId, e); return Response.status(Status.BAD_REQUEST).build(); } }
private Form switchUrlEncoding(final ContainerRequest request, final Form otherForm) { final Set<Map.Entry<String, List<String>>> entries = otherForm.asMap().entrySet(); MultivaluedMap<String, String> formMap = new NullableMultivaluedHashMap<>(); for (Map.Entry<String, List<String>> entry : entries) { final String charsetName = ReaderWriter.getCharset(MediaType.valueOf( request.getHeaderString(HttpHeaders.CONTENT_TYPE))).name(); String key; try { key = decode ? URLDecoder.decode(entry.getKey(), charsetName) : URLEncoder.encode(entry.getKey(), charsetName); for (String value : entry.getValue()) { if (value != null) { formMap.add(key, decode ? URLDecoder.decode(value, charsetName) : URLEncoder.encode(value, charsetName)); } else { formMap.add(key, null); } } } catch (UnsupportedEncodingException uee) { throw new ProcessingException(LocalizationMessages.ERROR_UNSUPPORTED_ENCODING(charsetName, extractor.getName()), uee); } } return new Form(formMap); }
@Authenticated @PUT @Path("my/request/{id}/result") public Response submitResult(@PathParam("id") String requestId, @Context HttpHeaders headers, @Context SecurityContext sec, InputStream content) throws URISyntaxException{ Principal user = (Principal)sec.getUserPrincipal(); MediaType type = headers.getMediaType(); log.info("Result received from node "+user.getNodeId()+": "+type.toString()); int request = Integer.parseInt(requestId); // TODO catch numberformatexception and return error if( !isRequestWritable(request, user.getNodeId()) ){ return Response.status(Status.FORBIDDEN).build(); } try { db.addOrReplaceResult(request, user.getNodeId(), type, content); } catch (SQLException e) { log.log(Level.SEVERE, "Unable to persist data", e); return Response.serverError().build(); } return Response.noContent().build(); }
/** * Get a single index configuration (as stored in zookeeper). */ @GET @Path("{name}/config") @Produces("application/json") public Response getConfig(@PathParam("name") String name) throws IndexerNotFoundException, IOException { IndexerDefinition index = getModel().getIndexer(name); ObjectMapper m = new ObjectMapper(); ObjectNode json = m.createObjectNode(); json.put("occVersion", index.getOccVersion()); json.put("config", new String(index.getConfiguration(), Charsets.UTF_8)); return Response.ok(m.writeValueAsString(json), new MediaType("application", "json")).build(); }
@Produces({MediaTypes.WADL_STRING, MediaTypes.WADL_JSON_STRING, "application/xml"}) @GET public synchronized Response getWadl( @Context Request request, @Context UriInfo uriInfo, @Context Providers providers) { if(!wadlContext.isWadlGenerationEnabled()) { return Response.status(Response.Status.NOT_FOUND).build(); Variant v = request.selectVariant(vl); if (v==null) { return Response.notAcceptable(vl).build(); if (applicationDescription == null || ((lastBaseUri != null) && !lastBaseUri.equals(uriInfo.getBaseUri()) && !lastVariant.equals(v))) { this.lastBaseUri = uriInfo.getBaseUri(); this.lastModified = new SimpleDateFormat(HTTPDATEFORMAT).format(new Date()); this.lastVariant = v; if(v.getMediaType().equals(MediaTypes.WADL)) { try { final Marshaller marshaller = wadlContext.getJAXBContext().createMarshaller(); } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not marshal wadl Application.", e); return Response.serverError().build();
@POST @Path("/books") @Produces("text/xml") @Consumes("application/xml") public Response addBook(Book book) { String ct1 = httpHeaders.getMediaType().toString(); String ct2 = httpHeaders.getRequestHeader("Content-Type").get(0); String ct3 = httpHeaders.getRequestHeaders().getFirst("Content-Type"); if (!("application/xml".equals(ct1) && ct1.equals(ct2) && ct1.equals(ct3))) { throw new RuntimeException("Unexpected content type"); } book.setId(bookId + 1); URI uri = ui.getRequestUriBuilder().path(Long.toString(book.getId())).build(); return Response.ok(book).location(uri).build(); }
public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, final MultipartRelatedOutput xopPackage) throws IOException { try { LogMessages.LOGGER.debugf("Provider : %s, Method : writeTo", getClass().getName()); Map<String, String> mediaTypeParameters = new LinkedHashMap<String, String>(); mediaTypeParameters.put("charset", StandardCharsets.UTF_8.name()); mediaTypeParameters.put("type", "text/xml"); MediaType xopRootMediaType = new MediaType("application", "xop+xml", mediaTypeParameters); Marshaller marshaller = getMarshaller(type, annotations, xopRootMediaType); marshaller.setAttachmentMarshaller(new XopAttachmentMarshaller( xopPackage)); ByteArrayOutputStream xml = new ByteArrayOutputStream(); marshaller.marshal(t, xml); OutputPart outputPart = xopPackage.addPart(xml.toByteArray(), xopRootMediaType, ContentIDUtils.generateContentID(), null); List<OutputPart> outputParts = xopPackage.getParts(); outputParts.remove(outputPart); outputParts.add(0, outputPart); } catch (JAXBException e) { Response response = Response.serverError().build(); throw new WebApplicationException(e, response); } }
private MultivaluedMap<String, String> toRequestState(ContainerRequestContext rc) { MultivaluedMap<String, String> requestState = new MetadataMap<>(); requestState.putAll(rc.getUriInfo().getQueryParameters(true)); if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.isCompatible(rc.getMediaType())) { String body = FormUtils.readBody(rc.getEntityStream(), StandardCharsets.UTF_8.name()); FormUtils.populateMapFromString(requestState, JAXRSUtils.getCurrentMessage(), body, StandardCharsets.UTF_8.name(), true); rc.setEntityStream(new ByteArrayInputStream(StringUtils.toBytesUTF8(body))); } return requestState; } public void setRedirectUri(String redirectUri) {
protected MultivaluedMap<String, String> toRequestState(ContainerRequestContext rc, UriInfo ui) { MultivaluedMap<String, String> requestState = new MetadataMap<>(); requestState.putAll(ui.getQueryParameters(decodeRequestParameters)); if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.isCompatible(rc.getMediaType())) { String body = FormUtils.readBody(rc.getEntityStream(), StandardCharsets.UTF_8.name()); FormUtils.populateMapFromString(requestState, JAXRSUtils.getCurrentMessage(), body, StandardCharsets.UTF_8.name(), decodeRequestParameters); } return requestState; }
@SuppressWarnings(value = "unchecked") MultivaluedMap<String, String> formData = (MultivaluedMap<String, String>)data; String charset = mediaType.getParameters().get(MediaType.CHARSET_PARAMETER); if (charset == null) charset = StandardCharsets.UTF_8.name(); for (Map.Entry<String, List<String>> entry : formData.entrySet())
public Match match(List<Match> matches, String httpMethod, HttpRequest request) MediaType contentType = request.getHttpHeaders().getMediaType(); List<MediaType> requestAccepts = request.getHttpHeaders().getAcceptableMediaTypes(); List<WeightedMediaType> weightedAccepts = new ArrayList<WeightedMediaType>(); for (MediaType accept : requestAccepts) weightedAccepts.add(WeightedMediaType.parse(accept)); ResponseBuilder resBuilder = Response.ok(allowHeaderValue.toString(), MediaType.TEXT_PLAIN_TYPE).header(HttpHeaderNames.ALLOW, allowHeaderValue.toString()); else acceptPatch.append(", "); acceptPatch.append(mediaType.toString()); resBuilder.header(HttpHeaderNames.ACCEPT_PATCH, acceptPatch.toString()); throw new DefaultOptionsMethodException(Messages.MESSAGES.noResourceMethodFoundForOptions(), resBuilder.build()); Response res = Response.status(HttpResponseCodes.SC_METHOD_NOT_ALLOWED).header(HttpHeaderNames.ALLOW, allowHeaderValue).build(); throw new NotAllowedException(Messages.MESSAGES.noResourceMethodFoundForHttpMethod(httpMethod), res); if (accept.isCompatible(produce))
@Override public void filter(final ContainerRequestContext request) { if (!request.getMethod().equalsIgnoreCase("POST")) { return; final String header = getParamValue(Source.HEADER, request.getHeaders(), "X-HTTP-Method-Override"); final String query = getParamValue(Source.QUERY, request.getUriInfo().getQueryParameters(), "_method"); if (override.equals("GET")) { if (request.getMediaType() != null && MediaType.APPLICATION_FORM_URLENCODED_TYPE.getType().equals(request.getMediaType().getType())) { final UriBuilder ub = request.getUriInfo().getRequestUriBuilder(); final Form f = ((ContainerRequest) request).readEntity(Form.class); for (final Map.Entry<String, List<String>> param : f.asMap().entrySet()) { ub.queryParam(param.getKey(), param.getValue().toArray()); request.setRequestUri(request.getUriInfo().getBaseUri(), ub.build());