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:fr.gael.dhus.datastore.processing.impl.ProcessProductTransfer.java

@Override
public void run(Product product) {
    String url = product.getOrigin();
    if (url == null) {
        return;/* w  w w.  j  ava2s  .c o  m*/
    }
    if (!product.getPath().toString().equals(url)) {
        return;
    }
    File dest = incomingManager.getNewProductIncomingPath();
    Boolean compute_checksum = null;
    try {
        compute_checksum = UnZip.supported((new URL(url)).getPath());
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    LockFactory lf = new NativeFSLockFactory(dest.getParentFile());
    Lock lock = lf.makeLock(".lock-writing");
    try {
        lock.obtain(900000);
    } catch (Exception e) {
        logger.warn("Cannot lock incoming directory - continuing without (" + e.getMessage() + ")");
    }
    try {
        User owner = productDao.getOwnerOfProduct(product);
        actionRecordWritterDao.uploadStart(dest.getPath(), owner.getUsername());
        URL u = new URL(url);
        String userInfos = u.getUserInfo();
        String username = null;
        String password = null;
        if (userInfos != null) {
            String[] infos = userInfos.split(":");
            username = infos[0];
            password = infos[1];
        }

        // Hooks to remove the partially transfered product
        Hook hook = new Hook(dest.getParentFile());
        Runtime.getRuntime().addShutdownHook(hook);
        upload(url, username, password, dest, compute_checksum);
        Runtime.getRuntime().removeShutdownHook(hook);

        String local_filename = ScannerFactory.getFileFromPath(url);
        File productFile = new File(dest, local_filename);
        product.setPath(productFile.toURI().toURL());
        productDao.update(product);
    } catch (Exception e) {
        FileUtils.deleteQuietly(dest);
        throw new DataStoreException("Cannot transfer product \"" + url + "\".", e);
    } finally {
        try {
            lock.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.comcast.magicwand.spells.saucelabs.SauceProvider.java

/**
 * Gets userInfo string from either the URL or system properties
 * @param url URL that might contain userInfo
 * @return String containing userInfo/*from  ww w . ja  v a  2s.  co  m*/
 * @throws FlyingPhoenixException If one of the following is true:
 * <ul>
 * <li>Credentials were NOT specified via system properties or URL</li>
 * <li>Credentials were specified by BOTH system properties and URL</li>
 * <li>Part of the credentials is missing; No username or no API key was found</li>
 * </ul>
 *
 */
protected String getUserInfo(URL url) throws FlyingPhoenixException {
    String urlUserInfo = url.getUserInfo();
    String credsUserInfo = null;

    if ((null != this.username) || (null != this.apiKey)) {
        credsUserInfo = String.format("%s:%s", (null == this.username ? "" : this.username),
                (null == this.apiKey ? "" : this.apiKey));
    }

    // make sure that only 1 set of creds is present
    if ((null != urlUserInfo) && (null != credsUserInfo)) {
        String msg = String.format("URL userInfo '%s' cannot be specified if '%s' or '%s' is defined",
                urlUserInfo, USERNAME, API_KEY);
        throw new FlyingPhoenixException(msg);
    }
    // if both sources of credentials are missing, throw an exception
    else if ((null == urlUserInfo) && (null == credsUserInfo)) {
        String msg = String.format(
                "Credentials are missing. Please include them using '%s' and '%s' properties or as part of a URL.",
                USERNAME, API_KEY);
        throw new FlyingPhoenixException(msg);
    }
    // make sure that both username and api key are present
    else if (nullSafeStartsEnds(credsUserInfo, ":") || nullSafeStartsEnds(urlUserInfo, ":")) {
        String msg = String.format("Either set '%s' and '%s' properties or define userInfo in the url",
                USERNAME, API_KEY);
        throw new FlyingPhoenixException(msg);
    }

    return (null == urlUserInfo) ? credsUserInfo : urlUserInfo;
}

From source file:opendap.threddsHandler.ThreddsCatalogUtil.java

public static String getUrlInfo(URL url) throws InterruptedException {
    String info = "URL:\n";

    info += "    getHost():         " + url.getHost() + "\n";
    info += "    getAuthority():    " + url.getAuthority() + "\n";
    info += "    getFile():         " + url.getFile() + "\n";
    info += "    getSystemPath():         " + url.getPath() + "\n";
    info += "    getDefaultPort():  " + url.getDefaultPort() + "\n";
    info += "    getPort():         " + url.getPort() + "\n";
    info += "    getProtocol():     " + url.getProtocol() + "\n";
    info += "    getQuery():        " + url.getQuery() + "\n";
    info += "    getRef():          " + url.getRef() + "\n";
    info += "    getUserInfo():     " + url.getUserInfo() + "\n";

    return info;//from  w  w  w.j a  va  2 s  .  co  m
}

From source file:sce.RESTXMLJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {/*w  ww  .j  a  v a2s .co  m*/
        //JobKey key = context.getJobDetail().getKey();

        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

        String url = jobDataMap.getString("#url");
        String binding = jobDataMap.getString("#binding");
        if (url == null | binding == null) {
            throw new JobExecutionException("#url and #binding parameters 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();
        //detect and exclude BOM
        //BOMInputStream bomIn = new BOMInputStream(this.urlConnection.getInputStream(), false);
        Document document = docBuilder.parse(this.urlConnection.getInputStream());

        String result = parseXMLResponse(document.getDocumentElement(), binding, context);

        //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:org.fao.geonet.utils.GeonetHttpRequestFactory.java

/**
 * Ceate an XmlRequest from a url./*w  ww .  j  av a 2  s  .  c  o m*/
 *
 * @param url the url of the request.
 * @return the XmlRequest.
 */
public final XmlRequest createXmlRequest(URL url) {
    final int port = url.getPort();
    final XmlRequest request = createXmlRequest(url.getHost(), port, url.getProtocol());

    request.setAddress(url.getPath());
    request.setQuery(url.getQuery());
    request.setFragment(url.getRef());
    request.setUserInfo(url.getUserInfo());
    request.setCookieStore(new BasicCookieStore());
    return request;
}

From source file:sce.ElasticJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {//from www .  j  av a  2s  .c  o  m
        // build the list of queries
        ArrayList<String> queries = new ArrayList<>();

        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String url = jobDataMap.getString("#url");
        String elasticJob = jobDataMap.getString("#elasticJobConstraints");

        int counter = 0;
        String expression = "";
        String j_tmp = "";

        JSONParser parser = new JSONParser();
        JSONObject jsonobject = (JSONObject) parser.parse(elasticJob);
        Iterator<?> keys = jsonobject.keySet().iterator();
        while (keys.hasNext()) {
            String i = (String) keys.next();
            JSONObject jsonobject2 = (JSONObject) jsonobject.get(i);
            Iterator<?> keys2 = jsonobject2.keySet().iterator();
            while (keys2.hasNext()) {
                String j = (String) keys2.next();
                JSONObject jsonobject3 = (JSONObject) jsonobject2.get(j);
                String configuration = "";
                if (jsonobject3.get("slaconfiguration") != null) {
                    configuration = (String) jsonobject3.get("slaconfiguration");
                } else if (jsonobject3.get("bcconfiguration") != null) {
                    configuration = (String) jsonobject3.get("bcconfiguration");
                } else if (jsonobject3.get("vmconfiguration") != null) {
                    configuration = (String) jsonobject3.get("vmconfiguration");
                } else if (jsonobject3.get("anyconfiguration") != null) {
                    configuration = (String) jsonobject3.get("anyconfiguration");
                }
                // add the query to the queries list
                queries.add(getQuery((String) jsonobject3.get("metric"), (String) jsonobject3.get("cfg"),
                        configuration, (String) jsonobject3.get("relation"),
                        String.valueOf(jsonobject3.get("threshold")), String.valueOf(jsonobject3.get("time")),
                        (String) jsonobject3.get("timeselect")));
                String op = jsonobject3.get("match") != null ? (String) jsonobject3.get("match") : "";
                switch (op) {
                case "":
                    break;
                case "any":
                    op = "OR(";
                    break;
                case "all":
                    op = "AND(";
                    break;
                }
                String closed_parenthesis = " ";
                int num_closed_parenthesis = !j_tmp.equals("") ? Integer.parseInt(j_tmp) - Integer.parseInt(j)
                        : 0;
                for (int parenthesis = 0; parenthesis < num_closed_parenthesis; parenthesis++) {
                    closed_parenthesis += " )";
                }
                expression += op + " " + counter + closed_parenthesis;
                j_tmp = j;
                counter++;
            }
        }
        ExpressionTree calc = new ExpressionTree(new Scanner(expression), queries);
        if (calc.evaluate()) {
            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());
                    }
                });
            }
            //call the callUrl
            URLConnection connection = u.openConnection();
            getUrlContents(connection);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new JobExecutionException(e);
    }
}

From source file:org.commonjava.aprox.model.core.RemoteRepository.java

public void calculateFields() {
    URL url = null;
    try {//from w ww. j a  v a 2s  . c  o m
        url = new URL(this.url);
    } catch (final MalformedURLException e) {
        LOGGER.error("Failed to parse repository URL: '{}'. Reason: {}", e, this.url, e.getMessage());
    }

    if (url == null) {
        return;
    }

    final String userInfo = url.getUserInfo();
    if (userInfo != null && user == null && password == null) {
        user = userInfo;
        password = null;

        int idx = userInfo.indexOf(':');
        if (idx > 0) {
            user = userInfo.substring(0, idx);
            password = userInfo.substring(idx + 1);

            final StringBuilder sb = new StringBuilder();
            idx = this.url.indexOf("://");
            sb.append(this.url.substring(0, idx + 3));

            idx = this.url.indexOf("@");
            if (idx > 0) {
                sb.append(this.url.substring(idx + 1));
            }

            this.url = sb.toString();
        }
    }

    host = url.getHost();
    if (url.getPort() < 0) {
        port = url.getProtocol().equals("https") ? 443 : 80;
    } else {
        port = url.getPort();
    }
}

From source file:eu.markov.jenkins.plugin.mvnmeta.MavenMetadataParameterDefinition.java

private MavenMetadataVersions getArtifactMetadata() {
    InputStream input = null;//from   ww  w  . j a  v a2  s  .c  o m
    try {
        URL url = new URL(getArtifactUrlForPath("maven-metadata.xml"));

        LOGGER.finest("Requesting metadata from URL: " + url.toExternalForm());

        URLConnection conn = url.openConnection();

        if (StringUtils.isNotBlank(url.getUserInfo())) {
            LOGGER.finest("Using implicit UserInfo");
            String encodedAuth = new String(Base64.encodeBase64(url.getUserInfo().getBytes(UTF8)), UTF8);
            conn.addRequestProperty("Authorization", "Basic " + encodedAuth);
        }

        if (StringUtils.isNotBlank(this.username) && StringUtils.isNotBlank(this.password)) {
            LOGGER.finest("Using explicit UserInfo");
            String userpassword = username + ":" + password;
            String encodedAuthorization = new String(Base64.encodeBase64(userpassword.getBytes(UTF8)), UTF8);
            conn.addRequestProperty("Authorization", "Basic " + encodedAuthorization);
        }

        input = conn.getInputStream();
        JAXBContext context = JAXBContext.newInstance(MavenMetadataVersions.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        MavenMetadataVersions metadata = (MavenMetadataVersions) unmarshaller.unmarshal(input);

        if (sortOrder == SortOrder.DESC) {
            Collections.reverse(metadata.versioning.versions);
        }
        metadata.versioning.versions = filterVersions(metadata.versioning.versions);

        return metadata;
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Could not parse maven-metadata.xml", e);
        MavenMetadataVersions result = new MavenMetadataVersions();
        result.versioning.versions.add("<" + e.getClass().getName() + ": " + e.getMessage() + ">");
        return result;
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:com.centurylink.mdw.util.HttpHelper.java

public HttpHelper(URL url) {
    this.url = url;
    if (url.getUserInfo() != null) {
        int colon = url.getUserInfo().indexOf(':');
        if (colon > 0) {
            this.user = url.getUserInfo().substring(0, colon);
            this.password = url.getUserInfo().substring(colon + 1);
        }/* w  w w .ja  v a 2  s . c om*/
    }
}