List of usage examples for java.net URLConnection guessContentTypeFromStream
public static String guessContentTypeFromStream(InputStream is) throws IOException
From source file:org.gathe.integration.WebHandler.java
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { LOG.debug("Handling target: " + target); if (target.equalsIgnoreCase("/init")) { String threadName = Thread.currentThread().getName(); endpointManager.doInit();/* w ww .ja va 2 s. c o m*/ response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); return; } if (target.startsWith("/static")) { String filename = target.substring("/static".length()); URL url = getClass().getResource(filename); InputStream stream = getClass().getResourceAsStream(filename); if (stream == null) { //resource not found response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().println("Resource not found"); baseRequest.setHandled(true); return; } String contentType = URLConnection.guessContentTypeFromStream(stream); response.setContentType(contentType); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); IOUtils.copy(stream, response.getOutputStream()); return; } if (target.startsWith("/status")) { int next; try { next = Integer.parseInt(target.substring(8)); } catch (Exception e) { next = -1; } if (next < 0) { next = endpointManager.getRingHead(); } String threadName = Thread.currentThread().getName(); Response responseObj = new Response(); semaphores.put(threadName, responseObj); synchronized (responseObj) { if (endpointManager.getRingHead() == next) { try { LOG.debug("Waiting for semaphone " + threadName); responseObj.wait(60000); } catch (InterruptedException e) { LOG.debug("Timeout"); } } //LOG.debug("Result is "+responseObj.getResponse()); LOG.debug("Messages from " + next + " to " + endpointManager.getRingHead()); String[] responses = endpointManager.getMessages(next); for (String resp : responses) { LOG.debug(resp); } String responseStr = endpointManager.join(responses, "\n"); response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().println(""); response.getWriter().println(responseStr); semaphores.remove(threadName); baseRequest.setHandled(true); return; } } response.setContentType("text/html; charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("Hello world!"); }
From source file:org.cerberus.service.sikuli.impl.SikuliService.java
private JSONObject generatePostParameters(String action, String locator, String text, long defaultWait) throws JSONException, IOException, MalformedURLException, MimeTypeException { JSONObject result = new JSONObject(); String picture = ""; String extension = ""; /**//from w ww . j a v a 2 s .c o m * Get Picture from URL and convert to Base64 */ if (locator != null) { URL url = new URL(locator); URLConnection connection = url.openConnection(); InputStream istream = new BufferedInputStream(connection.getInputStream()); /** * Get the MimeType and the extension */ String mimeType = URLConnection.guessContentTypeFromStream(istream); MimeTypes allTypes = MimeTypes.getDefaultMimeTypes(); MimeType mt = allTypes.forName(mimeType); extension = mt.getExtension(); /** * Encode in Base64 */ byte[] bytes = IOUtils.toByteArray(istream); picture = Base64.encodeBase64URLSafeString(bytes); } /** * Build JSONObject with parameters action : Action expected to be done * by Sikuli picture : Picture in Base64 format text : Text to type * defaultWait : Timeout for the action pictureExtension : Extension for * Base64 decoding */ result.put("action", action); result.put("picture", picture); result.put("text", text); result.put("defaultWait", defaultWait); result.put("pictureExtension", extension); return result; }
From source file:com.palantir.stash.disapprove.servlet.StaticContentServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { final String user = authenticateUser(req, res); if (user == null) { // not logged in, redirect res.sendRedirect(lup.getLoginUri(getUri(req)).toASCIIString()); return;/*from ww w .j a va 2 s .co m*/ } final String pathInfo = req.getPathInfo(); OutputStream os = null; try { // The class loader that found this class will also find the static resources ClassLoader cl = this.getClass().getClassLoader(); InputStream is = cl.getResourceAsStream(PREFIX + pathInfo); if (is == null) { res.sendError(404, "File " + pathInfo + " could not be found"); return; } os = res.getOutputStream(); //res.setContentType("text/html;charset=UTF-8"); String contentType = URLConnection.guessContentTypeFromStream(is); if (contentType == null) { contentType = URLConnection.guessContentTypeFromName(pathInfo); } if (contentType == null) { contentType = "application/binary"; } log.debug("Serving file " + pathInfo + " with content type " + contentType); res.setContentType(contentType); IOUtils.copy(is, os); /* byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = bis.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } */ } finally { if (os != null) { os.close(); } } }
From source file:at.tomtasche.reader.background.UpLoader.java
@Override public Document loadInBackground() { if (uri == DocumentLoader.URI_INTRO) { cancelLoad();/* ww w .j a va 2 s . c o m*/ return null; } String type = getContext().getContentResolver().getType(uri); if (type == null) type = URLConnection.guessContentTypeFromName(uri.toString()); if (type == null) { try { InputStream stream = getContext().getContentResolver().openInputStream(uri); try { type = URLConnection.guessContentTypeFromStream(stream); } finally { stream.close(); } } catch (Exception e) { e.printStackTrace(); } } if (type != null && (type.equals("text/html") || type.equals("text/plain") || type.equals("image/png") || type.equals("image/jpeg"))) { try { document = new Document(null); document.addPage(new Page("Document", new URI(uri.toString()), 0)); return document; } catch (URISyntaxException e) { e.printStackTrace(); } } String name = uri.getLastPathSegment(); try { name = URLEncoder.encode(name, "UTF-8"); type = URLEncoder.encode(type, "UTF-8"); } catch (Exception e) { } HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(SERVER_URL + "file?name=" + name + "&type=" + type); InputStream stream = null; try { stream = getContext().getContentResolver().openInputStream(uri); InputStreamEntity reqEntity = new InputStreamEntity(stream, -1); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { Map<String, Object> container = new Gson().fromJson(EntityUtils.toString(response.getEntity()), Map.class); String key = container.get("key").toString(); URI viewerUri = URI.create("https://docs.google.com/viewer?embedded=true&url=" + URLEncoder.encode(SERVER_URL + "file?key=" + key, "UTF-8")); document = new Document(null); document.addPage(new Page("Document", viewerUri, 0)); } else { throw new RuntimeException("server couldn't handle request"); } } catch (Throwable e) { e.printStackTrace(); lastError = e; } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { } httpclient.getConnectionManager().shutdown(); } return document; }
From source file:org.paxle.gui.impl.servlets.MetaDataIconServlet.java
@Override protected void doRequest(HttpServletRequest request, HttpServletResponse response) { try {/* w w w .j a v a 2 s. co m*/ final Context context = this.getVelocityView().createContext(request, response); final String servicePID = request.getParameter(REQ_PARAM_SERVICEPID); if (servicePID != null) { // getting the metaDataTool final MetaDataTool tool = (MetaDataTool) context.get(MetaDataTool.TOOL_NAME); if (tool == null) { this.log("No MetaDataTool found"); return; } final IMetaData metaData = tool.getMetaData(servicePID); if (metaData == null) { this.log(String.format("No metadata found for service with PID '%s'.", servicePID)); return; } // getting the icon InputStream in = metaData.getIcon(16); if (in == null) in = this.getClass().getResourceAsStream("/resources/images/cog.png"); // loading date final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); bout.close(); in.close(); // trying to detect the mimetype of the image final ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); String contentType = URLConnection.guessContentTypeFromStream(bin); bin.close(); // reading the image BufferedImage img = null; Iterator<ImageReader> readers = null; if (contentType != null) { readers = ImageIO.getImageReadersByMIMEType(contentType); while (readers != null && readers.hasNext() && img == null) { // trying the next reader 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(String.format("Unable to read metadata icon for service with PID '%s'.", servicePID), e); } finally { if (input != null) input.close(); } } } if (img != null) { response.setHeader("Content-Type", "image/png"); ImageIO.write(img, "png", response.getOutputStream()); return; } else { response.sendError(404); return; } } else { response.sendError(500, "Invalid usage"); } } catch (Throwable e) { this.log(String.format("Unexpected '%s'.", e.getClass().getName()), e); } }
From source file:org.trustedanalytics.metadata.utils.ContentDetectionUtils.java
private static Optional<MediaType> notConsumingGuessContentTypeFromStream(BufferedInputStream bin) throws IOException { Optional<MediaType> type = Optional.empty(); bin.mark(MAX_BYTES_READ_WHILE_PROBING_TYPE); try {// w ww. j ava 2 s .com String guess = URLConnection.guessContentTypeFromStream(bin); if (guess != null) { type = MediaType.fromString(guess); } } catch (IOException e) { LOGGER.error("Error while guessing stream type", e); } bin.reset(); bin.mark(0); return type; }
From source file:tilt.handler.get.TiltImageHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws TiltException { try {// w w w .j ava 2s. com imageType = ImageType.read(request.getParameter(Params.PICTYPE)); docid = request.getParameter(Params.DOCID); pageid = request.getParameter(Params.PAGEID); url = request.getParameter(Params.URL); if ((docid != null && pageid != null) || url != null) { if (url == null || url.length() == 0) url = Utils.getUrl(request.getServerName(), docid, pageid); Picture p = PictureRegistry.get(url); if (p == null) { TextIndex text = null; PictureRegistry.prune(); Double[][] coords = getCropRect(request.getServerName(), docid, pageid); Options opts = Options.get(request.getServerName(), docid); String imageUrl = Utils.getUrl(request.getServerName(), docid, pageid); String url = composeTextUrl(request, docid, pageid); String textParam = Utils.getFromUrl(url); if (textParam != null) text = new TextIndex(textParam, "en_GB"); InetAddress poster = getIPAddress(request); p = new Picture(opts, imageUrl, text, coords, poster); } byte[] pic = null; switch (imageType) { case load: p.load(); case original: pic = p.getOrigData(); break; case preflight: pic = p.getPreflightData(); break; case greyscale: pic = p.getGreyscaleData(); break; case twotone: pic = p.getTwoToneData(); break; case cleaned: pic = p.getCleanedData(); break; case reconstructed: pic = p.getReconstructedData(); break; case baselines: pic = p.getBaselinesData(); break; case words: pic = p.getWordsData(); break; case link: pic = p.getGreyscaleData(); break; } if (pic != null) { ByteArrayInputStream bis = new ByteArrayInputStream(pic); String mimeType = URLConnection.guessContentTypeFromStream(bis); response.setContentType(mimeType); ServletOutputStream sos = response.getOutputStream(); sos.write(pic); sos.close(); } else { response.getOutputStream().println("<p>image " + docid + " not found</p>"); } } else response.getOutputStream().println("<p>please specify a docid and pageid, or a url</p>"); } catch (Exception e) { throw new ImageException(e); } }
From source file:com.t3.persistence.FileUtil.java
/** * Given an InputStream this method tries to figure out what the content type might be. * @param in the InputStream to check/*from ww w. j av a 2 s .c om*/ * @return a <code>String</code> representing the content type name */ public static String getContentType(InputStream in) { String type = ""; try { type = URLConnection.guessContentTypeFromStream(in); if (log.isDebugEnabled()) log.debug("result from guessContentTypeFromStream() is " + type); } catch (IOException e) { } return type; }
From source file:org.glom.web.server.OnlineGlomImagesServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { //These match the history token keys in DetailsPlace: final String attrDocumentID = StringUtils.defaultString(req.getParameter("document")); final String attrTableName = StringUtils.defaultString(req.getParameter("table")); final String attrPrimaryKeyValue = StringUtils.defaultString(req.getParameter("value")); final String attrFieldName = StringUtils.defaultString(req.getParameter("field")); //To request a static LayoutItemImage from the document //instead of from the database: final String attrLayoutName = StringUtils.defaultString(req.getParameter("layout")); final String attrLayoutPath = StringUtils.defaultString(req.getParameter("layoutpath")); if (StringUtils.isEmpty(attrDocumentID)) { doError(resp, Response.SC_NOT_FOUND, "No document ID was specified."); return;/*w w w. j a va 2 s . c o m*/ } if (!isAuthenticated(req, attrDocumentID)) { doError(resp, Response.SC_NOT_FOUND, "No access to the document.", attrDocumentID); return; } if (StringUtils.isEmpty(attrTableName)) { doError(resp, Response.SC_NOT_FOUND, "No table name was specified.", attrDocumentID); return; } //TODO: Is it from the database or is it a static LayouteItemText from the document. final boolean fromDb = !StringUtils.isEmpty(attrPrimaryKeyValue); final boolean fromLayout = !StringUtils.isEmpty(attrLayoutName); if (!fromDb && !fromLayout) { doError(resp, Response.SC_NOT_FOUND, "No primary key value or layout name was specified.", attrDocumentID); return; } if (fromDb && StringUtils.isEmpty(attrFieldName)) { doError(resp, Response.SC_NOT_FOUND, "No field name was specified.", attrDocumentID); return; } final ConfiguredDocument configuredDocument = getDocument(attrDocumentID); if (configuredDocument == null) { doError(resp, Response.SC_NOT_FOUND, "The specified document was not found.", attrDocumentID); return; } final Document document = configuredDocument.getDocument(); if (document == null) { doError(resp, Response.SC_NOT_FOUND, "The specified document details were not found.", attrDocumentID); return; } byte[] bytes = null; if (fromDb) { bytes = getImageFromDatabase(req, resp, attrDocumentID, attrTableName, attrPrimaryKeyValue, attrFieldName, configuredDocument, document); } else { bytes = getImageFromDocument(req, resp, attrDocumentID, attrTableName, attrLayoutName, attrLayoutPath, configuredDocument, document); } if (bytes == null) { doError(resp, Response.SC_NOT_FOUND, "The image bytes could not be found. Please see the earlier error.", attrDocumentID); return; } final InputStream is = new ByteArrayInputStream(bytes); final String contentType = URLConnection.guessContentTypeFromStream(is); resp.setContentType(contentType); // Set content size: resp.setContentLength((int) bytes.length); // Open the output stream: final OutputStream out = resp.getOutputStream(); // Copy the contents to the output stream out.write(bytes); out.close(); }
From source file:net.rptools.assets.supplier.AbstractURIAssetSupplier.java
/** * Create an asset and determine its format. * @param id id of asset//from ww w. j ava2 s .c o m * @param type type of asset * @param listener listener to inform of (partial) completion * @param assetLength length, if known, or -1 * @param stream stream to read * @return asset * @throws IOException I/O problems */ @ThreadPolicy(ThreadPolicy.ThreadId.ANY) protected AssetImpl newAsset(final String id, final Type type, final AssetListener listener, final int assetLength, final InputStream stream) throws IOException { final InputStream input = new InputStreamInterceptor(getComponent().getFramework(), id, assetLength, stream, listener, getNotifyInterval()); final PushbackInputStream pushbackStream = new PushbackInputStream(input, PUSHBACK_LIMIT); final byte[] firstBytes = new byte[PUSHBACK_LIMIT]; final int actualLength = pushbackStream.read(firstBytes); if (actualLength != -1) { pushbackStream.unread(firstBytes, 0, actualLength); } final ByteArrayInputStream bais = new ByteArrayInputStream(firstBytes); final String mimeType = URLConnection.guessContentTypeFromStream(bais); LOGGER.debug("mimeType={}, actualLength={}", mimeType, actualLength); // read in image AssetImpl asset = null; switch (type) { case IMAGE: asset = new AssetImpl(new Image(pushbackStream)); asset.setMimetype(mimeType); break; case TEXT: asset = new AssetImpl(IOUtils.toString(pushbackStream, StandardCharsets.UTF_8.name())); asset.setMimetype(mimeType); break; default: break; } if (listener != null) { listener.notify(id, asset); } return asset; }