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:org.apache.synapse.config.SynapseConfigUtils.java

/**
 * Helper method to handle non-XMl resources
 *
 * @param url The resource url//from   w w w  . j  a va2  s  .c  o m
 * @return The content as an OMNode
 */
public static OMNode readNonXML(URL url) {

    try {
        // Open a new connection
        URLConnection newConnection = getURLConnection(url);
        if (newConnection == null) {
            if (log.isDebugEnabled()) {
                log.debug("Cannot create a URLConnection for given URL : " + url);
            }
            return null;
        }

        BufferedInputStream newInputStream = new BufferedInputStream(newConnection.getInputStream());

        OMFactory omFactory = OMAbstractFactory.getOMFactory();
        return omFactory.createOMText(
                new DataHandler(new SynapseBinaryDataSource(newInputStream, newConnection.getContentType())),
                true);

    } catch (IOException e) {
        handleException("Error when getting a stream from resource's content", e);
    }
    return null;
}

From source file:org.geoserver.wms.web.data.ExternalGraphicPanel.java

/**
 * Validates the external graphic and returns a connection to the graphic.
 * If validation fails, error messages will be added to the passed form
 * //  w w  w . j ava2  s .c  o m
 * @param target
 * @param form
 * @return URLConnection to the External Graphic file
 */
protected URLConnection getExternalGraphic(AjaxRequestTarget target, Form<?> form) {
    onlineResource.processInput();
    if (onlineResource.getModelObject() != null) {
        URL url = null;
        try {
            String baseUrl = baseURL(form);
            String external = onlineResource.getModelObject().toString();

            URI uri = new URI(external);
            if (uri.isAbsolute()) {
                url = uri.toURL();
                if (!external.startsWith(baseUrl)) {
                    form.warn("Recommend use of styles directory at " + baseUrl);
                }
            } else {
                WorkspaceInfo wsInfo = ((StyleInfo) getDefaultModelObject()).getWorkspace();
                if (wsInfo != null) {
                    url = new URL(ResponseUtils.appendPath(baseUrl, "styles", wsInfo.getName(), external));
                } else {
                    url = new URL(ResponseUtils.appendPath(baseUrl, "styles", external));
                }
            }

            URLConnection conn = url.openConnection();
            if ("text/html".equals(conn.getContentType())) {
                form.error("Unable to access url");
                return null; // error message back!
            }
            return conn;

        } catch (FileNotFoundException notFound) {
            form.error("Unable to access " + url);
        } catch (Exception e) {
            e.printStackTrace();
            form.error("Recommend use of styles directory at " + e);
        }
    }
    return null;
}

From source file:org.artifactory.cli.test.TestCli.java

private void importFromTemp(File importFrom) throws Exception {
    cleanOptions();/*from w w  w.jav  a2s  .  c  o m*/
    ArtAdmin.main(new String[] { "import", importFrom.getAbsolutePath(), "--server", "localhost:8080",
            "--syncImport", "--username", "admin", "--password", "password" });
    for (MdToFind mdPath : mdExported) {
        String url = "http://localhost:8080/artifactory" + mdPath.uri;
        URLConnection urlConnection = new URL(url).openConnection();
        urlConnection.connect();
        //Assert.assertEquals(urlConnection.getContentLength(), mdPath.imported.length(), "md "+mdPath.uri+" not the same than "+mdPath.imported.getAbsolutePath());
        assertTrue(urlConnection.getContentType().contains("xml"), "URL " + url + " is not xml");
    }
}

From source file:com.wavemaker.runtime.module.ModuleController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String requestURI = request.getRequestURI();
    final String moduleURI = "/" + MODULES_PREFIX;
    final String moduleURIAbs = moduleURI + "/";
    final String moduleJsURI = moduleURIAbs + MODULES_JS;
    final String epURI = moduleURIAbs + EXTENSION_PATH;
    final String epURIAbs = epURI + "/";
    final String idURI = moduleURIAbs + ID_PATH;
    final String idURIAbs = idURI + "/";

    // trim off the servlet name
    requestURI = requestURI.substring(requestURI.indexOf('/', 1));

    if (moduleURI.equals(requestURI) || moduleURIAbs.equals(requestURI)) {
    } else if (epURI.equals(requestURI) || epURIAbs.equals(requestURI)) {
        Set<String> names = this.moduleManager.listExtensionPoints();

        response.setContentType("text/html");
        Writer writer = response.getWriter();
        writer.write("<html><body>\n");
        for (String ext : names) {
            writer.write(ext + "<br />\n");
        }//from  w ww  .  j  a  v a2  s. c  om
        writer.write("</body></html>\n");
        writer.close();
    } else if (idURI.equals(requestURI) || idURIAbs.equals(requestURI)) {
        Set<String> names = this.moduleManager.listModules();

        response.setContentType("text/html");
        Writer writer = response.getWriter();
        writer.write("<html><body>\n");
        for (String ext : names) {
            writer.write(ext + "<br />\n");
        }
        writer.write("</body></html>\n");
        writer.close();
    } else if (moduleJsURI.equals(requestURI)) {
        Set<String> extensions = this.moduleManager.listExtensionPoints();

        JSONObject jo = new JSONObject();

        JSONObject extJO = new JSONObject();
        for (String extension : extensions) {
            JSONArray ja = new JSONArray();

            List<ModuleWire> wires = this.moduleManager.getModules(extension);
            for (ModuleWire wire : wires) {
                ja.add(wire.getName());
            }

            extJO.put(extension, ja);
        }

        jo.put("extensionPoints", extJO);

        response.setContentType(ServerConstants.JSON_CONTENT_TYPE);
        Writer writer = response.getWriter();
        writer.write(jo.toString());
        writer.close();
    } else {
        Tuple.Two<ModuleWire, String> tuple = parseRequestPath(requestURI);
        if (tuple.v1 == null) {
            String message = MessageResource.NO_MODULE_RESOURCE.getMessage(requestURI, tuple.v2);
            this.logger.error(message);

            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Writer outputWriter = response.getWriter();
            outputWriter.write(message);

            return null;
        }

        URL url = this.moduleManager.getModuleResource(tuple.v1, tuple.v2);
        URLConnection conn = url.openConnection();
        if (SystemUtils.IS_OS_WINDOWS) {
            conn.setDefaultUseCaches(false);
        }

        response.setContentType(conn.getContentType());
        OutputStream os = null;
        InputStream is = null;

        try {
            os = response.getOutputStream();
            is = conn.getInputStream();

            IOUtils.copy(conn.getInputStream(), os);
        } finally {
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        }
    }

    return null;
}

From source file:net.solarnetwork.node.support.HttpClientSupport.java

/**
 * Get an InputStream from a URLConnection response, handling compression.
 * //from  w w  w.  jav  a  2  s. c  o  m
 * <p>
 * This method handles decompressing the response if the encoding is set to
 * {@code gzip} or {@code deflate}.
 * </p>
 * 
 * @param conn
 *        the URLConnection
 * @return the InputStream
 * @throws IOException
 *         if any IO error occurs
 */
protected InputStream getInputStreamFromURLConnection(URLConnection conn) throws IOException {
    String enc = conn.getContentEncoding();
    String type = conn.getContentType();

    if (conn instanceof HttpURLConnection) {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        if (httpConn.getResponseCode() < 200 || httpConn.getResponseCode() > 299) {
            log.info("Non-200 HTTP response from {}: {}", conn.getURL(), httpConn.getResponseCode());
        }
    }

    log.trace("Got content type [{}] encoded as [{}]", type, enc);

    InputStream is = conn.getInputStream();
    if ("gzip".equalsIgnoreCase(enc)) {
        is = new GZIPInputStream(is);
    } else if ("deflate".equalsIgnoreCase("enc")) {
        is = new DeflaterInputStream(is);
    }
    return is;
}

From source file:org.deegree.enterprise.servlet.SimpleProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*w w  w.  java  2  s.c o m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        String query = request.getQueryString();
        Map<String, String> map = KVP2Map.toMap(query);
        if (removeCredentials) {
            map.remove("USER");
            map.remove("PASSWORD");
            map.remove("SESSIONID");
            query = "";
            for (String key : map.keySet()) {
                query += key + "=" + map.get(key) + "&";
            }
            query = query.substring(0, query.length() - 1);
        }
        String service = getService(map);
        String hostAddr = host.get(service);
        String req = hostAddr + "?" + query;
        URL url = new URL(req);
        LOG.logDebug("forward URL: " + url);

        URLConnection con = url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(false);
        is = con.getInputStream();
        response.setContentType(con.getContentType());
        response.setCharacterEncoding(con.getContentEncoding());
        os = response.getOutputStream();
        int read = 0;
        byte[] buf = new byte[16384];
        if (LOG.getLevel() == ILogger.LOG_DEBUG) {
            while ((read = is.read(buf)) > -1) {
                os.write(buf, 0, read);
                LOG.logDebug(new String(buf, 0, read,
                        con.getContentEncoding() == null ? "UTF-8" : con.getContentEncoding()));
            }
        } else {
            while ((read = is.read(buf)) > -1) {
                os.write(buf, 0, read);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        response.setContentType("text/plain; charset=" + CharsetUtils.getSystemCharset());
        os.write(StringTools.stackTraceToString(e).getBytes());
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            // try to do what ?
        }
        try {
            os.close();
        } catch (Exception e) {
            // try to do what ?
        }
    }
}

From source file:org.primefaces.component.imagecropper.ImageCropperRenderer.java

@Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue)
        throws ConverterException {
    String coords = (String) submittedValue;

    if (isValueBlank(coords)) {
        return null;
    }/*w  w w .  jav  a2 s.c  om*/

    String[] cropCoords = coords.split("_");

    int x = (int) Double.parseDouble(cropCoords[0]);
    int y = (int) Double.parseDouble(cropCoords[1]);
    int w = (int) Double.parseDouble(cropCoords[2]);
    int h = (int) Double.parseDouble(cropCoords[3]);

    if (w <= 0 || h <= 0) {
        return null;
    }

    ImageCropper cropper = (ImageCropper) component;
    Resource resource = getImageResource(context, cropper);
    InputStream inputStream = null;
    String imagePath = cropper.getImage();
    String contentType = null;

    try {

        if (resource != null && !"RES_NOT_FOUND".equals(resource.toString())) {
            inputStream = resource.getInputStream();
            contentType = resource.getContentType();
        } else {

            boolean isExternal = imagePath.startsWith("http");

            if (isExternal) {
                URL url = new URL(imagePath);
                URLConnection urlConnection = url.openConnection();
                inputStream = urlConnection.getInputStream();
                contentType = urlConnection.getContentType();
            } else {
                ExternalContext externalContext = context.getExternalContext();
                File file = new File(externalContext.getRealPath("") + imagePath);
                inputStream = new FileInputStream(file);
            }
        }

        // wrap input stream by BoundedInputStream to prevent uncontrolled resource consumption (#3286)
        if (cropper.getSizeLimit() != null) {
            inputStream = new BoundedInputStream(inputStream, cropper.getSizeLimit());
        }

        BufferedImage outputImage = ImageIO.read(inputStream);

        // avoid java.awt.image.RasterFormatException: (x + width) is outside of Raster
        // see #1208
        if (x + w > outputImage.getWidth()) {
            w = outputImage.getWidth() - x;
        }
        if (y + h > outputImage.getHeight()) {
            h = outputImage.getHeight() - y;
        }

        BufferedImage cropped = outputImage.getSubimage(x, y, w, h);
        ByteArrayOutputStream croppedOutImage = new ByteArrayOutputStream();
        String format = guessImageFormat(contentType, imagePath);
        ImageIO.write(cropped, format, croppedOutImage);

        return new CroppedImage(cropper.getImage(), croppedOutImage.toByteArray(), x, y, w, h);
    } catch (IOException e) {
        throw new ConverterException(e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOGGER.severe(e.getMessage());
            }
        }
    }
}

From source file:org.roosster.input.UrlFetcher.java

/**
 * URLs will be fetched a second time, if the entry's lastFetched
 * object is <code>null</code>, when processed the first time.
 *//*from www .  j a va2s. c o  m*/
private Entry[] fetch(URL url) throws IOException, Exception {
    LOG.debug("Opening connection to URL " + url);

    URLConnection con = url.openConnection();

    long modified = con.getLastModified();

    String embeddedContentEnc = null;

    String contentType = con.getContentType();
    if (contentType != null && contentType.indexOf(";") > -1) {
        LOG.debug("Content-type string (" + contentType + ") contains charset; strip it!");
        contentType = contentType.substring(0, contentType.indexOf(";")).trim();

        String cType = con.getContentType();
        if (cType.indexOf("=") > -1) {
            embeddedContentEnc = cType.substring(cType.indexOf("=") + 1).trim();
        }
    }

    String contentEnc = con.getContentEncoding();
    if (contentEnc == null) {
        if (embeddedContentEnc != null)
            contentEnc = embeddedContentEnc;
        else
            contentEnc = defaultEncoding;
    }

    ContentTypeProcessor proc = getProcessor(contentType);
    LOG.debug("ContentType: '" + contentType + "' - ContentEncoding: '" + contentEnc + "'");
    LOG.debug("Using Processor " + proc);

    Entry[] entries = proc.process(url, con.getInputStream(), contentEnc);

    Date modDate = new Date(modified);
    Date now = new Date();

    List returnArr = new ArrayList();
    for (int i = 0; i < entries.length; i++) {
        if (entries[i] == null)
            continue;

        URL entryUrl = entries[i].getUrl();

        String title = entries[i].getTitle();
        if (title == null || "".equals(title))
            entries[i].setTitle(entryUrl.toString());

        if (entries[i].getModified() == null)
            entries[i].setModified(modDate);

        if (entries[i].getIssued() == null)
            entries[i].setIssued(modDate);

        if (entries[i].getAdded() == null)
            entries[i].setAdded(now);

        String fileType = entries[i].getFileType();
        if (fileType == null || "".equals(fileType)) {

            int dotIndex = entryUrl.getPath().lastIndexOf(".");
            if (dotIndex != -1) {
                String type = entryUrl.getPath().substring(dotIndex + 1);
                entries[i].setFileType(type.toLowerCase());
                LOG.debug("Filetype is subsequently set to '" + type + "'");
            }

        }

        returnArr.add(entries[i]);
        entries[i] = null;
    }

    return (Entry[]) returnArr.toArray(new Entry[0]);
}

From source file:abelymiguel.miralaprima.SetMoza.java

private Boolean checkMimeUrlMoza(String url_moza) {
    String type;//from ww  w  .  java 2s. com
    Boolean result = false;
    URL url;
    URLConnection uc = null;
    try {
        url = new URL(url_moza);
        uc = url.openConnection();
    } catch (IOException ex) {
        Logger.getLogger(SetMoza.class.getName()).log(Level.SEVERE, null, ex);
        result = false;
    }
    type = uc.getContentType();
    if (type.equals("image/jpeg") || type.equals("image/png")) {
        result = true;
    }
    return result;
}

From source file:org.callimachusproject.xml.InputSourceResolver.java

/**
 * returns null for 404 resources.//from  ww w .ja  va  2s . c om
 */
private InputSource resolveURL(String systemId) throws IOException {
    URLConnection con = new URL(systemId).openConnection();
    con.addRequestProperty("Accept", getAcceptHeader());
    con.addRequestProperty("Accept-Encoding", "gzip");
    try {
        String base = con.getURL().toExternalForm();
        String type = con.getContentType();
        String encoding = con.getHeaderField("Content-Encoding");
        InputStream in = con.getInputStream();
        if (encoding != null && encoding.contains("gzip")) {
            in = new GZIPInputStream(in);
        }
        return create(type, in, base);
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        logger.warn("Could not resolve {}", systemId);
        throw e;
    }
}