Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

In this page you can find the example usage for java.net URI toURL.

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

From source file:de.fhg.igd.mapviewer.server.wms.overlay.WMSTileOverlay.java

/**
 * @see AbstractTileOverlayPainter#repaintTile(int, int, int, int,
 *      PixelConverter, int)// w  ww.j  ava2 s.  co m
 */
@Override
public BufferedImage repaintTile(int posX, int posY, int width, int height, PixelConverter converter,
        int zoom) {
    // the first converter isn't regarded as a new converter because it's
    // always the empty map
    boolean isNewConverter = lastConverter != null && !converter.equals(lastConverter);
    lastConverter = converter;

    if (!converter.supportsBoundingBoxes()) {
        if (isNewConverter) {
            handleError(Messages.WMSTileOverlay_0 + configuration.getName() + Messages.WMSTileOverlay_1);
        }
        return null;
    }

    synchronized (this) {
        if (capabilities == null) {
            try {
                capabilities = WMSUtil.getCapabilities(configuration.getBaseUrl());
            } catch (WMSCapabilitiesException e) {
                log.error("Error getting WMS capabilities"); //$NON-NLS-1$
            }
        }
    }

    if (capabilities != null) {
        int mapEpsg = converter.getMapEpsg();

        WMSBounds box;
        synchronized (this) {
            if (capabilities.getSupportedSRS().contains("EPSG:" + mapEpsg)) { //$NON-NLS-1$
                // same SRS supported
            } else {
                // SRS not supported
                if (isNewConverter) {
                    StringBuilder message = new StringBuilder();
                    message.append(Messages.WMSTileOverlay_2);
                    message.append(configuration.getName());
                    message.append(Messages.WMSTileOverlay_3);
                    boolean init = true;
                    for (String srs : capabilities.getSupportedSRS()) {
                        if (init) {
                            init = false;
                        } else {
                            message.append(", "); //$NON-NLS-1$
                        }
                        message.append(srs);
                    }
                    handleError(message.toString());
                }
                return null;
            }

            box = WMSUtil.getBoundingBox(capabilities, mapEpsg);
        }

        String srs = box.getSRS();

        if (srs.startsWith("EPSG:")) { //$NON-NLS-1$
            // determine format
            String format = null;
            Iterator<String> itFormat = supportedFormats.iterator();
            synchronized (this) {
                while (format == null && itFormat.hasNext()) {
                    String supp = itFormat.next();
                    if (capabilities.getFormats().contains(supp)) {
                        format = supp;
                    }
                }
            }
            if (format == null) {
                // no compatible format
                return null;
            }

            try {
                // check if tile lies within the bounding box
                int epsg = Integer.parseInt(srs.substring(5));

                GeoPosition topLeft = converter.pixelToGeo(new Point(posX, posY), zoom);
                GeoPosition bottomRight = converter.pixelToGeo(new Point(posX + width, posY + height), zoom);

                // WMS bounding box
                BoundingBox wms = new BoundingBox(box.getMinX(), box.getMinY(), -1, box.getMaxX(),
                        box.getMaxY(), 1);

                GeoConverter geotools = GeotoolsConverter.getInstance();
                GeoPosition bbTopLeft = geotools.convert(topLeft, epsg);
                GeoPosition bbBottomRight = geotools.convert(bottomRight, epsg);

                double minX = Math.min(bbTopLeft.getX(), bbBottomRight.getX());
                double minY = Math.min(bbTopLeft.getY(), bbBottomRight.getY());
                double maxX = Math.max(bbTopLeft.getX(), bbBottomRight.getX());
                double maxY = Math.max(bbTopLeft.getY(), bbBottomRight.getY());

                BoundingBox tile = new BoundingBox(minX, minY, -1, maxX, maxY, 1);

                // check if bounding box and tile overlap
                if (wms.intersectsOrCovers(tile) || tile.covers(wms)) {
                    WMSBounds bounds;
                    if (epsg == mapEpsg) {
                        bounds = new WMSBounds(srs, minX, minY, maxX, maxY);
                    } else {
                        // determine bounds for request
                        minX = Math.min(topLeft.getX(), bottomRight.getX());
                        minY = Math.min(topLeft.getY(), bottomRight.getY());
                        maxX = Math.max(topLeft.getX(), bottomRight.getX());
                        maxY = Math.max(topLeft.getY(), bottomRight.getY());
                        bounds = new WMSBounds("EPSG:" + mapEpsg, minX, minY, maxX, maxY); //$NON-NLS-1$
                    }

                    URI uri;
                    synchronized (this) {
                        uri = WMSUtil.getMapURI(capabilities, configuration, width, height, bounds, null,
                                format, true);
                    }

                    Proxy proxy = ProxyUtil.findProxy(uri);

                    InputStream in = uri.toURL().openConnection(proxy).getInputStream();

                    BufferedImage image = GraphicsUtilities.loadCompatibleImage(in);

                    // apply transparency to the image
                    BufferedImage result = GraphicsUtilities.createCompatibleTranslucentImage(image.getWidth(),
                            image.getHeight());
                    Graphics2D g = result.createGraphics();
                    try {
                        AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f);
                        g.setComposite(ac);
                        g.drawImage(image, 0, 0, null);
                    } finally {
                        g.dispose();
                    }

                    return result;
                }
            } catch (Throwable e) {
                log.warn("Error painting WMS overlay", e); //$NON-NLS-1$
            }
        }
    }

    return null;
}

From source file:org.eclipse.winery.repository.rest.resources.artifacts.GenericArtifactsResource.java

/**
 * Generates the implementation artifact using the implementation artifact generator. Also sets the properties
 * according to the requirements of OpenTOSCA.
 *//*w  ww  .  j  a  v a 2  s.  c  om*/
private Response generateImplementationArtifact(String interfaceName, String javaPackage, UriInfo uriInfo,
        ArtifactTemplateId artifactTemplateId) {

    assert (this instanceof ImplementationArtifactsResource);
    IRepository repository = RepositoryFactory.getRepository();

    QName type = RestUtils.getType(this.res);
    EntityTypeId typeId = getTypeId(type).orElseThrow(IllegalStateException::new);
    TInterface i = findInterface(typeId, interfaceName).orElseThrow(IllegalStateException::new);

    Path workingDir;
    try {
        workingDir = Files.createTempDirectory("winery");
    } catch (IOException e2) {
        GenericArtifactsResource.LOGGER.debug("Could not create temporary directory", e2);
        return Response.serverError().entity("Could not create temporary directory").build();
    }

    URI artifactTemplateFilesUri = uriInfo.getBaseUri().resolve(RestUtils.getAbsoluteURL(artifactTemplateId))
            .resolve("files");
    URL artifactTemplateFilesUrl;
    try {
        artifactTemplateFilesUrl = artifactTemplateFilesUri.toURL();
    } catch (MalformedURLException e2) {
        GenericArtifactsResource.LOGGER.debug("Could not convert URI to URL", e2);
        return Response.serverError().entity("Could not convert URI to URL").build();
    }

    String name = this.generateName(typeId, interfaceName);
    Generator gen = new Generator(i, javaPackage, artifactTemplateFilesUrl, name, workingDir.toFile());
    Path targetPath;
    try {
        targetPath = gen.generateProject();
    } catch (Exception e) {
        LOGGER.debug("IA generator failed", e);
        return Response.serverError().entity("IA generator failed").build();
    }

    DirectoryId fileDir = new ArtifactTemplateSourceDirectoryId(artifactTemplateId);
    try {
        BackendUtils.importDirectory(targetPath, repository, fileDir);
    } catch (IOException e) {
        throw new WebApplicationException(e);
    }

    // clean up
    FileUtils.forceDelete(workingDir);

    this.storeProperties(artifactTemplateId, typeId, name);

    URI url = uriInfo.getBaseUri().resolve(Util.getUrlPath(artifactTemplateId));
    return Response.created(url).build();
}

From source file:org.opendatakit.aggregate.odktables.impl.api.InstanceFileServiceImpl.java

@Override
public Response putFile(@Context HttpServletRequest req, @PathParam("filePath") List<PathSegment> segments,
        byte[] content) throws IOException, ODKTaskLockException {

    if (segments.size() < 1) {
        return Response.status(Status.BAD_REQUEST).entity(InstanceFileService.ERROR_MSG_INSUFFICIENT_PATH)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();/* w ww.  j  a  va 2  s .  c om*/
    }
    // The appId and tableId are from the surrounding TableService.
    // The rowId is already pulled out.
    // The segments are just rest/of/path in the full app-centric
    // path of:
    // appid/data/attachments/tableid/instances/instanceId/rest/of/path
    String partialPath = constructPathFromSegments(segments);
    String contentType = req.getContentType();
    String md5Hash = PersistenceUtils.newMD5HashUri(content);
    try {
        userPermissions.checkPermission(appId, tableId, TablePermission.WRITE_ROW);

        UriBuilder ub = info.getBaseUriBuilder();
        ub.path(OdkTables.class, "getTablesService");

        URI getFile = ub.clone().path(TableService.class, "getRealizedTable")
                .path(RealizedTableService.class, "getInstanceFiles").path(InstanceFileService.class, "getFile")
                .build(appId, tableId, schemaETag, rowId, partialPath);

        String locationUrl = getFile.toURL().toExternalForm();

        // we are adding a file -- delete any cached ETag value for this row's attachments manifest
        try {
            DbTableInstanceManifestETagEntity entity = DbTableInstanceManifestETags.getRowIdEntry(tableId,
                    rowId, cc);
            entity.delete(cc);
        } catch (ODKEntityNotFoundException e) {
            // ignore...
        }

        DbTableInstanceFiles blobStore = new DbTableInstanceFiles(tableId, cc);
        BlobEntitySet instance = blobStore.newBlobEntitySet(rowId, cc);
        int count = instance.getAttachmentCount(cc);
        for (int i = 1; i <= count; ++i) {
            String path = instance.getUnrootedFilename(i, cc);
            if (path != null && path.equals(partialPath)) {
                // we already have this in our store -- check that it is identical.
                // if not, we have a problem!!!
                if (md5Hash.equals(instance.getContentHash(i, cc))) {
                    return Response.status(Status.CREATED).header("Location", locationUrl)
                            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER,
                                    ApiConstants.OPEN_DATA_KIT_VERSION)
                            .header("Access-Control-Allow-Origin", "*")
                            .header("Access-Control-Allow-Credentials", "true").build();
                } else {
                    return Response.status(Status.BAD_REQUEST)
                            .entity(ERROR_FILE_VERSION_DIFFERS + "\n" + partialPath)
                            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER,
                                    ApiConstants.OPEN_DATA_KIT_VERSION)
                            .header("Access-Control-Allow-Origin", "*")
                            .header("Access-Control-Allow-Credentials", "true").build();
                }
            }
        }
        BlobSubmissionOutcome outcome = instance.addBlob(content, contentType, partialPath, false, cc);
        if (outcome == BlobSubmissionOutcome.NEW_FILE_VERSION) {
            return Response.status(Status.BAD_REQUEST).entity(ERROR_FILE_VERSION_DIFFERS + "\n" + partialPath)
                    .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Credentials", "true").build();
        }
        return Response.status(Status.CREATED).header("Location", locationUrl)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    } catch (ODKDatastoreException e) {
        LOGGER.error(("ODKTables file upload persistence error: " + e.getMessage()));
        return Response.status(Status.INTERNAL_SERVER_ERROR)
                .entity(ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.getMessage())
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    } catch (PermissionDeniedException e) {
        String msg = e.getMessage();
        if (msg == null) {
            msg = e.toString();
        }
        LOGGER.error(("ODKTables file upload permissions error: " + msg));
        return Response.status(Status.FORBIDDEN).entity(new Error(ErrorType.PERMISSION_DENIED, msg))
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    }
}

From source file:bpelg.packaging.ode.util.BgSchemaCollection.java

public void read(String location, URI baseUri) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Reading schema at '" + location + "' with baseUri '" + baseUri + "'");
    }//from  w  w w .  j  a  v  a  2 s  .  c  o  m
    if (baseUri == null) {
        baseUri = this.baseUri;
    }
    URI loc;
    if (baseUri != null) {
        loc = resolve(baseUri, location);
        if (!loc.isAbsolute()) {
            throw new IllegalArgumentException(
                    "Unable to resolve '" + loc.toString() + "' relative to '" + baseUri + "'");
        }
    } else {
        loc = new URI(location);
        if (!loc.isAbsolute()) {
            throw new IllegalArgumentException(
                    "Location '" + loc.toString() + "' is not absolute and no baseUri specified");
        }
    }
    InputSource inputSource = new InputSource();
    inputSource.setByteStream(loc.toURL().openStream());
    inputSource.setSystemId(loc.toString());
    read(inputSource);
}

From source file:org.opendatakit.aggregate.odktables.impl.api.InstanceFileServiceImpl.java

@Override
public Response getFile(@Context HttpHeaders httpHeaders, @PathParam("filePath") List<PathSegment> segments,
        @QueryParam(PARAM_AS_ATTACHMENT) String asAttachment) throws IOException {
    // The appId and tableId are from the surrounding TableService.
    // The rowId is already pulled out.
    // The segments are just rest/of/path in the full app-centric
    // path of:/*  www  . j a  v  a  2s . c o  m*/
    // appid/data/attachments/tableid/instances/instanceId/rest/of/path
    if (rowId == null || rowId.length() == 0) {
        return Response.status(Status.BAD_REQUEST).entity(InstanceFileService.ERROR_MSG_INVALID_ROW_ID)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    }
    if (segments.size() < 1) {
        return Response.status(Status.BAD_REQUEST).entity(InstanceFileService.ERROR_MSG_INSUFFICIENT_PATH)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    }
    // Now construct the whole path.
    String partialPath = constructPathFromSegments(segments);

    // retrieve the incoming if-none-match eTag...
    List<String> eTags = httpHeaders.getRequestHeader(HttpHeaders.IF_NONE_MATCH);
    String eTag = (eTags == null || eTags.isEmpty()) ? null : eTags.get(0);

    UriBuilder ub = info.getBaseUriBuilder();
    ub.path(OdkTables.class, "getTablesService");

    URI getFile = ub.clone().path(TableService.class, "getRealizedTable")
            .path(RealizedTableService.class, "getInstanceFiles").path(InstanceFileService.class, "getFile")
            .build(appId, tableId, schemaETag, rowId, partialPath);

    String locationUrl = getFile.toURL().toExternalForm();

    try {
        userPermissions.checkPermission(appId, tableId, TablePermission.READ_ROW);

        DbTableInstanceFiles blobStore = new DbTableInstanceFiles(tableId, cc);
        BlobEntitySet instance = blobStore.getBlobEntitySet(rowId, cc);

        int count = instance.getAttachmentCount(cc);
        for (int i = 1; i <= count; ++i) {
            String path = instance.getUnrootedFilename(i, cc);
            if (path != null && path.equals(partialPath)) {
                byte[] fileBlob = instance.getBlob(i, cc);
                String contentType = instance.getContentType(i, cc);
                String contentHash = instance.getContentHash(i, cc);
                Long contentLength = instance.getContentLength(i, cc);

                // And now prepare everything to be returned to the caller.
                if (fileBlob != null && contentType != null && contentLength != null && contentLength != 0L) {

                    // test if we should return a NOT_MODIFIED response...
                    if (eTag != null && eTag.equals(contentHash)) {
                        return Response.status(Status.NOT_MODIFIED).header(HttpHeaders.ETAG, eTag)
                                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER,
                                        ApiConstants.OPEN_DATA_KIT_VERSION)
                                .header("Access-Control-Allow-Origin", "*")
                                .header("Access-Control-Allow-Credentials", "true").build();
                    }

                    ResponseBuilder rBuild = Response.ok(fileBlob, contentType)
                            .header(HttpHeaders.ETAG, contentHash)
                            .header(HttpHeaders.CONTENT_LENGTH, contentLength)
                            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER,
                                    ApiConstants.OPEN_DATA_KIT_VERSION)
                            .header("Access-Control-Allow-Origin", "*")
                            .header("Access-Control-Allow-Credentials", "true");
                    if (asAttachment != null && !"".equals(asAttachment)) {
                        // Set the filename we're downloading to the disk.
                        rBuild.header(HtmlConsts.CONTENT_DISPOSITION,
                                "attachment; " + "filename=\"" + partialPath + "\"");
                    }
                    return rBuild.build();
                } else {
                    return Response.status(Status.NOT_FOUND)
                            .entity("File content not yet available for: " + locationUrl)
                            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER,
                                    ApiConstants.OPEN_DATA_KIT_VERSION)
                            .header("Access-Control-Allow-Origin", "*")
                            .header("Access-Control-Allow-Credentials", "true").build();
                }

            }
        }
        return Response.status(Status.NOT_FOUND).entity("No file found for: " + locationUrl)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        return Response.status(Status.INTERNAL_SERVER_ERROR)
                .entity("Unable to retrieve attachment and access attributes for: " + locationUrl)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    } catch (PermissionDeniedException e) {
        String msg = e.getMessage();
        if (msg == null) {
            msg = e.toString();
        }
        LOGGER.error(("ODKTables file upload permissions error: " + msg));
        return Response.status(Status.FORBIDDEN).entity(new Error(ErrorType.PERMISSION_DENIED, msg))
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    }
}

From source file:org.apache.cxf.maven_plugin.wadlto.AbstractCodeGeneratorMojo.java

/**
 * Determine if code should be generated from the given wadl
 *
 * @param wadlOption// www . j  a  va2  s.  co m
 * @param doneFile
 * @param wadlURI
 * @return
 */
private boolean shouldRun(WadlOption wadlOption, File doneFile, URI wadlURI) {
    long timestamp = 0;
    if ("file".equals(wadlURI.getScheme())) {
        timestamp = new File(wadlURI).lastModified();
    } else {
        try {
            timestamp = wadlURI.toURL().openConnection().getDate();
        } catch (Exception e) {
            // ignore
        }
    }
    boolean doWork = false;
    if (!doneFile.exists()) {
        doWork = true;
    } else if (timestamp > doneFile.lastModified()) {
        doWork = true;
    } else {
        File files[] = wadlOption.getDependencies();
        if (files != null) {
            for (int z = 0; z < files.length; ++z) {
                if (files[z].lastModified() > doneFile.lastModified()) {
                    doWork = true;
                }
            }
        }
    }
    return doWork;
}

From source file:com.esri.gpt.catalog.search.SearchEngineRest.java

@Override
public void doSearch() throws SearchException {
    Exception ex = null;//from   w ww.java 2s . c o m

    try {
        URI uri = this.getConnectionUri();
        URL url = uri.toURL();
        HttpClientRequest clientRequest = HttpClientRequest.newRequest(HttpClientRequest.MethodName.GET,
                url.toExternalForm());
        clientRequest.setConnectionTimeMs(getConnectionTimeoutMs());
        clientRequest.setResponseTimeOutMs(getResponseTimeoutMs());

        Map map = (Map) this.getRequestContext().extractFromSession(SEARCH_CREDENTIAL_MAP);
        if (map != null) {
            CredentialProvider credProvider = (CredentialProvider) map.get(this.getKey());
            if (credProvider != null) {
                clientRequest.setCredentialProvider(credProvider);
            }
        }

        clientRequest.execute();
        String response = clientRequest.readResponseAsCharacters();
        InputStream is = null;
        try {
            SearchXslProfile profile = this.readXslProfile();
            String js = Val.chkStr(profile.getResponsexslt());
            //String js = Val.chkStr(this.getFactoryAttributes().get("searchResponseJsT"));
            String xml = null;
            if (js.toLowerCase().endsWith(".js")) {
                try {
                    ResourcePath rPath = new ResourcePath();
                    URL fileUrl = rPath.makeUrl(js);
                    is = fileUrl.openStream();
                    String jsTransFile = IOUtils.toString(is, "UTF-8");
                    jsTransFile = "var jsGptInput =" + response + ";" + jsTransFile;
                    HttpServletRequest servletRequest = (HttpServletRequest) this.getRequestContext()
                            .getServletRequest();
                    if (servletRequest != null) {
                        jsTransFile = "var jsGptQueryString = '" + servletRequest.getQueryString() + "';"
                                + jsTransFile;
                    }
                    jsTransFile = "var jsGptEndpointSearchQuery = '" + url.toExternalForm() + "';"
                            + jsTransFile;
                    ScriptEngineManager manager = new ScriptEngineManager();
                    ScriptEngine engine = manager.getEngineByName("JavaScript");
                    //manager.put("jsGptInput", response);
                    Object obj = engine.eval(jsTransFile);
                    xml = obj.toString();
                    parseResponse(xml);// has to work before the finally. dont move
                } catch (Exception e) {
                    throw new SearchException(
                            e.getMessage() + ":" + "Error when doing transformation from javascript", e);
                }
            } else {
                xml = XmlIoUtil.jsonToXml(response, "gptJsonXml");
                parseResponse(xml);
            }

            checkPagination();
        } catch (SearchException e) {
            throw e;
        } catch (Exception e) {
            parseResponse(response);
            checkPagination();
        } finally {
            if (is != null) {
                IOUtils.closeQuietly(is);
            }
        }

    } catch (MalformedURLException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } finally {

    }
    if (ex != null) {
        throw new SearchException(ex.getMessage() + ": Could not perform search", ex);
    }
}

From source file:eu.esdihumboldt.hale.common.cache.Request.java

/**
 * Open a stream for the given URI.//from  w  w  w .j av a 2 s . co m
 * 
 * @param uri the URI
 * @return the opened input stream, the caller is responsible to close it
 * @throws IOException if opening the input stream fails
 */
private InputStream openStream(URI uri) throws IOException {
    Proxy proxy = ProxyUtil.findProxy(uri);
    CloseableHttpClient client = getClient(proxy);

    HttpGet httpget = new HttpGet(uri);
    final CloseableHttpResponse response = client.execute(httpget);

    InputStream in;

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        // fall back to URL.openStream
        in = uri.toURL().openStream();
    } else {
        HttpEntity entity = response.getEntity();

        // create InputStream
        in = new InputStreamDecorator(entity.getContent()) {

            @Override
            public void close() throws IOException {
                super.close();
                // ensure the response is closed
                response.close();
            }

            @Override
            protected void finalize() throws Throwable {
                // not sure if this actually has any effect
                close();

                super.finalize();
            }

        };
    }

    return in;
}

From source file:eu.planets_project.tb.impl.system.ServiceExecutionHandlerImpl.java

/**
 * Takes a given http URI and tries to download its binary content.
 * @param uri//from  ww  w . ja va2 s  . c o m
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
@SuppressWarnings("unused")
private byte[] downloadBinaryFromURI(URI uri) throws FileNotFoundException, IOException {

    InputStream in = null;
    try {
        if (!uri.getScheme().equals("http")) {
            throw new FileNotFoundException("URI schema " + uri.getScheme() + " not supported");
        }

        URLConnection c = uri.toURL().openConnection();
        in = c.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        byte[] data = bos.toByteArray();

        return data;
    } finally {
        in.close();
    }
}