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.common.util.CommonUtils.java

public static String extractVariable(String prefix, String arg, String propertyFile, Boolean fixPathSeparator) {

    // Determine if the property file is set in the environment otherwise use the default property file
    String defaultPropertyFile = CommonConstants.propertyFile;
    if (propertyFile == null || propertyFile.length() == 0) {
        propertyFile = getFileOrSystemPropertyValue(defaultPropertyFile, "CONFIG_PROPERTY_FILE");
        if (propertyFile == null || propertyFile.length() == 0) {
            propertyFile = defaultPropertyFile;
        }/*from   ww  w . j a  v  a2  s.c  o m*/
    }
    if (arg == null) {
        arg = "";
    }
    String resolvedArg = arg.trim();
    String propertyVal = null;
    String replaceProperty = null;
    boolean resolvedVariables = false;

    /* The separator list is a list of single characters that may be encountered within a string being parsed
     *   mtinius: 2012-01-23: added ":" and "@" as separators
     *   mtinius: 2013-02-13: added "'" as a separator for use case 11. below
     *   that will serve as a natural separator in the text. Examples are listed below
     *      1. / - $VCS_WORKSPACE_HOME/
     *      2. $ - $VCS_TYPE$_cisVcsTemp
     *      3. \ - $VCS_WORKSPACE_HOME\
     *      4. . - $VAR.log
     *      5. " - "$VAR"
     *      6. $ - $VCS_TYPE$_cisVcsTemp
     *      7. % - %VCS_TYPE%_cisVcsTemp
     *      8.   - $VAR1 $VAR2
     *      9. : - :pserver:$VCS_USERNAME:$VCS_PASSWORD@kauai:2401/home/cvs
     *     10. @ - :pserver:$VCS_USERNAME:$VCS_PASSWORD@kauai:2401/home/cvs
     *     11. WHERE status='$STATUS' (for query string from RegressionModule)
     */
    String separatorList = "\\/.\"$% :@'";

    /*
     *  Handle the use case to escape an argument containing $$ or %%
     *    Convert $$ into "!D!O!L!L!A!R!-#D#O#L#L#A#R#"
     *    Convert %% into "!P!E!R!C!E!N!T!-#P#E#R#C#E#N#T#"
     *    
     *    This is not quite orthodox but it was quick and easy.  
     *    Just as long as this pattern never shows up in the actual text it will all work. Playing the odds.
     */
    resolvedArg = argumentEscape("escape", resolvedArg);

    // Loop over the argument text until all variables are resolved - this gets repeated because variables may contain other variables.
    boolean variableSepFound = true;
    while (variableSepFound) {

        // Determine if this argument string contains a valid separator of $ or %
        if (resolvedArg.contains("$") || resolvedArg.contains("%")) {

            // Initialize variables each time through the loop
            String property = null;
            boolean endSepFound = false;
            int begSep = -1;
            int endSep = -1;

            // Parse variables beginning with $ or %
            if (resolvedArg.contains("$") || resolvedArg.contains("%")) {
                // Determine if the $ or % is the first separator found
                int begSep1 = resolvedArg.indexOf("$");
                int begSep2 = resolvedArg.indexOf("%");
                if (begSep1 > -1 && begSep2 > -1) {
                    if (begSep1 < begSep2) {
                        begSep = begSep1;
                    } else {
                        begSep = begSep2;
                    }
                } else if (begSep1 > -1) {
                    begSep = begSep1;
                } else {
                    begSep = begSep2;
                }

                for (int i = begSep + 1; i < resolvedArg.length() && !endSepFound; i++) {
                    // Extract the character from the argument text
                    String ch = resolvedArg.substring(i, i + 1);
                    // Determine if the separator list contains the character from the argument string (if yes then this is the end of this variable)
                    if (separatorList.contains(ch)) {
                        endSep = i;
                        property = resolvedArg.substring(begSep + 1, endSep);
                        // Extract replacement variable differently depending on whether the end separator is a $ and % or other
                        // SeparatorList=$ %
                        if (ch.equals("$") || ch.equals("%")) {
                            // Include the end separator when extracting
                            replaceProperty = resolvedArg.substring(begSep, endSep + 1);
                        } else { //SeparatorList=/ \ . "
                            // Do not include the end separator when extracting
                            replaceProperty = resolvedArg.substring(begSep, endSep);
                        }
                        endSepFound = true;
                    }
                }
                if (!endSepFound) {
                    property = resolvedArg.substring(begSep + 1, resolvedArg.length());
                    replaceProperty = resolvedArg.substring(begSep, resolvedArg.length());
                    endSepFound = true;
                }

                if (endSepFound) {
                    try {
                        // This indicates that there is a stand-alone $ or % sign with no property value
                        // When this situation arises then escape the single $ or % sign so that the value carries through as a value and not a variable.
                        if ((replaceProperty.equals("$") || replaceProperty.equals("%"))
                                && propertyVal == null) {
                            if (replaceProperty.equals("$"))
                                propertyVal = argumentEscape("escape", "$$");
                            if (replaceProperty.equals("%"))
                                propertyVal = argumentEscape("escape", "%%");
                        } else {
                            // First look in the property file and then look in the System Environment for the property
                            propertyVal = getFileOrSystemPropertyValue(propertyFile, property);
                        }
                    } catch (Exception e) {
                        // Property was not found in either the property file or System environment
                        throw new ApplicationException("Error parsing property file=" + propertyFile
                                + "  Original Property=" + arg + "  Resolved Property=[" + property
                                + "] was not found.  Invoked from method=" + prefix);
                    }
                    // Handle the use case to escape an argument containing $$ or %%
                    propertyVal = argumentEscape("escape", propertyVal);

                    // Property was found
                    if (propertyVal != null) {
                        // Replace Variables with the retrieved property value (note: variables may contain other variables)
                        resolvedArg = resolvedArg.replaceAll(Matcher.quoteReplacement(replaceProperty),
                                Matcher.quoteReplacement(propertyVal));
                        resolvedVariables = true;

                    } else {
                        // Property was not found in either the property file or System environment
                        throw new ApplicationException("Error parsing property file=" + propertyFile
                                + "  Original Property=" + arg + "  Resolved Property=[" + property
                                + "] was not found.  Invoked from method=" + prefix);
                    }
                }
            }

        } else {
            // No more variables found so exit the loop
            variableSepFound = false;
        }
    }
    if (resolvedVariables && fixPathSeparator) {

        String resolvedArgPrefix = null, resolvedArgSuffix = null;

        // We have to preserve the beginning // and \\ of the path for the network paths to work
        if (resolvedArg.startsWith("//") || resolvedArg.startsWith("\\\\")) {
            resolvedArgPrefix = resolvedArg.substring(0, 2);
            if (resolvedArgPrefix.equals("\\\\")) {
                resolvedArgPrefix = "//";
            }
            resolvedArgSuffix = resolvedArg.substring(2);

            //LogFactory.getLog(CommonUtils.class).info("ResolvedArg1: " + resolvedArg);

            // Replace double forward slashes // with a single /
            resolvedArgSuffix = resolvedArgSuffix.replaceAll("//", "/");

            // Replace double back slashes \\ with a single /
            resolvedArg = resolvedArgPrefix + resolvedArgSuffix.replaceAll("\\\\", "/");
            //LogFactory.getLog(CommonUtils.class).info("ResolvedArg2: " + resolvedArg);
        } else {
            //LogFactory.getLog(CommonUtils.class).info("ResolvedArg3: " + resolvedArg);
            // Replace double forward slashes // with a single /
            resolvedArg = resolvedArg.replaceAll("//", "/");

            // Replace double back slashes \\ with a single /
            resolvedArg = resolvedArg.replaceAll("\\\\", "/");
            //LogFactory.getLog(CommonUtils.class).info("ResolvedArg4: " + resolvedArg);
        }
    }

    // Handle the use case to unescape an argument containing $$ or %%
    resolvedArg = argumentEscape("unescape", resolvedArg);

    return resolvedArg;
}

From source file:org.nuxeo.theme.editor.Main.java

public String resolveVariables(String themeName, String resourceBankName, List<ImageInfo> images,
        String value) {/*from   w  w  w  .  jav a  2s .  c  o  m*/
    if (images == null) {
        return value;
    }

    String contextPath = VirtualHostHelper.getContextPathProperty();

    // basePath
    String basePath = ctx.getBasePath();
    value = value.replaceAll("\\$\\{basePath\\}", Matcher.quoteReplacement(basePath));

    value = PresetManager.resolvePresets(themeName, value);

    // images
    for (ImageInfo image : images) {
        String path = image.getPath();
        value = value.replaceAll(Matcher.quoteReplacement(path), Matcher.quoteReplacement(String
                .format("%s/nxthemes-images/%s/%s", contextPath, resourceBankName, path.replace(" ", "%20"))));
    }
    return value;
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
 * Handle the escaping and un-escaping of an argument
 * Perform this for $$ and %% found in arguments.
 * /*ww  w.  ja v  a  2 s  . c  o  m*/
 * @param action - "escape" or "unescape"
 * @param argument - the argument to act upon 
 */
private static String argumentEscape(String action, String argument) {

    /*
     * Handle the use case where there is an escaped $$ where the $ is part of the argument and not a variable
     *   the intended outcome
     *     VCS_REPOSITORY_URL=http://hostname:8080/$/Project/
     *   escape the single $ with $$
     *     VCS_REPOSITORY_URL=http://hostname:8080/$$/Project/
     *   what gets returned is this
     *     VCS_REPOSITORY_URL=http://hostname:8080/$/Project/
     *     
     *    This is not quite orthodox but it was quick and easy.  
     *    Just as long as this pattern never shows up in the actual text it will all work. Playing the odds.
     */
    String replaceDollarProperty = "!D!O!L!L!A!R!-#D#O#L#L#A#R#";
    /*
     * Handle the use case where there is an escaped %% where the % is part of the argument and not a variable
     *   the intended outcome
     *     <query>SELECT * FROM CAT1.SCH2.ViewSales WHERE ProductName like 'Mega%'</query>
     *   escape the single % with %%
     *     <query>SELECT * FROM CAT1.SCH2.ViewSales WHERE ProductName like 'Mega%%'</query>
     *   what gets returned is this
     *     <query>SELECT * FROM CAT1.SCH2.ViewSales WHERE ProductName like 'Mega%'</query>
     *     
     *    This is not quite orthodox but it was quick and easy.  
     *    Just as long as this pattern never shows up in the actual text it will all work. Playing the odds.
     */
    String replacePercentProperty = "!P!E!R!C!E!N!T!-#P#E#R#C#E#N#T#";

    // Perform the action to escape $$ or %%
    if (action.equalsIgnoreCase("escape")) {

        //ESCAPE $$: Handle the use case where there is an escaped $$ where the $ is part of the argument and not a variable
        if (argument.contains("$$")) {
            // Replace Variables with the retrieved property value (note: variables may contain other variables)
            argument = argument.replaceAll(Matcher.quoteReplacement("$$"),
                    Matcher.quoteReplacement(replaceDollarProperty));
        }

        // ESCAPE %%: Handle the use case where there is an escaped %% where the % is part of the argument and not a variable
        if (argument.contains("%%")) {
            // Replace Variables with the retrieved property value (note: variables may contain other variables)
            argument = argument.replaceAll(Matcher.quoteReplacement("%%"),
                    Matcher.quoteReplacement(replacePercentProperty));
        }

        // Perform the action to unescape $$ to a single $ or %% to a single %
    } else {

        //UNESCAPE $$: Handle the use case where there is an escaped $$ where the $ is part of the argument and not a variable
        if (argument.contains(replaceDollarProperty)) {
            // replace the unorthodox text with a single $ sign
            // Replace Variables with the retrieved property value (note: variables may contain other variables)
            argument = argument.replaceAll(Matcher.quoteReplacement(replaceDollarProperty),
                    Matcher.quoteReplacement("$"));
        }

        // UNESCAPE %%: Handle the use case where there is an escaped %% where the % is part of the argument and not a variable
        if (argument.contains(replacePercentProperty)) {
            // replace the unorthodox text with a single % sign
            // Replace Variables with the retrieved property value (note: variables may contain other variables)
            argument = argument.replaceAll(Matcher.quoteReplacement(replacePercentProperty),
                    Matcher.quoteReplacement("%"));
        }
    }
    return argument;
}

From source file:org.kepler.ddp.actor.ExecutionChoice.java

/** Rename a parameter in each of the refinement command lines. */
private void _renameInCommandLines(String oldName, String newName) {

    for (Refinement refinement : entityList(Refinement.class)) {
        Parameter commandLineParameter = (Parameter) refinement.getAttribute(COMMAND_LINE_NAME);
        // see if the command line exists in this refinement
        if (commandLineParameter != null) {

            // get the expression saved before the rename
            String expression = _refinementCommandLines.get(refinement);

            // do the rename in the expression
            String value = expression.replaceAll(Pattern.quote("$" + oldName),
                    Matcher.quoteReplacement("$" + newName));

            // rename the parameter name in references to the argument, e.g.,:
            // $(inputFile::argument)
            value = value.replaceAll(Pattern.quote("$(" + oldName + "::"),
                    Matcher.quoteReplacement("$(" + newName + "::"));

            // set the new value in the parameter
            commandLineParameter.setExpression(value);

            //System.out.println("rename: new command line for " + refinement.getName() + ":" +
            //commandLineParameter.getExpression());

        }/*from  w ww  .j ava 2  s .com*/
    }

    // update the default command line
    String value = _commandLineArguments.replaceAll(Pattern.quote("$" + oldName),
            Matcher.quoteReplacement("$" + newName));
    value = value.replaceAll(Pattern.quote("$(" + oldName + "::"),
            Matcher.quoteReplacement("$(" + newName + "::"));
    _commandLineArguments = value;

}

From source file:org.slc.sli.api.security.pdp.UriMutator.java

private String getQueryValueForQueryParameters(String queryName, String queryParameters) {
    String queryValue = null;/*from   w  w w  . j  a v  a2  s . c o m*/
    String[] queries = queryParameters.split("&");
    String queryRegEx = "^" + Matcher.quoteReplacement(queryName) + "=.+";

    for (String query : queries) {
        if (query.matches(queryRegEx)) {
            int indexOfQueryValue = queryRegEx.length() - 3;
            queryValue = query.substring(indexOfQueryValue);
            break;
        }
    }

    return queryValue;
}

From source file:org.slc.sli.api.security.pdp.UriMutator.java

/**
 * Removes the first occurrence of the specified queryName from the
 * specified queryParameters String.  Almost redundant with
 * {@link removeQueryParameter}, except that method removes all occurrences.
 * //w  w w  .j  a va  2 s  .  com
 * @param queryName Name of a parameter to remove from the queryString
 * @param queryParameters The full queryString
 */
private String removeQueryFromQueryParameters(String queryName, String queryParameters) {
    String queryRegEx = Matcher.quoteReplacement(queryName) + "=[^&]*&?";
    String rslt = queryParameters.replaceFirst(Matcher.quoteReplacement(queryRegEx), "");
    if (rslt.endsWith("&")) {
        // The queryRegEx will leave a trailing & if the removed parameter was the last
        rslt = rslt.substring(0, rslt.length() - 1);
    }
    return rslt;
}

From source file:com.cisco.dvbu.ps.deploytool.services.DataSourceManagerImpl.java

/*************************************************************************************
 * populateIntrospectionPlan()//  ww w.  j av  a  2 s .  c o m
 * 
 * This method is used for reading the DataSourceModule.xml file and populating
 * the internal structure for invocation of the INTROSPECT data source action.
 * 
 * This plan shows how to recursively add or update a data source with no schema or catalog.
 *       The path is left blank.  The action ADD_OR_UPDATE_RECURSIVELY is specified.
 <resource:entry>
   <resource:resourceId>
     <resource:path></resource:path>
     <resource:type>DATA_SOURCE</resource:type>
     <resource:subtype>RELATIONAL_DATA_SOURCE</resource:subtype>
   </resource:resourceId>
   <resource:action>ADD_OR_UPDATE_RECURSIVELY</resource:action>
 </resource:entry>
        
        
</resource:introspectResourcesTask>
 *************************************************************************************/
// Populate the Attribute List for Data Source Actions such as UPDATE
private IntrospectionPlan populateIntrospectionPlan(DataSourceChoiceType datasource, String serverId,
        String pathToServersXML) {

    String defaultPropertyFile = CommonConstants.propertyFile;
    /*  Determine the property file name for this environment
     *    1. Start with default file CommonConstants.propertyFile
     *    2. Get Java Environment variables
     *    3. Get OS System Environment variables
     */
    String propertyFile = CommonUtils.getFileOrSystemPropertyValue(defaultPropertyFile, "CONFIG_PROPERTY_FILE");
    // Set a default value if not found
    if (propertyFile == null || propertyFile.trim().length() == 0) {
        propertyFile = defaultPropertyFile;
    }
    String prefix = "DataSourcemanagerImpl.populateIntrospectionPlan";

    // Initialize the plan to null
    IntrospectionPlan plan = null;

    // Set up the introspection plan for this data source.   
    if (datasource.getIntrospectDataSource() != null) {

        //populate attributes from generic attributes from relational data source
        if (datasource.getIntrospectDataSource().getPlan() != null) {

            // Initialize a new plan
            plan = new IntrospectionPlan();
            IntrospectionPlanEntries planEntries = new IntrospectionPlanEntries();

            // Set the plan boolean values
            plan.setAutoRollback(datasource.getIntrospectDataSource().getPlan().isAutoRollback());
            plan.setCommitOnFailure(datasource.getIntrospectDataSource().getPlan().isCommitOnFailure());
            plan.setFailFast(datasource.getIntrospectDataSource().getPlan().isFailFast());
            plan.setScanForNewResourcesToAutoAdd(
                    datasource.getIntrospectDataSource().getPlan().isScanForNewResourcesToAutoAdd());
            plan.setUpdateAllIntrospectedResources(
                    datasource.getIntrospectDataSource().getPlan().isUpdateAllIntrospectedResources());

            // Get the list of Introspection Entries from the DataSourceModule.xml
            List<IntrospectDataSourcePlanEntryType> dsXmlEntries = datasource.getIntrospectDataSource()
                    .getPlan().getPlanEntry();

            // Iterate through the DataSourceModule.xml file introspection entries
            for (IntrospectDataSourcePlanEntryType dsXmlEntry : dsXmlEntries) {
                /* Retrieve the introspection plan entries list)
                    <planEntry>
                        <resourceId>
                   <resourcePath>string</resourcePath>
                   <!--Element resourceType is optional-->
                   <resourceType>TRIGGER</resourceType>
                   <subtype>string</subtype>
                        </resourceId>
                        <action>string</action>
                        <!--Element attributes is optional, maxOccurs=unbounded-->
                        <genericAttribute>
                   <name>string</name>
                   <type>UNKNOWN</type>
                   <!--Element value is optional-->
                   <value>string</value>
                   <!--Element valueArray is optional-->
                   <valueArray>
                       <!--Element item is optional, maxOccurs=unbounded-->
                       <item>string</item>
                       <item>string</item>
                       <item>string</item>
                   </valueArray>
                   <!--Element valueList is optional-->
                   <valueList>
                       <!--Element item is optional, maxOccurs=unbounded-->
                       <item>
                           <!--Element type is optional-->
                           <type>UNKNOWN</type>
                           <!--Element value is optional-->
                           <value>string</value>
                       </item>
                       <item>
                           <!--Element type is optional-->
                           <type>UNKNOWN</type>
                           <!--Element value is optional-->
                           <value>string</value>
                       </item>
                       <item>
                           <!--Element type is optional-->
                           <type>UNKNOWN</type>
                           <!--Element value is optional-->
                           <value>string</value>
                       </item>
                   </valueList>
                   <!--Element valueMap is optional-->
                   <valueMap>
                       <!--Element entry is optional, maxOccurs=unbounded-->
                       <entry>
                           <!--Element key is optional-->
                           <key>
                               <!--Element type is optional-->
                               <type>UNKNOWN</type>
                               <!--Element value is optional-->
                               <value>string</value>
                           </key>
                           <!--Element value is optional-->
                           <value>
                               <!--Element type is optional-->
                               <type>UNKNOWN</type>
                               <!--Element value is optional-->
                               <value>string</value>
                           </value>
                       </entry>
                       <entry>
                           <!--Element key is optional-->
                           <key>
                               <!--Element type is optional-->
                               <type>UNKNOWN</type>
                               <!--Element value is optional-->
                               <value>string</value>
                           </key>
                           <!--Element value is optional-->
                           <value>
                               <!--Element type is optional-->
                               <type>UNKNOWN</type>
                               <!--Element value is optional-->
                               <value>string</value>
                           </value>
                       </entry>
                       <entry>
                           <!--Element key is optional-->
                           <key>
                               <!--Element type is optional-->
                               <type>UNKNOWN</type>
                               <!--Element value is optional-->
                               <value>string</value>
                           </key>
                           <!--Element value is optional-->
                           <value>
                               <!--Element type is optional-->
                               <type>UNKNOWN</type>
                               <!--Element value is optional-->
                               <value>string</value>
                           </value>
                       </entry>
                   </valueMap>
                        </genericAttribute>
                    </planEntry>
                 */
                // Initialize a plan entry
                IntrospectionPlanEntry planEntry = new IntrospectionPlanEntry();

                // Set the action
                if (dsXmlEntry.getAction() != null) {
                    planEntry.setAction(IntrospectionPlanAction.valueOf(dsXmlEntry.getAction().toString()));
                }

                PathTypeSubtype pathTypeSubtype = new PathTypeSubtype();
                // Set the Resource Path [Note: path must be relative to the data source path.  It is not a full path.]
                if (dsXmlEntry.getResourceId().getResourcePath() != null) {
                    String resourcePath = CommonUtils.extractVariable(prefix,
                            datasource.getIntrospectDataSource().getResourcePath(), propertyFile, true) + "/";
                    String entryPath = CommonUtils.extractVariable(prefix,
                            dsXmlEntry.getResourceId().getResourcePath(), propertyFile, true);

                    // This code will make sure that a relative path is being used by parsing the data source path and comparing to this resource path
                    if (entryPath.contains(resourcePath)) {
                        entryPath = entryPath.replaceAll(Matcher.quoteReplacement(resourcePath),
                                Matcher.quoteReplacement(""));
                    }
                    /*
                    List<String> argList = null;
                    argList = CommonUtils.getArgumentsList(argList, true, dsXmlEntry.getResourceId().getResourcePath(), "/");
                    for (int i=0; i < argList.size(); i++) {
                       String part = argList.get(i);
                       if (resourcePath.contains("/"+part+"/")) {
                          resourcePath = resourcePath.replaceAll(Matcher.quoteReplacement("/"+part+"/"), Matcher.quoteReplacement(""));
                            
                       }
                    }
                    */

                    // Set the resource Path
                    pathTypeSubtype.setPath(entryPath);
                }
                // Set the Resource Type
                if (dsXmlEntry.getResourceId().getResourceType() != null)
                    pathTypeSubtype.setType(ResourceType.valueOf(CommonUtils.extractVariable(prefix,
                            dsXmlEntry.getResourceId().getResourceType().value(), propertyFile, true)));
                // Set the Subtype
                if (dsXmlEntry.getResourceId().getSubtype() != null)
                    pathTypeSubtype.setSubtype(ResourceSubType.valueOf(CommonUtils.extractVariable(prefix,
                            dsXmlEntry.getResourceId().getSubtype().toString(), propertyFile, true)));
                planEntry.setResourceId(pathTypeSubtype);

                if (dsXmlEntry.getGenericAttribute() != null) {
                    // Initialize the attribute list
                    AttributeList dsAttributeList = new AttributeList();

                    // Get the Resource definition for this data source path
                    DataSourceResource currentDataSource = (DataSourceResource) getResourceDAO().getResource(
                            serverId, datasource.getIntrospectDataSource().getResourcePath(), pathToServersXML);
                    /* Retrieve the actual Composite Data Source Type Name for the current data source by locating an attribute with name=type
                     * This is retrieved from the previous invocation to getResource() and casting the response to DataSourceResource type
                     * 
                     *   <resource:getResourceResponse xmlns:resource="http://www.compositesw.com/services/system/admin/resource">
                     *      <resource:resources>
                     *         <resource:resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="resource:dataSourceResource">
                     *            <resource:name>ServerAttributeDefinitions</resource:name>
                     *            <resource:path>/shared/test00/DataSources/ServerAttributeDefinitions</resource:path>
                     *            <resource:type>DATA_SOURCE</resource:type>
                     *            <resource:subtype>XML_FILE_DATA_SOURCE</resource:subtype>
                     *            ...elements removed
                     *            <resource:childCount>1</resource:childCount>
                     *            
                      *         --> <resource:dataSourceType>File-XML</resource:dataSourceType>
                     *            
                     *         </resource:resource>
                     *      </resource:resources>
                     *   </resource:getResourceResponse>
                     */
                    String dsTypeName = currentDataSource.getDataSourceType();

                    // Retrieve the full list of attribute definitions and update rules for this type of data source (resource:dataSourceType)
                    List<AttributeDef> attributeDefList = getDataSourceDAO()
                            .getDataSourceAttributeDefs(serverId, pathToServersXML, dsTypeName);

                    // Get the list of generic attributes from the plan entry attributes in the DataSourceModule.xml file
                    List<AttributeDefType> attributeTypes = dsXmlEntry.getGenericAttribute();

                    // Iterate through the DataSourceModule.xml file attributes
                    for (AttributeDefType attribute : attributeTypes) {

                        /* Retrieve the Attribute Definition list for a given DataSource Attribute Name (e.g. WSDL, XML/HTTP, File-XML, MySQL 5.0, Oracle 11g (Thin Driver))
                         * Below is an example of an Attribute Definition for the "type=MySql".  
                         * The associated Attribute Def Type Name=MySQL 5.0 which is what is needed to pass into getAttributeDef to get the update rules.
                           <resource:dataSourceType>
                              <resource:name>MySQL 5.0</resource:name>
                              <resource:type>MySql</resource:type>
                              ... <resource:attributes> removed from this documentation
                              </resource:attributes>
                           </resource:dataSourceType>
                         */
                        // Get the Attribute Definition and Update Rules for the specific DataSource type
                        AttributeDef attributeDef = getAttributeDef(attributeDefList, attribute.getName());

                        // Only set the attribute if the attribute is (READ_WRITE or WRITE_ON_CREATE) and the attribute is not in the "Non-Updateable Attribute List"
                        if ((attributeDef != null
                                && (attributeDef.getUpdateRule() == AttributeUpdateRule.READ_WRITE))
                                // WRITE_ON_CREATE is not allowed on updates - It will throw a null pointer exception.  This line is commented out:
                                //                        && (attributeDef.getUpdateRule() == AttributeUpdateRule.READ_WRITE || attributeDef.getUpdateRule() == AttributeUpdateRule.WRITE_ON_CREATE)) 

                                && !PropertyManager.getInstance().containsPropertyValue(propertyFile,
                                        "DataSourceModule_NonUpdateableAttributes", attribute.getName())) {

                            // Create the generic attribute structure from the DataSourceModule.xml
                            Attribute genericAttribute = populateGenericAttributeForUpdate(attribute,
                                    attributeDef, prefix, propertyFile);
                            if (genericAttribute != null) {
                                // Add the generic attribute to the data source object
                                dsAttributeList.getAttribute().add(genericAttribute);
                            }
                        }
                    }
                    planEntry.setAttributes(dsAttributeList);
                }
                // Add a new plan entry to the list
                planEntries.getEntry().add(planEntry);
            }
            plan.setEntries(planEntries);
        }
    }
    return plan;
}

From source file:com.sos.JSHelper.Options.JSOptionsClass.java

/**
 *
*
* \brief replaceVars - replace all vars in a string and return the string
*
* \details//from   ww  w  . java  2s . c  om
*
* \return String
*
 */
public String replaceVars(final String pstrReplaceIn) {
    @SuppressWarnings("unused")
    final String conMethodName = conClassName + "::replaceVars";

    getTextProperties();

    try {
        // zustzliche Parameter generieren
        objP.put("date", SOSOptionTime.getCurrentDateAsString());
        objP.put("time", SOSOptionTime.getCurrentTimeAsString("hh:mm:ss"));
        objP.put("local_user", System.getProperty("user.name"));

        java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
        objP.put("localhost", localMachine.getHostName());
        objP.put("local_host_ip", localMachine.getHostAddress());
    } catch (Exception uhe) {
    }

    String strVal = "";
    String strKey = "";

    // String strParamNameEnclosedInPercentSigns = ".*%\\{([^%]+)\\}.*";
    // %{variableName}
    String strParamNameEnclosedInPercentSigns = "^.*%\\{([^%]+)\\}.*$";
    // String strParamNameEnclosedInPercentSigns2 = "^.*%\\{([^\\}]+).*$";

    /**
     * Problem hier:
     * Wenn der gesamte String verwendet wird, so ist sptestens beim file_spec
     * keine korrekte Substitution mehr mglich.
     * Liegt warscheinlich am regexp pattern.
     */
    String strNewString = "";
    if (isNotNull(pstrReplaceIn)) {
        try {
            //            pstrReplaceIn = pstrReplaceIn.replaceAll("\\n", "\\$\\$N\\$\\$");
            String[] strA = pstrReplaceIn.split("\\n");
            for (String string : strA) {
                while (string.matches(strParamNameEnclosedInPercentSigns)) {
                    strKey = string.replaceFirst(strParamNameEnclosedInPercentSigns, "$1");
                    if (strKey.equalsIgnoreCase("uuid")) {
                        continue;
                    }
                    String strPP = "%\\{" + strKey + "\\}";
                    strVal = this.OptionByName(strKey);
                    if (isNotNull(strVal)) {
                        strVal = strVal.replace('\\', '/');
                        string = string.replaceAll(strPP, Matcher.quoteReplacement(strVal));
                        // logger.debug(Messages.getMsg(JSJ_D_0031, name, strPP, s)); //
                        // "processing job parameter '%1$s': substitute '%2$s' with '%3$s'."
                    } else {
                        strVal = (String) objP.get(strKey);
                        if (strVal != null) {
                            string = string.replaceAll(strPP, Matcher.quoteReplacement(strVal));
                        } else {
                            strVal = objSettings.get(strKey);
                            if (strVal != null) {
                                string = string.replaceAll(strPP, Matcher.quoteReplacement(strVal));
                            } else {
                                string = string.replaceAll(strPP, "?" + Matcher.quoteReplacement(strKey) + "?");
                                // logger.warn(Messages.getMsg(JSJ_D_0032, p)); // "variable '%1$s' not found. no substitution done"
                            }
                        }
                    }
                }
                strNewString += string + "\n";
            }
        } catch (Exception e) { // intentionally no error, wrong regexp ?
        }
    }
    //      pstrReplaceIn = pstrReplaceIn.replaceAll("\\$\\$N\\$\\$", "\n");
    return strNewString;
}

From source file:com.krawler.spring.crm.dashboard.CrmDashboardController.java

private void getCampaigns(Map<String, List<AuditTrailDetail>> auditTrailDetailMap, List<String> recordIds) {
    String itemname;/* w w w . j av  a 2  s  . c  o  m*/
    try {
        List<CrmCampaign> campaigns = crmCampaignDAOObj.getCampaigns(recordIds);

        if (campaigns != null) {
            for (CrmCampaign campaign : campaigns) {
                List<AuditTrailDetail> list = auditTrailDetailMap.get(campaign.getCampaignid());

                for (AuditTrailDetail auditDetail : list) {
                    itemname = campaign.getCampaignname();
                    if (!campaign.getIsarchive() && campaign.getDeleteflag() != 1) {
                        auditDetail.detail = auditDetail.detail.replaceAll(Matcher.quoteReplacement(itemname),
                                "<a href=# onclick=\"addCampaignTab('" + campaign.getCampaignid() + "')\">"
                                        + Matcher.quoteReplacement(itemname) + "</a>");
                    }
                }
            }
        }

    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
    }
}

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog220.java

protected String updateHiveEnvContent(String hiveEnvContent) {
    if (hiveEnvContent == null) {
        return null;
    }/*from www  .ja va 2s .  c om*/
    // There are two cases here
    // We do not have "export HADOOP_CLIENT_OPTS" and we need to add it
    // We have "export HADOOP_CLIENT_OPTS" with wrong order
    String exportHadoopClientOpts = "(?s).*export\\s*HADOOP_CLIENT_OPTS.*";
    if (hiveEnvContent.matches(exportHadoopClientOpts)) {
        String oldHeapSizeRegex = "export\\s*HADOOP_CLIENT_OPTS=\"-Xmx\\$\\{HADOOP_HEAPSIZE\\}m\\s*\\$HADOOP_CLIENT_OPTS\"";
        String newHeapSizeRegex = "export HADOOP_CLIENT_OPTS=\"$HADOOP_CLIENT_OPTS  -Xmx${HADOOP_HEAPSIZE}m\"";
        return hiveEnvContent.replaceAll(oldHeapSizeRegex, Matcher.quoteReplacement(newHeapSizeRegex));
    } else {
        String oldHeapSizeRegex = "export\\s*HADOOP_HEAPSIZE\\s*=\\s*\"\\{\\{hive_heapsize\\}\\}\"\\.*\\n\\s*fi\\s*\\n";
        String newHeapSizeRegex = "export HADOOP_HEAPSIZE={{hive_heapsize}} # Setting for HiveServer2 and Client\n"
                + "fi\n" + "\n"
                + "export HADOOP_CLIENT_OPTS=\"$HADOOP_CLIENT_OPTS  -Xmx${HADOOP_HEAPSIZE}m\"\n";
        return hiveEnvContent.replaceAll(oldHeapSizeRegex, Matcher.quoteReplacement(newHeapSizeRegex));
    }
}