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.index.IndexDirectory.java

/**
 * Create an index directory using an index remotely stored using the Object
 * Storage API./*from   w  ww .j  a  va  2s .c  o m*/
 * 
 * The URI should be created like that:
 * SWIFT://localhost?tenant=&container=&user=&password=&url=
 * 
 * The parameters must be URL encoded as UTF-8
 * 
 * @param uri
 * @throws IOException
 * @throws URISyntaxException
 * @throws JSONException
 * @throws SearchLibException
 */
protected IndexDirectory(final URI uri)
        throws IOException, URISyntaxException, JSONException, SearchLibException {
    if ("SWIFT".equals(uri.getScheme())) {
        HttpDownloader httpDownloader = new HttpDownloader(null, true, null);
        Map<String, String> parameters = LinkUtils.getUniqueQueryParameters(uri, "UTF-8");
        String tenant = parameters.get("tenant");
        String container = parameters.get("container");
        String user = parameters.get("user");
        String password = parameters.get("password");
        String url = parameters.get("url");
        SwiftToken token = new SwiftToken(httpDownloader, url, user, password, AuthType.KEYSTONE, tenant);
        directory = new ObjectStorageDirectory(httpDownloader, token, container);
        return;
    }
    throw new IOException("Unsupported protocol: " + uri);
}

From source file:gov.nih.nci.caarray.dataStorage.DataStorageFacade.java

private DataStorage dataStorageEngine(URI handle) {
    return this.dataStorageEngines.get(handle.getScheme());
}

From source file:com.github.dozermapper.core.builder.xml.SchemaLSResourceResolver.java

/**
 * Attempt to resolve systemId resource from classpath by checking:
 *
 * 1. Try {@link SchemaLSResourceResolver#getClass()#getClassLoader()}
 * 2. Try {@link BeanContainer#getClassLoader()}
 * 3. Try {@link Activator#getBundle()}/*from w  w  w  .j a v a  2s  .  c  om*/
 *
 * @param systemId systemId used by XSD
 * @return stream to XSD
 * @throws IOException if fails to find XSD
 */
private InputStream resolveFromClassPath(String systemId) throws IOException, URISyntaxException {
    InputStream source;

    String xsdPath;
    URI uri = new URI(systemId);
    if (uri.getScheme().equalsIgnoreCase("file")) {
        xsdPath = uri.toString();
    } else {
        xsdPath = uri.getPath();
        if (xsdPath.charAt(0) == '/') {
            xsdPath = xsdPath.substring(1);
        }
    }

    ClassLoader localClassLoader = getClass().getClassLoader();

    LOG.debug("Trying to locate [{}] via ClassLoader [{}]", xsdPath,
            localClassLoader.getClass().getSimpleName());

    //Attempt to find within this JAR
    URL url = localClassLoader.getResource(xsdPath);
    if (url == null) {
        //Attempt to find via user defined class loader
        DozerClassLoader dozerClassLoader = beanContainer.getClassLoader();

        LOG.debug("Trying to locate [{}] via DozerClassLoader [{}]", xsdPath,
                dozerClassLoader.getClass().getSimpleName());

        url = dozerClassLoader.loadResource(xsdPath);
    }

    if (url == null) {
        //Attempt to find via OSGi
        Bundle bundle = Activator.getBundle();
        if (bundle != null) {
            LOG.debug("Trying to locate [{}] via Bundle [{}]", xsdPath, bundle.getClass().getSimpleName());

            url = bundle.getResource(xsdPath);
        }
    }

    if (url == null) {
        throw new IOException("Could not resolve bean-mapping XML Schema [" + systemId
                + "]: not found in classpath; " + xsdPath);
    }

    try {
        source = url.openStream();
    } catch (IOException ex) {
        throw new IOException("Could not resolve bean-mapping XML Schema [" + systemId
                + "]: not found in classpath; " + xsdPath, ex);
    }

    LOG.debug("Found bean-mapping XML Schema [{}] in classpath @ [{}]", systemId, url.toString());

    return source;
}

From source file:com.whizzosoftware.hobson.wemo.WeMoPlugin.java

protected String minifyURI(URI uri) {
    if ("http".equals(uri.getScheme()) && uri.getPath().endsWith("setup.xml")) {
        if (uri.getPort() == 49153) {
            return uri.getHost();
        } else {//from  w w w . ja v a 2  s. c o m
            return uri.getHost() + ":" + uri.getPort();
        }
    } else {
        return uri.toASCIIString();
    }
}

From source file:com.olacabs.fabric.compute.builder.impl.JarScanner.java

URL[] download(Collection<String> urls) {

    ArrayList<URL> downloadedURLs = urls.stream().map(url -> {
        URI uri = URI.create(url);
        String downloaderImplClassName = properties.getProperty(String.format("fs.%s.impl", uri.getScheme()));
        if (null == downloaderImplClassName) {
            throw new RuntimeException(
                    new UnsupportedSchemeException(uri.getScheme() + " is not supported for downloading jars"));
        }//  ww  w .  j a  v a 2 s .c  om
        try {
            Class clazz = Class.forName(downloaderImplClassName);
            if (JarDownloader.class.isAssignableFrom(clazz)) {
                try {
                    return ((JarDownloader) clazz.newInstance()).download(url).toUri().toURL();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else {
                throw new RuntimeException("Unsupported implementation " + downloaderImplClassName + " of "
                        + JarDownloader.class.getSimpleName());
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }).collect(Collectors.toCollection(ArrayList::new));
    return downloadedURLs.toArray(new URL[downloadedURLs.size()]);
}

From source file:org.springframework.cloud.dataflow.rest.util.HttpClientConfigurer.java

protected HttpClientConfigurer(URI targetHost) {
    httpClientBuilder = HttpClientBuilder.create();
    this.targetHost = new HttpHost(targetHost.getHost(), targetHost.getPort(), targetHost.getScheme());
}

From source file:com.shazam.fork.reporter.gradle.JenkinsDownloader.java

@Nonnull
private URL getArtifactUrl(Build build, Artifact artifact) {
    try {/*from   w ww.j ava  2  s  . c  o m*/
        URI uri = new URI(build.getUrl());
        String artifactPath = uri.getPath() + "artifact/" + artifact.getRelativePath();
        URI artifactUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
                artifactPath, "", "");
        return artifactUri.toURL();
    } catch (URISyntaxException | MalformedURLException e) {
        throw new GradleException("Error when trying to construct artifact URL for: " + build.getUrl(), e);
    }
}

From source file:edu.unc.lib.dl.ingest.sip.METSPackageFileValidator.java

/**
 * Checks that there are as many files packaged as there are non-staged file references. Computes and compares the
 * MD5 digest of packaged files that have a checksum in METS. Checks access to all files referenced in staging
 * locations.//  w w w. j  a v  a2s  .c o m
 *
 * @param mets
 * @param metsPack
 * @param aip
 * @throws IngestException
 */
@SuppressWarnings("unchecked")
public void validateFiles(Document mets, METSPackageSIP metsPack) throws IngestException {
    StringBuffer errors = new StringBuffer();
    List<File> manifestFiles = new ArrayList<File>();
    List<String> missingFiles = new ArrayList<String>();
    List<String> badChecksumFiles = new ArrayList<String>();

    // find missing or corrupt files listed in manifest
    try {
        for (Element fileEl : (List<Element>) allFilesXpath.selectNodes(mets)) {
            String href = null;
            try {
                href = fileEl.getChild("FLocat", JDOMNamespaceUtil.METS_NS).getAttributeValue("href",
                        JDOMNamespaceUtil.XLINK_NS);
                URI uri = new URI(href);
                if (uri.getScheme() != null && !uri.getScheme().contains("file")) {
                    continue;
                }
            } catch (URISyntaxException e) {
                errors.append("Cannot parse file location: " + e.getLocalizedMessage() + " (" + href + ")");
                missingFiles.add(href);
                continue;
            } catch (NullPointerException e) {
                errors.append("A file location is missing for file ID: " + fileEl.getAttributeValue("ID"));
                continue;
            }
            File file = null;
            // locate the file and check that it exists
            try {
                log.debug("Looking in SIP");
                file = metsPack.getFileForLocator(href);
                file.equals(file);
                manifestFiles.add(file);
                log.debug("FILE IS IN METSPackage: " + file.getPath());
                if (file == null || !file.exists()) {
                    missingFiles.add(href);
                    continue;
                }
            } catch (IOException e) {
                log.debug(e);
                missingFiles.add(href);
                errors.append(e.getMessage());
            }

            String checksum = fileEl.getAttributeValue("CHECKSUM");
            if (checksum != null) {
                log.debug("found a checksum in METS");
                Checksum checker = new Checksum();
                try {
                    String sum = checker.getChecksum(file);
                    if (!sum.equals(checksum.toLowerCase())) {
                        log.debug("Checksum failed for file: " + href + " (METS says " + checksum
                                + ", but we got " + sum + ")");
                        badChecksumFiles.add(href);
                    }
                    log.debug("METS manifest checksum was verified for file: " + href);
                } catch (IOException e) {
                    throw new IngestException("Checksum failed to find file: " + href);
                }
            }
        }
    } catch (JDOMException e1) {
        throw new Error("Unexpected JDOM Exception", e1);
    }

    // TODO: account for local (not inline xmlData) MODS files
    // see if there are extra files in the SIP
    List<String> extraFiles = new ArrayList<String>();

    if (metsPack.getSIPDataDir() != null) {
        int zipPathLength = 0;
        try {
            zipPathLength = metsPack.getSIPDataDir().getCanonicalPath().length();

            for (File received : metsPack.getDataFiles()) {
                if (!manifestFiles.contains(received) && received.compareTo(metsPack.getMetsFile()) != 0) {
                    extraFiles.add("file://" + received.getCanonicalPath().substring(zipPathLength));
                }
            }
        } catch (IOException e) {
            throw new Error("Unexpected IO Exception trying to get path of a known file.", e);
        }
    }
    if (missingFiles.size() > 0 || badChecksumFiles.size() > 0 || extraFiles.size() > 0) {
        // We have an error here...
        String msg = "The files submitted do not match those listed in the METS manifest.";
        FilesDoNotMatchManifestException e = new FilesDoNotMatchManifestException(msg);
        e.setBadChecksumFiles(badChecksumFiles);
        e.setExtraFiles(extraFiles);
        e.setMissingFiles(missingFiles);
        throw e;
    }
}

From source file:com.beyondj.gateway.handlers.tcp.TcpGatewayHandler.java

@Override
public void handle(final NetSocket socket) {
    NetClient client = null;//from w ww .  j av a  2  s.  com
    List<String> paths = serviceMap.getPaths();
    TcpClientRequestFacade requestFacade = new TcpClientRequestFacade(socket);
    String path = pathLoadBalancer.choose(paths, requestFacade);
    if (path != null) {
        List<ServiceDetails> services = serviceMap.getServices(path);
        if (!services.isEmpty()) {
            ServiceDetails serviceDetails = serviceLoadBalancer.choose(services, requestFacade);
            if (serviceDetails != null) {
                List<String> urlStrings = serviceDetails.getServices();
                for (String urlString : urlStrings) {
                    if (StringUtils.isNotEmpty(urlString)) {
                        // lets create a client for this request...
                        try {
                            URI uri = new URI(urlString);
                            //URL url = new URL(urlString);
                            String urlProtocol = uri.getScheme();
                            if (Objects.equal(protocol, urlProtocol)) {
                                Handler<AsyncResult<NetSocket>> handler = new Handler<AsyncResult<NetSocket>>() {
                                    public void handle(final AsyncResult<NetSocket> asyncSocket) {
                                        NetSocket clientSocket = asyncSocket.result();
                                        Pump.createPump(clientSocket, socket).start();
                                        Pump.createPump(socket, clientSocket).start();
                                    }
                                };
                                client = createClient(socket, uri, handler);
                                break;
                            }
                        } catch (MalformedURLException e) {
                            LOG.warn("Failed to parse URL: " + urlString + ". " + e, e);
                        } catch (URISyntaxException e) {
                            LOG.warn("Failed to parse URI: " + urlString + ". " + e, e);
                        }
                    }
                }
            }
        }
    }
    if (client == null) {
        // fail to route
        LOG.info("No service available for protocol " + protocol + " for paths " + paths);
        socket.close();
    }
}

From source file:gov.nih.nci.caarray.dataStorage.DataStorageFacade.java

/**
 * Synchronize state of storate engines with state of caArray by removing from storage engines any data blocks that
 * are no longer referenced from any caArray entities. Only data blocks of a minimum threshold age are removed; this
 * is to handle data blocks which are referenced from entities created in an ongoing transaction that has not yet
 * been committed.//from   ww  w  .j  a va2s .  co  m
 * 
 * @param references the complete set of data handles that are currently held by entities in caArray. Any data
 *            blocks whose handles are not in this set and that are older than <i>minAge</i> will be removed.
 * @param minAge the minimum age for a data block to be eligible for removal, if it is unreferenced, in
 *            milliseconds. This should be at least as long as the maximum transaction time.
 */
public void removeUnreferencedData(Set<URI> references, long minAge) {
    final Date creationThreshold = new Date(System.currentTimeMillis() - minAge);
    for (final Map.Entry<String, DataStorage> dsEntry : this.dataStorageEngines.entrySet()) {
        final Set<URI> dsReferences = Sets.newHashSet(Iterables.filter(references, new Predicate<URI>() {
            @Override
            public boolean apply(URI uri) {
                return dsEntry.getKey().equals(uri.getScheme());
            }
        }));
        removeUnreferencedData(dsReferences, creationThreshold, dsEntry.getValue());
    }
}