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.tinygroup.vfs.impl.FtpFileObject.java

private void connectFtpServer() {
    try {//from ww  w. jav a  2s .  c  o  m
        ftpClient = new FTPClient();
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        ftpClient.configure(ftpClientConfig);
        URL url = getURL();
        if (url.getPort() <= 0) {
            ftpClient.connect(url.getHost());
        } else {
            ftpClient.connect(url.getHost(), url.getPort());
        }
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            throw new VFSRuntimeException("?");
        }
        if (url.getUserInfo() != null) {
            String userInfo[] = url.getUserInfo().split(":");
            String userName = null;
            String password = null;
            if (userInfo.length >= 1) {
                userName = userInfo[0];
            }
            if (userInfo.length >= 2) {
                password = userInfo[1];
            }
            if (!ftpClient.login(userName, password)) {
                throw new VFSRuntimeException("" + url.toString());
            }
            if (!ftpClient.setFileType(FTP.BINARY_FILE_TYPE)) {
                throw new VFSRuntimeException("");
            }
            ftpClient.setBufferSize(BUF_SIZE);
            ftpClient.setControlEncoding("utf-8");
        }
    } catch (Exception e) {
        throw new VFSRuntimeException(e);
    }
}

From source file:org.jvnet.hudson.update_center.MavenRepositoryImpl.java

/**
 * Loads a remote repository index (.zip or .gz), convert it to Lucene index and return it.
 *///from  w  w  w.  j  a  va  2  s. c  o  m
private File loadIndex(String id, URL url) throws IOException, UnsupportedExistingLuceneIndexException {
    File dir = new File(new File(System.getProperty("java.io.tmpdir")), "maven-index/" + id);
    File local = new File(dir, "index" + getExtension(url));
    File expanded = new File(dir, "expanded");

    URLConnection con = url.openConnection();
    if (url.getUserInfo() != null) {
        con.setRequestProperty("Authorization",
                "Basic " + new sun.misc.BASE64Encoder().encode(url.getUserInfo().getBytes()));
    }

    if (!expanded.exists() || !local.exists()
            || (local.lastModified() != con.getLastModified() && !offlineIndex)) {
        System.out.println("Downloading " + url);
        // if the download fail in the middle, only leave a broken tmp file
        dir.mkdirs();
        File tmp = new File(dir, "index_" + getExtension(url));
        FileOutputStream o = new FileOutputStream(tmp);
        IOUtils.copy(con.getInputStream(), o);
        o.close();

        if (expanded.exists())
            FileUtils.deleteDirectory(expanded);
        expanded.mkdirs();

        if (url.toExternalForm().endsWith(".gz")) {
            System.out.println("Reconstructing index from " + url);
            FSDirectory directory = FSDirectory.getDirectory(expanded);
            NexusIndexWriter w = new NexusIndexWriter(directory, new NexusAnalyzer(), true);
            FileInputStream in = new FileInputStream(tmp);
            try {
                IndexDataReader dr = new IndexDataReader(in);
                IndexDataReadResult result = dr.readIndex(w, new DefaultIndexingContext(id, id, null, expanded,
                        null, null, NexusIndexer.DEFAULT_INDEX, true));
            } finally {
                IndexUtils.close(w);
                IOUtils.closeQuietly(in);
                directory.close();
            }
        } else if (url.toExternalForm().endsWith(".zip")) {
            Expand e = new Expand();
            e.setSrc(tmp);
            e.setDest(expanded);
            e.execute();
        } else {
            throw new UnsupportedOperationException("Unsupported index format: " + url);
        }

        // as a proof that the expansion was properly completed
        tmp.renameTo(local);
        local.setLastModified(con.getLastModified());
    } else {
        System.out.println("Reusing the locally cached " + url + " at " + local);
    }

    return expanded;
}

From source file:com.ecomnext.rest.ning.NingRestRequestHolder.java

public NingRestRequestHolder(NingRestClient client, String url) {
    try {//w ww. j av  a2s  .  com
        this.client = client;
        URL reference = new URL(url);

        this.url = url;

        String userInfo = reference.getUserInfo();
        if (userInfo != null) {
            this.setAuth(userInfo);
        }
        if (reference.getQuery() != null) {
            this.setQueryString(reference.getQuery());
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.ecomnext.rest.ning.NingRestRequestHolder.java

public NingRestRequestHolder(NingRestClient client, String url, String... params) {
    try {/*from www  . ja  v  a 2  s  .c o  m*/
        this.client = client;

        UriTemplate uriTemplate = UriTemplate.fromTemplate(url);
        if (uriTemplate.getVariables().length != params.length) {
            throw new IllegalArgumentException(
                    "The number of variables in the URL and the number of values do not match");
        }

        for (int i = 0; i < params.length; i++) {
            uriTemplate.set(uriTemplate.getVariables()[i], params[i]);
        }
        url = uriTemplate.expand();

        URL reference = new URL(url);
        this.url = url;

        String userInfo = reference.getUserInfo();
        if (userInfo != null) {
            this.setAuth(userInfo);
        }
        if (reference.getQuery() != null) {
            this.setQueryString(reference.getQuery());
        }
    } catch (MalformedURLException | MalformedUriTemplateException | VariableExpansionException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.siegmar.japtproxy.fetcher.HttpClientConfigurer.java

protected void configureProxy(final HttpClientBuilder httpClientBuilder, final String proxy)
        throws InitializationException {
    final URL proxyUrl;
    try {/*w w  w  .  j  a  v  a 2 s  .  com*/
        proxyUrl = new URL(proxy);
    } catch (final MalformedURLException e) {
        throw new InitializationException("Invalid proxy url", e);
    }

    final String proxyHost = proxyUrl.getHost();
    final int proxyPort = proxyUrl.getPort() != -1 ? proxyUrl.getPort() : proxyUrl.getDefaultPort();

    LOG.info("Set proxy server to '{}:{}'", proxyHost, proxyPort);
    httpClientBuilder.setRoutePlanner(new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort)));

    final String userInfo = proxyUrl.getUserInfo();
    if (userInfo != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), buildCredentials(userInfo));

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }
}

From source file:sce.RESTKBJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {/* w  w w .java 2s . co  m*/
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

        String url = jobDataMap.getString("#url");
        if (url == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }

        URL u = new URL(url);

        //get user credentials from URL, if present
        final String usernamePassword = u.getUserInfo();

        //set the basic authentication credentials for the connection
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }

        //set the url connection, to disconnect if interrupt() is requested
        this.urlConnection = u.openConnection();

        //set the "Accept" header
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+xml");

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(this.urlConnection.getInputStream());

        parseKBResponse(document.getDocumentElement(), context);

        //set of the result is done in the method parseKBresponse, because it is built invoking it iteratively
        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        //context.setResult(result);
        //if notificationEmail is defined in the job data map, then send a notification email to it
        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }

        //trigger the linked jobs of the finished job, depending on the job result [true, false]
        jobChain(context);
        //System.out.println("Instance " + key + " of REST Job returns: " + truncateResult(result));
    } catch (IOException | ParserConfigurationException | SAXException e) {
        e.printStackTrace(System.out);
        throw new JobExecutionException(e);
    }
}

From source file:nya.miku.wishmaster.chans.dobrochan.DobroModule.java

private String sanitizeUrl(String urlStr) {
    if (urlStr == null)
        return null;
    try {/*w  w  w .  j  a v a2 s .c  o m*/
        URL url = new URL(urlStr);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return uri.toURL().toString();
    } catch (Exception e) {
        Logger.e(TAG, "sanitize url", e);
        return urlStr;
    }
}

From source file:org.sonatype.nexus.plugins.p2.repository.proxy.P2ProxyRepositoryImpl.java

private String getBaseMirrorsURL(final URL mirrorsURL) {
    final StringBuilder baseUrl = new StringBuilder();
    baseUrl.append(mirrorsURL.getProtocol()).append("://");
    if (mirrorsURL.getUserInfo() != null) {
        baseUrl.append(mirrorsURL.getUserInfo()).append("@");
    }//from   ww  w.java  2 s.  c o m
    baseUrl.append(mirrorsURL.getHost());
    if (mirrorsURL.getPort() != -1) {
        baseUrl.append(":").append(mirrorsURL.getPort());
    }

    return baseUrl.toString();
}

From source file:cn.com.loopj.android.http.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
 *///from  w ww .j a va 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
            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:sce.RESTAppMetricJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Connection conn = null;/* w  w w.j ava  2s .c  om*/
    try {
        String url1 = prop.getProperty("kb_url");
        //required parameters #url
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String callUrl = jobDataMap.getString("#url"); // url to call when passing result data from SPARQL query
        if (callUrl == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }
        String timeout = jobDataMap.getString("#timeout"); // timeout in ms to use when calling the #url
        if (timeout == null) {
            timeout = "5000";
        }

        //first SPARQL query to retrieve application related metrics and business configurations
        String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(), "UTF-8");
        URL u = new URL(url);
        final String usernamePassword = u.getUserInfo();
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");
        HashMap<String, Object> res = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r = (HashMap<String, Object>) res.get("results");
        ArrayList<Object> list = (ArrayList<Object>) r.get("bindings");
        ArrayList<String[]> lst = new ArrayList<>();
        for (Object obj : list) {
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value");
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value");
            lst.add(new String[] { mn, bc });
        }

        //second SPARQL query to retrieve alerts for SLA
        url = url1 + "?query=" + URLEncoder.encode(getValuesForMetrics(lst), "UTF-8");
        u = new URL(url);
        //java.io.FileWriter fstream = new java.io.FileWriter("/var/www/html/sce/log.txt", false);
        //java.io.BufferedWriter out = new java.io.BufferedWriter(fstream);
        //out.write(getAlertsForSLA(lst, slaTimestamp));
        //out.close();
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");

        //format the result
        HashMap<String, Object> alerts = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r1 = (HashMap<String, Object>) alerts.get("results");
        ArrayList<Object> list1 = (ArrayList<Object>) r1.get("bindings");
        String result = "";

        //MYSQL CONNECTION
        conn = Main.getConnection();
        // conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // use for transactions and at the end call conn.commit() conn.close()
        int counter = 0;

        //SET timestamp FOR MYSQL ROW
        Date dt = new java.util.Date();
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = sdf.format(dt);

        // JSON to be sent to the SM
        JSONArray jsonArray = new JSONArray();

        for (Object obj : list1) {
            //JSON to insert into database
            //JSONArray jsonArray = new JSONArray();
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value"); //metric
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); //metric_name
            String mu = (String) ((HashMap<String, Object>) o.get("mu")).get("value"); //metric_unit
            String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //value
            String mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //metric_timestamp
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business_configuration

            // add these metric value to the json array
            JSONObject object = new JSONObject();
            object.put("business_configuration", bc);
            object.put("metric", sm);
            object.put("metric_name", mn);
            object.put("metric_unit", mu);
            object.put("value", v);
            object.put("metric_timestamp", mt);
            jsonArray.add(object);

            //INSERT THE DATA INTO DATABASE
            PreparedStatement preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_APP_METRICS (timestamp, metric, metric_name, metric_unit, value, metric_timestamp, business_configuration) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?");
            preparedStatement.setString(1, timestamp); // date
            preparedStatement.setString(2, sm); // metric
            preparedStatement.setString(3, mn); // metric_name
            preparedStatement.setString(4, mu); // metric_unit
            preparedStatement.setString(5, v); // value
            preparedStatement.setString(6, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00)
            preparedStatement.setString(7, bc); // business_configuration 
            preparedStatement.setString(8, timestamp); // date
            preparedStatement.executeUpdate();
            preparedStatement.close();

            result += "\nService Metric: " + sm + "\n";
            result += "\nMetric Name: " + mn + "\n";
            result += "\nMetric Unit: " + mu + "\n";
            result += "Timestamp: " + mt + "\n";
            result += "Business Configuration: " + bc + "\n";
            result += "Value" + (counter + 1) + ": " + v + "\n";
            result += "Call Url: " + callUrl + "\n";

            counter++;
        }

        // send the JSON to the CM
        URL tmp_u = new URL(callUrl);
        final String usr_pwd = tmp_u.getUserInfo();
        String usr = null;
        String pwd = null;
        if (usr_pwd != null) {
            usr = usr_pwd.split(":")[0];
            pwd = usr_pwd.split(":")[1];
        }
        sendPostRequest(jsonArray.toJSONString(), callUrl, usr, pwd, Integer.parseInt(timeout));

        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        context.setResult(result);

        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }
        jobChain(context);
    } catch (MalformedURLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (IOException | SQLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (!conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}