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:net.sf.jabref.logic.net.URLDownload.java

public String determineMimeType() throws IOException {
    // this does not cause a real performance issue as the underlying HTTP/TCP connection is reused
    URLConnection urlConnection = openConnection();
    try {//from w w w  .j  av  a 2s  .c om
        return urlConnection.getContentType();
    } finally {
        try {
            urlConnection.getInputStream().close();
        } catch (IOException ignored) {
            // Ignored
        }
    }
}

From source file:net.sf.firemox.deckbuilder.BuildBook.java

/**
 * @param cardName//from w  ww  .ja  v  a 2 s.co m
 *          the key card name.
 * @return the image associated to this card
 * @throws BadElementException
 * @throws IOException
 *           If some other I/O error occurs
 */
@SuppressWarnings("null")
public Image getImage(String cardName) throws BadElementException, IOException {
    Iterator<String> i = null;
    i = cachedImageDir.iterator();
    File img = null;
    while (i.hasNext()) {
        String[] extensions = new String[] { ".jpg", ".jpeg", ".png", ".gif", ".tiff" };
        String base = i.next();
        for (int j = 0; j < extensions.length; j++) {
            img = new File(base, cardName.toLowerCase() + extensions[j]);
            if (img.exists()) {
                break;
            }
            img = null;
        }
        if (img != null)
            break;
        img = null;
    }
    if (img != null) {
        java.awt.Image awtImage = Toolkit.getDefaultToolkit().createImage(img.getAbsolutePath());
        java.awt.Image awtImageX4 = awtImage.getScaledInstance(800, -1, java.awt.Image.SCALE_SMOOTH);
        awtImage = null;
        return Image.getInstance(awtImageX4, null);
    }

    i = imageSources.iterator();
    while (i.hasNext()) {
        String urlpath = i.next();
        urlpath = urlpath.replace("{name}", cardName);
        URL url = new URL(urlpath);
        URLConnection cn = url.openConnection();
        if (cn.getContentType() == null
                || cn.getContentType().startsWith("image") && cn.getInputStream() != null) {
            img = new File(this.cachedImageDirStore, cardName.toLowerCase() + ".jpg");
            BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(img));
            BufferedInputStream is = new BufferedInputStream(cn.getInputStream());

            IOUtils.copy(is, fw);
            fw.close();

            java.awt.Image awtImage = Toolkit.getDefaultToolkit().createImage(img.getAbsolutePath());
            java.awt.Image awtImageX4 = null;
            awtImageX4 = awtImage.getScaledInstance(800, -1, java.awt.Image.SCALE_SMOOTH);
            return Image.getInstance(awtImageX4, null);
        }
    }
    return Image.getInstance(this.dedfaultImage);
}

From source file:org.openstatic.http.HttpResponse.java

/** Set the entire response body to the resource represented by this URL object, it will be relayed as read. */
public void setData(URL url) {
    try {//from ww  w .j a  v  a2s.  c om
        URLConnection urlc = url.openConnection();
        this.data = urlc.getInputStream();
        this.contentType = urlc.getContentType();
        this.dataLength = urlc.getContentLength();
    } catch (Exception e) {
        this.responseCode = "500 Server Error";
    }
}

From source file:info.joseluismartin.gtc.mvc.CacheController.java

private void proxyConnection(HttpServletRequest req, HttpServletResponse resp, String requestString,
        TileCache cache, String remoteUrlString, URL remoteUrl) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("Can't parse tile url [" + requestString + "], proxy to: " + remoteUrlString);
    }//w w w.j a  va 2 s.c om

    URLConnection conn = getConnection(remoteUrl);
    resp.setContentType(conn.getContentType());
    InputStream is = cache.parseResponse(conn.getInputStream(), remoteUrlString, getContextUrl(req));
    IOUtils.copy(is, resp.getOutputStream());

}

From source file:org.n52.wps.server.feed.AlgorithmFeed.java

private long testFeed() throws IOException {
    long lastFeedUpdate = 0;

    try {/*w ww  . j  a  v a  2s  . c om*/
        URL url = new URL(feedURL);
        URLConnection conn = url.openConnection();

        // TODO implement checks on MimeType
        String contentType = conn.getContentType();
        if (!contentType.equalsIgnoreCase(ZIP_MIME_TYPE)) {
            LOGGER.warn("Uncommon MimeType found at Feed URL: " + contentType);
        }
        lastFeedUpdate = conn.getLastModified();
    } catch (MalformedURLException e) {
        LOGGER.error("Invalid feedURL: " + feedURL);
        throw new IOException();
    } catch (IOException e) {
        LOGGER.error("Error connecting to feedURL: " + feedURL);
        throw new IOException();
    }
    return lastFeedUpdate;
}

From source file:org.moyrax.javascript.shell.Global.java

private static String readUrl(String filePath, String charCoding, boolean urlIsFile) throws IOException {
    int chunkLength;
    InputStream is = null;// w w w  .j a v  a2  s .  co m
    try {
        if (!urlIsFile) {
            URL urlObj = new URL(filePath);
            URLConnection uc = urlObj.openConnection();
            is = uc.getInputStream();
            chunkLength = uc.getContentLength();
            if (chunkLength <= 0)
                chunkLength = 1024;
            if (charCoding == null) {
                String type = uc.getContentType();
                if (type != null) {
                    charCoding = getCharCodingFromType(type);
                }
            }
        } else {
            File f = new File(filePath);

            long length = f.length();
            chunkLength = (int) length;
            if (chunkLength != length)
                throw new IOException("Too big file size: " + length);

            if (chunkLength == 0) {
                return "";
            }

            is = new FileInputStream(f);
        }

        Reader r;
        if (charCoding == null) {
            r = new InputStreamReader(is);
        } else {
            r = new InputStreamReader(is, charCoding);
        }
        return readReader(r, chunkLength);

    } finally {
        if (is != null)
            is.close();
    }
}

From source file:com.knowarth.portlet.downloadinterceptor.DownloadInterceptorPortlet.java

public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws IOException {
    //Setting out email parameters
    String emailAdd = resourceRequest.getParameter("emailAddress");
    String visitorName = resourceRequest.getParameter("visitorName");
    String cmpName = resourceRequest.getParameter("companyName");
    String phoneNumber = resourceRequest.getParameter("phoneNumber");
    String comments = resourceRequest.getParameter("comments");

    //Getting the preferences and reading URL Location reading from edit mode
    PortletPreferences prefs = resourceRequest.getPreferences();
    String resourceurl = prefs.getValue("resourceurl", "");
    String caseStudyName = prefs.getValue("caseStudyName", "");
    String receiveEmailAdd = prefs.getValue("receiverEmailAdd", "");
    //emailBodyContent Return the template stored in preferences edit mode.
    String emailBodyContent = prefs.getValue("emailBodyTemplate", "");
    String emailsubj = prefs.getValue("emailSubjectTemplate", "");
    String resExtension = prefs.getValue("ResourceExtension", "");
    String body = StringUtil.replace(emailBodyContent,
            new String[] { "[$VISITOR_NAME$]", "[$COMPANY_NAME$]", "[$EMAIL_ADDRESS$]", "[$PHONE_NUMBER$]",
                    "[$COMMENTS$]", "[$CASE_STUDY_NAME$]" },
            new String[] { visitorName, cmpName, emailAdd, phoneNumber, comments, caseStudyName });

    //Setting out body and email parameters
    String subject = StringUtil.replace(emailsubj, new String[] { "[$VISITOR_NAME$]", "[$CASE_STUDY_NAME$]" },
            new String[] { visitorName, caseStudyName });
    //code for sending email
    try {/*from w  w  w . j  a  v a2  s .  com*/
        InternetAddress fromAddress = new InternetAddress(emailAdd);
        InternetAddress toAddress = new InternetAddress(receiveEmailAdd);

        MailMessage mailMessage = new MailMessage(fromAddress, toAddress, subject, body, true);
        MailServiceUtil.sendEmail(mailMessage);

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        _log.error("Error Sending Message", e);
    } finally {
        //For Downloading a resource

        String contentDisposition = "attachment; filename=" + caseStudyName + "." + resExtension;
        OutputStream out = resourceResponse.getPortletOutputStream();

        //LInk for resource URL Goes here. Uncomment it out for dynamic location and comment out the static link
        URL url = new URL(resourceurl);
        URLConnection conn = url.openConnection();
        resourceResponse.setContentType(conn.getContentType());
        resourceResponse.setContentLength(conn.getContentLength());
        resourceResponse.setCharacterEncoding(conn.getContentEncoding());
        resourceResponse.setProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
        resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600");

        // open the stream and put it into BufferedReader
        InputStream stream = conn.getInputStream();
        int c;
        while ((c = stream.read()) != -1) {
            out.write(c);
        }
        out.flush();
        out.close();
        stream.close();

    }

}

From source file:org.theospi.portfolio.presentation.export.StreamedPage.java

public InputStream getStream() throws IOException {
    URLConnection conn = Access.getAccess().openConnection(link);

    // fetch and store final redirected URL and response headers
    InputStream returned = conn.getInputStream();

    this.setContentEncoding(conn.getContentEncoding());
    this.setContentType(conn.getContentType());
    this.setExpiration(conn.getExpiration());
    this.setLastModified(conn.getLastModified());

    return returned;
}

From source file:com.fluidops.iwb.provider.RDFProvider.java

@Override
public void gather(final List<Statement> res) throws Exception {

    InputStream rdfStream = null;
    RDFFormat rdfFormat;//w w w.  j  a  v  a  2s .  c  om
    String baseUri;
    try {

        // use either DataSource or legacy initialization
        if (config.dataSource != null) {
            RDFDataSource ds = config.lookupAndRefreshDataSource(RDFDataSource.class);

            rdfFormat = ds.getRDFFormat();
            if (rdfFormat == null)
                throw new IllegalStateException(String
                        .format("Data source '%s' does not provide a valid RDF Format", ds.getIdentifier()));

            rdfStream = ds.getRDFStream();
            baseUri = providerID.stringValue();
        } else {

            // legacy support
            URL url = new URL(config.url);

            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(1000);
            String contentType = conn.getContentType();

            rdfFormat = getRDFFormat(url, contentType);
            if (rdfFormat == null)
                throw new IllegalStateException(String.format(
                        "Cannot determine RDF format for URL '%s'. Please specify a format manually.",
                        config.url));

            rdfStream = conn.getInputStream();
            baseUri = config.url;
        }

        // load the RDF data from the rdf stream
        ParserConfig parserConfig = new ParserConfig();
        RDFLoader loader = new RDFLoader(parserConfig, ValueFactoryImpl.getInstance());
        loader.load(rdfStream, baseUri, rdfFormat, new RDFHandlerBase() {
            @Override
            public void handleStatement(Statement st) throws RDFHandlerException {
                res.add(st);
            }
        });

    } finally {
        IOUtils.closeQuietly(rdfStream);
    }
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Gets content type from connection and set default if null
 *
 * @param con  URL connection/*from  ww  w .j av  a  2 s .  co m*/
 * @return     Content type
 */
public String getContentType(final URLConnection con) {
    String contentType = con.getContentType();

    if (contentType != null) {
        logger.debug("getContentType() content type is '" + contentType + "'");
    } else {
        logger.debug("getContentType() Null content type - assuming html anyway.");
        // FIXME check this, if we need this default value!!!
        contentType = "html";
    }

    return contentType;
}