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:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploadHelperTest.java

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

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

    final Collection<WorkspaceNode> nodesToCheck = new ArrayList<>();
    nodesToCheck.add(mockChildNode);//from  w w  w.ja v  a  2s  .  c o  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.mycore.common.xml.MCREntityResolver.java

private boolean uriExists(URI absoluteSystemId) {
    if (absoluteSystemId.getScheme().startsWith("http")) {
        return false; //default resolver handles http anyway
    }// ww  w . ja  v a2 s .c  o  m
    if (absoluteSystemId.getScheme().equals("jar")) {
        //multithread issues, when using ZIP filesystem with second check
        try {
            URL jarURL = absoluteSystemId.toURL();
            try (InputStream is = jarURL.openStream()) {
                return is != null;
            }
        } catch (IOException e) {
            LOGGER.error("Error while checking (URL) URI: " + absoluteSystemId, e);
        }
    }
    try {
        if (isFileSystemAvailable(absoluteSystemId.getScheme())) {
            Path pathTest = Paths.get(absoluteSystemId);
            LOGGER.debug("Checking: " + pathTest);
            return Files.exists(pathTest);
        }
    } catch (Exception e) {
        LOGGER.error("Error while checking (Path) URI: " + absoluteSystemId, e);
    }
    return false;
}

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

@Test
public void assureLinksPidMetadataReference()
        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 String childFilename = "child.cmdi";
    final File childFile = new File("/workspaces/" + workspaceID + "/upload/"
            + FilenameUtils.getBaseName(parentFilename) + File.separator + childFilename);
    final URI childFileURI = childFile.toURI();
    final URL childFileURL = childFileURI.toURL();

    final Collection<WorkspaceNode> nodesToCheck = new ArrayList<>();
    nodesToCheck.add(mockChildNode);//w w w. j  av  a  2  s.com
    nodesToCheck.add(mockParentNode);

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

    context.checking(new Expectations() {
        {

            // loop

            // first iteration - metadata, so continues in this iteration
            oneOf(mockNodeUtil).isNodeMetadata(mockChildNode);
            will(returnValue(Boolean.TRUE));
            oneOf(mockChildNode).getWorkspaceURL();
            will(returnValue(childFileURL));
            oneOf(mockMetadataAPI).getMetadataDocument(childFileURL);
            will(returnValue(mockChildDocument));

            // 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:com.liferay.maven.plugins.AbstractLiferayMojo.java

protected List<String> getProjectClassPath() throws Exception {
    List<String> projectClassPath = new ArrayList<String>();

    projectClassPath.addAll(getToolsClassPath());

    for (Object object : project.getCompileClasspathElements()) {
        String path = (String) object;

        File file = new File(path);

        URI uri = file.toURI();

        URL url = uri.toURL();

        projectClassPath.add(url.toString());
    }//from   w  w w  .j  a  v  a  2s.  com

    getLog().debug("Project class path:");

    for (String path : projectClassPath) {
        getLog().debug("\t" + path);
    }

    return projectClassPath;
}

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

@Test
public void assureLinksPidMetadataReference_FailedLink()
        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 String childFilename = "child.cmdi";
    final File childFile = new File("/workspaces/" + workspaceID + "/upload/"
            + FilenameUtils.getBaseName(parentFilename) + File.separator + childFilename);
    final URI childFileURI = childFile.toURI();
    final URL childFileURL = childFileURI.toURL();

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

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

    context.checking(new Expectations() {
        {

            // loop

            // first iteration - metadata, so continues in this iteration
            oneOf(mockNodeUtil).isNodeMetadata(mockChildNode);
            will(returnValue(Boolean.TRUE));
            oneOf(mockChildNode).getWorkspaceURL();
            will(returnValue(childFileURL));
            oneOf(mockMetadataAPI).getMetadataDocument(childFileURL);
            will(returnValue(mockChildDocument));

            // 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.containsAll(failedLinks));
}

From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java

protected void addDependencyToClassPath(List<String> classPath, Dependency dependency) throws Exception {

    URI uri = resolveArtifactFileURI(dependency);

    URL url = uri.toURL();

    classPath.add(url.toString());//from ww  w.  ja  va 2s  .  c  om
}

From source file:org.apache.fop.apps.FOURIResolver.java

/**
 * Checks if the given base URL is acceptable. It also normalizes the URL.
 * @param base the base URL to check//from   www.j  a v  a2  s.  co  m
 * @return the normalized URL
 * @throws MalformedURLException if there's a problem with a file URL
 */
public String checkBaseURL(String base) throws MalformedURLException {
    // replace back slash with forward slash to ensure windows file:/// URLS are supported
    base = base.replace('\\', '/');
    if (!base.endsWith("/")) {
        // The behavior described by RFC 3986 regarding resolution of relative
        // references may be misleading for normal users:
        // file://path/to/resources + myResource.res -> file://path/to/myResource.res
        // file://path/to/resources/ + myResource.res -> file://path/to/resources/myResource.res
        // We assume that even when the ending slash is missing, users have the second
        // example in mind
        base += "/";
    }
    File dir = new File(base);
    if (dir.isDirectory()) {
        return dir.toURI().toASCIIString();
    } else {
        URI baseURI;
        try {
            baseURI = new URI(base);
            String scheme = baseURI.getScheme();
            boolean directoryExists = true;
            if ("file".equals(scheme)) {
                dir = FileUtils.toFile(baseURI.toURL());
                directoryExists = dir.isDirectory();
            }
            if (scheme == null || !directoryExists) {
                String message = "base " + base + " is not a valid directory";
                if (throwExceptions) {
                    throw new MalformedURLException(message);
                }
                log.error(message);
            }
            return baseURI.toASCIIString();
        } catch (URISyntaxException e) {
            //TODO not ideal: our base URLs are actually base URIs.
            throw new MalformedURLException(e.getMessage());
        }
    }
}

From source file:org.apache.xml.security.utils.resolver.implementations.ResolverDirectHTTP.java

/**
 * Method resolve/*  w  w w. j ava 2 s.  c om*/
 *
 * @param uri
 * @param baseURI
 *
 * @throws ResourceResolverException
 * @return 
 * $todo$ calculate the correct URI from the attribute and the baseURI
 */
public XMLSignatureInput engineResolve(Attr uri, String baseURI) throws ResourceResolverException {
    try {
        boolean useProxy = false;
        String proxyHost = engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyHost]);
        String proxyPort = engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPort]);

        if ((proxyHost != null) && (proxyPort != null)) {
            useProxy = true;
        }

        String oldProxySet = null;
        String oldProxyHost = null;
        String oldProxyPort = null;
        // switch on proxy usage
        if (useProxy) {
            if (log.isDebugEnabled()) {
                log.debug("Use of HTTP proxy enabled: " + proxyHost + ":" + proxyPort);
            }
            oldProxySet = System.getProperty("http.proxySet");
            oldProxyHost = System.getProperty("http.proxyHost");
            oldProxyPort = System.getProperty("http.proxyPort");
            System.setProperty("http.proxySet", "true");
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
        }

        boolean switchBackProxy = ((oldProxySet != null) && (oldProxyHost != null) && (oldProxyPort != null));

        // calculate new URI
        URI uriNew = null;
        try {
            uriNew = getNewURI(uri.getNodeValue(), baseURI);
        } catch (URISyntaxException ex) {
            throw new ResourceResolverException("generic.EmptyMessage", ex, uri, baseURI);
        }

        URL url = uriNew.toURL();
        URLConnection urlConnection = url.openConnection();

        {
            // set proxy pass
            String proxyUser = engineGetProperty(
                    ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyUser]);
            String proxyPass = engineGetProperty(
                    ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPass]);

            if ((proxyUser != null) && (proxyPass != null)) {
                String password = proxyUser + ":" + proxyPass;
                String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1"));

                // or was it Proxy-Authenticate ?
                urlConnection.setRequestProperty("Proxy-Authorization", encodedPassword);
            }
        }

        {
            // check if Basic authentication is required
            String auth = urlConnection.getHeaderField("WWW-Authenticate");

            if (auth != null && auth.startsWith("Basic")) {
                // do http basic authentication
                String user = engineGetProperty(
                        ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicUser]);
                String pass = engineGetProperty(
                        ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicPass]);

                if ((user != null) && (pass != null)) {
                    urlConnection = url.openConnection();

                    String password = user + ":" + pass;
                    String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1"));

                    // set authentication property in the http header
                    urlConnection.setRequestProperty("Authorization", "Basic " + encodedPassword);
                }
            }
        }

        String mimeType = urlConnection.getHeaderField("Content-Type");
        InputStream inputStream = urlConnection.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buf[] = new byte[4096];
        int read = 0;
        int summarized = 0;

        while ((read = inputStream.read(buf)) >= 0) {
            baos.write(buf, 0, read);
            summarized += read;
        }

        if (log.isDebugEnabled()) {
            log.debug("Fetched " + summarized + " bytes from URI " + uriNew.toString());
        }

        XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());

        result.setSourceURI(uriNew.toString());
        result.setMIMEType(mimeType);

        // switch off proxy usage
        if (useProxy && switchBackProxy) {
            System.setProperty("http.proxySet", oldProxySet);
            System.setProperty("http.proxyHost", oldProxyHost);
            System.setProperty("http.proxyPort", oldProxyPort);
        }

        return result;
    } catch (MalformedURLException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, baseURI);
    } catch (IOException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, baseURI);
    }
}

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

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

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

    final String childFilename = "child.cmdi";
    final File childFile = new File("/workspaces/" + workspaceID + "/upload/"
            + FilenameUtils.getBaseName(parentFilename) + File.separator + childFilename);
    final URI childFileURI = childFile.toURI();
    final URL childFileURL = childFileURI.toURL();

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

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

    context.checking(new Expectations() {
        {

            // loop

            // first iteration - metadata, so continues in this iteration
            oneOf(mockNodeUtil).isNodeMetadata(mockChildNode);
            will(returnValue(Boolean.TRUE));
            oneOf(mockChildNode).getWorkspaceURL();
            will(returnValue(childFileURL));
            oneOf(mockMetadataAPI).getMetadataDocument(childFileURL);
            will(returnValue(mockChildDocument));

            // 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(doAll(AddEntryToMap.putElements(mockParentDocument, mockParentNode),
                    returnValue(failedLinks)));
        }
    });

    context.checking(new Expectations() {
        {
            oneOf(mockParentNode).getWorkspaceURL();
            will(returnValue(parentFileURL));
            oneOf(mockMetadataApiBridge).removeSelfHandleAndSaveDocument(mockParentDocument, parentFileURL);
        }
    });

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

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