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:net.xy.jcms.shared.adapter.HttpRequestDataAccessContext.java

@Override
public String buildUriWithParams(final String requestString, final Map<Object, Object> parameters) {
    // 1. should not alter external links
    // 2. should convert absolute uris to relatives if possible
    try {/*from  ww w. j av  a  2 s  .  c o m*/
        URI build; // the initial request
        try {
            // first asume its already an proper url
            build = new URI(requestString);
        } catch (final URISyntaxException ex) {
            // second encode to an proper url
            final String requestUri = URLEncoder.encode(requestString, "UTF-8");
            build = new URI(requestUri);
        }
        if (!build.isAbsolute()) {
            build = rootUrl.resolve(build); // make it absolute
        }
        final String path = StringUtils.isNotBlank(build.getPath()) ? build.getPath() : "/";
        build = new URI(build.getScheme(), build.getUserInfo(), build.getHost(), build.getPort(), path,
                buildQuery(parameters), build.getFragment());
        final URI relBuild = rootUrl.relativize(build);
        final String ret;
        if (!relBuild.isAbsolute()) {
            // because we relativate it always to docroot, which is the
            // servlet container in JEE
            ret = contextPath + relBuild.toASCIIString().replace("+", "%20");
        } else {
            ret = relBuild.toASCIIString();
        }
        return ret;
    } catch (final URISyntaxException e) {
        throw new IllegalArgumentException("URL couldn't be build from given parameters. "
                + DebugUtils.printFields(requestString, parameters), e);
    } catch (final UnsupportedEncodingException e) {
        throw new IllegalArgumentException(
                " Encoding is not supported " + DebugUtils.printFields(requestString, parameters), e);
    }
}

From source file:com.gitblit.tickets.RedisTicketService.java

private JedisPool createPool(String url) {
    JedisPool pool = null;//from w  ww  .  java 2s . co m
    if (!StringUtils.isEmpty(url)) {
        try {
            URI uri = URI.create(url);
            if (uri.getScheme() != null && uri.getScheme().equalsIgnoreCase("redis")) {
                int database = Protocol.DEFAULT_DATABASE;
                String password = null;
                if (uri.getUserInfo() != null) {
                    password = uri.getUserInfo().split(":", 2)[1];
                }
                if (uri.getPath().indexOf('/') > -1) {
                    database = Integer.parseInt(uri.getPath().split("/", 2)[1]);
                }
                pool = new JedisPool(new GenericObjectPoolConfig(), uri.getHost(), uri.getPort(),
                        Protocol.DEFAULT_TIMEOUT, password, database);
            } else {
                pool = new JedisPool(url);
            }
        } catch (JedisException e) {
            log.error("failed to create a Redis pool!", e);
        }
    }
    return pool;
}

From source file:org.mycore.datamodel.ifs2.MCRVersioningMetadataStore.java

private void setupSVN(String type) {
    URI repositoryURI;
    String repositoryURIString = MCRConfiguration.instance()
            .getString("MCR.IFS2.Store." + type + ".SVNRepositoryURL");
    try {/*from   w  ww .j a va  2 s.  com*/
        repositoryURI = new URI(repositoryURIString);
    } catch (URISyntaxException e) {
        String msg = "Syntax error in MCR.IFS2.Store." + type + ".SVNRepositoryURL property: "
                + repositoryURIString;
        throw new MCRConfigurationException(msg, e);
    }
    try {
        LOGGER.info("Versioning metadata store " + type + " repository URL: " + repositoryURI);
        repURL = SVNURL.create(repositoryURI.getScheme(), repositoryURI.getUserInfo(), repositoryURI.getHost(),
                repositoryURI.getPort(), repositoryURI.getPath(), true);
        LOGGER.info("repURL: " + repURL);
        File dir = new File(repURL.getPath());
        if (!dir.exists() || (dir.isDirectory() && dir.list().length == 0)) {
            LOGGER.info("Repository does not exist, creating new SVN repository at " + repositoryURI);
            repURL = SVNRepositoryFactory.createLocalRepository(dir, true, false);
        }
    } catch (SVNException ex) {
        String msg = "Error initializing SVN repository at URL " + repositoryURI;
        throw new MCRConfigurationException(msg, ex);
    }
}

From source file:org.opendatakit.common.security.spring.Oauth2ResourceFilter.java

private Map<String, Object> getJsonResponse(String url, String accessToken) {

    Map<String, Object> nullData = new HashMap<String, Object>();

    // OK if we got here, we have a valid token.
    // Issue the request...
    URI nakedUri;
    try {//from   www  . jav a2 s  .  c om
        nakedUri = new URI(url);
    } catch (URISyntaxException e2) {
        e2.printStackTrace();
        logger.error(e2.toString());
        return nullData;
    }

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("access_token", accessToken));
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        logger.error(e1.toString());
        return nullData;
    }

    // DON'T NEED clientId on the toke request...
    // addCredentials(clientId, clientSecret, nakedUri.getHost());
    // setup request interceptor to do preemptive auth
    // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    // setup client
    HttpClient client = httpClientFactory.createHttpClient(httpParams);

    HttpGet httpget = new HttpGet(uri);
    logger.info(httpget.getURI().toString());

    HttpResponse response = null;
    try {
        response = client.execute(httpget, new BasicHttpContext());
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            logger.error("not 200: " + statusCode);
            return nullData;
        } else {
            HttpEntity entity = response.getEntity();

            if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                BufferedReader reader = null;
                InputStreamReader isr = null;
                try {
                    reader = new BufferedReader(isr = new InputStreamReader(entity.getContent()));
                    @SuppressWarnings("unchecked")
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    return userData;
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                    if (isr != null) {
                        try {
                            isr.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                }
            } else {
                logger.error("unexpected body");
                return nullData;
            }
        }
    } catch (IOException e) {
        logger.error(e.toString());
        return nullData;
    } catch (Exception e) {
        logger.error(e.toString());
        return nullData;
    }
}

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

public String resolvePropertyUri(String name, int index) {

    URI uri = getUri(index);

    Property p = getProperty(name);/*from w w w.  ja v a2s . c  om*/

    if (p != null) {
        try {
            // String scheme, String userInfo, String host, int port, String path, String query, String fragment
            String path = uri.getPath();
            if (path.endsWith("/")) {
                path = path + p.getHrefs().get(index);
            } else {
                path = path + "/" + p.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();
}

From source file:org.joyrest.oauth2.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  a va 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 (nonNull(keys) && 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:com.seajas.search.contender.service.modifier.AbstractModifierService.java

/**
 * Retrieve the FTP client belonging to the given URI.
 * /*from w  w  w  .j a  va2  s . c o m*/
 * @param uri
 * @return FTPClient
 */
protected FTPClient retrieveFtpClient(final URI uri) {
    // Create the FTP client

    FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

    try {
        ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not connect to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        if (StringUtils.hasText(uri.getUserInfo())) {
            if (uri.getUserInfo().contains(":"))
                ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                        uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
            else
                ftpClient.login(uri.getUserInfo(), "");
        }

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not login to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        // Switch to PASV and BINARY mode

        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        return ftpClient;
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    }

    return null;
}

From source file:org.eclipse.orion.server.tests.servlets.files.FileSystemTest.java

protected URI addSchemeHostPort(URI uri) {
    String scheme = uri.getScheme();
    String host = uri.getHost();// w  w w  .j  ava2s .  co  m
    int port = uri.getPort();
    if (scheme == null) {
        scheme = "http";
    }
    if (host == null) {
        host = "localhost";
    }
    if (port == -1) {
        port = 8080;
    }
    try {
        return new URI(scheme, uri.getUserInfo(), host, port, uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.aliyun.fs.oss.nat.JetOssNativeFileSystemStore.java

public void initialize(URI uri, Configuration conf) throws Exception {
    if (uri.getHost() == null) {
        throw new IllegalArgumentException("Invalid hostname in URI " + uri);
    }/*w w  w .j a va2s  .  c om*/

    // 1. try to get accessKeyId, accessJeySecret, securityToken,
    // endpoint from OSS URI.
    String userInfo = uri.getUserInfo();
    if (userInfo != null) {
        String[] ossCredentials = userInfo.split(":");
        if (ossCredentials.length >= 2) {
            accessKeyId = ossCredentials[0];
            accessKeySecret = ossCredentials[1];
        }
        if (ossCredentials.length == 3) {
            securityToken = ossCredentials[2];
        }
    }

    this.conf = conf;
    String host = uri.getHost();
    if (!StringUtils.isEmpty(host) && !host.contains(".")) {
        bucket = host;
    } else if (!StringUtils.isEmpty(host)) {
        bucket = host.substring(0, host.indexOf("."));
        endpoint = host.substring(host.indexOf(".") + 1);
    }

    // 2. try to get accessKeyId, accessJeySecret, securityToken,
    // endpoint from configuration.
    if (accessKeyId == null) {
        accessKeyId = conf.getTrimmed("fs.oss.accessKeyId");
    }
    if (accessKeySecret == null) {
        accessKeySecret = conf.getTrimmed("fs.oss.accessKeySecret");
    }
    if (securityToken == null) {
        securityToken = conf.getTrimmed("fs.oss.securityToken");
    }

    if (endpoint == null) {
        endpoint = conf.getTrimmed("fs.oss.endpoint");
    }

    // 3. try to get accessKeyId, accessJeySecret, securityToken,
    // endpoint from metaservice.
    LOG.debug("Try to get accessKeyId, accessJeySecret, securityToken, " + "endpoint from metaservice.");
    if (accessKeyId == null || accessKeySecret == null) {
        accessKeyId = MetaClient.getRoleAccessKeyId();
        accessKeySecret = MetaClient.getRoleAccessKeySecret();
        securityToken = MetaClient.getRoleSecurityToken();

        if (StringUtils.isEmpty(accessKeyId) || StringUtils.isEmpty(accessKeySecret)
                || StringUtils.isEmpty(securityToken)) {
            throw new IllegalArgumentException(
                    "AccessKeyId/AccessKeySecret/SecurityToken is not available, you "
                            + "can set them in OSS URI");
        }
    }

    if (endpoint == null) {
        endpoint = EndpointEnum.getEndpoint("oss", MetaClient.getClusterRegionName(),
                MetaClient.getClusterNetworkType());
        if (endpoint == null) {
            throw new IllegalArgumentException(
                    "Can not find any suitable " + "endpoint, you can set it in OSS URI");
        }
    }

    if (securityToken == null) {
        this.ossClient = new OSSClientAgent(endpoint, accessKeyId, accessKeySecret, conf);
    } else {
        this.ossClient = new OSSClientAgent(endpoint, accessKeyId, accessKeySecret, securityToken, conf);
    }
    this.numCopyThreads = conf.getInt("fs.oss.uploadPartCopy.thread.number", 10);
    this.numPutThreads = conf.getInt("fs.oss.uploadPart.thread.number", 5);
    this.maxSplitSize = conf.getInt("fs.oss.multipart.split.max.byte", 5 * 1024 * 1024);
    this.numSplits = conf.getInt("fs.oss.multipart.split.number", 10);
    this.maxSimpleCopySize = conf.getLong("fs.oss.copy.simple.max.byte", 64 * 1024 * 1024L);
    this.maxSimplePutSize = conf.getLong("fs.oss.put.simple.max.byte", 5 * 1024 * 1024);
}

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

private boolean identifyNewDiffResource(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    try {/*from   ww w.  ja  v a  2 s .  c  om*/
        StringWriter writer = new StringWriter();
        IOUtilities.pipe(request.getReader(), writer, false, false);
        JSONObject requestObject = new JSONObject(writer.toString());
        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 += ".."; //$NON-NLS-1$
                s += GitUtils.encode(requestObject.getString(GitConstants.KEY_COMMIT_NEW));
            }
            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.toString());
        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 Diff resource.", e));
    }
}