List of usage examples for java.net URLConnection guessContentTypeFromStream
public static String guessContentTypeFromStream(InputStream is) throws IOException
From source file:org.appcelerator.titanium.TiBlob.java
/** * Determines the MIME-type by reading first few characters from the given input stream. * @return the guessed MIME-type or null if the type could not be determined. *//*from w w w . jav a2s . c o m*/ public String guessContentTypeFromStream() { String mt = null; InputStream is = getInputStream(); if (is != null) { try { mt = URLConnection.guessContentTypeFromStream(is); } catch (Exception e) { Log.e(TAG, e.getMessage(), e, Log.DEBUG_MODE); } } return mt; }
From source file:utils.APIExporter.java
/** * This method get the API thumbnail and write in to the zip file * @param uuid API id of the API/* w ww .j a v a 2 s . co m*/ * @param accessToken valide access token with view scope * @param APIFolderpath archive base path */ private static void exportAPIThumbnail(String uuid, String accessToken, String APIFolderpath) { ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance(); try { //REST API call to get API thumbnail String url = config.getPublisherUrl() + "apis/" + uuid + "/thumbnail"; CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate()); HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken); CloseableHttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); //assigning the response in to inputStream BufferedHttpEntity httpEntity = new BufferedHttpEntity(entity); InputStream imageStream = httpEntity.getContent(); byte[] byteArray = IOUtils.toByteArray(imageStream); InputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(byteArray)); //getting the mime type of the input Stream String mimeType = URLConnection.guessContentTypeFromStream(inputStream); //getting file extension String extension = getThumbnailFileType(mimeType); OutputStream outputStream = null; if (extension != null) { //writing image in to the archive try { outputStream = new FileOutputStream(APIFolderpath + File.separator + "icon." + extension); IOUtils.copy(httpEntity.getContent(), outputStream); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(imageStream); IOUtils.closeQuietly(inputStream); } } } catch (IOException e) { log.error("Error occurred while exporting the API thumbnail"); } }
From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java
@Override public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException { LOGGER.debug("Transforming ResponseQueue with XSLT tranformer"); long grandTotal = -1; try {//from w w w .j a v a2 s .c o m DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null)); // TODO use streaming XSLT, not DOM List<Result> results = upstreamResponse.getResults(); grandTotal = upstreamResponse.getHits(); for (Result result : results) { Metacard metacard = result.getMetacard(); String thisMetacard = metacard.getMetadata(); if (metacard != null && thisMetacard != null) { Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null); if (metacard.getId() != null) { metacardElement .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId())); } if (metacard.getMetacardType().toString() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type", metacard.getMetacardType().getName())); } if (metacard.getTitle() != null) { metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle())); } if (result.getRelevanceScore() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score", result.getRelevanceScore().toString())); } if (result.getDistanceInMeters() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance", result.getDistanceInMeters().toString())); } if (metacard.getSourceId() != null) { metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId())); } if (metacard.getContentTypeName() != null) { String contentType = metacard.getContentTypeName(); Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type", contentType); // TODO revisit what to put in the qualifier typeElement.setAttribute("qualifier", "content-type"); metacardElement.appendChild(typeElement); } if (metacard.getResourceURI() != null) { try { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product", metacard.getResourceURI().toString())); } catch (DOMException e) { LOGGER.warn(" Unable to create resource uri element", e); } } if (metacard.getThumbnail() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail", Base64.encodeBase64String(metacard.getThumbnail()))); try { String mimeType = URLConnection .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail())); metacardElement .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType)); } catch (IOException e) { // TODO Auto-generated catch block metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png")); } } DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); if (metacard.getCreatedDate() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created", fmt.print(metacard.getCreatedDate().getTime()))); } // looking at the date last modified if (metacard.getModifiedDate() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated", fmt.print(metacard.getModifiedDate().getTime()))); } if (metacard.getEffectiveDate() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective", fmt.print(metacard.getEffectiveDate().getTime()))); } if (metacard.getLocation() != null) { metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation())); } Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document"); metacardElement.appendChild(documentElement); resultsElement.appendChild(metacardElement); Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(), true); documentElement.appendChild(importedNode); } else { LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer"); continue; } } if (LOGGER.isDebugEnabled()) { DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc)); } LOGGER.debug("Starting responsequeue xslt transform."); Transformer transformer; Map<String, Object> mergedMap = new HashMap<String, Object>(); mergedMap.put(GRAND_TOTAL, grandTotal); if (arguments != null) { mergedMap.putAll(arguments); } BinaryContent resultContent; StreamResult resultOutput = null; Source source = new DOMSource(doc); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resultOutput = new StreamResult(baos); try { transformer = templates.newTransformer(); } catch (TransformerConfigurationException tce) { throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(), tce.getCause()); } if (mergedMap != null && !mergedMap.isEmpty()) { for (Map.Entry<String, Object> entry : mergedMap.entrySet()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}"); } transformer.setParameter(entry.getKey(), entry.getValue()); } } try { transformer.transform(source, resultOutput); byte[] bytes = baos.toByteArray(); LOGGER.debug("Transform complete."); resultContent = new XsltTransformedContent(bytes, mimeType); } catch (TransformerException te) { LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause()); throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(), te.getCause()); } finally { // transformer.reset(); // don't need to do that unless we are putting it back into a // pool -- which we should do, but that can wait until later. } return resultContent; } catch (ParserConfigurationException e) { LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause()); throw new CatalogTransformerException("Error merging entries to xml feed.", e); } }
From source file:org.mifos.framework.image.service.ClientPhotoServiceDatabase.java
private String determineContentType(InputStream in) throws IOException { String contentType = URLConnection.guessContentTypeFromStream(in); if (contentType == null) { contentType = DEFAULT_CONTENT_TYPE; }//from ww w .j a v a 2 s. co m return contentType; }
From source file:com.laishidua.mobilecloud.ghostmyselfie.controller.GhostMySelfieController.java
/** * /* www . j av a2 s. c o m*/ * @param id : the id of the ghostmyselfie to associate this data stream with * @param ghostMyselfieData : the data stream * @param response : http response, exposed to allow manipulation like setting * error codes * @return : a GhostMySelfieStatus object if successful, null otherwise * @throws IOException */ @RequestMapping(value = GhostMySelfieSvcApi.GHOSTMYSELFIE_DATA_PATH, method = RequestMethod.POST) public ResponseEntity<GhostMySelfieStatus> setGhostMySelfieData( @PathVariable(GhostMySelfieSvcApi.ID_PARAMETER) long id, @RequestPart(GhostMySelfieSvcApi.DATA_PARAMETER) MultipartFile ghostMySelfieData, HttpServletResponse response, Principal p) throws IOException { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_JSON); GhostMySelfie gms = ghostMySelphie.findOne(id); if (gms != null) { if (p.getName().equals(gms.getOwner())) { String mimeType = URLConnection.guessContentTypeFromStream(ghostMySelfieData.getInputStream()); if (!mimeType.equals("image/jpeg") && !mimeType.equals("image/png")) { response.sendError(400, "Just jpg, jpeg and png images supported"); return null; } ghostMySelfieDataMgr = GhostMySelfieFileManager.get(); saveSomeGhostMySelfie(gms, ghostMySelfieData); return new ResponseEntity<GhostMySelfieStatus>( new GhostMySelfieStatus(GhostMySelfieStatus.GhostMySelfieState.READY), responseHeaders, HttpStatus.CREATED); } else { response.sendError(400, "Not your Selfie, hands off!"); return null; } } else { response.sendError(404, "Your Selfie is in another castle."); return null; } }
From source file:com.ge.predix.solsvc.blobstore.bootstrap.BlobstoreClientImpl.java
private String getContentType(byte[] b) { String contentType;// w ww . java2 s . c o m try { contentType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(b)); } catch (IOException e) { if (this.log.isDebugEnabled()) { this.log.debug("unable to determine content type", e); //$NON-NLS-1$ } return APPLICATION_OCTET_STREAM; } if (this.log.isDebugEnabled()) { this.log.debug("content type inferred is" + contentType); //$NON-NLS-1$ } return contentType; }
From source file:org.bankinterface.util.HttpClient.java
public String sendHttpRequest(String method) throws HttpClientException { InputStream in = sendHttpRequestStream(method); if (in == null) return null; StringBuilder buf = new StringBuilder(); try {/*from w w w . ja va 2s .c o m*/ String charset = null; String contentType = con.getContentType(); if (contentType == null) { try { contentType = URLConnection.guessContentTypeFromStream(in); } catch (IOException ioe) { logger.warn("Problems guessing content type from steam"); } } if (logger.isDebugEnabled()) { logger.debug("Content-Type: " + contentType); } if (contentType != null) { contentType = contentType.toUpperCase(); int charsetEqualsLoc = contentType.indexOf("=", contentType.indexOf("CHARSET")); int afterSemiColon = contentType.indexOf(";", charsetEqualsLoc); if (charsetEqualsLoc >= 0 && afterSemiColon >= 0) { charset = contentType.substring(charsetEqualsLoc + 1, afterSemiColon); } else if (charsetEqualsLoc >= 0) { charset = contentType.substring(charsetEqualsLoc + 1); } if (charset != null) { charset = charset.trim(); } if (logger.isDebugEnabled()) { logger.debug("Getting text from HttpClient with charset: " + charset); } } BufferedReader post = new BufferedReader( charset == null ? new InputStreamReader(in) : new InputStreamReader(in, charset)); String line = ""; if (logger.isDebugEnabled()) { logger.debug("---- HttpClient Response Content ----"); } while ((line = post.readLine()) != null) { if (logger.isDebugEnabled()) { logger.debug("[HttpClient] : " + line); } buf.append(line); if (lineFeed) { buf.append("\n"); } } } catch (Exception e) { throw new HttpClientException("Error processing input stream", e); } return buf.toString(); }
From source file:org.paxle.crawler.ftp.impl.FtpUrlConnection.java
@Override public String getContentType() { if (!this.client.isConnected()) return null; if (this.isDirectory) return DIR_MIMETYPE; String contentType = null;// w w w . j a v a 2s .c om try { InputStream inputStream = this.getInputStream(); contentType = URLConnection.guessContentTypeFromStream(inputStream); inputStream.close(); // we need to reconnect here if (!this.client.isConnected()) this.connect(); } catch (IOException e) { e.printStackTrace(); } return contentType; }
From source file:com.github.mobile.util.HttpImageGetter.java
@Override public Drawable getDrawable(String source) { Bitmap bitmap = null;/*from w ww .j av a 2 s.c om*/ if (!destroyed) { 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 = ImageUtils.renderSvgToBitmap(context.getResources(), is, width, height); } else { boolean isGif = mime != null && mime.startsWith("image/gif"); if (!isGif || canLoadGif()) { output = File.createTempFile("image", ".tmp", dir); if (FileUtils.save(output, is)) { if (isGif) { GifDrawable d = new GifDrawable(output); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } else { bitmap = ImageUtils.getBitmap(output, width, height); } } } } } } catch (IOException e) { // fall through to showing the loading 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 (destroyed && bitmap != null) { bitmap.recycle(); bitmap = null; } else if (bitmap != null) { loadedBitmaps.add(new WeakReference<>(bitmap)); } } if (bitmap == null) { return loading.getDrawable(source); } BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; }
From source file:com.baasbox.controllers.Asset.java
private static Result postFile() throws Throwable { MultipartFormData body = request().body().asMultipartFormData(); if (body == null) return badRequest( "missing data: is the body multipart/form-data? Check if it contains boundaries too!"); FilePart file = body.getFile("file"); Map<String, String[]> data = body.asFormUrlEncoded(); String[] meta = data.get("meta"); String[] name = data.get("name"); if (name == null || name.length == 0 || StringUtils.isEmpty(name[0].trim())) return badRequest("missing name field"); String ret = ""; if (file != null) { String metaJson = null;/* w w w . j a v a2 s . c om*/ if (meta != null && meta.length > 0) { metaJson = meta[0]; } java.io.File fileContent = file.getFile(); byte[] fileContentAsByteArray = Files.toByteArray(fileContent); String fileName = file.getFilename(); String contentType = file.getContentType(); if (contentType == null || contentType.isEmpty() || contentType.equalsIgnoreCase("application/octet-stream")) { //try to guess the content type InputStream is = new BufferedInputStream(new FileInputStream(fileContent)); contentType = URLConnection.guessContentTypeFromStream(is); if (contentType == null || contentType.isEmpty()) contentType = "application/octet-stream"; } try { ODocument doc = AssetService.createFile(name[0], fileName, metaJson, contentType, fileContentAsByteArray); ret = prepareResponseToJson(doc); } catch (ORecordDuplicatedException e) { return badRequest("An asset with the same name already exists"); } catch (OIndexException e) { return badRequest("An asset with the same name already exists"); } } else { return badRequest("missing file field"); } return created(ret); }