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:com.cladonia.xngreditor.URLUtilities.java

/**
 * Get the username from the user info block of this URL.
 * //  w  ww.  j  a  v  a  2 s  .co  m
 * @param url the url.
 * 
 * @return the username or null if not found.
 */
public static String getUsername(URL url) {
    String username = null;

    if (url != null) {
        String user = url.getUserInfo();

        if (user != null && user.trim().length() > 0) {
            int index = user.indexOf(':');

            if (index != -1) {
                username = user.substring(0, index);
            }
        }
    }

    //      System.out.println( "URLUtilities.getUsername( "+url+") ["+username+"]");

    return username;
}

From source file:org.talend.datatools.xml.utils.SchemaPopulationUtil.java

public static XSModel getXSModel(String fileName) throws URISyntaxException, MalformedURLException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from w  ww  . java 2s. c  o  m
    URI uri = null;
    File f = new File(fileName);
    if (f.exists()) {
        uri = f.toURI();
    } else {
        URL url = new URL(fileName);
        uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
    }

    // Then try to parse the input string as a url in web.
    if (uri == null) {
        uri = new URI(fileName);
    }

    // fixed a bug when parse one file contians Franch ,maybe need modification
    XMLSchemaLoader xsLoader = new XMLSchemaLoader();
    XSModel xsModel = xsLoader.loadURI(uri.toString());
    if (xsModel == null) {
        try {
            Grammar loadGrammar = xsLoader.loadGrammar(
                    new XMLInputSource(null, uri.toString(), null, new FileInputStream(f), "ISO-8859-1"));
            xsModel = ((XSGrammar) loadGrammar).toXSModel();
        } catch (XNIException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return xsModel;
}

From source file:at.fhooe.mcm.webdav.WebDavInterface.java

/**
 * {@inheritDoc}/*from   w  ww .j a va2s  . c o m*/
 */
WebDavInterface(String url) throws Exception {
    try {
        URL x = new URL(url);
        String userInfo = x.getUserInfo();
        int sepIdx = userInfo.lastIndexOf(':');
        if (sepIdx != -1) {
            user = userInfo.substring(0, sepIdx);
            pw = userInfo.substring(sepIdx + 1);

            String basePath = url;
            if (!basePath.endsWith("/")) {
                basePath = basePath + "/";
            }

            this.url = "http://" + x.getHost() + "/account/webdav.php";

            System.out.println(basePath);

        } else {
            throw new Exception("Server url not correctly configured!"
                    + "Needs http://USER:PASSWORD@privatenotes.dyndns-server.com/webdav2/USER");
        }
    } catch (MalformedURLException e) {
        throw new Exception("Server url not correctly configured!"
                + "Needs http://USER:PASSWORD@privatenotes.dyndns-server.com/webdav2/USER");
    }
}

From source file:cn.openwatch.internal.http.loopj.AsyncHttpClient.java

/**
 * Will encode url, if not disabled, and adds params on the end of it
 *
 * @param url             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
 */// w w  w .j  a v a 2  s  .  c  o  m
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
        }
    }

    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:org.hypertopic.RESTDatabase.java

public URL getURL(String path) throws Exception {
    URL url = new URL(this.baseUrl + path);
    return new URL(new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef()).toASCIIString());
}

From source file:com.bose.aem.spring.config.ConfigClientProperties.java

private String[] extractCredentials() {
    String[] result = new String[3];
    String uri = this.uri;
    result[2] = uri;//ww  w. j a  v  a  2 s. c o  m
    String[] creds = getUsernamePassword();
    result[0] = creds[0];
    result[1] = creds[1];
    try {
        URL url = new URL(uri);
        String userInfo = url.getUserInfo();
        if (StringUtils.isEmpty(userInfo) || ":".equals(userInfo)) {
            return result;
        }
        String bare = UriComponentsBuilder.fromHttpUrl(uri).userInfo(null).build().toUriString();
        result[2] = bare;
        if (!userInfo.contains(":")) {
            userInfo = userInfo + ":";
        }
        String[] split = userInfo.split(":");
        result[0] = split[0];
        result[1] = split[1];
        if (creds[1] != null) {
            // Explicit username / password takes precedence
            result[1] = creds[1];
            if ("user".equals(creds[0])) {
                // But the username can be overridden
                result[0] = split[0];
            }
        }
        return result;
    } catch (MalformedURLException e) {
        throw new IllegalStateException("Invalid URL: " + uri);
    }
}

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * Performs a simple get on the given URL
 *///from ww  w  .  j  ava2s.  c o  m
public static void doGet(URL url) {
    try {
        if (mockMode)
            return;
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        if (url.getUserInfo() != null) {
            String encoding = DatatypeConverter
                    .printBase64Binary(url.getUserInfo().getBytes(StandardCharsets.US_ASCII));
            urlc.setRequestProperty("Authorization", "Basic " + encoding);
        }
        urlc.connect();
        checkResponseCode(urlc);
    } catch (IOException e) {
        warn("An error occurred posting data to " + url + ". Please check that Solr is running.");
    }
}

From source file:com.macdonst.ftpclient.FtpClient.java

/**
 * Creates, connects and logs into a FTP server
 * @param url of the FTP server/* w  w w  .j  a va2  s.  c om*/
 * @return an instance of FTPClient
 * @throws IOException
 */
private FTPClient setup(URL url) throws IOException {
    FTPClient f = new FTPClient();
    f.connect(url.getHost(), extractPort(url));

    StringTokenizer tok = new StringTokenizer(url.getUserInfo(), ":");
    f.login(tok.nextToken(), tok.nextToken());

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

    return f;
}

From source file:org.apache.axis.utils.XMLUtils.java

/**
 * Utility to get the bytes at a protected uri
 *
 * This will retrieve the URL if a username and password are provided.
 * The java.net.URL class does not do Basic Authentication, so we have to
 * do it manually in this routine./*from www  .  jav  a 2 s .co  m*/
 *
 * If no username is provided, we create an InputSource from the uri
 * and let the InputSource go fetch the contents.
 *
 * @param uri the resource to get
 * @param username basic auth username
 * @param password basic auth password
 */
private static InputSource getInputSourceFromURI(String uri, String username, String password)
        throws IOException, ProtocolException, UnsupportedEncodingException {
    URL wsdlurl = null;
    try {
        wsdlurl = new URL(uri);
    } catch (MalformedURLException e) {
        // we can't process it, it might be a 'simple' foo.wsdl
        // let InputSource deal with it
        return new InputSource(uri);
    }

    // if no authentication, just let InputSource deal with it
    if (username == null && wsdlurl.getUserInfo() == null) {
        return new InputSource(uri);
    }

    // if this is not an HTTP{S} url, let InputSource deal with it
    if (!wsdlurl.getProtocol().startsWith("http")) {
        return new InputSource(uri);
    }

    URLConnection connection = wsdlurl.openConnection();
    // Does this work for https???
    if (!(connection instanceof HttpURLConnection)) {
        // can't do http with this URL, let InputSource deal with it
        return new InputSource(uri);
    }
    HttpURLConnection uconn = (HttpURLConnection) connection;
    String userinfo = wsdlurl.getUserInfo();
    uconn.setRequestMethod("GET");
    uconn.setAllowUserInteraction(false);
    uconn.setDefaultUseCaches(false);
    uconn.setDoInput(true);
    uconn.setDoOutput(false);
    uconn.setInstanceFollowRedirects(true);
    uconn.setUseCaches(false);

    // username/password info in the URL overrides passed in values
    String auth = null;
    if (userinfo != null) {
        auth = userinfo;
    } else if (username != null) {
        auth = (password == null) ? username : username + ":" + password;
    }

    if (auth != null) {
        uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding)));
    }

    uconn.connect();

    return new InputSource(uconn.getInputStream());
}

From source file:edu.si.services.sidora.rest.batch.beans.BatchRequestControllerBean.java

/**
 * Check Resource MimeType using Apache Tika
 * @param exchange//w  w  w.j  a va  2  s.co m
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public void getMIMEType(Exchange exchange) throws URISyntaxException, MalformedURLException {

    /**
     * TODO:
     *
     * Need to make sure that mimetypes are consistent with what's used in workbench.
     * See link for workbench mimetype list
     *
     * https://github.com/Smithsonian/sidora-workbench/blob/master/workbench/includes/utils.inc#L1119
     *
     */

    out = exchange.getIn();

    URL url = new URL(out.getHeader("resourceFile", String.class));

    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    String resourceFile = uri.toASCIIString();
    String resourceFileExt = FilenameUtils.getExtension(resourceFile);
    String mimeType = null;

    if (resourceFileExt.equalsIgnoreCase("nef")) {
        mimeType = "image/x-nikon-nef";
    } else if (resourceFileExt.equalsIgnoreCase("dng")) {
        mimeType = "image/x-adobe-dng";
    } else {
        LOG.debug("Checking {} for MIME Type", resourceFile);

        mimeType = new Tika().detect(resourceFile);
    }

    LOG.debug("Batch Process " + resourceFile + " || MIME=" + mimeType);

    out.setHeader("dsMIME", mimeType);
}