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:de.betterform.xml.dom.DOMUtil.java

public static Node getFragment(URI uri, InputStream xmlStream) throws XFormsException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from w  ww. j  a  v  a 2  s  . c o  m
    factory.setValidating(false);
    Document document = null;
    try {
        document = parseInputStream(xmlStream, true, false);
    } catch (ParserConfigurationException e) {
        throw new XFormsException(e);
    } catch (SAXException e) {
        throw new XFormsException(e);
    } catch (IOException e) {
        throw new XFormsException(e);
    }

    if (uri.getFragment() != null) {
        String fragment = uri.getFragment();
        if (fragment.indexOf("?") != -1) {
            fragment = fragment.substring(0, fragment.indexOf("?"));
        }
        return getById(document, fragment);
    }

    return document;
}

From source file:podd.resources.util.RemoteFileHelper.java

/**
 * Retrieve the path to the file on the datastore, given the encoded url and PID.
 * Check condition for whether the url is for a referenced file
 * @param url//www  . jav  a2s.  c om
 * @param pid
 * @return
 */
private String getPathToFile(URL url, String pid) {

    try {
        URI uri = url.toURI();
        String fragment = uri.getFragment();
        LOGGER.info("fragment=" + fragment);
        // If not a reference then translate to data store filename?
        if (fragment != null && fragment.equals(URL_FRAGMENT_REFERENCE)) {
            // Reference to existing file            
            return getDatastoreReferenceFilename(url);
        } else {
            // Reference to an uploaded file
            return getDatastoreFilename(url, pid);
        }

    } catch (URISyntaxException e) {
        LOGGER.error("Found exception", e);
        e.printStackTrace();
    }

    return null;
}

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

/**
 * Upload and configure files, libjars, jobjars, and archives pertaining to
 * the passed job.//w w w  .  ja  va  2s  . co  m
 * 
 * @param job the job containing the files to be uploaded
 * @param submitJobDir the submission directory of the job
 * @throws IOException
 */
public void uploadFiles(Job job, Path submitJobDir) throws IOException {
    Configuration conf = job.getConfiguration();
    short replication = (short) conf.getInt(Job.SUBMIT_REPLICATION, Job.DEFAULT_SUBMIT_REPLICATION);

    if (!(conf.getBoolean(Job.USED_GENERIC_PARSER, false))) {
        LOG.warn("Hadoop command-line option parsing not performed. "
                + "Implement the Tool interface and execute your application "
                + "with ToolRunner to remedy this.");
    }

    // get all the command line arguments passed in by the user conf
    String files = conf.get("tmpfiles");
    String libjars = conf.get("tmpjars");
    String archives = conf.get("tmparchives");
    String jobJar = job.getJar();

    //
    // Figure out what fs the JobTracker is using. Copy the
    // job to it, under a temporary name. This allows DFS to work,
    // and under the local fs also provides UNIX-like object loading
    // semantics. (that is, if the job file is deleted right after
    // submission, we can still run the submission to completion)
    //

    // Create a number of filenames in the JobTracker's fs namespace
    LOG.debug("default FileSystem: " + jtFs.getUri());
    if (jtFs.exists(submitJobDir)) {
        throw new IOException("Not submitting job. Job directory " + submitJobDir
                + " already exists!! This is unexpected.Please check what's there in" + " that directory");
    }
    submitJobDir = jtFs.makeQualified(submitJobDir);
    submitJobDir = new Path(submitJobDir.toUri().getPath());
    FsPermission mapredSysPerms = new FsPermission(JobSubmissionFiles.JOB_DIR_PERMISSION);
    FileSystem.mkdirs(jtFs, submitJobDir, mapredSysPerms);
    Path filesDir = JobSubmissionFiles.getJobDistCacheFiles(submitJobDir);
    Path archivesDir = JobSubmissionFiles.getJobDistCacheArchives(submitJobDir);
    Path libjarsDir = JobSubmissionFiles.getJobDistCacheLibjars(submitJobDir);
    // add all the command line files/ jars and archive
    // first copy them to jobtrackers filesystem

    if (files != null) {
        FileSystem.mkdirs(jtFs, filesDir, mapredSysPerms);
        String[] fileArr = files.split(",");
        for (String tmpFile : fileArr) {
            URI tmpURI = null;
            try {
                tmpURI = new URI(tmpFile);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException(e);
            }
            Path tmp = new Path(tmpURI);
            Path newPath = copyRemoteFiles(filesDir, tmp, conf, replication);
            try {
                URI pathURI = getPathURI(newPath, tmpURI.getFragment());
                DistributedCache.addCacheFile(pathURI, conf);
            } catch (URISyntaxException ue) {
                // should not throw a uri exception
                throw new IOException("Failed to create uri for " + tmpFile, ue);
            }
        }
    }

    if (libjars != null) {
        FileSystem.mkdirs(jtFs, libjarsDir, mapredSysPerms);
        String[] libjarsArr = libjars.split(",");
        for (String tmpjars : libjarsArr) {
            Path tmp = new Path(tmpjars);
            Path newPath = copyRemoteFiles(libjarsDir, tmp, conf, replication);
            DistributedCache.addFileToClassPath(new Path(newPath.toUri().getPath()), conf, jtFs);
        }
    }

    if (archives != null) {
        FileSystem.mkdirs(jtFs, archivesDir, mapredSysPerms);
        String[] archivesArr = archives.split(",");
        for (String tmpArchives : archivesArr) {
            URI tmpURI;
            try {
                tmpURI = new URI(tmpArchives);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException(e);
            }
            Path tmp = new Path(tmpURI);
            Path newPath = copyRemoteFiles(archivesDir, tmp, conf, replication);
            try {
                URI pathURI = getPathURI(newPath, tmpURI.getFragment());
                DistributedCache.addCacheArchive(pathURI, conf);
            } catch (URISyntaxException ue) {
                // should not throw an uri excpetion
                throw new IOException("Failed to create uri for " + tmpArchives, ue);
            }
        }
    }

    if (jobJar != null) { // copy jar to JobTracker's fs
        // use jar name if job is not named.
        if ("".equals(job.getJobName())) {
            job.setJobName(new Path(jobJar).getName());
        }
        Path jobJarPath = new Path(jobJar);
        URI jobJarURI = jobJarPath.toUri();
        // If the job jar is already in a global fs,
        // we don't need to copy it from local fs
        if (jobJarURI.getScheme() == null || jobJarURI.getScheme().equals("file")) {
            copyJar(jobJarPath, JobSubmissionFiles.getJobJar(submitJobDir), replication);
            job.setJar(JobSubmissionFiles.getJobJar(submitJobDir).toString());
        }
    } else {
        LOG.warn("No job jar file set.  User classes may not be found. " + "See Job or Job#setJar(String).");
    }

    addLog4jToDistributedCache(job, submitJobDir);

    // set the timestamps of the archives and files
    // set the public/private visibility of the archives and files
    ClientDistributedCacheManager.determineTimestampsAndCacheVisibilities(conf);
    // get DelegationToken for cached file
    ClientDistributedCacheManager.getDelegationTokens(conf, job.getCredentials());
}

From source file:org.ldp4j.tutorial.client.CachedRepresentationManager.java

private File createFile(String resource) {
    URI uri = URI.create(resource);
    StringBuilder builder = new StringBuilder();
    builder.append(uri.getScheme()).append("_");
    String userInfo = uri.getUserInfo();
    if (userInfo != null) {
        builder.append(userInfo).append("@");
    }/*from  w w w  . j a v a2s .c o  m*/
    builder.append(uri.getHost());
    if (uri.getPort() >= 0) {
        builder.append("_").append(uri.getPort());
    }
    if (uri.getPath() != null) {
        builder.append(uri.getRawPath().replace("/", "_"));
    }
    if (uri.getQuery() != null) {
        builder.append("?").append(uri.getRawQuery());
    }
    if (uri.getFragment() != null) {
        builder.append("#").append(uri.getRawFragment());
    }
    builder.append(".dat");
    File file = new File(this.cacheDirectory, builder.toString());
    return file;
}

From source file:hsyndicate.fs.SyndicateFSPath.java

public SyndicateFSPath(SyndicateFSPath parent, SyndicateFSPath child) {
    if (parent == null)
        throw new IllegalArgumentException("Can not resolve a path from a null parent");
    if (child == null)
        throw new IllegalArgumentException("Can not resolve a path from a null child");

    URI parentUri = parent.uri;
    if (parentUri == null)
        throw new IllegalArgumentException("Can not resolve a path from a null parent URI");

    String parentPath = parentUri.getPath();

    if (!(parentPath.equals("/") || parentPath.equals(""))) {
        // parent path is not empty -- need to parse
        try {//from w  w  w.ja v a2 s .  com
            parentUri = new URI(parentUri.getScheme(), parentUri.getAuthority(), parentUri.getPath() + "/",
                    null, parentUri.getFragment());
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
    }

    URI resolved = parentUri.resolve(child.uri);

    // assign resolved uri to member field
    this.uri = createPathUri(resolved.getScheme(), resolved.getAuthority(), normalizePath(resolved.getPath()));
    //LOG.info("path - " + uri.toString());
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

/**
 * Sets up a connection, retrying on connect failure.
 *//*from   w  w w  .  ja v  a  2 s .c  om*/
private HttpURLConnection connect(final URI uri, final String method, final byte[] entity,
        final Map<String, List<String>> headers)
        throws URISyntaxException, IOException, TimeoutException, InterruptedException, HeliosException {
    final long deadline = currentTimeMillis() + RETRY_TIMEOUT_MILLIS;
    final int offset = ThreadLocalRandom.current().nextInt();

    while (currentTimeMillis() < deadline) {
        final List<URI> endpoints = endpointSupplier.get();
        if (endpoints.isEmpty()) {
            throw new RuntimeException("failed to resolve master");
        }
        log.debug("endpoint uris are {}", endpoints);

        // Resolve hostname into IPs so client will round-robin and retry for multiple A records.
        // Keep a mapping of IPs to hostnames for TLS verification.
        final List<URI> ipEndpoints = Lists.newArrayList();
        final Map<URI, URI> ipToHostnameUris = Maps.newHashMap();

        for (final URI hnUri : endpoints) {
            try {
                final InetAddress[] ips = InetAddress.getAllByName(hnUri.getHost());
                for (final InetAddress ip : ips) {
                    final URI ipUri = new URI(hnUri.getScheme(), hnUri.getUserInfo(), ip.getHostAddress(),
                            hnUri.getPort(), hnUri.getPath(), hnUri.getQuery(), hnUri.getFragment());
                    ipEndpoints.add(ipUri);
                    ipToHostnameUris.put(ipUri, hnUri);
                }
            } catch (UnknownHostException e) {
                log.warn("Unable to resolve hostname {} into IP address: {}", hnUri.getHost(), e);
            }
        }

        for (int i = 0; i < ipEndpoints.size() && currentTimeMillis() < deadline; i++) {
            final URI ipEndpoint = ipEndpoints.get(positive(offset + i) % ipEndpoints.size());
            final String fullpath = ipEndpoint.getPath() + uri.getPath();

            final String scheme = ipEndpoint.getScheme();
            final String host = ipEndpoint.getHost();
            final int port = ipEndpoint.getPort();
            if (!VALID_PROTOCOLS.contains(scheme) || host == null || port == -1) {
                throw new HeliosException(String.format(
                        "Master endpoints must be of the form \"%s://heliosmaster.domain.net:<port>\"",
                        VALID_PROTOCOLS_STR));
            }

            final URI realUri = new URI(scheme, host + ":" + port, fullpath, uri.getQuery(), null);

            AgentProxy agentProxy = null;
            Deque<Identity> identities = Queues.newArrayDeque();
            try {
                if (scheme.equals("https")) {
                    agentProxy = AgentProxies.newInstance();
                    for (final Identity identity : agentProxy.list()) {
                        if (identity.getPublicKey().getAlgorithm().equals("RSA")) {
                            // only RSA keys will work with our TLS implementation
                            identities.offerLast(identity);
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("Couldn't get identities from ssh-agent", e);
            }

            try {
                do {
                    final Identity identity = identities.poll();

                    try {
                        log.debug("connecting to {}", realUri);

                        final HttpURLConnection connection = connect0(realUri, method, entity, headers,
                                ipToHostnameUris.get(ipEndpoint).getHost(), agentProxy, identity);

                        final int responseCode = connection.getResponseCode();
                        if (((responseCode == HTTP_FORBIDDEN) || (responseCode == HTTP_UNAUTHORIZED))
                                && !identities.isEmpty()) {
                            // there was some sort of security error. if we have any more SSH identities to try,
                            // retry with the next available identity
                            log.debug("retrying with next SSH identity since {} failed", identity.getComment());
                            continue;
                        }

                        return connection;
                    } catch (ConnectException | SocketTimeoutException | UnknownHostException e) {
                        // UnknownHostException happens if we can't resolve hostname into IP address.
                        // UnknownHostException's getMessage method returns just the hostname which is a
                        // useless message, so log the exception class name to provide more info.
                        log.debug(e.toString());
                        // Connecting failed, sleep a bit to avoid hammering and then try another endpoint
                        Thread.sleep(200);
                    }
                } while (false);
            } finally {
                if (agentProxy != null) {
                    agentProxy.close();
                }
            }
        }
        log.warn("Failed to connect, retrying in 5 seconds.");
        Thread.sleep(5000);
    }
    throw new TimeoutException("Timed out connecting to master");
}

From source file:org.opencms.staticexport.CmsDefaultLinkSubstitutionHandler.java

/**
 * @see org.opencms.staticexport.I_CmsLinkSubstitutionHandler#getRootPath(org.opencms.file.CmsObject, java.lang.String, java.lang.String)
 *///from  w  w w  . j  ava2s  .  c o m
public String getRootPath(CmsObject cms, String targetUri, String basePath) {

    if (cms == null) {
        // required by unit test cases
        return targetUri;
    }

    URI uri;
    String path;
    String fragment;
    String query;
    String suffix;

    // malformed uri
    try {
        uri = new URI(targetUri);
        path = uri.getPath();

        fragment = uri.getFragment();
        if (fragment != null) {
            fragment = "#" + fragment;
        } else {
            fragment = "";
        }

        query = uri.getQuery();
        if (query != null) {
            query = "?" + query;
        } else {
            query = "";
        }
    } catch (Exception e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_MALFORMED_URI_1, targetUri), e);
        }
        return null;
    }

    // concatenate query and fragment 
    suffix = query.concat(fragment);

    // opaque URI
    if (uri.isOpaque()) {
        return null;
    }

    // absolute URI (i.e. URI has a scheme component like http:// ...)
    if (uri.isAbsolute()) {
        CmsSiteMatcher matcher = new CmsSiteMatcher(targetUri);
        if (OpenCms.getSiteManager().isMatching(matcher)) {
            if (path.startsWith(OpenCms.getSystemInfo().getOpenCmsContext())) {
                path = path.substring(OpenCms.getSystemInfo().getOpenCmsContext().length());
            }
            boolean isWorkplaceServer = OpenCms.getSiteManager().isWorkplaceRequest(matcher);
            if (isWorkplaceServer) {
                String pathForCurrentSite = cms.getRequestContext().addSiteRoot(path);
                String pathForMatchedSite = cms.getRequestContext()
                        .addSiteRoot(OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(), path);
                String originalSiteRoot = cms.getRequestContext().getSiteRoot();
                String selectedPath = pathForCurrentSite;
                try {
                    cms.getRequestContext().setSiteRoot("");
                    // the path for the current site normally is preferred, but if it doesn't exist and the path for the matched site
                    // does exist, then use the path for the matched site 
                    if (!cms.existsResource(pathForCurrentSite, CmsResourceFilter.ALL)
                            && cms.existsResource(pathForMatchedSite, CmsResourceFilter.ALL)) {
                        selectedPath = pathForMatchedSite;
                    }
                } finally {
                    cms.getRequestContext().setSiteRoot(originalSiteRoot);
                }
                return selectedPath + suffix;
            } else {
                // add the site root of the matching site
                return cms.getRequestContext()
                        .addSiteRoot(OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(), path + suffix);
            }
        } else {
            return null;
        }
    }

    // relative URI (i.e. no scheme component, but filename can still start with "/") 
    String context = OpenCms.getSystemInfo().getOpenCmsContext();
    if ((context != null) && path.startsWith(context)) {
        // URI is starting with opencms context
        String siteRoot = null;
        if (basePath != null) {
            siteRoot = OpenCms.getSiteManager().getSiteRoot(basePath);
        }

        // cut context from path
        path = path.substring(context.length());

        if (siteRoot != null) {
            // special case: relative path contains a site root, i.e. we are in the root site                
            if (!path.startsWith(siteRoot)) {
                // path does not already start with the site root, we have to add this path as site prefix
                return cms.getRequestContext().addSiteRoot(siteRoot, path + suffix);
            } else {
                // since path already contains the site root, we just leave it unchanged
                return path + suffix;
            }
        } else {
            // site root is added with standard mechanism
            return cms.getRequestContext().addSiteRoot(path + suffix);
        }
    }

    // URI with relative path is relative to the given relativePath if available and in a site, 
    // otherwise invalid
    if (CmsStringUtil.isNotEmpty(path) && (path.charAt(0) != '/')) {
        if (basePath != null) {
            String absolutePath;
            int pos = path.indexOf("../../galleries/pics/");
            if (pos >= 0) {
                // HACK: mixed up editor path to system gallery image folder
                return CmsWorkplace.VFS_PATH_SYSTEM + path.substring(pos + 6) + suffix;
            }
            absolutePath = CmsLinkManager.getAbsoluteUri(path, cms.getRequestContext().addSiteRoot(basePath));
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
            // HACK: some editor components (e.g. HtmlArea) mix up the editor URL with the current request URL 
            absolutePath = CmsLinkManager.getAbsoluteUri(path,
                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS);
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
            // HACK: same as above, but XmlContent editor has one path element more
            absolutePath = CmsLinkManager.getAbsoluteUri(path,
                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS + "xmlcontent/");
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
        }

        return null;
    }

    // relative URI (= VFS path relative to currently selected site root)
    if (CmsStringUtil.isNotEmpty(path)) {
        return cms.getRequestContext().addSiteRoot(path) + suffix;
    }

    // URI without path (typically local link)
    return suffix;
}

From source file:org.codehaus.stomp.tcp.TcpTransportServer.java

public void start() throws IOException {
    URI bind = bindLocation;

    String host = bind.getHost();
    host = (host == null || host.length() == 0) ? "localhost" : host;
    InetAddress addr = InetAddress.getByName(host);

    try {//from   w ww .j a va 2 s.  co m
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog, addr);
        this.serverSocket.setSoTimeout(2000);
    } catch (IOException e) {
        throw new IOException("Failed to bind to server socket: " + bind + " due to: " + e, e);
    }
    try {
        connectURI = new URI(bind.getScheme(), bind.getUserInfo(), bind.getHost(), serverSocket.getLocalPort(),
                bind.getPath(), bind.getQuery(), bind.getFragment());
    } catch (URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }

    log.info("Listening for connections at: " + connectURI);
    runner = new Thread(this, "StompConnect Server Thread: " + toString());
    runner.setDaemon(daemon);
    runner.start();
}

From source file:de.thingweb.thing.Thing.java

public String resolveActionUri(String name, int index) {

    URI uri = getUri(index);

    Action a = getAction(name);//from   w w  w. j  a va2s  .  c o m

    if (a != null) {
        try {
            String path = uri.getPath();
            if (path.endsWith("/")) {
                path = path + a.getHrefs().get(index);
            } else {
                path = path + "/" + a.getHrefs().get(index);
            }
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path,
                    uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            throw new RuntimeException("TD with malformed hrefs");
        }
    } else {
        throw new RuntimeException("No such Property");
    }

    return uri.toString();
}