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:com.xmlcalabash.io.ReadableData.java

protected InputStream getStream(URI uri) {
    try {//  w  w  w .ja va  2s .  c om
        URL url = uri.toURL();
        URLConnection connection = url.openConnection();
        serverContentType = connection.getContentType();
        return connection.getInputStream();
    } catch (IOException ioe) {
        throw new XProcException(XProcConstants.dynamicError(29), ioe);
    }
}

From source file:org.kalypso.core.catalog.DynamicCatalog.java

private void internalAddEntry(String uri, final String systemID, final String publicID,
        final boolean relative) {
    // TODO check if entry already exists
    if (uri == null || uri.length() < 1)
        throw new UnsupportedOperationException();
    if (relative) {
        try {//from   w w w . j av a 2s  . c  o m
            final URI uri2 = new URI(uri);
            final String absolute = uri2.toURL().toExternalForm();
            final String relativePath = FileUtilities.getRelativePathTo(m_context.toExternalForm(), absolute);
            uri = relativePath;
        } catch (final Exception e) {
            // no
        }
    }
    final List<Object> publicOrSystemOrUri = m_catalog.getPublicOrSystemOrUri();
    if (systemID != null && systemID.length() > 0) {
        final System system = CatalogManager.OBJECT_FACTORY_CATALOG.createSystem();
        system.setSystemId(systemID);
        system.setUri(uri);
        publicOrSystemOrUri.add(CatalogManager.OBJECT_FACTORY_CATALOG.createSystem(system));
    }
    if (publicID != null && publicID.length() > 0) {
        final Public public_ = CatalogManager.OBJECT_FACTORY_CATALOG.createPublic();
        public_.setPublicId(publicID);
        public_.setUri(uri);
        publicOrSystemOrUri.add(CatalogManager.OBJECT_FACTORY_CATALOG.createPublic(public_));
    }

}

From source file:org.kaazing.maven.plugins.TrustStoreMojo.java

Map<String, String> getCertificates(String location) throws Exception {

    Map<String, String> certs = new HashMap<String, String>();

    Pattern labelPattern = Pattern.compile("^CKA_LABEL\\s+[A-Z0-9]+\\s+\\\"(.*)\\\"");
    Pattern beginContentPattern = Pattern.compile("^CKA_VALUE MULTILINE_OCTAL");
    Pattern endContentPattern = Pattern.compile("^END");
    Pattern untrustedPattern = Pattern.compile(
            "^CKA_TRUST_SERVER_AUTH\\s+CK_TRUST\\s+CKT_NSS_NOT_TRUSTED$|^CKA_TRUST_SERVER_AUTH\\s+CK_TRUST\\s+CKT_NSS_TRUST_UNKNOWN$");

    URI certsURI = new URI(location);

    // This should be the default, but make sure it's set anyway
    HttpURLConnection.setFollowRedirects(true);

    HttpURLConnection conn = (HttpURLConnection) certsURI.toURL().openConnection();
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new Exception(String.format("Error connecting to %s: %d %s", location, conn.getResponseCode(),
                conn.getResponseMessage()));
    }/*from ww w. j a v  a  2 s .c  o  m*/

    InputStream is = conn.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String alias = null;
    byte[] certData = new byte[MAX_CERT_SIZE];
    int certDataLen = 0;

    String line = br.readLine();
    while (line != null) {
        // Skip comments and empty lines
        if (line.startsWith("#")) {
            line = br.readLine();
            continue;
        }

        if (line.trim().length() == 0) {
            line = br.readLine();
            continue;
        }

        Matcher m = labelPattern.matcher(line);
        if (m.find()) {
            alias = m.group(1).toLowerCase().replaceAll("/", "-").replaceAll("\\s+", "");
            line = br.readLine();
            continue;
        }

        m = beginContentPattern.matcher(line);
        if (m.find()) {
            line = br.readLine();

            while (true) {
                m = endContentPattern.matcher(line);
                if (m.find()) {
                    StringBuilder pem = new StringBuilder();
                    pem.append("-----BEGIN CERTIFICATE-----\n");

                    String base64Data = Base64.encodeBase64String(Arrays.copyOf(certData, certDataLen));
                    pem.append(base64Data);

                    pem.append("\n-----END CERTIFICATE-----\n");

                    certs.put(alias, pem.toString());

                    // Prepare for another certificate/trust section
                    alias = null;
                    certData = new byte[MAX_CERT_SIZE];
                    certDataLen = 0;

                    line = br.readLine();
                    break;
                }

                String[] octets = line.split("\\\\");

                // We start at index 1, not zero, because the first element
                // in the array will always be an empty string.  The first
                // character in the string is a backslash; String.split()
                // thus populates the element before that backslash as an
                // empty string.
                for (int i = 1; i < octets.length; i++) {
                    int octet = Integer.parseInt(octets[i], 8);
                    certData[certDataLen++] = (byte) octet;
                }

                line = br.readLine();
            }

            continue;
        }

        m = untrustedPattern.matcher(line);
        if (m.find()) {
            // Remove untrusted certs from our map
            certs.remove(alias);

            line = br.readLine();
            continue;
        }

        line = br.readLine();
    }

    return certs;
}

From source file:ddf.catalog.transformer.resource.ResourceMetacardTransformerTest.java

private Resource getResource(MimeType mimeType, URI uri) throws Exception {
    Resource resource = mock(Resource.class);
    when(resource.getMimeType()).thenReturn(mimeType);
    when(resource.getMimeTypeValue()).thenReturn((mimeType == null) ? null : mimeType.getBaseType());
    when(resource.getInputStream()).thenReturn(uri.toURL().openConnection().getInputStream());
    return resource;
}

From source file:IntergrationTest.OCSPIntegrationTest.java

private byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception {
    InputStream is = null;/*from   w w  w  . ja  v  a2  s.co  m*/
    InputStream is_temp = null;
    try {
        if (uri == null)
            return null;
        URL url = uri.toURL();
        if (bActiveCheckUnknownHost) {
            url.getProtocol();
            String host = url.getHost();
            int port = url.getPort();
            if (port == -1)
                port = url.getDefaultPort();
            InetSocketAddress isa = new InetSocketAddress(host, port);
            if (isa.isUnresolved()) {
                //fix JNLP popup error issue
                throw new UnknownHostException("Host Unknown:" + isa.toString());
            }

        }
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoInput(true);
        uc.setAllowUserInteraction(false);
        uc.setInstanceFollowRedirects(true);
        setTimeout(uc);
        String contentEncoding = uc.getContentEncoding();
        int len = uc.getContentLength();
        // is = uc.getInputStream();
        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) {
            is_temp = uc.getInputStream();
            is = new GZIPInputStream(is_temp);

        } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) {
            is_temp = uc.getInputStream();
            is = new InflaterInputStream(is_temp);

        } else {
            is = uc.getInputStream();

        }
        if (len != -1) {
            int ch, i = 0;
            byte[] res = new byte[len];
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);

            }
            return res;

        } else {
            ArrayList<byte[]> buffer = new ArrayList<>();
            int buf_len = 1024;
            byte[] res = new byte[buf_len];
            int ch, i = 0;
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);
                if (i == buf_len) {
                    //rotate
                    buffer.add(res);
                    i = 0;
                    res = new byte[buf_len];

                }

            }
            int total_len = buffer.size() * buf_len + i;
            byte[] buf = new byte[total_len];
            for (int j = 0; j < buffer.size(); j++) {
                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }
            if (i > 0) {
                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }
            return buf;

        }

    } catch (Exception e) {
        e.printStackTrace();
        return null;

    } finally {
        closeInputStream(is_temp);
        closeInputStream(is);

    }

}

From source file:de.thingweb.client.ClientFactory.java

public Client getClientUrl(URI jsonld)
        throws JsonParseException, IOException, UnsupportedException, URISyntaxException {
    // URL can't handle coap uris --> use URI only
    if (isCoapScheme(jsonld.getScheme())) {
        CoapClient coap = new CoapClient(jsonld);

        // synchronous coap
        byte[] content = coap.get().getPayload();
        thing = ThingDescriptionParser.fromBytes(content);

        return getClient();
    } else {//from ww  w  .  java 2 s  .  c  o m
        return getClientUrl(jsonld.toURL());
    }
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.Crawl.java

/**
 * Download the file and extract content informations
 * /*from   w  ww  . j a  va 2s  .c om*/
 * @param httpDownloader
 */
public DownloadItem download(HttpDownloader httpDownloader) {
    synchronized (this) {
        InputStream is = null;
        DownloadItem downloadItem = null;
        try {
            URL url = urlItem.getURL();
            if (url == null)
                throw new MalformedURLException("Malformed URL: " + urlItem.getUrl());
            // URL normalisation
            URI uri = url.toURI();
            url = uri.toURL();

            credentialItem = credentialManager == null ? null : credentialManager.matchCredential(url);

            List<CookieItem> cookieList = cookieManager.getCookies(url.toExternalForm());
            downloadItem = ClientCatalog.getCrawlCacheManager().loadCache(uri);

            boolean fromCache = (downloadItem != null);

            if (!fromCache)
                downloadItem = httpDownloader.get(uri, credentialItem, null, cookieList);
            else if (Logging.isDebug)
                Logging.debug("Crawl cache deliver: " + uri);

            urlItem.setContentDispositionFilename(downloadItem.getContentDispositionFilename());

            urlItem.setContentBaseType(downloadItem.getContentBaseType());

            urlItem.setContentTypeCharset(downloadItem.getContentTypeCharset());

            urlItem.setContentEncoding(downloadItem.getContentEncoding());

            urlItem.setContentLength(downloadItem.getContentLength());

            urlItem.setLastModifiedDate(downloadItem.getLastModified());

            urlItem.setFetchStatus(FetchStatus.FETCHED);

            urlItem.setHeaders(downloadItem.getHeaders());

            Integer code = downloadItem.getStatusCode();
            if (code == null)
                throw new IOException("Http status is null");

            urlItem.setResponseCode(code);
            redirectUrlLocation = downloadItem.getRedirectLocation();
            if (redirectUrlLocation != null)
                urlItem.setRedirectionUrl(redirectUrlLocation.toURL().toExternalForm());

            urlItem.setBacklinkCount(config.getUrlManager().countBackLinks(urlItem.getUrl()));

            if (code >= 200 && code < 300) {
                if (!fromCache)
                    is = ClientCatalog.getCrawlCacheManager().storeCache(downloadItem);
                else
                    is = downloadItem.getContentInputStream();
                parseContent(is);
            } else if (code == 301) {
                urlItem.setFetchStatus(FetchStatus.REDIR_PERM);
            } else if (code > 301 && code < 400) {
                urlItem.setFetchStatus(FetchStatus.REDIR_TEMP);
            } else if (code >= 400 && code < 500) {
                urlItem.setFetchStatus(FetchStatus.GONE);
            } else if (code >= 500 && code < 600) {
                urlItem.setFetchStatus(FetchStatus.HTTP_ERROR);
            }
        } catch (FileNotFoundException e) {
            Logging.info("FileNotFound: " + urlItem.getUrl());
            urlItem.setFetchStatus(FetchStatus.GONE);
            setError("FileNotFound: " + urlItem.getUrl());
        } catch (LimitException e) {
            Logging.warn(e.toString() + " (" + urlItem.getUrl() + ")");
            urlItem.setFetchStatus(FetchStatus.SIZE_EXCEED);
            setError(e.getMessage());
        } catch (InstantiationException e) {
            Logging.error(e.getMessage(), e);
            urlItem.setParserStatus(ParserStatus.PARSER_ERROR);
            setError(e.getMessage());
        } catch (IllegalAccessException e) {
            Logging.error(e.getMessage(), e);
            urlItem.setParserStatus(ParserStatus.PARSER_ERROR);
            setError(e.getMessage());
        } catch (ClassNotFoundException e) {
            Logging.error(e.getMessage(), e);
            urlItem.setParserStatus(ParserStatus.PARSER_ERROR);
            setError(e.getMessage());
        } catch (URISyntaxException e) {
            Logging.warn(e.getMessage(), e);
            urlItem.setFetchStatus(FetchStatus.URL_ERROR);
            setError(e.getMessage());
        } catch (MalformedURLException e) {
            Logging.warn(e.getMessage(), e);
            urlItem.setFetchStatus(FetchStatus.URL_ERROR);
            setError(e.getMessage());
        } catch (IOException e) {
            Logging.error(e.getMessage(), e);
            urlItem.setFetchStatus(FetchStatus.ERROR);
            setError(e.getMessage());
        } catch (IllegalArgumentException e) {
            Logging.error(e.getMessage(), e);
            urlItem.setFetchStatus(FetchStatus.ERROR);
            setError(e.getMessage());
        } catch (Exception e) {
            Logging.error(e.getMessage(), e);
            urlItem.setFetchStatus(FetchStatus.ERROR);
            setError(e.getMessage());
        } finally {
            IOUtils.close(is);
        }
        return downloadItem;
    }
}

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploadHelperTest.java

@Test
public void assureLinksPidResourceReference()
        throws URISyntaxException, MalformedURLException, IOException, MetadataException, WorkspaceException {

    final File uploadDirectory = new File("/workspaces/" + workspaceID + "/upload");

    final String parentFilename = "parent.cmdi";
    final URI parentFileURI = new URI(uploadDirectory.toURI() + File.separator + parentFilename);
    final URL parentFileURL = parentFileURI.toURL();

    final Collection<WorkspaceNode> nodesToCheck = new ArrayList<>();
    nodesToCheck.add(mockChildNode);/*from  w w w .j a  va  2 s .co m*/
    nodesToCheck.add(mockParentNode);

    final Collection<ImportProblem> failedLinks = new ArrayList<>();
    final Map<MetadataDocument, WorkspaceNode> documentsWithInvalidSelfHandles = new HashMap<>();

    context.checking(new Expectations() {
        {

            // loop

            // first iteration - not metadata, so jumps to next iteration
            oneOf(mockNodeUtil).isNodeMetadata(mockChildNode);
            will(returnValue(Boolean.FALSE));

            // second iteration - metadata, so continues in this iteration
            oneOf(mockNodeUtil).isNodeMetadata(mockParentNode);
            will(returnValue(Boolean.TRUE));
            oneOf(mockParentNode).getWorkspaceURL();
            will(returnValue(parentFileURL));
            oneOf(mockMetadataAPI).getMetadataDocument(parentFileURL);
            will(returnValue(mockParentDocument));

            oneOf(mockWorkspaceUploadReferenceHandler).matchReferencesWithNodes(mockWorkpace, nodesToCheck,
                    mockParentNode, mockParentDocument, documentsWithInvalidSelfHandles);
            will(returnValue(failedLinks));
        }
    });

    Collection<ImportProblem> result = workspaceUploadHelper.assureLinksInWorkspace(mockWorkpace, nodesToCheck);

    assertTrue("Result different from expected", result.isEmpty());
}

From source file:org.kitodo.filemanagement.FileManagement.java

@Override
public InputStream read(URI uri) throws IOException {
    uri = fileMapper.mapUriToKitodoDataDirectoryUri(uri);
    return uri.toURL().openStream();
}

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploadHelperTest.java

@Test
public void assureLinksRelativePathReference()
        throws URISyntaxException, MalformedURLException, IOException, MetadataException, WorkspaceException {

    final String parentFilename = "parent.cmdi";
    final URI parentFileURI = new URI("file:/workspaces/" + workspaceID + "/upload/" + parentFilename);
    final URL parentFileURL = parentFileURI.toURL();

    final Collection<WorkspaceNode> nodesToCheck = new ArrayList<>();
    nodesToCheck.add(mockChildNode);//w w  w  .  j ava 2  s  . co  m
    nodesToCheck.add(mockParentNode);

    final Collection<ImportProblem> failedLinks = new ArrayList<>();
    final Map<MetadataDocument, WorkspaceNode> documentsWithInvalidSelfHandles = new HashMap<>();

    context.checking(new Expectations() {
        {

            // loop

            // first iteration - not metadata, so jumps to next iteration
            oneOf(mockNodeUtil).isNodeMetadata(mockChildNode);
            will(returnValue(Boolean.FALSE));

            // second iteration - metadata, so continues in this iteration
            oneOf(mockNodeUtil).isNodeMetadata(mockParentNode);
            will(returnValue(Boolean.TRUE));
            oneOf(mockParentNode).getWorkspaceURL();
            will(returnValue(parentFileURL));
            oneOf(mockMetadataAPI).getMetadataDocument(parentFileURL);
            will(returnValue(mockParentDocument));

            oneOf(mockWorkspaceUploadReferenceHandler).matchReferencesWithNodes(mockWorkpace, nodesToCheck,
                    mockParentNode, mockParentDocument, documentsWithInvalidSelfHandles);
            will(returnValue(failedLinks));
        }
    });

    Collection<ImportProblem> result = workspaceUploadHelper.assureLinksInWorkspace(mockWorkpace, nodesToCheck);

    assertTrue("Result different from expected", result.isEmpty());
}