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:com.clustercontrol.plugin.impl.ProxyManagerPlugin.java

@Override
public void activate() {
    ProxySelector.setDefault(new HinemosProxySelector(ProxySelector.getDefault()));
    Authenticator.setDefault(new HinemosAuthenticator());
}

From source file:com.cisco.dvbu.ps.deploytool.dao.jdbcapi.RegressionPerfTestDAOImpl.java

public void executePerformanceTest(CompositeServer cisServerConfig, RegressionTestType regressionConfig,
        List<RegressionTestType> regressionList) throws CompositeException {
    // 0. Check the input parameter values:
    if (cisServerConfig == null || regressionConfig == null) {
        throw new CompositeException(
                "XML Configuration objects are not initialized when trying to run Regression test.");
    }//w  w  w  .j  ava 2 s. c o m
    if (this.cisServerConfig == null) {
        this.cisServerConfig = cisServerConfig;
    }
    if (this.regressionConfig == null) {
        this.regressionConfig = regressionConfig;
    }

    // To do: take a look at the authenticator from the original pubtest
    Authenticator.setDefault(new BasicAuthenticator(cisServerConfig));

    // Initialize start time and format
    java.util.Date startDate = new java.util.Date();
    Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    // 1. Initialize configuration items: 
    String prefix = "executePerformanceTest";
    // Get items from config file:
    // Get input file path
    String inputFilePath = CommonUtils.extractVariable(prefix, regressionConfig.getInputFilePath(),
            propertyFile, true);
    // Test for zero length before testing for null
    if (inputFilePath != null && inputFilePath.length() == 0)
        inputFilePath = null;
    // Now test for null
    if (inputFilePath == null)
        throw new CompositeException("Input file path is not defined in the regression XML file.");

    // Get the test type
    String testType = CommonUtils.extractVariable(prefix, regressionConfig.getTestRunParams().getTestType(),
            propertyFile, false);

    // Get the base directory where the files should be stored
    String baseDir = null;
    if (regressionConfig.getTestRunParams().getBaseDir() != null) {
        baseDir = CommonUtils.extractVariable(prefix, regressionConfig.getTestRunParams().getBaseDir().trim(),
                propertyFile, true);
        if (baseDir != null && baseDir.length() > 0) {
            baseDir = baseDir.replaceAll(Matcher.quoteReplacement("\\\\"), Matcher.quoteReplacement("/"));
            baseDir = baseDir.replaceAll(Matcher.quoteReplacement("\\"), Matcher.quoteReplacement("/"));
            // Make the sub-directory for the base directory which is where the result files go for each execution
            boolean res = CommonUtils.mkdirs(baseDir);
        } else {
            baseDir = null;
        }
    }

    // Get log file delimiter
    if (regressionConfig.getTestRunParams().getLogDelimiter() != null) {
        logDelim = RegressionManagerUtils.getDelimiter(CommonUtils.extractVariable(prefix,
                regressionConfig.getTestRunParams().getLogDelimiter().toString(), propertyFile, false));
    }

    // Get output file delimiter
    if (regressionConfig.getTestRunParams().getDelimiter() != null) {
        outputDelimiter = RegressionManagerUtils.getDelimiter(CommonUtils.extractVariable(prefix,
                regressionConfig.getTestRunParams().getDelimiter().toString(), propertyFile, false));
    }

    // Get the printOutput variable
    if (regressionConfig.getTestRunParams().getPrintOutput() != null)
        printOutputType = CommonUtils.extractVariable(prefix,
                regressionConfig.getTestRunParams().getPrintOutput(), propertyFile, false);

    // Get the regression log location
    String logFilePath = CommonUtils.extractVariable(prefix,
            regressionConfig.getTestRunParams().getLogFilePath(), propertyFile, true);
    if (logFilePath == null || logFilePath.length() == 0) {
        throw new CompositeException(
                "The log file path testRunParams.logFilePath may not be null or empty in the regression XML file.");
    }
    String logAppend = CommonUtils.extractVariable(prefix, regressionConfig.getTestRunParams().getLogAppend(),
            propertyFile, false);
    if (logAppend == null || logAppend.length() == 0) {
        throw new CompositeException(
                "The log file append testRunParams.logAppend may not be null or empty in the regression XML file.");
    }

    String content = CommonUtils.rpad("Result", 8, padChar) + logDelim
            + CommonUtils.rpad("ExecutionStartTime", 26, padChar) + logDelim
            + CommonUtils.rpad("Duration", 20, padChar) + logDelim + CommonUtils.rpad("Rows", 20, padChar)
            + logDelim + CommonUtils.rpad("Database", 30, padChar) + logDelim
            + CommonUtils.rpad("Query", 70, padChar) + logDelim + CommonUtils.rpad("Type", 11, padChar)
            + logDelim + CommonUtils.rpad("OutputFile", 50, padChar) + logDelim + "Message" + "\r\n";

    // Write out the header log entry -- if it does not exist the sub-directories will automatically be created.
    if (RegressionManagerUtils.checkBooleanConfigParam(logAppend)) {
        CommonUtils.appendContentToFile(logFilePath, content);
    } else {
        // create a new file
        CommonUtils.createFileWithContent(logFilePath, content);
    }

    // Check for performance test threads and duration
    perfTestThreads = 1;
    if (regressionConfig.getTestRunParams().getPerfTestThreads() != null)
        perfTestThreads = regressionConfig.getTestRunParams().getPerfTestThreads();
    perfTestDuration = 60;
    if (regressionConfig.getTestRunParams().getPerfTestThreads() != null)
        perfTestDuration = regressionConfig.getTestRunParams().getPerfTestDuration();
    perfTestSleepPrint = 5;
    if (regressionConfig.getTestRunParams().getPerfTestSleepPrint() != null) {
        perfTestSleepPrint = regressionConfig.getTestRunParams().getPerfTestSleepPrint();
        // Must be a minimum of 5 seconds otherwise too much log activity will be generated
        if (perfTestSleepPrint == 0)
            perfTestSleepPrint = 5;
    }
    perfTestSleepExec = 0;
    if (regressionConfig.getTestRunParams().getPerfTestSleepExec() != null)
        perfTestSleepExec = regressionConfig.getTestRunParams().getPerfTestSleepExec();

    // Check to see what should be executed
    boolean runQueries = RegressionManagerUtils.checkBooleanConfigParam(CommonUtils.extractVariable(prefix,
            regressionConfig.getTestRunParams().getRunQueries(), propertyFile, false));
    boolean runProcs = RegressionManagerUtils.checkBooleanConfigParam(CommonUtils.extractVariable(prefix,
            regressionConfig.getTestRunParams().getRunProcedures(), propertyFile, false));
    boolean runWs = RegressionManagerUtils.checkBooleanConfigParam(CommonUtils.extractVariable(prefix,
            regressionConfig.getTestRunParams().getRunWS(), propertyFile, false));
    boolean useAllDatasources = RegressionManagerUtils.checkBooleanConfigParam(CommonUtils.extractVariable(
            prefix, regressionConfig.getTestRunParams().getUseAllDatasources(), propertyFile, false));

    // Get the list of items from the input file
    RegressionItem[] items = RegressionManagerUtils.parseItems(inputFilePath);

    // Initialize counters
    //   Initialize Success Counters
    int totalSuccessTests = 0;
    int totalSuccessQueries = 0;
    int totalSuccessProcs = 0;
    int totalSuccessWS = 0;
    //   Initialize Skipped Counters
    int totalSkippedTests = 0;
    int totalSkippedQueries = 0;
    int totalSkippedProcs = 0;
    int totalSkippedWS = 0;
    //   Initialize Error Counters
    int totalFailedTests = 0;
    int totalFailedQueries = 0;
    int totalFailedProcs = 0;
    int totalFailedWS = 0;

    // 2. Execute items: 
    // Execute each item from the input file
    for (int i = 0; i < items.length; i++) {
        // Initialize the overall start time
        java.util.Date beginDate = new java.util.Date();
        String executionStartTime = formatter.format(beginDate);
        // Initialize the item object
        item = items[i];

        /*
         * For Performance Test we do not write to an output file.
         */
        outputFile = null;

        String message = null;
        errorMessage = null;
        errorFound = false;
        String detailContent = null;
        String result = "SKIPPED"; // [SKIPPED,SUCCESS,ERROR,HEADER,DETAIL,TOTALS]
        String duration = "";
        String database = item.database;
        totalRows = 0;
        String query = "";
        String resourceType = "";
        String resourceURL = "";

        // Setup Query
        if (item.type == RegressionManagerUtils.TYPE_QUERY) {
            resourceType = QUERY;
            query = item.input;
            query = query.replaceAll("\n", " ");
            resourceURL = RegressionManagerUtils.getTableUrl(query); // Retrieve only the FROM clause table URL with no where clause and no SELECT * FROM projections
            /*
             * For Performance Test we do not write to an output file.
             */
            //if (baseDir != null) 
            //   outputFile = (baseDir + "/" + database + "/" + resourceURL + ".txt").replaceAll("//", "/");
        }

        // Setup Procedures
        if (item.type == RegressionManagerUtils.TYPE_PROCEDURE) {
            resourceType = PROCEDURE;
            query = item.input;
            query = query.replaceAll("\n", " ");
            resourceURL = RegressionManagerUtils.getTableUrl(query); // Retrieve only the FROM clause procedure URL with no where clause and no SELECT * FROM projections and no parameters.
            /*
             * For Performance Test we do not write to an output file.
             */
            //if (baseDir != null) 
            //   outputFile = (baseDir + "/" + database + "/" + resourceURL + ".txt").replaceAll("//", "/");               
        }

        // Setup Web Services
        if (item.type == RegressionManagerUtils.TYPE_WS) {
            resourceType = WS;
            query = (item.path + "/" + item.action).replaceAll("//", "/");
            resourceURL = (item.path + "/" + item.action).replaceAll("//", "/").replaceAll("/", "."); // construct ws path from the path and action combined.
            if (resourceURL.indexOf(".") == 0)
                resourceURL = resourceURL.substring(1);
            /*
             * For Performance Test we do not write to an output file.
             */
            //if (baseDir != null) 
            //   outputFile = (baseDir + "/" + database + "/" + resourceURL + ".txt").replaceAll("//", "/");             
        }

        /*
         *  If testRunParams.useAllDatasources is set to true in then use all datasource queries in the input file 
         *  otherwise determine if the database in the input file is in the testRunParams.datasource list in the XML file
         *  and process it if it is.
         *  
         *  See if database exists in this list then process if it is.
         *          <datasources>
        *            <dsName>MYTEST</dsName>
        *            <dsName>testWebService00</dsName>
        *         </datasources>   
         */
        boolean databaseMatch = true;
        if (!useAllDatasources)
            databaseMatch = RegressionManagerUtils.findDatabaseMatch(database,
                    regressionConfig.getTestRunParams().getDatasources(), propertyFile);

        /* Determine if the specific resource should be compared by checking the XML resource list.
         * If the resourceURL pattern matches what is in this list then process it.
         *       <resources>
         *         <resource>TEST1.*</resource>
         *         <resource>TEST1.SCH.*</resource>
         *         <resource>TEST1.SCH.VIEW1</resource>
         *      </resources>
         */
        boolean resourceMatch = RegressionManagerUtils.findResourceMatch(resourceURL,
                regressionConfig.getTestRunParams().getResources(), propertyFile);

        try {
            RegressionManagerUtils.printOutputStr(printOutputType, "summary",
                    "------------------------ Test " + (i + 1) + " -----------------------------",
                    "Test " + (i + 1) + " ... ");
            if (item.type == RegressionManagerUtils.TYPE_QUERY && runQueries && databaseMatch
                    && resourceMatch) {
                // Initialize the file
                if (outputFile != null)
                    CommonUtils.createFileWithContent(outputFile, "");

                // Establish a JDBC connection for this database
                cisConnections = RegressionManagerUtils.establishJdbcConnection(item.database, cisConnections,
                        cisServerConfig, regressionConfig, propertyFile); // don't need to check for null here.

                // Print out the line to the command line
                RegressionManagerUtils.printOutputStr(printOutputType, "summary",
                        "Execute Query:  " + item.input, "");

                // Execute the performance test for a query
                detailContent = executePerformanceTestWorkers();

                if (errorMessage == null) {
                    result = "SUCCESS";
                    totalSuccessTests++;
                    totalSuccessQueries++;
                } else {
                    result = "ERROR";
                    totalFailedQueries++;
                    totalFailedTests++;
                    logger.error(errorMessage);
                    logger.error("Item Input Details: " + item.toString());

                }
            } else if (item.type == RegressionManagerUtils.TYPE_PROCEDURE && runProcs && databaseMatch
                    && resourceMatch) {
                // Initialize the file
                if (outputFile != null)
                    CommonUtils.createFileWithContent(outputFile, "");

                // Establish a JDBC connection for this database
                cisConnections = RegressionManagerUtils.establishJdbcConnection(item.database, cisConnections,
                        cisServerConfig, regressionConfig, propertyFile); // don't need to check for null here.

                // Print out the line to the command line
                RegressionManagerUtils.printOutputStr(printOutputType, "summary",
                        "Execute Procedure:  " + item.input, "");

                // Execute the performance test for a procedure
                detailContent = executePerformanceTestWorkers();

                if (errorMessage == null) {
                    result = "SUCCESS";
                    totalSuccessTests++;
                    totalSuccessProcs++;
                } else {
                    result = "ERROR";
                    totalFailedProcs++;
                    totalFailedTests++;
                    logger.error(errorMessage);
                    logger.error("Item Input Details: " + item.toString());
                }
            } else if (item.type == RegressionManagerUtils.TYPE_WS && runWs && databaseMatch && resourceMatch) {
                // Initialize the file
                if (outputFile != null)
                    CommonUtils.createFileWithContent(outputFile, "");

                // Print out the line to the command line
                RegressionManagerUtils.printOutputStr(printOutputType, "summary",
                        "Execute Web Service:  " + item.path, "");
                RegressionManagerUtils.printOutputStr(printOutputType, "summary", item.input, "");

                // Execute the performance test for a web service
                detailContent = executePerformanceTestWorkers();

                if (errorMessage == null) {
                    result = "SUCCESS";
                    totalSuccessTests++;
                    totalSuccessWS++;
                } else {
                    result = "ERROR";
                    totalFailedWS++;
                    totalFailedTests++;
                    logger.error(errorMessage);
                    logger.error("Item Input Details: " + item.toString());
                }
            } else {
                // Skip this test
                if (item.type == RegressionManagerUtils.TYPE_WS) {
                    totalSkippedWS++;
                    message = "  ::Reason: type=" + resourceType + "  runWs=" + runWs + "  databaseMatch="
                            + databaseMatch + "  resourceMatch=" + resourceMatch;
                    RegressionManagerUtils.printOutputStr(printOutputType, "summary",
                            "Test Skipped: " + resourceURL + message + "\n", "");
                } else if (item.type == RegressionManagerUtils.TYPE_QUERY) {
                    totalSkippedQueries++;
                    message = "  ::Reason: type=" + resourceType + "  runQueries=" + runQueries
                            + "  databaseMatch=" + databaseMatch + "  resourceMatch=" + resourceMatch;
                    RegressionManagerUtils.printOutputStr(printOutputType, "summary",
                            "Test Skipped: " + query + message + "\n", "");
                } else {
                    totalSkippedProcs++;
                    message = "  ::Reason: type=" + resourceType + "  runProcedures=" + runProcs
                            + "  databaseMatch=" + databaseMatch + "  resourceMatch=" + resourceMatch;
                    RegressionManagerUtils.printOutputStr(printOutputType, "summary",
                            "Test Skipped: " + query + message + "\n", "");
                }
                totalSkippedTests++;
            }
        } catch (Exception e) {
            result = "ERROR";
            errorMessage = e.getMessage().replace("\n", " ").replaceAll("\r", " ");
            totalFailedTests++;
            logger.error(errorMessage);
            logger.error("Item Input Details: " + item.toString());
        }

        // Setup message line to be output to the log file
        if (message == null)
            message = "";
        if (errorMessage != null) {
            message = "  ::ERROR: " + errorMessage + "  " + message;
            // Don't output the detail content if no DETAIL entries exist
            if (detailContent != null && !detailContent.contains("DETAIL"))
                detailContent = null;
        }

        // Setup outputFile to be blank if it was never set in the first place which is valid.
        if (outputFile == null)
            outputFile = "";

        // Setup the detailContent rows
        if (detailContent != null) {
            detailContent = "\n" + detailContent;
            if (detailContent.lastIndexOf("\n") > 0) {
                detailContent = detailContent.substring(0, detailContent.length() - 1);
            }
        } else {
            detailContent = "";
        }

        // Get the final total duration
        duration = CommonUtils.getElapsedTime(beginDate);

        // Output the log entry
        content = CommonUtils.rpad(result, 8, padChar) + logDelim
                + CommonUtils.rpad(executionStartTime, 26, padChar) + logDelim
                + CommonUtils.rpad(duration.trim(), 20, padChar) + logDelim
                + CommonUtils.rpad("" + totalRows, 20, padChar) + logDelim
                + CommonUtils.rpad(database, 30, padChar) + logDelim + CommonUtils.rpad(query, 70, padChar)
                + logDelim + CommonUtils.rpad(resourceType, 11, padChar) + logDelim
                + CommonUtils.rpad(outputFile, 50, padChar) + logDelim + message;
        // content contains the overall output message
        // detailContent contains the DETAIL messages from the performance test
        // The log is written in a way that the overall message is displayed first followed by the content
        CommonUtils.appendContentToFile(logFilePath, content + detailContent);
        // Since the display is being printed in real-time, the detail messages come out first followed by the overall content message.
        RegressionManagerUtils.printOutputStr(printOutputType, "summary", "\n" + content, "");

    } // end of process input file items loop

    // Print out timings
    String duration = CommonUtils.getElapsedTime(startDate);
    String testTypeMessage = "";
    if (PERFORMANCE.equalsIgnoreCase(testType))
        testTypeMessage = "Execute a full query from the query list.";

    int len = 56;
    logger.info("--------------------------------------------------------");
    logger.info("--------- Regression Performance Test Summary ----------");
    logger.info("--------------------------------------------------------");
    logger.info("--------------------------------------------------------");
    logger.info(CommonUtils.rpad("Test Type: " + testType, len, " "));
    logger.info(CommonUtils.rpad("  " + testTypeMessage, len, " "));
    logger.info("                                                        ");
    logger.info(CommonUtils.rpad("Total Successful        Queries: " + totalSuccessQueries, len, " "));
    logger.info(CommonUtils.rpad("Total Successful     Procedures: " + totalSuccessProcs, len, " "));
    logger.info(CommonUtils.rpad("Total Successful   Web Services: " + totalSuccessWS, len, " "));
    logger.info("                                 ---------              ");
    logger.info(CommonUtils.rpad("Total Successful -------> Tests: " + totalSuccessTests, len, " "));
    logger.info("                                                        ");
    logger.info(CommonUtils.rpad("Total Skipped           Queries: " + totalSkippedQueries, len, " "));
    logger.info(CommonUtils.rpad("Total Skipped        Procedures: " + totalSkippedProcs, len, " "));
    logger.info(CommonUtils.rpad("Total Skipped      Web Services: " + totalSkippedWS, len, " "));
    logger.info("                                 ---------              ");
    logger.info(CommonUtils.rpad("Total Skipped ----------> Tests: " + totalSkippedTests, len, " "));
    logger.info("                                                        ");
    logger.info(CommonUtils.rpad("Total Failed            Queries: " + totalFailedQueries, len, " "));
    logger.info(CommonUtils.rpad("Total Failed         Procedures: " + totalFailedProcs, len, " "));
    logger.info(CommonUtils.rpad("Total Failed       Web Services: " + totalFailedWS, len, " "));
    logger.info("                                 ---------              ");
    logger.info(CommonUtils.rpad("Total Failed -----------> Tests: " + totalFailedTests, len, " "));
    logger.info("                                                        ");
    logger.info(CommonUtils.rpad(
            "Total Combined ---------> Tests: " + (totalSuccessTests + totalSkippedTests + totalFailedTests),
            len, " "));
    logger.info("                                                        ");
    logger.info(CommonUtils.rpad("      Performance Test duration: " + duration, len, " "));
    logger.info("                                                        ");
    logger.info("Review \"perftest\" Summary: " + logFilePath);
    logger.info("--------------------------------------------------------");

    String moduleActionMessage = "MODULE_INFO: Performance Summary: Successful=" + totalSuccessTests
            + " Skipped=" + totalSkippedTests + " Failed=" + totalFailedTests;
    System.setProperty("MODULE_ACTION_MESSAGE", moduleActionMessage);

    // 3. Close all connections: 
    JdbcConnector connector = new JdbcConnector();
    if (cisConnections != null) {
        for (Connection nextConnection : cisConnections.values()) // getting all non-null values
        {
            connector.closeJdbcConnection(nextConnection);
        }
        cisConnections = null;
    }
    RegressionManagerUtils.printOutputStr(printOutputType, "summary", "\nCompleted executePerformanceTest()",
            "");
}

From source file:com.freedomotic.plugins.devices.ipx800.Ipx800.java

private Document getXMLStatusFile(Board board) {
    final Board b = board;
    //get the xml file from the socket connection
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {//from w  ww  . j  av  a  2  s . c  o  m
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        LOG.error(ex.getMessage());
    }
    Document doc = null;
    String statusFileURL = null;
    try {
        if (board.getAuthentication().equalsIgnoreCase("true")) {
            Authenticator.setDefault(new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(b.getUsername(), b.getPassword().toCharArray());
                }
            });
            statusFileURL = "http://" + b.getIpAddress() + ":" + Integer.toString(b.getPort())
                    + b.getPathAuthentication() + "/" + GET_STATUS_URL;
        } else {
            statusFileURL = "http://" + board.getIpAddress() + ":" + Integer.toString(board.getPort()) + "/"
                    + GET_STATUS_URL;
        }
        LOG.info("Ipx800 gets relay status from file {0}", statusFileURL);
        doc = dBuilder.parse(new URL(statusFileURL).openStream());
        doc.getDocumentElement().normalize();
    } catch (ConnectException connEx) {
        LOG.error(Freedomotic.getStackTraceInfo(connEx));
        //disconnect();
        this.stop();
        this.setDescription("Connection timed out, no reply from the board at " + statusFileURL);
    } catch (SAXException ex) {
        //this.stop();
        LOG.error(Freedomotic.getStackTraceInfo(ex));
    } catch (Exception ex) {
        //this.stop();
        setDescription("Unable to connect to " + statusFileURL);
        LOG.error(Freedomotic.getStackTraceInfo(ex));
    }
    return doc;
}

From source file:hudson.remoting.Launcher.java

public void run() throws Exception {
    if (auth != null) {
        final int idx = auth.indexOf(':');
        if (idx < 0)
            throw new CmdLineException(null, "No ':' in the -auth option");
        Authenticator.setDefault(new Authenticator() {
            @Override//www .j  av a  2s . c  o m
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(auth.substring(0, idx),
                        auth.substring(idx + 1).toCharArray());
            }
        });
    }
    if (connectionTarget != null) {
        runAsTcpClient();
        System.exit(0);
    } else if (slaveJnlpURL != null) {
        List<String> jnlpArgs = parseJnlpArguments();
        try {
            hudson.remoting.jnlp.Main._main(jnlpArgs.toArray(new String[jnlpArgs.size()]));
        } catch (CmdLineException e) {
            System.err.println("JNLP file " + slaveJnlpURL + " has invalid arguments: " + jnlpArgs);
            System.err.println("Most likely a configuration error in the master");
            System.err.println(e.getMessage());
            System.exit(1);
        }
    } else if (tcpPortFile != null) {
        runAsTcpServer();
        System.exit(0);
    } else {
        runWithStdinStdout();
        System.exit(0);
    }
}

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

public static String updateResourceInstance(String commonName, String state) {
    ResourceInstance ri = getResourceInstance(commonName);
    if (ri == null)
        return null;

    Client c = Client.create();//from w  w w .  java2 s.  c  om
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/resourceInstance/" + ri.getId());
    ResourceInstanceInstanceDocument riDoc = ResourceInstanceInstanceDocument.Factory.newInstance();
    riDoc.addNewResourceInstanceInstance();
    riDoc.getResourceInstanceInstance().setCommonName(ri.getCommonName());
    riDoc.getResourceInstanceInstance().setResourceSpec(ri.getResourceSpec().getId());
    riDoc.getResourceInstanceInstance().setStateId(state);
    riDoc.getResourceInstanceInstance().setShared("true");
    riDoc.getResourceInstanceInstance().setDescription("singleton " + ri.getCommonName());

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

    System.out.println(request);
    String resp = r.type(MediaType.TEXT_XML).put(String.class, request);

    resp = addSchemaDefinition(resp);
    try {
        ResourceInstanceDocument pcDoc = ResourceInstanceDocument.Factory.parse(resp);
        return pcDoc.getResourceInstance().getId();
    } catch (XmlException ex) {
        return null;
    }

}

From source file:io.uploader.drive.config.Configuration.java

private void setProxy() {
    setProxySystemProperty(httpProxySettings, "http");
    setProxySystemProperty(httpsProxySettings, "https");

    Authenticator.setDefault(new Authenticator() {
        @Override/*w  ww .jav  a2 s.c o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            if (getRequestorType() == RequestorType.PROXY) {
                String prot = getRequestingProtocol().toLowerCase();

                String host = System.getProperty(prot + ".proxyHost", "");
                String port = System.getProperty(prot + ".proxyPort", "80");
                String user = System.getProperty(prot + ".proxyUser", "");
                String password = System.getProperty(prot + ".proxyPassword", "");

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

From source file:org.caleydo.data.importer.tcga.Settings.java

public boolean validate() {
    if (dataRuns == null)
        dataRuns = analysisRuns;//from ww  w  .j  ava 2s  .c  o  m
    if (dataRuns.size() != analysisRuns.size()) {
        System.err.println(
                "Error during parsing of program arguments. You need to provide a corresponding data run for each analysis run. Closing program.");
        return false;
    }

    if (numThreads <= 0)
        numThreads = Runtime.getRuntime().availableProcessors();

    if (username != null && password != null) {
        username = fixPrompt(username, "Enter the username: ");
        password = fixPrompt(password, "Enter the password: ");
        // set Authenticator for following urls
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password.toCharArray());
            }
        });
    }

    if (awgGroup != null) {
        String tumor = awgGroup.toUpperCase();
        // check if not manually overridden
        if (analysisPattern.equals(ANALYSIS_PATTERN))
            analysisPattern = BASE_URL + "awg_" + awgGroup
                    + "__{0,date,yyyy_MM_dd}/data/{2}/{0,date,yyyyMMdd}/{3}";
        if (filePattern.equals(FILE_PATTERN))
            filePattern = "gdac.broadinstitute.org_{1}.{3}.Level_{4}.{0,date,yyyyMMdd}00.0.0.tar.gz";
        if (dataPattern.equals(DATA_PATTERN))
            dataPattern = BASE_URL + "/stddata__{0,date,yyyy_MM_dd}/data/" + tumor + "/{0,date,yyyyMMdd}/{3}";
        if (dataFilePattern.equals(DATAFILE_PATTERN))
            dataFilePattern = "gdac.broadinstitute.org_" + tumor
                    + ".{3}.Level_{4}.{0,date,yyyyMMdd}00.0.0.tar.gz";
        if (reportPattern.equals(REPORT_PATTERN))
            reportPattern = BASE_URL + "awg_" + awgGroup + "__{0,date,yyyy_MM_dd}/reports/cancer/{1}/";
    }

    return true;
}

From source file:org.kawanfw.commons.client.http.HttpTransferOne.java

/**
 * Sets the proxy credentials/*  w  w w. j  ava2  s . c om*/
 * 
 */
private void setProxyCredentials() {

    if (proxy == null) {
        try {
            displayErrroMessageIfNoProxySet();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    // Sets the credential for authentication
    if (passwordAuthentication != null) {
        final String proxyAuthUsername = passwordAuthentication.getUserName();
        final char[] proxyPassword = passwordAuthentication.getPassword();

        Authenticator authenticator = new Authenticator() {

            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyAuthUsername, proxyPassword);
            }
        };

        Authenticator.setDefault(authenticator);
    }

}

From source file:hudson.ProxyConfiguration.java

public static InputStream getInputStream(URL url) throws IOException {
    Jenkins h = Jenkins.getInstance(); // this code might run on slaves
    final ProxyConfiguration p = (h != null) ? h.proxy : null;
    if (p == null)
        return new RetryableHttpStream(url);

    InputStream is = new RetryableHttpStream(url, p.createProxy(url.getHost()));
    if (p.getUserName() != null) {
        // Add an authenticator which provides the credentials for proxy authentication
        Authenticator.setDefault(new Authenticator() {

            @Override/*w  w  w  .  ja va2  s.  com*/
            public PasswordAuthentication getPasswordAuthentication() {
                if (getRequestorType() != RequestorType.PROXY) {
                    return null;
                }
                return new PasswordAuthentication(p.getUserName(), p.getPassword().toCharArray());
            }
        });
    }

    return is;
}

From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java

public Resolution directRequest() throws UnsupportedEncodingException, URISyntaxException, URIException,
        IOException, SAXException, ParserConfigurationException {
    Double x1 = x - offset;//  ww w . ja va  2  s  .  com
    Double y1 = y - offset;
    Double x2 = x + offset;
    Double y2 = y + offset;
    final String username = "B3_develop";
    final String password = "8ndj39";
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

    Coordinate coord = new Coordinate(x, y);
    Point point = geometryFactory.createPoint(coord);

    URL url2 = new URL(
            "https://atlas.cyclomedia.com/recordings/wfs?service=WFS&VERSION=1.1.0&maxFeatures=100&request=GetFeature&SRSNAME=EPSG:28992&typename=atlas:Recording"
                    + "&filter=<Filter><And><BBOX><gml:Envelope%20srsName=%27EPSG:28992%27>"
                    + "<gml:lowerCorner>" + x1.intValue() + "%20" + y1.intValue() + "</gml:lowerCorner>"
                    + "<gml:upperCorner>" + x2.intValue() + "%20" + y2.intValue()
                    + "</gml:upperCorner></gml:Envelope></BBOX><ogc:PropertyIsNull><ogc:PropertyName>expiredAt</ogc:PropertyName></ogc:PropertyIsNull></And></Filter>");

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });
    InputStream is = url2.openStream();

    // wrap the urlconnection in a bufferedreader
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

    String line;

    StringBuilder content = new StringBuilder();
    // read from the urlconnection via the bufferedreader
    while ((line = bufferedReader.readLine()) != null) {
        content.append(line + "\n");
    }
    bufferedReader.close();

    String s = content.toString();
    String tsString = "timeStamp=";
    int indexOfTimestamp = s.indexOf(tsString);
    int indexOfLastQuote = s.indexOf("\"", indexOfTimestamp + 2 + tsString.length());
    String contentString = s.substring(0, indexOfTimestamp - 2);
    contentString += s.substring(indexOfLastQuote);

    contentString = removeDates(contentString, "<atlas:recordedAt>", "</atlas:recordedAt>");

    Configuration configuration = new org.geotools.gml3.GMLConfiguration();
    configuration.getContext().registerComponentInstance(new GeometryFactory(new PrecisionModel(), 28992));

    Parser parser = new Parser(configuration);
    parser.setValidating(false);
    parser.setStrict(false);
    parser.setFailOnValidationError(false);

    ByteArrayInputStream bais = new ByteArrayInputStream(contentString.getBytes());
    Object obj = parser.parse(bais);

    SimpleFeatureCollection fc = (SimpleFeatureCollection) obj;

    SimpleFeatureIterator it = fc.features();
    SimpleFeature sf = null;
    List<SimpleFeature> fs = new ArrayList<SimpleFeature>();
    while (it.hasNext()) {
        sf = it.next();
        sf.getUserData().put(DISTANCE_KEY, point.distance((Geometry) sf.getDefaultGeometry()));
        fs.add(sf);
    }
    Collections.sort(fs, new Comparator<SimpleFeature>() {
        @Override
        public int compare(SimpleFeature o1, SimpleFeature o2) {
            Double d1 = (Double) o1.getUserData().get(DISTANCE_KEY);
            Double d2 = (Double) o2.getUserData().get(DISTANCE_KEY);
            return d1.compareTo(d2);
        }
    });
    SimpleFeature f = fs.get(0);
    imageId = (String) f.getAttribute("imageId");
    sign();
    return new ForwardResolution("/WEB-INF/jsp/app/globespotter.jsp");
}