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:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedGETUriFromPath() throws IOException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*from   ww w.  jav  a  2s .c  om*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "GET", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try (InputStream is = connection.getInputStream()) {
        connection.setReadTimeout(3000);
        connection.connect();

        if (connection.getResponseCode() != 200) {
            Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset()));
        }

        String actual = IOUtils.toString(is, Charset.defaultCharset());

        Assert.assertEquals(actual, TEST_DATA);
    } finally {
        connection.disconnect();
    }
}

From source file:com.nesscomputing.migratory.information.DefaultMigrationInformationStrategy.java

public MigrationInformation getInformation(final URI location) {
    if (location == null) {
        return null;
    }// ww  w . j  av  a 2 s.c  om
    // Must be loaded from an URL, e.g. jar:file:... ends up on schema specific part and path is null.
    try {
        final String path = location.toURL().getPath();
        final String fileName = path.substring(path.lastIndexOf('/') + 1);
        final String[] pieces = StringUtils.split(fileName, '.');
        if (pieces.length < 3 || pieces.length > 4) {
            throw new MigratoryException(Reason.INTERNAL, "'%s' is not a valid migration name!", fileName);
        }

        final String[] versionPieces = StringUtils.split(pieces[1], '-');

        int startVersion = -1;
        int endVersion = -1;
        switch (versionPieces.length) {
        case 1:
            endVersion = Integer.parseInt(versionPieces[0], 10);
            if (endVersion < 1) {
                throw new MigratoryException(Reason.INTERNAL, "'%s' has an end version of 0!", fileName);
            }

            startVersion = endVersion - 1;
            break;

        case 2:
            startVersion = Integer.parseInt(versionPieces[0], 10);
            endVersion = Integer.parseInt(versionPieces[1], 10);

            if (endVersion < 1) {
                throw new MigratoryException(Reason.INTERNAL, "'%s' has an end version of 0!", fileName);
            }

            if (startVersion == endVersion) {
                throw new MigratoryException(Reason.INTERNAL, "'%s' has the same start and end version!",
                        fileName);
            }
            break;
        default:
            throw new MigratoryException(Reason.INTERNAL, "Can not interpret '%s'!", fileName);
        }

        final boolean needsRoot = (pieces.length == 4 && "root".equals(pieces[2].toLowerCase(Locale.ENGLISH)));

        boolean template = false;

        if ("st".equals(pieces[pieces.length - 1])) {
            template = true;
        } else if (!"sql".equals(pieces[pieces.length - 1])) {
            throw new MigratoryException(Reason.INTERNAL, "'%s' has a bad suffix (not .st or .sql)!", fileName);
        }

        return new MigrationInformation(pieces[0], startVersion, endVersion, needsRoot, template);
    } catch (MalformedURLException mue) {
        throw new MigratoryException(Reason.INTERNAL, mue);
    }
}

From source file:org.kalypso.simulation.core.util.AbstractSimulationDataProvider.java

@Override
public Object getInputForID(final String id) throws SimulationException {
    final String path = m_idhash.get(id);
    if (path == null)
        throw new NoSuchElementException(
                Messages.getString("org.kalypso.simulation.core.util.AbstractSimulationDataProvider.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 {// ww w . j  av  a 2 s  .c o  m
            final URI baseURL = getBaseURL().toURI();
            final URI 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.util.AbstractSimulationDataProvider.1"), e); //$NON-NLS-1$
        } catch (final URISyntaxException e) {
            throw new SimulationException(
                    Messages.getString("org.kalypso.simulation.core.util.AbstractSimulationDataProvider.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.util.AbstractSimulationDataProvider.3", path, type), e); //$NON-NLS-1$
            }
        }
    }

    throw new SimulationException(
            Messages.getString("org.kalypso.simulation.core.util.AbstractSimulationDataProvider.4") + type, //$NON-NLS-1$
            null);
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedHEADUriFromPath() throws IOException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*from w w  w.j a  v  a2s. c  o m*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "HEAD", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("HEAD");
        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();

        if (connection.getResponseCode() != 200) {
            Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset()));
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(TEST_DATA.length(), connection.getContentLength());
    } finally {
        connection.disconnect();
    }
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedPUTUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*ww w .  ja v a 2 s.com*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "PUT", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    connection.setReadTimeout(3000);
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    connection.setChunkedStreamingMode(10);
    connection.connect();

    try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), UTF_8)) {
        out.write(TEST_DATA);
    } finally {
        connection.disconnect();
    }

    // Wait for file to become available
    for (int i = 0; i < 10; i++) {
        Thread.sleep(500);

        if (mantaClient.existsAndIsAccessible(path)) {
            break;
        }
    }

    String actual = mantaClient.getAsString(path);
    Assert.assertEquals(actual, TEST_DATA);
}

From source file:gmusic.api.api.comm.ApacheConnector.java

private HttpRequestBase adjustAddress(URI address, final HttpRequestBase request)
        throws MalformedURLException, URISyntaxException {
    if (address.toString().startsWith(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES)) {
        address = new URI(
                address.toURL() + String.format(COOKIE_FORMAT, getCookieValue("xt")) + "&format=jsarray");
    }//from   w ww  .j a  va 2  s  .  co m

    request.setURI(address);

    if (authorizationToken != null) {
        request.addHeader(GOOGLE_LOGIN_AUTH_KEY, String.format(GOOGLE_LOGIN_AUTH_VALUE, authorizationToken));
    }
    // if((address.toString().startsWith("https://android.clients.google.com/music/mplay"))
    // && deviceId != null)
    // {
    // request.addHeader("X-Device-ID", deviceId);
    // }

    return request;
}

From source file:org.kie.workbench.common.screens.datasource.management.backend.core.dbcp.DBCPDataSourceProvider.java

/**
 * facilitates tests programming./*from  w  ww  . j a  v  a2  s  .c o m*/
 */
protected URLConnectionFactory buildConnectionFactory(URI uri, String driverClass, String connectionURL,
        Properties connectionProperties) throws Exception {
    return new URLConnectionFactory(uri.toURL(), driverClass, connectionURL, connectionProperties);
}

From source file:org.mule.module.launcher.log4j2.LoggerContextConfigurer.java

private boolean isUrlInsideDirectory(URI uri, File directory) {
    if (uri == null) {
        return false;
    }/*from w  w  w .j ava  2  s . co m*/

    URL url;
    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
        throw new MuleRuntimeException(MessageFactory.createStaticMessage("Could not locate file " + uri), e);
    }

    if (directory != null && FileUtils.isFile(url)) {
        File urlFile = new File(url.getFile());
        return directory.equals(urlFile.getParentFile());
    }

    return false;
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedOPTIONSUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*from  w w  w  . ja  v  a  2 s.  com*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "OPTIONS", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("OPTIONS");
        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();

        if (connection.getResponseCode() != 200) {
            String errorText = IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset());

            if (config.getMantaUser().contains("/")) {
                String msg = String.format("This fails due to an outstanding bug: MANTA-2839.\n%s", errorText);
                throw new SkipException(msg);
            }

            Assert.fail(errorText);
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(headers.get("Server").get(0), "Manta");
    } finally {
        connection.disconnect();
    }
}

From source file:org.kalypso.kalypsomodel1d2d.sim.ExecuteTelemacKalypsoSimulation.java

private Map<String, Object> createInputs(final String pStrExe, final URI pTelemacModelPath) {
    final Map<String, Object> inputs = new HashMap<>();
    try {//from  ww w  .  j  a va 2s .  c o m
        inputs.put(PreTelemacKalypso.CALC_CORE_EXE, pStrExe);
        inputs.put(PreTelemacKalypso.OUTPUT_PATH_Telemac, pTelemacModelPath.toURL().toExternalForm());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return inputs;
}