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:Main.java

/**
 * Extract the UUID part from a MusicBrainz identifier.
 * //from  w w w .  j  a va 2s. c o  m
 * This function takes a MusicBrainz ID (an absolute URI) as the input
 * and returns the UUID part of the URI, thus turning it into a relative
 * URI. If <code>uriStr</code> is null or a relative URI, then it is
 * returned unchanged.
 * 
 * The <code>resType</code> parameter can be used for error checking.
 * Set it to 'artist', 'release', or 'track' to make sure 
 * <code>uriStr</code> is a syntactically valid MusicBrainz identifier
 * of the given resource type. If it isn't, an 
 * <code>IllegalArgumentException</code> exception is raised. This error
 * checking only works if <code>uriStr</code> is an absolute URI, of course.
 * 
 * Example:
 * >>>  MBUtils.extractUuid('http://musicbrainz.org/artist/c0b2500e-0cef-4130-869d-732b23ed9df5', 'artist')
 * 'c0b2500e-0cef-4130-869d-732b23ed9df5'
 * 
 * @param uriStr A string containing a MusicBrainz ID (an URI), or null
 * @param resType A string containing a resource type
 * @return A String containing a relative URI or null
 * @throws URISyntaxException 
 */
public static String extractUuid(String uriStr, String resType) {
    if (uriStr == null) {
        return null;
    }

    URI uri;
    try {
        uri = new URI(uriStr);
    } catch (URISyntaxException e) {
        return uriStr; // not really a valid URI, probably the UUID
    }
    if (uri.getScheme() == null) {
        return uriStr; // not really a valid URI, probably the UUID
    }

    if (!"http".equals(uri.getScheme()) || !"musicbrainz.org".equals(uri.getHost())) {
        throw new IllegalArgumentException(uri.toString() + " is no MB ID");
    }

    String regex = "^/(label|artist|release-group|release|recording|work|collection)/([^/]*)$";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(uri.getPath());
    if (m.matches()) {
        if (resType == null) {
            return m.group(2);
        } else {
            if (resType.equals(m.group(1))) {
                return m.group(2);
            } else {
                throw new IllegalArgumentException("expected '" + resType + "' Id");
            }
        }
    } else {
        throw new IllegalArgumentException("'" + uriStr + " is no valid MB id");
    }
}

From source file:Main.java

/** Obtiene el flujo de entrada de un fichero (para su lectura) a partir de su URI.
 * @param uri URI del fichero a leer/*w w w .  jav a  2s. c o m*/
 * @return Flujo de entrada hacia el contenido del fichero
 * @throws IOException Cuando no se ha podido abrir el fichero de datos. */
public static InputStream loadFile(final URI uri) throws IOException {

    if (uri == null) {
        throw new IllegalArgumentException("Se ha pedido el contenido de una URI nula"); //$NON-NLS-1$
    }

    if (uri.getScheme().equals("file")) { //$NON-NLS-1$
        // Es un fichero en disco. Las URL de Java no soportan file://, con
        // lo que hay que diferenciarlo a mano

        // Retiramos el "file://" de la uri
        String path = uri.getSchemeSpecificPart();
        if (path.startsWith("//")) { //$NON-NLS-1$
            path = path.substring(2);
        }
        return new FileInputStream(new File(path));
    }

    // Es una URL
    final InputStream tmpStream = new BufferedInputStream(uri.toURL().openStream());

    // Las firmas via URL fallan en la descarga por temas de Sun, asi que
    // descargamos primero
    // y devolvemos un Stream contra un array de bytes
    final byte[] tmpBuffer = getDataFromInputStream(tmpStream);

    return new java.io.ByteArrayInputStream(tmpBuffer);
}

From source file:com.ibm.jaggr.core.impl.deps.DepUtils.java

/**
 * Removes URIs containing duplicate and non-orthogonal paths so that the
 * collection contains only unique and non-overlapping paths.
 *
 * @param uris collection of URIs/*from   w  w w. j  a v  a2  s. com*/
 *
 * @return a new collection with redundant paths removed
 */
static public Collection<URI> removeRedundantPaths(Collection<URI> uris) {
    List<URI> result = new ArrayList<URI>();
    for (URI uri : uris) {
        String path = uri.getPath();
        if (!path.endsWith("/")) { //$NON-NLS-1$
            path += "/"; //$NON-NLS-1$
        }
        boolean addIt = true;
        for (int i = 0; i < result.size(); i++) {
            URI testUri = result.get(i);
            if (!StringUtils.equals(testUri.getScheme(), uri.getScheme())
                    || !StringUtils.equals(testUri.getHost(), uri.getHost())
                    || testUri.getPort() != uri.getPort()) {
                continue;
            }
            String test = testUri.getPath();
            if (!test.endsWith("/")) { //$NON-NLS-1$
                test += "/"; //$NON-NLS-1$
            }
            if (path.equals(test) || path.startsWith(test)) {
                addIt = false;
                break;
            } else if (test.startsWith(path)) {
                result.remove(i);
            }
        }
        if (addIt)
            result.add(uri);
    }
    // Now copy the trimmed list back to the original
    return result;
}

From source file:net.adamcin.recap.replication.RecapReplicationUtil.java

/**
 * Builds a RecapAddress from related properties of the provided AgentConfig
 * @param config//from w  w w. jav  a2s .  com
 * @return
 * @throws com.day.cq.replication.ReplicationException
 */
public static RecapAddress getAgentAddress(AgentConfig config) throws ReplicationException {

    final String uri = config.getTransportURI();

    if (!uri.startsWith(TRANSPORT_URI_SCHEME_PREFIX)) {
        throw new ReplicationException("uri must start with " + TRANSPORT_URI_SCHEME_PREFIX);
    }

    final String user = config.getTransportUser();
    final String pass = config.getTransportPassword();

    try {

        final URI parsed = new URI(uri.substring(TRANSPORT_URI_SCHEME_PREFIX.length()));
        final boolean https = "https".equals(parsed.getScheme());
        final String host = parsed.getHost();
        final int port = parsed.getPort() < 0 ? (https ? 443 : 80) : parsed.getPort();
        final String prefix = StringUtils.isEmpty(parsed.getPath()) ? null : parsed.getPath();

        return new DefaultRecapAddress() {
            @Override
            public boolean isHttps() {
                return https;
            }

            @Override
            public String getHostname() {
                return host;
            }

            @Override
            public Integer getPort() {
                return port;
            }

            @Override
            public String getUsername() {
                return user;
            }

            @Override
            public String getPassword() {
                return pass;
            }

            @Override
            public String getServletPath() {
                return prefix;
            }
        };
    } catch (URISyntaxException e) {
        throw new ReplicationException(e);
    }
}

From source file:com.linkedin.cubert.ScriptExecutor.java

/**
 * Properties are collected in the following order--
 * <p/>//from   ww  w  . j  a  v a  2 s .co  m
 * 1. Azkaban (or other) executor params
 * 2. properties passed through -f argument (for multiple order in CLI order)
 * 3. properties passed as -D arguments directly on CLI
 *
 * @param cmdLine
 * @param executorProps
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
private static Properties getProperties(CommandLine cmdLine, Properties executorProps)
        throws URISyntaxException, IOException {
    Properties props = new Properties();

    // 1. Substitute executor params
    if (executorProps != null) {
        props.putAll(extractCubertParams(executorProps));
    }

    // 2. -f properties
    String[] propFiles = cmdLine.getOptionValues("f");
    if (propFiles != null && propFiles.length > 0) {
        for (String propFile : propFiles) {
            URI uri = new URI(propFile);
            boolean isHDFS = (uri.getScheme() != null) && uri.getScheme().equalsIgnoreCase("hdfs");
            String path = uri.getPath();
            if (isHDFS) {
                props.load(new BufferedReader(
                        new InputStreamReader(FileSystem.get(new JobConf()).open(new Path(path)))));
            } else {
                props.load(new BufferedReader(new FileReader(path)));
            }
        }
    }

    // 3. -D properties
    if (cmdLine.getOptionProperties("D").size() > 0) {
        props.putAll(cmdLine.getOptionProperties("D"));
    }
    return props;
}

From source file:net.sf.jasperreports.eclipse.wizard.project.ProjectUtil.java

/**
 * Checks if a possible project could contain existing resources.
 * //from  w  ww  .  ja  v  a  2  s . c  o m
 * @param prjName
 *          the project name
 * @return
 */
public static boolean hasExistingContent(String prjName) {
    try {
        URI rootLocation = ResourcesPlugin.getWorkspace().getRoot().getLocationURI();
        URI prjLocation = new URI(rootLocation.getScheme(), null,
                Path.fromPortableString(rootLocation.getPath()).append(prjName).toString(), null);
        IFileStore file = EFS.getStore(prjLocation);
        return file.fetchInfo().exists();
    } catch (URISyntaxException e) {
        JasperReportsPlugin.getDefault().logError(e);
    } catch (CoreException e) {
        JasperReportsPlugin.getDefault().logError(e);
    }
    return false;
}

From source file:com.vmware.identity.openidconnect.protocol.URIUtils.java

private static int getPort(URI uri) {
    int port = uri.getPort();
    if (port == -1) {
        if (("https").equalsIgnoreCase(uri.getScheme())) {
            port = 443;/* w  w  w .j  a va2 s .  c  o m*/
        } else if (("http").equalsIgnoreCase(uri.getScheme())) {
            port = 80;
        }
    }
    return port;
}

From source file:net.sf.jasperreports.eclipse.wizard.project.ProjectUtil.java

/**
 * Deletes the content of a possible project. Also the project folder is
 * deleted.//from   w  ww .ja  v a 2 s. c o  m
 * 
 * @param prjName
 *          the project name
 */
public static void deleteProjectFolder(String prjName) {
    try {
        URI rootLocation = ResourcesPlugin.getWorkspace().getRoot().getLocationURI();
        URI prjLocation = new URI(rootLocation.getScheme(), null,
                Path.fromPortableString(rootLocation.getPath()).append(prjName).toString(), null);
        File prjDir = new File(prjLocation);
        if (prjDir.exists()) {
            FileUtils.deleteDirectory(prjDir);
        }
    } catch (URISyntaxException e) {
        JasperReportsPlugin.getDefault().logError(e);
    } catch (IOException e) {
        JasperReportsPlugin.getDefault().logError(e);
    }

}

From source file:com.navnorth.learningregistry.LRClient.java

public static String executeHttpGet(String url) throws Exception {
    BufferedReader in = null;/* ww w. j a v  a 2 s  . c om*/
    try {
        URI uri = new URI(url);
        HttpClient client = getHttpClient(uri.getScheme());
        HttpGet request = new HttpGet(uri);

        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.navnorth.learningregistry.LRClient.java

public static String executeJsonGet(String url) throws Exception {
    BufferedReader in = null;/*from  w w w . ja  va 2  s .c  o m*/
    try {
        URI uri = new URI(url);
        HttpClient client = getHttpClient(uri.getScheme());
        HttpGet request = new HttpGet(uri);

        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}