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:gr.iti.mklab.bubing.parser.ITIHTMLParser.java

public void processImageURL(URI pageUri, URI base, String imageUri, String altText)
        throws MalformedURLException, IOException {

    URI url = BURL.parse(imageUri);
    if (url != null) {
        URI resolved = base.resolve(url);
        String resolvedStr = resolved.toString();
        //avoid trying to index the same image multiple times
        if (!ItiAgent.UNIQUE_IMAGE_URLS.mightContain(resolvedStr)) {
            // Put it in the bloom filter even if it is not saved eventually
            // to avoid doing the same checks for the same image a second time
            ItiAgent.UNIQUE_IMAGE_URLS.put(resolvedStr);

            final URLConnection con = resolved.toURL().openConnection();

            if (Utils.checkContentHeaders(con.getContentLength(), con.getContentType())) {

                InputStream is = con.getInputStream();

                BufferedImage image = null;
                try {
                    image = ImageIO.read(is);
                } catch (IllegalArgumentException e) {
                    // this exception is probably thrown because of a greyscale jpeg image
                    System.out.println("Exception: " + e.getMessage() + " | Image: " + imageUri);
                    image = ImageIOGreyScale.read(is); // retry with the modified class
                } catch (MalformedURLException e) {
                    System.out.println("Malformed url exception. Url: " + imageUri);
                }// www  .  j av a2  s . com

                if (Utils.checkImage(image)) {

                    Image item = new Image();
                    item.setUrl(resolvedStr);
                    item.setTitle(altText);
                    item.setWidth(image.getWidth());
                    item.setHeight(image.getHeight());
                    item.setWebPageUrl(pageUri.toString());
                    item.setLastModifiedDate(new Date(con.getLastModified()));
                    item.setObjectId(new ObjectId());

                    try {
                        VisualIndexer.getInstance().indexAndStore(image, item);
                    } catch (Exception e) {
                        System.out.println("HTMLImageParser parse exeption: " + e);
                    }

                }
            }
        }
    }
}

From source file:org.restcomm.connect.interpreter.SmsInterpreter.java

protected URI resolve(final URI base, final URI uri) {
    if (base.equals(uri)) {
        return uri;
    } else {/*w ww .  j a  va  2  s  .  com*/
        if (!uri.isAbsolute()) {
            return base.resolve(uri);
        } else {
            return uri;
        }
    }
}

From source file:org.apache.cxf.maven_plugin.AbstractCodegenMoho.java

public URI getWsdlURI(GenericWsdlOption option, URI baseURI) throws MojoExecutionException {
    String wsdlLocation = option.getUri();
    if (wsdlLocation == null) {
        throw new MojoExecutionException("No wsdl available for base URI " + baseURI);
    }// w ww  . j a v a2s . c o  m
    File wsdlFile = new File(wsdlLocation);
    return wsdlFile.exists() ? wsdlFile.toURI() : baseURI.resolve(URIParserUtil.escapeChars(wsdlLocation));
}

From source file:eu.planets_project.tb.gui.backing.data.DigitalObjectBrowser.java

/**
 * @param location//from  w ww  .jav a  2 s.  c  om
 * @return
 */
protected List<DigitalObjectTreeNode> getBreadcrumb(URI location) {
    // Build a list:
    List<DigitalObjectTreeNode> b = new ArrayList<DigitalObjectTreeNode>();
    b.add(this.getRootTreeNode());
    // Get the path and trim any trailing slash:
    String path = "";
    if (location != null && location.getPath() != null)
        path = location.getPath().replaceFirst("/$", "");
    log.info("Getting breadcrumb for path " + path + " from location " + location);
    // Split and descend...
    String[] parts = path.split("/");
    for (int i = 0; i < parts.length; i++) {
        String relative = "./";
        for (int j = 1; j < parts.length - i; j++)
            relative += "../";
        URI newloc = location.resolve(relative);
        if (this.dr.canAccessURI(newloc)) {
            log.debug("Adding parent location: " + newloc);
            b.add(new DigitalObjectTreeNode(newloc));
        }
    }
    return b;
}

From source file:org.esigate.impl.UrlRewriter.java

/**
 * Fixes an url according to the chosen mode.
 * // w w w .  jav  a 2s  .  c o  m
 * @param url
 *            the url to fix (can be anything found in an html page, relative, absolute, empty...)
 * @param requestUrl
 *            The incoming request URL (could be absolute or relative to visible base url).
 * @param baseUrl
 *            The base URL selected for this request.
 * @param visibleBaseUrl
 *            The base URL viewed by the browser.
 * @param absolute
 *            Should the rewritten urls contain the scheme host and port
 * 
 * @return the fixed url.
 */
public String rewriteUrl(String url, String requestUrl, String baseUrl, String visibleBaseUrl,
        boolean absolute) {
    // Base url should end with /
    if (!baseUrl.endsWith("/")) {
        baseUrl = baseUrl + "/";
    }
    URI baseUri = UriUtils.createURI(baseUrl);

    // If no visible url base is defined, use base url as visible base url
    if (!visibleBaseUrl.endsWith("/")) {
        visibleBaseUrl = visibleBaseUrl + "/";
    }
    URI visibleBaseUri = UriUtils.createURI(visibleBaseUrl);

    // Build the absolute Uri of the request sent to the backend
    URI requestUri;
    if (requestUrl.startsWith(visibleBaseUrl)) {
        requestUri = UriUtils.createURI(requestUrl);
    } else {
        requestUri = UriUtils.concatPath(baseUri, requestUrl);
    }

    // Interpret the url relatively to the request url (may be relative)
    URI uri = UriUtils.resolve(url, requestUri);
    // Normalize the path (remove . or .. if possible)
    uri = uri.normalize();

    // Try to relativize url to base url
    URI relativeUri = baseUri.relativize(uri);
    // If the url is unchanged do nothing
    if (relativeUri.equals(uri)) {
        LOG.debug("url kept unchanged: [{}]", url);
        return url;
    }
    // Else rewrite replacing baseUrl by visibleBaseUrl
    URI result = visibleBaseUri.resolve(relativeUri);
    // If mode relative, remove all the scheme://host:port to keep only a url relative to server root (starts with
    // "/")
    if (!absolute) {
        result = UriUtils.removeServer(result);
    }
    LOG.debug("url fixed: [{}] -> [{}]", url, result);
    return result.toString();
}

From source file:org.kitodo.production.services.file.FileService.java

/**
 * Creates a MetaDirectory.//from  ww  w.  ja  va 2  s. c  o  m
 *
 * @param parentFolderUri
 *            The URI, where the
 * @param directoryName
 *            the name of the directory
 * @return true or false
 * @throws IOException
 *             an IOException
 */
URI createMetaDirectory(URI parentFolderUri, String directoryName) throws IOException {
    if (!fileExist(parentFolderUri.resolve(directoryName))) {
        CommandService commandService = ServiceManager.getCommandService();
        String path = FileSystems.getDefault()
                .getPath(ConfigCore.getKitodoDataDirectory(), parentFolderUri.getRawPath(), directoryName)
                .normalize().toAbsolutePath().toString();
        List<String> commandParameter = Collections.singletonList(path);
        File script = new File(ConfigCore.getParameter(ParameterCore.SCRIPT_CREATE_DIR_META));
        CommandResult commandResult = commandService.runCommand(script, commandParameter);
        if (!commandResult.isSuccessful()) {
            String message = MessageFormat.format(
                    "Could not create directory {0} in {1}! No new directory was created", directoryName,
                    parentFolderUri.getPath());
            logger.warn(message);
            throw new IOException(message);
        }
    } else {
        logger.info("Metadata directory: {} already existed! No new directory was created", directoryName);
    }
    return URI.create(parentFolderUri.getPath() + '/' + directoryName);
}

From source file:org.keycloak.testsuite.util.saml.RequiredConsentBuilder.java

/**
 * Prepares a GET/POST request for consent granting . The consent page is expected
 * to have at least input fields with id "kc-login" and "kc-cancel".
 *
 * @param consentPage/*w w w .  j  a  va2 s  .c o m*/
 * @param consent
 * @return
 */
public HttpUriRequest handleConsentPage(String consentPage, URI currentURI) {
    org.jsoup.nodes.Document theLoginPage = Jsoup.parse(consentPage);

    List<NameValuePair> parameters = new LinkedList<>();
    for (Element form : theLoginPage.getElementsByTag("form")) {
        String method = form.attr("method");
        String action = form.attr("action");
        boolean isPost = method != null && "post".equalsIgnoreCase(method);

        for (Element input : form.getElementsByTag("input")) {
            if (Objects.equals(input.id(), "kc-login")) {
                if (approveConsent)
                    parameters.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
            } else if (Objects.equals(input.id(), "kc-cancel")) {
                if (!approveConsent)
                    parameters.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
            } else {
                parameters.add(new BasicNameValuePair(input.attr("name"), input.val()));
            }
        }

        if (isPost) {
            HttpPost res = new HttpPost(currentURI.resolve(action));

            UrlEncodedFormEntity formEntity;
            try {
                formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            res.setEntity(formEntity);

            return res;
        } else {
            UriBuilder b = UriBuilder.fromPath(action);
            for (NameValuePair parameter : parameters) {
                b.queryParam(parameter.getName(), parameter.getValue());
            }
            return new HttpGet(b.build());
        }
    }

    throw new IllegalArgumentException("Invalid consent page: " + consentPage);
}

From source file:org.koiroha.jyro.workers.crawler.Crawler.java

/**
 * Parse content.//w  w  w .j  a va  2s  .c o  m
 *
 * @param content content to analyze
 * @throws WorkerException if fail to retrieve
*/
private List<URI> parseHtmlContent(URI uri, String type, byte[] content) {
    List<URI> urls = new ArrayList<URI>();

    try {
        // parse html document
        Charset def = Xml.getCharset(type);
        HTMLDocumentBuilderFactory factory = new HTMLDocumentBuilderFactory();
        factory.setNamespaceAware(false);
        factory.setXIncludeAware(false);
        InputSource is = factory.guessInputSource(new ByteArrayInputStream(content), def.name(),
                content.length);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);

        // extract link
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nl = (NodeList) xpath.evaluate("//a/@href", doc, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            String href = ((Attr) nl.item(i)).getValue();
            urls.add(uri.resolve(href));
        }
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
    return urls;
}

From source file:org.apache.hadoop.hive.shims.Hadoop20Shims.java

@Override
public URI getHarUri(URI original, URI base, URI originalBase) throws URISyntaxException {
    URI relative = null;/*from   w w w  . j a va 2s  .c  om*/

    String dirInArchive = original.getPath();
    if (dirInArchive.length() > 1 && dirInArchive.charAt(0) == '/') {
        dirInArchive = dirInArchive.substring(1);
    }

    relative = new URI(null, null, dirInArchive, null);

    return base.resolve(relative);
}

From source file:gr.iti.mklab.bubing.parser.ITIHTMLParser.java

/**
 * Pre-process a string that represents a raw link found in the page, trying to derelativize it. If it succeeds, the
 * resulting URL is passed to the link receiver.
 *
 * @param linkReceiver the link receiver that will receive the resulting URL.
 * @param base         the base URL to be used to derelativize the link.
 * @param s            the raw link to be derelativized.
 *///from  w  w  w . j av  a 2 s . c o  m
protected void process(final LinkReceiver linkReceiver, final URI base, final String s, final String text,
        boolean checkImage) {
    if (s == null)
        return;
    URI url = BURL.parse(s);
    if (url == null)
        return;
    if (checkImage && Utils.isImageUrl(s)) {
        try {
            processImageURL(url, base, s, text);
        } catch (Exception ex) {
        }
    } else
        linkReceiver.link(base.resolve(url));
}