Example usage for java.util.regex Matcher quoteReplacement

List of usage examples for java.util.regex Matcher quoteReplacement

Introduction

In this page you can find the example usage for java.util.regex Matcher quoteReplacement.

Prototype

public static String quoteReplacement(String s) 

Source Link

Document

Returns a literal replacement String for the specified String .

Usage

From source file:org.rhq.enterprise.server.core.EmailManagerBean.java

private String cleanse(String passedValue, String defaultValue) {
    String results = passedValue;
    if (results == null) {
        results = defaultValue;//from  w w w  . ja v a 2  s  . c  o m
    }
    // cleanse no matter what, because it's possible the defaultValue has invalid characters too
    return Matcher.quoteReplacement(results);
}

From source file:org.nuxeo.common.utils.TextTemplate.java

/**
 * That method is not recursive. It processes the given text only once.
 *
 * @param props CryptoProperties containing the variable values
 * @param text Text to process// ww w .  j  av a 2 s . c o  m
 * @return the processed text
 * @since 7.4
 */
protected String processString(CryptoProperties props, String text) {
    Matcher m = PATTERN.matcher(text);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        // newVarsValue == ${[#]embeddedVar[:=default]}
        String embeddedVar = m.group(PATTERN_GROUP_VAR);
        String value = props.getProperty(embeddedVar, keepEncryptedAsVar);
        if (value == null) {
            value = m.group(PATTERN_GROUP_DEFAULT);
        }
        if (value != null) {
            if (trim) {
                value = value.trim();
            }
            if (Crypto.isEncrypted(value)) {
                if (keepEncryptedAsVar && m.group(PATTERN_GROUP_DECRYPT) == null) {
                    value = "${" + embeddedVar + "}";
                } else {
                    value = new String(vars.getCrypto().decrypt(value));
                }
            }

            // Allow use of backslash and dollars characters
            value = Matcher.quoteReplacement(value);
            m.appendReplacement(sb, value);
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:org.springframework.integration.sftp.outbound.SftpServerOutboundTests.java

@Test
@SuppressWarnings("unchecked")
public void testInt3172LocalDirectoryExpressionMGETRecursive() throws IOException {
    String dir = "sftpSource/";
    long modified = setModifiedOnSource1();
    File secondRemote = new File(getSourceRemoteDirectory(), "sftpSource2.txt");
    secondRemote.setLastModified(System.currentTimeMillis() - 1_000_000);
    this.inboundMGetRecursive.send(new GenericMessage<Object>(dir + "*"));
    Message<?> result = this.output.receive(1000);
    assertNotNull(result);/*from  w  ww . j  a v  a  2 s  .  co m*/
    List<File> localFiles = (List<File>) result.getPayload();
    assertEquals(3, localFiles.size());

    boolean assertedModified = false;
    for (File file : localFiles) {
        assertThat(file.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
                containsString(dir));
        if (file.getPath().contains("localTarget1")) {
            assertedModified = assertPreserved(modified, file);
        }
    }
    assertTrue(assertedModified);
    assertThat(localFiles.get(2).getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
            containsString(dir + "subSftpSource"));

    File secondTarget = new File(getTargetLocalDirectory() + File.separator + "sftpSource", "localTarget2.txt");
    ByteArrayOutputStream remoteContents = new ByteArrayOutputStream();
    ByteArrayOutputStream localContents = new ByteArrayOutputStream();
    FileUtils.copyFile(secondRemote, remoteContents);
    FileUtils.copyFile(secondTarget, localContents);
    String localAsString = new String(localContents.toByteArray());
    assertEquals(new String(remoteContents.toByteArray()), localAsString);
    long oldLastModified = secondRemote.lastModified();
    FileUtils.copyInputStreamToFile(new ByteArrayInputStream("junk".getBytes()), secondRemote);
    long newLastModified = secondRemote.lastModified();
    secondRemote.setLastModified(oldLastModified);
    this.inboundMGetRecursive.send(new GenericMessage<Object>(dir + "*"));
    this.output.receive(0);
    localContents = new ByteArrayOutputStream();
    FileUtils.copyFile(secondTarget, localContents);
    assertEquals(localAsString, new String(localContents.toByteArray()));
    secondRemote.setLastModified(newLastModified);
    this.inboundMGetRecursive.send(new GenericMessage<Object>(dir + "*"));
    this.output.receive(0);
    localContents = new ByteArrayOutputStream();
    FileUtils.copyFile(secondTarget, localContents);
    assertEquals("junk", new String(localContents.toByteArray()));
    // restore the remote file contents
    FileUtils.copyInputStreamToFile(new ByteArrayInputStream(localAsString.getBytes()), secondRemote);
}

From source file:org.entando.edo.builder.TestBuilder.java

@Test
public void test_Controller_Spring_Xml() throws IOException {
    String commonPath = "src/main/resources/spring/plugins/jppet/apsadmin".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

    File actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    List<File> actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:org.apache.falcon.expression.ExpressionHelper.java

public static String substitute(String originalValue, Properties properties) {
    Matcher envVarMatcher = SYS_PROPERTY_PATTERN.matcher(originalValue);
    while (envVarMatcher.find()) {
        String envVar = originalValue.substring(envVarMatcher.start() + 2, envVarMatcher.end() - 1);
        String envVal = properties.getProperty(envVar, System.getenv(envVar));

        envVar = "\\$\\{" + envVar + "\\}";
        if (envVal != null) {
            originalValue = originalValue.replaceAll(envVar, Matcher.quoteReplacement(envVal));
            envVarMatcher = SYS_PROPERTY_PATTERN.matcher(originalValue);
        }//from   ww  w.j av a  2  s.c om
    }
    return originalValue;
}

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 ww . java  2 s. co  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:cz.cuni.mff.d3s.tools.perfdoc.server.measuring.codegen.CodeGenerator.java

private void makeAndCompileMeasurementCode(BenchmarkSetting setting) throws CompileException, IOException {

    MethodReflectionInfo mrInfo = (MethodReflectionInfo) setting.getTestedMethod();
    Method testedMethod = mrInfo.getMethod();
    MeasurementQuality measurementQuality = setting.getMeasurementQuality();

    VelocityContext context = new VelocityContext();

    context.put("priority", measurementQuality.getPriority());
    context.put("warmupTime", measurementQuality.getWarmupTime());
    context.put("warmupCycles", measurementQuality.getNumberOfWarmupCycles());
    context.put("measurementCycles", measurementQuality.getNumberOfMeasurementsCycles());
    context.put("measurementTime", measurementQuality.getMeasurementTime());

    String pathToMainDir = System.getProperty("user.dir");
    String pathToDir = pathToMainDir + File.separator
            + getDirectory().replaceAll("/", Matcher.quoteReplacement(File.separator)) + File.separator;
    context.put("directoryWhereToSaveResults", StringEscapeUtils.escapeJava(pathToDir));

    context.put("mClass", mrInfo.getContainingClass().getName());
    context.put("mFunctionIsStatic", Modifier.isStatic(testedMethod.getModifiers()));

    writeCode(context, templateMeasurementName);

    String javaClassDirectory = compiledClassDestinationDir + directoryName;
    String javaSourceName = javaDestinationDir + directoryName + "/" + templateMeasurementName + ".java";

    List<String> classPaths = getCompilationClassPaths();
    classPaths.add(javaClassDirectory);//from   w  w w .  j av a2 s .  c om

    Compiler.compile(javaSourceName, classPaths);
}

From source file:org.rhq.plugins.jbossas.script.ScriptComponent.java

private String replacePropertyPatterns(String envVars) {
    Pattern pattern = Pattern.compile("(%([^%]*)%)");
    Matcher matcher = pattern.matcher(envVars);
    Configuration parentPluginConfig = this.resourceContext.getParentResourceComponent()
            .getPluginConfiguration();/*  w w w  . java  2s  .c  om*/
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        String propName = matcher.group(2);
        PropertySimple prop = parentPluginConfig.getSimple(propName);
        String propPattern = matcher.group(1);
        String replacement = (prop != null) ? prop.getStringValue() : propPattern;
        matcher.appendReplacement(buffer, Matcher.quoteReplacement(replacement));
    }

    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:com.arrow.acn.client.api.DeviceApi.java

/**
 * Sends GET request to obtain events related to specific device and
 * corresponding {@code criteria}//from   w  w  w .  ja  v a2 s.  co m
 *
 * @param hid
 *            {@link String} representing device {@code hid}
 * @param criteria
 *            {@link EventsSearchCriteria} representing search filter
 *            parameters.
 *
 * @return subset of {@link DeviceEventModel} containing event parameters.
 *         <b>Note:</b> resulting subset may contain not all events
 *         corresponding to search parameters because it cannot exceed page
 *         size passed in{@code
 * criteria}
 *
 * @throws AcnClientException
 *             if request failed
 */
public PagingResultModel<DeviceEventModel> listHistoricalDeviceEvents(String hid,
        EventsSearchCriteria criteria) {
    String method = "listHistoricalDeviceEvents";
    try {
        URI uri = buildUri(PATTERN.matcher(SPECIFIC_EVENTS_URL).replaceAll(Matcher.quoteReplacement(hid)),
                criteria);
        PagingResultModel<DeviceEventModel> result = execute(new HttpGet(uri), criteria,
                getDeviceEventModelTypeRef());
        log(method, result);
        return result;
    } catch (Throwable e) {
        logError(method, e);
        throw new AcnClientException(method, e);
    }
}

From source file:org.apache.nifi.processors.standard.util.FTPUtils.java

/**
 * Handles the logic required to change to the given directory RELATIVE TO THE CURRENT DIRECTORY which can include creating new directories needed.
 *
 * This will first attempt to change to the full path of the given directory outright. If that fails, then it will attempt to change from the top of the tree of the given directory all the way
 * down to the final leaf node of the given directory.
 *
 * @param client - the ftp client with an already active connection
 * @param dirPath - the path to change or create directories to
 * @param createDirs - if true will attempt to create any missing directories
 * @param processor - used solely for targeting logging output.
 * @throws IOException if any access problem occurs
 *//*w w  w  .  j  av a  2  s.c  om*/
public static void changeWorkingDirectory(final FTPClient client, final String dirPath,
        final boolean createDirs, final Processor processor) throws IOException {
    final String currentWorkingDirectory = client.printWorkingDirectory();
    final File dir = new File(dirPath);
    logger.debug(processor + " attempting to change directory from " + currentWorkingDirectory + " to "
            + dir.getPath());
    boolean dirExists = false;
    final String forwardPaths = dir.getPath().replaceAll(Matcher.quoteReplacement("\\"),
            Matcher.quoteReplacement("/"));
    //always use forward paths for long string attempt
    try {
        dirExists = client.changeWorkingDirectory(forwardPaths);
        if (dirExists) {
            logger.debug(processor + " changed working directory to '" + forwardPaths + "' from '"
                    + currentWorkingDirectory + "'");
        } else {
            logger.debug(processor + " could not change directory to '" + forwardPaths + "' from '"
                    + currentWorkingDirectory + "' so trying the hard way.");
        }
    } catch (final IOException ioe) {
        logger.debug(processor + " could not change directory to '" + forwardPaths + "' from '"
                + currentWorkingDirectory + "' so trying the hard way.");
    }
    if (!dirExists) { //couldn't navigate directly...begin hard work
        final Deque<String> stack = new LinkedList<>();
        File fakeFile = new File(dir.getPath());
        do {
            stack.push(fakeFile.getName());
        } while ((fakeFile = fakeFile.getParentFile()) != null);

        String dirName = null;
        while ((dirName = stack.peek()) != null) {
            stack.pop();
            //find out if exists, if not make it if configured to do so or throw exception
            dirName = ("".equals(dirName.trim())) ? "/" : dirName;
            boolean exists = false;
            try {
                exists = client.changeWorkingDirectory(dirName);
            } catch (final IOException ioe) {
                exists = false;
            }
            if (!exists && createDirs) {
                logger.debug(processor + " creating new directory and changing to it " + dirName);
                client.makeDirectory(dirName);
                if (!(client.makeDirectory(dirName) || client.changeWorkingDirectory(dirName))) {
                    throw new IOException(
                            processor + " could not create and change to newly created directory " + dirName);
                } else {
                    logger.debug(processor + " successfully changed working directory to " + dirName);
                }
            } else if (!exists) {
                throw new IOException(processor + " could not change directory to '" + dirName + "' from '"
                        + currentWorkingDirectory + "'");
            }
        }
    }
}