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.server.cf.commands.GetLogsCommand.java

private ServerStatus setRunningInstances(JSONObject jsonResp, String appUrl) {
    try {/*from w ww  . j  av  a  2s . c  om*/
        URI targetURI = URIUtil.toURI(target.getUrl());
        String runningInstancesUrl = appUrl + "/instances";
        URI runningInstancesURI = targetURI.resolve(runningInstancesUrl);

        GetMethod getRunningInstancesMethod = new GetMethod(runningInstancesURI.toString());
        HttpUtil.configureHttpMethod(getRunningInstancesMethod, target);

        ServerStatus getStatus = HttpUtil.executeMethod(getRunningInstancesMethod);
        if (!getStatus.isOK()) {
            return getStatus;
        }

        JSONObject runningInstances = getStatus.getJsonData();
        for (Iterator<String> iterator = runningInstances.keys(); iterator.hasNext();) {
            JSONArray logsJSON = new JSONArray();
            String runningInstanceNo = iterator.next();
            ServerStatus prepareJSONStatus = prepareJSONResp(logsJSON, runningInstanceNo, appUrl);
            if (prepareJSONStatus.isOK())
                jsonResp.put(runningInstanceNo, logsJSON);
        }
    } catch (Exception e) {
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, e);
    }
    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
}

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

@Override
protected ServerStatus _doIt() {

    /* multi server status */
    MultiServerStatus status = new MultiServerStatus();

    try {/*from  w  w  w .  j  a va  2 s  .  co m*/

        JSONObject response = new JSONObject();
        JSONArray services = new JSONArray();

        /* get services */
        URI targetURI = URIUtil.toURI(target.getUrl());
        String spaceGuid = target.getSpace().getGuid();

        URI serviceInstancesURI = targetURI.resolve("/v2/spaces/" + spaceGuid + "/service_instances"); //$NON-NLS-1$//$NON-NLS-2$
        NameValuePair[] pa = new NameValuePair[] { //
                new NameValuePair("return_user_provided_service_instances", "true"), //  //$NON-NLS-1$//$NON-NLS-2$
                new NameValuePair("inline-relations-depth", "1") //  //$NON-NLS-1$ //$NON-NLS-2$
        };

        do {

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

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

            JSONObject resp = jobStatus.getJsonData();
            if (resp.has(CFProtocolConstants.V2_KEY_NEXT_URL)
                    && !resp.isNull(CFProtocolConstants.V2_KEY_NEXT_URL))
                serviceInstancesURI = targetURI.resolve(resp.getString(CFProtocolConstants.V2_KEY_NEXT_URL));
            else
                serviceInstancesURI = null;

            JSONArray resources = resp.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);
            for (int i = 0; i < resources.length(); ++i) {
                JSONObject serviceObj = resources.getJSONObject(i);

                JSONObject serviceInstanceEntity = serviceObj.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY);
                JSONObject serviceEntity = serviceInstanceEntity
                        .getJSONObject(CFProtocolConstants.V2_KEY_SERVICE_PLAN)//
                        .getJSONObject(CFProtocolConstants.V2_KEY_ENTITY);

                String serviceGuid = serviceEntity.getString(CFProtocolConstants.V2_KEY_SERVICE_GUID);
                GetServiceCommand getServiceCommand = new GetServiceCommand(target, serviceGuid);

                /* get detailed info about the service */
                jobStatus = (ServerStatus) getServiceCommand.doIt(); /* FIXME: unsafe type cast */
                status.add(jobStatus);
                if (!jobStatus.isOK())
                    return status;

                JSONObject serviceResp = jobStatus.getJsonData();
                boolean isBindable = serviceResp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY)
                        .getBoolean(CFProtocolConstants.V2_KEY_BINDABLE);

                if (isBindable) {
                    Service s = new Service(serviceInstanceEntity.getString(CFProtocolConstants.V2_KEY_NAME));
                    services.put(s.toJSON());
                }
            }

        } while (serviceInstancesURI != null);

        response.put(ProtocolConstants.KEY_CHILDREN, services);
        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, response);

    } 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:org.eclipse.orion.server.cf.commands.GetAppCommand.java

public ServerStatus _doIt() {
    try {//  w w w  . j  av a2  s .  com
        URI targetURI = URIUtil.toURI(target.getUrl());

        // Find the app
        String appsUrl = target.getSpace().getCFJSON().getJSONObject("entity").getString("apps_url");
        URI appsURI = targetURI.resolve(appsUrl);
        GetMethod getAppsMethod = new GetMethod(appsURI.toString());
        HttpUtil.configureHttpMethod(getAppsMethod, target);
        getAppsMethod.setQueryString("q=name:" + URLEncoder.encode(name, "UTF8") + "&inline-relations-depth=1");

        ServerStatus getStatus = HttpUtil.executeMethod(getAppsMethod);
        if (!getStatus.isOK())
            return getStatus;

        JSONObject apps = getStatus.getJsonData();

        if (!apps.has("resources") || apps.getJSONArray("resources").length() == 0)
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Application not found",
                    null);

        // Get more details about the app
        JSONObject appJSON = apps.getJSONArray("resources").getJSONObject(0).getJSONObject("metadata");

        String summaryAppUrl = appJSON.getString("url") + "/summary";
        URI summaryAppURI = targetURI.resolve(summaryAppUrl);

        GetMethod getSummaryMethod = new GetMethod(summaryAppURI.toString());
        HttpUtil.configureHttpMethod(getSummaryMethod, target);

        getStatus = HttpUtil.executeMethod(getSummaryMethod);
        if (!getStatus.isOK())
            return getStatus;

        JSONObject summaryJSON = getStatus.getJsonData();

        this.app = new App();
        this.app.setAppJSON(appJSON);
        this.app.setSummaryJSON(summaryJSON);

        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, this.app.toJSON());
    } 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.apache.taverna.update.impl.UpdateManagerImpl.java

@Override
public boolean checkForUpdates() throws UpdateException {
    ApplicationProfile applicationProfile = applicationConfiguration.getApplicationProfile();
    String version = applicationProfile.getVersion();
    Updates updates = applicationProfile.getUpdates();

    URI updatesURL;/*from   w w w.  j a va 2s.  co m*/
    try {
        URI updateSiteURI = new URI(updates.getUpdateSite());
        updatesURL = updateSiteURI.resolve(updates.getUpdatesFile());
    } catch (URISyntaxException e) {
        throw new UpdateException(
                String.format("Update site URL (%s) is not a valid URL", updates.getUpdateSite()), e);
    }
    File updateDirectory = applicationConfiguration.getApplicationHomeDir().resolve("updates").toFile();
    updateDirectory.mkdirs();
    File updatesFile = new File(updateDirectory, updates.getUpdatesFile());
    try {
        downloadManager.download(updatesURL, updatesFile.toPath(), DIGEST_ALGORITHM);
    } catch (DownloadException e) {
        throw new UpdateException(String.format("Error downloading %1$s", updatesURL), e);
    }

    try {
        UpdateSite updateSite = (UpdateSite) unmarshaller.unmarshal(updatesFile);
        applicationVersions = updateSite.getVersions();
        latestVersion = applicationVersions.getLatestVersion();
        updateAvailable = isHigherVersion(latestVersion.getVersion(), version);
    } catch (JAXBException e) {
        throw new UpdateException(String.format("Error reading %s", updatesFile.getName()), e);
    }
    lastCheckTime = System.currentTimeMillis();
    return updateAvailable;
}

From source file:org.forgerock.openidm.provisioner.Id.java

public URI getId() {
    try {//from   ww w .  j av  a  2 s  .  c  o  m
        URI id = getObjectSetId();
        if (null != localId) {
            id = id.resolve(URLEncoder.encode(localId, CHARACTER_ENCODING_UTF_8));
        }
        return id;
    } catch (UnsupportedEncodingException e) {
        // Should never happen.
        throw new UndeclaredThrowableException(e);
    }
}

From source file:org.forgerock.openidm.provisioner.Id.java

public URI getQualifiedId() {
    try {/*from   w  w w .  j a v a 2s .c o m*/
        URI id = getObjectSetId();
        if (null != localId) {
            id = id.resolve(URLEncoder.encode(localId, CHARACTER_ENCODING_UTF_8));
        }
        return baseURI.resolve(SYSTEM_BASE).resolve(id);
    } catch (UnsupportedEncodingException e) {
        // Should never happen.
        throw new UndeclaredThrowableException(e);
    }
}

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

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

    try {/*from   ww w .  j  av a2s. co  m*/
        /* upload project contents */
        File appPackage = PackageUtils.getApplicationPackage(appStore);
        deployedAppPackageName = PackageUtils.getApplicationPackageType(appStore);

        if (appPackage == null) {
            status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to read application content", null));
            return status;
        }

        URI targetURI = URIUtil.toURI(target.getUrl());
        PutMethod uploadMethod = new PutMethod(
                targetURI.resolve("/v2/apps/" + getApplication().getGuid() + "/bits?async=true").toString());
        uploadMethod.addRequestHeader(new Header("Authorization",
                "bearer " + target.getCloud().getAccessToken().getString("access_token")));

        Part[] parts = { new StringPart(CFProtocolConstants.V2_KEY_RESOURCES, "[]"),
                new FilePart(CFProtocolConstants.V2_KEY_APPLICATION, appPackage) };
        uploadMethod.setRequestEntity(new MultipartRequestEntity(parts, uploadMethod.getParams()));

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

        /* long running task, keep track */
        int attemptsLeft = MAX_ATTEMPTS;
        JSONObject resp = jobStatus.getJsonData();
        String taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY)
                .getString(CFProtocolConstants.V2_KEY_STATUS);
        while (!CFProtocolConstants.V2_KEY_FINISHED.equals(taksStatus)
                && !CFProtocolConstants.V2_KEY_FAILURE.equals(taksStatus)) {
            if (CFProtocolConstants.V2_KEY_FAILED.equals(taksStatus)) {
                /* delete the tmp file */
                appPackage.delete();
                status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Upload failed",
                        null));
                return status;
            }

            if (attemptsLeft == 0) {
                /* delete the tmp file */
                appPackage.delete();
                status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                        "Upload timeout exceeded", null));
                return status;
            }

            /* two seconds */
            Thread.sleep(2000);

            /* check whether job has finished */
            URI jobLocation = targetURI.resolve(resp.getJSONObject(CFProtocolConstants.V2_KEY_METADATA)
                    .getString(CFProtocolConstants.V2_KEY_URL));
            GetMethod jobRequest = new GetMethod(jobLocation.toString());
            HttpUtil.configureHttpMethod(jobRequest, target);

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

            resp = jobStatus.getJsonData();
            taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY)
                    .getString(CFProtocolConstants.V2_KEY_STATUS);

            --attemptsLeft;
        }

        if (CFProtocolConstants.V2_KEY_FAILURE.equals(jobStatus)) {
            status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to upload application bits", null));
            return status;
        }

        /* delete the tmp file */
        appPackage.delete();

        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:org.eclipse.orion.internal.server.servlets.site.SiteConfigurationResourceHandler.java

private boolean handleGet(HttpServletRequest req, HttpServletResponse resp, SiteInfo site) throws IOException {
    // Strip off the SiteConfig id from the request URI
    URI location = getURI(req);
    URI baseLocation = location.resolve(""); //$NON-NLS-1$
    JSONObject result = toJSON(site, baseLocation);
    OrionServlet.writeJSONResponse(req, resp, result, JsonURIUnqualificationStrategy.LOCATION_ONLY);
    return true;//  w  w w. ja  va 2s . co m
}

From source file:org.jactr.entry.iterative.impl.RealTimeFactorPerformanceListener.java

/**
 * @see org.jactr.entry.iterative.IIterativeRunListener#postRun(int, int,
 *      java.util.Collection)/*from w ww  .  j  a va  2s. c o m*/
 */
public void postRun(int currentRunIndex, int totalRuns, @SuppressWarnings("unused") Collection<IModel> models)
        throws TerminateIterativeRunException {

    if (currentRunIndex % _blockSize == 0) {
        double realTimeFactor = (double) _blockSimTimeSum / (double) _blockRealTimeSum;
        _row.append((realTimeFactor / _blockSize)).append("\t");
        _blockRealTimeSum = 0;
        _blockSimTimeSum = 0;
    }

    if (currentRunIndex == totalRuns && _fileName.length() != 0)
        try {
            /*
             * done, so we dump
             */
            URI root = new File(System.getProperty("user.dir")).toURI();
            File output = new File(root.resolve(_fileName));
            PrintWriter pw = new PrintWriter(new FileWriter(output, true));
            pw.println(_row.toString());
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Dumping row " + _row);
            pw.close();
        } catch (Exception e) {
            LOGGER.error("Could not write to " + _fileName, e);
        }
}

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

@Override
public boolean update() throws UpdateException {
    if (updateAvailable) {
        ApplicationProfile applicationProfile = applicationConfiguration.getApplicationProfile();
        Updates updates = applicationProfile.getUpdates();
        URI profileURL;//w  w  w. j a v a  2s.c om
        try {
            URI updateSiteURI = new URI(updates.getUpdateSite());
            profileURL = updateSiteURI.resolve(latestVersion.getFile());
        } catch (URISyntaxException e) {
            throw new UpdateException(
                    String.format("Update site URL (%s) is not a valid URL", updates.getUpdateSite()), e);
        }

        File updateDirectory = applicationConfiguration.getApplicationHomeDir().resolve("updates").toFile();
        updateDirectory.mkdirs();
        File latestProfileFile = new File(updateDirectory,
                "ApplicationProfile-" + latestVersion.getVersion() + ".xml");
        try {
            downloadManager.download(profileURL, latestProfileFile.toPath(), DIGEST_ALGORITHM);
        } catch (DownloadException e) {
            throw new UpdateException(String.format("Error downloading %1$s", profileURL), e);
        }

        ApplicationProfile latestProfile;
        try {
            latestProfile = (ApplicationProfile) unmarshaller.unmarshal(latestProfileFile);
        } catch (JAXBException e) {
            throw new UpdateException(String.format("Error reading %s", latestProfileFile.getName()), e);
        }

        Set<BundleInfo> requiredBundles = getRequiredBundles(applicationConfiguration.getApplicationProfile(),
                latestProfile);
        downloadBundles(latestProfile, requiredBundles,
                applicationConfiguration.getStartupDir().resolve("lib").toFile());
        File applicationProfileFile = applicationConfiguration.getStartupDir().resolve("ApplicationProfile.xml")
                .toFile();
        try {
            FileUtils.copyFile(latestProfileFile, applicationProfileFile);
        } catch (IOException e) {
            throw new UpdateException(String.format("Error copying %1$s to %2$s", latestProfileFile.getName(),
                    applicationProfileFile.getName()), e);
        }
        //         eventAdmin.postEvent(new Event("UpdateManagerEvent", new HashMap()));
        updateAvailable = false;
        return true;
    }
    return false;
}