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:net.ripe.rpki.validator.util.HierarchicalUriCache.java

public boolean contains(URI uriToCheck) {
    URI uri = uriToCheck;
    while (StringUtils.isNotEmpty(uri.getRawPath())) {
        if (cache.contains(uri)) {
            return true;
        }/*from   w ww .  j  a  v a  2s  .  co  m*/
        String path = uri.getRawPath();
        if ("/".equals(path)) {
            return false;
        }

        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }

        int i = path.lastIndexOf('/');
        if (i != -1) {
            uri = uri.resolve(path.substring(0, i + 1));
        } else {
            return false;
        }
    }
    return false;
}

From source file:org.eclipse.orion.server.cf.commands.CheckRouteCommand.java

@Override
protected ServerStatus _doIt() {
    try {/* ww w  . j a  v  a 2  s  .c om*/
        URI targetURI = URIUtil.toURI(target.getUrl());
        ServerStatus getRouteStatus;

        GetDomainsCommand getDomainsCommand = new GetDomainsCommand(target, domainName);
        ServerStatus getDomainsStatus = (ServerStatus) getDomainsCommand.doIt();
        if (!getDomainsStatus.isOK())
            return getDomainsStatus;

        String domainId = getDomainsCommand.getDomains().get(0).getGuid();

        URI routesURI = targetURI.resolve("/v2/routes/reserved/domain/" + domainId + "/host/" + hostName);
        GetMethod getRouteMethod = new GetMethod(routesURI.toString());
        HttpUtil.configureHttpMethod(getRouteMethod, target.getCloud());

        getRouteStatus = HttpUtil.executeMethod(getRouteMethod);

        if (!getRouteStatus.isOK()) {
            if (getRouteStatus.getHttpCode() == 404
                    && getRouteStatus.getJsonData().getString("error_code").equals("CF-NotFound"))
                return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, null);
            return getRouteStatus;
        }
        JSONObject result = new JSONObject();
        if (getRouteStatus.getMessage().equals("OK")) {
            result.append("Route", getRouteStatus.toJSON());
        }

        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);

    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.openvpms.web.echo.dialog.HelpDialog.java

/**
 * Tries to locate an existing URL for the given topic URL.
 *
 * @param topicURL the topic URL//  w w  w  . j  a  v  a  2s  .c om
 * @return the closest parent URL to the topic that exists, or {@code null} if none is found
 */
private String getExistingParent(String topicURL) {
    String result = null;
    try {
        URI uri = new URI(topicURL);
        String path = uri.getPath();
        while (!StringUtils.isEmpty(path)) {
            if (!path.endsWith("/")) {
                uri = uri.resolve(".");
            } else {
                uri = uri.resolve("..");
            }
            String parent = uri.toURL().toString();
            if (exists(parent)) {
                result = parent;
                break;
            }
            path = uri.getPath();
        }
    } catch (URISyntaxException exception) {
        log.debug(exception, exception);
    } catch (MalformedURLException exception) {
        log.debug(exception, exception);
    }
    return result;
}

From source file:de.sub.goobi.export.download.ExportMets.java

/**
 * write MetsFile to given Path.//from ww  w  .  j  av a2s. co m
 *
 * @param myProcess
 *            the Process to use
 * @param metaFile
 *            the meta file which should be written
 * @param gdzfile
 *            the FileFormat-Object to use for Mets-Writing
 */

protected boolean writeMetsFile(Process myProcess, URI metaFile, Fileformat gdzfile,
        boolean writeLocalFilegroup)
        throws PreferencesException, WriteException, IOException, TypeNotAllowedForParentException {

    MetsModsImportExport mm = new MetsModsImportExport(this.myPrefs);
    mm.setWriteLocal(writeLocalFilegroup);
    URI imageFolderPath = serviceManager.getFileService().getImagesDirectory(myProcess);
    /*
     * before creating mets file, change relative path to absolute -
     */
    DigitalDocument dd = gdzfile.getDigitalDocument();
    if (dd.getFileSet() == null) {
        Helper.setMeldung(myProcess.getTitle()
                + ": digital document does not contain images; temporarily adding them for mets file creation");
        MetadatenImagesHelper mih = new MetadatenImagesHelper(this.myPrefs, dd);
        mih.createPagination(myProcess, null);
    }

    /*
     * get the topstruct element of the digital document depending on anchor
     * property
     */
    DocStruct topElement = dd.getLogicalDocStruct();
    if (this.myPrefs.getDocStrctTypeByName(topElement.getType().getName()).getAnchorClass() != null) {
        if (topElement.getAllChildren() == null || topElement.getAllChildren().size() == 0) {
            throw new PreferencesException(myProcess.getTitle()
                    + ": the topstruct element is marked as anchor, but does not have any children for "
                    + "physical docstrucs");
        } else {
            topElement = topElement.getAllChildren().get(0);
        }
    }

    /*
     * if the top element does not have any image related, set them all
     */
    if (topElement.getAllToReferences("logical_physical") == null
            || topElement.getAllToReferences("logical_physical").size() == 0) {
        if (dd.getPhysicalDocStruct() != null && dd.getPhysicalDocStruct().getAllChildren() != null) {
            Helper.setMeldung(myProcess.getTitle()
                    + ": topstruct element does not have any referenced images yet; temporarily adding them "
                    + "for mets file creation");
            for (DocStruct mySeitenDocStruct : dd.getPhysicalDocStruct().getAllChildren()) {
                topElement.addReferenceTo(mySeitenDocStruct, "logical_physical");
            }
        } else {
            if (this instanceof ExportDms && ((ExportDms) this).exportDmsTask != null) {
                ((ExportDms) this).exportDmsTask.setException(new RuntimeException(
                        myProcess.getTitle() + ": could not find any referenced images, export aborted"));
            } else {
                Helper.setFehlerMeldung(
                        myProcess.getTitle() + ": could not find any referenced images, export aborted");
            }
            return false;
        }
    }

    for (ContentFile cf : dd.getFileSet().getAllFiles()) {
        String location = cf.getLocation();
        // If the file's location string shoes no sign of any protocol,
        // use the file protocol.
        if (!location.contains("://")) {
            location = "file://" + location;
        }
        String url = new URL(location).getFile();
        URI uri = !url.startsWith(imageFolderPath.getPath()) ? imageFolderPath : URI.create("");
        uri = uri.resolve(url);
        cf.setLocation(uri.toString());
    }

    mm.setDigitalDocument(dd);

    /*
     * wenn Filegroups definiert wurden, werden diese jetzt in die
     * Metsstruktur bernommen
     */
    // Replace all paths with the given VariableReplacer, also the file
    // group paths!
    VariableReplacer vp = new VariableReplacer(mm.getDigitalDocument(), this.myPrefs, myProcess, null);
    List<ProjectFileGroup> myFilegroups = myProcess.getProject().getProjectFileGroups();

    if (myFilegroups != null && myFilegroups.size() > 0) {
        for (ProjectFileGroup pfg : myFilegroups) {
            // check if source files exists
            if (pfg.getFolder() != null && pfg.getFolder().length() > 0) {
                URI folder = serviceManager.getProcessService().getMethodFromName(pfg.getFolder(), myProcess);
                if (fileService.fileExist(folder) && fileService.getSubUris(folder).size() > 0) {
                    VirtualFileGroup v = new VirtualFileGroup();
                    v.setName(pfg.getName());
                    v.setPathToFiles(vp.replace(pfg.getPath()));
                    v.setMimetype(pfg.getMimeType());
                    v.setFileSuffix(pfg.getSuffix());
                    v.setOrdinary(!pfg.isPreviewImage());
                    mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v);
                }
            } else {

                VirtualFileGroup v = new VirtualFileGroup();
                v.setName(pfg.getName());
                v.setPathToFiles(vp.replace(pfg.getPath()));
                v.setMimetype(pfg.getMimeType());
                v.setFileSuffix(pfg.getSuffix());
                v.setOrdinary(!pfg.isPreviewImage());
                mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v);
            }
        }
    }

    // Replace rights and digiprov entries.
    mm.setRightsOwner(vp.replace(myProcess.getProject().getMetsRightsOwner()));
    mm.setRightsOwnerLogo(vp.replace(myProcess.getProject().getMetsRightsOwnerLogo()));
    mm.setRightsOwnerSiteURL(vp.replace(myProcess.getProject().getMetsRightsOwnerSite()));
    mm.setRightsOwnerContact(vp.replace(myProcess.getProject().getMetsRightsOwnerMail()));
    mm.setDigiprovPresentation(vp.replace(myProcess.getProject().getMetsDigiprovPresentation()));
    mm.setDigiprovReference(vp.replace(myProcess.getProject().getMetsDigiprovReference()));
    mm.setDigiprovPresentationAnchor(vp.replace(myProcess.getProject().getMetsDigiprovPresentationAnchor()));
    mm.setDigiprovReferenceAnchor(vp.replace(myProcess.getProject().getMetsDigiprovReferenceAnchor()));

    mm.setPurlUrl(vp.replace(myProcess.getProject().getMetsPurl()));
    mm.setContentIDs(vp.replace(myProcess.getProject().getMetsContentIDs()));

    // Set mets pointers. MetsPointerPathAnchor or mptrAnchorUrl is the
    // pointer used to point to the superordinate (anchor) file, that is
    // representing a virtual? group such as a series. Several anchors
    // pointer paths can be defined/ since it is possible to define several
    // levels of superordinate structures (such as the complete edition of
    // a daily newspaper, one year ouf of that edition, )
    String anchorPointersToReplace = myProcess.getProject().getMetsPointerPath();
    mm.setMptrUrl(null);
    for (String anchorPointerToReplace : anchorPointersToReplace.split(Project.ANCHOR_SEPARATOR)) {
        String anchorPointer = vp.replace(anchorPointerToReplace);
        mm.setMptrUrl(anchorPointer);
    }

    // metsPointerPathAnchor or mptrAnchorUrl is the pointer used to point
    // from the (lowest) superordinate
    // (anchor) file to the lowest level file (the non-anchor file).
    String metsPointerToReplace = myProcess.getProject().getMetsPointerPathAnchor();
    String metsPointer = vp.replace(metsPointerToReplace);
    mm.setMptrAnchorUrl(metsPointer);

    if (ConfigCore.getBooleanParameter("ExportValidateImages", true)) {
        try {
            // TODO andere Dateigruppen nicht mit image Namen ersetzen
            List<URI> images = new MetadatenImagesHelper(this.myPrefs, dd).getDataFiles(myProcess);
            List<String> imageStrings = new ArrayList<>();
            for (URI uri : images) {
                imageStrings.add(uri.toString());
            }
            int sizeOfPagination = dd.getPhysicalDocStruct().getAllChildren().size();
            int sizeOfImages = images.size();
            if (sizeOfPagination == sizeOfImages) {
                dd.overrideContentFiles(imageStrings);
            } else {
                List<String> param = new ArrayList<>();
                param.add(String.valueOf(sizeOfPagination));
                param.add(String.valueOf(sizeOfImages));
                Helper.setFehlerMeldung(Helper.getTranslation("imagePaginationError", param));
                return false;
            }
        } catch (IndexOutOfBoundsException | InvalidImagesException e) {
            logger.error(e);
            return false;
        }
    } else {
        // create pagination out of virtual file names
        dd.addAllContentFiles();

    }

    mm.write(metaFile.toString());
    Helper.setMeldung(null, myProcess.getTitle() + ": ", "ExportFinished");
    return true;
}

From source file:org.eclipse.orion.internal.server.servlets.workspace.ProjectParentDecorator.java

private void addParents(URI resource, JSONObject representation, ProjectInfo project, IPath resourcePath)
        throws JSONException {
    //start at parent of current resource
    resourcePath = resourcePath.removeLastSegments(1).addTrailingSeparator();
    JSONArray parents = new JSONArray();
    //for all but the project we can just manipulate the path to get the name and location
    while (resourcePath.segmentCount() > 2) {
        try {//from w w w  .  j  av a 2 s .  c om
            URI uri = resource.resolve(new URI(null, null, resourcePath.toString(), null));
            addParent(parents, resourcePath.lastSegment(), new URI(resource.getScheme(),
                    resource.getAuthority(), uri.getPath(), uri.getQuery(), uri.getFragment()));
        } catch (URISyntaxException e) {
            //ignore this parent
            LogHelper.log(e);
        }
        resourcePath = resourcePath.removeLastSegments(1);
    }
    //add the project
    if (resourcePath.segmentCount() == 2) {
        try {
            URI uri = resource.resolve(new URI(null, null, resourcePath.toString(), null));
            addParent(parents, project.getFullName(), new URI(resource.getScheme(), resource.getAuthority(),
                    uri.getPath(), uri.getQuery(), uri.getFragment()));
        } catch (URISyntaxException e) {
            //ignore this project
            LogHelper.log(e);
        }
    }
    representation.put(ProtocolConstants.KEY_PARENTS, parents);
}

From source file:org.apache.eagle.jpm.mr.history.parser.JHFEventReaderBase.java

private String buildJobTrackingUrl(String jobId) {
    String jobTrackingUrlBase = appConfig.getJobHistoryEndpointConfig().mrHistoryServerUrl + "/jobhistory/job/";
    try {// w w  w.  ja v  a 2s .c  o  m
        URI oldUri = new URI(jobTrackingUrlBase);
        URI resolved = oldUri.resolve(jobId);
        return resolved.toString();
    } catch (URISyntaxException e) {
        LOG.warn("Tracking url build failed with baseURL=%s, resolvePart=%s", jobTrackingUrlBase, jobId);
        return jobTrackingUrlBase;
    }
}

From source file:org.apache.taverna.update.impl.UpdateManagerImpl.java

/**
 * @param requiredBundles/*from  w  w w. ja  v a2  s .  com*/
 * @param file
 * @throws UpdateException
 */
private void downloadBundles(ApplicationProfile profile, Set<BundleInfo> requiredBundles, File file)
        throws UpdateException {
    Updates updates = profile.getUpdates();
    String updateSite = updates.getUpdateSite();
    String libDirectory = updates.getLibDirectory();
    if (!libDirectory.endsWith("/")) {
        libDirectory = libDirectory + "/";
    }

    URI updateLibDirectory;
    try {
        updateLibDirectory = new URI(updateSite).resolve(libDirectory);
    } catch (URISyntaxException e) {
        throw new UpdateException(
                String.format("Update site URL (%s) is not a valid URL", updates.getUpdateSite()), e);
    }
    for (BundleInfo bundle : requiredBundles) {
        URI bundleURI = updateLibDirectory.resolve(bundle.getFileName());
        Path bundleDestination = new File(file, bundle.getFileName()).toPath();
        try {
            downloadManager.download(bundleURI, bundleDestination, DIGEST_ALGORITHM);
        } catch (DownloadException e) {
            throw new UpdateException(
                    String.format("Error downloading %1$s to %2$s", bundleURI, bundleDestination), e);
        }
    }
}

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

/**
 * Prepares a GET/POST request for logging the given user into the given login page. The login page is expected
 * to have at least input fields with id "username" and "password".
 *
 * @param user//from  www . j av  a2s  . co m
 * @param loginPage
 * @return
 */
private HttpUriRequest handleLoginPage(String loginPage, URI currentURI) {
    if (idpAlias != null) {
        org.jsoup.nodes.Document theLoginPage = Jsoup.parse(loginPage);
        Element zocialLink = theLoginPage.getElementById("zocial-" + this.idpAlias);
        assertThat("Unknown idp: " + this.idpAlias, zocialLink, Matchers.notNullValue());
        final String link = zocialLink.attr("href");
        assertThat("Invalid idp link: " + this.idpAlias, link, Matchers.notNullValue());
        return new HttpGet(currentURI.resolve(link));
    }

    return handleLoginPage(user, loginPage);
}

From source file:org.springframework.ide.eclipse.boot.wizard.NewSpringBootWizardModel.java

/**
 * Dynamically discover input fields and 'style' options by parsing initializr form.
 */// w ww .  j  a v  a2  s . co  m
private void discoverOptions(FieldArrayModel<String> fields,
        HierarchicalMultiSelectionFieldModel<Dependency> dependencies) throws Exception {
    InitializrServiceSpec serviceSpec = parseJsonFrom(new URL(JSON_URL));

    Map<String, String> textInputs = serviceSpec.getTextInputs();
    for (Entry<String, String> e : KNOWN_STRING_INPUTS.entrySet()) {
        String name = e.getKey();
        String defaultValue = textInputs.get(name);
        if (defaultValue != null) {
            fields.add(new StringFieldModel(name, defaultValue).label(e.getValue()));
        }
    }

    { //field: type
        String groupName = "type";
        RadioGroup group = radioGroups.ensureGroup(groupName);
        group.label("Type:");
        for (Type type : serviceSpec.getTypeOptions(groupName)) {
            BuildType bt = KNOWN_TYPES.get(type.getId());
            if (bt != null) {
                for (ImportStrategy is : bt.getImportStrategies()) {
                    TypeRadioInfo radio = new TypeRadioInfo(groupName, type, is);
                    radio.setLabel(is.displayName());
                    group.add(radio);
                }
            }
        }
        //When a type is selected the 'baseUrl' should be update according to its action.
        group.getSelection().selection.addListener(new ValueListener<RadioInfo>() {
            public void gotValue(LiveExpression<RadioInfo> exp, RadioInfo value) {
                try {
                    if (value != null) {
                        URI base = new URI(JSON_URL);
                        URI resolved = base.resolve(((TypeRadioInfo) value).getAction());
                        baseUrl.setValue(resolved.toString());
                    }
                } catch (Exception e) {
                    BootWizardActivator.log(e);
                }
            }
        });
    }

    for (Entry<String, String> e : KNOWN_SINGLE_SELECTS.entrySet()) {
        String groupName = e.getKey();
        RadioGroup group = radioGroups.ensureGroup(groupName);
        group.label(e.getValue());
        addOptions(group, serviceSpec.getSingleSelectOptions(groupName));
        if (groupName.equals("bootVersion")) {
            this.bootVersion = group;
        }
    }

    //styles
    for (DependencyGroup dgroup : serviceSpec.getDependencies()) {
        String catName = dgroup.getName();
        for (Dependency dep : dgroup.getContent()) {
            dependencies.choice(catName, dep.getName(), dep, dep.getDescription(),
                    createEnablementExp(bootVersion, dep));
        }
    }
}

From source file:com.collaborne.jsonschema.generator.driver.GeneratorDriver.java

/**
 * Calculate type URIs for all the given {@code schemaFiles}.
 *
 * @param rootUri/*from   w  w w .  j  a  v  a2  s.  com*/
 * @param baseDirectory
 * @param schemaFiles
 * @return
 */
public Set<URI> getInitialTypes(URI rootUri, Path baseDirectory, List<Path> schemaFiles) {
    Set<URI> types = new HashSet<>();
    URI baseDirectoryUri = baseDirectory.toAbsolutePath().normalize().toUri();
    for (Path schemaFile : schemaFiles) {
        URI schemaFileUri = schemaFile.toAbsolutePath().normalize().toUri();
        URI relativeSchemaUri = baseDirectoryUri.relativize(schemaFileUri);
        URI schemaUri = rootUri.resolve(relativeSchemaUri);

        types.add(schemaUri.resolve("#"));
    }

    return types;
}