Example usage for java.net URI getUserInfo

List of usage examples for java.net URI getUserInfo

Introduction

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

Prototype

public String getUserInfo() 

Source Link

Document

Returns the decoded user-information component of this URI.

Usage

From source file:org.devnexus.aerogear.RestRunner.java

private URL appendQuery(String query, URL baseURL) {
    try {//from   w w w  . j  ava 2  s  . c o m
        URI baseURI = baseURL.toURI();
        String baseQuery = baseURI.getQuery();
        if (baseQuery == null || baseQuery.isEmpty()) {
            baseQuery = query;
        } else {
            if (query != null && !query.isEmpty()) {
                baseQuery = baseQuery + "&" + query;
            }
        }

        if (baseQuery.isEmpty()) {
            baseQuery = null;
        }

        return new URI(baseURI.getScheme(), baseURI.getUserInfo(), baseURI.getHost(), baseURI.getPort(),
                baseURI.getPath(), baseQuery, baseURI.getFragment()).toURL();
    } catch (MalformedURLException ex) {
        Log.e(TAG, "The URL could not be created from " + baseURL.toString(), ex);
        throw new RuntimeException(ex);
    } catch (URISyntaxException ex) {
        Log.e(TAG, "Error turning " + query + " into URI query.", ex);
        throw new RuntimeException(ex);
    }
}

From source file:org.opendatakit.api.filter.ProxyUrlSetFilter.java

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    String forwardedPort = requestContext.getHeaderString("x-forwarded-port");
    String forwardedProto = requestContext.getHeaderString("x-forwarded-proto");
    String host = requestContext.getHeaderString("host");

    UriInfo uriInfo = requestContext.getUriInfo();
    URI requestUri = uriInfo.getRequestUri();
    URI baseUri = uriInfo.getBaseUri();
    int forwardedPortInt = uriInfo.getRequestUri().getPort();

    if (StringUtils.isNotEmpty(forwardedPort) || StringUtils.isNotEmpty(forwardedProto)) {
        if (StringUtils.isNotEmpty(forwardedPort)) {
            try {
                forwardedPortInt = Integer.parseInt(forwardedPort);
            } catch (NumberFormatException e) {
                logger.error("Unable to parse x-forwarded-port number " + forwardedPort
                        + " Generated URLs in JSON responses may be wrong.");
                // Life goes on. Non-fatal.
            }//from w ww  . j av  a2s  .c  om
        }
        if (StringUtils.isEmpty(forwardedProto)) {
            forwardedProto = uriInfo.getRequestUri().getScheme();
        }
        try {
            URI newRequestUri = new URI(forwardedProto, requestUri.getUserInfo(), host, forwardedPortInt,
                    requestUri.getPath(), requestUri.getQuery(), requestUri.getFragment());

            URI newBaseUri = new URI(forwardedProto, baseUri.getUserInfo(), host, forwardedPortInt,
                    baseUri.getPath(), baseUri.getQuery(), baseUri.getFragment());

            requestContext.setRequestUri(newBaseUri, newRequestUri);
        } catch (URISyntaxException e) {
            logger.error("Unable to update requestUri. Generated URLs in JSON responses may be wrong.");
            // Life goes on. Non-fatal.
        }

    }
}

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;//from ww w .ja  v a  2 s. c om
    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:com.streamsets.pipeline.stage.origin.remote.FTPRemoteDownloadSourceDelegate.java

protected void initAndConnectInternal(List<Stage.ConfigIssue> issues, Source.Context context, URI remoteURI,
        String archiveDir) throws IOException {
    options = new FileSystemOptions();
    this.remoteURI = remoteURI;
    if (conf.strictHostChecking) {
        issues.add(context.createConfigIssue(Groups.CREDENTIALS.getLabel(), CONF_PREFIX + "strictHostChecking",
                Errors.REMOTE_12));//from ww w  .j a  va  2 s . c  om
    }
    switch (conf.auth) {
    case PRIVATE_KEY:
        issues.add(context.createConfigIssue(Groups.CREDENTIALS.getLabel(), CONF_PREFIX + "privateKey",
                Errors.REMOTE_11));
        break;
    case PASSWORD:
        String username = resolveUsername(remoteURI, issues, context);
        String password = resolvePassword(remoteURI, issues, context);
        if (remoteURI.getUserInfo() != null) {
            remoteURI = UriBuilder.fromUri(remoteURI).userInfo(null).build();
        }
        StaticUserAuthenticator authenticator = new StaticUserAuthenticator(remoteURI.getHost(), username,
                password);
        DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(options, authenticator);
        break;
    case NONE:
        break;
    default:
        break;
    }
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(options, true);
    FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(options, conf.userDirIsRoot);

    // Only actually try to connect and authenticate if there were no issues
    if (issues.isEmpty()) {
        LOG.info("Connecting to {}", remoteURI.toString());
        // To ensure we can connect, else we fail validation.
        remoteDir = VFS.getManager().resolveFile(remoteURI.toString(), options);
        // Ensure we can assess the remote directory...
        remoteDir.refresh();
        // throw away the results.
        remoteDir.getChildren();

        setupModTime();
    }

    if (archiveDir != null) {
        archiveURI = UriBuilder.fromUri(remoteURI).replacePath(archiveDir).build();
        archiveOptions = (FileSystemOptions) options.clone();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(archiveOptions, conf.archiveDirUserDirIsRoot);
    }
}

From source file:com.streamsets.pipeline.lib.remote.FTPRemoteConnector.java

@Override
protected void initAndConnect(List<Stage.ConfigIssue> issues, ConfigIssueContext context, URI remoteURI,
        Label remoteGroup, Label credGroup) {
    options = new FileSystemOptions();
    this.remoteURI = remoteURI;
    if (remoteConfig.strictHostChecking) {
        issues.add(context.createConfigIssue(credGroup.getLabel(), CONF_PREFIX + "strictHostChecking",
                Errors.REMOTE_07));/*  w  w  w  . j ava  2s  .  c  o m*/
    }
    switch (remoteConfig.auth) {
    case PRIVATE_KEY:
        issues.add(
                context.createConfigIssue(credGroup.getLabel(), CONF_PREFIX + "privateKey", Errors.REMOTE_06));
        break;
    case PASSWORD:
        String username = resolveUsername(remoteURI, issues, context, credGroup);
        String password = resolvePassword(remoteURI, issues, context, credGroup);
        if (remoteURI.getUserInfo() != null) {
            remoteURI = UriBuilder.fromUri(remoteURI).userInfo(null).build();
        }
        StaticUserAuthenticator authenticator = new StaticUserAuthenticator(remoteURI.getHost(), username,
                password);
        try {
            DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(options, authenticator);
        } catch (FileSystemException e) {
            // This method doesn't actually ever throw a FileSystemException, it simply declares that it does...
            // This shouldn't happen, but just in case, we'll log it
            LOG.error("Unexpected Exception", e);
        }
        break;
    case NONE:
        break;
    default:
        break;
    }

    FtpFileSystemConfigBuilder configBuilder = FtpFileSystemConfigBuilder.getInstance();
    if (remoteURI.getScheme().equals(FTPS_SCHEME)) {
        configBuilder = FtpsFileSystemConfigBuilder.getInstance();
        FtpsFileSystemConfigBuilder.getInstance().setFtpsMode(options, remoteConfig.ftpsMode.getMode());
        FtpsFileSystemConfigBuilder.getInstance().setDataChannelProtectionLevel(options,
                remoteConfig.ftpsDataChannelProtectionLevel.getLevel());
        if (remoteConfig.useFTPSClientCert) {
            setFtpsUserKeyManagerOrTrustManager(remoteConfig.ftpsClientCertKeystoreFile,
                    CONF_PREFIX + "ftpsClientCertKeystoreFile", remoteConfig.ftpsClientCertKeystorePassword,
                    CONF_PREFIX + "ftpsClientCertKeystorePassword", remoteConfig.ftpsClientCertKeystoreType,
                    true, issues, context, credGroup);
        }
        switch (remoteConfig.ftpsTrustStoreProvider) {
        case FILE:
            setFtpsUserKeyManagerOrTrustManager(remoteConfig.ftpsTruststoreFile,
                    CONF_PREFIX + "ftpsTruststoreFile", remoteConfig.ftpsTruststorePassword,
                    CONF_PREFIX + "ftpsTruststorePassword", remoteConfig.ftpsTruststoreType, false, issues,
                    context, credGroup);
            break;
        case JVM_DEFAULT:
            try {
                FtpsFileSystemConfigBuilder.getInstance().setTrustManager(options,
                        TrustManagerUtils.getDefaultTrustManager(null));
            } catch (GeneralSecurityException e) {
                issues.add(context.createConfigIssue(credGroup.getLabel(), CONF_PREFIX + "ftpsTruststoreFile",
                        Errors.REMOTE_14, "trust", "JVM", e.getMessage(), e));
            }
            break;
        case ALLOW_ALL:
            // fall through
        default:
            FtpsFileSystemConfigBuilder.getInstance().setTrustManager(options,
                    TrustManagerUtils.getAcceptAllTrustManager());
            break;
        }
    }
    configBuilder.setPassiveMode(options, true);
    configBuilder.setUserDirIsRoot(options, remoteConfig.userDirIsRoot);

    // Only actually try to connect and authenticate if there were no issues
    if (issues.isEmpty()) {
        LOG.info("Connecting to {}", remoteURI.toString());
        try {
            remoteDir = VFS.getManager().resolveFile(remoteURI.toString(), options);
            remoteDir.refresh();
            if (remoteConfig.createPathIfNotExists && !remoteDir.exists()) {
                remoteDir.createFolder();
            }
            remoteDir.getChildren();
        } catch (FileSystemException e) {
            LOG.error(Errors.REMOTE_11.getMessage(), remoteURI.toString(), e.getMessage(), e);
            issues.add(context.createConfigIssue(remoteGroup.getLabel(), CONF_PREFIX + "remoteAddress",
                    Errors.REMOTE_11, remoteURI.toString(), e.getMessage(), e));
        }
    }
}

From source file:com.googlecode.jdeltasync.DeltaSyncClient.java

/**
 * Slightly modified version of {@link DefaultRedirectStrategy#getLocationURI(HttpRequest, HttpResponse, HttpContext)}
 * which also adds the query string from the original request URI to the new URI.
 *//*ww w .  j a  v  a 2 s .  co m*/
private URI getRedirectLocationURI(IDeltaSyncSession session, HttpUriRequest request, HttpResponse response,
        HttpContext context) throws DeltaSyncException {

    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new DeltaSyncException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (session.getLogger().isDebugEnabled()) {
        session.getLogger().debug("Redirect requested to location '" + location + "'");
    }

    URI uri = null;
    try {
        uri = new URI(location);
        if (request.getURI().getRawQuery() != null) {
            String query = request.getURI().getRawQuery();
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                    query, uri.getFragment());
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException("Invalid redirect URI: " + location, ex);
    }

    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final RequestConfig config = clientContext.getRequestConfig();

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (config.isRelativeRedirectsAllowed()) {
                throw new DeltaSyncException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            HttpHost target = clientContext.getTargetHost();
            if (target == null) {
                throw new IllegalStateException("Target host not available " + "in the HTTP context");
            }

            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute("http.protocol.redirect-locations");
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute("http.protocol.redirect-locations", redirectLocations);
    }

    if (config.isCircularRedirectsAllowed()) {
        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new DeltaSyncException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new DeltaSyncException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

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

private boolean identifyNewCommitResource(HttpServletRequest request, HttpServletResponse response,
        Repository db, String newCommit) throws ServletException {
    try {//from   ww w.  ja  v a  2 s  .c o m
        URI u = getURI(request);
        IPath p = new Path(u.getPath());
        IPath np = new Path("/"); //$NON-NLS-1$
        for (int i = 0; i < p.segmentCount(); i++) {
            String s = p.segment(i);
            if (i == 2) {
                s += ".." + newCommit; //$NON-NLS-1$
            }
            np = np.append(s);
        }
        if (p.hasTrailingSeparator())
            np = np.addTrailingSeparator();
        URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), np.toString(), u.getQuery(),
                u.getFragment());
        JSONObject result = new JSONObject();
        result.put(ProtocolConstants.KEY_LOCATION, nu);
        OrionServlet.writeJSONResponse(request, response, result);
        response.setHeader(ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString());
        return true;
    } catch (Exception e) {
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "An error occured when identifying a new Commit resource.", e));
    }
}

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  w w w  .j  av  a 2  s .co  m
        // 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();

}