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:org.codice.ddf.catalog.content.monitor.DavEntry.java

static String getLocation(String initialLocation, DavEntry parent) {
    String location = initialLocation;
    if (parent != null && !location.startsWith(HTTP)) {
        String parentLocation = parent.getLocation();
        if (parentLocation.endsWith(FORSLASH) && location.startsWith(FORSLASH)) {
            location = location.replaceFirst(FORSLASH, "");
        }/*from  ww w .  j  ava2 s.c  o m*/
        if (!parentLocation.endsWith(FORSLASH) && !location.startsWith(FORSLASH)) {
            location = FORSLASH + location;
        }
        location = parentLocation + location;
    }
    try {
        // URL class performs structural decomposition of location for us
        // URI class performs character encoding, but ONLY via multipart constructors
        // Finally, we have a fully qualified and escaped location for future manipulation
        URL url = new URL(location);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        location = uri.toASCIIString();
    } catch (MalformedURLException | URISyntaxException e) {
        throw new RuntimeException(e);
    }
    return location;
}

From source file:com.dmsl.anyplace.utils.NetworkUtils.java

public static String encodeURL(String urlStr) throws URISyntaxException, MalformedURLException {
    URL url = new URL(urlStr);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());
    url = uri.toURL();/*from  w ww.  j  a  v a 2s.  co m*/
    return url.toString();
}

From source file:de.jwi.ftp.FTPUploader.java

public static String upload(URL url, List files) {
    String rcs = "";

    if (!"ftp".equals(url.getProtocol())) {
        return "not ftp protocol";
    }//from   www.  j  a va  2  s.c  o  m

    String host = url.getHost();
    String userInfo = url.getUserInfo();
    String path = url.getPath();
    String user = null;
    String pass = null;

    int p;
    if ((userInfo != null) && ((p = userInfo.indexOf(':')) > -1)) {
        user = userInfo.substring(0, p);
        pass = userInfo.substring(p + 1);
    } else {
        user = userInfo;
    }

    FTPClient ftp = new FTPClient();

    try {
        int reply;
        ftp.connect(host);

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return "connection refused";
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        return "could not connect to " + host;
    }

    try {
        if (!ftp.login(user, pass)) {
            ftp.logout();
            return "failed to login";
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        ftp.enterLocalPassiveMode();

        rcs = uploadFiles(ftp, path, files);

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        return "connection closed";
    } catch (IOException e) {
        return e.getMessage();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    return rcs;
}

From source file:org.springframework.cloud.config.server.support.AwsCodeCommitCredentialProvider.java

/**
 * This provider can handle uris like/*from w w  w .  ja va 2s. c om*/
 * https://git-codecommit.$AWS_REGION.amazonaws.com/v1/repos/$REPO .
 * @param uri uri to parse
 * @return {@code true} if the URI can be handled
 */
public static boolean canHandle(String uri) {
    if (!hasText(uri)) {
        return false;
    }

    try {
        URL url = new URL(uri);
        URI u = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        if (u.getScheme().equals("https")) {
            String host = u.getHost();
            if (host.endsWith(".amazonaws.com") && host.startsWith("git-codecommit.")) {
                return true;
            }
        }
    } catch (Throwable t) {
        // ignore all, we can't handle it
    }

    return false;
}

From source file:org.apache.jmeter.protocol.http.util.ConversionUtils.java

/**
 * Checks a URL and encodes it if necessary,
 * i.e. if it is not currently correctly encoded.
 * Warning: it may not work on all unencoded URLs.
 * @param url non-encoded URL/* w  w  w  .j a  va2  s . c om*/
 * @return URI which has been encoded as necessary
 * @throws URISyntaxException if parts of the url form a non valid URI
 */
public static URI sanitizeUrl(URL url) throws URISyntaxException {
    try {
        return url.toURI(); // Assume the URL is already encoded
    } catch (URISyntaxException e) { // it's not, so encode it
        return new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef()); // anchor or fragment
    }
}

From source file:sce.ElasticJob.java

public static URL convertToURLEscapingIllegalCharacters(String string) {
    try {//from   www.ja  va  2  s .  co m
        String decodedURL = URLDecoder.decode(string, "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());
        return uri.toURL();
    } catch (MalformedURLException | URISyntaxException | UnsupportedEncodingException e) {
        e.printStackTrace(System.out);
        return null;
    }
}

From source file:LNISmokeTest.java

/**
 * Fix basic auth.//from   ww w.  j a  va 2 s. c om
 * 
 * Set up HTTP basic authentication based on user/password in URL.
 * The HttpURLConnection class should do this itself!
 * 
 * @param url the url
 * @param conn the conn
 */
private static void fixBasicAuth(URL url, HttpURLConnection conn) {
    String userinfo = url.getUserInfo();
    if (userinfo != null) {
        String cui = new String(Base64.encodeBase64(userinfo.getBytes()));
        conn.addRequestProperty("Authorization", "Basic " + cui);
        System.err.println("DEBUG: Sending Basic auth=" + cui);
    }
}

From source file:eu.trentorise.smartcampus.network.RemoteConnector.java

private static String normalizeURL(String uriString) throws RemoteException {
    try {/*from   w w  w.j  a  v a2s.  com*/
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (Exception e) {
        throw new RemoteException(e.getMessage());
    }
    return uriString;
}

From source file:com.redhat.rcm.version.util.InputUtils.java

public static File getFile(final String location, final File downloadsDir, final boolean deleteExisting)
        throws VManException {
    if (client == null) {
        setupClient();/*  w ww . j a v  a  2s. c  o  m*/
    }

    File result = null;

    if (location.startsWith("http")) {
        logger.info("Downloading: '" + location + "'...");

        try {
            final URL url = new URL(location);
            final String userpass = url.getUserInfo();
            if (!isEmpty(userpass)) {
                final AuthScope scope = new AuthScope(url.getHost(), url.getPort());
                final Credentials creds = new UsernamePasswordCredentials(userpass);

                client.getCredentialsProvider().setCredentials(scope, creds);
            }
        } catch (final MalformedURLException e) {
            logger.error("Malformed URL: '" + location + "'", e);
            throw new VManException("Failed to download: %s. Reason: %s", e, location, e.getMessage());
        }

        final File downloaded = new File(downloadsDir, new File(location).getName());
        if (deleteExisting && downloaded.exists()) {
            downloaded.delete();
        }

        if (!downloaded.exists()) {
            HttpGet get = new HttpGet(location);
            OutputStream out = null;
            try {
                HttpResponse response = null;
                // Work around for scenario where we are loading from a server
                // that does a refresh e.g. gitweb
                final int tries = 0;
                do {
                    get = new HttpGet(location);
                    response = client.execute(get);
                    if (response.containsHeader("Cache-control")) {
                        logger.info("Waiting for server to generate cache...");
                        get.abort();
                        try {
                            Thread.sleep(3000);
                        } catch (final InterruptedException e) {
                        }
                    } else {
                        break;
                    }
                } while (tries < MAX_RETRIES);

                if (response.containsHeader("Cache-control")) {
                    throw new VManException(
                            "Failed to read: %s. Cache-control header was present in final attempt.", location);
                }

                final int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    final InputStream in = response.getEntity().getContent();
                    out = new FileOutputStream(downloaded);

                    copy(in, out);
                } else {
                    logger.info("Received status: '{}' while downloading: {}", response.getStatusLine(),
                            location);

                    throw new VManException("Received status: '%s' while downloading: %s",
                            response.getStatusLine(), location);
                }
            } catch (final ClientProtocolException e) {
                throw new VManException("Failed to download: '%s'. Error: %s", e, location, e.getMessage());
            } catch (final IOException e) {
                throw new VManException("Failed to download: '%s'. Error: %s", e, location, e.getMessage());
            } finally {
                closeQuietly(out);
                get.abort();
            }
        }

        result = downloaded;
    } else {
        logger.info("Using local file: '" + location + "'...");

        result = new File(location);
    }

    return result;
}

From source file:com.skcraft.launcher.util.HttpRequest.java

/**
 * URL may contain spaces and other nasties that will cause a failure.
 *
 * @param existing the existing URL to transform
 * @return the new URL, or old one if there was a failure
 *///from   w  w  w. j a  v a 2 s .  c  o m
private static URL reformat(URL existing) {
    try {
        URL url = new URL(existing.toString());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        url = uri.toURL();
        return url;
    } catch (MalformedURLException e) {
        return existing;
    } catch (URISyntaxException e) {
        return existing;
    }
}