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:jasdl.bridge.JASDLOntologyManager.java

/**
 * Gets the alias corresponding to a URI. URI corresponds to a known entity, its alias is returned.
 * Otherwise, the label is taken from (scheme concat scheme specific part) and the functor from the fragment (minus the #).
 * Additionally, applied default mapping strategies to URI fragment to prevent invalid functors being generated.
 * /*from w w w.ja va  2  s  .  co  m*/
 * Note: Ontology referenced by URI must be a known ontology!
 * @param uri
 * @return
 */
public Alias toAlias(URI uri, List<MappingStrategy> strategies) throws JASDLUnknownMappingException {
    try {
        OWLEntity entity = toEntity(uri);
        return getAliasManager().getLeft(entity);
    } catch (JASDLUnknownMappingException e) {
        // unknown uri, create a new alias
        OWLOntology ontology = getLogicalURIManager()
                .getLeft(URI.create(uri.getScheme() + ":" + uri.getSchemeSpecificPart()));
        Atom label = getLabelManager().getLeft(ontology);
        String _functor = uri.getFragment();

        // apply mapping strategies to fragment of URI to generate a valid functor
        for (MappingStrategy strategy : strategies) {
            _functor = strategy.apply(_functor);
        }
        return AliasFactory.INSTANCE.create(new Atom(_functor), label);

    }
}

From source file:com.cisco.oss.foundation.http.AbstractHttpClient.java

protected S updateRequestUri(S request, InternalServerProxy serverProxy) {

    URI origUri = request.getUri();
    String host = serverProxy.getHost();
    String scheme = origUri.getScheme() == null ? (request.isHttpsEnabled() ? "https" : "http")
            : origUri.getScheme();/*from  w  w w . j  a va  2s . c  o  m*/

    int port = serverProxy.getPort();

    String urlPath = "";
    if (origUri.getRawPath() != null && origUri.getRawPath().startsWith("/")) {
        urlPath = origUri.getRawPath();
    } else {
        urlPath = "/" + origUri.getRawPath();
    }

    URI newURI = null;
    try {
        if (autoEncodeUri) {
            String query = origUri.getQuery();
            newURI = new URI(scheme, origUri.getUserInfo(), host, port, urlPath, query, origUri.getFragment());
        } else {
            String query = origUri.getRawQuery();
            if (query != null) {
                newURI = new URI(scheme + "://" + host + ":" + port + urlPath + "?" + query);
            } else {
                newURI = new URI(scheme + "://" + host + ":" + port + urlPath);
            }

        }
    } catch (URISyntaxException e) {
        throw new ClientException(e.toString());
    }

    S req = (S) request.replaceUri(newURI);
    //        try {
    //            req = (S) this.clone();
    //        } catch (CloneNotSupportedException e) {
    //            throw new IllegalArgumentException(e);
    //        }
    //        req.uri = newURI;
    return req;
}

From source file:org.paxle.crawler.smb.impl.SmbCrawler.java

public ICrawlerDocument request(URI requestUri) {
    if (requestUri == null)
        throw new NullPointerException("URL was null");
    this.logger.info(String.format("Crawling URL '%s' ...", requestUri));

    ICrawlerDocument crawlerDoc = null;/* w ww.ja v  a2s .c o  m*/
    InputStream input = null;
    try {
        final ICrawlerContext ctx = this.contextLocal.getCurrentContext();

        // creating an empty crawler-document
        crawlerDoc = ctx.createDocument();
        crawlerDoc.setCrawlerDate(new Date());
        crawlerDoc.setLocation(requestUri);

        /* 
         * Create a temp URI to ensure that the port is set properly
         * This is required otherwise jcifs throws an exception.
         */
        URI temp = new URI(requestUri.getScheme(), requestUri.getUserInfo(), requestUri.getHost(),
                (requestUri.getPort() == -1) ? 445 : requestUri.getPort(), requestUri.getPath(),
                requestUri.getQuery(), requestUri.getFragment());

        SmbFile smbFile = new SmbFile(temp.toURL());
        if (!smbFile.exists()) {
            crawlerDoc.setStatus(Status.NOT_FOUND, "The resource does not exist");
            this.logger.info(String.format("The resource '%s' does not exit.", requestUri));
            return crawlerDoc;
        } else if (!smbFile.canRead()) {
            crawlerDoc.setStatus(Status.NOT_FOUND, "The resource can not be read.");
            this.logger.info(String.format("The resource '%s' can not be read.", requestUri));
            return crawlerDoc;
        }

        final ICrawlerTools crawlerTools = ctx.getCrawlerTools();
        if (smbFile.isDirectory()) {
            /* Append '/' if necessary. Otherwise we will get:
             * jcifs.smb.SmbException: smb://srver/dir directory must end with '/'
             */
            // XXX still needed with the SmbFile(URL)-constructor?
            String uriString = requestUri.toASCIIString();
            if (!uriString.endsWith("/")) {
                uriString += "/";
                smbFile = new SmbFile(uriString);
            }

            // set the mimetype accordingly
            crawlerDoc.setMimeType("text/html");

            // using the dir creation date as last-mod date
            long creationTimeStamp = smbFile.createTime();
            if (creationTimeStamp != 0) {
                crawlerDoc.setLastModDate(new Date(creationTimeStamp));
            }

            // getting the content of the directory
            SmbFile[] smbFiles = smbFile.listFiles();
            final Iterator<DirlistEntry> dirlistIt = new DirlistIterator(smbFiles, false);

            // generate & save dir listing
            crawlerTools.saveListing(crawlerDoc, dirlistIt, true, smbFiles.length > 50 // if more than 50 files, use compression
            );
        } else if (smbFile.isFile()) {
            // last modified timestamp
            long modTimeStamp = smbFile.getLastModified();
            if (modTimeStamp != 0) {
                crawlerDoc.setLastModDate(new Date(modTimeStamp));
            }

            // get file content
            input = smbFile.getInputStream();
        }

        if (input != null) {
            // copy data into file
            crawlerTools.saveInto(crawlerDoc, input);

            // finished
            crawlerDoc.setStatus(Status.OK);
        } else {
            crawlerDoc.setStatus(Status.UNKNOWN_FAILURE, "Unable to determine the smb-file type");
        }
    } catch (Throwable e) {
        crawlerDoc.setStatus(Status.UNKNOWN_FAILURE, "Unexpected Exception: " + e.getMessage());

        this.logger.warn(String.format("Unexpected '%s' while trying to crawl resource '%s'.",
                e.getClass().getName(), requestUri), e);
    } finally {
        if (input != null)
            try {
                input.close();
            } catch (Exception e) {
                /* ignore this */}
    }

    return crawlerDoc;
}

From source file:org.apache.woden.internal.DOMWSDLReader.java

private Description readWSDL(String wsdlURI, Document domDoc) throws WSDLException {

    //Try to find an element the XPointer points to if a Fragment Identifier exists.
    URI uri = null;
    try {//from  w ww .  j  a v a 2 s .c  o  m
        uri = new URI(wsdlURI);
    } catch (URISyntaxException e) {
        String msg = getErrorReporter().getFormattedMessage("WSDL506", new Object[] { null, wsdlURI });
        throw new WSDLException(WSDLException.PARSER_ERROR, msg, e);
    }

    String fragment = uri.getFragment();

    if (fragment == null) { //No fragment identifier so just use the root element.
        return readWSDL(wsdlURI, domDoc.getDocumentElement());//Use document root if no WSDL20 root found.
    } else {
        XPointer xpointer;
        try {
            xpointer = new XPointer(fragment);
        } catch (InvalidXPointerException e) {
            String msg = getErrorReporter().getFormattedMessage("WSDL530", new Object[] { fragment, wsdlURI });
            throw new WSDLException(WSDLException.PARSER_ERROR, msg, e);
        }
        Element root = domDoc.getDocumentElement();

        DOMXMLElementEvaluator evaluator = new DOMXMLElementEvaluator(xpointer, root, getErrorReporter());
        Element result = evaluator.evaluateElement();

        if (result != null) { //Element from XPointer evaluation.
            return readWSDL(wsdlURI, result);
        } else {
            String msg = getErrorReporter().getFormattedMessage("WSDL531", new Object[] { fragment, wsdlURI });
            throw new WSDLException(WSDLException.PARSER_ERROR, msg);
        }
    }
}

From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java

private String append(String base, Map<String, ?> query, Map<String, String> keys, boolean fragment) {

    UriComponentsBuilder template = UriComponentsBuilder.newInstance();
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base);
    URI redirectUri;
    try {/*from   ww  w.  j  ava2  s .c  om*/
        // assume it's encoded to start with (if it came in over the wire)
        redirectUri = builder.build(true).toUri();
    } catch (Exception e) {
        // ... but allow client registrations to contain hard-coded non-encoded values
        redirectUri = builder.build().toUri();
        builder = UriComponentsBuilder.fromUri(redirectUri);
    }
    template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost())
            .userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath());

    if (fragment) {
        StringBuilder values = new StringBuilder();
        if (redirectUri.getFragment() != null) {
            String append = redirectUri.getFragment();
            values.append(append);
        }
        for (String key : query.keySet()) {
            if (values.length() > 0) {
                values.append("&");
            }
            String name = key;
            if (keys != null && keys.containsKey(key)) {
                name = keys.get(key);
            }
            values.append(name + "={" + key + "}");
        }
        if (values.length() > 0) {
            template.fragment(values.toString());
        }
        UriComponents encoded = template.build().expand(query).encode();
        builder.fragment(encoded.getFragment());
    } else {
        for (String key : query.keySet()) {
            String name = key;
            if (keys != null && keys.containsKey(key)) {
                name = keys.get(key);
            }
            template.queryParam(name, "{" + key + "}");
        }
        template.fragment(redirectUri.getFragment());
        UriComponents encoded = template.build().expand(query).encode();
        builder.query(encoded.getQuery());
    }

    return builder.build().toUriString();

}

From source file:de.betterform.connector.file.FileURIResolver.java

/**
 * Performs link traversal of the <code>file</code> URI and returns the
 * result as a DOM document.//from w  w w  .  ja  v a2 s .  com
 *
 * @return a DOM node parsed from the <code>file</code> URI.
 * @throws XFormsException if any error occurred during link traversal.
 */
public Object resolve() throws XFormsException {
    try {
        // create uri
        URI uri = new URI(getURI());

        // use scheme specific part in order to handle UNC names
        String fileName = uri.getSchemeSpecificPart();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("loading file '" + fileName + "'");
        }

        // create file
        File file = new File(fileName);

        // check for directory
        if (file.isDirectory()) {
            return FileURIResolver.buildDirectoryListing(file);
        }

        // parse file
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        Document document = factory.newDocumentBuilder().parse(file);

        /*
                    Document document = CacheManager.getDocument(file);
                    if(document == null) {
            document = DOMResource.newDocumentBuilder().parse(file);
            CacheManager.putIntoFileCache(file, document);
                    }
        */

        // check for fragment identifier
        if (uri.getFragment() != null) {
            return document.getElementById(uri.getFragment());
        }

        return document;
    } catch (Exception e) {
        //todo: improve error handling as files might fail due to missing DTDs or Schemas - this won't be detected very well
        throw new XFormsException(e);
    }
}

From source file:com.github.brandtg.pantopod.crawler.CrawlingEventHandler.java

private URI getNextUri(URI url, String href, String chroot) throws Exception {
    //    if (href.contains("..")) {
    ///*from   w  w  w .  ja  va  2 s  .  c  o  m*/
    //      throw new IllegalArgumentException("Relative URI not allowed: " + href);
    //    }

    URI hrefUri = URI.create(href.trim().replaceAll(" ", "+"));

    URIBuilder builder = new URIBuilder();

    builder.setScheme(hrefUri.getScheme() == null ? url.getScheme() : hrefUri.getScheme());
    builder.setHost(hrefUri.getHost() == null ? url.getHost() : hrefUri.getHost());
    builder.setPort(hrefUri.getPort() == -1 ? url.getPort() : hrefUri.getPort());

    if (hrefUri.getPath() != null) {
        StringBuilder path = new StringBuilder();
        if (hrefUri.getHost() == null && chroot != null) {
            path.append(chroot);
        }

        // Ensure no two slashes
        if (hrefUri.getPath() != null && hrefUri.getPath().length() > 0 && hrefUri.getPath().charAt(0) == '/'
                && path.length() > 0 && path.charAt(path.length() - 1) == '/') {
            path.setLength(path.length() - 1);
        }

        path.append(hrefUri.getPath());

        builder.setPath(chroot == null ? "" : chroot + hrefUri.getPath());
    }
    if (hrefUri.getQuery() != null) {
        builder.setCustomQuery(hrefUri.getQuery());
    }
    if (hrefUri.getFragment() != null) {
        builder.setFragment(hrefUri.getFragment());
    }

    return builder.build();
}

From source file:org.pentaho.big.data.kettle.plugins.hdfs.trans.HadoopFileInputMeta.java

protected String encryptDecryptPassword(String source, EncryptDirection direction) {
    Validate.notNull(direction, "'direction' must not be null");
    try {/*from ww w .  j  a v a 2 s .co  m*/
        URI uri = new URI(source);
        String userInfo = uri.getUserInfo();
        if (userInfo != null) {
            String[] userInfoArray = userInfo.split(":", 2);
            if (userInfoArray.length < 2) {
                return source; //no password present
            }
            String password = userInfoArray[1];
            String processedPassword = password;
            switch (direction) {
            case ENCRYPT:
                processedPassword = Encr.encryptPasswordIfNotUsingVariables(password);
                break;
            case DECRYPT:
                processedPassword = Encr.decryptPasswordOptionallyEncrypted(password);
                break;
            default:
                throw new InvalidParameterException("direction must be 'ENCODE' or 'DECODE'");
            }
            URI encryptedUri = new URI(uri.getScheme(), userInfoArray[0] + ":" + processedPassword,
                    uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
            return encryptedUri.toString();
        }
    } catch (URISyntaxException e) {
        return source; // if this is non-parseable as a uri just return the source without changing it.
    }
    return source; // Just for the compiler should NEVER hit this code
}

From source file:org.eclipse.orion.server.git.servlets.GitTreeHandlerV1.java

private JSONObject listEntry(String name, long timeStamp, boolean isDir, long length, URI location,
        boolean appendName) {
    JSONObject jsonObject = new JSONObject();
    try {/*w  w w .  java2s  . c o m*/
        jsonObject.put(ProtocolConstants.KEY_NAME, name);
        jsonObject.put(ProtocolConstants.KEY_LOCAL_TIMESTAMP, timeStamp);
        jsonObject.put(ProtocolConstants.KEY_DIRECTORY, isDir);
        jsonObject.put(ProtocolConstants.KEY_LENGTH, length);
        if (location != null) {
            if (isDir && !location.getPath().endsWith("/")) {
                location = URIUtil.append(location, "");
            }
            if (appendName) {
                location = URIUtil.append(location, name);
                if (isDir) {
                    location = URIUtil.append(location, "");
                }
            }
            jsonObject.put(ProtocolConstants.KEY_LOCATION, location);
            if (isDir) {
                try {
                    jsonObject.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);
                }
            }
        }
        JSONObject attributes = new JSONObject();
        attributes.put("ReadOnly", true);
        jsonObject.put(ProtocolConstants.KEY_ATTRIBUTES, attributes);

    } catch (JSONException e) {
        //cannot happen because the key is non-null and the values are strings
        throw new RuntimeException(e);
    }
    return jsonObject;
}