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.eclipse.orion.internal.server.servlets.project.ProjectDecorator.java

public void addAtributesFor(HttpServletRequest request, URI resource, JSONObject representation) {
    if (!"/file".equals(request.getServletPath())) //$NON-NLS-1$
        return;//  w w  w. j  av a 2s. com
    String pathInfo = request.getPathInfo();
    Path path = new Path(pathInfo);
    if (path.segmentCount() < 2) {
        return;
    }
    try {
        ProjectInfo project = OrionConfiguration.getMetaStore().readProject(path.segment(0), path.segment(1));
        Project projectData = Project.fromProjectInfo(project);
        if (projectData.exists()) {
            JSONObject projectJson = new JSONObject(); //TODO decide what project information should be included in decorator
            projectJson.put(ProtocolConstants.KEY_LOCATION, URIUtil
                    .append(URIUtil.append(resource.resolve("/project/"), path.segment(0)), path.segment(1))
                    .toString());
            representation.put(ProtocolConstants.KEY_PROJECT_INFO, projectJson);
        }
    } catch (Exception e) {
        LogHelper.log(e);
    }
}

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

@Test
public void testCopyFileToDirectoryWithMissingDirectory() throws IOException {
    URI originFile = fileService.createResource(URI.create("fileServiceTest"), "copyFileToDirectoryMissing");
    URI targetDirectory = URI.create("fileServiceTest/copyFileToDirectoryMissingTarget/");

    assertTrue(fileService.fileExist(originFile));
    assertFalse(fileService.fileExist(targetDirectory));
    assertFalse(fileService.fileExist(targetDirectory.resolve("copyFileToDirectoryMissing")));

    fileService.copyFileToDirectory(originFile, targetDirectory);

    assertTrue(fileService.fileExist(originFile));
    assertTrue(fileService.fileExist(targetDirectory.resolve("copyFileToDirectoryMissing")));

}

From source file:org.kitodo.services.data.LdapServerService.java

/**
 * Retrieve home directory of given user.
 *
 * @param user/*from w ww.  j a va 2 s.  com*/
 *            User object
 * @return path as URI
 */
public URI getUserHomeDirectory(User user) {

    URI userFolderBasePath = URI.create("file:///" + ConfigCore.getParameter(Parameters.DIR_USERS));

    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_LOCAL_DIRECTORY)) {
        return userFolderBasePath.resolve(user.getLogin());
    }
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) {

        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            ctx.reconnect(null);

            Attributes attrs = ctx.getAttributes(buildUserDN(user));
            Attribute la = attrs.get("homeDirectory");
            return URI.create((String) la.get(0));

            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);

            return userFolderBasePath.resolve(user.getLogin());
        } catch (NamingException e) {

            logger.error("JNDI error:", e);

            return userFolderBasePath.resolve(user.getLogin());
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
    if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx;
    URI userFolderPath = null;
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(buildUserDN(user));
        Attribute ldapAttribute = attrs.get("homeDirectory");
        userFolderPath = URI.create((String) ldapAttribute.get(0));
        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

    if (userFolderPath != null && !userFolderPath.isAbsolute()) {
        if (userFolderPath.getPath().startsWith("/")) {
            userFolderPath = serviceManager.getFileService().deleteFirstSlashFromPath(userFolderPath);
        }
        return userFolderBasePath.resolve(userFolderPath);
    } else {
        return userFolderPath;
    }
}

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

@Override
protected ServerStatus _doIt() {
    /* multi server status */
    MultiServerStatus status = new MultiServerStatus();

    try {/*from   w  w  w. j  a  va  2 s .  c om*/

        /* bind services */
        URI targetURI = URIUtil.toURI(target.getUrl());

        ManifestParseTree manifest = getApplication().getManifest();
        ManifestParseTree app = manifest.get("applications").get(0); //$NON-NLS-1$

        if (app.has(CFProtocolConstants.V2_KEY_SERVICES)) {

            /* fetch all services */
            URI servicesURI = targetURI.resolve("/v2/services"); //$NON-NLS-1$
            GetMethod getServicesMethod = new GetMethod(servicesURI.toString());
            HttpUtil.configureHttpMethod(getServicesMethod, target);
            getServicesMethod.setQueryString("inline-relations-depth=1"); //$NON-NLS-1$

            /* send request */
            ServerStatus jobStatus = HttpUtil.executeMethod(getServicesMethod);
            status.add(jobStatus);
            if (!jobStatus.isOK())
                return status;

            JSONObject resp = jobStatus.getJsonData();
            JSONArray servicesJSON = resp.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);

            /* check for manifest version */
            ManifestParseTree services = app.getOpt(CFProtocolConstants.V2_KEY_SERVICES);
            if (services == null)
                /* nothing to do */
                return status;

            int version = services.isList() ? 6 : 2;

            if (version == 2) {
                String spaceGuid = target.getSpace().getGuid();
                URI serviceInstancesURI2 = targetURI.resolve("/v2/spaces/" + spaceGuid + "/service_instances"); //$NON-NLS-1$//$NON-NLS-2$

                for (ManifestParseTree service : services.getChildren()) {
                    String serviceName = service.getLabel();

                    String nameService = "name:" + serviceName; //$NON-NLS-1$
                    NameValuePair[] pa = new NameValuePair[] {
                            new NameValuePair("return_user_provided_service_instance", "false"), //  //$NON-NLS-1$//$NON-NLS-2$
                            new NameValuePair("q", nameService), //$NON-NLS-1$
                            new NameValuePair("inline-relations-depth", "2") //   //$NON-NLS-1$ //$NON-NLS-2$
                    };

                    GetMethod getServiceMethod = new GetMethod(serviceInstancesURI2.toString());
                    getServiceMethod.setQueryString(pa);
                    HttpUtil.configureHttpMethod(getServiceMethod, target);

                    /* send request */
                    jobStatus = HttpUtil.executeMethod(getServiceMethod);
                    status.add(jobStatus);
                    if (!jobStatus.isOK())
                        return status;

                    resp = jobStatus.getJsonData();
                    String serviceInstanceGUID = null;
                    JSONArray respArray = resp.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);
                    for (int i = 0; i < respArray.length(); ++i) {
                        JSONObject o = respArray.optJSONObject(i);
                        if (o != null) {
                            JSONObject str = o.optJSONObject(CFProtocolConstants.V2_KEY_METADATA);
                            if (str != null) {
                                serviceInstanceGUID = str.getString(CFProtocolConstants.V2_KEY_GUID);
                                break;
                            }
                        }
                    }

                    if (serviceInstanceGUID == null) {
                        /* no service instance bound to the application, create one if possible */

                        /* support both 'type' and 'label' fields as service type */
                        ManifestParseTree serviceType = service.getOpt(CFProtocolConstants.V2_KEY_TYPE);
                        if (serviceType == null)
                            serviceType = service.get(CFProtocolConstants.V2_KEY_LABEL);

                        ManifestParseTree provider = service.get(CFProtocolConstants.V2_KEY_PROVIDER);
                        ManifestParseTree plan = service.get(CFProtocolConstants.V2_KEY_PLAN);

                        String servicePlanGUID = findServicePlanGUID(serviceType.getValue(),
                                provider.getValue(), plan.getValue(), servicesJSON);
                        if (servicePlanGUID == null) {
                            String[] bindings = { serviceName, serviceType.getValue(), plan.getValue() };
                            String msg = NLS.bind(
                                    "Could not find service instance {0} nor service {1} with plan {2} in target.",
                                    bindings);
                            status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg,
                                    null));
                            return status;
                        }

                        /* create service instance */
                        URI serviceInstancesURI = targetURI.resolve("/v2/service_instances"); //$NON-NLS-1$
                        PostMethod createServiceMethod = new PostMethod(serviceInstancesURI.toString());
                        HttpUtil.configureHttpMethod(createServiceMethod, target);

                        /* set request body */
                        JSONObject createServiceRequest = new JSONObject();
                        createServiceRequest.put(CFProtocolConstants.V2_KEY_SPACE_GUID,
                                target.getSpace().getCFJSON().getJSONObject(CFProtocolConstants.V2_KEY_METADATA)
                                        .getString(CFProtocolConstants.V2_KEY_GUID));
                        createServiceRequest.put(CFProtocolConstants.V2_KEY_NAME, serviceName);
                        createServiceRequest.put(CFProtocolConstants.V2_KEY_SERVICE_PLAN_GUID, servicePlanGUID);
                        createServiceMethod.setRequestEntity(new StringRequestEntity(
                                createServiceRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$

                        /* send request */
                        jobStatus = HttpUtil.executeMethod(createServiceMethod);
                        status.add(jobStatus);
                        if (!jobStatus.isOK())
                            return status;

                        resp = jobStatus.getJsonData();
                        serviceInstanceGUID = resp.getJSONObject(CFProtocolConstants.V2_KEY_METADATA)
                                .getString(CFProtocolConstants.V2_KEY_GUID);
                    }

                    /* bind service to the application */
                    URI serviceBindingsURI = targetURI.resolve("/v2/service_bindings"); //$NON-NLS-1$
                    PostMethod bindServiceMethod = new PostMethod(serviceBindingsURI.toString());
                    HttpUtil.configureHttpMethod(bindServiceMethod, target);

                    /* set request body */
                    JSONObject bindServiceRequest = new JSONObject();
                    bindServiceRequest.put(CFProtocolConstants.V2_KEY_APP_GUID, getApplication().getGuid());
                    bindServiceRequest.put(CFProtocolConstants.V2_KEY_SERVICE_INSTANCE_GUID,
                            serviceInstanceGUID);
                    bindServiceMethod.setRequestEntity(new StringRequestEntity(bindServiceRequest.toString(),
                            "application/json", "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$

                    /* send request */
                    jobStatus = HttpUtil.executeMethod(bindServiceMethod);
                    status.add(jobStatus);
                    if (!jobStatus.isOK())
                        return status;
                }
            }

            if (version == 6) {

                String spaceGuid = target.getSpace().getGuid();
                URI serviceInstancesURI = targetURI.resolve("/v2/spaces/" + spaceGuid + "/service_instances"); //$NON-NLS-1$//$NON-NLS-2$

                for (ManifestParseTree service : services.getChildren()) {
                    String nameService = service.getValue();

                    NameValuePair[] pa = new NameValuePair[] {
                            new NameValuePair("return_user_provided_service_instance", "true"), // //$NON-NLS-1$ //$NON-NLS-2$
                            new NameValuePair("q", "name:" + nameService), //$NON-NLS-1$//$NON-NLS-2$
                            new NameValuePair("inline-relations-depth", "2") }; //$NON-NLS-1$ //$NON-NLS-2$

                    GetMethod getServiceMethod = new GetMethod(serviceInstancesURI.toString());
                    getServiceMethod.setQueryString(pa);
                    HttpUtil.configureHttpMethod(getServiceMethod, target);

                    /* send request */
                    jobStatus = HttpUtil.executeMethod(getServiceMethod);
                    status.add(jobStatus);
                    if (!jobStatus.isOK())
                        return status;

                    resp = jobStatus.getJsonData();
                    String serviceInstanceGUID = null;
                    JSONArray respArray = resp.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);
                    for (int i = 0; i < respArray.length(); i++) {
                        JSONObject o = respArray.optJSONObject(i);
                        if (o != null) {
                            JSONObject str = o.optJSONObject(CFProtocolConstants.V2_KEY_METADATA);
                            if (str != null) {
                                serviceInstanceGUID = str.getString(CFProtocolConstants.V2_KEY_GUID);
                            }
                        }
                    }

                    if (serviceInstanceGUID == null) {
                        status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                                "Service instance " + nameService + " can not be found in target space", null));
                        return status;
                    }

                    /* bind service to the application */
                    URI serviceBindingsURI = targetURI.resolve("/v2/service_bindings"); //$NON-NLS-1$
                    PostMethod bindServiceMethod = new PostMethod(serviceBindingsURI.toString());
                    HttpUtil.configureHttpMethod(bindServiceMethod, target);

                    /* set request body */
                    JSONObject bindServiceRequest = new JSONObject();
                    bindServiceRequest.put(CFProtocolConstants.V2_KEY_APP_GUID, getApplication().getGuid());
                    bindServiceRequest.put(CFProtocolConstants.V2_KEY_SERVICE_INSTANCE_GUID,
                            serviceInstanceGUID);
                    bindServiceMethod.setRequestEntity(new StringRequestEntity(bindServiceRequest.toString(),
                            "application/json", "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$

                    /* send request */
                    jobStatus = HttpUtil.executeMethod(bindServiceMethod);
                    status.add(jobStatus);
                    if (!jobStatus.isOK())
                        return status;
                }
            }
        }

        return status;

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

From source file:com.soundcloud.playerapi.ApiWrapper.java

/**
 * Constructs URI path for a given resource.
 * @param request      the resource to access
 * @param api          api or web//from   w w  w.  j  a v a  2  s  .c o  m
 * @param secure       whether to use SSL or not
 * @return a valid URI
 */
public URI getURI(Request request, boolean api, boolean secure) {
    final URI uri = api ? env.getResourceURI(secure) : env.getAuthResourceURI(secure);
    return uri.resolve(request.toUrl());
}

From source file:org.apache.archiva.indexer.maven.MavenIndexManager.java

private String calculateIndexRemoteUrl(URI baseUri, RemoteIndexFeature rif) {
    if (rif.getIndexUri() == null) {
        return baseUri.resolve(DEFAULT_INDEXER_DIR).toString();
    } else {/*from   w  ww .  ja v a 2 s  .c  o m*/
        return baseUri.resolve(rif.getIndexUri()).toString();
    }
}

From source file:org.structr.schema.export.StructrTypeDefinition.java

@Override
public URI getId() {

    final URI id = root.getId();
    final URI uri = URI.create("definitions/" + getName());

    return id.resolve(uri);
}

From source file:org.kitodo.services.file.FileServiceTest.java

@Test
public void testCopyFileToDirectoryWithMissingDirectory() throws IOException {
    URI originFile = fileService.createResource(URI.create("fileServiceTest"), "copyFileToDirectoryMissing");
    URI targetDirectory = URI.create("fileServiceTest/copyFileToDirectoryMissingTarget/");

    Assert.assertTrue(fileService.fileExist(originFile));
    Assert.assertFalse(fileService.fileExist(targetDirectory));
    Assert.assertFalse(fileService.fileExist(targetDirectory.resolve("copyFileToDirectoryMissing")));

    fileService.copyFileToDirectory(originFile, targetDirectory);

    Assert.assertTrue(fileService.fileExist(originFile));
    Assert.assertTrue(fileService.fileExist(targetDirectory.resolve("copyFileToDirectoryMissing")));

}

From source file:uk.ac.ebi.eva.pipeline.jobs.steps.VariantLoaderStep.java

@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
    ObjectMap variantOptions = jobOptions.getVariantOptions();
    ObjectMap pipelineOptions = jobOptions.getPipelineOptions();

    VariantStorageManager variantStorageManager = StorageManagerFactory.getVariantStorageManager();// TODO add mongo
    URI outdirUri = URLHelper.createUri(pipelineOptions.getString("output.dir"));
    URI nextFileUri = URLHelper.createUri(pipelineOptions.getString("input.vcf"));

    //          URI pedigreeUri = pipelineOptions.getString("input.pedigree") != null ? createUri(pipelineOptions.getString("input.pedigree")) : null;
    Path output = Paths.get(outdirUri.getPath());
    Path input = Paths.get(nextFileUri.getPath());
    Path outputVariantJsonFile = output.resolve(
            input.getFileName().toString() + ".variants.json" + pipelineOptions.getString("compressExtension"));
    //          outputFileJsonFile = output.resolve(input.getFileName().toString() + ".file.json" + config.compressExtension);
    URI transformedVariantsUri = outdirUri.resolve(outputVariantJsonFile.getFileName().toString());

    logger.info("-- PreLoad variants -- {}", nextFileUri);
    variantStorageManager.preLoad(transformedVariantsUri, outdirUri, variantOptions);
    logger.info("-- Load variants -- {}", nextFileUri);
    variantStorageManager.load(transformedVariantsUri, variantOptions);
    //          logger.info("-- PostLoad variants -- {}", nextFileUri);
    //          variantStorageManager.postLoad(transformedVariantsUri, outdirUri, variantOptions);

    return RepeatStatus.FINISHED;
}

From source file:groovyx.net.http.URIBuilder.java

protected URI update(String scheme, String userInfo, String host, int port, String path, String query,
        String fragment) throws URISyntaxException {
    URI u = new URI(scheme, userInfo, host, port, base.getPath(), null, null);

    StringBuilder sb = new StringBuilder();
    if (path != null)
        sb.append(path);/*w w  w  . j  a  va2s  .c o m*/
    if (query != null)
        sb.append('?').append(query);
    if (fragment != null)
        sb.append('#').append(fragment);
    return u.resolve(sb.toString());
}