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:edu.kit.dama.staging.services.processor.impl.DownloadZipper.java

@Override
public void performPostTransferProcessing(TransferTaskContainer pContainer) throws StagingProcessorException {
    LOGGER.debug("Zipping data");
    URL generatedFolder = pContainer.getGeneratedUrl();
    LOGGER.debug("Using target folder: {}", generatedFolder);

    try {/*from   ww  w .  j  a  va 2s  .com*/
        String zipFileName = CryptUtil.stringToSHA1(pContainer.getTransferInformation().getDigitalObjectId())
                + ".zip";
        URL targetZip = URLCreator.appendToURL(generatedFolder, zipFileName);
        LOGGER.debug("Zipping all data to file {}", targetZip);
        File targetFile = new File(targetZip.toURI());

        ITransferInformation info = pContainer.getTransferInformation();
        LOGGER.debug("Obtaining local folder for transfer with id {}", info.getTransferId());

        File localFolder = StagingService.getSingleton().getLocalStagingFolder(info,
                StagingService.getSingleton().getContext(info));
        File dataFolder = new File(
                FilenameUtils.concat(localFolder.getAbsolutePath(), Constants.STAGING_DATA_FOLDER_NAME));
        if (!dataFolder.exists()) {
            throw new IOException(
                    "Data folder " + dataFolder.getAbsolutePath() + " does not exist. Aborting zip operation.");
        }

        LOGGER.debug("Start zip operation using data input folder URL {}", dataFolder);
        ZipUtils.zip(new File(dataFolder.toURI()), targetFile);
        LOGGER.debug("Deleting 'data' folder content.");
        for (File f : new File(dataFolder.toURI()).listFiles()) {
            FileUtils.deleteQuietly(f);
        }
        LOGGER.debug("Moving result file {} to 'data' folder.", targetFile);
        FileUtils.moveFileToDirectory(targetFile, new File(dataFolder.toURI()), false);
        LOGGER.debug("Zip operation successfully finished.");
    } catch (IOException | URISyntaxException ex) {
        throw new StagingProcessorException("Failed to zip data", ex);
    }
}

From source file:com.sachviet.bookman.server.util.ResolverUtil.java

public void findInPackage(String packageName, Test... tests) {
    packageName = packageName.replace('.', '/');
    final ClassLoader loader = getClassLoader();
    Enumeration<URL> urls;
    try {/*w  w w.  j  ava2 s .  co m*/
        urls = loader.getResources(packageName);
    } catch (IOException ioe) {
        LOG.trace("Could not read package: " + packageName, ioe); //$NON-NLS-1$
        return;
    }
    while (urls.hasMoreElements()) {
        try {
            URL eurl = urls.nextElement();
            String urlPath = eurl.toURI().toString();

            if (urlPath.indexOf('!') > 0) {
                urlPath = urlPath.substring(0, urlPath.indexOf('!'));
                if (urlPath.startsWith("jar:")) { //$NON-NLS-1$
                    urlPath = urlPath.substring(4);
                }
                eurl = new URL(urlPath);
            }
            LOG.trace("Scanning for classes in [" + urlPath //$NON-NLS-1$
                    + "] matching criteria: " + tests); //$NON-NLS-1$

            // is it a file?
            final File file = new File(URLDecoder.decode(eurl.getFile(), "UTF-8")); //$NON-NLS-1$
            // File file = new File(eurl.getFile());
            if (file.exists() && file.isDirectory()) {
                loadImplementationsInDirectory(packageName, file, tests);
            } else {
                loadImplementationsInJar(packageName, eurl, tests);
            }
        } catch (IOException e) {
            LOG.trace("could not read entries", e); //$NON-NLS-1$
        } catch (URISyntaxException se) {
            LOG.trace("could not read entries", se); //$NON-NLS-1$
        }
    }
}

From source file:com.stereokrauts.stereoscope.webgui.messaging.handler.protocol.HttpServerRequestHandler.java

public Path createInvalidPath(Path other) {
    URL resource = this.getClass().getClassLoader().getResource(".");
    //URL resource = this.getClass().getClassLoader().getResource("index.html");
    if (resource != null) {
        try {/*ww  w.  ja  v a 2 s .  com*/
            URI uri = resource.toURI();
            return Paths.get(uri + other.toString());
        } catch (URISyntaxException e) {
            LOG.error("HTTP request handler: Desired resource not found.");
        }
    }
    // If all else fails, return null, but beware that this can cause PathAdjuster to NPE.
    return null;
}

From source file:io.vertx.ext.shell.term.TelnetTermServerTest.java

@Test
public void testKeymapFromFilesystem(TestContext context) throws Exception {
    URL url = TermServer.class.getResource(SSHTermOptions.DEFAULT_INPUTRC);
    File f = new File(url.toURI());
    startTelnet(context, new TelnetTermOptions().setIntputrc(f.getAbsolutePath()), Term::close);
    client.connect("localhost", server.actualPort());
}

From source file:com.mobilevangelist.glass.helloworld.GetTheWeatherActivity.java

private Bitmap loadImageFromURL(String getURL) {

    try {/* ww w. java2 s .c o m*/
        URL url = new URL(getURL);

        HttpGet httpRequest = null;
        httpRequest = new HttpGet(url.toURI());
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
        InputStream input = b_entity.getContent();
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;
    } catch (Exception ex) {

        Toast t2 = Toast.makeText(getApplicationContext(), "Image Loading Failed", Toast.LENGTH_LONG);
        t2.setGravity(Gravity.CENTER, 0, 0);
        t2.show();
        return null;
    }
}

From source file:com.enigmastation.ml.bayes.CorpusTest.java

@Test(groups = { "fulltest" })
public void testCorpus() throws URISyntaxException, IOException, InterruptedException {
    final Classifier classifier = new FisherClassifierImpl();
    ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    // first we expand the test dataset
    URL resource = this.getClass().getResource("/src/test/resources/publiccorpus");
    File resourceFile = new File(resource.toURI());
    String[] dataFileNames = resourceFile.list(new FilenameFilter() {
        @Override//from w ww . ja va2  s. c o  m
        public boolean accept(File dir, String name) {
            return name.endsWith(".bz2");
        }
    });

    List<String> directories = new ArrayList<String>();
    final List<File> trainingFiles = new ArrayList<>();

    for (String fileName : dataFileNames) {
        directories.add(expandFile(fileName));
    }
    // collect every name, plus mark to delete on exit
    for (String inputDirectory : directories) {
        URL url = this.getClass().getResource(inputDirectory);
        File[] dataFiles = new File(url.toURI()).listFiles();
        for (File f : dataFiles) {
            handleFiles(f, trainingFiles);
        }
    }
    long startTime = System.currentTimeMillis();
    final int[] counter = { 0 };
    final int[] marker = { 0 };
    // now let's walk through a training cycle
    for (final File file : trainingFiles) {
        service.submit(new Runnable() {
            @Override
            public void run() {
                if ((++marker[0]) % 100 == 0) {
                    System.out.println("Progress training: " + marker[0] + " of " + trainingFiles.size());
                }
                if (counter[0] > 2) {
                    try {
                        trainWith(classifier, file);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                counter[0] = (counter[0] + 1) % 10;
            }
        });
    }
    service.shutdown();
    service.awaitTermination(2, TimeUnit.HOURS);
    service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    long endTime = System.currentTimeMillis();
    System.out.printf("Training took %d ms%n", (endTime - startTime));
    startTime = System.currentTimeMillis();
    marker[0] = 0;
    // now test against the training data
    for (final File file : trainingFiles) {
        service.submit(new Runnable() {
            public void run() {
                if ((++marker[0]) % 100 == 0) {
                    System.out.println("Progress evaluating: " + marker[0] + " of " + trainingFiles.size());
                }
                if (counter[0] < 3) {
                    try {
                        classify(classifier, file);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                counter[0] = (counter[0] + 1) % 10;
            }
        });
    }
    service.shutdown();
    service.awaitTermination(2, TimeUnit.HOURS);
    endTime = System.currentTimeMillis();
    System.out.printf("Training accuracy: %d tests, %f%% accuracy%n", tests, (hits * 100.0) / tests);
    System.out.printf("Training took %d ms%n", (endTime - startTime));
}

From source file:com.example.app.model.DemoUserProfileDAO.java

/**
 * Convert a URL to a URI returning the default value on error.
 *
 * @param url the URL.//w ww .  j a  va  2 s . c  om
 * @param defaultValue the default value.
 * @return the URI.
 */
@Contract("_,null->null;_,!null->!null")
public URI toURI(URL url, URI defaultValue) {
    if (url == null)
        return defaultValue;
    try {
        return url.toURI();
    } catch (URISyntaxException e) {
        _logger.warn("Unable to convert URL to URI: " + url, e);
    }
    return defaultValue;
}

From source file:ca.nrc.cadc.search.PackageServlet.java

/**
 * Handle a GET request with the given Registry client to perform the lookup.
 *
 * @param request        The HTTP Request.
 * @param response       The HTTP Response.
 * @param registryClient The RegistryClient to do lookups.
 * @throws IOException        Any request access problems.
 *///from ww w  .ja v  a2  s .c om
void get(final HttpServletRequest request, final HttpServletResponse response,
        final RegistryClient registryClient) throws IOException {

    // TODO: prior to version 2.5.0, this servlet supported multiple IDs.
    // TODO: Consider how this might be supported in future.
    final String[] idValues = request.getParameterValues("ID");
    if (idValues.length > 1) {
        throw new UnsupportedOperationException("Multiple IDs in package lookup.");
    } else {
        final String IDValue = idValues[0];
        if (IDValue.length() > 0) {
            try {
                final PublisherID publisherID = new PublisherID(URI.create(IDValue));

                final URL serviceURL = registryClient.getServiceURL(publisherID.getResourceID(),
                        Standards.PKG_10, AuthMethod.COOKIE);

                final URIBuilder builder = new URIBuilder(serviceURL.toURI());
                builder.addParameter("ID", IDValue);

                response.sendRedirect(builder.build().toURL().toExternalForm());
            } catch (URISyntaxException e) {
                throw new IOException(String.format("Service URL from %s is invalid.", IDValue), e);
            }
        } else {
            throw new UnsupportedOperationException("Invalid ID in package lookup.");
        }
    }
}

From source file:gov.fda.open.demo.service.FDADataProxyServiceImplTest.java

/**
 * Sets the up.//from   w w w  . j ava 2 s .  c  om
 *
 * @throws ApplicationException
 *             the exception
 * @throws URISyntaxException 
 * @throws IOException 
 */
@Before
public void setUp() throws ApplicationException, IOException, URISyntaxException {
    ReflectionTestUtils.setField(fdaDataProxyService, URI_KEY, URI_VALUE);
    ReflectionTestUtils.setField(fdaDataProxyService, APP_KEY, APP_VALUE);
    ReflectionTestUtils.setField(fdaDataProxyService, LIMIT_KEY, LIMIT_VALUE);

    // Setup
    URL fileURL = getClass().getClassLoader().getResource(RESOURCE);

    jsonString = FileUtils.readFileToString(new File(fileURL.toURI()));
}