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:com.meltmedia.cadmium.servlets.AbstractSecureRedirectStrategy.java

/**
 * Returns a new URI object, based on the specified URI template, with an updated port (scheme) and port.  If the port
 * number is -1, then the default port is used in the resulting URI. 
 * //from ww w .j  a  va  2 s.c om
 * @param protocol the new protocol (scheme) in the resulting URI.
 * @param port the new port in the resulting URI, or the default port if -1 is provided.
 * @param template the source of all other values for the new URI.
 * @return a new URI object with the updated protocol and port.
 * @throws URISyntaxException 
 */
public static URI changeProtocolAndPort(String protocol, int port, URI template) throws URISyntaxException {
    return new URI(protocol, template.getUserInfo(), template.getHost(), port, template.getPath(),
            template.getQuery(), null);
}

From source file:examples.mail.IMAPUtils.java

/**
 * Parse the URI and use the details to connect to the IMAP(S) server and login.
 *
 * @param uri the URI to use, e.g. imaps://user:pass@imap.mail.yahoo.com/folder
 * or imaps://user:pass@imap.googlemail.com/folder
 * @param defaultTimeout initial timeout (in milliseconds)
 * @param listener for tracing protocol IO (may be null)
 * @return the IMAP client - connected and logged in
 * @throws IOException if any problems occur
 *//*from   ww w .  ja  va 2 s .  c o  m*/
static IMAPClient imapLogin(URI uri, int defaultTimeout, ProtocolCommandListener listener) throws IOException {
    final String userInfo = uri.getUserInfo();
    if (userInfo == null) {
        throw new IllegalArgumentException("Missing userInfo details");
    }

    String[] userpass = userInfo.split(":");
    if (userpass.length != 2) {
        throw new IllegalArgumentException("Invalid userInfo details: '" + userInfo + "'");
    }

    String username = userpass[0];
    String password = userpass[1];
    /*
     * If the initial password is:
     * '*' - replace it with a line read from the system console
     * '-' - replace it with next line from STDIN
     * 'ABCD' - if the input is all upper case, use the field as an environment variable name
     *
     * Note: there are no guarantees that the password cannot be snooped.
     *
     * Even using the console may be subject to memory snooping,
     * however it should be safer than the other methods.
     *
     * STDIN may require creating a temporary file which could be read by others
     * Environment variables may be visible by using PS
     */
    if ("-".equals(password)) { // stdin
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        password = in.readLine();
    } else if ("*".equals(password)) { // console
        Console con = System.console(); // Java 1.6
        if (con != null) {
            char[] pwd = con.readPassword("Password for " + username + ": ");
            password = new String(pwd);
        } else {
            throw new IOException("Cannot access Console");
        }
    } else if (password.equals(password.toUpperCase(Locale.ROOT))) { // environment variable name
        final String tmp = System.getenv(password);
        if (tmp != null) { // don't overwrite if variable does not exist (just in case password is all uppers)
            password = tmp;
        }
    }

    final IMAPClient imap;

    final String scheme = uri.getScheme();
    if ("imaps".equalsIgnoreCase(scheme)) {
        System.out.println("Using secure protocol");
        imap = new IMAPSClient(true); // implicit
    } else if ("imap".equalsIgnoreCase(scheme)) {
        imap = new IMAPClient();
    } else {
        throw new IllegalArgumentException("Invalid protocol: " + scheme);
    }
    final int port = uri.getPort();
    if (port != -1) {
        imap.setDefaultPort(port);
    }

    imap.setDefaultTimeout(defaultTimeout);

    if (listener != null) {
        imap.addProtocolCommandListener(listener);
    }

    final String server = uri.getHost();
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    try {
        imap.connect(server);
        System.out.println("Successfully connected");
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    if (!imap.login(username, password)) {
        imap.disconnect();
        throw new RuntimeException("Could not login to server. Check login details.");
    }

    return imap;
}

From source file:org.cloudfoundry.caldecott.client.TunnelHelper.java

public static Map<String, String> getTunnelServiceInfo(CloudFoundryClient client, String serviceName) {
    String urlToUse = getTunnelUri(client) + "/services/" + serviceName;
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Auth-Token", getTunnelAuth(client));
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    HttpEntity<String> response = restTemplate.exchange(urlToUse, HttpMethod.GET, requestEntity, String.class);
    String json = response.getBody().trim();
    Map<String, String> svcInfo = new HashMap<String, String>();
    try {/*from   w w  w. j  a  v a  2 s. com*/
        svcInfo = convertJsonToMap(json);
    } catch (IOException e) {
        return new HashMap<String, String>();
    }
    if (svcInfo.containsKey("url")) {
        String svcUrl = svcInfo.get("url");
        try {
            URI uri = new URI(svcUrl);
            String[] userInfo;
            if (uri.getUserInfo().contains(":")) {
                userInfo = uri.getUserInfo().split(":");
            } else {
                userInfo = new String[2];
                userInfo[0] = uri.getUserInfo();
                userInfo[1] = "";
            }
            svcInfo.put("user", userInfo[0]);
            svcInfo.put("username", userInfo[0]);
            svcInfo.put("password", userInfo[1]);
            svcInfo.put("host", uri.getHost());
            svcInfo.put("hostname", uri.getHost());
            svcInfo.put("port", "" + uri.getPort());
            svcInfo.put("path", (uri.getPath().startsWith("/") ? uri.getPath().substring(1) : uri.getPath()));
            svcInfo.put("vhost", svcInfo.get("path"));
        } catch (URISyntaxException e) {
        }
    }
    return svcInfo;
}

From source file:com.github.wolf480pl.mias4j.util.AbstractTransformingClassLoader.java

public static URL guessCodeSourceURL(String resourcePath, URL resourceURL) {
    // FIXME: Find a better way to do this
    @SuppressWarnings("restriction")
    String escaped = sun.net.www.ParseUtil.encodePath(resourcePath, false);
    String path = resourceURL.getPath();
    if (!path.endsWith(escaped)) {
        // Umm... whadda we do now? Maybe let's fallback to full resource URL.
        LOG.warn("Resource URL path \"" + path + "\" doesn't end with escaped resource path \"" + escaped
                + "\" for resource \"" + resourcePath + "\"");
        return resourceURL;
    }/*from w  w w .  j a  va 2s .c  o m*/
    path = path.substring(0, path.length() - escaped.length());
    if (path.endsWith("!/")) { // JAR
        path = path.substring(0, path.length() - 2);
    }
    try {
        URI uri = resourceURL.toURI();
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path, uri.getQuery(),
                uri.getFragment()).toURL();
    } catch (MalformedURLException | URISyntaxException e) {
        // Umm... whadda we do now? Maybe let's fallback to full resource URL.
        LOG.warn("Couldn't assemble CodeSource URL with modified path", e);
        return resourceURL;
    }
}

From source file:com.vmware.identity.openidconnect.protocol.URIUtils.java

public static boolean areEqual(URI lhs, URI rhs) {
    Validate.notNull(lhs, "lhs");
    Validate.notNull(rhs, "rhs");

    URI lhsCopy;//www. j  a  va  2 s . c o m
    URI rhsCopy;
    try {
        lhsCopy = new URI(lhs.getScheme(), lhs.getUserInfo(), lhs.getHost(), URIUtils.getPort(lhs),
                lhs.getPath(), lhs.getQuery(), lhs.getFragment());
        rhsCopy = new URI(rhs.getScheme(), rhs.getUserInfo(), rhs.getHost(), URIUtils.getPort(rhs),
                rhs.getPath(), rhs.getQuery(), rhs.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("failed to transform uri for equality check", e);
    }

    return lhsCopy.equals(rhsCopy);
}

From source file:org.switchyard.component.http.endpoint.StandaloneEndpointPublisher.java

/**
 * Method for get request information from a http exchange.
 *
 * @param request HttpExchange/*from w w  w  .j a  v a2 s .c o  m*/
 * @param type ContentType
 * @return Request information from a http exchange
 * @throws IOException when the request information could not be read
 */
public static HttpRequestInfo getRequestInfo(HttpExchange request, ContentType type) throws IOException {
    HttpRequestInfo requestInfo = new HttpRequestInfo();

    if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) {
        requestInfo.setAuthType(HttpServletRequest.BASIC_AUTH);
    }
    URI u = request.getRequestURI();
    URI requestURI = null;
    try {
        requestURI = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), null, null);
    } catch (URISyntaxException e) {
        // Strange that this could happen when copying from another URI.
        LOGGER.debug(e);
    }
    requestInfo.setCharacterEncoding(type.getCharset());
    requestInfo.setContentType(type.toString());
    requestInfo.setContextPath(request.getHttpContext().getPath());
    requestInfo.setLocalAddr(request.getLocalAddress().getAddress().getHostAddress());
    requestInfo.setLocalName(request.getLocalAddress().getAddress().getHostName());
    requestInfo.setMethod(request.getRequestMethod());
    requestInfo.setProtocol(request.getProtocol());
    requestInfo.setQueryString(u.getQuery());
    requestInfo.setRemoteAddr(request.getRemoteAddress().getAddress().getHostAddress());
    requestInfo.setRemoteHost(request.getRemoteAddress().getAddress().getHostName());
    if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) {
        requestInfo.setRemoteUser(request.getPrincipal().getUsername());
    }
    requestInfo.setContentLength(request.getRequestBody().available());
    // requestInfo.setRequestSessionId(request.getRequestedSessionId());
    if (requestURI != null) {
        requestInfo.setRequestURI(requestURI.toString());
    }
    requestInfo.setScheme(u.getScheme());
    requestInfo.setServerName(u.getHost());
    requestInfo.setRequestPath(u.getPath());

    // Http Query params...
    if (requestInfo.getQueryString() != null) {
        Charset charset = null;
        if (type.getCharset() != null) {
            try {
                charset = Charset.forName(type.getCharset());
            } catch (Exception exception) {
                LOGGER.debug(exception);
            }
        }
        for (NameValuePair nameValuePair : URLEncodedUtils.parse(requestInfo.getQueryString(), charset)) {
            requestInfo.addQueryParam(nameValuePair.getName(), nameValuePair.getValue());
        }
    }

    // Credentials...
    requestInfo.getCredentials().addAll(new HttpExchangeCredentialExtractor().extract(request));

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(requestInfo);
    }

    return requestInfo;
}

From source file:org.apache.activemq.artemis.utils.uri.BeanSupport.java

public static <P> P setData(URI uri, P obj, Map<String, String> query) throws Exception {
    synchronized (beanUtils) {
        beanUtils.setProperty(obj, "host", uri.getHost());
        beanUtils.setProperty(obj, "port", uri.getPort());
        beanUtils.setProperty(obj, "userInfo", uri.getUserInfo());
        beanUtils.populate(obj, query);//  ww  w. j av a 2 s .co m
    }
    return obj;
}

From source file:URISupport.java

public static URI changeScheme(URI bindAddr, String scheme) throws URISyntaxException {
    return new URI(scheme, bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(),
            bindAddr.getQuery(), bindAddr.getFragment());
}

From source file:URISupport.java

/**
 * Creates a URI with the given query/*w  w w  .  j  av a2s  .co m*/
 */
public static URI createURIWithQuery(URI uri, String query) throws URISyntaxException {
    return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), query,
            uri.getFragment());
}

From source file:com.google.caja.precajole.StaticPrecajoleMap.java

public static String normalizeUri(String uri) {
    try {//from  ww  w .  j av a 2  s. com
        URI u = new URI(uri).normalize();
        if (u.getHost() != null) {
            u = new URI(lowercase(u.getScheme()), u.getUserInfo(), lowercase(u.getHost()), u.getPort(),
                    u.getPath(), u.getQuery(), u.getFragment());
        } else if (u.getScheme() != null) {
            u = new URI(lowercase(u.getScheme()), u.getSchemeSpecificPart(), u.getFragment());
        }
        return u.toString();
    } catch (URISyntaxException e) {
        return uri;
    }
}