Example usage for java.net URLConnection getContentType

List of usage examples for java.net URLConnection getContentType

Introduction

In this page you can find the example usage for java.net URLConnection getContentType.

Prototype

public String getContentType() 

Source Link

Document

Returns the value of the content-type header field.

Usage

From source file:InstallJars.java

/**
 * Install a Zip/Jar file.// w w  w.j a  va2  s  . c o  m
 * 
 * @param fileUrl
 *          The file/zip/jar file
 * @param targetPath
 *          root of directory or file to install into
 * @param doExpand
 * @param doRun
 * @exception IOException
 *              Thrown if a JAR file access error occurs
 */
public void installFile(String fileUrl, String targetPath, boolean doExpand, boolean doRun) throws IOException {
    String targetFilename = new File(targetPath).getCanonicalPath().replace('\\', '/');
    println("Installing in " + targetFilename);
    URL url = new URL(fileUrl);
    URLConnection conn = url.openConnection();
    // System.out.println("Conn = " + conn);
    String ctype = conn.getContentType();
    println("Content type is " + ctype);
    String extension = getExtension(fileUrl);
    if (extension.equals("class")) {
        installClass(conn, targetFilename, doExpand, doRun);
        // println("Installed class file " + fileUrl + "; please run");
    } else if (extension.equalsIgnoreCase("zip")) {
        installZip(conn, targetFilename, doExpand, doRun);
        // println("Installed ZIP file " + fileUrl + "; ZIP expanded");
    } else if (extension.equalsIgnoreCase("gz")) {
        installGZip(conn, targetFilename, doExpand, doRun);
        // println("Installed GZIP file " + fileUrl + "; ZIP expanded");
    } else if (extension.equalsIgnoreCase("jar")) {
        installJar(conn, targetFilename, doExpand, doRun);
        // System.out.println("Installed JAR file " + fileUrl + "; please add to
        // CLASSPATH");
    } else {
        throw new IllegalArgumentException("Unknown extension - " + extension);
    }
}

From source file:org.getobjects.appserver.publisher.GoResource.java

@Override
public void appendToResponse(final WOResponse _r, final WOContext _ctx) {
    URLConnection con = null;
    try {//from www. j  a  v  a  2 s . com
        con = this.url.openConnection();
    } catch (IOException coe) {
        log.warn("could not open connection to url: " + this.url);
        _r.setStatus(WOMessage.HTTP_STATUS_NOT_FOUND);
        return;
    }

    /* open stream */

    InputStream is = null;
    try {
        is = con.getInputStream();
    } catch (IOException ioe) {
        log.warn("could not open stream to url: " + this.url);
        _r.setStatus(WOMessage.HTTP_STATUS_NOT_FOUND);
        return;
    }

    /* transfer */

    try {
        String mimeType = con.getContentType();
        if (mimeType == null || "content/unknown".equals(mimeType))
            mimeType = mimeTypeForPath(this.url.getPath());

        if (mimeType == null)
            mimeType = "application/octet-stream";

        _r.setHeaderForKey(mimeType, "content-type");
        _r.setHeaderForKey("" + con.getContentLength(), "content-length");

        /* setup caching headers */

        Date now = new Date();
        GregorianCalendar cal = new GregorianCalendar();

        cal.setTime(new Date(con.getLastModified()));
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "last-modified");

        cal.setTime(now);
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "date");

        cal.add(Calendar.SECOND, this.expirationIntervalForMimeType(mimeType));
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "expires");

        /* start streaming */

        _r.enableStreaming();

        byte[] buffer = new byte[0xFFFF];
        for (int len; (len = is.read(buffer)) != -1;)
            _r.appendContentData(buffer, len);
    } catch (IOException e) {
        log.error("IO error trying to deliver resource: " + this.url, e);
        _r.setStatus(WOMessage.HTTP_STATUS_INTERNAL_ERROR);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
            log.warn("could not close URL input stream: " + this.url, e);
        }
    }
}

From source file:org.getobjects.appserver.publisher.JoResource.java

@Override
public void appendToResponse(WOResponse _r, WOContext _ctx) {
    URLConnection con = null;
    try {//from  ww  w . j  av a  2s .c  om
        con = this.url.openConnection();
    } catch (IOException coe) {
        log.warn("could not open connection to url: " + this.url);
        _r.setStatus(WOMessage.HTTP_STATUS_NOT_FOUND);
        return;
    }

    /* open stream */

    InputStream is = null;
    try {
        is = con.getInputStream();
    } catch (IOException ioe) {
        log.warn("could not open stream to url: " + this.url);
        _r.setStatus(WOMessage.HTTP_STATUS_NOT_FOUND);
        return;
    }

    /* transfer */

    try {
        String mimeType = con.getContentType();
        if (mimeType == null || "content/unknown".equals(mimeType))
            mimeType = mimeTypeForPath(this.url.getPath());

        if (mimeType == null)
            mimeType = "application/octet-stream";

        _r.setHeaderForKey(mimeType, "content-type");
        _r.setHeaderForKey("" + con.getContentLength(), "content-length");

        /* setup caching headers */

        Date now = new Date();
        GregorianCalendar cal = new GregorianCalendar();

        cal.setTime(new Date(con.getLastModified()));
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "last-modified");

        cal.setTime(now);
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "date");

        cal.add(Calendar.SECOND, this.expirationIntervalForMimeType(mimeType));
        _r.setHeaderForKey(WOMessage.httpFormatDate(cal), "expires");

        /* start streaming */

        _r.enableStreaming();

        byte[] buffer = new byte[0xFFFF];
        for (int len; (len = is.read(buffer)) != -1;)
            _r.appendContentData(buffer, len);
    } catch (IOException e) {
        log.error("IO error trying to deliver resource: " + this.url, e);
        _r.setStatus(WOMessage.HTTP_STATUS_INTERNAL_ERROR);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
            log.warn("could not close URL input stream: " + this.url, e);
        }
    }
}

From source file:com.google.ratel.deps.io.input.XmlStreamReader.java

/**
 * Creates a Reader using the InputStream of a URLConnection.
 * <p>/* w  ww. j  a  v a 2s  . c o  m*/
 * If the URLConnection is not of type HttpURLConnection and there is not
 * 'content-type' header in the fetched data it uses the same logic used for
 * files.
 * <p>
 * If the URLConnection is a HTTP Url or there is a 'content-type' header in
 * the fetched data it uses the same logic used for an InputStream with
 * content-type.
 * <p>
 * It does a lenient charset encoding detection, check the constructor with
 * the lenient parameter for details.
 *
 * @param conn URLConnection to create a Reader from.
 * @param defaultEncoding The default encoding
 * @throws IOException thrown if there is a problem reading the stream of
 *         the URLConnection.
 */
public XmlStreamReader(URLConnection conn, String defaultEncoding) throws IOException {
    this.defaultEncoding = defaultEncoding;
    boolean lenient = true;
    String contentType = conn.getContentType();
    InputStream is = conn.getInputStream();
    BOMInputStream bom = new BOMInputStream(new BufferedInputStream(is, BUFFER_SIZE), false, BOMS);
    BOMInputStream pis = new BOMInputStream(bom, true, XML_GUESS_BYTES);
    if (conn instanceof HttpURLConnection || contentType != null) {
        this.encoding = doHttpStream(bom, pis, contentType, lenient);
    } else {
        this.encoding = doRawStream(bom, pis, lenient);
    }
    this.reader = new InputStreamReader(pis, encoding);
}

From source file:InstallJars.java

public void installZip(URLConnection conn, String target, boolean doExpand, boolean doRun) throws IOException {
    // doRun not used on htis type
    if (doExpand) {
        String ctype = conn.getContentType();
        if (!ctype.equals("application/zip")) {
            throw new IllegalArgumentException("Unkexpected content type - " + ctype);
        }//from w  w  w  .  j  av a2s .c  om
        println("Expanding ZIP file to " + target + " from " + conn.getURL().toExternalForm());
        ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream(conn.getInputStream(), BLOCK_SIZE * BLOCK_COUNT));
        int count = 0;
        prepDirs(target, true);
        try {
            for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
                copyEntry(target, zis, ze);
                // zis.closeEntry();
                count++;
            }
        } finally {
            try {
                zis.close();
            } catch (IOException ioe) {
            }
        }
        println("Installed " + count + " files/directories");
    } else {
        print("Installing ZIP file " + target + " from " + conn.getURL().toExternalForm());
        copyStream(conn, target);
        println();
    }
}

From source file:org.apache.sling.jcr.contentloader.internal.BundleContentLoader.java

/**
 * Create a file from the given url./*w ww .  j  a v a2 s.com*/
 *
 * @param configuration
 * @param parent
 * @param source
 * @param createdNodes
 * @param contentCreator
 * @throws IOException
 * @throws RepositoryException
 */
private void createFile(PathEntry configuration, Node parent, URL source, List<String> createdNodes,
        final DefaultContentCreator contentCreator) throws IOException, RepositoryException {

    final String srcPath = source.getPath();
    int pos = srcPath.lastIndexOf("/");
    final String name = getName(source.getPath());
    final String path;
    if (pos == -1) {
        path = name;
    } else {
        path = srcPath.substring(0, pos + 1) + name;
    }

    contentCreator.init(configuration, getContentReaders(), createdNodes, null);
    contentCreator.prepareParsing(parent, name);
    final URLConnection conn = source.openConnection();
    final long lastModified = Math.min(conn.getLastModified(), configuration.getLastModified());
    final String type = conn.getContentType();
    final InputStream data = conn.getInputStream();
    contentCreator.createFileAndResourceNode(path, data, type, lastModified);
    contentCreator.finishNode();
    contentCreator.finishNode();
}

From source file:InstallJars.java

public void installGZip(URLConnection conn, String target, boolean doExpand, boolean doRun) throws IOException {
    // doRun not used on htis type
    if (doExpand) {
        String ctype = conn.getContentType();
        if (!ctype.equals("application/x-tar")) {
            throw new IllegalArgumentException("Unkexpected content type - " + ctype);
        }//from   ww  w .j av a2 s .  c om
        print("Expanding GZIP file to " + target + " from " + conn.getURL().toExternalForm());
        prepDirs(target, false);
        GZIPInputStream zis = new GZIPInputStream(
                new BufferedInputStream(conn.getInputStream(), BLOCK_SIZE * BLOCK_COUNT));
        try {
            // BufferedOutputStream os = new BufferedOutputStream(new
            // FileOutputStream(target), BLOCK_SIZE * BLOCK_COUNT);
            // try {
            // byte[] buf = new byte[bufferSize];
            // for (int size = zis.read(buf, 0, buf.length), count = 0;
            // size >= 0;
            // size = zis.read(buf, 0, buf.length), count++) {
            // //if (count % 4 == 0) print(".");
            // os.write(buf, 0, size);
            // }
            // }
            // finally {
            // try { os.flush(); os.close(); } catch (IOException ioe) {}
            // }
            pumpGZip(target, zis);
        } finally {
            try {
                zis.close();
            } catch (IOException ioe) {
            }
        }
        println();
    } else {
        print("Installing GZIP file " + target + " from " + conn.getURL().toExternalForm());
        copyStream(conn, target);
        println();
    }
}

From source file:com.ibm.jaggr.service.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Replace <code>url(&lt;<i>relative-path</i>&gt;)</code> references in the
 * input CSS with/*from www.  j  a v a2s  .  c  o m*/
 * <code>url(data:&lt;<i>mime-type</i>&gt;;&lt;<i>base64-encoded-data</i>&gt;</code>
 * ). The conversion is controlled by option settings as described in
 * {@link CSSModuleBuilder}.
 * 
 * @param css
 *            The input CSS
 * @param uri
 *            The URI for the input CSS
 * @return The transformed CSS with images in-lined as determined by option
 *         settings.
 */
protected String inlineImageUrls(HttpServletRequest req, String css, IResource res) {
    if (imageSizeThreshold == 0 && inlinedImageIncludeList.size() == 0) {
        // nothing to do
        return css;
    }

    // In-lining of imports can be disabled by request parameter for debugging
    if (!TypeUtil.asBoolean(req.getParameter(INLINEIMAGES_REQPARAM_NAME), true)) {
        return css;
    }

    StringBuffer buf = new StringBuffer();
    Matcher m = urlPattern.matcher(css);
    while (m.find()) {
        String fullMatch = m.group(0);
        String urlMatch = m.group(1);

        // remove quotes.
        urlMatch = quotedStringPattern.matcher(urlMatch).replaceAll(""); //$NON-NLS-1$
        urlMatch = forwardSlashPattern.matcher(urlMatch).replaceAll("/"); //$NON-NLS-1$

        // Don't do anything with non-relative URLs
        if (urlMatch.startsWith("/") || urlMatch.startsWith("#") || protocolPattern.matcher(urlMatch).find()) { //$NON-NLS-1$ //$NON-NLS-2$
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }

        URI imageUri = res.getURI().resolve(urlMatch);
        boolean exclude = false, include = false;

        // Determine if this image is in the include list
        for (Pattern regex : inlinedImageIncludeList) {
            if (regex.matcher(imageUri.getPath()).find()) {
                include = true;
                break;
            }
        }

        // Determine if this image is in the exclude list
        for (Pattern regex : inlinedImageExcludeList) {
            if (regex.matcher(imageUri.getPath()).find()) {
                exclude = true;
                break;
            }
        }
        // If there's an include list, then only the files in the include list
        // will be inlined
        if (inlinedImageIncludeList.size() > 0 && !include || exclude) {
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }

        boolean imageInlined = false;
        InputStream in = null;
        try {
            // In-line the image.
            URLConnection connection = imageUri.toURL().openConnection();
            in = connection.getInputStream();
            int size = connection.getContentLength();
            String type = connection.getContentType();
            if (type == null) {
                type = "content/unknown"; //$NON-NLS-1$
            }
            if (include || inlineableImageTypes.contains(type) && size <= imageSizeThreshold) {
                String base64 = getBase64(connection);
                m.appendReplacement(buf, ""); //$NON-NLS-1$
                buf.append("url('data:" + type + //$NON-NLS-1$
                        ";base64," + base64 + "')"); //$NON-NLS-1$ //$NON-NLS-2$
                imageInlined = true;
            }
        } catch (IOException ex) {
            if (log.isLoggable(Level.WARNING)) {
                log.log(Level.WARNING,
                        MessageFormat.format(Messages.CSSModuleBuilder_0, new Object[] { imageUri }), ex);
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignore) {
                }
            }
        }
        if (!imageInlined) {
            // Image not in-lined.  Write the original URL
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
        }
    }
    m.appendTail(buf);
    return buf.toString();
}

From source file:stringreplacer.rewriting.RewriterServlet.java

/**
 * This method in the entry-point for forwarding all HTTP requests made.
 *///  w ww .  j  av  a2s  .c  om
protected void doRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {

    /* We code the origin server name as the first directory in the URL
     * being requested. This would normally be setup in an Apache
     * ProxyPass setting. Here we slice out the origin server name from
     * the URL.
     */
    final String origin;
    {
        String pathInfo = request.getPathInfo();
        String[] pathSplit = StringUtils.split(pathInfo, "/");

        if (pathSplit.length == 0) {
            throw new IOException("No origin servername specified on url");
        } else {
            origin = pathSplit[0];
        }
    }

    /* Since the requesting url that was forwarded is placed after the origin
     * server name as a directory, we need to remove the origin server name
     * and get the full URL with query parameters being requested.
     */
    final String path;
    {
        String uri = request.getRequestURI();
        String query = isNotEmpty(request.getQueryString()) ? "?" + request.getQueryString() : "";
        int forwardUriPos = uri.indexOf(origin) + origin.length();
        path = uri.substring(forwardUriPos) + query;
    }

    final URLConnection connection;

    try {
        connection = openUrlConnection(origin, path, request);
        log("Opening: " + connection);
    } catch (FileNotFoundException fnfe) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    /* We now search the content type of all forwarded requests for content
     * types that start with our matching strings because it will be only
     * these content types that we will act upon to rewrite string data.
     */
    boolean matching = false;
    {
        final String originContentType = connection.getContentType().trim().toLowerCase();
        for (String contentType : targetContentTypes) {
            matching = originContentType.startsWith(contentType);
            if (matching) {
                break;
            }
        }
    }

    /* We need to pass all headers that were sent from the origin server
     * to the client, otherwise the client will get a bunch of garbage
     * like raw gzipped output.
     */
    {
        for (String key : connection.getHeaderFields().keySet()) {
            String value = connection.getHeaderField(key);

            /* We have received a HTTP relocation request. We will want to
             * rewrite this url as well. */
            if (key != null && key.trim().equalsIgnoreCase("Location")) {
                log("Redirect: " + value + " => ");
                value = processStringWithRewriters(value);
                log(value);
            }

            response.setHeader(key, value);
        }

        response.setContentType(connection.getContentType());
    }

    /* Use memory to buffer origin request stream otherwise we might experience
     * some hiccups in performance. */
    InputStream in = null;

    try {
        in = new BufferedInputStream(connection.getInputStream());

        // Rewrite the input stream
        if (matching) {
            in = attachNestedStreams(in);
            copyFromOrigin(in, response);

            // Do nothing and just copy it
        } else {
            copyFromOrigin(in, response);
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:ubic.gemma.image.aba.AllenBrainAtlasServiceImpl.java

private void showHeader(URLConnection url) {

    this.infoOut.println("");
    this.infoOut.println("URL              : " + url.getURL().toString());
    this.infoOut.println("Content-Type     : " + url.getContentType());
    this.infoOut.println("Content-Length   : " + url.getContentLength());
    if (url.getContentEncoding() != null)
        this.infoOut.println("Content-Encoding : " + url.getContentEncoding());
}