List of usage examples for java.net URLConnection getContentType
public String getContentType()
From source file:com.nominanuda.web.mvc.URLStreamer.java
private String determineContentType(URL url, URLConnection conn) { String ct = conn.getContentType(); if (ct == null || "content/unknown".equals(ct)) { ct = mimeHelper.guessContentTypeFromPath(url.toString()); //TODO add default charset if contenttype is textual }//from www .ja v a2 s . c om if (ct == null) { ct = defaultContentType; } return ct; }
From source file:com.occamlab.te.parsers.ImageParser.java
public static Document parse(URLConnection uc, Element instruction, PrintWriter logger) { Document doc = null;// w ww . j av a 2 s. co m InputStream is = null; try { is = uc.getInputStream(); doc = parse(is, instruction, logger); } catch (Exception e) { String msg = String.format("Failed to parse %s resource from %s \n %s", uc.getContentType(), uc.getURL(), e.getMessage()); jlogger.warning(msg); } finally { if (null != is) { try { is.close(); } catch (IOException e) { } } } return doc; }
From source file:com.vmware.thinapp.common.util.AfUtil.java
/** * Attempt to download the icon specified by the given URL. If the resource at the URL * has a content type of image/*, the binary data for this resource will be downloaded. * * @param iconUrlStr URL of the image resource to access * @return the binary data and content type of the image resource at the given URL, null * if the URL is invalid, the resource does not have a content type starting with image/, or * on some other failure./*from w w w.j a v a 2 s . c om*/ */ public static final @Nullable IconInfo getIconInfo(String iconUrlStr) { if (!StringUtils.hasLength(iconUrlStr)) { log.debug("No icon url exists."); return null; } URL iconUrl = null; try { // Need to encode any invalid characters before creating the URL object iconUrl = new URL(UriUtils.encodeHttpUrl(iconUrlStr, "UTF-8")); } catch (MalformedURLException ex) { log.debug("Malformed icon URL string: {}", iconUrlStr, ex); return null; } catch (UnsupportedEncodingException ex) { log.debug("Unable to encode icon URL string: {}", iconUrlStr, ex); return null; } // Open a connection with the given URL final URLConnection conn; final InputStream inputStream; try { conn = iconUrl.openConnection(); inputStream = conn.getInputStream(); } catch (IOException ex) { log.debug("Unable to open connection to URL: {}", iconUrlStr, ex); return null; } String contentType = conn.getContentType(); int sizeBytes = conn.getContentLength(); try { // Make sure the resource has an appropriate content type if (!conn.getContentType().startsWith("image/")) { log.debug("Resource at URL {} does not have a content type of image/*.", iconUrlStr); return null; // Make sure the resource is not too large } else if (sizeBytes > MAX_ICON_SIZE_BYTES) { log.debug("Image resource at URL {} is too large: {}", iconUrlStr, sizeBytes); return null; } else { // Convert the resource to a byte array byte[] iconBytes = ByteStreams.toByteArray(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return inputStream; } }); return new IconInfo(iconBytes, contentType); } } catch (IOException e) { log.debug("Error reading resource data.", e); return null; } finally { Closeables.closeQuietly(inputStream); } }
From source file:com.ramforth.webserver.http.modules.HttpUrlModule.java
private void addContentTypeHeaderForURL(IHttpResponse httpResponse, URLConnection urlConnection) { String mimeType = urlConnection.getContentType(); if (StringUtilities.isNullOrEmpty(mimeType) || "content/unknown".equals(mimeType)) { String extension = FilenameUtils.getExtension(urlConnection.getURL().getPath()); mimeType = "application/octet-stream"; if (!StringUtilities.isNullOrEmpty(extension)) { String mimeType2 = MimeTypeMap.getInstance().getMimeTypeForExtension(extension); if (mimeType2 != null) { mimeType = mimeType2;/*from w w w. j a v a 2 s . c o m*/ } } } httpResponse.setContentType(mimeType); }
From source file:bolts.WebViewAppLinkResolver.java
/** * Gets a string with the proper encoding (including using the charset specified in the MIME type * of the request) from a URLConnection. *///w w w .ja va2s. c om private static String readFromConnection(URLConnection connection) throws IOException { InputStream stream; if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; try { stream = connection.getInputStream(); } catch (Exception e) { stream = httpConnection.getErrorStream(); } } else { stream = connection.getInputStream(); } try { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = 0; while ((read = stream.read(buffer)) != -1) { output.write(buffer, 0, read); } String charset = connection.getContentEncoding(); if (charset == null) { String mimeType = connection.getContentType(); String[] parts = mimeType.split(";"); for (String part : parts) { part = part.trim(); if (part.startsWith("charset=")) { charset = part.substring("charset=".length()); break; } } if (charset == null) { charset = "UTF-8"; } } return new String(output.toByteArray(), charset); } finally { stream.close(); } }
From source file:org.polymap.rap.openlayers.util.ProxyServlet.java
private void doProxy(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (getServletConfig().getInitParameter("host_list") == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "There is no Host-List for this Servlet"); return;//from w w w . j a va 2 s . com } List<String> host_list = Arrays.asList(getServletConfig().getInitParameter("host_list").split(",")); String url_param = null; url_param = request.getParameter("url"); if (url_param == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "URL Parameter Missing"); return; } try { URL url = new URL(url_param); /* Check if the host is in the list of allowed hosts */ if (!host_list.contains(url.getHost())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "URL Parameter Bad - the Host " + url.getHost() + " is not in my list of valid Hosts!"); return; } URLConnection con = url.openConnection(); if (con.getContentType() != null) response.setContentType(con.getContentType()); else response.setContentType("text/xml"); /* check if the client accepts gzip Encoding */ boolean client_accepts_gzip = false; // be pessimistic if (request.getHeader("Accept-Encoding") != null) { List<String> encoding_list = Arrays.asList(request.getHeader("Accept-Encoding").split(",")); client_accepts_gzip = (encoding_list.contains("gzip")); } response.setDateHeader("Date", System.currentTimeMillis()); if (client_accepts_gzip) { response.setHeader("Content-Encoding", "gzip"); ByteArrayOutputStream output_to_tmp = new ByteArrayOutputStream(); IOUtils.copy(url.openStream(), output_to_tmp); OutputStream output_to_response = new GZIPOutputStream(response.getOutputStream()); output_to_response.write(output_to_tmp.toByteArray()); output_to_response.close(); } else { // client will not accept gzip -> dont compress IOUtils.copy(url.openStream(), response.getOutputStream()); } } catch (IOException e) { System.out.println("Err" + e); response.sendError(HttpServletResponse.SC_NOT_FOUND, "Err:" + e); } }
From source file:org.apache.synapse.config.SynapseConfigUtils.java
/** * Get an object from a given URL. Will first fetch the content from the * URL and depending on the content-type, a suitable XMLToObjectMapper * (if available) would be used to transform this content into an Object. * If a suitable XMLToObjectMapper cannot be found, the content would be * treated as XML and an OMNode would be returned * * @param url the URL to the resource//from w ww . j a v a2 s. c om * @param properties bag of properties to pass in any information to the factory * @return an Object created from the given URL */ public static Object getObject(URL url, Properties properties) { try { if (url != null && "file".equals(url.getProtocol())) { try { url.openStream(); } catch (IOException ignored) { String path = url.getPath(); if (log.isDebugEnabled()) { log.debug("Can not open a connection to the URL with a path :" + path); } String synapseHome = (String) properties.get(SynapseConstants.SYNAPSE_HOME); if (synapseHome != null) { if (log.isDebugEnabled()) { log.debug("Trying to resolve an absolute path of the " + " URL using the synapse.home : " + synapseHome); } if (synapseHome.endsWith("/")) { synapseHome = synapseHome.substring(0, synapseHome.lastIndexOf("/")); } url = new URL(url.getProtocol() + ":" + synapseHome + "/" + path); try { url.openStream(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to resolve an absolute path of the " + " URL using the synapse.home : " + synapseHome); } log.warn("IO Error reading from URL " + url.getPath() + e); } } } } if (url == null) { return null; } URLConnection connection = getURLConnection(url); if (connection == null) { if (log.isDebugEnabled()) { log.debug("Cannot create a URLConnection for given URL : " + url); } return null; } XMLToObjectMapper xmlToObject = getXmlToObjectMapper(connection.getContentType()); InputStream inputStream = connection.getInputStream(); try { XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement omElem = builder.getDocumentElement(); // detach from URL connection and keep in memory // TODO remove this omElem.build(); if (xmlToObject != null) { return xmlToObject.getObjectFromOMNode(omElem, properties); } else { return omElem; } } catch (XMLStreamException e) { if (log.isDebugEnabled()) { log.debug("Content at URL : " + url + " is non XML.."); } return readNonXML(url); } catch (OMException e) { if (log.isDebugEnabled()) { log.debug("Content at URL : " + url + " is non XML.."); } return readNonXML(url); } finally { inputStream.close(); } } catch (IOException e) { handleException("Error connecting to URL : " + url, e); } return null; }
From source file:org.openstatic.http.HttpResponse.java
/** Set the entire response body to the resource represented by this URL object, this will be buffered entirely before relay. */ public void setBufferedData(URL url) { try {/*from w ww. j av a2 s. com*/ URLConnection urlc = url.openConnection(); this.setBufferedData(urlc.getInputStream(), urlc.getContentType()); } catch (Exception e) { this.responseCode = "500 Server Error"; } }
From source file:org.eclipse.smarthome.core.audio.URLAudioStream.java
private InputStream createInputStream() throws AudioException { try {// w w w . j a v a2 s . co m if (url.toLowerCase().endsWith(".m3u")) { InputStream is = new URL(url).openStream(); String urls = IOUtils.toString(is); for (String line : urls.split("\n")) { if (!line.isEmpty() && !line.startsWith("#")) { url = line; break; } } } else if (url.toLowerCase().endsWith(".pls")) { InputStream is = new URL(url).openStream(); String urls = IOUtils.toString(is); for (String line : urls.split("\n")) { if (!line.isEmpty() && line.startsWith("File")) { Matcher matcher = plsStreamPattern.matcher(line); if (matcher.find()) { url = matcher.group(1); break; } } } } URL streamUrl = new URL(url); URLConnection connection = streamUrl.openConnection(); InputStream is = null; if (connection.getContentType().equals("unknown/unknown")) { // Java does not parse non-standard headers used by SHOUTCast int port = streamUrl.getPort() > 0 ? streamUrl.getPort() : 80; // Manipulate User-Agent to receive a stream shoutCastSocket = new Socket(streamUrl.getHost(), port); OutputStream os = shoutCastSocket.getOutputStream(); String user_agent = "WinampMPEG/5.09"; String req = "GET / HTTP/1.0\r\nuser-agent: " + user_agent + "\r\nIcy-MetaData: 1\r\nConnection: keep-alive\r\n\r\n"; os.write(req.getBytes()); is = shoutCastSocket.getInputStream(); } else { // getInputStream() method is more error-proof than openStream(), // because openStream() does openConnection().getInputStream(), // which opens a new connection and does not reuse the old one. is = connection.getInputStream(); } return is; } catch (MalformedURLException e) { logger.error("URL '{}' is not a valid url : '{}'", url, e.getMessage()); throw new AudioException("URL not valid"); } catch (IOException e) { logger.error("Cannot set up stream '{}': {}", url, e); throw new AudioException("IO Error"); } }
From source file:net.pms.medialibrary.commons.helpers.FileImportHelper.java
/** * Saves the file specified by the url to the file saveFileName * @param url url of the file to save/*w w w .j a v a 2s . co m*/ * @param saveFileName absolute path to save the file to * @throws IOException thrown if the save operation failed or the content type of the file was of type text */ public static void saveUrlToFile(String url, String saveFileName) throws IOException { URL u = new URL(url); URLConnection uc = u.openConnection(); String contentType = uc.getContentType(); int contentLength = uc.getContentLength(); if (contentType.startsWith("text/") || contentLength == -1) { throw new IOException("This is not a binary file."); } InputStream raw = uc.getInputStream(); InputStream in = new BufferedInputStream(raw); byte[] data = new byte[contentLength]; int bytesRead = 0; int offset = 0; while (offset < contentLength) { bytesRead = in.read(data, offset, data.length - offset); if (bytesRead == -1) break; offset += bytesRead; } in.close(); if (offset != contentLength) { throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes"); } FileOutputStream out = new FileOutputStream(saveFileName); out.write(data); out.flush(); out.close(); log.debug(String.format("Saved url='%s' to file='%s'", url, saveFileName)); }