List of usage examples for org.springframework.http MediaType equals
@Override public boolean equals(@Nullable Object other)
From source file:jetbrains.buildServer.vsoRooms.rest.impl.StringJsonConverter.java
public boolean canWrite(Class<?> aClass, MediaType mediaType) { return aClass.equals(String.class) && mediaType.equals(MediaType.APPLICATION_JSON); }
From source file:org.craftercms.commons.rest.HttpMessageConvertingResponseWriter.java
public <T> void writeWithMessageConverters(T returnValue, HttpServletRequest request, HttpServletResponse response) throws IOException, HttpMediaTypeNotAcceptableException { Class<?> returnValueClass = returnValue.getClass(); List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request); List<MediaType> producibleMediaTypes = getProducibleMediaTypes(returnValueClass); Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>(); for (MediaType r : requestedMediaTypes) { for (MediaType p : producibleMediaTypes) { if (r.isCompatibleWith(p)) { compatibleMediaTypes.add(getMostSpecificMediaType(r, p)); }/* w w w. j a v a 2 s. com*/ } } if (compatibleMediaTypes.isEmpty()) { throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes); } List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes); MediaType.sortBySpecificityAndQuality(mediaTypes); MediaType selectedMediaType = null; for (MediaType mediaType : mediaTypes) { if (mediaType.isConcrete()) { selectedMediaType = mediaType; break; } else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) { selectedMediaType = MediaType.APPLICATION_OCTET_STREAM; break; } } if (selectedMediaType != null) { selectedMediaType = selectedMediaType.removeQualityValue(); for (HttpMessageConverter<?> messageConverter : messageConverters) { if (messageConverter.canWrite(returnValueClass, selectedMediaType)) { ((HttpMessageConverter<T>) messageConverter).write(returnValue, selectedMediaType, new ServletServerHttpResponse(response)); logger.debug(LOG_KEY_WRITTEN_WITH_MESSAGE_CONVERTER, returnValue, selectedMediaType, messageConverter); return; } } } throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes); }
From source file:org.opendatakit.api.odktables.FileService.java
@GET @Path("{odkClientVersion}/{filePath:.*}") public Response getFile(@Context HttpHeaders httpHeaders, @PathParam("odkClientVersion") String odkClientVersion, @PathParam("filePath") List<PathSegment> segments, @QueryParam(PARAM_AS_ATTACHMENT) String asAttachment) throws IOException, ODKTaskLockException, ODKEntityNotFoundException, ODKOverQuotaException, FileNotFoundException, PermissionDeniedException, ODKDatastoreException { // First we need to get the table id from the path. We're // going to be assuming that you're passing the entire path of the file // under /sdcard/opendatakit/appId/ e.g., tables/tableid/the/rest/of/path. // So we'll reclaim the tidbits and then reconstruct the entire path. // If you are getting general files, there will be no recoverable tableId, // and these are then app-level files. if (segments.size() < 1) { return Response.status(Status.BAD_REQUEST).entity(FileService.ERROR_MSG_INSUFFICIENT_PATH) .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION) .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true") .build();/*from ww w . ja v a 2s. c om*/ } String appRelativePath = constructPathFromSegments(segments); String tableId = FileManager.getTableIdForFilePath(appRelativePath); FileContentInfo fileContentInfo = null; // DbTableFileInfo.NO_TABLE_ID -- means that we are working with app-level // permissions if (!DbTableFileInfo.NO_TABLE_ID.equals(tableId)) { userPermissions.checkPermission(appId, tableId, TablePermission.READ_PROPERTIES); } // retrieve the incoming if-none-match eTag... List<String> eTags = httpHeaders.getRequestHeader(HttpHeaders.IF_NONE_MATCH); String eTag = (eTags == null || eTags.isEmpty()) ? null : eTags.get(0); FileManager fm = new FileManager(appId, callingContext); fileContentInfo = fm.getFile(odkClientVersion, tableId, appRelativePath); // And now prepare everything to be returned to the caller. if (fileContentInfo.fileBlob != null && fileContentInfo.contentType != null && fileContentInfo.contentLength != null && fileContentInfo.contentLength != 0L) { // test if we should return a NOT_MODIFIED response... if (eTag != null && eTag.equals(fileContentInfo.contentHash)) { return Response.status(Status.NOT_MODIFIED).header(HttpHeaders.ETAG, eTag) .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION) .header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Credentials", "true").build(); } javax.ws.rs.core.MediaType mediaType = javax.ws.rs.core.MediaType.valueOf(fileContentInfo.contentType); if (mediaType.equals(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE) || fileContentInfo.contentType.startsWith("text")) { mediaType = mediaType.withCharset("utf-8"); } ResponseBuilder rBuild = Response.ok(fileContentInfo.fileBlob).type(mediaType) .header(HttpHeaders.CONTENT_LENGTH, fileContentInfo.contentLength) .header(HttpHeaders.ETAG, fileContentInfo.contentHash) .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION) .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true"); if (asAttachment != null && !"".equals(asAttachment)) { // Set the filename we're downloading to the disk. rBuild.header(WebConsts.CONTENT_DISPOSITION, "attachment; " + "filename=\"" + appRelativePath + "\""); } return rBuild.build(); } else { return Response.status(Status.NOT_FOUND) .entity("File content not yet available for: " + appRelativePath) .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION) .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true") .build(); } }
From source file:com.httpMessageConvert.FormHttpMessageConverter.java
public boolean canRead(Class<?> clazz, MediaType mediaType) { System.out.println("----------------coming ------------"); if (mediaType == null) { return true; }//from w w w. jav a 2 s . c om for (MediaType supportedMediaType : getSupportedMediaTypes()) { // we can't read multipart if (!supportedMediaType.equals(MediaType.MULTIPART_FORM_DATA) && supportedMediaType.includes(mediaType)) { return true; } } return false; }
From source file:com.revolsys.ui.web.rest.interceptor.WebAnnotationMethodHandlerAdapter.java
private MediaType getMediaType(final List<MediaType> supportedMediaTypes, final MediaType acceptedMediaType) { for (final MediaType mediaType : supportedMediaTypes) { if (mediaType.equals(acceptedMediaType)) { return mediaType; }//w ww . j a v a2s .c om } for (final MediaType mediaType : supportedMediaTypes) { if (acceptedMediaType.isWildcardType() || mediaType.includes(acceptedMediaType)) { return mediaType; } } return null; }
From source file:org.apache.geode.management.internal.web.http.support.HttpRequester.java
Object extractResponse(ClientHttpResponse response) throws IOException { MediaType mediaType = response.getHeaders().getContentType(); if (mediaType.equals(MediaType.APPLICATION_JSON)) { return org.apache.commons.io.IOUtils.toString(response.getBody(), "UTF-8"); } else {/*from w ww. j a va2s. co m*/ Path tempFile = Files.createTempFile("fileDownload", ""); if (tempFile.toFile().exists()) { FileUtils.deleteQuietly(tempFile.toFile()); } Files.copy(response.getBody(), tempFile); return tempFile; } }
From source file:org.artifactory.engine.DownloadServiceImpl.java
private void respondFoundResource(InternalRequestContext requestContext, ArtifactoryResponse response, RepoResource resource) throws IOException { //Get the actual repository the resource is in RepoPath responseRepoPath = resource.getResponseRepoPath(); String repoKey = responseRepoPath.getRepoKey(); //Send the resource file back (will update the cache for remote repositories) ResourceStreamHandle handle = getAlternateHandle(requestContext, response, responseRepoPath); boolean alternateRedirect = HttpUtils.isRedirectionResponseCode(response.getStatus()) && handle != null; // Error is every value that is not between 200-207, in case of alternateRedirect the status is 30x therefore we have to exclude this case if (response.isError() && !alternateRedirect) { RepoRequests.logToContext("Alternative response reset status as error - returning"); return;//from ww w. jav a 2 s .co m } Repo responseRepo = repositoryService.repositoryByKey(repoKey); try { if (handle == null) { RepoRequests.logToContext("Retrieving a content handle from target repo"); //Only if we didn't already set an alternate response handle = repositoryService.getResourceStreamHandle(requestContext, responseRepo, resource); } AddonsManager addonsManager = InternalContextHelper.get().beanForType(AddonsManager.class); PluginsAddon pluginAddon = addonsManager.addonByType(PluginsAddon.class); RepoRequests.logToContext("Executing any BeforeDownload user plugins that may exist"); pluginAddon.execPluginActions(BeforeDownloadAction.class, null, requestContext.getRequest(), responseRepoPath); if (requestContext.getRequest().isHeadOnly()) { /** * If we should response to a head, make sure repo is a remote and that stores locally (to save the * double artifact downloads) */ RepoRequests.logToContext("Request was of type HEAD - responding with no content"); requestResponseHelper.sendHeadResponse(response, resource); } else if (response.isPropertiesQuery()) { RepoRequests.logToContext("Request was of type Properties - responding with properties format " + response.getPropertiesMediaType()); Properties properties = repositoryService.getProperties(resource.getRepoPath()); if (properties != null && !properties.isEmpty()) { MediaType mediaType = MediaType.valueOf(response.getPropertiesMediaType()); String content; if (mediaType.equals(MediaType.APPLICATION_XML)) { content = InternalContextHelper.get().beanForType(MetadataDefinitionService.class) .getMetadataDefinition(Properties.class).getXmlProvider().toXml(properties); } else if (mediaType.equals(MediaType.APPLICATION_JSON)) { content = jsonProperties(responseRepoPath, properties); } else { response.sendError(HttpStatus.SC_BAD_REQUEST, "Media Type " + mediaType + " not supported!", log); return; } requestResponseHelper.updateResponseForProperties(response, resource, content, mediaType); } else { RepoRequests.logToContext("No properties found. Responding with 404"); response.sendError(HttpStatus.SC_NOT_FOUND, "No properties could be found.", log); } } else { RepoRequests.logToContext("Responding with selected content handle"); //Streaming the file is done outside a tx, so there is a chance that the content will change! requestResponseHelper.sendBodyResponse(response, resource, handle); } } catch (RepoRejectException rre) { int status = rre.getErrorCode(); log.debug("Repo rejection while downloading: " + rre.getMessage(), rre); if (status == HttpStatus.SC_FORBIDDEN && authorizationService.isAnonymous()) { RepoRequests.logToContext( "Response status is '%s' and authenticated as anonymous - sending challenge", status); // Transform a forbidden to unauthorized if received for an anonymous user response.sendAuthorizationRequired(rre.getMessage(), authenticationEntryPoint.getRealmName()); } else { RepoRequests.logToContext("Error occurred while sending response - sending error instead: %s", rre.getMessage()); String msg = "Rejected artifact download request: " + rre.getMessage(); sendError(requestContext, response, status, msg, log); } } catch (RemoteRequestException rre) { log.debug("Remote exception while downloading: " + rre.getMessage(), rre); RepoRequests.logToContext("Error occurred while sending response - sending error instead: %s", rre.getMessage()); sendError(requestContext, response, rre.getRemoteReturnCode(), rre.getMessage(), log); } catch (BadPomException bpe) { log.debug("Bad pom while downloading: " + bpe.getMessage(), bpe); RepoRequests.logToContext("Error occurred while sending response - sending error instead: %s", bpe.getMessage()); sendError(requestContext, response, HttpStatus.SC_CONFLICT, bpe.getMessage(), log); } catch (StorageException se) { log.debug("Exception while downloading: " + se.getMessage(), se); RepoRequests.logToContext("Error occurred while sending response - sending error instead: %s", se.getMessage()); sendError(requestContext, response, HttpStatus.SC_INTERNAL_SERVER_ERROR, se.getMessage(), log); } finally { IOUtils.closeQuietly(handle); } }
From source file:org.artifactory.request.RequestResponseHelper.java
public void updateResponseForProperties(ArtifactoryResponse response, RepoResource res, String content, MediaType mediaType, InternalRequestContext requestContext) throws IOException { RepoPath propsDownloadRepoPath;/*from w ww .j a v a2 s.co m*/ String contentType; if (mediaType.equals(MediaType.APPLICATION_XML)) { propsDownloadRepoPath = RepoPathFactory.create(res.getRepoPath().getRepoKey(), res.getRepoPath().getPath() + "?" + ArtifactRestConstants.PROPERTIES_XML_PARAM); contentType = mediaType.getType(); } else if (mediaType.equals(MediaType.APPLICATION_JSON)) { propsDownloadRepoPath = RepoPathFactory.create(res.getRepoPath().getRepoKey(), res.getRepoPath().getPath() + "?" + ArtifactRestConstants.PROPERTIES_PARAM); contentType = MT_ITEM_PROPERTIES; } else { response.sendError(HttpStatus.SC_BAD_REQUEST, "Media Type " + mediaType + " not supported!", log); return; } // props generated xml and json always browsable setBasicHeaders(response, res, false, ""); noCache(response); byte[] bytes = content.getBytes("utf-8"); try (InputStream is = new ByteArrayInputStream(bytes)) { int bodySize = bytes.length; response.setContentLength(bodySize); AccessLogger.downloaded(propsDownloadRepoPath); // Try to get range header String rangesString = tryToGetRangeHeaderInsensitive(HttpHeaders.RANGE, requestContext.getRequest()); String ifRangesString = tryToGetRangeHeaderInsensitive(HttpHeaders.IF_RANGE, requestContext.getRequest()); // Get artifact last modified date long lastModified = res.getLastModified(); // Get artifact sha1 String sha1 = res.getInfo().getSha1(); // Create range aware data for the response RangeAwareContext context = createRangeAwareContext(is, bodySize, rangesString, ifRangesString, contentType, lastModified, sha1); // If request range not satisfiable update response status end return if (context.getStatus() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) { response.setHeader(HttpHeaders.CONTENT_RANGE, context.getContentRange()); response.setStatus(context.getStatus()); return; } // update content length with range aware content length response.setContentLength(context.getContentLength()); // update content type with range aware content type response.setContentType(context.getContentType()); // update headers with range aware headers if (context.getContentRange() != null) { response.setHeader(HttpHeaders.CONTENT_RANGE, context.getContentRange()); } // Set response status if (context.getStatus() > 0) { response.setStatus(context.getStatus()); } // Get range aware input stream InputStream inputStream = context.getInputStream(); // Get current time for logs long start = System.currentTimeMillis(); // Send stream response.sendStream(inputStream); // Fire Download traffic event fireDownloadTrafficEvent(response, propsDownloadRepoPath, bodySize, start); } }
From source file:org.cloudfoundry.identity.uaa.security.CsrfAwareEntryPointAndDeniedHandler.java
protected boolean wantJson(HttpServletRequest request) { String accept = request.getHeader("Accept"); boolean json = false; if (StringUtils.hasText(accept)) { for (MediaType mediaType : MediaType.parseMediaTypes(accept)) { if (mediaType.equals(MediaType.APPLICATION_JSON)) { json = true;/*w w w. j a va 2 s. c om*/ break; } } } return json; }
From source file:org.encuestame.oauth1.support.OAuth1Utils.java
/** * * @param bodyType/*from w ww . j a v a2s . c om*/ * @param bodyBytes * @return */ private static Map<String, String> extractBodyParameters(MediaType bodyType, byte[] bodyBytes) { if (bodyType != null && bodyType.equals(MediaType.APPLICATION_FORM_URLENCODED)) { return extractParameters(new String(bodyBytes)); } return new HashMap<String, String>(); }