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.apache.cxf.maven_plugin.AbstractCodegenMoho.java

protected void runForked(Set<URI> classPath, String mainClassName, String[] args)
        throws MojoExecutionException {
    getLog().info("Running code generation in fork mode...");
    getLog().debug("Running code generation in fork mode with args " + Arrays.asList(args));

    Commandline cmd = new Commandline();
    cmd.getShell().setQuotedArgumentsEnabled(true); // for JVM args
    cmd.setWorkingDirectory(project.getBuild().getDirectory());
    try {/*from   w  w w .jav a  2s  .c  om*/
        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(mainClassName);
        manifest.getMainSection().addConfiguredAttribute(attr);

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

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

        String tmpFilePath = file.getAbsolutePath();
        if (tmpFilePath.contains(" ")) {
            //ensure the path is in double quotation marks if the path contain space
            tmpFilePath = "\"" + tmpFilePath + "\"";
        }
        cmd.createArg().setValue(tmpFilePath);

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

    StreamConsumer out = new StreamConsumer() {
        public void consumeLine(String line) {
            getLog().info(line);
        }
    };
    final StringBuilder b = new StringBuilder();
    StreamConsumer err = new StreamConsumer() {
        public void consumeLine(String line) {
            b.append(line);
            b.append("\n");
            getLog().warn(line);
        }
    };
    int exitCode;
    try {
        exitCode = CommandLineUtils.executeCommandLine(cmd, out, err);
    } catch (CommandLineException e) {
        getLog().debug(e);
        throw new MojoExecutionException(e.getMessage(), e);
    }

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

    if (exitCode != 0) {
        StringBuilder msg = new StringBuilder("\nExit code: ");
        msg.append(exitCode);
        msg.append('\n');
        msg.append("Command line was: ").append(cmdLine).append('\n').append('\n');

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

    file.delete();
    if (b.toString().contains("WSDL2Java Error")) {
        StringBuilder msg = new StringBuilder();
        msg.append(b.toString());
        msg.append('\n');
        msg.append("Command line was: ").append(cmdLine).append('\n').append('\n');
        throw new MojoExecutionException(msg.toString());
    }

}

From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

@Override
public String replaceFile(final String UURI, final String tenantID, final URI resourceURI) throws IOException {
    //Create Unique hash
    final String hash = hashText(UURI);
    if (hash == null) {
        //TODO: Throw exception
        LOG.error("Unable to create HASH for UID {}", UURI);
    }//  w ww . jav a  2  s.  co  m

    //Get Filename (including directories)
    final String filename = getFilename(hash);

    //Add Volume to the Path
    final Path file = Paths.get(VOLUME + "/" + tenantID + filename);

    //Convert URI to URL
    final URL resourceUrl = resourceURI.toURL();

    //Write the contents to the file
    replaceFile(file, resourceUrl);

    return getRelativePath(file);
}

From source file:org.geoserver.config.GeoServerPersister.java

List<File> resources(StyleInfo s) throws IOException {
    final List<File> files = new ArrayList<File>();
    try {//from   ww  w  .jav a  2s .  c  o m
        s.getStyle().accept(new AbstractStyleVisitor() {
            @Override
            public void visit(ExternalGraphic exgr) {
                if (exgr.getOnlineResource() == null) {
                    return;
                }

                URI uri = exgr.getOnlineResource().getLinkage();
                if (uri == null) {
                    return;
                }

                File f = null;
                try {
                    f = DataUtilities.urlToFile(uri.toURL());
                } catch (MalformedURLException e) {
                    LOGGER.log(Level.WARNING, "Error attemping to processing SLD resource", e);
                }

                if (f != null && f.exists()) {
                    files.add(f);
                }
            }
        });
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Error loading style", e);
    }

    return files;
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

@Override
public URL createClassroomUrl(String roomId, Identity identity, VCConfiguration config) {
    URL url = null;/*from w  w  w. java  2 s .c om*/
    URI uri = UriBuilder.fromUri(protocol + "://" + baseUrl).port(port).path(PREFIX + roomId)
            .queryParam("session", cookie).build();
    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
        logWarn("Cannot create access URL to Adobe Connect meeting for id \"" + PREFIX + roomId
                + "\" and user \"" + identity.getName() + "\"", e);
    }
    return url;
}

From source file:org.eclipse.jdt.ls.core.internal.handlers.DocumentLifeCycleHandlerTest.java

@Test
public void testDidOpenNotOnClasspath() throws Exception {
    importProjects("eclipse/hello");
    IProject project = WorkspaceHelper.getProject("hello");
    URI uri = project.getFile("nopackage/Test2.java").getRawLocationURI();
    ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
    String source = FileUtils.readFileToString(FileUtils.toFile(uri.toURL()));
    openDocument(cu, source, 1);/*from w  w w  .  j a v  a 2s. co m*/
    Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
    assertEquals(project, cu.getJavaProject().getProject());
    assertEquals(source, cu.getSource());
    List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
    assertEquals(1, diagnosticReports.size());
    PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
    assertEquals(1, diagParam.getDiagnostics().size());
    closeDocument(cu);
    Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
    diagnosticReports = getClientRequests("publishDiagnostics");
    assertEquals(2, diagnosticReports.size());
    diagParam = diagnosticReports.get(1);
    assertEquals(0, diagParam.getDiagnostics().size());
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

@Override
public URL createClassroomGuestUrl(String roomId, Identity identity, VCConfiguration config) {
    URL url = null;//from  w  ww .j a  v  a2 s . co  m
    URI uri = UriBuilder.fromUri(protocol + "://" + baseUrl).port(port).path(PREFIX + roomId)
            .queryParam("guestName", identity.getName()).build();
    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
        logWarn("Cannot create access URL to Adobe Connect meeting for id \"" + PREFIX + roomId
                + "\" and user \"" + identity.getName() + "\"", e);
    }
    return url;
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.connid.ConnectorFactoryConnIdImpl.java

/**
 * Scan directory for bundles only on first lval we do the scan
 *
 * @param path/*  w  w w  .  j av  a 2s  .  c om*/
 * @return
 */
private Set<URI> scanDirectory(String path) {

    // Prepare return object
    Set<URI> bundle = new HashSet<>();
    // Convert path to object File
    File dir = new File(path);

    // Test if this path is single jar or need to do deep examination
    if (isThisJarFileBundle(dir)) {
        try {
            final URI uri = dir.toURI();
            if (isThisBundleCompatible(uri.toURL())) {
                bundle.add(uri);
            } else {
                LOGGER.warn("Skip loading bundle {} due error occurred", uri.toURL());
            }
        } catch (MalformedURLException e) {
            LOGGER.error("This never happened we hope.", e);
            throw new SystemException(e);
        }
        return bundle;
    }

    // Test if it is a directory
    if (!dir.isDirectory()) {
        LOGGER.error("Provided Icf connector path {} is not a directory.", dir.getAbsolutePath());
    }

    // List directory items
    File[] dirEntries = dir.listFiles();
    if (null == dirEntries) {
        LOGGER.warn("No bundles found in directory {}", dir.getAbsolutePath());
        return bundle;
    }

    // test all entries for bundle
    for (int i = 0; i < dirEntries.length; i++) {
        if (isThisJarFileBundle(dirEntries[i])) {
            try {
                final URI uri = dirEntries[i].toURI();
                if (isThisBundleCompatible(uri.toURL())) {
                    bundle.add(uri);
                } else {
                    LOGGER.warn("Skip loading bundle {} due error occurred", uri.toURL());
                }
            } catch (MalformedURLException e) {
                LOGGER.error("This never happened we hope.", e);
                throw new SystemException(e);
            }
        }
    }
    return bundle;
}

From source file:org.kepler.ddp.director.DDPEngine.java

/** Get a list of jars required for director to start. 
 *  It also set _classLoader value based on the jars.
 *//*from  w  w w. j a va  2  s .co m*/
protected List<URI> _getJarList() throws IllegalActionException {
    final List<URI> jarPaths = new LinkedList<URI>();
    final List<File> jarsWithRelativePaths = new LinkedList<File>();

    for (String additionalJar : _additionalJars) {
        jarsWithRelativePaths.add(new File(additionalJar));
    }

    // get the jars in the director's includeJars parameter
    String includeJarsStr = _director.includeJars.stringValue();
    if (includeJarsStr != null && !includeJarsStr.isEmpty()) {
        for (String jarPath : includeJarsStr.split(",")) {
            File jarFile = new File(jarPath);
            // see if jar is an absolute path
            if (jarFile.isAbsolute()) {
                if (!jarFile.exists() || !jarFile.canRead()) {
                    throw new IllegalActionException(_director,
                            "Jar does not exist or cannot be read: " + jarFile);
                }
                // jars with absolute paths are added directly
                System.out.println("Adding jar: " + jarFile.getAbsolutePath());
                jarPaths.add(jarFile.toURI());
            } else {
                jarsWithRelativePaths.add(jarFile);
            }
        }
    }

    // add the module jars, e.g., actors.jar, ptolemy.jar, etc.
    // also add any jars in includeJars with a relative path - these jars
    // are assumed to be module/lib/jar.
    final ModuleTree moduleTree = ModuleTree.instance();
    for (Module module : moduleTree) {

        final File moduleJar = module.getTargetJar();

        // add the module jar if it exists.
        // some modules, e.g., outreach, do not have jars.
        if (moduleJar.exists()) {
            jarPaths.add(moduleJar.toURI());
        }

        final List<File> moduleJars = module.getJars();
        for (File jar : moduleJars) {
            // include kepler-tasks.jar since we need classes
            // in org.kepler.build to initialize kepler in the
            // stub. see StubUtilities.initializeKepler()
            if (jar.getName().equals("kepler-tasks.jar")) {
                //System.out.println("adding jar " + jar);
                jarPaths.add(jar.toURI());
            } else if (jar.getName().matches("^log4j.*jar$") || //add log4j jar since it is used for display-redirect function in DDP.
                    jar.getName().equals("ant.jar")) {
                jarPaths.add(jar.toURI());
            } else if (!jarsWithRelativePaths.isEmpty()) {
                for (File jarFile : jarsWithRelativePaths) {
                    if (jar.getName().equals(jarFile.getName())) {
                        System.out.println("Adding jar in module " + module.getName() + ": " + jar);
                        jarPaths.add(jar.toURI());
                    }
                }
            }
        }
    }

    // add any jars specified by the actors.
    final List<DDPPatternActor> actors = _container.entityList(DDPPatternActor.class);
    for (DDPPatternActor actor : actors) {
        final String jarsStr = actor.getJars();
        if (!jarsStr.isEmpty()) {
            final String[] jars = jarsStr.split(",");
            for (String jar : jars) {
                final File jarFile = new File(jar);
                if (!jarFile.exists() || !jarFile.canRead()) {
                    throw new IllegalActionException(actor,
                            "Jar does not exist or cannot be read: " + jarFile.getAbsolutePath());
                }
                System.out.println("Adding jar for " + actor.getFullName() + ": " + jarFile.getAbsolutePath());
                jarPaths.add(jarFile.toURI());
            }
        }
    }

    URL[] jarArray;
    try {
        List<URL> jarURLs = new LinkedList<URL>();
        for (URI jarURI : jarPaths) {
            jarURLs.add(jarURI.toURL());
        }

        jarArray = jarURLs.toArray(new URL[jarURLs.size()]);

        if (jarArray != null && jarArray.length > 0) {
            _classLoader = new URLClassLoader(jarArray, Thread.currentThread().getContextClassLoader());
            Thread.currentThread().setContextClassLoader(_classLoader);
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new IllegalActionException(_director, e.getMessage());
    }

    return jarPaths;
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
        final Map<String, List<String>> headers, final String hostname, final AgentProxy agentProxy,
        final Identity identity) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
                Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length,
                Json.asPrettyStringUnchecked(entity));
    } else {//from  ww  w.  java  2s  .  co  m
        log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
    }

    final URLConnection urlConnection = ipUri.toURL().openConnection();
    final HttpURLConnection connection = (HttpURLConnection) urlConnection;

    // We verify the TLS certificate against the original hostname since verifying against the
    // IP address will fail
    if (urlConnection instanceof HttpsURLConnection) {
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        connection.setRequestProperty("Host", hostname);

        final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String ip, SSLSession sslSession) {
                final String tHostname = hostname.endsWith(".") ? hostname.substring(0, hostname.length() - 1)
                        : hostname;
                return new DefaultHostnameVerifier().verify(tHostname, sslSession);
            }
        });

        if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) {
            final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user);
            httpsConnection.setSSLSocketFactory(factory);
        }
    }

    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
    connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    if (entity.length > 0) {
        connection.setDoOutput(true);
        connection.getOutputStream().write(entity);
    }
    if (urlConnection instanceof HttpsURLConnection) {
        setRequestMethod(connection, method, true);
    } else {
        setRequestMethod(connection, method, false);
    }

    final int responseCode = connection.getResponseCode();
    if (responseCode == HTTP_BAD_GATEWAY) {
        throw new ConnectException("502 Bad Gateway");
    }

    return connection;
}