List of usage examples for java.net URLConnection guessContentTypeFromName
public static String guessContentTypeFromName(String fname)
From source file:org.openlegacy.mvc.AbstractRestController.java
protected void getImage(HttpServletResponse response, String filename) throws IOException { if (uploadDir == null) { String property = "java.io.tmpdir"; // Get the temporary directory and print it. uploadDir = System.getProperty(property); }//from w ww .j av a 2 s. c om File file = new File(uploadDir, filename); BufferedImage bufferedImage = ImageIO.read(file); response.setContentType(URLConnection.guessContentTypeFromName(filename)); OutputStream out = response.getOutputStream(); String ext = ""; int i = filename.lastIndexOf('.'); if (i >= 0) { ext = filename.substring(i + 1); } ImageIO.write(bufferedImage, ext, out); out.close(); }
From source file:com.xxxifan.devbox.library.rxfile.RxFile.java
public static Observable<String> getFileType(String filePath) { Log.e(TAG, "Filepath in getFileType: " + filePath); final String[] parts = filePath.split("/"); return Observable.fromCallable(new Func0<String>() { @Override/* w w w . j a v a 2s.c o m*/ public String call() { return parts.length > 0 ? URLConnection.guessContentTypeFromName(parts[0]) : null; } }); }
From source file:com.google.jenkins.plugins.storage.AbstractUpload.java
/** * Auxiliar method for detecting web-related filename extensions, so * setting correctly Content-Type./*from ww w . j a v a2 s .co m*/ */ private String detectMIMEType(String filename) { String extension = Files.getFileExtension(filename); if (CONTENT_TYPES.containsKey(extension)) { return CONTENT_TYPES.get(extension); } else { return URLConnection.guessContentTypeFromName(filename); } }
From source file:com.pavlospt.rxfile.RxFile.java
public static String getMimeType(String fileName) { return URLConnection.guessContentTypeFromName(fileName); }
From source file:org.caboclo.clients.GoogleDriveClient.java
private String getMimeType(java.io.File file) { String mimeType = URLConnection.guessContentTypeFromName(file.getName()); mimeType = (mimeType == null) ? "application/octet-stream" : mimeType; return mimeType; }
From source file:edu.umn.cs.spatialHadoop.visualization.HadoopvizServer.java
/** * Tries to load the given resource name frmo class path if it exists. Used to * serve static files such as HTML pages, images and JavaScript files. * //from w w w .ja v a 2 s .c o m * @param target * @param response * @throws IOException */ private void tryToLoadStaticResource(String target, HttpServletResponse response) throws IOException { LOG.info("Loading resource " + target); // Try to load this resource as a static page InputStream resource = getClass().getResourceAsStream("/webapps/static/hadoopviz" + target); if (resource == null) { reportError(response, "Cannot load resource '" + target + "'", null); return; } byte[] buffer = new byte[1024 * 1024]; ServletOutputStream outResponse = response.getOutputStream(); int size; while ((size = resource.read(buffer)) != -1) { outResponse.write(buffer, 0, size); } resource.close(); outResponse.close(); response.setStatus(HttpServletResponse.SC_OK); if (target.endsWith(".js")) { response.setContentType("application/javascript"); } else if (target.endsWith(".css")) { response.setContentType("text/css"); } else { response.setContentType(URLConnection.guessContentTypeFromName(target)); } }
From source file:com.att.api.rest.RESTClient.java
/** * Sends an http POST multipart request. * * @param jsonObj JSON Object to set as the start part * @param fnames file names for any files to add * @return api response//from w ww . j av a2 s .com * * @throws RESTException if request was unsuccessful */ public APIResponse httpPost(JSONObject jsonObj, String[] fnames) throws RESTException { HttpResponse response = null; try { HttpClient httpClient = createClient(); HttpPost httpPost = new HttpPost(url); this.setHeader("Content-Type", "multipart/form-data; type=\"application/json\"; " + "start=\"<startpart>\"; boundary=\"foo\""); addInternalHeaders(httpPost); final Charset encoding = Charset.forName("UTF-8"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT, "foo", encoding); StringBody sbody = new StringBody(jsonObj.toString(), "application/json", encoding); FormBodyPart stringBodyPart = new FormBodyPart("root-fields", sbody); stringBodyPart.addField("Content-ID", "<startpart>"); entity.addPart(stringBodyPart); for (int i = 0; i < fnames.length; ++i) { final String fname = fnames[i]; String type = URLConnection.guessContentTypeFromStream(new FileInputStream(fname)); if (type == null) { type = URLConnection.guessContentTypeFromName(fname); } if (type == null) { type = "application/octet-stream"; } FileBody fb = new FileBody(new File(fname), type, "UTF-8"); FormBodyPart fileBodyPart = new FormBodyPart(fb.getFilename(), fb); fileBodyPart.addField("Content-ID", "<fileattachment" + i + ">"); fileBodyPart.addField("Content-Location", fb.getFilename()); entity.addPart(fileBodyPart); } httpPost.setEntity(entity); return buildResponse(httpClient.execute(httpPost)); } catch (Exception e) { throw new RESTException(e); } finally { if (response != null) { this.releaseConnection(response); } } }
From source file:com.att.api.rest.RESTClient.java
public APIResponse httpPost(String[] fnames, String subType, String[] bodyNameAttribute) throws RESTException { HttpResponse response = null;//from www.java 2 s . c om try { HttpClient httpClient = createClient(); HttpPost httpPost = new HttpPost(url); this.setHeader("Content-Type", "multipart/" + subType + "; " + "boundary=\"foo\""); addInternalHeaders(httpPost); final Charset encoding = Charset.forName("UTF-8"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT, "foo", encoding); for (int i = 0; i < fnames.length; ++i) { final String fname = fnames[i]; String contentType = null; contentType = URLConnection.guessContentTypeFromStream(new FileInputStream(fname)); if (contentType == null) { contentType = URLConnection.guessContentTypeFromName(fname); } if (contentType == null) contentType = this.getMIMEType(new File(fname)); if (fname.endsWith("srgs")) contentType = "application/srgs+xml"; if (fname.endsWith("grxml")) contentType = "application/srgs+xml"; if (fname.endsWith("pls")) contentType = "application/pls+xml"; FileBody fb = new FileBody(new File(fname), contentType, "UTF-8"); FormBodyPart fileBodyPart = new FormBodyPart(bodyNameAttribute[i], fb); fileBodyPart.addField("Content-ID", "<fileattachment" + i + ">"); fileBodyPart.addField("Content-Location", fb.getFilename()); if (contentType != null) { fileBodyPart.addField("Content-Type", contentType); } entity.addPart(fileBodyPart); } httpPost.setEntity(entity); return buildResponse(httpClient.execute(httpPost)); } catch (IOException e) { throw new RESTException(e); } finally { if (response != null) { this.releaseConnection(response); } } }
From source file:de.bahnhoefe.deutschlands.bahnhofsfotos.DetailsActivity.java
private void uploadPhoto() { final ProgressDialog progress = new ProgressDialog(DetailsActivity.this); progress.setMessage(getResources().getString(R.string.send)); progress.setTitle(getResources().getString(R.string.app_name)); progress.setProgressStyle(ProgressDialog.STYLE_SPINNER); progress.show();//from w w w . j av a 2 s. c o m final File mediaFile = getStoredMediaFile(); RequestBody file = RequestBody .create(MediaType.parse(URLConnection.guessContentTypeFromName(mediaFile.getName())), mediaFile); rsapi.photoUpload(email, token, bahnhof.getId(), countryCode.toLowerCase(), file) .enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { progress.dismiss(); switch (response.code()) { case 202: new SimpleDialogs().confirm(DetailsActivity.this, R.string.upload_completed); break; case 400: new SimpleDialogs().confirm(DetailsActivity.this, R.string.upload_bad_request); break; case 401: new SimpleDialogs().confirm(DetailsActivity.this, R.string.upload_token_invalid); break; case 409: new SimpleDialogs().confirm(DetailsActivity.this, R.string.upload_conflict); break; case 413: new SimpleDialogs().confirm(DetailsActivity.this, R.string.upload_too_big); break; default: new SimpleDialogs().confirm(DetailsActivity.this, String.format(getText(R.string.upload_failed).toString(), response.code())); } } @Override public void onFailure(Call<Void> call, Throwable t) { Log.e(TAG, "Error uploading photo", t); progress.dismiss(); new SimpleDialogs().confirm(DetailsActivity.this, String.format(getText(R.string.upload_failed).toString(), t.getMessage())); } }); }
From source file:org.wso2.carbon.connector.integration.test.canvas.CanvasConnectorIntegrationTest.java
/** * Test createEntry method with Mandatory Parameters. *//*from w w w .java 2 s . co m*/ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateDiscussionTopicWithOptionalParameters" }, description = "Canvas {createEntry} integration test with Mandatory parameters.") public void testCreateEntryWithMandatoryParameters() 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"); String userId = esbRestResponse.getBody().getString("user_id"); connectorProperties.put("entryId", entryId); 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(apiFirstElement.getString("created_at").split("T")[0], sdf.format(new Date())); Assert.assertEquals(apiFirstElement.getString("user_id"), userId); }