Example usage for java.net URI resolve

List of usage examples for java.net URI resolve

Introduction

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

Prototype

public URI resolve(String str) 

Source Link

Document

Constructs a new URI by parsing the given string and then resolving it against this URI.

Usage

From source file:org.orbeon.oxf.util.URLRewriterUtils.java

/**
 * Rewrite a URL based on a base URL, a URL, and a rewriting mode.
 *
 * @param scheme            base URL scheme
 * @param host              base URL host
 * @param port              base URL port
 * @param contextPath       base URL context path
 * @param requestPath       base URL request path
 * @param urlString         URL to rewrite (accept human-readable URI)
 * @param rewriteMode       rewrite mode (see ExternalContext.Response)
 * @return                  rewritten URL
 *///from   w  w w  . j a va2  s . c om
private static String rewriteURL(String scheme, String host, int port, String contextPath, String requestPath,
        String urlString, int rewriteMode) {
    // Accept human-readable URI
    urlString = NetUtils.encodeHRRI(urlString, true);

    // Case where a protocol is specified: the URL is left untouched (except for human-readable processing)
    if (NetUtils.urlHasProtocol(urlString))
        return urlString;

    try {
        final String baseURLString;
        {
            String _baseURLString;
            // Prepend absolute base if needed
            if ((rewriteMode & ExternalContext.Response.REWRITE_MODE_ABSOLUTE) != 0) {
                _baseURLString = scheme + "://" + host + ((port == 80 || port == -1) ? "" : ":" + port);
            } else {
                _baseURLString = "";
            }
            // Append context path if needed
            if ((rewriteMode & ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_NO_CONTEXT) == 0)
                _baseURLString = _baseURLString + contextPath;

            baseURLString = _baseURLString;
        }

        // Return absolute path URI with query string and fragment identifier if needed
        if (urlString.startsWith("?")) {
            // This is a special case that appears to be implemented
            // in Web browsers as a convenience. Users may use it.
            return baseURLString + requestPath + urlString;
        } else if ((rewriteMode & ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE) != 0
                && !urlString.startsWith("/") && !"".equals(urlString)) {
            // Don't change the URL if it is a relative path and we don't force absolute
            return urlString;
        } else {
            // Regular case, parse the URL

            final URI baseURIWithPath = new URI("http", "example.org", requestPath, null);
            final URI resolvedURI = baseURIWithPath.resolve(urlString).normalize();// normalize to remove "..", etc.

            // Append path, query and fragment
            final String query = resolvedURI.getRawQuery();
            final String fragment = resolvedURI.getRawFragment();
            final String tempResult = resolvedURI.getRawPath() + ((query != null) ? "?" + query : "")
                    + ((fragment != null) ? "#" + fragment : "");

            // Prepend base
            return baseURLString + tempResult;
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:com.microsoft.alm.common.utils.UrlHelper.java

public static URI resolveEndpointUri(URI baseUri, String endpointPath) {
    if (!baseUri.getPath().endsWith("/")) {
        baseUri = createUri(baseUri.toString() + "/");
    }/*from w w  w  .j  a v  a  2s  .c o m*/

    if (endpointPath.startsWith("/")) {
        endpointPath = endpointPath.substring(1);
    }

    return baseUri.resolve(endpointPath);
}

From source file:org.hl7.fhir.client.ClientUtils.java

/**
 * ***************************************************************
 * Client connection methods//www.jav  a 2 s .c om
* **************************************************************
 */
public static HttpURLConnection buildConnection(URI baseServiceUri, String tail) {
    try {
        HttpURLConnection client = (HttpURLConnection) baseServiceUri.resolve(tail).toURL().openConnection();
        return client;
    } catch (MalformedURLException mue) {
        throw new EFhirClientException("Invalid Service URL", mue);
    } catch (IOException ioe) {
        throw new EFhirClientException(
                "Unable to establish connection to server: " + baseServiceUri.toString() + tail, ioe);
    }
}

From source file:fr.gael.dhus.service.ProductService.java

private static boolean checkUrl(URL url) {
    Objects.requireNonNull(url, "`url` parameter must not be null");

    // OData Synchronized product, DELME
    if (url.getPath().endsWith("$value")) {
        // Ignoring ...
        return true;
    }/*from   w w  w .j  a v  a 2s  .  c om*/

    // Case of simple file
    try {
        File f = new File(url.toString());
        if (f.exists())
            return true;
    } catch (Exception e) {
        logger.debug("url \"" + url + "\" not formatted as a file");
    }

    // Case of local URL
    try {
        URI local = new File(".").toURI();
        URI uri = local.resolve(url.toURI());
        File f = new File(uri);
        if (f.exists())
            return true;
    } catch (Exception e) {
        logger.debug("url \"" + url + "\" not a local URL");
    }

    // Case of remote URL
    try {
        URLConnection con = url.openConnection();
        con.connect();
        InputStream is = con.getInputStream();
        is.close();
        return true;
    } catch (Exception e) {
        logger.debug("url \"" + url + "\" not a remote URL");
    }
    // Unrecovrable case
    return false;
}

From source file:UriUtils.java

/**
 * Returns the parent of the specified URI.
 * <p/>//w w  w .jav  a2s  .  c  om
 * For example, applying this method to the URI &quot;<tt>http://www.site.com/articles/article.html</tt>&quot; will
 * return the URI for &quot;<tt>http://www.site.com/articles/</tt>&quot;.
 *
 * @param uri The URI for which to return the parent.
 * @return The parent of the specified URI.
 * @throws IllegalArgumentException <ul> <li>The URI cannot be null></li> <li>Can't resolve parent for the specified
 *                                  URI.</li> </ul>
 */
public static URI getParent(final URI uri) throws IllegalArgumentException {
    if (uri == null)
        throw new IllegalArgumentException("The URI cannot be null.");

    final String path = uri.toString();
    final int finalSeparator = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
    final int extension = path.lastIndexOf('.');
    if (extension > finalSeparator)
        try {
            // Extract all but final segment
            return new URI(path.substring(0, finalSeparator + 1)).normalize();
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Can't resolve parent for the specified URI.", e);
        }
    else
        return uri.resolve(up);
}

From source file:edu.usc.goffish.gofs.tools.GoFSDeployGraph.java

private static void writeSlices(IPartitionDirectory partitionDirectory, String graphId,
        IPartitionBuilder partitionBuilder, IPartitionMapper partitionMapper,
        IPartitionDistributer partitionDistributer, Long2LongOpenHashMap remoteVerticesMappings)
        throws IOException {
    long time;//w  ww  .j  a va2  s. co m
    int totalSubgraphs = 0;

    // write slices and deploy
    for (ISerializablePartition partition : partitionBuilder.getPartitions()) {

        // assign remote vertex subgraph ids
        for (ISubgraph subgraph : partition) {
            for (ITemplateVertex remoteVertex : subgraph.remoteVertices()) {
                // CHEAT
                if (!(remoteVertex instanceof TemplateRemoteVertex)) {
                    throw new IllegalStateException();
                }
                ((TemplateRemoteVertex) remoteVertex)
                        .setRemoteSubgraphId(remoteVerticesMappings.get(remoteVertex.getId()));
            }
        }

        System.out.println("**partition " + partition.getId() + " has " + partition.size()
                + " subgraphs across " + partition.numVertices() + " vertices");
        totalSubgraphs += partition.size();

        System.out.println("distributing partition " + partition.getId() + "...");
        time = System.currentTimeMillis();

        URI dataNodeLocation = partitionMapper.getLocationForPartition(partition);
        URI slicesLocation = dataNodeLocation.resolve(DataNode.DATANODE_SLICE_DIR.toString());

        UUID fragment = partitionDistributer.distribute(slicesLocation, partition);
        partitionDirectory.putPartitionMapping(graphId, partition.getId(),
                dataNodeLocation.resolve("#" + fragment.toString()));

        System.out.println("distribution finished [" + (System.currentTimeMillis() - time) + "ms]");
    }

    System.out.println("**total subgraphs: " + totalSubgraphs);
}

From source file:org.apache.axis2.jaxws.description.impl.DescriptionUtils.java

/**
 * This is a helper method that will open a stream to an @HandlerChain configuration file.
 *
 * @param configFile  - The path to the file
 * @param className   - The class in which the annotation was declared. This is used in case the
 *                    file path is relative.
 * @param classLoader - ClassLoader used to load relative file paths.
 * @return/*from www.  j av  a 2  s. co  m*/
 */
public static InputStream openHandlerConfigStream(String configFile, String className,
        ClassLoader classLoader) {
    InputStream configStream = null;
    URL configURL;
    if (log.isDebugEnabled()) {
        log.debug("Attempting to load @HandlerChain configuration file: " + configFile + " relative to class: "
                + className);
    }
    // Attempt 1:
    // Try absolute loading
    try {
        if (log.isDebugEnabled()) {
            log.debug("Attempt 1: Try absolute load of (" + configFile + ")");
        }
        configURL = new URL(configFile);
        if (configURL != null) {
            if (log.isDebugEnabled()) {
                log.debug("Found absolute @HandlerChain configuration file: " + configFile);
            }
            configStream = configURL.openStream();
        }
    } catch (MalformedURLException e) {
        // try another method to obtain a stream to the configuration file
        if (log.isDebugEnabled()) {
            log.debug("Attempt 1 Failed with exception.  Try Attempt 2.  " + "The caught exception is : " + e);
        }
    } catch (IOException e) {
        // report this since it was a valid URL but the openStream caused a problem
        if (log.isDebugEnabled()) {
            log.debug("The URL was valid, but opening the stream " + "caused a problem : " + e);
        }
        throw ExceptionFactory.makeWebServiceException(
                Messages.getMessage("hcConfigLoadFail", configFile, className, e.toString()));
    }

    // Attempt 2:
    // Try relative uri loading from Classloaders
    if (configStream == null) {
        if (log.isDebugEnabled()) {
            log.debug("@HandlerChain.file attribute refers to a relative location: " + configFile);
            log.debug("Attempt 2: Try relative uri load of (" + configFile + ") " + "from the classloaders");
        }
        className = className.replace(".", "/");
        try {
            if (log.isDebugEnabled()) {
                log.debug("Resolving @HandlerChain configuration file: " + configFile
                        + " relative to class file: " + className);
            }
            URI uri = new URI(className);
            uri = uri.resolve(configFile);
            String resolvedPath = uri.toString();
            if (log.isDebugEnabled()) {
                log.debug("@HandlerChain.file resolved file path location: " + resolvedPath);
            }
            configStream = getInputStream_priv(resolvedPath, classLoader);
        } catch (Throwable e) {
            if (log.isDebugEnabled()) {
                log.debug("Attempt 2 Failed with exception. " + "The caught exception is : " + e);
            }
            throw ExceptionFactory.makeWebServiceException(
                    Messages.getMessage("hcConfigLoadFail", configFile, className, e.toString()));
        }
    }
    if (configStream == null) {
        //throw ExceptionFactory.makeWebServiceException(Messages.getMessage("handlerChainNS",
        //                                                             configFile, className));
        // No longer throwing an exception here.  This method is best-effort, and the caller may
        // change the class to which the path is relative and try again.  The caller is responsible
        // for determining when to "give up"
        if (log.isDebugEnabled()) {
            log.debug("@HandlerChain configuration fail: " + configFile + " in class: " + className
                    + " failed to load.");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("@HandlerChain configuration file: " + configFile + " in class: " + className
                    + " was successfully loaded.");
        }
    }
    return configStream;
}

From source file:pl.psnc.ep.rt.web.servlets.CollXMLServlet.java

private static String getRepositoryURL(ServletRequestWrapper reqWr) {
    String requestUrl = reqWr.getRequestUrl(reqWr.isSecure());
    try {/*from  www  .  j  av a 2 s. c o  m*/
        URI uri = new URI(requestUrl);
        uri = uri.resolve("/");
        String result = uri.toString();
        if (result.endsWith("/"))
            result = result.substring(0, result.length() - 1);
        return result;
    } catch (URISyntaxException e) {
        throw new RuntimeException("Invalid request url? " + requestUrl);
    }
}

From source file:net.minecraftforge.common.crafting.CraftingHelper.java

public static boolean findFiles(ModContainer mod, String base, Function<Path, Boolean> preprocessor,
        BiFunction<Path, Path, Boolean> processor) {
    FileSystem fs = null;//from   ww  w.j a  va  2  s .  c  o  m
    try {
        File source = mod.getSource();

        if ("minecraft".equals(mod.getModId()) && DEBUG_LOAD_MINECRAFT) {
            try {
                URI tmp = CraftingManager.class.getResource("/assets/.mcassetsroot").toURI();
                source = new File(tmp.resolve("..").getPath());
            } catch (URISyntaxException e) {
                FMLLog.log.error("Error finding Minecraft jar: ", e);
                return false;
            }
        }

        Path root = null;
        if (source.isFile()) {
            try {
                fs = FileSystems.newFileSystem(source.toPath(), null);
                root = fs.getPath("/" + base);
            } catch (IOException e) {
                FMLLog.log.error("Error loading FileSystem from jar: ", e);
                return false;
            }
        } else if (source.isDirectory()) {
            root = source.toPath().resolve(base);
        }

        if (root == null || !Files.exists(root))
            return false;

        if (preprocessor != null) {
            Boolean cont = preprocessor.apply(root);
            if (cont == null || !cont.booleanValue())
                return false;
        }

        if (processor != null) {
            Iterator<Path> itr = null;
            try {
                itr = Files.walk(root).iterator();
            } catch (IOException e) {
                FMLLog.log.error("Error iterating filesystem for: {}", mod.getModId(), e);
                return false;
            }

            while (itr != null && itr.hasNext()) {
                Boolean cont = processor.apply(root, itr.next());
                if (cont == null || !cont.booleanValue())
                    return false;
            }
        }

        return true;
    } finally {
        IOUtils.closeQuietly(fs);
    }
}

From source file:com.sworddance.util.UriFactoryImpl.java

/**
 * @param httpUri//w  ww  . j  a va  2  s .  c o  m
 * @return root URI
 */
public static URI getRootDirectory(URI httpUri) {
    String path = httpUri.getPath();
    URI base = httpUri.resolve(substringBeforeLast(path, PATH_SEPARATOR) + PATH_SEPARATOR);
    return base;
}