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:com.cisco.dvbu.ps.deploytool.dao.jdbcapi.RegressionInputFileJdbcDAOImpl.java

/**
 * Generates pubtest input file for a given CIS instance and other input parameters, such as domain, user, published datasource and others. 
 * /*  w  ww . j a v a  2s .  c o  m*/
 * @param cisServerConfig         composite server object used for connections
 * @param regressionConfig         regression config object
 * @param regressionQueries       regression query object
 * 
 * @return String representation of the input file
 * 
 * @throws CompositeException
 */
public String generateInputFile(CompositeServer cisServerConfig, RegressionTestType regressionConfig,
        RegressionQueriesType regressionQueries) // String serverId, String dsList, String pathToRegressionXML, String pathToServersXML)
        throws CompositeException {
    // First check the input parameter values:
    if (cisServerConfig == null || regressionConfig == null) {
        throw new CompositeException("XML Configuration objects are not initialized "
                + "when trying to generate Regression input file.");
    }

    // Set the command and action name
    String command = "generateInputFile";
    String actionName = "CREATE_FILE";

    // Initialize start time and format
    Date startDate = new Date();

    // Initialize all variables
    String prefix = "generateInputFile";
    String outString = null; // Output String the above buffer is converted to.   

    String queriesStr = "";
    String proceduresStr = "";
    String wsStr = "";
    boolean getActualLinkType = false;

    // Get the DEBUG3 value from the property file
    setGlobalProperties();

    populateConfigValues(regressionConfig, regressionQueries);

    totalQueriesGenerated = 0;
    totalProceduresGenerated = 0;
    totalWebServicesGenerated = 0;

    // Begin the input file generation
    if (this.needQueries) {
        /**
         * [QUERY]
        * database=MYTEST
        * SELECT count(1) cnt FROM CAT1.SCH1.customers
         */
        RegressionItem[] items = buildQueriesString(cisServerConfig, regressionConfig);

        // Output the query to the input file
        for (int i = 0; i < items.length; i++) {
            StringBuffer buf = new StringBuffer();
            RegressionItem item = new RegressionItem();
            item = items[i];
            buf.append("[QUERY]\n");
            buf.append("database=" + item.database + "\n"); // datasource
            if (item.outputFilename != null)
                buf.append("outputFilename=" + item.outputFilename + "\n"); // outputFilename
            buf.append(item.input + "\n\n"); // patterns: table | schema.table | cat.schema.table
            queriesStr = queriesStr + buf.toString();

            // Add debug statement to log output when debug3=true
            CommonUtils.writeOutput(
                    "Added query to query list:           resource path=" + item.resourcePath + "  type="
                            + item.resourceType + "  query=" + item.input,
                    prefix, "-debug3", logger, debug1, debug2, debug3);
        }
    }
    if (this.needProcs) {
        if (this.useSelectForProcs) {
            /**
             * [PROCEDURE]
            * database=MYTEST
            * SELECT * FROM CAT1.SCH1.LookupProduct(1)
             */
            RegressionItem[] items = buildProcsStringSelectSyntax(cisServerConfig, regressionConfig);

            // Output the query to the input file
            for (int i = 0; i < items.length; i++) {
                StringBuffer buf = new StringBuffer();
                RegressionItem item = new RegressionItem();
                item = items[i];
                buf.append("[PROCEDURE]\n");
                buf.append("database=" + item.database + "\n"); // datasource
                if (item.outTypes != null && item.outTypes.length > 0) {
                    String outTypes = null;
                    for (int j = 0; j < item.outTypes.length; j++) {
                        if (outTypes == null) {
                            outTypes = "";
                        } else {
                            outTypes = outTypes + ", ";
                        }
                        outTypes = outTypes + item.outTypes[j];
                    }
                    buf.append("outTypes=" + outTypes + "\n");
                }
                if (item.outputFilename != null)
                    buf.append("outputFilename=" + item.outputFilename + "\n"); // outputFilename
                buf.append(item.input + "\n\n"); // patterns: table | schema.table | cat.schema.table
                proceduresStr = proceduresStr + buf.toString();

                // Add debug statement to log output when debug3=true
                CommonUtils.writeOutput(
                        "Added procedure to query list:       resource path=" + item.resourcePath + "  type="
                                + item.resourceType + "  query=" + item.input,
                        prefix, "-debug3", logger, debug1, debug2, debug3);
            }
        } else {
            /**
             * [PROCEDURE]
            * database=MYTEST
            * CALL CAT1.SCH1.LookupProduct(1)
             */
            RegressionItem[] items = buildProcsStringCallSyntax(cisServerConfig, regressionConfig);

            // Output the query to the input file
            for (int i = 0; i < items.length; i++) {
                StringBuffer buf = new StringBuffer();
                RegressionItem item = new RegressionItem();
                item = items[i];
                buf.append("[PROCEDURE]\n");
                buf.append("database=" + item.database + "\n"); // datasource
                if (item.outTypes != null && item.outTypes.length > 0) {
                    String outTypes = null;
                    for (int j = 0; j < item.outTypes.length; j++) {
                        if (outTypes == null) {
                            outTypes = "";
                        } else {
                            outTypes = outTypes + ", ";
                        }
                        outTypes = outTypes + item.outTypes[j];
                    }
                    buf.append("outTypes=" + outTypes + "\n");
                }
                if (item.outputFilename != null)
                    buf.append("outputFilename=" + item.outputFilename + "\n"); // outputFilename
                buf.append(item.input + "\n\n"); // patterns: table | schema.table | cat.schema.table
                proceduresStr = proceduresStr + buf.toString();

                // Add debug statement to log output when debug3=true
                CommonUtils.writeOutput(
                        "Added call procedure to query list:  resource path=" + item.resourcePath + "  type="
                                + item.resourceType + "  query=" + item.input,
                        prefix, "-debug3", logger, debug1, debug2, debug3);
            }
        }
    }
    if (this.needWs) {
        /**
         * [WEB_SERVICE]
        *   database=testWebService00_NoParams_wrapped
        *   path=/soap11/testWebService00_NoParams_wrapped
        *   action=ViewSales
        *   encrypt=false
        *   contentType=text/xml;charset=UTF-8
        *   <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/">
        *      <soapenv:Header/>
        *       <soapenv:Body>
        *           <ns1:ViewSales>
        *               <ns1:ViewSalesInput></ns1:ViewSalesInput>
        *           </ns1:ViewSales>
        *       </soapenv:Body>
        *   </soapenv:Envelope>
         */
        RegressionItem[] items = buildWsString(cisServerConfig, regressionConfig, getActualLinkType);

        // Output the query to the input file
        for (int i = 0; i < items.length; i++) {
            StringBuffer buf = new StringBuffer();
            RegressionItem item = new RegressionItem();
            item = items[i];
            buf.append("[WEB_SERVICE]\n");
            buf.append("database=" + item.database + "\n");
            buf.append("path=" + item.path + "\n"); // name of the web service port with path is the path in the input file 
            buf.append("action=" + item.action + "\n");
            buf.append("encrypt=" + item.encrypt + "\n");
            buf.append("contentType=" + item.contentType + "\n");
            if (item.outputFilename != null)
                buf.append("outputFilename=" + item.outputFilename + "\n"); // outputFilename
            buf.append(item.input + "\n\n");
            wsStr = wsStr + buf.toString();

            // Add debug statement to log output when debug3=true
            String queryNoLines = item.input.replaceAll(Pattern.quote("\n"), Matcher.quoteReplacement(""));
            CommonUtils.writeOutput(
                    "Added web service to query list:     resource path=" + item.resourcePath + "  type="
                            + item.resourceType + "  query=" + queryNoLines,
                    prefix, "-debug3", logger, debug1, debug2, debug3);
        }
    }

    // Write the pubtest input file to the file system.
    outString = new String(fileDescription + queriesStr + proceduresStr + wsStr); // Built String
    String filePath = CommonUtils.extractVariable(prefix, regressionConfig.getInputFilePath(), propertyFile,
            true);

    // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
    if (CommonUtils.isExecOperation()) {
        CommonUtils.createFileWithContent(filePath, outString);
    } else {
        logger.info(
                "NO_OPERATION SET: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.");
    }

    // Print out timings
    String duration = CommonUtils.getElapsedTime(startDate);

    int len = 56;
    logger.info("--------------------------------------------------------");
    logger.info("------------ Regression Generation Summary -------------");
    logger.info("--------------------------------------------------------");
    logger.info("                                                        ");
    logger.info(CommonUtils.rpad("            Total Queries Generated: " + totalQueriesGenerated, len, " "));
    logger.info(CommonUtils.rpad("         Total Procedures Generated: " + totalProceduresGenerated, len, " "));
    logger.info(
            CommonUtils.rpad("       Total Web Services Generated: " + totalWebServicesGenerated, len, " "));
    logger.info("                                     ---------          ");
    logger.info(CommonUtils.rpad(
            "Total Combined ---------> Generated: "
                    + (totalQueriesGenerated + totalProceduresGenerated + totalWebServicesGenerated),
            len, " "));
    logger.info("                                                        ");
    logger.info(CommonUtils.rpad("     Input file generation duration: " + duration, len, " "));
    logger.info("                                                        ");
    logger.info("Review input file: " + filePath);
    logger.info("--------------------------------------------------------");

    String moduleActionMessage = "MODULE_INFO: Generate Summary: Queries=" + totalQueriesGenerated
            + " Procedures=" + totalProceduresGenerated + " WebServices=" + totalWebServicesGenerated;
    System.setProperty("MODULE_ACTION_MESSAGE", moduleActionMessage);

    return outString;
}

From source file:org.infoglue.cms.controllers.kernel.impl.simple.InstallationController.java

public void updateServer(String appServer, String smtpServer, String smtpAuth, String smtpUser,
        String smtpPassword, String systemEmailSender, String hostName, String superUserName,
        String superUserPassword, String superUserEmail, String operatingMode, HttpServletRequest request)
        throws Exception {
    if (appServer.equals("") || hostName.equals("") || superUserName.equals("") || superUserPassword.equals("")
            || superUserEmail.equals("") || operatingMode.equals("")) {
        throw new Exception("Mandatory field(s) missing");
    }//from www .j  a v  a 2  s. c  om

    String dbProvider = (String) request.getSession().getAttribute("install_dbProvider");
    //String jdbcDriverName = (String)request.getSession().getAttribute("install_jdbcDriverName");
    //String jdbcURL = (String)request.getSession().getAttribute("install_jdbcURL");
    //String igUser = (String)request.getSession().getAttribute("install_dbUser");
    //String igPassword = (String)request.getSession().getAttribute("install_dbPassword");

    if (dbProvider == null) {
        dbProvider = getJDBCEngine();
        request.getSession().setAttribute("install_dbProvider", dbProvider);
    }

    //String jdbcEngine = getJDBCEngine();

    //cms.properties
    String cmsFilePath = CastorDatabaseService.class.getResource("/cms.properties").toURI().getPath();
    if (logger.isInfoEnabled())
        logger.info("cmsFilePath:" + cmsFilePath);
    String contents = FileHelper
            .getStreamAsString(CastorDatabaseService.class.getResourceAsStream("/cms.properties"));
    if (logger.isInfoEnabled())
        logger.info("contents:" + contents);

    contents = contents.replaceAll("@configured@", "true");
    contents = contents.replaceAll("@useUpdateSecurity@", "true");
    contents = contents.replaceAll("@externalWebServerAddress@", "");
    contents = contents.replaceAll("@webServerAddress@", "http://" + hostName);
    contents = contents.replaceAll("@digitalAssetPath@", "");
    contents = contents.replaceAll("@URIEncoding@", "UTF-8");
    if (CmsPropertyHandler.getApplicationName().equalsIgnoreCase("cms")) {
        contents = contents.replaceAll("@context.root.cms@", request.getContextPath().replaceAll("/", ""));
        contents = contents.replaceAll("@context.root.working@", "infoglueDeliverWorking");
        contents = contents.replaceAll("@context.root.preview@", "infoglueDeliverPreview");
        contents = contents.replaceAll("@context.root.live@", "infoglueDeliverLive");
    } else {
        if (CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("0")) {
            contents = contents.replaceAll("@context.root.cms@", "infoglueCMS");
            contents = contents.replaceAll("@context.root.working@",
                    request.getContextPath().replaceAll("/", ""));
            contents = contents.replaceAll("@context.root.preview@", "infoglueDeliverPreview");
            contents = contents.replaceAll("@context.root.live@", "infoglueDeliverLive");
        } else if (CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("2")) {
            contents = contents.replaceAll("@context.root.cms@", "infoglueCMS");
            contents = contents.replaceAll("@context.root.working@", "infoglueDeliverWorking");
            contents = contents.replaceAll("@context.root.preview@",
                    request.getContextPath().replaceAll("/", ""));
            contents = contents.replaceAll("@context.root.live@", "infoglueDeliverLive");
        } else if (CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("3")) {
            contents = contents.replaceAll("@context.root.cms@", "infoglueCMS");
            contents = contents.replaceAll("@context.root.working@", "infoglueDeliverWorking");
            contents = contents.replaceAll("@context.root.preview@", "infoglueDeliverPreview");
            contents = contents.replaceAll("@context.root.live@", request.getContextPath().replaceAll("/", ""));
        } else {
            contents = contents.replaceAll("@context.root.cms@", "infoglueCMS");
            contents = contents.replaceAll("@context.root.working@",
                    request.getContextPath().replaceAll("/", ""));
            contents = contents.replaceAll("@context.root.preview@", "infoglueDeliverPreview");
            contents = contents.replaceAll("@context.root.live@", "infoglueDeliverLive");
        }
    }

    String applicationServerRoot = CmsPropertyHandler.getContextRootPath();
    applicationServerRoot = FilenameUtils.separatorsToUnix(applicationServerRoot);
    if (!applicationServerRoot.endsWith("\\")) {
        applicationServerRoot = applicationServerRoot.substring(0, applicationServerRoot.lastIndexOf("/"));
        applicationServerRoot = applicationServerRoot.substring(0, applicationServerRoot.lastIndexOf("/") + 1);
    }
    logger.error("applicationServerRoot:" + applicationServerRoot);

    contents = contents.replaceAll("@useShortTableNames@",
            ((dbProvider.equalsIgnoreCase("oracle") || dbProvider.equalsIgnoreCase("db2")) ? "true" : "false"));
    contents = contents.replaceAll("@database.driver.engine@", dbProvider);
    contents = contents.replaceAll("@warningEmailReceiver@", superUserEmail);
    contents = contents.replaceAll("@operatingMode.cms@", "0");
    contents = contents.replaceAll("@administratorUserName@", superUserName);
    contents = contents.replaceAll("@administratorPassword@", superUserPassword);
    contents = contents.replaceAll("@administratorEmail@", superUserEmail);

    contents = contents.replaceAll("@loginUrl@", "Login.action");
    contents = contents.replaceAll("@logoutUrl@", "");
    contents = contents.replaceAll("@invalidLoginUrl@", "Login!invalidLogin.action");
    contents = contents.replaceAll("@authenticatorClass@",
            "org.infoglue.cms.security.InfoGlueBasicAuthenticationModule");
    contents = contents.replaceAll("@authorizerClass@",
            "org.infoglue.cms.security.InfoGlueBasicAuthorizationModule");
    contents = contents.replaceAll("@serverName@", "" + hostName);
    contents = contents.replaceAll("@authConstraint@", "cmsUser");

    contents = contents.replaceAll("@databaseEngine@", dbProvider);
    contents = contents.replaceAll("@logTransactions@", "false");
    contents = contents.replaceAll("@errorUrl@", "/error.jsp");
    contents = contents.replaceAll("@tree@", "html");
    contents = contents.replaceAll("@showContentVersionFirst@", "true");
    contents = contents.replaceAll("@showComponentsFirst@", "true");
    contents = contents.replaceAll("@protectContentTypes@", "false");
    contents = contents.replaceAll("@protectWorkflows@", "false");
    contents = contents.replaceAll("@protectCategories@", "false");
    contents = contents.replaceAll("@wysiwygEditor@", "ckeditor4");
    contents = contents.replaceAll("@edition.pageSize@", "20");
    contents = contents.replaceAll("@masterServer@", "");
    contents = contents.replaceAll("@slaveServer@", "");
    contents = contents.replaceAll("@up2dateUrl@", "http://www.infoglue.org/ViewPage.action?siteNodeId=23");

    contents = contents.replaceAll("@portletBase@", Matcher.quoteReplacement(applicationServerRoot));
    contents = contents.replaceAll("@mail.smtp.host@", smtpServer);
    contents = contents.replaceAll("@mail.smtp.auth@", smtpAuth);
    contents = contents.replaceAll("@mail.smtp.user@", smtpUser);
    contents = contents.replaceAll("@mail.smtp.password@", smtpPassword);
    contents = contents.replaceAll("@mail.contentType@", "text/html");
    contents = contents.replaceAll("@systemEmailSender@", systemEmailSender);
    contents = contents.replaceAll("@niceURIEncoding@", "utf-8");
    contents = contents.replaceAll("@logDatabaseMessages@", "false");
    contents = contents.replaceAll("@enablePortal@", "true");

    if (logger.isInfoEnabled())
        logger.info("contents after:" + contents);
    if (logger.isInfoEnabled())
        logger.info("Want to write to:" + cmsFilePath);
    File targetFile = new File(cmsFilePath);
    if (logger.isInfoEnabled())
        logger.info("targetFile:" + targetFile.exists());

    FileHelper.writeToFile(targetFile, contents, false);

    CacheController.clearCache("serverNodePropertiesCache");
    CmsPropertyHandler.initializeProperties();
    CmsPropertyHandler.resetHardCachedSettings();
    InfoGlueAuthenticationFilter.initializeCMSProperties();
    //END cms.properties

    //deliver.properties
    String deliverFilePath = CastorDatabaseService.class.getResource("/deliver.properties").toURI().getPath();
    if (logger.isInfoEnabled())
        logger.info("deliverFilePath:" + deliverFilePath);
    String contentsDeliver = FileHelper
            .getStreamAsString(CastorDatabaseService.class.getResourceAsStream("/deliver.properties"));
    if (logger.isInfoEnabled())
        logger.info("contentsDeliver:" + contentsDeliver);

    contentsDeliver = contentsDeliver.replaceAll("@configured@", "true");
    contentsDeliver = contentsDeliver.replaceAll("@useSelectivePageCacheUpdate@", "true");
    contentsDeliver = contentsDeliver.replaceAll("@livePublicationThreadClass@",
            "org.infoglue.deliver.util.SelectiveLivePublicationThread");
    contentsDeliver = contentsDeliver.replaceAll("@compressPageCache@", "true");
    contentsDeliver = contentsDeliver.replaceAll("@siteNodesToRecacheOnPublishing@", "");
    contentsDeliver = contentsDeliver.replaceAll("@pathsToRecacheOnPublishing@", "/");
    contentsDeliver = contentsDeliver.replaceAll("@recachePublishingMethod@", "");
    contentsDeliver = contentsDeliver.replaceAll("@recacheUrl@", "");
    contentsDeliver = contentsDeliver.replaceAll("@useUpdateSecurity@", "true");
    contentsDeliver = contentsDeliver.replaceAll("@forceImportTagFileCaching@", "false");
    contentsDeliver = contentsDeliver.replaceAll("@operatingMode.deliver@", operatingMode);

    if (CmsPropertyHandler.getApplicationName().equalsIgnoreCase("cms")) {
        contentsDeliver = contentsDeliver.replaceAll("@context.root.cms@",
                request.getContextPath().replaceAll("/", ""));
        contentsDeliver = contentsDeliver.replaceAll("@context.root.working@", "infoglueDeliverWorking");
        contentsDeliver = contentsDeliver.replaceAll("@context.root.preview@", "infoglueDeliverPreview");
        contentsDeliver = contentsDeliver.replaceAll("@context.root.live@", "infoglueDeliverLive");
    } else {
        if (CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("0")) {
            contentsDeliver = contentsDeliver.replaceAll("@context.root.cms@", "infoglueCMS");
            contentsDeliver = contentsDeliver.replaceAll("@context.root.working@",
                    request.getContextPath().replaceAll("/", ""));
            contentsDeliver = contentsDeliver.replaceAll("@context.root.preview@", "infoglueDeliverPreview");
            contentsDeliver = contentsDeliver.replaceAll("@context.root.live@", "infoglueDeliverLive");
        } else if (CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("2")) {
            contentsDeliver = contentsDeliver.replaceAll("@context.root.cms@", "infoglueCMS");
            contentsDeliver = contentsDeliver.replaceAll("@context.root.working@", "infoglueDeliverWorking");
            contentsDeliver = contentsDeliver.replaceAll("@context.root.preview@",
                    request.getContextPath().replaceAll("/", ""));
            contentsDeliver = contentsDeliver.replaceAll("@context.root.live@", "infoglueDeliverLive");
        } else if (CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("3")) {
            contentsDeliver = contentsDeliver.replaceAll("@context.root.cms@", "infoglueCMS");
            contentsDeliver = contentsDeliver.replaceAll("@context.root.working@", "infoglueDeliverWorking");
            contentsDeliver = contentsDeliver.replaceAll("@context.root.preview@", "infoglueDeliverPreview");
            contentsDeliver = contentsDeliver.replaceAll("@context.root.live@",
                    request.getContextPath().replaceAll("/", ""));
        } else {
            contentsDeliver = contentsDeliver.replaceAll("@context.root.cms@", "infoglueCMS");
            contentsDeliver = contentsDeliver.replaceAll("@context.root.working@",
                    request.getContextPath().replaceAll("/", ""));
            contentsDeliver = contentsDeliver.replaceAll("@context.root.preview@", "infoglueDeliverPreview");
            contentsDeliver = contentsDeliver.replaceAll("@context.root.live@", "infoglueDeliverLive");
        }
    }

    contentsDeliver = contentsDeliver.replaceAll("@URIEncoding@", "UTF-8");
    contentsDeliver = contentsDeliver.replaceAll("@externalWebServerAddress@", "");
    contentsDeliver = contentsDeliver.replaceAll("@webServerAddress@", "http://" + hostName);
    contentsDeliver = contentsDeliver.replaceAll("@digitalAssetPath@", "");

    contentsDeliver = contentsDeliver.replaceAll("@useShortTableNames@",
            ((dbProvider.equalsIgnoreCase("oracle") || dbProvider.equalsIgnoreCase("db2")) ? "true" : "false"));
    contentsDeliver = contentsDeliver.replaceAll("@database.driver.engine@", dbProvider);
    contentsDeliver = contentsDeliver.replaceAll("@warningEmailReceiver@", superUserEmail);
    contentsDeliver = contentsDeliver.replaceAll("@operatingMode.cms@", "0");
    contentsDeliver = contentsDeliver.replaceAll("@administratorUserName@", superUserName);
    contentsDeliver = contentsDeliver.replaceAll("@administratorPassword@", superUserPassword);
    contentsDeliver = contentsDeliver.replaceAll("@administratorEmail@", superUserEmail);

    contentsDeliver = contentsDeliver.replaceAll("@loginUrl@", "Login.action");
    contentsDeliver = contentsDeliver.replaceAll("@logoutUrl@", "");
    contentsDeliver = contentsDeliver.replaceAll("@invalidLoginUrl@", "Login!invalidLogin.action");
    contentsDeliver = contentsDeliver.replaceAll("@authenticatorClass@",
            "org.infoglue.cms.security.InfoGlueBasicAuthenticationModule");
    contentsDeliver = contentsDeliver.replaceAll("@authorizerClass@",
            "org.infoglue.cms.security.InfoGlueBasicAuthorizationModule");
    contentsDeliver = contentsDeliver.replaceAll("@serverName@", "" + hostName);
    contentsDeliver = contentsDeliver.replaceAll("@authConstraint@", "cmsUser");

    contentsDeliver = contentsDeliver.replaceAll("@databaseEngine@", dbProvider);
    contentsDeliver = contentsDeliver.replaceAll("@logTransactions@", "false");
    contentsDeliver = contentsDeliver.replaceAll("@errorUrl@", "/error.jsp");
    contentsDeliver = contentsDeliver.replaceAll("@tree@", "html");
    contentsDeliver = contentsDeliver.replaceAll("@showContentVersionFirst@", "true");
    contentsDeliver = contentsDeliver.replaceAll("@showComponentsFirst@", "true");
    contentsDeliver = contentsDeliver.replaceAll("@protectContentTypes@", "false");
    contentsDeliver = contentsDeliver.replaceAll("@protectWorkflows@", "false");
    contentsDeliver = contentsDeliver.replaceAll("@protectCategories@", "false");
    contentsDeliver = contentsDeliver.replaceAll("@wysiwygEditor@", "FCKEditor");
    contentsDeliver = contentsDeliver.replaceAll("@edition.pageSize@", "20");
    contentsDeliver = contentsDeliver.replaceAll("@masterServer@", "");
    contentsDeliver = contentsDeliver.replaceAll("@slaveServer@", "");
    contentsDeliver = contentsDeliver.replaceAll("@up2dateUrl@",
            "http://www.infoglue.org/ViewPage.action?siteNodeId=23");
    contentsDeliver = contentsDeliver.replaceAll("@portletBase@",
            Matcher.quoteReplacement(applicationServerRoot));
    contentsDeliver = contentsDeliver.replaceAll("@mail.smtp.host@", smtpServer);
    contentsDeliver = contentsDeliver.replaceAll("@mail.smtp.auth@", smtpAuth);
    contentsDeliver = contentsDeliver.replaceAll("@mail.smtp.user@", smtpUser);
    contentsDeliver = contentsDeliver.replaceAll("@mail.smtp.password@", smtpPassword);
    contentsDeliver = contentsDeliver.replaceAll("@mail.contentType@", "text/html");
    contentsDeliver = contentsDeliver.replaceAll("@systemEmailSender@", systemEmailSender);
    contentsDeliver = contentsDeliver.replaceAll("@niceURIEncoding@", "utf-8");
    contentsDeliver = contentsDeliver.replaceAll("@logDatabaseMessages@", "false");
    contentsDeliver = contentsDeliver.replaceAll("@enablePortal@", "true");

    if (logger.isInfoEnabled())
        logger.info("contentsDeliver after:" + contentsDeliver);
    if (logger.isInfoEnabled())
        logger.info("Want to write to:" + deliverFilePath);
    File targetFileDeliver = new File(deliverFilePath);
    if (logger.isInfoEnabled())
        logger.info("targetFileDeliver:" + targetFileDeliver.exists());

    FileHelper.writeToFile(targetFileDeliver, contentsDeliver, false);

    CacheController.clearCache("serverNodePropertiesCache");
    CmsPropertyHandler.initializeProperties();
    CmsPropertyHandler.resetHardCachedSettings();
    InfoGlueAuthenticationFilter.initializeProperties();
    if (logger.isInfoEnabled())
        logger.info("Operatingmode:" + CmsPropertyHandler.getOperatingMode());
    if (logger.isInfoEnabled())
        logger.info("adminEmail:" + CmsPropertyHandler.getAdministratorEmail());
    //END deliver.properties

}

From source file:org.etudes.mneme.impl.ImportServiceImpl.java

/**
 * Create a fillin question from Samigo data.
 * /*  www.  ja v  a2  s .com*/
 * @param these
 *        The Samigo data entries.
 * @param pool
 *        The pool for the question.
 * @param text
 *        true if text, false if numeric.
 * @return The question, or null if it was not made
 * @throws AssessmentPermissionException
 */
protected Question createFillin(SamigoQuestion[] these, String attachments, Pool pool, boolean text)
        throws AssessmentPermissionException {
    // validate: fist questionChoiceText for the question text not null
    boolean valid = (these[0].questionChoiceText != null);

    // answerMatchText from all for the choices not null
    if (valid) {
        for (int index = 0; index < these.length; index++) {
            if (these[index].answerMatchText == null) {
                valid = false;
                break;
            }
        }
    }

    if (!valid) {
        M_log.info("createFillin: invalid samigo question: " + these[0].itemId);
        return null;
    }

    // create the question
    Question question = this.questionService.newQuestion(pool, "mneme:FillBlanks");
    FillBlanksQuestionImpl f = (FillBlanksQuestionImpl) (question.getTypeSpecificQuestion());

    // detect these[0].exclusive and translate to our "any order"
    f.setAnyOrder(Boolean.FALSE.toString());
    if ((these[0].exclusive != null) && (these[0].exclusive.booleanValue())) {
        // if we find that all the fill-in correct patterns are the same,
        // and there are is one for each answer (comma separated),
        // spread them out, one per fill-in, and set any-order
        boolean mutualExclusive = true;
        for (int index = 1; index < these.length; index++) {
            if (!these[index].answerMatchText.equals(these[0].answerMatchText)) {
                mutualExclusive = false;
                break;
            }
        }

        if (mutualExclusive) {
            String[] parts = these[0].answerMatchText.split("\\|");
            if ((parts != null) && (parts.length == these.length)) {
                for (int index = 0; index < these.length; index++) {
                    these[index].answerMatchText = parts[index];
                }

                f.setAnyOrder(Boolean.TRUE.toString());
            }
        }
    }

    // case sensitive
    if (these[0].caseSensitive != null)
        f.setCaseSensitive(these[0].caseSensitive.toString());

    // text or numeric
    f.setResponseTextual(Boolean.toString(text));

    // recreate the text, fillin in the "{}" with these answerMatchText

    String questionText = these[0].questionChoiceText;
    for (int index = 0; index < these.length; index++) {
        questionText = questionText.replaceFirst("\\{\\}",
                Matcher.quoteReplacement("{" + these[index].answerMatchText + "}"));
    }

    // set the text
    String clean = HtmlHelper.cleanAndAssureAnchorTarget(questionText + attachments, true);
    f.setText(clean);

    return question;
}

From source file:org.muse.mneme.impl.AttachmentServiceImpl.java

/**
 * {@inheritDoc}//from  w w w  .  jav a 2  s  .c  om
 */
public String translateEmbeddedReferences(String data, List<Translation> translations) {
    if (data == null)
        return data;
    if (translations == null)
        return data;

    // pattern to find any src= or href= text
    // groups: 0: the whole matching text 1: src|href 2: the string in the quotes
    Pattern p = Pattern.compile("(src|href)[\\s]*=[\\s]*\"([^\"]*)\"");

    Matcher m = p.matcher(data);
    StringBuffer sb = new StringBuffer();

    // process each "harvested" string (avoiding like strings that are not in src= or href= patterns)
    while (m.find()) {
        if (m.groupCount() == 2) {
            String ref = m.group(2);

            // harvest any content hosting reference
            int index = ref.indexOf("/access/content/");
            if (index != -1) {
                // except for any in /user/ or /public/
                if (ref.indexOf("/access/content/user/") != -1) {
                    index = -1;
                } else if (ref.indexOf("/access/content/public/") != -1) {
                    index = -1;
                }
            }

            // harvest also the mneme docs references
            if (index == -1)
                index = ref.indexOf("/access/mneme/content/");

            if (index != -1) {
                // save just the reference part (i.e. after the /access);
                String normal = ref.substring(index + 7);

                // deal with %20 and other encoded URL stuff
                try {
                    normal = URLDecoder.decode(normal, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    M_log.warn("harvestAttachmentsReferenced: " + e);
                }

                // translate the normal form
                String translated = normal;
                for (Translation translation : translations) {
                    translated = translation.translate(translated);
                }

                // URL encode translated
                String escaped = EscapeRefUrl.escapeUrl(translated);

                // if changed, replace
                if (!normal.equals(translated)) {
                    m.appendReplacement(sb, Matcher.quoteReplacement(
                            m.group(1) + "=\"" + ref.substring(0, index + 7) + escaped + "\""));
                }
            }
        }
    }

    m.appendTail(sb);

    return sb.toString();
}

From source file:org.zaproxy.zap.extension.ascanrules.CommandInjectionPlugin.java

/**
 * Generate payload variants for uninitialized variable waf bypass
 * https://www.secjuice.com/web-application-firewall-waf-evasion/
 *
 * @param cmd the cmd to insert uninitialized variable
 *///ww  w .  j  a v a 2  s .com
private static String insertUninitVar(String cmd) {
    int varLength = ThreadLocalRandom.current().nextInt(1, 3) + 1;
    char[] array = new char[varLength];
    // $xx
    array[0] = '$';
    for (int i = 1; i < varLength; ++i) {
        array[i] = (char) ThreadLocalRandom.current().nextInt(97, 123);
    }
    String var = new String(array);

    // insert variable before each space and '/' in the path
    return cmd.replaceAll("\\s", Matcher.quoteReplacement(var + " ")).replaceAll("\\/",
            Matcher.quoteReplacement(var + "/"));
}

From source file:de.tor.tribes.ui.views.DSWorkbenchConquersFrame.java

private void updateFilter() {
    if (highlighter != null) {
        jConquersTable.removeHighlighter(highlighter);
    }//from w  ww.j a  v a 2  s .  c o m
    final List<String> columns = new LinkedList<>();
    for (Object o : jXColumnList.getSelectedValues()) {
        columns.add((String) o);
    }
    if (!jFilterRows.isSelected()) {
        jConquersTable.setRowFilter(null);
        final List<Integer> relevantCols = new LinkedList<>();
        List<TableColumn> cols = jConquersTable.getColumns(true);
        for (int i = 0; i < jConquersTable.getColumnCount(); i++) {
            TableColumnExt col = jConquersTable.getColumnExt(i);
            if (col.isVisible() && columns.contains(col.getTitle())) {
                relevantCols.add(cols.indexOf(col));
            }
        }
        for (Integer col : relevantCols) {
            PatternPredicate patternPredicate0 = new PatternPredicate(
                    (jFilterCaseSensitive.isSelected() ? "" : "(?i)")
                            + Matcher.quoteReplacement(jTextField1.getText()),
                    col);
            MattePainter mp = new MattePainter(new Color(0, 0, 0, 120));
            highlighter = new PainterHighlighter(
                    new HighlightPredicate.NotHighlightPredicate(patternPredicate0), mp);
            jConquersTable.addHighlighter(highlighter);
        }
    } else {
        jConquersTable.setRowFilter(new RowFilter<TableModel, Integer>() {

            @Override
            public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
                final List<Integer> relevantCols = new LinkedList<>();
                List<TableColumn> cols = jConquersTable.getColumns(true);
                for (int i = 0; i < jConquersTable.getColumnCount(); i++) {
                    TableColumnExt col = jConquersTable.getColumnExt(i);
                    if (col.isVisible() && columns.contains(col.getTitle())) {
                        relevantCols.add(cols.indexOf(col));
                    }
                }

                for (Integer col : relevantCols) {
                    if (jFilterCaseSensitive.isSelected()) {
                        if (entry.getStringValue(col).contains(jTextField1.getText())) {
                            return true;
                        }
                    } else {
                        if (entry.getStringValue(col).toLowerCase()
                                .contains(jTextField1.getText().toLowerCase())) {
                            return true;
                        }
                    }
                }
                return false;
            }
        });
    }
}

From source file:org.azyva.dragom.cliutil.CliUtil.java

/**
 * Helper method that factors the code for loading a Properties file.
 * <p>/*from w  w w .  j a  va2s .c  o m*/
 * All occurrences of "~" in the path to the Properties files are replaced with
 * the value of the user.home system property.
 * <p>
 * If the properties file is not found, propertiesDefault is returned (may be
 * null).
 * <p>
 * If propertiesDefault is null, a new Properties is created without default
 * Properties.
 * <p>
 * If propertiesDefault is not null, a new Properties is created with these
 * default Properties.
 *
 * @param stringPropertiesFile Path to the Properties file in String form.
 * @param propertiesDefault Default Properties.
 * @return Properties. May be null.
 */
private static Properties loadProperties(String stringPropertiesFile, Properties propertiesDefault) {
    Properties properties;

    properties = propertiesDefault;

    CliUtil.logger.debug("Loading properties from " + stringPropertiesFile);

    stringPropertiesFile = stringPropertiesFile.replace("~",
            Matcher.quoteReplacement(System.getProperty("user.home")));

    try (InputStream inputStreamProperties = new FileInputStream(stringPropertiesFile)) {
        if (propertiesDefault == null) {
            properties = new Properties();
        } else {
            properties = new Properties(propertiesDefault);
        }
        properties.load(inputStreamProperties);
    } catch (FileNotFoundException fnfe) {
        CliUtil.logger.debug("Properties file " + stringPropertiesFile + " not found.");
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    return properties;
}

From source file:org.opennms.ng.services.databaseschemaconfig.JdbcFilterDao.java

/**
 * Generic method to parse and translate a rule into SQL.
 *
 * Only columns listed in database-schema.xml may be used in a filter
 * (explicit "table.column" specification is not supported in filters)
 *
 * To differentiate column names from SQL key words (operators, functions, typecasts, etc)
 * SQL_KEYWORD_REGEX must match any SQL key words that may be used in filters,
 * and must not match any column names or prefixed values
 *
 * To make filter syntax more simple and intuitive than SQL
 * - Filters support some aliases for common SQL key words / operators
 *    "&amp;" or "&amp;&amp;" = "AND"
 *    "|" or "||" = "OR"/*from w ww  . j  av  a2  s  .c  om*/
 *    "!" = "NOT"
 *    "==" = "="
 * - "IPLIKE" may be used as an operator instead of a function in filters ("ipAddr IPLIKE '*.*.*.*'")
 *   When using "IPLIKE" as an operator, the value does not have to be quoted ("ipAddr IPLIKE *.*.*.*" is ok)
 * - Some common SQL expressions may be generated by adding a (lower-case) prefix to an unquoted value in the filter
 *    "isVALUE" = "serviceName = VALUE"
 *    "notisVALUE" = interface does not support the specified service
 *    "catincVALUE" = node is in the specified category
 * - Double-quoted (") strings in filters are converted to single-quoted (') strings in SQL
 *   SQL treats single-quoted strings as constants (values) and double-quoted strings as identifiers (columns, tables, etc)
 *   So, all quoted strings in filters are treated as constants, and filters don't support quoted identifiers
 *
 * This function does not do complete syntax/grammar checking - that is left to the database itself - do not assume the output is valid SQL
 *
 * @param tables
 *            a list to be populated with any tables referenced by the returned SQL
 * @param rule
 *            the rule to parse
 *
 * @return an SQL WHERE clause
 *
 * @throws org.opennms.ng.services.databaseschemaconfig.FilterParseException
 *             if any errors occur during parsing
 */
private String parseRule(final List<Table> tables, final String rule) throws FilterParseException {
    if (rule != null && rule.length() > 0) {
        final List<String> extractedStrings = new ArrayList<String>();

        String sqlRule = rule;

        // Extract quoted strings from rule and convert double-quoted strings to single-quoted strings
        // Quoted strings need to be extracted first to avoid accidentally matching/modifying anything within them
        // As in SQL, pairs of quotes within a quoted string are treated as an escaped quote character:
        //  'a''b' = a'b ; "a""b" = a"b ; 'a"b' = a"b ; "a'b" = a'b
        Matcher regex = SQL_QUOTE_PATTERN.matcher(sqlRule);
        StringBuffer tempStringBuff = new StringBuffer();
        while (regex.find()) {
            final String tempString = regex.group();
            if (tempString.charAt(0) == '"') {
                extractedStrings.add("'" + tempString.substring(1, tempString.length() - 1)
                        .replaceAll("\"\"", "\"").replaceAll("'", "''") + "'");
            } else {
                extractedStrings.add(regex.group());
            }
            regex.appendReplacement(tempStringBuff, "###@" + (extractedStrings.size() - 1) + "@###");
        }
        final int tempIndex = tempStringBuff.length();
        regex.appendTail(tempStringBuff);
        if (tempStringBuff.substring(tempIndex).indexOf('\'') > -1) {
            final String message = "Unmatched ' in filter rule '" + rule + "'";
            LOG.error(message);
            throw new FilterParseException(message);
        }
        if (tempStringBuff.substring(tempIndex).indexOf('"') > -1) {
            final String message = "Unmatched \" in filter rule '" + rule + "'";
            LOG.error(message);
            throw new FilterParseException(message);
        }
        sqlRule = tempStringBuff.toString();

        // Translate filter-specific operators to SQL operators
        sqlRule = sqlRule.replaceAll("\\s*(?:&|&&)\\s*", " AND ");
        sqlRule = sqlRule.replaceAll("\\s*(?:\\||\\|\\|)\\s*", " OR ");
        sqlRule = sqlRule.replaceAll("\\s*!(?!=)\\s*", " NOT ");
        sqlRule = sqlRule.replaceAll("==", "=");

        // Translate IPLIKE operators to IPLIKE() functions
        // If IPLIKE is already used as a function in the filter, this regex should not match it
        regex = SQL_IPLIKE_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            // Is the second argument already a quoted string?
            if (regex.group().charAt(0) == '#') {
                regex.appendReplacement(tempStringBuff, "IPLIKE($1, $2)");
            } else {
                regex.appendReplacement(tempStringBuff, "IPLIKE($1, '$2')");
            }
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();

        // Extract SQL key words to avoid identifying them as columns or prefixed values
        regex = SQL_KEYWORD_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            extractedStrings.add(regex.group().toUpperCase());
            regex.appendReplacement(tempStringBuff, "###@" + (extractedStrings.size() - 1) + "@###");
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();

        // Identify prefixed values and columns
        regex = SQL_VALUE_COLUMN_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            // Convert prefixed values to SQL expressions
            if (regex.group().startsWith("is")) {
                regex.appendReplacement(tempStringBuff,
                        addColumn(tables, "serviceName") + " = '" + regex.group().substring(2) + "'");
            } else if (regex.group().startsWith("notis")) {
                regex.appendReplacement(tempStringBuff, addColumn(tables, "ipAddr")
                        + " NOT IN (SELECT ifServices.ipAddr FROM ifServices, service WHERE service.serviceName ='"
                        + regex.group().substring(5) + "' AND service.serviceID = ifServices.serviceID)");
            } else if (regex.group().startsWith("catinc")) {
                regex.appendReplacement(tempStringBuff, addColumn(tables, "nodeID")
                        + " IN (SELECT category_node.nodeID FROM category_node, categories WHERE categories.categoryID = category_node.categoryID AND categories.categoryName = '"
                        + regex.group().substring(6) + "')");
            } else {
                // Call addColumn() on each column
                regex.appendReplacement(tempStringBuff, addColumn(tables, regex.group()));
            }
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();

        // Merge extracted strings back into expression
        regex = SQL_ESCAPED_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            regex.appendReplacement(tempStringBuff,
                    Matcher.quoteReplacement(extractedStrings.get(Integer.parseInt(regex.group(1)))));
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();
        return "WHERE " + sqlRule;
    }
    return "";
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Return the input with embedded property references expanded
 *
 * @param properties the properties to select form
 * @param input      the input/* w  ww .  jav a2  s  .co m*/
 *
 * @return string with references expanded
 */
public static String expandProperties(final Properties properties, final String input) {
    final Pattern pattern = Pattern.compile(PROPERTY_PATTERN);
    final Matcher matcher = pattern.matcher(input);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        final String match = matcher.group(1);
        if (null != properties.get(match)) {
            matcher.appendReplacement(sb, Matcher.quoteReplacement(properties.getProperty(match)));
        } else {
            matcher.appendReplacement(sb, Matcher.quoteReplacement(matcher.group(0)));
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:gtu._work.ui.RegexDirReplacer.java

/**
 * @param fromPattern/*from   w w w . jav  a 2s  .c  o  m*/
 *            ???pattern
 * @param toFormat
 *            ??pattern
 * @param replaceText
 *            ??
 */
String replacer(String fromPattern, String toFormat, String replaceText, File file) {
    String errorRtn = replaceText.toString();
    try {
        Pattern pattern = Pattern.compile(fromPattern);
        Matcher matcher = pattern.matcher(replaceText);

        StringBuilder sb = new StringBuilder();
        int startPos = 0;

        String tempStr = null;
        for (; matcher.find();) {
            tempStr = toFormat.toString();
            sb.append(replaceText.substring(startPos, matcher.start()));
            for (int ii = 0; ii <= matcher.groupCount(); ii++) {
                tempStr = tempStr.replaceAll("#" + ii + "#", Matcher.quoteReplacement(matcher.group(ii)));
                System.out.println("group[" + ii + "] -- " + matcher.group(ii) + "\t--> " + tempStr);
            }
            sb.append(tempStr);
            startPos = matcher.end();
        }

        sb.append(replaceText.substring(startPos));

        return sb.toString();
    } catch (Exception ex) {
        // JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(ex.getMessage(),
        // getTitle());
        errMsg.append(file.getName() + ":" + ex + "\n");
        return errorRtn;
    }
}