Example usage for java.net URL toURI

List of usage examples for java.net URL toURI

Introduction

In this page you can find the example usage for java.net URL toURI.

Prototype

public URI toURI() throws URISyntaxException 

Source Link

Document

Returns a java.net.URI equivalent to this URL.

Usage

From source file:de.alpharogroup.lang.ClassUtils.java

/**
 * Gives the resource as a file Object./*w w w  . j a  va2s  .c o  m*/
 *
 * @param name
 *            The name from the file.
 * @param obj
 *            The Object.
 * @return The file or null if the file does not exists.
 * @throws URISyntaxException
 *             occurs by creation of the file with an uri.
 */
public static File getResourceAsFile(final String name, final Object obj) throws URISyntaxException {
    File file = null;
    URL url = getResource(name, obj);
    if (null == url) {
        url = ClassUtils.getClassLoader(obj).getResource(name);
        if (null != url) {
            file = new File(url.toURI());
        }
    } else {
        file = new File(url.toURI());

    }
    return file;
}

From source file:brooklyn.util.ResourceUtils.java

public static URL tidy(URL url) {
    // File class has helpful methods for URIs but not URLs. So we convert.
    URI in;/*w  w w . j a v  a2  s.  c om*/
    try {
        in = url.toURI();
    } catch (URISyntaxException e) {
        throw Exceptions.propagate(e);
    }
    URI out;

    Matcher matcher = pattern.matcher(in.toString());
    if (matcher.matches()) {
        // home-relative
        File home = new File(Os.home());
        File file = new File(home, matcher.group(1));
        out = file.toURI();
    } else if (in.getScheme().equals("file:")) {
        // some other file, so canonicalize
        File file = new File(in);
        out = file.toURI();
    } else {
        // some other scheme, so no-op
        out = in;
    }

    URL urlOut;
    try {
        urlOut = out.toURL();
    } catch (MalformedURLException e) {
        throw Exceptions.propagate(e);
    }
    if (!urlOut.equals(url) && log.isDebugEnabled()) {
        log.debug("quietly changing " + url + " to " + urlOut);
    }
    return urlOut;
}

From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java

private static File download(File file, URL url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    OutputStream out = null;//from  w ww  . j  a va2s .  c o  m
    file.getParentFile().mkdirs();
    try {
        HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        Builder builder = RequestConfig.custom();
        HttpHost proxy = getProxy(target);
        if (proxy != null) {
            builder = builder.setProxy(proxy);
        }
        RequestConfig config = builder.build();
        HttpGet request = new HttpGet(url.toURI());
        request.setConfig(config);
        response = httpclient.execute(target, request);
        InputStream in = response.getEntity().getContent();
        out = new BufferedOutputStream(new FileOutputStream(file));
        copy(in, out);
        return file;
    } catch (Exception e) {
        logWarning(e);
        ;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.java

/**
 * Make the given URL available as a file. A temporary file is created and deleted upon a
 * regular shutdown of the JVM. If the parameter {@code aCache} is {@code true}, the temporary
 * file is remembered in a cache and if a file is requested for the same URL at a later time,
 * the same file is returned again. If the previously created file has been deleted meanwhile,
 * it is recreated from the URL. This method should not be used for creating executable
 * binaries. For this purpose, getUrlAsExecutable should be used.
 *
 * @param aUrl//from w ww.j  a v  a 2  s . c  om
 *            the URL.
 * @param aCache
 *            use the cache or not.
 * @param aForceTemp
 *            always create a temporary file, even if the URL is already a file.
 * @return a file created from the given URL.
 * @throws IOException
 *             if the URL cannot be accessed to (re)create the file.
 */
public static synchronized File getUrlAsFile(URL aUrl, boolean aCache, boolean aForceTemp) throws IOException {
    // If the URL already points to a file, there is not really much to do.
    if (!aForceTemp && "file".equalsIgnoreCase(aUrl.getProtocol())) {
        try {
            return new File(aUrl.toURI());
        } catch (URISyntaxException e) {
            throw new IOException(e);
        }
    }

    synchronized (urlFileCache) {
        // Lets see if we already have a file for this URL in our cache. Maybe
        // the file has been deleted meanwhile, so we also check if the file
        // actually still exists on disk.
        File file = urlFileCache.get(aUrl.toString());
        if (!aCache || (file == null) || !file.exists()) {
            // Create a temporary file and try to preserve the file extension
            String suffix = FilenameUtils.getExtension(aUrl.getPath());
            if (suffix.length() == 0) {
                suffix = "temp";
            }
            String name = FilenameUtils.getBaseName(aUrl.getPath());

            // Get a temporary file which will be deleted when the JVM shuts
            // down.
            file = File.createTempFile(name, "." + suffix);
            file.deleteOnExit();

            // Now copy the file from the URL to the file.

            InputStream is = null;
            OutputStream os = null;
            try {
                is = aUrl.openStream();
                os = new FileOutputStream(file);
                copy(is, os);
            } finally {
                closeQuietly(is);
                closeQuietly(os);
            }

            // Remember the file
            if (aCache) {
                urlFileCache.put(aUrl.toString(), file);
            }
        }

        return file;
    }
}

From source file:eu.esdihumboldt.hale.io.appschema.writer.AppSchemaFileWriterTest.java

@BeforeClass
public static void loadTestProject() {

    try {/*from  w  w w  .j a v  a 2 s .co  m*/
        URL archiveLocation = AppSchemaFileWriterTest.class.getResource(PROJECT_LOCATION);

        ArchiveProjectReader projectReader = new ArchiveProjectReader();
        projectReader.setSource(new DefaultInputSupplier(archiveLocation.toURI()));
        IOReport report = projectReader.execute(new LogProgressIndicator());
        if (!report.isSuccess()) {
            throw new RuntimeException("project reader execution failed");
        }
        tempDir = projectReader.getTemporaryFiles().iterator().next();

        project = projectReader.getProject();
        assertNotNull(project);

        sourceSchemaSpace = new DefaultSchemaSpace();
        targetSchemaSpace = new DefaultSchemaSpace();

        // load schemas
        List<IOConfiguration> resources = project.getResources();
        for (IOConfiguration resource : resources) {
            String actionId = resource.getActionId();
            String providerId = resource.getProviderId();

            // get provider
            IOProvider provider = null;
            IOProviderDescriptor descriptor = IOProviderExtension.getInstance().getFactory(providerId);
            if (descriptor == null) {
                throw new RuntimeException("Could not load I/O provider with ID: " + resource.getProviderId());
            }

            provider = descriptor.createExtensionObject();
            provider.loadConfiguration(resource.getProviderConfiguration());
            prepareProvider(provider, project, tempDir.toURI());

            IOReport providerReport = provider.execute(new LogProgressIndicator());
            if (!providerReport.isSuccess()) {
                throw new RuntimeException("I/O provider execution failed");
            }

            // handle results
            // TODO: could (should?) be done by an advisor
            if (provider instanceof SchemaReader) {
                Schema schema = ((SchemaReader) provider).getSchema();
                if (actionId.equals(SchemaIO.ACTION_LOAD_SOURCE_SCHEMA)) {
                    sourceSchemaSpace.addSchema(schema);
                } else if (actionId.equals(SchemaIO.ACTION_LOAD_TARGET_SCHEMA)) {
                    targetSchemaSpace.addSchema(schema);
                }
            }
        }

        // load alignment
        List<ProjectFileInfo> projectFiles = project.getProjectFiles();
        for (ProjectFileInfo projectFile : projectFiles) {
            if (projectFile.getName().equals(AlignmentIO.PROJECT_FILE_ALIGNMENT)) {
                AlignmentReader alignReader = new JaxbAlignmentReader();
                alignReader.setSource(new DefaultInputSupplier(projectFile.getLocation()));
                alignReader.setSourceSchema(sourceSchemaSpace);
                alignReader.setTargetSchema(targetSchemaSpace);
                alignReader.setPathUpdater(new PathUpdate(null, null));
                IOReport alignReport = alignReader.execute(new LogProgressIndicator());
                if (!alignReport.isSuccess()) {
                    throw new RuntimeException("alignment reader execution failed");
                }

                alignment = alignReader.getAlignment();
                assertNotNull(alignment);

                break;
            }
        }
    } catch (Exception e) {
        log.error("Exception occurred", e);
        fail("Test project could not be loaded: " + e.getMessage());
    }

}

From source file:com.cloud.consoleproxy.ConsoleProxy.java

private static void configLog4j() {
    URL configUrl = System.class.getResource("/conf/log4j-cloud.xml");
    if (configUrl == null)
        configUrl = ClassLoader.getSystemResource("log4j-cloud.xml");

    if (configUrl == null)
        configUrl = ClassLoader.getSystemResource("conf/log4j-cloud.xml");

    if (configUrl != null) {
        try {//from   w  w w  . ja  v a  2s  . c o  m
            System.out.println("Configure log4j using " + configUrl.toURI().toString());
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }

        try {
            File file = new File(configUrl.toURI());

            System.out.println("Log4j configuration from : " + file.getAbsolutePath());
            DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
        } catch (URISyntaxException e) {
            System.out.println("Unable to convert log4j configuration Url to URI");
        }
        // DOMConfigurator.configure(configUrl);
    } else {
        System.out.println("Configure log4j with default properties");
    }
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

private static DiscoveryResults discoverPollingClient(URL proxy, URL endpoint, String username, String password,
        HttpClientContext context, String defaultCollection) throws Exception {

    DiscoveryResults results = new DiscoveryResults();
    {//from   ww w .  ja  v  a  2 s . c o  m
        HttpClient discoverClient = buildClient(proxy, username, password);
        String sessionID = MessageHelper.generateMessageId();
        // Prepare the message to send.
        DiscoveryRequest request = messageFactory.get().createDiscoveryRequest().withMessageId(sessionID);
        DiscoveryResponse response = call(discoverClient, endpoint.toURI(), request, context,
                DiscoveryResponse.class);
        for (ServiceInstanceType serviceInstance : response.getServiceInstances()) {
            if (serviceInstance.isAvailable() && serviceInstance.getServiceType() == ServiceTypeEnum.POLL) {
                results.pollEndpoint = new URL(serviceInstance.getAddress());
            } else if (serviceInstance.isAvailable()
                    && serviceInstance.getServiceType() == ServiceTypeEnum.COLLECTION_MANAGEMENT) {
                results.collectionManagementEndpoint = new URL(serviceInstance.getAddress());
            }
        }
        if (results.pollEndpoint == null) {
            throw new RuntimeException("Unable to discover a poll TAXII feed");
        }
    }
    if (defaultCollection == null)
    //get collections
    {
        HttpClient discoverClient = buildClient(proxy, username, password);
        String sessionID = MessageHelper.generateMessageId();
        CollectionInformationRequest request = messageFactory.get().createCollectionInformationRequest()
                .withMessageId(sessionID);
        CollectionInformationResponse response = call(discoverClient,
                results.collectionManagementEndpoint.toURI(), request, context,
                CollectionInformationResponse.class);
        LOG.info("Unable to find the default collection; available collections are:");
        for (CollectionRecordType c : response.getCollections()) {
            LOG.info(c.getCollectionName());
            results.collections.add(c.getCollectionName());
        }
        System.exit(0);
    }
    return results;
}

From source file:de.alpharogroup.lang.ClassExtensions.java

/**
 * Gives the resource as a file Object.//  w w w  .j av a  2  s.c o m
 *
 * @param name
 *            The name from the file.
 * @return The file or null if the file does not exists.
 * @throws URISyntaxException
 *             occurs by creation of the file with an uri.
 */
public static File getResourceAsFile(final String name) throws URISyntaxException {
    File file = null;
    URL url = getResource(name);
    if (null == url) {
        url = ClassExtensions.getClassLoader().getResource(name);
        if (null != url) {
            file = new File(url.toURI());
        }
    } else {
        file = new File(url.toURI());
    }
    return file;
}

From source file:ca.sqlpower.enterprise.ServerInfoProvider.java

private static void init(URL url, String username, String password, CookieStore cookieStore)
        throws IOException {

    if (version.containsKey(generateServerKey(url, username, password)))
        return;/* ww w .j  av a 2 s. com*/

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(cookieStore);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(url.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(url, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(url, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(url, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer || (watermarkMessage != null && watermarkMessage.trim().length() > 0)) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    HyperlinkListener hyperlinkListener = new HyperlinkListener() {
                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent e) {
                            try {
                                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                    if (e.getURL() != null) {
                                        BrowserUtil.launch(e.getURL().toString());
                                    }
                                }
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    };
                    HTMLUserPrompter htmlPrompter = new HTMLUserPrompter(UserPromptOptions.OK,
                            UserPromptResponse.OK, null, watermarkMessage, hyperlinkListener, "OK");
                    htmlPrompter.promptUser("");
                }
            });
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}

From source file:de.alpharogroup.lang.ClassExtensions.java

/**
 * Gives the resource as a file Object.//  www. j  a  v a 2  s. co m
 *
 * @param name
 *            The name from the file.
 * @param obj
 *            The Object.
 * @return The file or null if the file does not exists.
 * @throws URISyntaxException
 *             occurs by creation of the file with an uri.
 */
public static File getResourceAsFile(final String name, final Object obj) throws URISyntaxException {
    File file = null;
    URL url = getResource(name, obj);
    if (null == url) {
        url = ClassExtensions.getClassLoader(obj).getResource(name);
        if (null != url) {
            file = new File(url.toURI());
        }
    } else {
        file = new File(url.toURI());

    }
    return file;
}