Example usage for java.net URI getFragment

List of usage examples for java.net URI getFragment

Introduction

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

Prototype

public String getFragment() 

Source Link

Document

Returns the decoded fragment component of this URI.

Usage

From source file:org.esigate.util.UriUtils.java

/**
 * Interpret the url relatively to the request url (may be relative). Due to a bug in {@link URI} class when using a
 * relUri containing only a query string, we cannot use directly the method provided by {@link URI} class.
 * //ww  w  . j  a v a 2 s .  c o  m
 * @param relUri
 *            the relative URI
 * @param base
 *            the reference {@link URI}
 * @return the resolved {@link URI}
 */
public static URI resolve(String relUri, URI base) {
    URI uri = createURI(relUri);
    if (uri.getScheme() == null && uri.getUserInfo() == null && uri.getHost() == null && uri.getPort() == -1
            && StringUtils.isEmpty(uri.getPath()) && uri.getQuery() != null) {
        try {
            return new URI(base.getScheme(), base.getUserInfo(), base.getHost(), base.getPort(), base.getPath(),
                    uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            throw new InvalidUriException(e);
        }
    } else {
        return base.resolve(uri);
    }
}

From source file:org.soyatec.windowsazure.authenticate.HttpRequestAccessor.java

/**
 * Given the service endpoint in case of path-style URIs, path contains
 * container name and remaining part if they are present, this method
 * constructs the Full Uri.//from  w  ww  . j  av a2 s  . c  o  m
 * 
 * @param endPoint
 * @param path
 * @return Full URI
 */
private static URI constructUriFromUriAndString(URI endPoint, String path) {
    // This is where we encode the url path to be valid
    String encodedPath = Utilities.encode(path);
    if (!Utilities.isNullOrEmpty(encodedPath) && encodedPath.charAt(0) != ConstChars.Slash.charAt(0)) {
        encodedPath = ConstChars.Slash + encodedPath;
    }
    try {
        // @Note : rename blob with blank spaces in name
        return new URI(endPoint.getScheme(), null, endPoint.getHost(), endPoint.getPort(),
                encodedPath.replaceAll("%20", " "), endPoint.getQuery(), endPoint.getFragment());
        // return new URI(endPoint.getScheme(), endPoint.getHost(),
        // encodedPath, endPoint.getFragment());
    } catch (URISyntaxException e) {
        Logger.error("Can not new URI", e);
        return null;
    }
}

From source file:org.apache.ignite.internal.processors.hadoop.igfs.HadoopIgfsEndpoint.java

/**
 * Normalize IGFS URI.//from ww w  . j  a va2 s. com
 *
 * @param uri URI.
 * @return Normalized URI.
 * @throws IOException If failed.
 */
public static URI normalize(URI uri) throws IOException {
    try {
        if (!F.eq(IgniteFileSystem.IGFS_SCHEME, uri.getScheme()))
            throw new IOException("Failed to normalize UIR because it has non IGFS scheme: " + uri);

        HadoopIgfsEndpoint endpoint = new HadoopIgfsEndpoint(uri.getAuthority());

        StringBuilder sb = new StringBuilder();

        if (endpoint.igfs() != null)
            sb.append(endpoint.igfs());

        return new URI(uri.getScheme(), sb.length() != 0 ? sb.toString() : null, endpoint.host(),
                endpoint.port(), uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException | IgniteCheckedException e) {
        throw new IOException("Failed to normalize URI: " + uri, e);
    }
}

From source file:org.apache.hadoop.security.ProviderUtils.java

/**
 * Convert a nested URI to decode the underlying path. The translation takes
 * the authority and parses it into the underlying scheme and authority.
 * For example, "myscheme://hdfs@nn/my/path" is converted to
 * "hdfs://nn/my/path".// w  w  w.  j ava2s .c o m
 * @param nestedUri the URI from the nested URI
 * @return the unnested path
 */
public static Path unnestUri(URI nestedUri) {
    StringBuilder result = new StringBuilder();
    String authority = nestedUri.getAuthority();
    if (authority != null) {
        String[] parts = nestedUri.getAuthority().split("@", 2);
        result.append(parts[0]);
        result.append("://");
        if (parts.length == 2) {
            result.append(parts[1]);
        }
    }
    result.append(nestedUri.getPath());
    if (nestedUri.getQuery() != null) {
        result.append("?");
        result.append(nestedUri.getQuery());
    }
    if (nestedUri.getFragment() != null) {
        result.append("#");
        result.append(nestedUri.getFragment());
    }
    return new Path(result.toString());
}

From source file:org.apache.hadoop.mapreduce.JobSubmitter.java

@SuppressWarnings("deprecation")
private static void addMRFrameworkToDistributedCache(Configuration conf) throws IOException {
    String framework = conf.get(MRJobConfig.MAPREDUCE_APPLICATION_FRAMEWORK_PATH, "");
    if (!framework.isEmpty()) {
        URI uri;
        try {//  w w w  .  jav a2  s  . c  om
            uri = new URI(framework);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Unable to parse '" + framework
                    + "' as a URI, check the setting for " + MRJobConfig.MAPREDUCE_APPLICATION_FRAMEWORK_PATH,
                    e);
        }

        String linkedName = uri.getFragment();

        // resolve any symlinks in the URI path so using a "current" symlink
        // to point to a specific version shows the specific version
        // in the distributed cache configuration
        FileSystem fs = FileSystem.get(uri, conf);
        Path frameworkPath = fs.makeQualified(new Path(uri.getScheme(), uri.getAuthority(), uri.getPath()));
        FileContext fc = FileContext.getFileContext(frameworkPath.toUri(), conf);
        frameworkPath = fc.resolvePath(frameworkPath);
        uri = frameworkPath.toUri();
        try {
            uri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, linkedName);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }

        DistributedCache.addCacheArchive(uri, conf);
    }
}

From source file:org.apache.hadoop.mapreduce.v2.util.MRApps.java

/**
 * Set up the DistributedCache related configs to make
 * {@link DistributedCache#getLocalCacheFiles(Configuration)}
 * and/*from w w w  . j ava 2 s  .c  o  m*/
 * {@link DistributedCache#getLocalCacheArchives(Configuration)}
 * working.
 * @param conf
 * @throws java.io.IOException
 */
@SuppressWarnings("deprecation")
public static void setupDistributedCacheLocal(Configuration conf) throws IOException {

    String localWorkDir = System.getenv("PWD");
    //        ^ ^ all symlinks are created in the current work-dir

    // Update the configuration object with localized archives.
    URI[] cacheArchives = DistributedCache.getCacheArchives(conf);
    if (cacheArchives != null) {
        List<String> localArchives = new ArrayList<String>();
        for (int i = 0; i < cacheArchives.length; ++i) {
            URI u = cacheArchives[i];
            Path p = new Path(u);
            Path name = new Path((null == u.getFragment()) ? p.getName() : u.getFragment());
            String linkName = name.toUri().getPath();
            localArchives.add(new Path(localWorkDir, linkName).toUri().getPath());
        }
        if (!localArchives.isEmpty()) {
            conf.set(MRJobConfig.CACHE_LOCALARCHIVES,
                    StringUtils.arrayToString(localArchives.toArray(new String[localArchives.size()])));
        }
    }

    // Update the configuration object with localized files.
    URI[] cacheFiles = DistributedCache.getCacheFiles(conf);
    if (cacheFiles != null) {
        List<String> localFiles = new ArrayList<String>();
        for (int i = 0; i < cacheFiles.length; ++i) {
            URI u = cacheFiles[i];
            Path p = new Path(u);
            Path name = new Path((null == u.getFragment()) ? p.getName() : u.getFragment());
            String linkName = name.toUri().getPath();
            localFiles.add(new Path(localWorkDir, linkName).toUri().getPath());
        }
        if (!localFiles.isEmpty()) {
            conf.set(MRJobConfig.CACHE_LOCALFILES,
                    StringUtils.arrayToString(localFiles.toArray(new String[localFiles.size()])));
        }
    }
}

From source file:org.apache.hadoop.security.ProviderUtils.java

/**
 * Mangle given local java keystore file URI to allow use as a
 * LocalJavaKeyStoreProvider.// w  ww . j av a  2  s  .  co  m
 * @param localFile absolute URI with file scheme and no authority component.
 *                  i.e. return of File.toURI,
 *                  e.g. file:///home/larry/creds.jceks
 * @return URI of the form localjceks://file/home/larry/creds.jceks
 * @throws IllegalArgumentException if localFile isn't not a file uri or if it
 *                                  has an authority component.
 * @throws URISyntaxException if the wrapping process violates RFC 2396
 */
public static URI nestURIForLocalJavaKeyStoreProvider(final URI localFile) throws URISyntaxException {
    if (!("file".equals(localFile.getScheme()))) {
        throw new IllegalArgumentException("passed URI had a scheme other than " + "file.");
    }
    if (localFile.getAuthority() != null) {
        throw new IllegalArgumentException(
                "passed URI must not have an " + "authority component. For non-local keystores, please use "
                        + JavaKeyStoreProvider.class.getName());
    }
    return new URI(LocalJavaKeyStoreProvider.SCHEME_NAME, "//file" + localFile.getSchemeSpecificPart(),
            localFile.getFragment());
}

From source file:org.talend.core.runtime.maven.MavenUrlHelper.java

public static MavenArtifact parseMvnUrl(String mvnUrl, boolean setDefaultValue) {

    if (mvnUrl == null || !mvnUrl.startsWith(MVN_PROTOCOL)) {
        return null;
    }//from   ww  w.j a  va  2  s.co m
    MavenArtifact artifact = new MavenArtifact();
    try {
        String substring = mvnUrl.substring(MVN_PROTOCOL.length());

        // repo
        int repoUrlIndex = substring.lastIndexOf(REPO_SEPERATOR);
        if (repoUrlIndex > 0) { // has repo url
            String repoWithUserPwd = substring.substring(0, repoUrlIndex);
            String repoUrl = repoWithUserPwd;
            try {
                URI repoWithUserPwdURI = new URI(repoWithUserPwd);
                String userPassword = repoWithUserPwdURI.getUserInfo();
                URI repoWithoutUserPwdURI = new URI(repoWithUserPwdURI.getScheme(), null,
                        repoWithUserPwdURI.getHost(), repoWithUserPwdURI.getPort(),
                        repoWithUserPwdURI.getPath(), repoWithUserPwdURI.getQuery(),
                        repoWithUserPwdURI.getFragment());
                repoUrl = repoWithoutUserPwdURI.toString();
                try {
                    repoUrl = URLDecoder.decode(repoUrl, "UTF-8");
                } catch (Exception e) {
                    // nothing to do
                }

                // username and password
                if (StringUtils.isNotEmpty(userPassword)) {
                    int splitIndex = userPassword.indexOf(USER_PASSWORD_SPLITER);
                    if (0 < splitIndex) {
                        artifact.setUsername(userPassword.substring(0, splitIndex));
                        if (splitIndex < userPassword.length() - 1) {
                            String password = userPassword.substring(splitIndex + 1);
                            if (password != null) {
                                String decryptedPassword = decryptPassword(password);
                                if (decryptedPassword != null) {
                                    password = decryptedPassword;
                                }
                            }
                            artifact.setPassword(password);
                        }
                    }
                }
            } catch (Exception e) {
                ExceptionHandler.process(e);
            }

            artifact.setRepositoryUrl(repoUrl);
            substring = substring.substring(repoUrlIndex + 1);
        }
        String[] segments = substring.split(SEPERATOR);
        // only group-id and artifact-id is required
        if (segments.length < 2 || segments[0].trim().length() == 0 || segments[1].trim().length() == 0) {
            return null;
        }
        artifact.setGroupId(segments[0].trim());
        artifact.setArtifactId(segments[1].trim());

        // version
        if (segments.length >= 3 && segments[2].trim().length() > 0) {
            // validate the version
            String verStr = segments[2].trim();
            if (VERSION_LATEST.equals(verStr)) {
                artifact.setVersion(VERSION_LATEST);
            } else if (VERSION_SNAPSHOT.equals(verStr)) {
                artifact.setVersion(VERSION_SNAPSHOT);
            } else if (verStr.length() > 0) {
                // range := ( '[' | '(' ) version ',' version ( ')' | ']' )
                // TODO, maybe need parse the range for version.
                if ((verStr.startsWith("[") || verStr.startsWith("("))
                        && (verStr.endsWith(")") || verStr.endsWith("]"))) {
                    artifact.setVersion(verStr);
                } else {
                    artifact.setVersion(verStr);
                }
            }
        }
        if (segments.length >= 4 && segments[3].trim().length() > 0) { // has packaging
            artifact.setType(segments[3].trim());
        }

        if (segments.length >= 5 && segments[4].trim().length() > 0) {// has classifier
            // classifier is can be null.
            artifact.setClassifier(segments[4].trim());
        }

        /*
         * set default values.
         */
        if (artifact.getVersion() == null && setDefaultValue) {
            // if not set, will be LATEST by default
            artifact.setVersion(VERSION_LATEST);
        }
        if (artifact.getType() == null && setDefaultValue) {
            // if not set, will be jar by default
            artifact.setType(MavenConstants.TYPE_JAR);
        }
    } catch (Exception e) {
        ExceptionHandler.process(new Exception("Problem happened when install this maven URL: " + mvnUrl, e));
        return null;
    }

    return artifact;

}

From source file:org.eclipse.orion.internal.server.servlets.file.ServletFileStoreHandler.java

public static JSONObject toJSON(IFileStore store, IFileInfo info, URI location) {
    JSONObject result = new JSONObject();
    try {//  ww w  . j  a  va  2  s . c o  m
        result.put(ProtocolConstants.KEY_NAME, info.getName());
        result.put(ProtocolConstants.KEY_LOCAL_TIMESTAMP, info.getLastModified());
        result.put(ProtocolConstants.KEY_DIRECTORY, info.isDirectory());
        result.put(ProtocolConstants.KEY_LENGTH, info.getLength());
        if (location != null) {
            result.put(ProtocolConstants.KEY_LOCATION, location);
            if (info.isDirectory())
                try {
                    result.put(ProtocolConstants.KEY_CHILDREN_LOCATION, new URI(location.getScheme(),
                            location.getAuthority(), location.getPath(), "depth=1", location.getFragment())); //$NON-NLS-1$
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
        }
        result.put(ProtocolConstants.KEY_ATTRIBUTES, getAttributes(store, info));
    } catch (JSONException e) {
        //cannot happen because the key is non-null and the values are strings
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.webcurator.ui.tools.controller.BrowseHelper.java

/**
 * Gets the absolute URL based on the URL string and the current resource.
 * This method handles relative URLs.// w  ww.  j  a v a2s . co m
 * 
 * @param currentUrl The URL of the current resource.
 * @param subUrl The URL to be rewritten.
 * @return The absolute URL of the resource.
 */
public static String getAbsURL(String currentUrl, String subUrl) {
    String replacedUrl = subUrl.trim();
    try {
        UURI base = UURIFactory.getInstance(currentUrl);
        UURI absUURI = UURIFactory.getInstance(base, replacedUrl);

        // does subUrl have a fragment (a.k.a a ref or jump tag) ?
        URI uri = null;
        try {
            uri = new URI(replacedUrl);
        } catch (URISyntaxException uriEx) {
            //Tried to parse and failed, attempt to URL encode
            String strUri = URLEncoder.encode(replacedUrl, "UTF-8");
            //put the fragment marker back (if there was one)
            Pattern p = Pattern.compile("%23");
            Matcher m = p.matcher(strUri);
            uri = new URI(m.replaceFirst("#"));
        }

        String fragment = uri.getFragment();
        if (fragment == null) {
            return absUURI.getEscapedURI();
        } else {
            return absUURI.getEscapedURI() + "#" + fragment;
        }
    } catch (Exception ex) {
        log.error("Error parsing URI '" + replacedUrl + "': ", ex);
        return null;
    }
}