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:adams.flow.sink.DownloadFile.java

/**
 * Executes the flow item./*w w  w.ja v  a2  s .com*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
@MixedCopyright(author = "http://stackoverflow.com/users/2920131/lboix", license = License.CC_BY_SA_3, url = "http://stackoverflow.com/a/13122190", note = "handling basic authentication")
protected String doExecute() {
    String result;
    URL url;
    BufferedInputStream input;
    BufferedOutputStream output;
    FileOutputStream fos;
    byte[] buffer;
    int len;
    int count;
    URLConnection conn;
    String basicAuth;

    input = null;
    output = null;
    fos = null;
    try {
        if (m_InputToken.getPayload() instanceof String)
            url = new URL((String) m_InputToken.getPayload());
        else
            url = (URL) m_InputToken.getPayload();

        conn = url.openConnection();
        if (url.getUserInfo() != null) {
            basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
            conn.setRequestProperty("Authorization", basicAuth);
        }
        input = new BufferedInputStream(conn.getInputStream());
        fos = new FileOutputStream(m_OutputFile.getAbsoluteFile());
        output = new BufferedOutputStream(fos);
        buffer = new byte[m_BufferSize];
        count = 0;
        while ((len = input.read(buffer)) > 0) {
            count++;
            output.write(buffer, 0, len);
            if (count % 100 == 0)
                output.flush();
        }
        output.flush();

        result = null;
    } catch (Exception e) {
        result = handleException("Problem downloading '" + m_InputToken.getPayload() + "': ", e);
    } finally {
        FileUtils.closeQuietly(input);
        FileUtils.closeQuietly(output);
        FileUtils.closeQuietly(fos);
    }

    return result;
}

From source file:podd.resources.util.RemoteFileHelper.java

private Datastore checkValidDataStore(URL url) throws DataAccessException {
    return checkValidDataStore(new Datastore(url.getHost(), url.getPort(), url.getUserInfo(), ""));
}

From source file:org.apache.hadoop.hive.ql.udf.generic.GenericUDTFParseUrlTuple.java

private String evaluate(URL url, int index) {
    if (url == null || index < 0 || index >= partnames.length) {
        return null;
    }//from   ww  w.j ava 2  s  .  co  m

    switch (partnames[index]) {
    case HOST:
        return url.getHost();
    case PATH:
        return url.getPath();
    case QUERY:
        return url.getQuery();
    case REF:
        return url.getRef();
    case PROTOCOL:
        return url.getProtocol();
    case FILE:
        return url.getFile();
    case AUTHORITY:
        return url.getAuthority();
    case USERINFO:
        return url.getUserInfo();
    case QUERY_WITH_KEY:
        return evaluateQuery(url.getQuery(), paths[index]);
    case NULLNAME:
    default:
        return null;
    }
}

From source file:org.springframework.richclient.image.Handler.java

protected URLConnection openConnection(URL url) throws IOException {
    if (!StringUtils.hasText(url.getPath())) {
        throw new MalformedURLException("must provide an image key.");
    } else if (StringUtils.hasText(url.getHost())) {
        throw new MalformedURLException("host part should be empty.");
    } else if (url.getPort() != -1) {
        throw new MalformedURLException("port part should be empty.");
    } else if (StringUtils.hasText(url.getQuery())) {
        throw new MalformedURLException("query part should be empty.");
    } else if (StringUtils.hasText(url.getRef())) {
        throw new MalformedURLException("ref part should be empty.");
    } else if (StringUtils.hasText(url.getUserInfo())) {
        throw new MalformedURLException("user info part should be empty.");
    }/*from www .j  a va2  s . c om*/
    urlHandlerImageSource.getImage(url.getPath());
    Resource image = urlHandlerImageSource.getImageResource(url.getPath());
    if (image != null)
        return image.getURL().openConnection();

    throw new IOException("null image returned for key [" + url.getFile() + "].");
}

From source file:com.piusvelte.webcaster.MainActivity.java

@Override
public void openMedium(int parent, int child) {
    Medium m = getMediaAt(parent).get(child);
    final ContentMetadata contentMetadata = new ContentMetadata();
    contentMetadata.setTitle(m.getFile().substring(m.getFile().lastIndexOf(File.separator) + 1));

    if (mediaProtocolMessageStream != null) {
        String urlStr = String.format("http://%s/%s", mediaHost, m.getFile());

        try {/*w ww  . java  2  s . c om*/
            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();
            MediaProtocolCommand cmd = mediaProtocolMessageStream.loadMedia(url.toString(), contentMetadata,
                    true);
            cmd.setListener(new MediaProtocolCommand.Listener() {
                @Override
                public void onCompleted(MediaProtocolCommand mPCommand) {
                    btnPlay.setText(getString(R.string.pause) + " " + contentMetadata.getTitle());
                    onSetVolume(0.5);
                }

                @Override
                public void onCancelled(MediaProtocolCommand mPCommand) {
                    btnPlay.setText(getString(R.string.play) + " " + contentMetadata.getTitle());
                }
            });
        } catch (IllegalStateException e) {
            Log.e(TAG, "Problem occurred with MediaProtocolCommand during loading", e);
        } catch (IOException e) {
            Log.e(TAG, "Problem opening MediaProtocolCommand during loading", e);
        } catch (URISyntaxException e) {
            Log.e(TAG, "Problem encoding URI: " + urlStr, e);
        }
    } else {
        Toast.makeText(this, "No message stream", Toast.LENGTH_SHORT).show();
    }
}

From source file:dbf.parser.pkg2.handler.java

private void sendPost(String json) throws Exception {
    System.out.println("Adding url ..");
    String url = "http://shorewindowcleaning:withwindows@ironside.ddns.net:5984/shorewindowcleaning/_bulk_docs";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Content-Type", "application/json");
    String basicAuth = "Basic " + new String(new Base64().encode(obj.getUserInfo().getBytes()));
    con.setRequestProperty("Authorization", basicAuth);

    //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
    System.out.println("Adding output ..");
    // Send post request
    con.setDoOutput(true);/*w  ww . j ava 2s.  c om*/
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
    wr.write(json);
    wr.flush();
    wr.close();
    System.out.println("geting content ..");
    // System.out.println(con.getResponseMessage());
    int responseCode = con.getResponseCode();
    System.out.println("Adding checking response ..");
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + json);
    System.out.println("Response Code : " + responseCode);
    System.out.println(con.getResponseMessage());
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

From source file:com.novartis.opensource.yada.adaptor.RESTAdaptor.java

/**
 * Gets the input stream from the {@link URLConnection} and stores it in 
 * the {@link YADAQueryResult} in {@code yq}
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 *//*from  w w  w.  ja va2  s  .c  om*/
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    boolean isPostPutPatch = this.method.equals(YADARequest.METHOD_POST)
            || this.method.equals(YADARequest.METHOD_PUT) || this.method.equals(YADARequest.METHOD_PATCH);
    resetCountParameter(yq);
    int rows = yq.getData().size() > 0 ? yq.getData().size() : 1;
    /*
     * Remember:
     * A row is an set of YADA URL parameter values, e.g.,
     * 
     *  x,y,z in this:      
     *    ...yada/q/queryname/p/x,y,z
     *  so 1 row
     *    
     *  or each of {col1:x,col2:y,col3:z} and {col1:a,col2:b,col3:c} in this:
     *    ...j=[{qname:queryname,DATA:[{col1:x,col2:y,col3:z},{col1:a,col2:b,col3:c}]}]
     *  so 2 rows
     */
    for (int row = 0; row < rows; row++) {
        String result = "";

        // creates result array and assigns it
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();

        String urlStr = yq.getUrl(row);

        for (int i = 0; i < yq.getParamCount(row); i++) {
            Matcher m = PARAM_URL_RX.matcher(urlStr);
            if (m.matches()) {
                String param = yq.getVals(row).get(i);
                urlStr = urlStr.replaceFirst(PARAM_SYMBOL_RX, m.group(1) + param);
            }
        }

        l.debug("REST url w/params: [" + urlStr + "]");
        try {
            URL url = new URL(urlStr);
            URLConnection conn = null;

            if (this.hasProxy()) {
                String[] proxyStr = this.proxy.split(":");
                Proxy proxySvr = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyStr[0], Integer.parseInt(proxyStr[1])));
                conn = url.openConnection(proxySvr);
            } else {
                conn = url.openConnection();
            }

            // basic auth
            if (url.getUserInfo() != null) {
                //TODO issue with '@' sign in pw, must decode first
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                conn.setRequestProperty("Authorization", basicAuth);
            }

            // cookies
            if (yq.getCookies() != null && yq.getCookies().size() > 0) {
                String cookieStr = "";
                for (HttpCookie cookie : yq.getCookies()) {
                    cookieStr += cookie.getName() + "=" + cookie.getValue() + ";";
                }
                conn.setRequestProperty("Cookie", cookieStr);
            }

            if (yq.getHttpHeaders() != null && yq.getHttpHeaders().length() > 0) {
                l.debug("Processing custom headers...");
                @SuppressWarnings("unchecked")
                Iterator<String> keys = yq.getHttpHeaders().keys();
                while (keys.hasNext()) {
                    String name = keys.next();
                    String value = yq.getHttpHeaders().getString(name);
                    l.debug("Custom header: " + name + " : " + value);
                    conn.setRequestProperty(name, value);
                    if (name.equals(X_HTTP_METHOD_OVERRIDE) && value.equals(YADARequest.METHOD_PATCH)) {
                        l.debug("Resetting method to [" + YADARequest.METHOD_POST + "]");
                        this.method = YADARequest.METHOD_POST;
                    }
                }
            }

            HttpURLConnection hConn = (HttpURLConnection) conn;
            if (!this.method.equals(YADARequest.METHOD_GET)) {
                hConn.setRequestMethod(this.method);
                if (isPostPutPatch) {
                    //TODO make YADA_PAYLOAD case-insensitive and create an alias for it, e.g., ypl
                    // NOTE: YADA_PAYLOAD is a COLUMN NAME found in a JSONParams DATA object.  It 
                    //       is not a YADA param
                    String payload = yq.getDataRow(row).get(YADA_PAYLOAD)[0];
                    hConn.setDoOutput(true);
                    OutputStreamWriter writer;
                    writer = new OutputStreamWriter(conn.getOutputStream());
                    writer.write(payload.toString());
                    writer.flush();
                }
            }

            // debug
            Map<String, List<String>> map = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                l.debug("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
            }

            try (BufferedReader in = new BufferedReader(new InputStreamReader(hConn.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    result += String.format("%1s%n", inputLine);
                }
            }
            yqr.addResult(row, result);
        } catch (MalformedURLException e) {
            String msg = "Unable to access REST source due to a URL issue.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (IOException e) {
            String msg = "Unable to read REST response.";
            throw new YADAAdaptorExecutionException(msg, e);
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * <p>Encodes illegal characters in the specified URL's path, query string and anchor according to the URL
 * encoding rules observed in real browsers.</p>
 *
 * <p>For example, this method changes <tt>"http://first/?a=b c"</tt> to <tt>"http://first/?a=b%20c"</tt>.</p>
 *
 * @param url the URL to encode/*from   ww w . ja  va  2  s.  co  m*/
 * @param minimalQueryEncoding whether or not to perform minimal query encoding, like IE does
 * @param charset the charset
 * @return the encoded URL
 */
public static URL encodeUrl(final URL url, final boolean minimalQueryEncoding, final String charset) {
    if (!isNormalUrlProtocol(URL_CREATOR.getProtocol(url))) {
        return url; // javascript:, about:, data: and anything not supported like foo:
    }

    try {
        String path = url.getPath();
        if (path != null) {
            path = encode(path, PATH_ALLOWED_CHARS, "UTF-8");
        }
        String query = url.getQuery();
        if (query != null) {
            if (minimalQueryEncoding) {
                query = org.apache.commons.lang3.StringUtils.replace(query, " ", "%20");
            } else {
                query = encode(query, QUERY_ALLOWED_CHARS, charset);
            }
        }
        String anchor = url.getRef();
        if (anchor != null) {
            anchor = encode(anchor, ANCHOR_ALLOWED_CHARS, "UTF-8");
        }
        return createNewUrl(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), path, anchor,
                query);
    } catch (final MalformedURLException e) {
        // Impossible... I think.
        throw new RuntimeException(e);
    }
}

From source file:com.enonic.vertical.engine.PresentationEngine.java

private Document getURL(String address, String encoding, int timeoutMs) {
    InputStream in = null;/*  www  . j  a va  2 s .c  o m*/
    BufferedReader reader = null;
    Document result;
    try {
        URL url = new URL(address);
        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(timeoutMs > 0 ? timeoutMs : DEFAULT_CONNECTION_TIMEOUT);
        urlConn.setRequestProperty("User-Agent",
                VerticalProperties.getVerticalProperties().getDataSourceUserAgent());
        String userInfo = url.getUserInfo();
        if (StringUtils.isNotBlank(userInfo)) {
            String userInfoBase64Encoded = new String(Base64.encodeBase64(userInfo.getBytes()));
            urlConn.setRequestProperty("Authorization", "Basic " + userInfoBase64Encoded);
        }
        in = urlConn.getInputStream();

        // encoding == null: XML file
        if (encoding == null) {
            result = XMLTool.domparse(in);
        } else {
            StringBuffer sb = new StringBuffer(1024);
            reader = new BufferedReader(new InputStreamReader(in, encoding));
            char[] line = new char[1024];
            int charCount = reader.read(line);
            while (charCount > 0) {
                sb.append(line, 0, charCount);
                charCount = reader.read(line);
            }

            result = XMLTool.createDocument("urlresult");
            Element root = result.getDocumentElement();
            XMLTool.createCDATASection(result, root, sb.toString());
        }
    } catch (SocketTimeoutException ste) {
        String message = "Socket timeout when trying to get url: " + address;
        VerticalEngineLogger.warn(this.getClass(), 0, message, null);
        result = null;
    } catch (IOException ioe) {
        String message = "Failed to get URL: %t";
        VerticalEngineLogger.warn(this.getClass(), 0, message, ioe);
        result = null;
    } catch (RuntimeException re) {
        String message = "Failed to get URL: %t";
        VerticalEngineLogger.warn(this.getClass(), 0, message, re);
        result = null;
    } finally {
        try {
            if (reader != null) {
                reader.close();
            } else if (in != null) {
                in.close();
            }
        } catch (IOException ioe) {
            String message = "Failed to close URL connection: %t";
            VerticalEngineLogger.warn(this.getClass(), 0, message, ioe);
        }
    }

    if (result == null) {
        result = XMLTool.createDocument("noresult");
    }

    return result;
}

From source file:adams.flow.transformer.DownloadContent.java

/**
 * Executes the flow item.//w ww .j  a v a 2 s. co m
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
@MixedCopyright(author = "http://stackoverflow.com/users/2920131/lboix", license = License.CC_BY_SA_3, url = "http://stackoverflow.com/a/13122190", note = "handling basic authentication")
protected String doExecute() {
    String result;
    URL url;
    BufferedInputStream input;
    byte[] buffer;
    byte[] bufferSmall;
    int len;
    StringBuilder content;
    URLConnection conn;
    String basicAuth;

    input = null;
    content = new StringBuilder();
    try {
        if (m_InputToken.getPayload() instanceof String)
            url = new URL((String) m_InputToken.getPayload());
        else if (m_InputToken.getPayload() instanceof BaseURL)
            url = ((BaseURL) m_InputToken.getPayload()).urlValue();
        else
            url = (URL) m_InputToken.getPayload();

        conn = url.openConnection();
        if (url.getUserInfo() != null) {
            basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
            conn.setRequestProperty("Authorization", basicAuth);
        }
        input = new BufferedInputStream(conn.getInputStream());
        buffer = new byte[m_BufferSize];
        while ((len = input.read(buffer)) > 0) {
            if (len < m_BufferSize) {
                bufferSmall = new byte[len];
                System.arraycopy(buffer, 0, bufferSmall, 0, len);
                content.append(new String(bufferSmall));
            } else {
                content.append(new String(buffer));
            }
        }

        m_OutputToken = new Token(content.toString());
        content = null;
        result = null;
    } catch (Exception e) {
        result = handleException("Problem downloading '" + m_InputToken.getPayload() + "': ", e);
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (Exception e) {
            // ignored
        }
    }

    return result;
}