Example usage for java.net URI getScheme

List of usage examples for java.net URI getScheme

Introduction

In this page you can find the example usage for java.net URI getScheme.

Prototype

public String getScheme() 

Source Link

Document

Returns the scheme component of this URI.

Usage

From source file:com.jaeksoft.searchlib.util.LinkUtils.java

public final static URL getLink(URL currentURL, String href, UrlFilterItem[] urlFilterList,
        boolean removeFragment) {

    if (href == null)
        return null;
    href = href.trim();/*from   w  w  w  .j a  v  a  2s  .  c  o  m*/
    if (href.length() == 0)
        return null;

    String fragment = null;
    try {
        URI u = URIUtils.resolve(currentURL.toURI(), href);
        href = u.toString();
        href = UrlFilterList.doReplace(u.getHost(), href, urlFilterList);
        URI uri = URI.create(href);
        uri = uri.normalize();

        String p = uri.getPath();
        if (p != null)
            if (p.contains("/./") || p.contains("/../"))
                return null;

        if (!removeFragment)
            fragment = uri.getRawFragment();

        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                uri.getQuery(), fragment).normalize().toURL();
    } catch (MalformedURLException e) {
        Logging.info(e.getMessage());
        return null;
    } catch (URISyntaxException e) {
        Logging.info(e.getMessage());
        return null;
    } catch (IllegalArgumentException e) {
        Logging.info(e.getMessage());
        return null;
    }
}

From source file:org.apache.camel.component.http4.HttpComponent.java

private static int getPort(URI uri) {
    int port = uri.getPort();
    if (port < 0) {
        if ("http4".equals(uri.getScheme()) || "http".equals(uri.getScheme())) {
            port = 80;//  w  ww  . j  ava2s.c  o  m
        } else if ("https4".equals(uri.getScheme()) || "https".equals(uri.getScheme())) {
            port = 443;
        } else {
            throw new IllegalArgumentException("Unknown scheme, cannot determine port number for uri: " + uri);
        }
    }
    return port;
}

From source file:com.sun.jersey.client.apache4.ApacheHttpClient4.java

/**
 * Create a default Apache HTTP client handler.
 *
 * @param cc ClientConfig instance. Might be null.
 *
 * @return a default Apache HTTP client handler.
 *///from   w ww .jav  a2 s .  c o m
private static ApacheHttpClient4Handler createDefaultClientHandler(final ClientConfig cc) {

    Object connectionManager = null;
    Object httpParams = null;

    if (cc != null) {
        connectionManager = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER);
        if (connectionManager != null) {
            if (!(connectionManager instanceof ClientConnectionManager)) {
                Logger.getLogger(ApacheHttpClient4.class.getName()).log(Level.WARNING,
                        "Ignoring value of property " + ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER
                                + " (" + connectionManager.getClass().getName()
                                + ") - not instance of org.apache.http.conn.ClientConnectionManager.");
                connectionManager = null;
            }
        }

        httpParams = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS);
        if (httpParams != null) {
            if (!(httpParams instanceof HttpParams)) {
                Logger.getLogger(ApacheHttpClient4.class.getName()).log(Level.WARNING,
                        "Ignoring value of property " + ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS + " ("
                                + httpParams.getClass().getName()
                                + ") - not instance of org.apache.http.params.HttpParams.");
                httpParams = null;
            }
        }
    }

    final DefaultHttpClient client = new DefaultHttpClient((ClientConnectionManager) connectionManager,
            (HttpParams) httpParams);

    CookieStore cookieStore = null;
    boolean preemptiveBasicAuth = false;

    if (cc != null) {
        for (Map.Entry<String, Object> entry : cc.getProperties().entrySet())
            client.getParams().setParameter(entry.getKey(), entry.getValue());

        if (cc.getPropertyAsFeature(ApacheHttpClient4Config.PROPERTY_DISABLE_COOKIES))
            client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);

        Object credentialsProvider = cc.getProperty(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER);
        if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
            client.setCredentialsProvider((CredentialsProvider) credentialsProvider);
        }

        final Object proxyUri = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_PROXY_URI);
        if (proxyUri != null) {
            final URI u = getProxyUri(proxyUri);
            final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());

            if (cc.getProperties().containsKey(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME)
                    && cc.getProperties().containsKey(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD)) {

                client.getCredentialsProvider().setCredentials(new AuthScope(u.getHost(), u.getPort()),
                        new UsernamePasswordCredentials(
                                cc.getProperty(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME).toString(),
                                cc.getProperty(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD).toString()));

            }
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }

        preemptiveBasicAuth = cc
                .getPropertyAsFeature(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION);
    }

    if (client.getParams().getParameter(ClientPNames.COOKIE_POLICY) == null || !client.getParams()
            .getParameter(ClientPNames.COOKIE_POLICY).equals(CookiePolicy.IGNORE_COOKIES)) {
        cookieStore = new BasicCookieStore();
        client.setCookieStore(cookieStore);
    }

    return new ApacheHttpClient4Handler(client, cookieStore, preemptiveBasicAuth);
}

From source file:com.aliyun.oss.integrationtests.TestUtils.java

public static String composeLocation(String endpoint, String bucketName, String key) {
    try {// w  w  w.j av  a 2s.  c  o  m
        URI baseUri = URI.create(endpoint);
        URI resultUri = new URI(baseUri.getScheme(), null, bucketName + "." + baseUri.getHost(),
                baseUri.getPort(), String.format("/%s", HttpUtil.urlEncode(key, DEFAULT_CHARSET_NAME)), null,
                null);
        return URLDecoder.decode(resultUri.toString(), DEFAULT_CHARSET_NAME);
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}

From source file:org.eel.kitchen.jsonschema.ref.JsonRef.java

/**
 * Build a JSON Reference from a URI/*from   ww  w  .  j a v  a2 s . c  o  m*/
 *
 * @param uri the provided URI
 * @return the JSON Reference
 * @throws NullPointerException the provided URI is null
 */
public static JsonRef fromURI(final URI uri) {
    Preconditions.checkNotNull(uri, "URI must not be null");

    final URI normalized = uri.normalize();

    if (HASHONLY_URI.equals(normalized) || EMPTY_URI.equals(normalized))
        return EmptyJsonRef.getInstance();

    return "jar".equals(normalized.getScheme()) ? new JarJsonRef(normalized)
            : new HierarchicalJsonRef(normalized);
}

From source file:io.flutter.server.vmService.VmOpenSourceLocationListener.java

/**
 * Connect to the VM observatory service via the specified URI
 *
 * @return an API object for interacting with the VM service (not {@code null}).
 *///w w w . ja  va 2s.com
public static VmOpenSourceLocationListener connect(@NotNull final String url) throws IOException {

    // Validate URL
    final URI uri;
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL: " + url, e);
    }
    final String wsScheme = uri.getScheme();
    if (!"ws".equals(wsScheme) && !"wss".equals(wsScheme)) {
        throw new IOException("Unsupported URL scheme: " + wsScheme);
    }

    // Create web socket and observatory
    final WebSocket webSocket;
    try {
        webSocket = new WebSocket(uri);
    } catch (WebSocketException e) {
        throw new IOException("Failed to create websocket: " + url, e);
    }
    final VmOpenSourceLocationListener listener = new VmOpenSourceLocationListener(new MessageSender() {
        @Override
        public void sendMessage(JsonObject message) {
            try {
                webSocket.send(message.toString());
            } catch (WebSocketException e) {
                LOG.warn(e);
            }
        }

        @Override
        public void close() {
            try {
                webSocket.close();
            } catch (WebSocketException e) {
                LOG.warn(e);
            }
        }
    });

    webSocket.setEventHandler(new WebSocketEventHandler() {
        final JsonParser parser = new JsonParser();

        @Override
        public void onClose() {
            // ignore
        }

        @Override
        public void onMessage(WebSocketMessage message) {
            listener.onMessage(parser.parse(message.getText()).getAsJsonObject());
        }

        @Override
        public void onOpen() {
            listener.onOpen();
        }

        @Override
        public void onPing() {
            // ignore
        }

        @Override
        public void onPong() {
            // ignore
        }
    });

    // Establish WebSocket Connection
    try {
        webSocket.connect();
    } catch (WebSocketException e) {
        throw new IOException("Failed to connect: " + url, e);
    }
    return listener;
}

From source file:com.spectralogic.ds3client.NetworkClientImpl.java

private static HttpHost buildHost(final ConnectionDetails connectionDetails) throws MalformedURLException {
    final URI proxyUri = connectionDetails.getProxy();
    if (proxyUri != null) {
        return new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme());
    } else {//from  w w  w. j a  v  a 2 s. co m
        final URL url = NetUtils.buildUrl(connectionDetails, "/");
        return new HttpHost(url.getHost(), NetUtils.getPort(url), url.getProtocol());
    }
}

From source file:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java

private static boolean hasSameRepresentation(final URI a, final URI b) {
    try {//www .ja v  a 2  s .c om
        return new URI(a.getScheme(), a.getAuthority(), a.getPath(), null, null)
                .equals(new URI(b.getScheme(), b.getAuthority(), b.getPath(), null, null));
    } catch (final URISyntaxException e) {
        throw new RuntimeException("Shoud never happen", e);
    }
}

From source file:com.massabot.codesender.utils.FirmwareUtils.java

public synchronized static void initialize() {
    System.out.println("Initializing firmware... ...");
    File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME);

    // Create directory if it's missing.
    if (!firmwareConfig.exists()) {
        firmwareConfig.mkdirs();//from w ww  .j a  v  a 2  s .co  m
    }

    FileSystem fileSystem = null;

    // Copy firmware config files.
    try {
        final String dir = "/resources/firmware_config/";

        URI location = FirmwareUtils.class.getResource(dir).toURI();

        Path myPath;
        if (location.getScheme().equals("jar")) {
            try {
                // In case the filesystem already exists.
                fileSystem = FileSystems.getFileSystem(location);
            } catch (FileSystemNotFoundException e) {
                // Otherwise create the new filesystem.
                fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap());
            }

            myPath = fileSystem.getPath(dir);
        } else {
            myPath = Paths.get(location);
        }

        Stream<Path> files = Files.walk(myPath, 1);
        for (Path path : (Iterable<Path>) () -> files.iterator()) {
            System.out.println(path);
            final String name = path.getFileName().toString();
            File fwConfig = new File(firmwareConfig, name);
            if (name.endsWith(".json")) {
                boolean copyFile = !fwConfig.exists();
                ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path));

                // If the file is outdated... ask the user (once).
                if (fwConfig.exists()) {
                    ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig));
                    boolean outOfDate = current.getVersion() < jarSetting.getVersion();
                    if (outOfDate && !userNotified && !overwriteOldFiles) {
                        int result = NarrowOptionPane.showNarrowConfirmDialog(200,
                                Localization.getString("settings.file.outOfDate.message"),
                                Localization.getString("settings.file.outOfDate.title"),
                                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        overwriteOldFiles = result == JOptionPane.OK_OPTION;
                        userNotified = true;
                    }

                    if (overwriteOldFiles) {
                        copyFile = true;
                        jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom;
                    }
                }

                // Copy file from jar to firmware_config directory.
                if (copyFile) {
                    try {
                        save(fwConfig, jarSetting);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (Exception ex) {
        String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"),
                ex.getLocalizedMessage());
        GUIHelpers.displayErrorDialog(errorMessage);
        logger.log(Level.SEVERE, errorMessage, ex);
    } finally {
        if (fileSystem != null) {
            try {
                fileSystem.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Problem closing filesystem.", ex);
            }
        }
    }

    configFiles.clear();
    for (File f : firmwareConfig.listFiles()) {
        try {
            ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class);
            // ConfigLoader config = new ConfigLoader(f);
            configFiles.put(config.getName(), new ConfigTuple(config, f));
        } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) {
            GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath());
        }
    }
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UmlsCommon.LoadRRFToDB.java

private static boolean verifyTableExists(URI tableURI) {
    // if its a file, check if it exists
    if (tableURI.getScheme().equals("file")) {
        return new File(tableURI).exists();
    }// w  w  w.j a  v a2 s.  c  om
    // otherwise, just try to connect..
    // TODO: find a better way to check this instead of catching an
    // exception.
    else {
        try {
            tableURI.toURL().openConnection();
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}