Example usage for java.net Authenticator setDefault

List of usage examples for java.net Authenticator setDefault

Introduction

In this page you can find the example usage for java.net Authenticator setDefault.

Prototype

public static synchronized void setDefault(Authenticator a) 

Source Link

Document

Sets the authenticator that will be used by the networking code when a proxy or an HTTP server asks for authentication.

Usage

From source file:sce.RESTCheckSLAJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Connection conn = null;//  w w w  .  j  av  a  2 s . com
    try {
        //required parameters #url, #slaId, #slaTimestamp
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String url1 = jobDataMap.getString("#url"); // e.g. http://kb-read:icaro@192.168.0.106:8080/IcaroKB/sparql
        if (url1 == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }
        String slaId = jobDataMap.getString("#slaId");
        if (slaId == null) {
            throw new JobExecutionException("#slaId parameter must be not null");
        }
        String slaTimestamp = jobDataMap.getString("#slaTimestamp"); // e.g. 2014-09-10T16:30:00
        //if timestamp is not defined, use current
        if (slaTimestamp == null) {
            //throw new JobExecutionException("#slaTimestamp parameter must be not null");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            slaTimestamp = sdf.format(new Date());
        }
        //first SPARQL query to retrieve services, metrics and thresholds in the SLA
        String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(slaId), "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");
        int bindings = list.size();
        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 v = (String) ((HashMap<String, Object>) o.get("v")).get("value");
            String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value");
            String p = (String) ((HashMap<String, Object>) o.get("p")).get("value");
            String callUrl = (String) ((HashMap<String, Object>) o.get("act")).get("value");
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value");
            lst.add(new String[] { mn, v, sm, p, callUrl, bc });
        }

        //second SPARQL query to retrieve alerts for SLA
        url = url1 + "?query=" + URLEncoder.encode(getAlertsForSLA(lst, slaTimestamp), "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");
        //ArrayList<String[]> lst1 = new ArrayList<>();
        //int counter = 0;
        String vv_temp;
        String result = "";

        //LOAD QUARTZ PROPERTIES
        Properties prop = new Properties();
        prop.load(this.getClass().getResourceAsStream("quartz.properties"));

        //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);

        //Hashmap to store callUrls to be called in case of alarm
        HashMap<String, Integer> callUrlMap = new HashMap<>();

        // JSON to be sent to the SM
        JSONArray jsonArray = new JSONArray();
        boolean notify = false; // whether notify the SM or not

        // Business Configuration
        String bc = "";

        for (Object obj : list1) {
            //JSON to insert into database
            //JSONArray jsonArray = new JSONArray();
            boolean alarm; //set to true if there is an alarm on sla

            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String y = (String) ((HashMap<String, Object>) o.get("y")).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 mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //timestamp
            //String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value");
            String vm = (String) ((HashMap<String, Object>) o.get("vm")).get("value"); //virtual_machine
            String vmn = (String) ((HashMap<String, Object>) o.get("vmn")).get("value"); //virtual_machine_name
            String hm = o.get("hm") != null ? (String) ((HashMap<String, Object>) o.get("hm")).get("value")
                    : ""; //host_machine
            //String na = (String) ((HashMap<String, Object>) o.get("na")).get("value");
            //String ip = (String) ((HashMap<String, Object>) o.get("ip")).get("value");
            String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //threshold
            String p = (String) ((HashMap<String, Object>) o.get("p")).get("value"); //relation (<,>,=)
            vv_temp = (String) ((HashMap<String, Object>) o.get("vv")).get("value"); //value
            String callUrl = (String) ((HashMap<String, Object>) o.get("callUrl")).get("value"); //call url
            bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business configuration

            /*JSONObject object = new JSONObject();
             object.put("metric", y);
             object.put("metric_name", mn);
             object.put("metric_unit", mu);
             object.put("timestamp", mt);
             //object.put("service", sm);
             object.put("virtual_machine", vm);
             object.put("virtual_machine_name", vmn);
             object.put("host_machine", hm);
             object.put("value", vv_temp);
             object.put("relation", getProperty(p));
             object.put("threshold", v);
             jsonArray.add(object);*/
            //CHECK IF THE SLA IS VIOLATED
            alarm = checkSLA(Double.parseDouble(vv_temp), Double.parseDouble(v), p);

            // if alarm is true, then put the callUrl in a HashMap
            // and build the json object to be added to the json array to be sent to the SM
            if (alarm) {
                callUrlMap.put(callUrl, 1);

                notify = true;
                JSONObject object = new JSONObject();
                object.put("sla", slaId);
                object.put("metric", y);
                object.put("metric_name", mn);
                object.put("metric_unit", mu);
                object.put("metric_timestamp", mt);
                object.put("virtual_machine", vm);
                object.put("virtual_machine_name", vmn);
                object.put("host_machine", hm);
                object.put("value", vv_temp);
                object.put("relation", p.substring(p.lastIndexOf("#") + 1));
                object.put("threshold", v);
                object.put("call_url", callUrl);
                jsonArray.add(object);
            }

            //INSERT THE DATA INTO DATABASE
            PreparedStatement preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_SPARQL (timestamp, sla, alarm, metric, metric_name, metric_unit, metric_timestamp, virtual_machine, virtual_machine_name, host_machine, value, relation, threshold, call_url, business_configuration) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?");
            preparedStatement.setString(1, timestamp); // date
            preparedStatement.setString(2, slaId); // sla
            preparedStatement.setInt(3, alarm ? 1 : 0); // alarm
            preparedStatement.setString(4, y); // metric
            preparedStatement.setString(5, mn); // metric_name
            preparedStatement.setString(6, mu); // metric_unit
            preparedStatement.setString(7, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00)
            preparedStatement.setString(8, vm); // virtual_machine
            preparedStatement.setString(9, vmn); // virtual_machine_name
            preparedStatement.setString(10, hm); // host_machine
            preparedStatement.setString(11, vv_temp); // value
            preparedStatement.setString(12, p.substring(p.lastIndexOf("#") + 1)); //relation (e.g., http://www.cloudicaro.it/cloud_ontology/core#hasMetricValueLessThan)
            preparedStatement.setString(13, v); // threshold
            preparedStatement.setString(14, callUrl); // callUrl
            preparedStatement.setString(15, bc); // business configuration
            preparedStatement.setString(16, timestamp); // date
            preparedStatement.executeUpdate();
            preparedStatement.close();

            //lst1.add(new String[]{y, mt, vv_temp});
            result += "\nService Metric: " + y + "\n";
            result += "\nMetric Name: " + mn + "\n";
            result += "\nMetric Unit: " + mu + "\n";
            result += "Timestamp: " + mt + "\n";
            //result += "Service: " + sm + "\n";
            result += "Virtual Machine: " + vm + "\n";
            result += "Virtual Machine Name: " + vmn + "\n";
            result += "Host Machine: " + hm + "\n";
            //result += "Network Adapter: " + na + "\n";
            //result += "IP: " + ip + "\n";
            result += "Value" + (counter + 1) + ": " + vv_temp + "\n";
            result += "Threshold: " + getProperty(lst.get(counter)[3]) + " " + lst.get(counter)[1] + "\n";
            result += "Call Url: " + callUrl + "\n";
            result += "Business Configuration: " + bc + "\n";

            counter++;
        }

        // if the notify is true, then send the JSON to the SM
        if (notify) {
            JSONObject object = new JSONObject();
            object.put("metric", jsonArray);
            object.put("business_configuration", bc);
            object.put("timestamp", timestamp);
            object.put("sla", slaId);
            sendPostRequest(object.toJSONString());
        }

        //call the callUrls in the HashMap
        Iterator it = callUrlMap.entrySet().iterator();
        while (it.hasNext()) {
            try {
                Map.Entry pairs = (Map.Entry) it.next();
                URL u_callUrl = new URL((String) pairs.getKey());
                //get user credentials from URL, if present
                final String usernamePasswordCallUrl = u_callUrl.getUserInfo();
                //set the basic authentication credentials for the connection
                if (usernamePasswordCallUrl != null) {
                    Authenticator.setDefault(new Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(usernamePasswordCallUrl.split(":")[0],
                                    usernamePasswordCallUrl.split(":")[1].toCharArray());
                        }
                    });
                }
                //call the callUrl
                URLConnection connection = u_callUrl.openConnection();
                getUrlContents(connection);
            } catch (Exception e) {
            }
            it.remove(); // avoids a ConcurrentModificationException

        }

        //clean the callUrl map
        callUrlMap.clear();

        //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);
        }
    }
}

From source file:io.fabric8.agent.mvn.MavenConfigurationImpl.java

/**
 * Enables the proxy server for a given URL.
 *//*from w  w  w  . ja  v  a 2  s. co  m*/
public void enableProxy(URL url) {
    final String proxySupport = m_propertyResolver.get(m_pid + MavenConstants.PROPERTY_PROXY_SUPPORT);
    if ("false".equalsIgnoreCase(proxySupport)) {
        return; // automatic proxy support disabled
    }

    final String protocol = url.getProtocol();
    if (protocol == null || protocol.equals(get(m_pid + MavenConstants.PROPERTY_PROXY_SUPPORT))) {
        return; // already have this proxy enabled
    }

    Map<String, String> proxyDetails = m_settings.getProxySettings().get(protocol);
    if (proxyDetails != null) {
        LOGGER.trace("Enabling proxy [" + proxyDetails + "]");

        final String user = proxyDetails.get("user");
        final String pass = proxyDetails.get("pass");

        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pass.toCharArray());
            }
        });

        System.setProperty(protocol + ".proxyHost", proxyDetails.get("host"));
        System.setProperty(protocol + ".proxyPort", proxyDetails.get("port"));

        System.setProperty(protocol + ".nonProxyHosts", proxyDetails.get("nonProxyHosts"));

        set(m_pid + MavenConstants.PROPERTY_PROXY_SUPPORT, protocol);
    }
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static String createComposite(String commonName, String[] atomic, String description) {
    Client c = Client.create();/*from   w w w . j  av  a2  s  .  co m*/
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/configParamComposite/");
    ConfigParamCompositeInstanceDocument pDoc = ConfigParamCompositeInstanceDocument.Factory.newInstance();
    pDoc.addNewConfigParamCompositeInstance();
    pDoc.getConfigParamCompositeInstance().setCommonName(commonName);
    pDoc.getConfigParamCompositeInstance().setDescription(description);
    pDoc.getConfigParamCompositeInstance().setConfigParamsArray(atomic);

    String request = pDoc.toString();
    request = request.replace(" xmlns=\"http://xml.netbeans.org/schema/repo.xsd\"", "");
    request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + request;

    String resp = r.type(MediaType.TEXT_XML).post(String.class, request);
    System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ConfigParamCompositeDocument pcDoc = ConfigParamCompositeDocument.Factory.parse(resp);
        return pcDoc.getConfigParamComposite().getId();
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }

}

From source file:com.hpe.application.automation.tools.rest.RestClient.java

/**
 * Open http connection/*  ww  w .  j  av a 2  s.c  o m*/
 */
public static URLConnection openConnection(final ProxyInfo proxyInfo, String urlString) throws IOException {
    Proxy proxy = null;
    URL url = new URL(urlString);
    if (proxyInfo != null && StringUtils.isNotBlank(proxyInfo._host)
            && StringUtils.isNotBlank(proxyInfo._port)) {
        int port = Integer.parseInt(proxyInfo._port.trim());
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyInfo._host, port));
    }
    if (proxy != null && StringUtils.isNotBlank(proxyInfo._userName)
            && StringUtils.isNotBlank(proxyInfo._password)) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyInfo._userName, proxyInfo._password.toCharArray()); //To change body of overridden methods use File | Settings | File Templates.
            }
        };
        Authenticator.setDefault(authenticator);
    }
    if (proxy == null) {
        return url.openConnection();
    }
    return url.openConnection(proxy);
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void differentRealm() throws Exception {

    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);
    // Different password in case resetAuthCache() did not run
    UsernamePassword userPassword = new UsernamePassword(USERNAME, PASSWORD4);
    userRealm.put(USERNAME, PASSWORD4);/*  w  w w . j av  a 2s . c om*/
    //      userPassword.setShouldSave(true);
    //FixedPasswordProvider.setUsernamePassword(userPassword);

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), userPassword);
    URLConnection c = url.openConnection();

    c.connect();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0));

    assertEquals("Did not invoke authenticator", 1, authenticator.calls);
    assertEquals("Did not invoke our password provider", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    // different realm should be treated as a second connection, and not even use saved credentials

    credentialManager.resetAuthCache();
    userRealm.setName(REALM2);

    URLConnection c2 = url.openConnection();
    c2.connect();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));

    assertEquals("Did not invoke authenticator again", 2, authenticator.calls);
    assertEquals("Did not invoke provider again", 2,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    assertEquals("Unexpected prompt/realm", REALM2, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM2,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());
}

From source file:org.apache.cxf.maven_plugin.AbstractCodegenMoho.java

private void restoreProxySetting(String originalProxyHost, String originalProxyPort,
        String originalNonProxyHosts, String originalProxyUser, String originalProxyPassword) {
    if (originalProxyHost != null) {
        System.setProperty(HTTP_PROXY_HOST, originalProxyHost);
    } else {//from   w  ww .  ja va 2  s. com
        System.getProperties().remove(HTTP_PROXY_HOST);
    }
    if (originalProxyPort != null) {
        System.setProperty(HTTP_PROXY_PORT, originalProxyPort);
    } else {
        System.getProperties().remove(HTTP_PROXY_PORT);
    }
    if (originalNonProxyHosts != null) {
        System.setProperty(HTTP_NON_PROXY_HOSTS, originalNonProxyHosts);
    } else {
        System.getProperties().remove(HTTP_NON_PROXY_HOSTS);
    }
    if (originalProxyUser != null) {
        System.setProperty(HTTP_PROXY_USER, originalProxyUser);
    } else {
        System.getProperties().remove(HTTP_PROXY_USER);
    }
    if (originalProxyPassword != null) {
        System.setProperty(HTTP_PROXY_PASSWORD, originalProxyPassword);
    } else {
        System.getProperties().remove(HTTP_PROXY_PASSWORD);
    }
    Proxy proxy = mavenSession.getSettings().getActiveProxy();
    if (proxy != null && !StringUtils.isEmpty(proxy.getUsername())
            && !StringUtils.isEmpty(proxy.getPassword())) {
        Authenticator.setDefault(null);
    }
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static String updateComposite(String id, String commonName, String[] atomic, String description) {
    Client c = Client.create();//from   w  w  w .j a  va 2 s.  c o  m
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/configParamComposite/" + id);
    ConfigParamCompositeInstanceDocument pDoc = ConfigParamCompositeInstanceDocument.Factory.newInstance();
    pDoc.addNewConfigParamCompositeInstance();
    pDoc.getConfigParamCompositeInstance().setCommonName(commonName);
    pDoc.getConfigParamCompositeInstance().setDescription(description);
    pDoc.getConfigParamCompositeInstance().setConfigParamsArray(atomic);

    String request = pDoc.toString();
    request = request.replace(" xmlns=\"http://xml.netbeans.org/schema/repo.xsd\"", "");
    request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + request;

    String resp = r.type(MediaType.TEXT_XML).put(String.class, request);
    System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ConfigParamCompositeDocument pcDoc = ConfigParamCompositeDocument.Factory.parse(resp);
        return pcDoc.getConfigParamComposite().getId();
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }

}

From source file:org.talend.components.salesforce.runtime.SalesforceSourceOrSink.java

private void setProxy(ConnectorConfig config) {
    final ProxyPropertiesRuntimeHelper proxyHelper = new ProxyPropertiesRuntimeHelper(
            properties.getConnectionProperties().proxy);

    if (proxyHelper.getProxyHost() != null) {
        if (proxyHelper.getSocketProxy() != null) {
            config.setProxy(proxyHelper.getSocketProxy());
        } else {//from  w w w .ja  v a2s . co  m
            config.setProxy(proxyHelper.getProxyHost(), Integer.parseInt(proxyHelper.getProxyPort()));
        }

        if (proxyHelper.getProxyUser() != null && proxyHelper.getProxyUser().length() > 0) {
            config.setProxyUsername(proxyHelper.getProxyUser());

            if (proxyHelper.getProxyPwd() != null && proxyHelper.getProxyPwd().length() > 0) {
                config.setProxyPassword(proxyHelper.getProxyPwd());

                Authenticator.setDefault(new Authenticator() {

                    @Override
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(proxyHelper.getProxyUser(),
                                proxyHelper.getProxyPwd().toCharArray());
                    }

                });
            }
        }
    }
}

From source file:com.minoritycode.Application.java

private static boolean setProxy() {

    System.out.println("Setting proxy...");

    String host = null;/*from   ww  w. jav  a2 s  .  c  o m*/

    host = config.getProperty("proxyHost").trim();

    if (host == null || host.isEmpty() || host.equals("")) {
        logger.logLine("error proxy host not set in config file");
        if (manualOperation) {
            String message = "Please enter your proxy Host address";
            host = Credentials.getInput(message).trim();
            Credentials.saveProperty("proxyHost", host);

            if (host.equals(null)) {
                System.exit(0);
            }
        } else {
            return false;
        }
    }

    String port = config.getProperty("proxyPort").trim();

    if (port == null || port.isEmpty()) {
        logger.logLine("error proxy port not set in config file");
        if (manualOperation) {
            String message = "Please enter your proxy port";
            port = Credentials.getInput(message).trim();
            Credentials.saveProperty("proxyPort", port);

            if (port.equals(null)) {
                System.exit(0);
            }
        } else {
            return false;
        }
    }

    String user = config.getProperty("proxyUser").trim();

    if (user == null || user.isEmpty()) {
        logger.logLine("error proxy username not set in config file");
        if (manualOperation) {
            String message = "Please enter your proxy username";
            user = Credentials.getInput(message).trim();

            if (user.equals(null)) {
                System.exit(0);
            }

            Credentials.saveProperty("proxyUser", user);
        } else {
            return false;
        }
    }

    String password = config.getProperty("proxyPassword").trim();

    if (password == null || password.isEmpty()) {
        logger.logLine("error proxy password not set in config file");
        if (manualOperation) {
            String message = "Please enter your proxy password";
            password = Credentials.getInput(message).trim();
            Credentials.saveProperty("proxyPassword", password);
            if (password.equals(null)) {
                System.exit(0);
            }
        } else {
            return false;
        }
    }

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {

            if (getRequestorType() == RequestorType.PROXY) {
                String prot = getRequestingProtocol().toLowerCase();
                String host = System.getProperty(prot + ".proxyHost", config.getProperty("proxyHost"));
                String port = System.getProperty(prot + ".proxyPort", config.getProperty("proxyPort"));
                String user = System.getProperty(prot + ".proxyUser", config.getProperty("proxyUser"));
                String password = System.getProperty(prot + ".proxyPassword",
                        config.getProperty("proxyPassword"));

                if (getRequestingHost().equalsIgnoreCase(host)) {
                    if (Integer.parseInt(port) == getRequestingPort()) {
                        // Seems to be OK.
                        return new PasswordAuthentication(user, password.toCharArray());
                    }
                }
            }
            return null;
        }
    });

    System.setProperty("http.proxyPort", port);
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyUser", user);
    System.setProperty("http.proxyPassword", password);

    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, Integer.parseInt(port)));

    //        System.out.println(host+":"+port +" "+ user+":"+password);
    System.out.println("Proxy set");
    return true;
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static ConfigParamComposite getComposite(int id) {
    Client c = Client.create();//from ww w.j  ava 2s  .c om
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/configParamComposite/" + id);

    String resp = r.get(String.class);

    System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ConfigParamCompositeDocument pcDoc = ConfigParamCompositeDocument.Factory.parse(resp);
        return pcDoc.getConfigParamComposite();
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }

}