List of usage examples for java.net URLConnection guessContentTypeFromStream
public static String guessContentTypeFromStream(InputStream is) throws IOException
From source file:com.gh4a.utils.HttpImageGetter.java
private Drawable loadImageForUrl(String source) { Bitmap bitmap = null;//from w w w . jav a 2 s . c om if (!mDestroyed) { File output = null; InputStream is = null; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(source).openConnection(); is = connection.getInputStream(); if (is != null) { String mime = connection.getContentType(); if (mime == null) { mime = URLConnection.guessContentTypeFromName(source); } if (mime == null) { mime = URLConnection.guessContentTypeFromStream(is); } if (mime != null && mime.startsWith("image/svg")) { bitmap = renderSvgToBitmap(mContext.getResources(), is, mWidth, mHeight); } else { boolean isGif = mime != null && mime.startsWith("image/gif"); if (!isGif || canLoadGif()) { output = File.createTempFile("image", ".tmp", mCacheDir); if (FileUtils.save(output, is)) { if (isGif) { GifDrawable d = new GifDrawable(output); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } else { bitmap = getBitmap(output, mWidth, mHeight); } } } } } } catch (IOException e) { // fall through to showing the error bitmap } finally { if (output != null) { output.delete(); } if (is != null) { try { is.close(); } catch (IOException e) { // ignored } } if (connection != null) { connection.disconnect(); } } } synchronized (this) { if (mDestroyed && bitmap != null) { bitmap.recycle(); bitmap = null; } } if (bitmap == null) { return mErrorDrawable; } BitmapDrawable drawable = new LoadedBitmapDrawable(mContext.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; }
From source file:org.mifos.customers.client.struts.actionforms.ClientCustActionForm.java
private void validatePicture(HttpServletRequest request, ActionErrors errors) throws PageExpiredException { if (picture != null && StringUtils.isNotBlank(picture.getFileName())) { if (picture.getFileSize() > ClientConstants.PICTURE_ALLOWED_SIZE) { addInvalidPictureError(errors, "image size should be less then 300K"); }/* w w w . j av a 2 s . c om*/ try { String contentType = URLConnection.guessContentTypeFromStream(picture.getInputStream()); if (contentType == null) { contentType = URLConnection.guessContentTypeFromName(picture.getFileName()); } if (contentType == null || !(contentType.equals("image/jpeg") || contentType.equals("image/gif") || contentType.equals("image/jpg") || contentType.equals("image/png"))) { addInvalidPictureError(errors, "allowed only jpg/gif/png"); } } catch (IOException e) { addInvalidPictureError(errors, e.getMessage()); } } }
From source file:org.paxle.gui.impl.servlets.ConfigView.java
public void writeImage(HttpServletRequest request, HttpServletResponse response, Context context) throws Exception { final String pid = request.getParameter("pid"); if (pid == null) { response.sendError(501, "No pid supplied."); return;/*www .java2 s.c o m*/ } final String bundleID = request.getParameter("bundleID"); if (bundleID == null) { response.sendError(501, "No bundle-ID supplied."); return; } final ConfigTool configTool = (ConfigTool) context.get(ConfigTool.TOOL_NAME); if (configTool == null) { response.sendError(501, "Config-Tool not found."); return; } final Configurable configurabel = configTool.getConfigurable(Integer.valueOf(bundleID), pid); if (configurabel == null) { response.sendError(501, String .format("No configurable component found for bundle-ID '%s' and PID '%s'.", bundleID, pid)); return; } // loading metadata final ObjectClassDefinition ocd = configurabel.getObjectClassDefinition(); if (ocd == null) { response.sendError(501, String.format("No ObjectClassDefinition found for service with PID '%s'.", pid)); return; } try { // trying to find a proper icon final int[] sizes = new int[] { 16, 32, 64, 128, 256 }; BufferedImage img = null; for (int size : sizes) { // trying to find an icon InputStream in = ocd.getIcon(size); if (in == null) { if (size == sizes[sizes.length - 1]) { // fallback to the default image in = this.getClass().getResourceAsStream("/resources/images/cog.png"); } else continue; } // loading date final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); bout.close(); in.close(); // trying to detect the mimetype of the image ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); String contentType = URLConnection.guessContentTypeFromStream(bin); bin.close(); Iterator<ImageReader> readers = null; if (contentType != null) { readers = ImageIO.getImageReadersByMIMEType(contentType); } else { readers = ImageIO.getImageReadersByFormatName("png"); } while (readers.hasNext() && img == null) { // trying the next reader final ImageReader reader = readers.next(); InputStream input = null; try { input = new ByteArrayInputStream(bout.toByteArray()); reader.setInput(ImageIO.createImageInputStream(input)); img = reader.read(0); } catch (Exception e) { this.log("Unable to read image for pid " + pid, e); } finally { if (input != null) input.close(); } } if (img != null) { response.setHeader("Content-Type", "image/png"); ImageIO.write(img, "png", response.getOutputStream()); return; } } // no icon found. response.sendError(404); } catch (Throwable e) { response.sendError(404, e.getMessage()); return; } }
From source file:com.baasbox.android.BaasFile.java
private Upload uploadRequest(BaasBox box, InputStream stream, int flags, BaasHandler<BaasFile> handler, JsonObject acl) {/*from ww w. j a v a 2s .c o m*/ RequestFactory factory = box.requestFactory; if (!isBound.compareAndSet(false, true)) { throw new IllegalArgumentException("you cannot upload new content for this file"); } if (stream == null) throw new IllegalArgumentException("doStream cannot be null"); boolean tryGuessExtension = false; if (this.mimeType == null) { try { this.mimeType = URLConnection.guessContentTypeFromStream(stream); tryGuessExtension = true; } catch (IOException e) { this.mimeType = "application/octet-doStream"; } } if (this.name == null) { this.name = UUID.randomUUID().toString(); if (tryGuessExtension) { String ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); if (ext != null) { this.name = name + "." + ext; } } } String endpoint = factory.getEndpoint("file"); HttpRequest req = factory.uploadFile(endpoint, true, stream, name, mimeType, acl, attachedData); return new Upload(box, this, req, flags, handler); }
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 ww w . jav a 2 s .co m*/ * * @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:org.eclipse.smarthome.binding.sonos.handler.ZonePlayerHandler.java
private String getContentTypeFromUrl(URL url) { if (url == null) { return null; }//from www . j ava 2s.c o m String contentType; InputStream input = null; try { URLConnection connection = url.openConnection(); contentType = connection.getContentType(); logger.debug("Content type from headers: {}", contentType); if (contentType == null) { input = connection.getInputStream(); contentType = URLConnection.guessContentTypeFromStream(input); logger.debug("Content type from data: {}", contentType); if (contentType == null) { contentType = RawType.DEFAULT_MIME_TYPE; } } } catch (IOException e) { logger.debug("Failed to identify content type from URL: {}", e.getMessage()); contentType = RawType.DEFAULT_MIME_TYPE; } finally { IOUtils.closeQuietly(input); } return contentType; }
From source file:com.att.api.rest.RESTClient.java
public APIResponse httpPost(String[] fnames, String subType, String[] bodyNameAttribute) throws RESTException { HttpResponse response = null;// w ww. j ava 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:edu.stanford.epad.common.util.EPADFileUtils.java
public static void sendFile(HttpServletRequest httpRequest, HttpServletResponse httpResponse, File file, String fileName, boolean download) throws Exception { InputStream is = null;/* w w w . j a v a 2 s . com*/ try { is = new BufferedInputStream(new FileInputStream(file)); String mimeType = URLConnection.guessContentTypeFromStream(is); httpResponse.setContentType(mimeType); if (download) httpResponse.setHeader("Content-disposition", "attachment;filename=" + fileName); httpResponse.setHeader("pragma", "no-cache"); OutputStream outStream = null; String encoding = null; if (httpRequest != null) encoding = httpRequest.getHeader("Accept-Encoding"); if (false && encoding != null && encoding.indexOf("gzip") != -1) { httpResponse.setHeader("Content-Encoding", "gzip"); outStream = new GZIPOutputStream(httpResponse.getOutputStream()); } else if (false && encoding != null && encoding.indexOf("compress") != -1) { httpResponse.setHeader("Content-Encoding", "compress"); outStream = new ZipOutputStream(httpResponse.getOutputStream()); } else { outStream = httpResponse.getOutputStream(); } int chunk = 1024; byte[] buffer = new byte[chunk]; int length = -1; int i = 0; while ((length = is.read(buffer)) != -1) { outStream.write(buffer, 0, length); if (length < chunk) break; } is.close(); is = null; } finally { if (is != null) is.close(); } }
From source file:eionet.cr.harvest.BaseHarvest.java
/** * Returns content loader for local files. * * @param file File to re-harvest/*from w w w. java 2 s . com*/ * @param contentType content type originally stored * @return ContentLoader */ private ContentLoader getLocalFileContentloader(File file, String contentType) { ContentLoader contentLoader = null; if (contentType == null) { contentType = getContextSourceDTO().getMediaType(); } // try to guess contentType if (contentType == null) { InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); contentType = URLConnection.guessContentTypeFromStream(is); } catch (Exception e) { LOGGER.warn(loggerMsg("Error getting content type for " + file.getPath())); } finally { IOUtils.closeQuietly(is); } } if (contentType == null) { return null; } // content type is not null if (contentType.startsWith("application/rss+xml") || contentType.startsWith("application/atom+xml")) { contentLoader = new FeedFormatLoader(); } else { // TODO refactor? RDFFormat rdfFormat = null; if (contentType.equals(CONTENT_TYPE_TEXT)) { String fileName = file.getName(); String[] arr = fileName.split("\\."); if (arr.length > 0) { String ext = arr[arr.length - 1]; if (StringUtils.isNotEmpty(ext)) { if (ext.equalsIgnoreCase(EXT_TTL)) { rdfFormat = RDFFormat.TURTLE; } if (ext.equalsIgnoreCase(EXT_N3)) { rdfFormat = RDFFormat.N3; } } } } else { rdfFormat = RDFMediaTypes.toRdfFormat(contentType); } if (rdfFormat != null) { contentLoader = new RDFFormatLoader(rdfFormat); } } return contentLoader; }
From source file:org.exoplatform.utils.ExoDocumentUtils.java
/** * Gets a DocumentInfo with info coming from the file at the given URI. * /* w ww.j a va2 s. c o m*/ * @param fileUri the file URI (file:// ...) * @return a DocumentInfo or null if an error occurs */ public static DocumentInfo documentFromFileUri(Uri fileUri) { if (fileUri == null) return null; try { URI uri = new URI(fileUri.toString()); File file = new File(uri); DocumentInfo document = new DocumentInfo(); document.documentName = file.getName(); document.documentSizeKb = file.length() / 1024; document.documentData = new FileInputStream(file); // Guess the mime type in 2 ways try { // 1) by inspecting the file's first bytes document.documentMimeType = URLConnection.guessContentTypeFromStream(document.documentData); } catch (IOException e) { document.documentMimeType = null; } if (document.documentMimeType == null) { // 2) if it fails, by stripping the extension of the filename // and getting the mime type from it String extension = ""; int dotPos = document.documentName.lastIndexOf('.'); if (0 <= dotPos) extension = document.documentName.substring(dotPos + 1); document.documentMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } // Get the orientation angle from the EXIF properties if ("image/jpeg".equals(document.documentMimeType)) document.orientationAngle = getExifOrientationAngleFromFile(file.getAbsolutePath()); return document; } catch (URISyntaxException e) { Log.e(LOG_TAG, "Cannot retrieve the file at " + fileUri); if (Log.LOGD) Log.d(LOG_TAG, e.getMessage() + "\n" + Log.getStackTraceString(e)); } catch (FileNotFoundException e) { Log.e(LOG_TAG, "Cannot retrieve the file at " + fileUri); if (Log.LOGD) Log.d(LOG_TAG, e.getMessage() + "\n" + Log.getStackTraceString(e)); } return null; }