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.site.SiteConfigurationResourceHandler.java

private boolean handlePut(HttpServletRequest req, HttpServletResponse resp, SiteInfo site)
        throws IOException, CoreException, JSONException {
    UserInfo user = OrionConfiguration.getMetaStore().readUser(getUserName(req));
    JSONObject requestJson = OrionServlet.readJSONRequest(req);
    copyProperties(requestJson, site, true);

    // Start/stop the site if necessary
    changeHostingStatus(req, resp, requestJson, user, site);

    // Everything succeeded, save the changed site
    site.save(user);//from ww  w  . ja v a 2  s.c o  m

    // 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;
}

From source file:org.kalypso.simulation.core.refactoring.local.LocalSimulationDataProvider.java

@Override
public Object getInputForID(final String id) throws SimulationException {
    final String path = m_inputs.get(id);
    if (path == null)
        throw new NoSuchElementException(Messages
                .getString("org.kalypso.simulation.core.refactoring.local.LocalSimulationDataProvider.0") + id); //$NON-NLS-1$

    final DataType inputType = m_modelspec == null ? null : m_modelspec.getInput(id);

    // default to xs:anyURI if no type is given
    final QName type = inputType == null ? QNAME_ANY_URI : inputType.getType();

    // URI types are treated as URLs,
    if (type.equals(QNAME_ANY_URI)) {
        try {//from  w  w  w . j  a  v a2  s . com
            final URI relativeURI;

            final URI baseURL = getBaseURL().toURI();
            if (path.startsWith("platform:/resource//")) //$NON-NLS-1$
            {
                relativeURI = baseURL.resolve(URIUtil.encodePath(path.substring(20)));
            } else {
                relativeURI = baseURL.resolve(URIUtil.encodePath(path));
            }

            // try to silently convert the URI to a URL
            try {
                final URL url = relativeURI.toURL();
                return url;
            } catch (final MalformedURLException e) {
                // gobble
            }
            return relativeURI;
        } catch (final IOException e) {
            throw new SimulationException(Messages.getString(
                    "org.kalypso.simulation.core.refactoring.local.LocalSimulationDataProvider.1"), e); //$NON-NLS-1$
        } catch (final URISyntaxException e) {
            throw new SimulationException(Messages.getString(
                    "org.kalypso.simulation.core.refactoring.local.LocalSimulationDataProvider.2"), e); //$NON-NLS-1$
        }
    } else {
        final ITypeRegistry<IMarshallingTypeHandler> typeRegistry = MarshallingTypeRegistrySingleton
                .getTypeRegistry();
        final IMarshallingTypeHandler handler = typeRegistry.getTypeHandlerForTypeName(type);
        if (handler != null) {
            try {
                return handler.parseType(path);
            } catch (final ParseException e) {
                throw new SimulationException(Messages.getString(
                        "org.kalypso.simulation.core.refactoring.local.LocalSimulationDataProvider.4", path, //$NON-NLS-1$
                        type), e);
            }
        }
    }

    throw new SimulationException(
            Messages.getString("org.kalypso.simulation.core.refactoring.local.LocalSimulationDataProvider.3") //$NON-NLS-1$
                    + type,
            null);
}

From source file:com.icesoft.faces.renderkit.IncludeRenderer.java

public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
    if (context == null || component == null) {
        throw new NullPointerException("Null Faces context or component parameter");
    }/*from  w  w  w.  j  ava  2s . c o  m*/
    // suppress rendering if "rendered" property on the component is
    // false.
    if (!component.isRendered()) {
        return;
    }

    String page = (String) component.getAttributes().get("page");

    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    URI absoluteURI = null;
    try {
        absoluteURI = new URI(request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + request.getRequestURI());
        URL includedURL = absoluteURI.resolve(page).toURL();
        URLConnection includedConnection = includedURL.openConnection();
        includedConnection.setRequestProperty("Cookie",
                "JSESSIONID=" + ((HttpSession) context.getExternalContext().getSession(false)).getId());
        Reader contentsReader = new InputStreamReader(includedConnection.getInputStream());

        try {
            StringWriter includedContents = new StringWriter();
            char[] buf = new char[2000];
            int len = 0;
            while ((len = contentsReader.read(buf)) > -1) {
                includedContents.write(buf, 0, len);
            }

            ((UIOutput) component).setValue(includedContents.toString());
        } finally {
            contentsReader.close();
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
    }

    super.encodeBegin(context, component);
}

From source file:uk.org.taverna.commons.update.impl.UpdateManagerImpl.java

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

    URL updatesURL;// w  ww.  j  a v  a  2 s  .co m
    try {
        URI updateSiteURI = new URI(updates.getUpdateSite());
        updatesURL = updateSiteURI.resolve(updates.getUpdatesFile()).toURL();
    } catch (MalformedURLException e) {
        throw new UpdateException(
                String.format("Update site URL (%s) is not a valid URL", updates.getUpdateSite()), e);
    } catch (URISyntaxException e) {
        throw new UpdateException(
                String.format("Update site URL (%s) is not a valid URL", updates.getUpdateSite()), e);
    }
    File updateDirectory = new File(applicationConfiguration.getApplicationHomeDir(), "updates");
    updateDirectory.mkdirs();
    File updatesFile = new File(updateDirectory, updates.getUpdatesFile());
    try {
        downloadManager.download(updatesURL, updatesFile, 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:com.reprezen.swagedit.json.references.JsonReference.java

protected URI resolveURI(URI baseURI) {
    if (baseURI == null || absolute) {
        return getUri();
    } else {/*from  ww  w . jav a 2s. co m*/
        try {
            return baseURI.resolve(getUri());
        } catch (NullPointerException e) {
            return null;
        }
    }
}

From source file:org.apache.any23.rdf.Any23ValueFactoryWrapper.java

/**
 * Fixes typical errors in IRIs, and resolves relative IRIs against a base IRI.
 *
 * @param uri     A IRI, relative or absolute, can have typical syntax errors
 * @param baseIRI A base IRI to use for resolving relative IRIs
 * @return An absolute IRI, sytnactically valid, or null if not fixable
 *//*from   ww  w. ja  v  a  2  s . c  o  m*/
public IRI resolveIRI(String uri, java.net.URI baseIRI) {
    try {
        return wrappedFactory.createIRI(baseIRI.resolve(RDFUtils.fixIRIWithException(uri)).toString());
    } catch (IllegalArgumentException iae) {
        reportError(iae);
        return null;
    }
}

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

private URI getImageFile(final URI href) {
    URI fileDir = tempDir.toURI().relativize(currentFile.getParentFile().toURI());
    if (job.getGeneratecopyouter() != Job.Generate.OLDSOLUTION) {
        fileDir = fileDir.resolve(uplevels.replace(File.separator, URI_SEPARATOR));
    }/*from  w w  w  . j a v a 2s. com*/
    final URI fileName = fileDir.resolve(href);
    final URI imgInputUri = outputDir.toURI().resolve(fileName);
    return imgInputUri;
}

From source file:org.apache.tajo.ws.rs.netty.NettyRestHandlerContainer.java

protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    URI baseUri = getBaseUri(ctx, request);
    URI requestUri = baseUri.resolve(request.getUri());
    ByteBuf responseContent = PooledByteBufAllocator.DEFAULT.buffer();
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            responseContent);//from  w  w w.j a  v  a  2  s  .c  o  m

    NettyRestResponseWriter responseWriter = new NettyRestResponseWriter(ctx, response);
    ContainerRequest containerRequest = new ContainerRequest(baseUri, requestUri, request.getMethod().name(),
            getSecurityContext(), new MapPropertiesDelegate());
    containerRequest.setEntityStream(new ByteBufInputStream(request.content()));

    HttpHeaders httpHeaders = request.headers();
    for (String headerName : httpHeaders.names()) {
        List<String> headerValues = httpHeaders.getAll(headerName);
        containerRequest.headers(headerName, headerValues);
    }
    containerRequest.setWriter(responseWriter);
    try {
        applicationHandler.handle(containerRequest);
    } finally {
        responseWriter.releaseConnection();
    }
}

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

public ServerStatus _doIt() {
    /* multi server status */
    MultiServerStatus result = new MultiServerStatus();

    try {/*w w w .jav  a 2 s .co m*/
        URI targetURI = URIUtil.toURI(target.getUrl());

        String appUrl = this.app.getAppJSON().getString("url"); //$NON-NLS-1$
        URI appURI = targetURI.resolve(appUrl);

        PutMethod startMethod = new PutMethod(appURI.toString());
        HttpUtil.configureHttpMethod(startMethod, target);
        startMethod.setQueryString("inline-relations-depth=1"); //$NON-NLS-1$

        JSONObject startCommand = new JSONObject();
        startCommand.put("console", true); //$NON-NLS-1$
        startCommand.put("state", "STARTED"); //$NON-NLS-1$ //$NON-NLS-2$
        StringRequestEntity requestEntity = new StringRequestEntity(startCommand.toString(),
                CFProtocolConstants.JSON_CONTENT_TYPE, "UTF-8"); //$NON-NLS-1$
        startMethod.setRequestEntity(requestEntity);

        ServerStatus startStatus = HttpUtil.executeMethod(startMethod);
        result.add(startStatus);
        if (!result.isOK())
            return result;

        if (timeout < 0) {
            /* extract user defined timeout if present */
            ManifestParseTree manifest = app.getManifest();
            ManifestParseTree timeoutNode = manifest.get(CFProtocolConstants.V2_KEY_APPLICATIONS).get(0)
                    .getOpt(CFProtocolConstants.V2_KEY_TIMEOUT);
            timeout = (timeoutNode != null) ? Integer.parseInt(timeoutNode.getValue())
                    : ManifestConstants.DEFAULT_TIMEOUT;
        }

        /* long running task, keep track */
        timeout = Math.min(timeout, ManifestConstants.MAX_TIMEOUT);
        int attemptsLeft = timeout / 2;

        String msg = NLS.bind("Can not start the application", commandName); //$NON-NLS-1$
        ServerStatus getInstancesStatus = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                msg, null);

        while (attemptsLeft > 0) {

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

            // check instances
            String appInstancesUrl = appUrl + "/instances"; //$NON-NLS-1$
            URI appInstancesURI = targetURI.resolve(appInstancesUrl);

            GetMethod getInstancesMethod = new GetMethod(appInstancesURI.toString());
            HttpUtil.configureHttpMethod(getInstancesMethod, target);

            getInstancesStatus = HttpUtil.executeMethod(getInstancesMethod);
            if (!getInstancesStatus.isOK()) {
                --attemptsLeft;
                continue;
            }

            JSONObject appInstancesJSON = getInstancesStatus.getJsonData();

            int instancesNo = appInstancesJSON.length();
            int runningInstanceNo = 0;
            int flappingInstanceNo = 0;

            Iterator<String> instanceIt = appInstancesJSON.keys();
            while (instanceIt.hasNext()) {
                JSONObject instanceJSON = appInstancesJSON.getJSONObject(instanceIt.next());
                if ("RUNNING".equals(instanceJSON.optString("state"))) //$NON-NLS-1$ //$NON-NLS-2$
                    runningInstanceNo++;
                else if ("FLAPPING".equals(instanceJSON.optString("state"))) //$NON-NLS-1$ //$NON-NLS-2$
                    flappingInstanceNo++;
            }
            ;

            if (runningInstanceNo == instancesNo)
                break;

            if (flappingInstanceNo > 0)
                break;

            --attemptsLeft;
        }

        result.add(getInstancesStatus);
        return 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:com.turn.camino.config.ConfigBuilder.java

/**
 * Resolves include config to context location
 *
 * @param include include config/*from  ww w  .  j av  a 2 s. co  m*/
 * @param context URI context
 * @return resolved URI
 * @throws IOException
 */
protected URI resolveInclude(String include, URI context) throws IOException {
    URI uri = URI.create(include);
    if (uri.getScheme() != null) {
        return uri;
    }
    if (context != null) {
        return context.resolve(uri);
    }
    throw new IOException("Cannot find config " + include);
}