Example usage for java.net PasswordAuthentication PasswordAuthentication

List of usage examples for java.net PasswordAuthentication PasswordAuthentication

Introduction

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

Prototype

public PasswordAuthentication(String userName, char[] password) 

Source Link

Document

Creates a new PasswordAuthentication object from the given user name and password.

Usage

From source file:tasly.greathealth.erp.order.facades.DefaultOrderDeliveryStatusUpdateFacade.java

/**
 * TS-689:Hybris OMS???SAP ERP//from  w ww. j  a  va  2 s. c o m
 * Create ECC orders according to OMS orders:
 * 1. order.approve_status=1
 * 2. ?order.replication_status="N,E"
 * 3. ??order.replication_times<3
 *
 * @return processed order ID list
 * @author vincent.yin
 */
@Override
@Transactional
public List<String> createEccOrders() {
    List<TaslyOrderData> approverdOmsOrderDatas = new ArrayList<TaslyOrderData>();
    List<TaslyOrder> approverdOmsOrders = new ArrayList<TaslyOrder>();
    final String[] replication_status = { REPLICATIONSTATUS_N, REPLICATIONSTATUS_E };

    processedOmsOrderIDs = new ArrayList<String>();
    // below used for create ecc order soap client
    // baseinfo
    ZSTRUPIBASEINFO2 baseInfor = new ZSTRUPIBASEINFO2();
    // orders
    final ZSTRSDOMSSALEORDERTAB orders = new ZSTRSDOMSSALEORDERTAB();
    ZSTRSDOMSSALEORDER order = new ZSTRSDOMSSALEORDER();
    // message
    final ZSTRSDOMSSALEORDERS message = new ZSTRSDOMSSALEORDERS();
    // parameter
    final ZSDOMSSALESORDERCREATE parameters = new ZSDOMSSALESORDERCREATE();
    // request
    final ZFMSDOMSSALEORDERREQUEST orderRequest = new ZFMSDOMSSALEORDERREQUEST();

    // fetch the ERP code mapping data
    this.setErpCodeMappingMap();
    // fetch express data
    this.setExpressMap();

    // 1.get approved order list from OMS
    approverdOmsOrderDatas = orderService.getOmsApprovedOrders(CO_APPROVESTATUS, replication_status,
            CO_REPLICATIONTIME);
    // convert orderdata to order dto
    approverdOmsOrders = converters.convertAll(approverdOmsOrderDatas, orderConverter);

    LOG.info(CO_LogHead + "OMS ??: " + approverdOmsOrders.size());

    // 2.process message baseInfor
    // set baseInfor
    baseInfor = createEccBaseInfo();

    // 3.process message orderList
    // process each oms order
    for (final TaslyOrder taslyOrder : approverdOmsOrders) {
        // used to process sales and customer match
        String salsOrg = null;
        String customerOrg = null;
        LOG.info(CO_LogHead + "--------------------------------------------------");
        LOG.info(CO_LogHead + "?? :" + taslyOrder.getOrderId());

        if (null != taslyOrder.getInnerSource() || null != taslyOrder.getChannelSource()) {
            salsOrg = this.getSalesOrgMap().get(taslyOrder.getInnerSource().toString());
            customerOrg = this.getCustomerOrgMap().get(taslyOrder.getChannelSource().toString());

            LOG.info(CO_LogHead + "channelSource is: " + taslyOrder.getChannelSource().toString()
                    + ",innserSource is: " + taslyOrder.getInnerSource().toString() + ",salsOrg is:" + salsOrg
                    + ",customerOrg is: " + customerOrg);
        }
        if (null == salsOrg || null == customerOrg) {
            nullFlag = true;
            nullList.add(CO_LogHead + "[orders].inner_source or ||[orders].channel_source");

        }

        order = new ZSTRSDOMSSALEORDER();
        // this list was used to update order.replication_status later
        if (!nullFlag) {
            // create each ECC order
            order = createEccOrder(taslyOrder, salsOrg, customerOrg);
            // This order is OK,
            if (!nullFlag) {
                orders.getItem().add(order);
                processedOmsOrderIDs.add(taslyOrder.getOrderId());
            } else {
                LOG.error(
                        CO_LogHead + "? " + taslyOrder.getOrderId() + " ,:");
                LOGERROR.error(
                        CO_LogHead + "? " + taslyOrder.getOrderId() + " ,:");
                for (final String field : nullList) {
                    LOG.error(field);
                    // TS-891
                    LOGERROR.error(field);
                }
                // to process the next order
                nullFlag = false;
                nullList = new ArrayList<String>();
            }
        }
    }
    // set baseInfo attribute
    orderRequest.setBASEINFO(baseInfor);
    // set message orders attribute
    message.setORDERS(orders);
    // set message attribute
    orderRequest.setMESSAGE(message);
    // set Ecc parameters
    parameters.setIREQUEST(orderRequest);

    // SIECCOMSSALESORDERCREATEOUTAsyn serviceInterface = null;
    // 4. invoke eccSoapClient to creat new order
    if (processedOmsOrderIDs.size() > 0) {
        // // start put WSDL user name and password into Authenticator
        Authenticator.setDefault(new Authenticator() {
            // @Override
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(PIUSERNAME, PIPASSWORD.toCharArray());
            }
        });
        //
        try {
            // invoke the soap service
            LOG.info(CO_LogHead + "???PI?");

            createOrderSoapService.siECCOMSSALESORDERCREATEOUTAsyn(parameters);
            // 5. updated all of these omsorders replication_status from 'N' to 'Y'
            updateOrderReplicationStatus(processedOmsOrderIDs);

            LOG.info(CO_LogHead + "????");

        } catch (final Exception e) {
            LOG.error(CO_LogHead + "PI???!");
        }
    }
    return processedOmsOrderIDs;
}

From source file:sce.RESTCheckSLAJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Connection conn = null;/*from  w w  w . j  a v a 2 s . c o  m*/
    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  .  jav  a  2  s . com*/
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:com.hpe.application.automation.tools.rest.RestClient.java

/**
 * Open http connection/*from w  w  w .  j  a v  a2s.  c om*/
 */
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: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  ww w.  j a v  a 2 s.c o 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;// w  ww.j  av a 2s  .c om

    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.apache.cxf.maven_plugin.AbstractCodegenMoho.java

protected void configureProxyServerSettings() throws MojoExecutionException {

    Proxy proxy = mavenSession.getSettings().getActiveProxy();

    if (proxy != null) {

        getLog().info("Using proxy server configured in maven.");

        if (proxy.getHost() == null) {
            throw new MojoExecutionException("Proxy in settings.xml has no host");
        } else {//from  w ww .java2 s  .  c om
            if (proxy.getHost() != null) {
                System.setProperty(HTTP_PROXY_HOST, proxy.getHost());
            }
            if (String.valueOf(proxy.getPort()) != null) {
                System.setProperty(HTTP_PROXY_PORT, String.valueOf(proxy.getPort()));
            }
            if (proxy.getNonProxyHosts() != null) {
                System.setProperty(HTTP_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
            }
            if (!StringUtils.isEmpty(proxy.getUsername()) && !StringUtils.isEmpty(proxy.getPassword())) {
                final String authUser = proxy.getUsername();
                final String authPassword = proxy.getPassword();
                Authenticator.setDefault(new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(authUser, authPassword.toCharArray());
                    }
                });

                System.setProperty(HTTP_PROXY_USER, authUser);
                System.setProperty(HTTP_PROXY_PORT, authPassword);
            }
        }

    }
}

From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java

private void addProxySelector() {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override/*  w  w w. jav a  2 s .c o  m*/
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }

    final ProxySelector defaultProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals("fastdl.mongodb.org")) {
                return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
            } else {
                return defaultProxySelector.select(uri);
            }
        }

        @Override
        public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        }
    });
}

From source file:com.blackducksoftware.integration.hub.jenkins.PostBuildScanDescriptor.java

/**
 * Performs on-the-fly validation of the form field 'serverUrl'.
 *
 *///from  w  w w  . j  a v  a  2s  .  c om
public FormValidation doCheckServerUrl(@QueryParameter("serverUrl") final String serverUrl)
        throws IOException, ServletException {
    if (StringUtils.isBlank(serverUrl)) {
        return FormValidation.error(Messages.HubBuildScan_getPleaseSetServerUrl());
    }
    URL url;
    try {
        url = new URL(serverUrl);
        try {
            url.toURI();
        } catch (final URISyntaxException e) {
            return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl());
        }
    } catch (final MalformedURLException e) {
        return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl());
    }
    try {
        Proxy proxy = null;

        final Jenkins jenkins = Jenkins.getInstance();
        if (jenkins != null) {
            final ProxyConfiguration proxyConfig = jenkins.proxy;
            if (proxyConfig != null) {
                proxy = ProxyConfiguration.createProxy(url.getHost(), proxyConfig.name, proxyConfig.port,
                        proxyConfig.noProxyHost);

                if (proxy != null && proxy != Proxy.NO_PROXY) {

                    if (StringUtils.isNotBlank(proxyConfig.getUserName())
                            && StringUtils.isNotBlank(proxyConfig.getPassword())) {
                        Authenticator.setDefault(new Authenticator() {
                            @Override
                            public PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(proxyConfig.getUserName(),
                                        proxyConfig.getPassword().toCharArray());
                            }
                        });
                    } else {
                        Authenticator.setDefault(null);
                    }
                }
            }
        }

        URLConnection connection = null;
        if (proxy != null) {
            connection = url.openConnection(proxy);
        } else {
            connection = url.openConnection();
        }

        connection.getContent();
    } catch (final IOException ioe) {
        return FormValidation.error(ioe, Messages.HubBuildScan_getCanNotReachThisServer_0_(serverUrl));
    } catch (final RuntimeException e) {
        return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl());
    }
    return FormValidation.ok();
}

From source file:com.panet.imeta.cluster.SlaveServer.java

/**
 * Contact the server and get back the reply as a string
 * @return the requested information/* w w w. j a  v  a2  s. c  o  m*/
 * @throws Exception in case something goes awry 
 */
public String getContentFromServer(String service) throws Exception {
    // Following variable hides class variable. MB 7/10/07
    // LogWriter log = LogWriter.getInstance();

    String urlToUse = constructUrl(service);
    URL server;
    StringBuffer result = new StringBuffer();

    try {
        String beforeProxyHost = System.getProperty("http.proxyHost"); //$NON-NLS-1$
        String beforeProxyPort = System.getProperty("http.proxyPort"); //$NON-NLS-1$
        String beforeNonProxyHosts = System.getProperty("http.nonProxyHosts"); //$NON-NLS-1$

        BufferedReader input = null;

        try {
            if (log.isBasic())
                log.logBasic(toString(), Messages.getString("SlaveServer.DEBUG_ConnectingTo", urlToUse)); //$NON-NLS-1$

            if (proxyHostname != null) {
                System.setProperty("http.proxyHost", environmentSubstitute(proxyHostname)); //$NON-NLS-1$
                System.setProperty("http.proxyPort", environmentSubstitute(proxyPort)); //$NON-NLS-1$
                if (nonProxyHosts != null)
                    System.setProperty("http.nonProxyHosts", environmentSubstitute(nonProxyHosts)); //$NON-NLS-1$
            }

            if (username != null && username.length() > 0) {
                Authenticator.setDefault(new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(environmentSubstitute(username),
                                password != null ? environmentSubstitute(password).toCharArray()
                                        : new char[] {});
                    }
                });
            }

            // Get a stream for the specified URL
            server = new URL(urlToUse);
            URLConnection connection = server.openConnection();

            log.logDetailed(toString(), Messages.getString("SlaveServer.StartReadingReply")); //$NON-NLS-1$

            // Read the result from the server...
            InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 1000);

            input = new BufferedReader(new InputStreamReader(inputStream));

            long bytesRead = 0L;
            String line;
            while ((line = input.readLine()) != null) {
                result.append(line).append(Const.CR);
                bytesRead += line.length();
            }
            if (log.isBasic())
                log.logBasic(toString(), Messages.getString("SlaveServer.FinishedReadingResponse"), bytesRead); //$NON-NLS-1$
            if (log.isDebug())
                log.logDebug(toString(), "response from the webserver: {0}", result);
        } catch (MalformedURLException e) {
            log.logError(toString(), Messages.getString("SlaveServer.UrlIsInvalid", urlToUse, e.getMessage())); //$NON-NLS-1$
            log.logError(toString(), Const.getStackTracker(e));
        } catch (IOException e) {
            log.logError(toString(), Messages.getString("SlaveServer.CannotSaveDueToIOError", e.getMessage())); //$NON-NLS-1$
            log.logError(toString(), Const.getStackTracker(e));
        } catch (Exception e) {
            log.logError(toString(), Messages.getString("SlaveServer.ErrorReceivingFile", e.getMessage())); //$NON-NLS-1$
            log.logError(toString(), Const.getStackTracker(e));
        } finally {
            // Close it all
            try {
                if (input != null)
                    input.close();
            } catch (Exception e) {
                log.logError(toString(), Messages.getString("SlaveServer.CannotCloseStream", e.getMessage())); //$NON-NLS-1$
                log.logError(toString(), Const.getStackTracker(e));
            }

        }

        // Set the proxy settings back as they were on the system!
        System.setProperty("http.proxyHost", Const.NVL(beforeProxyHost, "")); //$NON-NLS-1$  //$NON-NLS-2$
        System.setProperty("http.proxyPort", Const.NVL(beforeProxyPort, "")); //$NON-NLS-1$  //$NON-NLS-2$
        System.setProperty("http.nonProxyHosts", Const.NVL(beforeNonProxyHosts, "")); //$NON-NLS-1$  //$NON-NLS-2$

        // Get the result back...
        return result.toString();
    } catch (Exception e) {
        throw new Exception(Messages.getString("SlaveServer.CannotContactURLForSecurityInformation", urlToUse), //$NON-NLS-1$
                e);
    }
}