Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

In this page you can find the example usage for java.net URI toURL.

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

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 ww  w .  ja v  a 2s. co  m
            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.dtolabs.client.utils.HttpClientChannel.java

/**
 * Process the URL based on the query params, and create the HttpURLConnection with appropriate headers for username
 * and password.//  w  w w  . j a  va2  s.  c  om
 */
protected void init(String uriSpec, Map query) throws CoreException {

    requestUrl = uriSpec;
    if (query != null && query.size() > 0) {
        requestUrl = constructURLQuery(uriSpec, query);
    }

    URI uri;
    try {
        uri = new URI(requestUrl);
    } catch (URISyntaxException e) {
        throw new CoreException(e.getMessage());
    }

    requestURL = null;
    try {
        requestURL = uri.toURL();
    } catch (MalformedURLException e) {
        throw new CoreException(e.getMessage());
    }
    logger.debug("creating connection object to URL: " + requestUrl);

    httpc = new HttpClient();
}

From source file:be.fedict.trust.crl.OnlineCrlRepository.java

private X509CRL getCrl(URI crlUri) throws IOException, CertificateException, CRLException,
        NoSuchProviderException, NoSuchParserException, StreamParsingException {
    HttpClient httpClient = new HttpClient();
    if (null != this.networkConfig) {
        httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(),
                this.networkConfig.getProxyPort());
    }/*from   ww  w  .j a v  a2 s. c  om*/
    if (null != this.credentials) {
        HttpState httpState = httpClient.getState();
        this.credentials.init(httpState);
    }
    String downloadUrl = crlUri.toURL().toString();
    LOG.debug("downloading CRL from: " + downloadUrl);
    GetMethod getMethod = new GetMethod(downloadUrl);
    getMethod.addRequestHeader("User-Agent", "jTrust CRL Client");
    int statusCode = httpClient.executeMethod(getMethod);
    if (HttpURLConnection.HTTP_OK != statusCode) {
        LOG.debug("HTTP status code: " + statusCode);
        return null;
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    X509CRL crl = (X509CRL) certificateFactory.generateCRL(getMethod.getResponseBodyAsStream());
    LOG.debug("CRL size: " + crl.getEncoded().length + " bytes");
    return crl;
}

From source file:org.apache.cxf.maven_plugin.wadlto.AbstractCodeGeneratorMojo.java

private void runForked(Set<URI> classPath, Class<?> cls, String[] args) throws MojoExecutionException {
    getLog().info("Running wadl2java in fork mode...");

    Commandline cmd = new Commandline();
    cmd.getShell().setQuotedArgumentsEnabled(true); // for JVM args
    cmd.setWorkingDirectory(project.getBuild().getDirectory());
    try {//w  w w  .  j  a  v  a  2 s . co m
        cmd.setExecutable(getJavaExecutable().getAbsolutePath());
    } catch (IOException e) {
        getLog().debug(e);
        throw new MojoExecutionException(e.getMessage(), e);
    }

    cmd.createArg().setLine(additionalJvmArgs);

    File file = null;
    try {
        //file = new File("/tmp/test.jar");
        file = FileUtils.createTempFile("cxf-codegen", ".jar");

        JarArchiver jar = new JarArchiver();
        jar.setDestFile(file.getAbsoluteFile());

        Manifest manifest = new Manifest();
        Attribute attr = new Attribute();
        attr.setName("Class-Path");
        StringBuilder b = new StringBuilder(8000);
        for (URI cp : classPath) {
            b.append(cp.toURL().toExternalForm()).append(' ');
        }
        attr.setValue(b.toString());
        manifest.getMainSection().addConfiguredAttribute(attr);

        attr = new Attribute();
        attr.setName("Main-Class");
        attr.setValue(cls.getName());
        manifest.getMainSection().addConfiguredAttribute(attr);

        jar.addConfiguredManifest(manifest);
        jar.createArchive();

        cmd.createArg().setValue("-jar");
        cmd.createArg().setValue(file.getAbsolutePath());

    } catch (Exception e1) {
        throw new MojoExecutionException("Could not create runtime jar", e1);
    }
    cmd.addArguments(args);

    CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();
    CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer();

    int exitCode;
    try {
        exitCode = CommandLineUtils.executeCommandLine(cmd, out, err);
    } catch (CommandLineException e) {
        getLog().debug(e);
        throw new MojoExecutionException(e.getMessage(), e);
    }

    String output = StringUtils.isEmpty(out.getOutput()) ? null : '\n' + out.getOutput().trim();

    String cmdLine = CommandLineUtils.toString(cmd.getCommandline());

    if (exitCode != 0) {
        if (StringUtils.isNotEmpty(output)) {
            getLog().info(output);
        }

        StringBuilder msg = new StringBuilder("\nExit code: ");
        msg.append(exitCode);
        if (StringUtils.isNotEmpty(err.getOutput())) {
            msg.append(" - ").append(err.getOutput());
        }
        msg.append('\n');
        msg.append("Command line was: ").append(cmdLine).append('\n').append('\n');

        throw new MojoExecutionException(msg.toString());
    }

    if (file != null) {
        file.delete();
    }
    if (StringUtils.isNotEmpty(err.getOutput()) && err.getOutput().contains("WADL2Java Error")) {
        StringBuilder msg = new StringBuilder();
        msg.append(err.getOutput());
        msg.append('\n');
        msg.append("Command line was: ").append(cmdLine).append('\n').append('\n');
        throw new MojoExecutionException(msg.toString());
    }

}

From source file:com.googlecode.fascinator.indexer.SolrWrapperQueueConsumer.java

/**
 * Initialize a Solr core object./*from  w  ww.  j av  a 2 s  . com*/
 * 
 * @param coreName : The core to initialize
 * @return SolrServer : The initialized core
 */
private SolrServer initCore(String core) {
    boolean isEmbedded = globalConfig.getBoolean(false, "indexer", core, "embedded");
    try {
        // Embedded Solr
        if (isEmbedded) {
            // Solr over HTTP - Needed to run commits
            // so the core web server sees them.
            String uri = globalConfig.getString(null, "indexer", core, "uri");
            if (uri == null) {
                log.error("No URI provided for core: '{}'", core);
                return null;
            }
            URI solrUri = new URI(uri);
            commit = new CommonsHttpSolrServer(solrUri.toURL());
            username = globalConfig.getString(null, "indexer", core, "username");
            password = globalConfig.getString(null, "indexer", core, "password");
            if (username != null && password != null) {
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
                HttpClient hc = ((CommonsHttpSolrServer) solr).getHttpClient();
                hc.getParams().setAuthenticationPreemptive(true);
                hc.getState().setCredentials(AuthScope.ANY, credentials);
            }

            // First time execution
            if (coreContainer == null) {
                String home = globalConfig.getString(DEFAULT_SOLR_HOME, "indexer", "home");
                log.info("Embedded Solr Home = {}", home);
                File homeDir = new File(home);
                if (!homeDir.exists()) {
                    log.error("Solr directory does not exist!");
                    return null;
                }
                System.setProperty("solr.solr.home", homeDir.getAbsolutePath());
                File coreXmlFile = new File(homeDir, "solr.xml");
                coreContainer = new CoreContainer(homeDir.getAbsolutePath(), coreXmlFile);
                for (SolrCore aCore : coreContainer.getCores()) {
                    log.info("Loaded core: {}", aCore.getName());
                }
            }
            String coreName = globalConfig.getString(null, "indexer", core, "coreName");
            if (coreName == null) {
                log.error("No 'coreName' node for core: '{}'", core);
                return null;
            }
            return new EmbeddedSolrServer(coreContainer, coreName);

            // Solr over HTTP
        } else {
            String uri = globalConfig.getString(null, "indexer", core, "uri");
            if (uri == null) {
                log.error("No URI provided for core: '{}'", core);
                return null;
            }

            URI solrUri = new URI(uri);
            CommonsHttpSolrServer thisCore = new CommonsHttpSolrServer(solrUri.toURL());
            username = globalConfig.getString(null, "indexer", core, "username");
            password = globalConfig.getString(null, "indexer", core, "password");
            if (username != null && password != null) {
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
                HttpClient hc = thisCore.getHttpClient();
                hc.getParams().setAuthenticationPreemptive(true);
                hc.getState().setCredentials(AuthScope.ANY, credentials);
            }
            return thisCore;
        }

    } catch (MalformedURLException mue) {
        log.error(core + " : Malformed URL", mue);
    } catch (URISyntaxException urise) {
        log.error(core + " : Invalid URI", urise);
    } catch (IOException ioe) {
        log.error(core + " : Failed to read Solr configuration", ioe);
    } catch (ParserConfigurationException pce) {
        log.error(core + " : Failed to parse Solr configuration", pce);
    } catch (SAXException saxe) {
        log.error(core + " : Failed to load Solr configuration", saxe);
    }
    return null;
}

From source file:dip.world.variant.VariantManager.java

/** 
 *   Gets a specific resource for a Variant or a SymbolPack, given a URL to
 *   the package and a reference URI. Threadsafe. 
 *   <p>//www .  j  a  va2  s  .  com
 *   Typically, getResource(Variant, URI) or getResource(SymbolPack, URI) is
 *   preferred to this method.
 *
 */
public static synchronized URL getResource(URL packURL, URI uri) {
    // ensure we have been initialized...
    checkVM();

    // if we are in webstart, assume that this is a webstart jar. 
    if (vm.isInWebstart) {
        URL url = getWSResource(packURL, uri);

        // if cannot get it, fall through.
        if (url != null) {
            return url;
        }
    }

    // if URI has a defined scheme, convert to a URL (if possible) and return it.
    if (uri.getScheme() != null) {
        try {
            return uri.toURL();
        } catch (MalformedURLException e) {
            return null;
        }
    }

    // resolve & load.
    URLClassLoader classLoader = getClassLoader(packURL);
    return classLoader.findResource(uri.toString());
}

From source file:com.liferay.maven.plugins.AbstractToolsLiferayMojo.java

protected List<String> getProjectClassPath() throws Exception {
    List<String> projectClassPath = new ArrayList<String>();

    projectClassPath.addAll(getToolsClassPath());

    List<MavenProject> classPathMavenProjects = new ArrayList<MavenProject>();

    classPathMavenProjects.add(project);

    for (Object object : project.getDependencyArtifacts()) {
        Artifact artifact = (Artifact) object;

        ArtifactHandler artifactHandler = artifact.getArtifactHandler();

        if (!artifactHandler.isAddedToClasspath()) {
            continue;
        }/*from www .  ja va 2  s. c om*/

        MavenProject dependencyMavenProject = resolveProject(artifact);

        if (dependencyMavenProject == null) {
            continue;
        } else {
            getLog().debug("Resolved dependency project " + dependencyMavenProject);
        }

        List<String> compileSourceRoots = dependencyMavenProject.getCompileSourceRoots();

        if (compileSourceRoots.isEmpty()) {
            continue;
        }

        getLog().debug("Adding project to class path " + dependencyMavenProject);

        classPathMavenProjects.add(dependencyMavenProject);
    }

    for (MavenProject classPathMavenProject : classPathMavenProjects) {
        for (Object object : classPathMavenProject.getCompileClasspathElements()) {

            String path = (String) object;

            getLog().debug("Class path element " + path);

            File file = new File(path);

            URI uri = file.toURI();

            URL url = uri.toURL();

            projectClassPath.add(url.toString());
        }
    }

    getLog().debug("Project class path:");

    for (String path : projectClassPath) {
        getLog().debug("\t" + path);
    }

    return projectClassPath;
}

From source file:io.apiman.manager.api.rest.impl.PluginResourceImpl.java

/**
 * Loads a plugin registry from its URL.  Will use the value in the
 * cache if it exists.  If not, it will connect to the remote URL and
 * grab the registry JSON file./*from w  w w  .j  a  va  2s.  c om*/
 * @param registryUrl the URL of the registry
 */
private PluginRegistryBean loadRegistry(URI registryUrl) {
    PluginRegistryBean fromCache = registryCache.get(registryUrl);
    if (fromCache != null) {
        return fromCache;
    }
    try {
        PluginRegistryBean registry = mapper.reader(PluginRegistryBean.class).readValue(registryUrl.toURL());
        registryCache.put(registryUrl, registry);
        return registry;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.mercer.cpsg.swarm.oidc.deployment.OIDCAuthenticationMechanism.java

private JWKSet getProviderRSAKeys(URI jwkSetURI) throws Exception {
    InputStream is = jwkSetURI.toURL().openStream();
    String jsonString = IOUtils.toString(is);
    return getProviderRSAKeys(JSONObjectUtils.parse(jsonString));

}

From source file:de.betterform.agent.betty.Betty.java

/**
 * Init: Initializes an AppletAdapter.//w  ww  .  jav a 2 s .com
 */
public void init() {
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Applet init start");
        }

        // set splash screen

        //            javascriptCall("setSplash", getSplashScreen(XFormsProcessorImpl.getAppInfo(), ""));

        // get code and document bases
        URL codeBaseUrl = getCodeBase();
        URL documentBaseUrl = getDocumentBase();
        LOGGER.debug("getDocumentBase: " + documentBaseUrl.toExternalForm());

        // extract document name
        String documentPath = documentBaseUrl.getPath();
        this.documentName = documentPath.substring(documentPath.lastIndexOf('/') + 1);

        // update splash screen
        //            javascriptCall("setSplash", getSplashScreen("configuring", this.documentName));

        // init logging
        URI log4jUrl = resolveParameter(codeBaseUrl, LOG4J_PARAMETER, LOG4J_DEFAULT);
        DOMConfigurator.configure(log4jUrl.toURL());

        LOGGER.info("init: code base '" + codeBaseUrl + "'");
        LOGGER.info("init: document base '" + documentBaseUrl + "'");
        LOGGER.info("init: document name '" + this.documentName + "'");

        // loading config
        URI configUrl = resolveParameter(codeBaseUrl, CONFIG_PARAMETER, CONFIG_DEFAULT);
        LOGGER.info("configURL '" + configUrl + "'");
        if (configUrl.toString().startsWith("file:")) {
            LOGGER.info("loading from file:");
            Config.getInstance(new FileInputStream(new File(configUrl)));
        } else {
            LOGGER.info("loading from http:");
            Config.getInstance(configUrl.toURL().openConnection().getInputStream());
        }

        // init adapter
        this.appletProcessor = initAdapter(documentBaseUrl);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        handleException(e);
        throw new RuntimeException(e);
    }
}