Example usage for java.net Authenticator Authenticator

List of usage examples for java.net Authenticator Authenticator

Introduction

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

Prototype

Authenticator

Source Link

Usage

From source file:org.talend.core.nexus.NexusServerUtils.java

public static String resolveSha1(String nexusUrl, final String userName, final String password,
        String repositoryId, String groupId, String artifactId, String version, String type) throws Exception {
    HttpURLConnection urlConnection = null;
    final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator();
    if (userName != null && !"".equals(userName)) {
        Authenticator.setDefault(new Authenticator() {

            @Override/*from   ww  w .j a  v a  2 s.  c o m*/
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password.toCharArray());
            }

        });
    }
    try {
        String service = NexusConstants.SERVICES_RESOLVE + "a=" + artifactId + "&g=" + groupId + "&r="
                + repositoryId + "&v=" + version + "&p=" + type;
        urlConnection = getHttpURLConnection(nexusUrl, service, userName, password);
        SAXReader saxReader = new SAXReader();

        InputStream inputStream = urlConnection.getInputStream();
        Document document = saxReader.read(inputStream);

        Node sha1Node = document.selectSingleNode("/artifact-resolution/data/sha1");
        String sha1 = null;
        if (sha1Node != null) {
            sha1 = sha1Node.getText();
        }
        return sha1;

    } catch (FileNotFoundException e) {
        // jar not existing on remote nexus
        return null;
    } finally {
        Authenticator.setDefault(defaultAuthenticator);
        if (null != urlConnection) {
            urlConnection.disconnect();
        }
    }
}

From source file:org.fuin.esmp.AbstractEventStoreMojo.java

private void addProxySelector(final String proxyHost, final int proxyPort, final String proxyUser,
        final String proxyPassword, final URL downloadUrl) throws URISyntaxException {

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

    final URI downloadUri = downloadUrl.toURI();

    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals(downloadUri.getHost()) && proxyHost != null && proxyHost.length() != 0) {
                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.diablominer.DiabloMiner.DiabloMiner.java

void execute(String[] args) throws Exception {
    threads.add(Thread.currentThread());

    Options options = new Options();
    options.addOption("u", "user", true, "bitcoin host username");
    options.addOption("p", "pass", true, "bitcoin host password");
    options.addOption("o", "host", true, "bitcoin host IP");
    options.addOption("r", "port", true, "bitcoin host port");
    options.addOption("l", "url", true, "bitcoin host url");
    options.addOption("x", "proxy", true, "optional proxy settings IP:PORT<:username:password>");
    options.addOption("g", "worklifetime", true, "maximum work lifetime in seconds");
    options.addOption("d", "debug", false, "enable debug output");
    options.addOption("dt", "debugtimer", false, "run for 1 minute and quit");
    options.addOption("D", "devices", true, "devices to enable, default all");
    options.addOption("f", "fps", true, "target GPU execution timing");
    options.addOption("na", "noarray", false, "turn GPU kernel array off");
    options.addOption("v", "vectors", true, "vector size in GPU kernel");
    options.addOption("w", "worksize", true, "override GPU worksize");
    options.addOption("ds", "ksource", false, "output GPU kernel source and quit");
    options.addOption("h", "help", false, "this help");

    PosixParser parser = new PosixParser();

    CommandLine line = null;/*from w  ww.ja v a 2  s  .  co m*/

    try {
        line = parser.parse(options, args);

        if (line.hasOption("help")) {
            throw new ParseException("");
        }
    } catch (ParseException e) {
        System.out.println(e.getLocalizedMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DiabloMiner -u myuser -p mypassword [args]\n", "", options,
                "\nRemember to set rpcuser and rpcpassword in your ~/.bitcoin/bitcoin.conf "
                        + "before starting bitcoind or bitcoin --daemon");
        return;
    }

    String splitUrl[] = null;
    String splitUser[] = null;
    String splitPass[] = null;
    String splitHost[] = null;
    String splitPort[] = null;

    if (line.hasOption("url"))
        splitUrl = line.getOptionValue("url").split(",");

    if (line.hasOption("user"))
        splitUser = line.getOptionValue("user").split(",");

    if (line.hasOption("pass"))
        splitPass = line.getOptionValue("pass").split(",");

    if (line.hasOption("host"))
        splitHost = line.getOptionValue("host").split(",");

    if (line.hasOption("port"))
        splitPort = line.getOptionValue("port").split(",");

    int networkStatesCount = 0;

    if (splitUrl != null)
        networkStatesCount = splitUrl.length;

    if (splitUser != null)
        networkStatesCount = Math.max(splitUser.length, networkStatesCount);

    if (splitPass != null)
        networkStatesCount = Math.max(splitPass.length, networkStatesCount);

    if (splitHost != null)
        networkStatesCount = Math.max(splitHost.length, networkStatesCount);

    if (splitPort != null)
        networkStatesCount = Math.max(splitPort.length, networkStatesCount);

    if (networkStatesCount == 0) {
        error("You forgot to give any bitcoin connection info, please add either -l, or -u -p -o and -r");
        System.exit(-1);
    }

    int j = 0;

    for (int i = 0; j < networkStatesCount; i++, j++) {
        String protocol = "http";
        String host = "localhost";
        int port = 8332;
        String path = "/";
        String user = "diablominer";
        String pass = "diablominer";
        byte hostChain = 0;

        if (splitUrl != null && splitUrl.length > i) {
            String[] usernameFix = splitUrl[i].split("@", 3);
            if (usernameFix.length > 2)
                splitUrl[i] = usernameFix[0] + "+++++" + usernameFix[1] + "@" + usernameFix[2];

            URL url = new URL(splitUrl[i]);

            if (url.getProtocol() != null && url.getProtocol().length() > 1)
                protocol = url.getProtocol();

            if (url.getHost() != null && url.getHost().length() > 1)
                host = url.getHost();

            if (url.getPort() != -1)
                port = url.getPort();

            if (url.getPath() != null && url.getPath().length() > 1)
                path = url.getPath();

            if (url.getUserInfo() != null && url.getUserInfo().length() > 1) {
                String[] userPassSplit = url.getUserInfo().split(":");

                user = userPassSplit[0].replace("+++++", "@");

                if (userPassSplit.length > 1 && userPassSplit[1].length() > 1)
                    pass = userPassSplit[1];
            }
        }

        if (splitUser != null && splitUser.length > i)
            user = splitUser[i];

        if (splitPass != null && splitPass.length > i)
            pass = splitPass[i];

        if (splitHost != null && splitHost.length > i)
            host = splitHost[i];

        if (splitPort != null && splitPort.length > i)
            port = Integer.parseInt(splitPort[i]);

        NetworkState networkState;

        try {
            networkState = new JSONRPCNetworkState(this, new URL(protocol, host, port, path), user, pass,
                    hostChain);
        } catch (MalformedURLException e) {
            throw new DiabloMinerFatalException(this, "Malformed connection paramaters");
        }

        if (networkStateHead == null) {
            networkStateHead = networkStateTail = networkState;
        } else {
            networkStateTail.setNetworkStateNext(networkState);
            networkStateTail = networkState;
        }
    }

    networkStateTail.setNetworkStateNext(networkStateHead);

    if (line.hasOption("proxy")) {
        final String[] proxySettings = line.getOptionValue("proxy").split(":");

        if (proxySettings.length >= 2) {
            proxy = new Proxy(Type.HTTP,
                    new InetSocketAddress(proxySettings[0], Integer.valueOf(proxySettings[1])));
        }

        if (proxySettings.length >= 3) {
            Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxySettings[2], proxySettings[3].toCharArray());
                }
            });
        }
    }

    if (line.hasOption("worklifetime"))
        workLifetime = Integer.parseInt(line.getOptionValue("worklifetime")) * 1000;

    if (line.hasOption("debug"))
        debug = true;

    if (line.hasOption("debugtimer")) {
        debugtimer = true;
    }

    if (line.hasOption("devices")) {
        String devices[] = line.getOptionValue("devices").split(",");
        enabledDevices = new HashSet<String>();
        for (String s : devices) {
            enabledDevices.add(s);

            if (Integer.parseInt(s) == 0) {
                error("Do not use 0 with -D, devices start at 1");
                System.exit(-1);
            }
        }
    }

    if (line.hasOption("fps")) {
        GPUTargetFPS = Float.parseFloat(line.getOptionValue("fps"));

        if (GPUTargetFPS < 0.1) {
            error("--fps argument is too low, adjusting to 0.1");
            GPUTargetFPS = 0.1;
        }
    }

    if (line.hasOption("noarray")) {
        GPUNoArray = true;
    }

    if (line.hasOption("worksize"))
        GPUForceWorkSize = Integer.parseInt(line.getOptionValue("worksize"));

    if (line.hasOption("vectors")) {
        String tempVectors[] = line.getOptionValue("vectors").split(",");

        GPUVectors = new Integer[tempVectors.length];

        try {
            for (int i = 0; i < GPUVectors.length; i++) {
                GPUVectors[i] = Integer.parseInt(tempVectors[i]);

                if (GPUVectors[i] > 16) {
                    error("DiabloMiner now uses comma-seperated vector layouts, use those instead");
                    System.exit(-1);
                } else if (GPUVectors[i] != 1 && GPUVectors[i] != 2 && GPUVectors[i] != 3 && GPUVectors[i] != 4
                        && GPUVectors[i] != 8 && GPUVectors[i] != 16) {
                    error(GPUVectors[i] + " is not a vector length of 1, 2, 3, 4, 8, or 16");
                    System.exit(-1);
                }
            }

            Arrays.sort(GPUVectors, Collections.reverseOrder());
        } catch (NumberFormatException e) {
            error("Cannot parse --vector argument(s)");
            System.exit(-1);
        }
    } else {
        GPUVectors = new Integer[1];
        GPUVectors[0] = 1;
    }

    if (line.hasOption("ds"))
        GPUDebugSource = true;

    info("Started");

    StringBuilder list = new StringBuilder(networkStateHead.getQueryUrl().toString());
    NetworkState networkState = networkStateHead.getNetworkStateNext();

    while (networkState != networkStateHead) {
        list.append(", " + networkState.getQueryUrl());
        networkState = networkState.getNetworkStateNext();
    }

    info("Connecting to: " + list);

    long previousHashCount = 0;
    double previousAdjustedHashCount = 0.0;
    long previousAdjustedStartTime = startTime = (now()) - 1;
    StringBuilder hashMeter = new StringBuilder(80);
    Formatter hashMeterFormatter = new Formatter(hashMeter);

    int deviceCount = 0;

    List<List<? extends DeviceState>> allDeviceStates = new ArrayList<List<? extends DeviceState>>();

    List<? extends DeviceState> GPUDeviceStates = new GPUHardwareType(this).getDeviceStates();
    deviceCount += GPUDeviceStates.size();
    allDeviceStates.add(GPUDeviceStates);

    while (running.get()) {
        for (List<? extends DeviceState> deviceStates : allDeviceStates) {
            for (DeviceState deviceState : deviceStates) {
                deviceState.checkDevice();
            }
        }

        long now = now();
        long currentHashCount = hashCount.get();
        double adjustedHashCount = (double) (currentHashCount - previousHashCount)
                / (double) (now - previousAdjustedStartTime);
        double hashLongCount = (double) currentHashCount / (double) (now - startTime) / 1000.0;

        if (now - startTime > TIME_OFFSET * 2) {
            double averageHashCount = (adjustedHashCount + previousAdjustedHashCount) / 2.0 / 1000.0;

            hashMeter.setLength(0);

            if (!debug) {
                hashMeterFormatter.format("\rmhash: %.1f/%.1f | accept: %d | reject: %d | hw error: %d",
                        averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get());
            } else {
                hashMeterFormatter.format("\rmh: %.1f/%.1f | a/r/hwe: %d/%d/%d | gh: ", averageHashCount,
                        hashLongCount, blocks.get(), rejects.get(), hwErrors.get());

                double basisAverage = 0.0;

                for (List<? extends DeviceState> deviceStates : allDeviceStates) {
                    for (DeviceState deviceState : deviceStates) {
                        hashMeterFormatter.format("%.1f ",
                                deviceState.getDeviceHashCount() / 1000.0 / 1000.0 / 1000.0);
                        basisAverage += deviceState.getBasis();
                    }
                }

                basisAverage = 1000 / (basisAverage / deviceCount);

                hashMeterFormatter.format("| fps: %.1f", basisAverage);
            }

            System.out.print(hashMeter);
        } else {
            System.out.print("\rWaiting...");
        }

        if (now() - TIME_OFFSET * 2 > previousAdjustedStartTime) {
            previousHashCount = currentHashCount;
            previousAdjustedHashCount = adjustedHashCount;
            previousAdjustedStartTime = now - 1;
        }

        if (debugtimer && now() > startTime + 60 * 1000) {
            System.out.print("\n");
            info("Debug timer is up, quitting...");
            System.exit(0);
        }

        try {
            if (now - startTime > TIME_OFFSET)
                Thread.sleep(1000);
            else
                Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }

    hashMeterFormatter.close();
}

From source file:io.takari.maven.testing.executor.junit.MavenVersionResolver.java

private void setHttpCredentials(final Credentials credentials) {
    Authenticator authenticator = null;
    if (credentials != null) {
        authenticator = new Authenticator() {
            @Override/*from  w w w .java  2 s  .  co m*/
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(credentials.username, credentials.password.toCharArray());
            }
        };
    }
    Authenticator.setDefault(authenticator);
}

From source file:org.openbravo.test.webservice.BaseWSTest.java

/**
 * Creates a HTTP connection./*from w ww .  ja v  a  2  s. c  o  m*/
 * 
 * @param wsPart
 * @param method
 *          POST, PUT, GET or DELETE
 * @return the created connection
 * @throws Exception
 */
protected HttpURLConnection createConnection(String wsPart, String method) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(LOGIN, PWD.toCharArray());
        }
    });
    log.debug(method + ": " + getOpenbravoURL() + wsPart);
    final URL url = new URL(getOpenbravoURL() + wsPart);
    final HttpURLConnection hc = (HttpURLConnection) url.openConnection();
    hc.setRequestMethod(method);
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    hc.setRequestProperty("Content-Type", "text/xml");
    return hc;
}

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

public static URLConnection openConnection(final ProxyInfo proxyInfo, String urlString) throws IOException {
    Proxy proxy = null;/*www  .j a va  2  s .  c  om*/
    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:tasly.greathealth.erp.order.facades.DefaultOrderDeliveryStatusUpdateFacade.java

/**
 * TS-689:Hybris OMS???SAP ERP/*w ww.ja  v a  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 .  ja  v  a 2 s .  c  om
    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 ww  w. j a  v  a  2 s  .  c  om*/
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/*w  w  w  . j  a  va2 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);
}