Example usage for java.net URL getUserInfo

List of usage examples for java.net URL getUserInfo

Introduction

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

Prototype

public String getUserInfo() 

Source Link

Document

Gets the userInfo part of this URL .

Usage

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * Perform a GET-request using the specified {@link HttpClient}. If the URL contains an authentication part, the
 * UserCredentials will be set to the {@link HttpClient} instance. Depending on the specified <tt>url</tt> and the
 * settings from the <tt>escidoc-core.properties</tt>, the {@link HttpClient} instance will be configured to use a
 * proxy or not.//from   w ww .j  a v a 2 s.c o  m
 * 
 * @see ConnectionUtility#getHttpClient()
 * @see ConnectionUtility#getHttpClient(HttpParams)
 * 
 * @param client
 * @param url
 * @return The response of the request.
 * @throws WebserverSystemException
 */
public HttpResponse getRequestURL(final DefaultHttpClient client, final URL url)
        throws WebserverSystemException {
    String username = null;
    String password = null;
    final String userinfo = url.getUserInfo();
    if (userinfo != null) {
        final String[] loginValues = SPLIT_PATTERN.split(userinfo);
        username = loginValues[0];
        password = loginValues[1];
    }

    return getRequestURL(client, url, username, password);
}

From source file:org.apache.flink.table.runtime.functions.SqlFunctionUtils.java

/**
 * Parse url and return various components of the URL.
 * If accept any null arguments, return null.
 *
 * @param urlStr        URL string.//from  w  w w .j av a  2s . co  m
 * @param partToExtract determines which components would return.
 *                      accept values:
 *                      HOST,PATH,QUERY,REF,
 *                      PROTOCOL,FILE,AUTHORITY,USERINFO
 * @return target value.
 */
public static String parseUrl(String urlStr, String partToExtract) {
    URL url;
    try {
        url = URL_CACHE.get(urlStr);
    } catch (Exception e) {
        LOG.error("Parse URL error: " + urlStr, e);
        return null;
    }
    if ("HOST".equals(partToExtract)) {
        return url.getHost();
    }
    if ("PATH".equals(partToExtract)) {
        return url.getPath();
    }
    if ("QUERY".equals(partToExtract)) {
        return url.getQuery();
    }
    if ("REF".equals(partToExtract)) {
        return url.getRef();
    }
    if ("PROTOCOL".equals(partToExtract)) {
        return url.getProtocol();
    }
    if ("FILE".equals(partToExtract)) {
        return url.getFile();
    }
    if ("AUTHORITY".equals(partToExtract)) {
        return url.getAuthority();
    }
    if ("USERINFO".equals(partToExtract)) {
        return url.getUserInfo();
    }

    return null;
}

From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java

/**
 * Will encode url, if not disabled, and adds params on the end of it
 *
 * @param url//from   w  w  w .  j a v a  2 s  . c o m
 *            String with URL, should be valid URL without params
 * @param params
 *            RequestParams to be appended on the end of URL
 * @param shouldEncodeUrl
 *            whether url should be encoded (replaces spaces with %20)
 * @return encoded url if requested with params appended if any available
 */
public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) {
    if (url == null)
        return null;

    if (shouldEncodeUrl) {
        try {
            String decodedURL = URLDecoder.decode(url, "UTF-8");
            URL _url = new URL(decodedURL);
            URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(),
                    _url.getPath(), _url.getQuery(), _url.getRef());
            url = _uri.toASCIIString();
        } catch (Exception ex) {
            // Should not really happen, added just for sake of validity
            Log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
        }
    }

    if (params != null) {
        // Construct the query string and trim it, in case it
        // includes any excessive white spaces.
        String paramString = params.getParamString().trim();

        // Only add the query string if it isn't empty and it
        // isn't equal to '?'.
        if (!paramString.equals("") && !paramString.equals("?")) {
            url += url.contains("?") ? "&" : "?";
            url += paramString;
        }
    }

    return url;
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * Perform a POST-request using the specified {@link HttpClient}. If the URL contains an authentication part, the
 * UserCredentials will be set to the {@link HttpClient} instance. Depending on the specified <tt>url</tt> and the
 * settings from the <tt>escidoc-core.properties</tt>, the {@link HttpClient} instance will be configured to use a
 * proxy or not. The <tt>body</tt> will be set to the request and must be encoded as <b>UTF-8</b>.
 * /*  w ww. j ava  2  s  .c  o  m*/
 * @see ConnectionUtility#getHttpClient()
 * @see ConnectionUtility#getHttpClient(HttpParams)
 * 
 * @param client
 *            The {@link HttpClient} to use.
 * @param url
 *            URL of resource.
 * @param body
 *            The post body of HTTP request encoded in UTF-8.
 * @return The response of the request.
 * @throws WebserverSystemException
 *             Thrown if connection failed.
 */
public HttpResponse postRequestURL(final DefaultHttpClient client, final URL url, final String body)
        throws WebserverSystemException {
    String username = null;
    String password = null;
    final String userinfo = url.getUserInfo();
    if (userinfo != null) {
        final String[] loginValues = SPLIT_PATTERN.split(userinfo);
        username = loginValues[0];
        password = loginValues[1];
    }

    return post(client, url, body, null, username, password);
}

From source file:com.gargoylesoftware.htmlunit.WebRequest.java

/**
 * Sets the target URL. The URL may be simplified if needed (for instance eliminating
 * irrelevant path portions like "/./").
 * @param url the target URL/*from  w ww . j  a v  a  2s  .c o  m*/
 */
public void setUrl(URL url) {
    if (url != null) {
        final String path = url.getPath();
        if (path.isEmpty()) {
            url = buildUrlWithNewFile(url, "/" + url.getFile());
        } else if (path.contains("/.")) {
            final String query = (url.getQuery() != null) ? "?" + url.getQuery() : "";
            url = buildUrlWithNewFile(url, removeDots(path) + query);
        }
        url_ = url.toExternalForm();

        // http://john.smith:secret@localhost
        final String userInfo = url.getUserInfo();
        if (userInfo != null) {
            final int splitPos = userInfo.indexOf(':');
            if (splitPos == -1) {
                urlCredentials_ = new UsernamePasswordCredentials(userInfo, "");
            } else {
                final String username = userInfo.substring(0, splitPos);
                final String password = userInfo.substring(splitPos + 1);
                urlCredentials_ = new UsernamePasswordCredentials(username, password);
            }
        }
    } else {
        url_ = null;
    }
}

From source file:com.rabbitmq.http.client.Client.java

private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username,
        final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory,
        final SSLContext sslContext) throws MalformedURLException {
    String theUser = username;/*w w w  .j  av  a2s  .c  o m*/
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = userParts[0];
        }
        if (userParts.length > 1) {
            thePassword = userParts[1];
        }
    }
    final HttpClientBuilder bldr = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword));
    bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")));
    if (sslConnectionSocketFactory != null) {
        bldr.setSSLSocketFactory(sslConnectionSocketFactory);
    }
    if (sslContext != null) {
        bldr.setSslcontext(sslContext);
    }

    HttpClient httpClient = bldr.build();

    // RabbitMQ HTTP API currently does not support challenge/response for PUT methods.
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme);
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setAuthCache(authCache);
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return ctx;
        }
    };
}

From source file:org.openbel.framework.core.protocol.handler.FTPConnector.java

/**
 * Connects and authenticates with the ftp server specified by the
 * {@code ftpUrl}.//from   www  . j a v a  2s  .  co  m
 * 
 * @param ftpUrl {@link URL}, the ftp server url
 * @throws ResourceDownloadError - Thrown if there was an ftp error
 * connecting or authenticating with the ftp server.
 */
public void connectAndLogin(URL ftpUrl) throws ResourceDownloadError {
    if (!ftpUrl.getProtocol().equals("ftp")) {
        throw new InvalidArgument(
                "The ftp connection does not support protocol '" + ftpUrl.getProtocol() + "', only 'ftp'.");
    }

    //connect to ftp server
    String host = ftpUrl.getHost();
    int port = ftpUrl.getPort() == -1 ? DEFAULT_FTP_PORT : ftpUrl.getPort();
    ftpClient = new FTPClient();

    try {
        ftpClient.connect(host, port);
    } catch (Exception e) {
        final String url = ftpUrl.toString();
        final String msg = e.getMessage();
        throw new ResourceDownloadError(url, msg, e);
    }

    //login to user account
    String userInfo = ftpUrl.getUserInfo();
    String username = DEFAULT_USER_NAME;
    String password = "";
    if (userInfo != null) {
        if (userInfo.contains(":")) {
            //provided username & password so parse
            String[] userInfoTokens = userInfo.split("\\:");
            if (userInfoTokens.length == 2) {
                username = userInfoTokens[0];
                password = userInfoTokens[1];
            }
        } else {
            //provided only username
            username = userInfo;

            //prompt for password
            char[] pwd;
            try {
                pwd = PasswordPrompter.getPassword(pwdInputStream, "Connecting to '" + ftpUrl.toString()
                        + "'.  Enter password for user '" + username + "': ");
            } catch (IOException e) {
                final String name = ftpUrl.toString();
                final String msg = e.getMessage();
                throw new ResourceDownloadError(name, msg, e);
            }
            if (pwd == null) {
                password = "";
            } else {
                password = String.valueOf(pwd);
            }
        }
    }

    try {
        if (!ftpClient.login(username, password)) {
            final String name = ftpUrl.toString();
            final String msg = "Login error for username and password";
            throw new ResourceDownloadError(name, msg);
        }
    } catch (IOException e) {
        final String name = ftpUrl.toString();
        final String msg = "Login error for username and password";
        throw new ResourceDownloadError(name, msg, e);
    }

    try {
        ftpClient.pasv();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (IOException e) {
        final String url = ftpUrl.toString();
        final String msg = "Error setting passive mode or transfer type";
        throw new ResourceDownloadError(url, msg, e);
    }
}

From source file:org.aludratest.service.gui.web.selenium.selenium2.AludraSeleniumHttpCommandExecutor.java

/** Constructs a new HttpCommandExecutor for the given remote server.
 * //from  w  w  w. j  a  v  a2  s.  c  o m
 * @param addressOfRemoteServer Remove server, or <code>null</code> to fall back to the System property
 *            <code>webdriver.remote.server</code>, or to <code>http://localhost:4444/wd/hub</code> if system property is not
 *            set. */
public AludraSeleniumHttpCommandExecutor(URL addressOfRemoteServer) {
    try {
        remoteServer = addressOfRemoteServer == null
                ? new URL(System.getProperty("webdriver.remote.server", "http://localhost:4444/wd/hub"))
                : addressOfRemoteServer;
    } catch (MalformedURLException e) {
        throw new WebDriverException(e);
    }

    commandCodec = new JsonHttpCommandCodec();
    responseCodec = new JsonHttpResponseCodec();

    synchronized (AludraSeleniumHttpCommandExecutor.class) {
        if (httpClientFactory == null) {
            httpClientFactory = new HttpClientFactory();
        }
    }

    if (addressOfRemoteServer != null && addressOfRemoteServer.getUserInfo() != null) {
        // Use HTTP Basic auth
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                addressOfRemoteServer.getUserInfo());
        client = httpClientFactory.createHttpClient(credentials);
    } else {
        client = httpClientFactory.getHttpClient();
    }

    // Some machines claim "localhost.localdomain" is the same as "localhost".
    // This assumption is not always true.

    String host = remoteServer.getHost().replace(".localdomain", "");

    targetHost = new HttpHost(host, remoteServer.getPort(), remoteServer.getProtocol());
}

From source file:org.codice.alliance.nsili.client.SampleNsiliClient.java

private URI getEncodedUriFromString(String urlString) throws URISyntaxException, MalformedURLException {
    URL url = new URL(urlString);

    return new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());
}