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:org.openremote.android.console.model.PollingHelper.java

/**
 * Request current status and start polling.
 *//*w ww .j ava2 s  . c  om*/
public void requestCurrentStatusAndStartPolling(Context context) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 50 * 1000);

    //make polling socket timout bigger than Controller (50s)
    HttpConnectionParams.setSoTimeout(params, 55 * 1000);

    client = new DefaultHttpClient(params);
    if (isPolling) {
        return;
    }

    try {
        URL uri = new URL(serverUrl);
        uri.toURI();
        if ("https".equals(uri.getProtocol())) {
            Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                    uri.getPort());
            client.getConnectionManager().getSchemeRegistry().register(sch);
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_CATEGORY, "Create URL fail:" + serverUrl);
        return;
    } catch (URISyntaxException e) {
        Log.e(LOG_CATEGORY, "Could not convert " + serverUrl + " to a compliant URI");
        return;
    }
    isPolling = true;
    handleRequest(serverUrl + "/rest/status/" + pollingStatusIds);
    while (isPolling) {
        doPolling();
    }
}

From source file:com.adaptris.core.fs.FsHelperTest.java

@Test
public void testFullURIWithColons() throws Exception {
    URL url = FsHelper.createUrlFromString("file:///c:/home/fred/d:/home/fred");
    assertEquals("fred", new File(url.toURI()).getName());
}

From source file:gobblin.aws.AWSJobConfigurationManagerTest.java

@BeforeClass
public void setUp() throws Exception {
    this.eventBus.register(this);

    // Prepare the test url to download the job conf from
    final URL url = GobblinAWSClusterLauncherTest.class.getClassLoader().getResource(JOB_FIRST_ZIP);
    final String jobConfZipUri = getJobConfigZipUri(new File(url.toURI()));

    // Prepare the test dir to download the job conf to
    if (this.jobConfigFileDir.exists()) {
        FileUtils.deleteDirectory(this.jobConfigFileDir);
    }//  w  w w. j  a  v  a2  s  . com
    Assert.assertTrue(this.jobConfigFileDir.mkdirs(), "Failed to create " + this.jobConfigFileDir);

    final Config config = ConfigFactory.empty()
            .withValue(GobblinClusterConfigurationKeys.JOB_CONF_PATH_KEY,
                    ConfigValueFactory.fromAnyRef(this.jobConfigFileDir.toString()))
            .withValue(GobblinAWSConfigurationKeys.JOB_CONF_S3_URI_KEY,
                    ConfigValueFactory.fromAnyRef(jobConfZipUri))
            .withValue(GobblinAWSConfigurationKeys.JOB_CONF_REFRESH_INTERVAL,
                    ConfigValueFactory.fromAnyRef("10s"));
    this.jobConfigurationManager = new AWSJobConfigurationManager(this.eventBus, config);
    this.jobConfigurationManager.startAsync().awaitRunning();
}

From source file:cz.incad.kramerius.audio.servlets.ServletAudioHttpRequestForwarder.java

public Void forwardGetRequest(URL url) throws IOException, URISyntaxException {
    LOGGER.log(Level.INFO, "forwarding {0}", url);
    HttpGet proxyToRepositoryRequest = new HttpGet(url.toURI());
    forwardSelectedRequestHeaders(clientToProxyRequest, proxyToRepositoryRequest);
    //printRepositoryRequestHeaders(repositoryRequest);
    HttpResponse repositoryToProxyResponse = httpClient.execute(proxyToRepositoryRequest);
    //printRepositoryResponseHeaders(repositoryResponse);
    forwardSelectedResponseHeaders(repositoryToProxyResponse, proxyToClientResponse);
    forwardResponseCode(repositoryToProxyResponse, proxyToClientResponse);
    forwardData(repositoryToProxyResponse.getEntity().getContent(), proxyToClientResponse.getOutputStream());
    return null;/*from  www . j a  v  a  2s .co m*/
}

From source file:io.cloudslang.lang.compiler.CompileDecisionTest.java

@Test
public void testDecision1PreCompile() throws Exception {
    URL decision = getClass().getResource("/decision/decision_1.sl");

    Executable executable = compiler.preCompile(fromFile(decision.toURI()));

    Assert.assertNotNull(executable);/*w w  w .j a va 2  s. co  m*/
    Assert.assertTrue(executable instanceof Decision);
    Decision expectedDecision = new Decision(emptyActionData, emptyActionData, "user.decisions", "decision_1",
            inputs1, outputs1, results1, Collections.<String>emptySet(), emptySetSystemProperties);
    Assert.assertEquals(expectedDecision, executable);
}

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

@Test
public void testURINotFound() throws IOException, URISyntaxException {
    URL remoteURL = new URL("http://127.0.0.1/cr.html");

    final URI externalURI = remoteURL.toURI();
    final String uuid = UUID.randomUUID().toString();

    exception.expect(IOException.class);
    final String path = hashedDirectoryService.storeFile(uuid, TENANT_ID, externalURI);
    LOGGER.info(path);//w ww. java 2s .c  o  m
}

From source file:com.othermedia.asyncimage.AsyncImageDownloader.java

@Override
public void run() {
    if (parentImageCache == null)
        return;/*from w  ww  . j a  v  a  2  s.c o m*/

    // The downloader runs until the queue is empty or the cache is disconnected
    while (parentImageCache != null && parentImageCache.downloadQueue.size() > 0) {

        AsyncImageTask currentTask = parentImageCache.downloadQueue.remove(0); // Pop first task in (FIFO)

        try {

            // -- Check and retrieve file cache
            String hashedPath = null;
            try {
                if (parentImageCache.isFileCacheEnabled()) {
                    hashedPath = parentImageCache.hashString(currentTask.getImageURL()) + ".png";
                    if (parentImageCache.hasInFileCache(hashedPath)) {
                        parentImageCache.fileCacheRetrieve(hashedPath, currentTask.getImageURL());
                    }
                }
            } catch (Exception e) {
                Log.e(DebugTag, "Exception on retrieving from file cache: " + e + ": " + e.getMessage());
            }

            // - Check cache, if the image got retrieved by an earlier request or from file cache
            if (parentImageCache.hasCached(currentTask.getImageURL())) {
                parentImageCache.updateTargetFromHandler(currentTask.getTargetImageView(),
                        currentTask.getImageURL());
            } else {
                // ...Else download image:

                int tries = 3; // Allowed download Tries

                while (tries > 0) {
                    tries--; // In case of a short network drop or other random connection error.

                    try {

                        // -- Create HTTP Request
                        URL requestUrl = new URL(currentTask.getImageURL());
                        HttpGet httpRequest = new HttpGet(requestUrl.toURI());
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpResponse httpResponse = (HttpResponse) httpClient.execute(httpRequest);

                        // -- Process Bitmap Download
                        BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(httpResponse.getEntity());
                        InputStream inputStream = bufferedEntity.getContent();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        BitmapDrawable drawable = new BitmapDrawable(bitmap);
                        parentImageCache.cacheImage(currentTask.getImageURL(), drawable); // - cache downloaded bitmap, then update ImageView:
                        parentImageCache.updateTargetFromHandler(currentTask.getTargetImageView(),
                                currentTask.getImageURL());

                        tries = 0; // Release tries.
                        inputStream.close();

                        // -- Cache Drawable as file, if enabled
                        if (parentImageCache.isFileCacheEnabled()) {
                            try {
                                if (hashedPath != null) {
                                    File outputFile = new File(parentImageCache.getCacheDir(), hashedPath);
                                    FileOutputStream outputStream = new FileOutputStream(outputFile);
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
                                }
                            } catch (Exception e) {
                                Log.e(DebugTag,
                                        "Exception on file caching process: " + e + ": " + e.getMessage());
                            }
                        } // -- End file caching.

                    } catch (Exception e) {
                        Log.e(DebugTag, "Exception on download process: " + e + ": " + e.getMessage());
                        try {
                            Thread.sleep(250);
                        } catch (InterruptedException ei) {
                        }
                    }
                }
            }

        } catch (Exception e) {
            Log.e(DebugTag, "Exception on current AsyncImageTask: " + e + ": " + e.getMessage());
        }

    }

    parentImageCache.downloaderFinished(); // Release thread reference from cache

}

From source file:io.cloudslang.lang.compiler.modeller.transformers.PythonActionTransformerTest.java

private Map<String, Serializable> loadPythonActionData(String filePath) throws URISyntaxException {
    URL resource = getClass().getResource(filePath);
    ParsedSlang file = yamlParser.parse(SlangSource.fromFile(new File(resource.toURI())));
    Map op = file.getOperation();
    @SuppressWarnings("unchecked")
    Map<String, Serializable> returnMap = (Map) op.get(SlangTextualKeys.PYTHON_ACTION_KEY);
    return returnMap;
}

From source file:it.pronetics.madstore.server.jaxrs.atom.pub.impl.DefaultCollectionResourceHandler.java

private void configureFeed(Feed feed, PagingList<Entry> entries, Collection collectionModel) throws Exception {
    URL selfUrl = resourceResolver.resolveResourceUriFor(ResourceName.COLLECTION,
            uriInfo.getBaseUri().toString(), collectionKey);
    URL nextUrl = UriBuilder.fromUri(selfUrl.toURI())
            .queryParam(HttpConstants.PAGE_PARAMETER, new Integer(pageNumberOfEntries + 1))
            .queryParam(HttpConstants.MAX_PARAMETER, maxNumberOfEntries).build().toURL();
    URL prevUrl = UriBuilder.fromUri(selfUrl.toURI())
            .queryParam(HttpConstants.PAGE_PARAMETER, new Integer(pageNumberOfEntries - 1))
            .queryParam(HttpConstants.MAX_PARAMETER, maxNumberOfEntries).build().toURL();
    String id = resourceResolver.resolveResourceIdFor(uriInfo.getBaseUri().toString(), ResourceName.COLLECTION,
            collectionKey);/*from  w w  w. j  av a  2s  .  c o  m*/

    feed.setId(id);
    feed.addLink(selfUrl.toString(), "self");
    feed.setTitle(collectionModel.getTitle());
    feed.addAuthor(Abdera.getInstance().getFactory().newAuthor().getText());

    for (Entry entry : entries) {
        feed.addEntry(entry);
    }

    if (entries.size() > 0) {
        int currentLastResult = ((pageNumberOfEntries - 1) * maxNumberOfEntries) + entries.size();
        if (currentLastResult < entries.getTotal()) {
            feed.addLink(nextUrl.toString(), "next");
        }
        if (pageNumberOfEntries > 1) {
            feed.addLink(prevUrl.toString(), "previous");
        }
    }
}