List of usage examples for java.net URLConnection guessContentTypeFromName
public static String guessContentTypeFromName(String fname)
From source file:io.swagger.client.ApiClient.java
/** * Guess Content-Type header from the given file (defaults to "application/octet-stream"). * * @param file The given file/*from w w w . jav a2 s. c om*/ * @return The guessed Content-Type */ public String guessContentTypeFromFile(File file) { String contentType = URLConnection.guessContentTypeFromName(file.getName()); if (contentType == null) { return "application/octet-stream"; } else { return contentType; } }
From source file:org.wso2.carbon.connector.integration.test.canvas.CanvasConnectorIntegrationTest.java
/** * Test createEntry method with Optional Parameters. *//*from ww w .j a v a 2 s . c o m*/ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateDiscussionTopicWithOptionalParameters" }, description = "Canvas {createEntry} integration test with optional parameters.") public void testCreateEntryWithOptionalParameters() throws IOException, JSONException { headersMap.put("Action", "urn:createEntry"); final String requestString = proxyUrl + "?courseId=" + connectorProperties.getProperty("courseId") + "&topicId=" + connectorProperties.getProperty("topicId") + "&apiUrl=" + connectorProperties.getProperty("apiUrl") + "&accessToken=" + connectorProperties.getProperty("accessToken"); MultipartFormdataProcessor multipartProcessor = new MultipartFormdataProcessor(requestString, headersMap); File file = new File(pathToResourcesDirectory + connectorProperties.getProperty("attachmentFileName")); multipartProcessor.addFileToRequest("attachment", file, URLConnection.guessContentTypeFromName(file.getName())); multipartProcessor.addFormDataToRequest("message", connectorProperties.getProperty("entryMessage")); RestResponse<JSONObject> esbRestResponse = multipartProcessor.processForJsonResponse(); String entryId = esbRestResponse.getBody().getString("id"); final String apiUrl = connectorProperties.getProperty("apiUrl") + "/api/v1/courses/" + connectorProperties.getProperty("courseId") + "/discussion_topics/" + connectorProperties.getProperty("topicId") + "/entry_list?ids[]=" + entryId; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); JSONArray apiResponseArray = new JSONArray(apiRestResponse.getBody().getString("output")); JSONObject apiFirstElement = apiResponseArray.getJSONObject(0); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Assert.assertEquals(connectorProperties.getProperty("entryMessage"), apiFirstElement.getString("message")); Assert.assertEquals(connectorProperties.getProperty("attachmentFileName"), apiFirstElement.getJSONObject("attachment").getString("filename")); Assert.assertEquals(apiFirstElement.getString("created_at").split("T")[0], sdf.format(new Date())); }
From source file:org.wso2.carbon.apimgt.rest.api.publisher.impl.ApisApiServiceImpl.java
/** * Uploads a thumbnail image into an API * /*from w w w . j a v a 2s .c o m*/ * @param apiId API Id * @param fileInputStream input stream of thumbnail image * @param fileDetail file details as Attachment * @param contentType content type of the payload * @param ifMatch If-match header value * @param ifUnmodifiedSince If-Unmodified-Since header value * @return metadata of the uploaded thumbnail image */ @Override public Response apisApiIdThumbnailPost(String apiId, InputStream fileInputStream, Attachment fileDetail, String contentType, String ifMatch, String ifUnmodifiedSince) { try { APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider(); String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String fileName = fileDetail.getDataHandler().getName(); String fileContentType = URLConnection.guessContentTypeFromName(fileName); if (StringUtils.isBlank(fileContentType)) { fileContentType = fileDetail.getContentType().toString(); } //this will fail if user does not have access to the API or the API does not exist API api = APIMappingUtil.getAPIFromApiIdOrUUID(apiId, tenantDomain); ResourceFile apiImage = new ResourceFile(fileInputStream, fileContentType); String thumbPath = APIUtil.getIconPath(api.getId()); String thumbnailUrl = apiProvider.addResourceFile(thumbPath, apiImage); api.setThumbnailUrl(APIUtil.prependTenantPrefix(thumbnailUrl, api.getId().getProviderName())); APIUtil.setResourcePermissions(api.getId().getProviderName(), null, null, thumbPath); apiProvider.updateAPI(api); String uriString = RestApiConstants.RESOURCE_PATH_THUMBNAIL.replace(RestApiConstants.APIID_PARAM, apiId); URI uri = new URI(uriString); FileInfoDTO infoDTO = new FileInfoDTO(); infoDTO.setRelativePath(uriString); infoDTO.setMediaType(apiImage.getContentType()); return Response.created(uri).entity(infoDTO).build(); } catch (APIManagementException e) { //Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need to expose the // existence of the resource if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log); } else { String errorMessage = "Error while retrieving thumbnail of API : " + apiId; RestApiUtil.handleInternalServerError(errorMessage, e, log); } } catch (URISyntaxException e) { String errorMessage = "Error while retrieving thumbnail location of API: " + apiId; RestApiUtil.handleInternalServerError(errorMessage, e, log); } catch (FaultGatewaysException e) { //This is logged and process is continued because icon is optional for an API log.error("Failed to update API after adding icon. ", e); } finally { IOUtils.closeQuietly(fileInputStream); } return null; }
From source file:com.gargoylesoftware.htmlunit.WebClient.java
/** * Tries to guess the content type of the file.<br> * This utility could be located in an helper class but we can compare this functionality * for instance with the "Helper Applications" settings of Mozilla and therefore see it as a * property of the "browser".//from w ww. java2s. c o m * @param file the file * @return "application/octet-stream" if nothing could be guessed */ public String guessContentType(final File file) { String contentType = URLConnection.guessContentTypeFromName(file.getName()); if (file.getName().endsWith(".xhtml")) { // Java's mime type map doesn't know about XHTML files (at least in Sun JDK5). contentType = "application/xhtml+xml"; } if (contentType == null) { InputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); contentType = URLConnection.guessContentTypeFromStream(inputStream); } catch (final IOException e) { // Ignore silently. } finally { IOUtils.closeQuietly(inputStream); } } if (contentType == null) { if (file.getName().endsWith(".js")) { contentType = "text/javascript"; } else { contentType = "application/octet-stream"; } } return contentType; }
From source file:org.wso2.carbon.apimgt.rest.api.publisher.v1.impl.ApisApiServiceImpl.java
@Override public Response updateAPIThumbnail(String apiId, InputStream fileInputStream, Attachment fileDetail, String ifMatch, MessageContext messageContext) { try {// ww w. jav a 2 s.c om APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider(); String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String fileName = fileDetail.getDataHandler().getName(); String fileContentType = URLConnection.guessContentTypeFromName(fileName); if (org.apache.commons.lang3.StringUtils.isBlank(fileContentType)) { fileContentType = fileDetail.getContentType().toString(); } //this will fail if user does not have access to the API or the API does not exist API api = apiProvider.getAPIbyUUID(apiId, tenantDomain); ResourceFile apiImage = new ResourceFile(fileInputStream, fileContentType); String thumbPath = APIUtil.getIconPath(api.getId()); String thumbnailUrl = apiProvider.addResourceFile(thumbPath, apiImage); api.setThumbnailUrl(APIUtil.prependTenantPrefix(thumbnailUrl, api.getId().getProviderName())); APIUtil.setResourcePermissions(api.getId().getProviderName(), null, null, thumbPath); //Creating URI templates due to available uri templates in returned api object only kept single template //for multiple http methods String apiSwaggerDefinition = apiProvider.getOpenAPIDefinition(api.getId()); if (!org.apache.commons.lang3.StringUtils.isEmpty(apiSwaggerDefinition)) { APIDefinition apiDefinitionFromOpenAPISpec = new APIDefinitionFromOpenAPISpec(); Set<URITemplate> uriTemplates = apiDefinitionFromOpenAPISpec.getURITemplates(api, apiSwaggerDefinition); api.setUriTemplates(uriTemplates); // scopes Set<Scope> scopes = apiDefinitionFromOpenAPISpec.getScopes(apiSwaggerDefinition); api.setScopes(scopes); } apiProvider.updateAPI(api); String uriString = RestApiConstants.RESOURCE_PATH_THUMBNAIL.replace(RestApiConstants.APIID_PARAM, apiId); URI uri = new URI(uriString); FileInfoDTO infoDTO = new FileInfoDTO(); infoDTO.setRelativePath(uriString); infoDTO.setMediaType(apiImage.getContentType()); return Response.created(uri).entity(infoDTO).build(); } catch (APIManagementException e) { //Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need to expose the // existence of the resource if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log); } else if (isAuthorizationFailure(e)) { RestApiUtil.handleAuthorizationFailure( "Authorization failure while adding thumbnail for API : " + apiId, e, log); } else { String errorMessage = "Error while retrieving thumbnail of API : " + apiId; RestApiUtil.handleInternalServerError(errorMessage, e, log); } } catch (URISyntaxException e) { String errorMessage = "Error while retrieving thumbnail location of API: " + apiId; RestApiUtil.handleInternalServerError(errorMessage, e, log); } catch (FaultGatewaysException e) { //This is logged and process is continued because icon is optional for an API log.error("Failed to update API after adding icon. ", e); } finally { IOUtils.closeQuietly(fileInputStream); } return null; }