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.amplafi.flow.launcher.FlowLauncherLinkGeneratorImpl.java

public URI createURI(URI base, FlowLauncher flowLauncher) {
    StringBuilder uriBuilder = new StringBuilder();
    if (this.servicePrefix != null) {
        uriBuilder.append(this.servicePrefix);
    }/*from  w  ww .  ja  v  a  2s  .co  m*/
    uriBuilder.append("/").append(flowLauncher.getFlowTypeName());
    if (flowLauncher instanceof MorphFlowLauncher) {
        // HACK (should be explicitly the FlowStateLookupKey)
        uriBuilder.append("/").append(((MorphFlowLauncher) flowLauncher).getKeyExpression().toString());
        // what would be in the initial state of a morph? perhaps control operations like which flow to morph to?
    } else if (flowLauncher instanceof ContinueFlowLauncher) {
        // HACK (should be explicitly the FlowStateLookupKey)
        uriBuilder.append("/").append(((ContinueFlowLauncher) flowLauncher).getKeyExpression().toString());
        // what would be in the initial state of a continue? perhaps control operations?
    } else if (flowLauncher instanceof StartFromDefinitionFlowLauncher) {
        String createQueryString = UriFactoryImpl.createQueryString(flowLauncher.getInitialFlowState());
        if (isNotBlank(createQueryString)) {
            uriBuilder.append("?");
            uriBuilder.append(createQueryString);
        }
    }
    String uriStr = uriBuilder.toString();
    if (base != null) {
        return base.resolve(uriStr);
    } else {
        return UriFactoryImpl.createUri(uriStr);
    }
}

From source file:se.kodapan.io.http.HttpAccessor.java

private boolean downloadFollowRedirects(final URI referer, final Request request, final Response response)
        throws IOException, SAXException {

    final URI requestURL = request.method.getURI();

    response.finalURL = requestURL;/* w  w w  .j  av a  2 s . c  o  m*/

    if (log.isDebugEnabled()) {
        if (referer != null) {
            log.debug("Redirecting from " + referer + " to " + requestURL);
        }
    }

    if (!response.redirectChain.add(requestURL)) {
        throw new IOException("Circular redirection");
    }

    if (response.redirectChain.size() > 10) {
        throw new IOException("Breaking at link depth " + response.redirectChain.size());
    }

    if (!download(request, response)) {
        return false;
    }

    if (response.httpResponse.getStatusLine().getStatusCode() >= 300
            && response.httpResponse.getStatusLine().getStatusCode() <= 399) {
        URI redirectURL = requestURL.resolve(response.httpResponse.getFirstHeader("Location").getValue());

        // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

        if (response.httpResponse.getStatusLine().getStatusCode() == 303
                && !(request.method instanceof HttpGet)) {
            // 303:s should be redirected as GET
            HttpGet get = new HttpGet(redirectURL);
            for (Header header : request.method.getAllHeaders()) {
                get.addHeader(header);
            }
            request.method = get;
        } else {
            request.method.setURI(redirectURL);
        }

        return downloadFollowRedirects(requestURL, request, response);
    }

    // attempt to follow html meta refresh redirect

    if (response.contentType != null && response.contentType.toLowerCase().startsWith("text/html")) {

        InputSource inputSource;
        if (response.contentEncoding != null) {
            inputSource = new InputSource(
                    new InputStreamReader(new FileInputStream(response.contentFile), response.contentEncoding));
        } else {
            inputSource = new InputSource(new FileInputStream(response.contentFile));
        }
        DOMParser parser = new DOMParser();
        parser.parse(inputSource);
        response.htmlDom = parser.getDocument();

        return NekoHtmlTool.visitNodes(response.htmlDom, requestURL, new NekoHtmlTool.Visitor<Boolean>() {
            public Boolean visit(Node node, URI documentURI) {
                if ("META".equals(node.getLocalName())) {
                    Node httpEquivNode = node.getAttributes().getNamedItem("http-equiv");
                    if (httpEquivNode != null) {
                        String tmp = httpEquivNode.getTextContent();
                        if ("refresh".equalsIgnoreCase(tmp)) {
                            node = node.getAttributes().getNamedItem("content");
                            if (node != null) {
                                tmp = node.getTextContent();
                                Matcher matcher = pattern.matcher(tmp);
                                if (matcher.matches()) {
                                    // 0;url=
                                    int seconds = Integer.valueOf(matcher.group(1));
                                    URI redirectUrl;
                                    redirectUrl = requestURL.resolve(matcher.group(3));
                                    if (!redirectUrl.equals(requestURL)) {
                                        try {
                                            HttpGet get = new HttpGet(redirectUrl);
                                            for (Header header : request.method.getAllHeaders()) {
                                                get.addHeader(header);
                                            }
                                            request.method = get;
                                            if (!downloadFollowRedirects(requestURL, request, response)) {
                                                log.error(
                                                        "Expected a document as we have been redirected to it, but the new URL could not be retrieved. "
                                                                + requestURL + "  --> " + redirectUrl);
                                                return false;
                                            }
                                            return true;

                                        } catch (Exception e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }
        });
    }

    return true;

}

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

/**
 * Creates images files by copy of a configured source dummy image at images
 * source folder of given process./*from  w w  w.  j av  a2 s.c  o m*/
 *
 * @param process
 *            The process object.
 * @param numberOfNewImages
 *            The number of images to be created.
 */
public void createDummyImagesForProcess(Process process, int numberOfNewImages)
        throws IOException, URISyntaxException {
    URI imagesDirectory = getSourceDirectory(process);
    int startValue = getNumberOfFiles(imagesDirectory) + 1;
    URI dummyImage = getDummyImagePath();

    // Load number of digits to create valid filenames
    String numberOfDigits = extractNumber(ConfigCore.getParameter(ParameterCore.IMAGE_PREFIX));

    for (int i = startValue; i < startValue + numberOfNewImages; i++) {
        copyFile(dummyImage, imagesDirectory.resolve(String.format("%0" + numberOfDigits + "d", i) + ".tif"));
    }
}

From source file:org.dita.dost.writer.SeparateChunkTopicParser.java

@Override
public void write(final URI currentFile) throws DITAOTException {
    this.currentFile = currentFile;
    final URI hrefValue = toURI(getValue(rootTopicref, ATTRIBUTE_NAME_HREF));
    final URI copytoValue = toURI(getValue(rootTopicref, ATTRIBUTE_NAME_COPY_TO));
    final String scopeValue = getCascadeValue(rootTopicref, ATTRIBUTE_NAME_SCOPE);
    // Chimera path, has fragment
    URI parseFilePath;//  w  w w. j a  v a2 s.c om
    final Collection<String> chunkValue = split(getValue(rootTopicref, ATTRIBUTE_NAME_CHUNK));
    final String processRoleValue = getCascadeValue(rootTopicref, ATTRIBUTE_NAME_PROCESSING_ROLE);
    boolean dotchunk = false;

    if (copytoValue != null) {
        if (hrefValue != null && hrefValue.getFragment() != null) {
            parseFilePath = setFragment(copytoValue, hrefValue.getFragment());
        } else {
            parseFilePath = copytoValue;
        }
    } else {
        parseFilePath = hrefValue;
    }

    try {
        // if the path to target file make sense
        currentParsingFile = currentFile.resolve(parseFilePath);
        URI outputFileName;
        /*
         * FIXME: we have code flaws here, references in ditamap need to
         * be updated to new created file.
         */
        String id = null;
        String firstTopicID = null;
        if (parseFilePath.getFragment() != null) {
            id = parseFilePath.getFragment();
            if (chunkValue.contains(CHUNK_SELECT_BRANCH)) {
                outputFileName = resolve(currentFile, id + FILE_EXTENSION_DITA);
                targetTopicId = id;
                startFromFirstTopic = false;
                selectMethod = CHUNK_SELECT_BRANCH;
            } else if (chunkValue.contains(CHUNK_SELECT_DOCUMENT)) {
                firstTopicID = getFirstTopicId(currentFile.resolve(parseFilePath).getPath());

                topicDoc = getTopicDoc(currentFile.resolve(parseFilePath));

                if (firstTopicID != null) {
                    outputFileName = resolve(currentFile, firstTopicID + FILE_EXTENSION_DITA);
                    targetTopicId = firstTopicID;
                } else {
                    outputFileName = resolve(currentParsingFile, null);
                    dotchunk = true;
                    targetTopicId = null;
                }
                selectMethod = CHUNK_SELECT_DOCUMENT;
            } else {
                outputFileName = resolve(currentFile, id + FILE_EXTENSION_DITA);
                targetTopicId = id;
                startFromFirstTopic = false;
                selectMethod = CHUNK_SELECT_TOPIC;
            }
        } else {
            firstTopicID = getFirstTopicId(currentFile.resolve(parseFilePath).getPath());

            topicDoc = getTopicDoc(currentFile.resolve(parseFilePath));

            if (firstTopicID != null) {
                outputFileName = resolve(currentFile, firstTopicID + FILE_EXTENSION_DITA);
                targetTopicId = firstTopicID;
            } else {
                outputFileName = resolve(currentParsingFile, null);
                dotchunk = true;
                targetTopicId = null;
            }
            selectMethod = CHUNK_SELECT_DOCUMENT;
        }
        if (copytoValue != null) {
            // use @copy-to value as the new file name
            outputFileName = resolve(currentFile, copytoValue.toString());
        }

        if (new File(outputFileName).exists()) {
            final URI t = outputFileName;
            outputFileName = resolve(currentFile, generateFilename());
            conflictTable.put(outputFileName, t);
            dotchunk = false;
        }
        output = new OutputStreamWriter(new FileOutputStream(new File(outputFileName)), UTF8);
        outputFile = outputFileName;

        if (!dotchunk) {
            final FileInfo fi = generateFileInfo(outputFile);
            job.add(fi);

            changeTable.put(currentFile.resolve(parseFilePath), setFragment(outputFileName, id));
            // new generated file
            changeTable.put(outputFileName, outputFileName);
        }

        // change the href value
        final URI newHref = setFragment(
                getRelativePath(currentFile.resolve(FILE_NAME_STUB_DITAMAP), outputFileName),
                firstTopicID != null ? firstTopicID : id);
        rootTopicref.setAttribute(ATTRIBUTE_NAME_HREF, newHref.toString());

        include = false;

        addStubElements();

        // Place siblingStub
        if (rootTopicref.getNextSibling() != null) {
            rootTopicref.getParentNode().insertBefore(siblingStub, rootTopicref.getNextSibling());
        } else {
            rootTopicref.getParentNode().appendChild(siblingStub);
        }

        reader.setErrorHandler(new DITAOTXMLErrorHandler(currentParsingFile.getPath(), logger));
        logger.info("Processing " + currentParsingFile);
        reader.parse(currentParsingFile.toString());
        output.flush();

        removeStubElements();
    } catch (final RuntimeException e) {
        throw e;
    } catch (final Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (output != null) {
                output.close();
                output = null;
                if (dotchunk) {
                    final File dst = new File(currentParsingFile);
                    final File src = new File(outputFile);
                    logger.debug("Delete " + currentParsingFile);
                    deleteQuietly(dst);
                    logger.debug("Move " + outputFile + " to " + currentParsingFile);
                    moveFile(src, dst);
                    final FileInfo fi = job.getFileInfo(outputFile);
                    if (fi != null) {
                        job.remove(fi);
                    }
                }
            }
        } catch (final Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}

From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java

private URI getUserPrincipal() throws SocketException, ClientProtocolException, AuthenticationException,
        FileNotFoundException, IOException, CaldavProtocolException, URISyntaxException {
    URI uri = this.url.toURI();
    HttpPropFind request = createPropFindRequest(uri, PROPFIND_USER_PRINCIPAL, 0);
    HttpResponse response = httpClient.execute(targetHost, request, mContext);
    checkStatus(response);//ww  w  . j  a  v a  2 s  .  com
    ServerInfoHandler serverInfoHandler = new ServerInfoHandler();
    parseXML(response, serverInfoHandler);
    String userPrincipal = null;
    if (serverInfoHandler.currentUserPrincipal != null) {
        userPrincipal = serverInfoHandler.currentUserPrincipal;
    } else if (serverInfoHandler.principalUrl != null) {
        userPrincipal = serverInfoHandler.principalUrl;
    } else {
        throw new CaldavProtocolException("no principal url found");
    }
    try {
        URI userPrincipalUri = new URI(userPrincipal);
        userPrincipalUri = uri.resolve(userPrincipalUri);
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Found userPrincipal: " + userPrincipalUri.toString());
        }
        return userPrincipalUri;
    } catch (URISyntaxException e) {
        throw new CaldavProtocolException("principal url '" + userPrincipal + "' malformed");
    }
}

From source file:org.eclipse.winery.repository.export.TOSCAExportUtil.java

/**
 * Adds the given id as import to the given imports collection
 *//*ww  w . j  a  va2s .c  om*/
private void addToImports(TOSCAComponentId id, Collection<TImport> imports) {
    TImport imp = new TImport();
    imp.setImportType(org.eclipse.winery.common.constants.Namespaces.TOSCA_NAMESPACE);
    imp.setNamespace(id.getNamespace().getDecoded());
    URI uri = (URI) this.exportConfiguration.get(TOSCAExportUtil.ExportProperties.REPOSITORY_URI.toString());
    if (uri == null) {
        // self-contained mode
        // all Definitions are contained in "Definitions" directory,
        // therefore, we provide the filename only
        // references are resolved relatively from a definitions element
        // (COS01, line 425)
        String fn = CSARExporter.getDefinitionsFileName(id);
        fn = Util.URLencode(fn);
        imp.setLocation(fn);
    } else {
        String path = Utils.getURLforPathInsideRepo(BackendUtils.getPathInsideRepo(id));
        path = path + "?definitions";
        URI absoluteURI = uri.resolve(path);
        imp.setLocation(absoluteURI.toString());
    }
    imports.add(imp);

    // FIXME: Currently the depended elements (such as the artifact
    // templates linked to a node type implementation) are gathered by the
    // corresponding "addXY" method.
    // Reason: the corresponding TDefinitions element is *not* updated if a
    // related element is added/removed.
    // That means: The imports are not changed.
    // The current issue is that TOSCA allows imports of Definitions only
    // and the repository has the concrete elements as main structure
    // Although during save the import can be updated (by fetching the
    // associated resource and get the definitions of it),
    // The concrete definitions cannot be determined without
    // a) having a complete index of all definitions in the repository
    // b) crawling through the *complete* repository
    // Possibly the current solution, just lazily adding all dependent
    // elements is the better solution.
}

From source file:org.dita.dost.module.BranchFilterModule.java

/** Copy and filter topics for branches. These topics have a new name and will be added to job configuration. */
private void generateCopies(final Element topicref, final List<FilterUtils> filters) {
    final List<FilterUtils> fs = combineFilterUtils(topicref, filters);

    final String copyTo = topicref.getAttribute(BRANCH_COPY_TO);
    if (!copyTo.isEmpty()) {
        final URI dstUri = map.resolve(copyTo);
        final URI dstAbsUri = job.tempDirURI.resolve(dstUri);
        final String href = topicref.getAttribute(ATTRIBUTE_NAME_HREF);
        final URI srcUri = map.resolve(href);
        final URI srcAbsUri = job.tempDirURI.resolve(srcUri);
        final FileInfo srcFileInfo = job.getFileInfo(srcUri);
        if (srcFileInfo != null) {
            //                final FileInfo fi = new FileInfo.Builder(srcFileInfo).uri(dstUri).build();
            //                 TODO: Maybe Job should be updated earlier?
            //                job.add(fi);
            logger.info("Filtering " + srcAbsUri + " to " + dstAbsUri);
            final ProfilingFilter writer = new ProfilingFilter();
            writer.setLogger(logger);/*from  ww w.j  av  a 2 s.  com*/
            writer.setJob(job);
            writer.setFilterUtils(fs);
            writer.setCurrentFile(dstAbsUri);
            final List<XMLFilter> pipe = singletonList(writer);

            final File dstDirUri = new File(dstAbsUri.resolve("."));
            if (!dstDirUri.exists() && !dstDirUri.mkdirs()) {
                logger.error("Failed to create directory " + dstDirUri);
            }
            try {
                xmlUtils.transform(srcAbsUri, dstAbsUri, pipe);
            } catch (final DITAOTException e) {
                logger.error("Failed to filter " + srcAbsUri + " to " + dstAbsUri + ": " + e.getMessage(), e);
            }
            topicref.setAttribute(ATTRIBUTE_NAME_HREF, copyTo);
            topicref.removeAttribute(BRANCH_COPY_TO);
            // disable filtering again
            topicref.setAttribute(SKIP_FILTER, Boolean.TRUE.toString());
        }
    }
    for (final Element child : getChildElements(topicref, MAP_TOPICREF)) {
        if (DITAVAREF_D_DITAVALREF.matches(child)) {
            continue;
        }
        generateCopies(child, fs);
    }
}

From source file:com.seajas.search.contender.service.exploration.ExplorationService.java

/**
 * Make an attempt to retrieve all feed links from the given HTML content.
 * //from  w ww  .  j a v a2  s  .co  m
 * @param htmlContent
 * @return List<String>
 */
public List<String> getIndirectlyAccessibleFeedLinks(final URI uri, final String htmlContent) {
    List<String> result = new ArrayList<String>();

    try {
        HtmlCleaner cleaner = new HtmlCleaner();

        TagNode node = cleaner.clean(htmlContent);

        Document document = new CustomDomSerializer(cleaner.getProperties(), true).createDOM(node);

        // Now try to extract the appropriate links

        XPath xpath = XPathFactory.newInstance().newXPath();

        try {
            XPathExpression xpathExpression = xpath.compile(
                    "//head/link[contains(translate(@type, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'rss+xml') or contains(translate(@type, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'atom+xml')]/@href");

            NodeList nodeList = (NodeList) xpathExpression.evaluate(document, XPathConstants.NODESET);

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node listNode = nodeList.item(i);

                if (listNode instanceof Attr) {
                    String resultUrl = ((Attr) listNode).getValue();

                    if (!StringUtils.hasText(resultUrl)) {
                        logger.warn("The given alternate-link tag contains no href - skipping");

                        continue;
                    }

                    try {
                        new URL(resultUrl.trim());

                        result.add(resultUrl.trim());
                    } catch (MalformedURLException e) {
                        try {
                            result.add(uri.resolve(resultUrl.trim()).normalize().toString());
                        } catch (IllegalArgumentException e2) {
                            logger.warn(
                                    "The given (presumably relative) URL is not valid - not adding to the result list",
                                    e2);
                        }
                    }
                } else
                    logger.error("Invalid node type " + listNode.getNodeType() + " - skipping");
            }
        } catch (XPathExpressionException e) {
            logger.error("Could not apply the given XPath expression to extract RSS alternate links", e);
        }

        // Now determine if the URLs are fully-qualified

    } catch (ParserConfigurationException e) {
        logger.info("Could not serialize the given content", e);

        return null;
    }

    return result;
}

From source file:org.apache.ode.bpel.compiler.v1.BpelCompilerImpl.java

public void addXsdImport(URI from, URI location, SourceLocation sloc) {
    URI resFrom = from.resolve(location);
    if (__log.isDebugEnabled())
        __log.debug("Adding XSD import from " + resFrom + " location " + location);
    XMLEntityResolver resolver = new WsdlFinderXMLEntityResolver(_resourceFinder, location,
            new HashMap<URI, String>(), true);
    try {/*from  w w w .ja va2 s.  co m*/
        Map<URI, byte[]> schemas = XSUtils.captureSchema(resFrom.toString(), resolver);
        InputStream xsdStream = _resourceFinder.openResource(resFrom);
        byte[] data;
        try {
            data = StreamUtils.read(xsdStream);
        } finally {
            xsdStream.close();
        }
        schemas.put(resFrom, data);
        _wsdlRegistry.addSchemas(schemas);
    } catch (XsdException e) {
        CompilationException ce = new CompilationException(__cmsgs.errInvalidImport(location.toString()));
        recoveredFromError(sloc, ce);
    } catch (MalformedURLException e) {
        CompilationException ce = new CompilationException(__cmsgs.errInvalidImport(location.toString()));
        recoveredFromError(sloc, ce);
    } catch (IOException e) {
        CompilationException ce = new CompilationException(__cmsgs.errInvalidImport(location.toString()));
        recoveredFromError(sloc, ce);
    }
}

From source file:pl.psnc.dl.wf4ever.sms.SemanticMetadataServiceImplTest.java

@Test
public final void getAnnotations()
        throws FileNotFoundException, URISyntaxException, ManifestTraversingException {
    URI fakeURI = new URI("http://www.example.com/ROs/");
    File file = new File(PROJECT_PATH + "/src/test/resources/rdfStructure/ro1/.ro/manifest.ttl");
    FileInputStream is = new FileInputStream(file);
    SemanticMetadataService sms = new SemanticMetadataServiceImpl(userProfile, ResearchObject.create(fakeURI),
            is, RDFFormat.TURTLE);// ww w .  j ava  2  s  . c o m
    List<Annotation> list = sms.getAnnotations(ResearchObject.create(fakeURI));
    list.get(0).getUri().equals(fakeURI.resolve("ann1"));
    //@TODO check if body and related resources are these same
    try {
    } finally {
        sms.close();
    }
}