Hook to allow derived classes to override behavior associated with
extracting params from a GString.

@param gstring a GString containing the SQL query with embedded params
@return extracts the parameters from the expression as a List
@see #expand(Object)
428946
protected List<Object> getParameters(GString gstring) {
        return new ArrayList<Object>(Arrays.asList(gstring.getValues()));
    }
72023
protected String redefineArgsIfNeeds(String formatString) {
        if (!formatString.contains("{") || !formatString.contains("}")) { // no parameter
            return formatString;
        }
        final List<ScopeInfo> plainVariableList = Srl.extractScopeList(formatString, "{", "}");
        if (!plainVariableList.stream()
                .map(info -> info.getContent()) // to content list
                .filter(tent -> !Srl.isNumberHarfAll(tent)) // named only (non-number only)
                .findAny() // one or zero
                .isPresent()) { // no named exists, number only
            return formatString; // no need to redefine
        }
        createVariableOrderAgent().orderScopeList(plainVariableList);
        final Map<String, String> fromToMap = new LinkedHashMap<String, String>(plainVariableList.size());
        int index = 0;
        for (ScopeInfo scopeInfo : plainVariableList) {
            fromToMap.put(scopeInfo.getScope(), "{" + index + "}");
            ++index;
        }
        return buildRedefinedMessage(formatString, fromToMap);
    }
946947
private List<Object> onParameterValue(String paramString)
    {
        List<Object> value = kunderaQuery.getClauseValue(paramString);
        if (value == null)
        {
            throw new IllegalStateException("parameter has not been bound" + paramString);
        }
        return value;
    }
53556
private String expandLHS(final String lhs,
                             int lineOffset) {
        substitutions = new ArrayList<Map<String, String>>();

        //        logger.info( "*** LHS>" + lhs + "<" );
        final StringBuilder buf = new StringBuilder();
        
        final String[] lines = lhs.split( (lhs.indexOf("\r\n") >= 0 ? "\r\n":"\n"),
                                          -1 ); // since we assembled the string, we know line breaks are \n
        final String[] expanded = new String[lines.length]; // buffer for expanded lines
        int lastExpanded = -1;
        int lastPattern = -1;
        for ( int i = 0; i < lines.length - 1; i++ ) {
            final String trimmed = lines[i].trim();
            expanded[++lastExpanded] = lines[i];

            if ( trimmed.length() == 0 || trimmed.startsWith( "#" ) || trimmed.startsWith( "//" ) ) {
                // comments - do nothing
            } else if ( trimmed.startsWith( ">" ) ) {
                // passthrough code - simply remove the passthrough mark character
                expanded[lastExpanded] = lines[i].replaceFirst( ">",
                                                                " " );
                lastPattern = lastExpanded;
            } else {
                // regular expansion - expand the expression
                expanded[lastExpanded] =
                        substitute( expanded[lastExpanded],
                                    this.condition,
                                    i + lineOffset,
                                    useWhen,
                                    showSteps );

                // do we need to report errors for that?
                if ( lines[i].equals( expanded[lastExpanded] ) ) {
                    // report error
                    this.addError( new ExpanderException( "Unable to expand: " + lines[i].replaceAll( "[\n\r]",
                                                                                                      "" ).trim(),
                                                          i + lineOffset ) );
                }
                // but if the original starts with a "-", it means we need to add it
                // as a constraint to the previous pattern
                if ( trimmed.startsWith( "-" ) && (!lines[i].equals( expanded[lastExpanded] )) ) {
                    if ( lastPattern >= 0 ) {
                        ConstraintInformation c = ConstraintInformation.findConstraintInformationInPattern( expanded[lastPattern] );
                        if ( c.start > -1 ) {
                            // rebuilding previous pattern structure
                            expanded[lastPattern] = expanded[lastPattern].substring( 0,
                                                                                     c.start ) + c.constraints + ((c.constraints.trim().length() == 0) ? "" : ", ") + expanded[lastExpanded].trim() + expanded[lastPattern].substring( c.end );
                        } else {
                            // error, pattern not found to add constraint to
                            this.addError( new ExpanderException( "No pattern was found to add the constraint to: " + lines[i].trim(),
                                                                  i + lineOffset ) );
                        }
                    }
                    lastExpanded--;
                } else {
                    lastPattern = lastExpanded;
                }
            }
        }
        for ( int i = 0; i <= lastExpanded; i++ ) {
            buf.append( expanded[i] );
            buf.append( nl );
        }

        return buf.toString();
    }
639880
@Override
    public Query createQuery(String qlString)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "em.createQuery(" + qlString + ");\n" + toString());

        return getEMInvocationInfo(false).createQuery(qlString);
    }
975243
public StringExpression prepend(Expression<String> str) {
        return Expressions.stringOperation(Ops.CONCAT, str, mixin);
    }
701777
private String substitute(String exp,
                              List<DSLMappingEntry> entries,
                              int line,
                              Map<String, Integer> use,
                              boolean showSingleSteps) {
        if ( entries.size() == 0 ) {
            if ( line > 0 ) {
                this.addError( new ExpanderException( "No mapping entries for expanding: " + exp,
                                                      line ) );
            }
            return exp;
        }
        if ( showSingleSteps ) {
            logger.info( "to expand: |" + exp + "|" );
        }
        Map<String, String> key2value = new HashMap<String, String>();
        for ( final DSLMappingEntry entry : entries ) {
            Map<String, Integer> vars = entry.getVariables();
            String mappingKey = entry.getMappingKey();
            String vp = entry.getValuePattern();
            Pattern kp = entry.getKeyPattern();
            Matcher m = kp.matcher( exp );
            int startPos = 0;
            boolean match;
            Integer count;
            if ( showUsage ) {
                count = use.get( mappingKey );
                if ( count == null ) use.put( mappingKey, 0 );
            }
            while ( startPos < exp.length() && m.find( startPos ) ) {
                match = true;
                if ( showSingleSteps ) {
                    logger.info( "  matches: " + kp.toString() );
                }
                if ( showUsage ) {
                    use.put( mappingKey,
                             use.get( mappingKey ) + 1 );
                }
                // Replace the range of group 0.  
                String target = m.group( 0 );
                if ( !vars.keySet().isEmpty() ) {
                    // Build a pattern matching any variable enclosed in braces.
                    StringBuilder sb = new StringBuilder();
                    String del = "\\{(";
                    for ( String key : vars.keySet() ) {
                        sb.append( del ).append( Pattern.quote( key ) );
                        del = "|";
                    }
                    sb.append( ")" ).append( funcPatStr ).append( "\\}" );
                    Pattern allkeyPat = Pattern.compile( sb.toString() );
                    vp = entry.getValuePattern();
                    Matcher allkeyMat = allkeyPat.matcher( vp );

                    // While the pattern matches, get the actual key and replace by '$' + index
                    while ( allkeyMat.find() ) {
                        String theKey = allkeyMat.group( 1 );
                        String theFunc = allkeyMat.group( 2 );
                        String foundValue = m.group( vars.get( theKey ) );
                        String theValue = applyFunc( theFunc,
                                                     foundValue );
                        String newVp = vp.substring( 0,
                                                     allkeyMat.start() ) + theValue + vp.substring( allkeyMat.end() );
                        allkeyMat.reset( newVp );
                        key2value.put( theKey,
                                       foundValue );
                        if (newVp.equals(vp)) {
                            break;
                        } else {
                            vp = newVp;
                        }
                    }
                }

                // Try to find any matches from previous lines.
                Matcher varRefMat = varRefPat.matcher( vp );
                while ( varRefMat.find() ) {
                    String theKey = varRefMat.group( 1 );
                    String theFunc = varRefMat.group( 2 );
                    for ( int ientry = substitutions.size() - 1; ientry >= 0; ientry-- ) {
                        String foundValue = substitutions.get( ientry ).get( theKey );
                        if ( foundValue != null ) {
                            String theValue = applyFunc( theFunc,
                                                         foundValue );
                            // replace it
                            vp = vp.substring( 0,
                                               varRefMat.start() ) + theValue + vp.substring( varRefMat.end() );
                            varRefMat.reset( vp );
                            break;
                        }
                    }
                }

                // add the new set of substitutions
                if ( key2value.size() > 0 ) {
                    substitutions.add( key2value );
                }

                // now replace the target
                exp = exp.substring( 0,
                                     m.start() ) + vp + exp.substring( m.end() );
                if ( match && showSingleSteps ) {
                    logger.info( "   result: |" + exp + "|" );
                }
                startPos = m.start() + vp.length();
                m.reset( exp );
            }
        }
        return exp;
    }
212041
private String limitString(int rowIndex){

        if(params.length != 2){
            throw new IllegalArgumentException("Wrong number of Parameters for limit string expression");
        }

        final RecordList.Record currentRecord = recordList.getRecords().get(rowIndex);
        final String field = currentRecord.getValueByFieldName(params[0]);
        int limit = Integer.parseInt(params[1]);

        if (field.isEmpty() || field.length() < limit){
            return field;
        }

        String result = field.substring(0, limit) + "...";
        return result;
    }
598243
@Override
  public ExpandableField<?> deserialize(JsonElement json, Type typeOfT,
      JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonNull()) {
      return null;
    }

    ExpandableField<?> expandableField;

    // Check if json is a String ID. If so, the field has not been expanded, so we only need to
    // serialize a String and create a new ExpandableField with the String id only.
    if (json.isJsonPrimitive()) {
      JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
      if (jsonPrimitive.isString()) {
        expandableField = new ExpandableField<>(jsonPrimitive.getAsString(), null);
        return expandableField;
      } else {
        throw new JsonParseException("ExpandableField is a non-string primitive type.");
      }
    // Check if json is an expanded Object. If so, the field has been expanded, so we need to
    // serialize it into the proper typeOfT, and create an ExpandableField with both the String id
    // and this serialized object.
    } else if (json.isJsonObject()) {
      // Get the `id` out of the response
      JsonObject fieldAsJsonObject = json.getAsJsonObject();
      String id = fieldAsJsonObject.getAsJsonPrimitive("id").getAsString();
      // We need to get the type inside the generic ExpandableField to make sure fromJson correctly
      // serializes the JsonObject:
      Type clazz = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
      expandableField = new ExpandableField<>(id, (HasId) context.deserialize(json, clazz));
      return expandableField;
    }

    // If json is neither a String nor an Object, error. (We expect all expandable objects to fit
    // the known string-or-object design. If one doesn't, then something may have changed in the API
    // and this code may need to be updated.)
    throw new JsonParseException("ExpandableField is a non-object, non-primitive type.");
  }
283094
private StringBuffer expandConstructions(final String drl) {
        // display keys if requested
        if ( showKeyword ) {
            for ( DSLMappingEntry entry : this.keywords ) {
                logger.info( "keyword: " + entry.getMappingKey() );
                logger.info( "         " + entry.getKeyPattern() );
            }
        }
        if ( showWhen ) {
            for ( DSLMappingEntry entry : this.condition ) {
                logger.info( "when: " + entry.getMappingKey() );
                logger.info( "      " + entry.getKeyPattern() );
                //                logger.info( "      " + entry.getValuePattern() );
            }
        }
        if ( showThen ) {
            for ( DSLMappingEntry entry : this.consequence ) {
                logger.info( "then: " + entry.getMappingKey() );
                logger.info( "      " + entry.getKeyPattern() );
            }
        }

        // parse and expand specific areas
        final Matcher m = finder.matcher( drl );
        final StringBuffer buf = new StringBuffer();
        int drlPos = 0;
        int linecount = 0;
        while ( m.find() ) {
            final StringBuilder expanded = new StringBuilder();

            int newPos = m.start();
            linecount += countNewlines( drl,
                                        drlPos,
                                        newPos );
            drlPos = newPos;

            String constr = m.group().trim();
            if ( constr.startsWith( "rule" ) ) {
                String headerFragment = m.group( 1 );
                expanded.append( headerFragment ); // adding rule header and attributes
                String lhsFragment = m.group( 2 );
                expanded.append( this.expandLHS( lhsFragment,
                                                 linecount + countNewlines( drl,
                                                                            drlPos,
                                                                            m.start( 2 ) ) + 1 ) );
                String thenFragment = m.group( 3 );
                expanded.append( thenFragment ); // adding "then" header
                String rhsFragment = this.expandRHS( m.group( 4 ),
                                                     linecount + countNewlines( drl,
                                                                                drlPos,
                                                                                m.start( 4 ) ) + 1 );
                expanded.append( rhsFragment );
                expanded.append( m.group( 5 ) ); // adding rule trailer

            } else if ( constr.startsWith( "query" ) ) {
                String fragment = m.group( 6 );
                expanded.append( fragment ); // adding query header and attributes
                String lhsFragment = this.expandLHS( m.group( 7 ),
                                                     linecount + countNewlines( drl,
                                                                                drlPos,
                                                                                m.start( 7 ) ) + 1 );
                expanded.append( lhsFragment );
                expanded.append( m.group( 8 ) ); // adding query trailer

            } else {
                // strange behavior
                this.addError( new ExpanderException( "Unable to expand statement: " + constr,
                                                      0 ) );
            }
            m.appendReplacement( buf,
                                 Matcher.quoteReplacement( expanded.toString() ) );
        }
        m.appendTail( buf );
        return buf;
    }
175975
private String expandString() {
        final FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.SMALL);
        try {
            final INodeReadTrx rtx = createRtxAndMove();
            final FilterAxis axis = new FilterAxis(new DescendantAxis(rtx), rtx, new TextFilter(rtx));

            while (axis.hasNext()) {
                if (rtx.getNode().getKind() == TEXT) {
                    fsb.append(rtx.getValueOfCurrentNode());
                }
                axis.next();
            }
            rtx.close();
        } catch (final TTException exc) {
            LOGGER.error(exc.toString());
        }
        return fsb.condense().toString();
    }
119690
function expandArrayPlaceholders(args){
	var sql = args[0];
	var params = args[1];
	if (!Array.isArray(params) || params.length === 0)
		return;
	var assocLengthsOfArrayParams = {};
	for (var i=0; i<params.length; i++)
		if (Array.isArray(params[i])){
			if (params[i].length === 0)
				throw Error("empty array in query params");
			assocLengthsOfArrayParams[i] = params[i].length;
		}
	if (Object.keys(assocLengthsOfArrayParams).length === 0)
		return;
	var arrParts = sql.split('?');
	if (arrParts.length - 1 !== params.length)
		throw Error("wrong parameter count");
	var expanded_sql = "";
	for (var i=0; i<arrParts.length; i++){
		expanded_sql += arrParts[i];
		if (i === arrParts.length-1) // last part
			break;
		var len = assocLengthsOfArrayParams[i];
		if (len) // array
			expanded_sql += _.fill(Array(len), "?").join(",");
		else
			expanded_sql += "?";
	}
	var flattened_params = _.flatten(params);
	args[0] = expanded_sql;
	args[1] = flattened_params;
}
1228738
public static String format(String formatString, Object... args) {
    // Rewrites the varargs so that objects that need special formatting are
    // replaced with formatted strings, then hands off to {@link String#format}.

    Object[] formattedArgs = new Object[args.length];
    for (int i = 0; i < args.length; ++i) {
      formattedArgs[i] = formatObject(args[i]);
    }

    return String.format(formatString, (Object[]) formattedArgs);
  }
658831
public static Object stringToParam(String string, String typeString) throws IllegalArgumentException {
		if (typeString.equals("boolean") || typeString.equals("java.lang.Boolean")) {
			return Boolean.parseBoolean(string);
		} else if (typeString.equals("char") || typeString.equals("java.lang.Character")) {
			if (string.length() == 0) {
				// not sure what to do here
				return '\0';
			} else {
				return string.toCharArray()[0];
			}
		} else if (typeString.equals("byte") || typeString.equals("java.lang.Byte")) {
			return Byte.parseByte(string);
		} else if (typeString.equals("short") || typeString.equals("java.lang.Short")) {
			return Short.parseShort(string);
		} else if (typeString.equals("int") || typeString.equals("java.lang.Integer")) {
			return Integer.parseInt(string);
		} else if (typeString.equals("long") || typeString.equals("java.lang.Long")) {
			return Long.parseLong(string);
		} else if (typeString.equals("java.lang.String")) {
			return string;
		} else if (typeString.equals("float") || typeString.equals("java.lang.Float")) {
			return Float.parseFloat(string);
		} else if (typeString.equals("double") || typeString.equals("java.lang.Double")) {
			return Double.parseDouble(string);
		} else {
			Constructor<?> constr = getConstructor(typeString);
			try {
				return constr.newInstance(new Object[] { string });
			} catch (Exception e) {
				throw new IllegalArgumentException(
						"Could not get new instance using string constructor for type " + typeString);
			}
		}
	}
555872
@Override
    public GStringExpression visitGstring(GstringContext ctx) {
        final List<ConstantExpression> stringLiteralList = new LinkedList<>();
        final String begin = ctx.GStringBegin().getText();
        final String beginQuotation = beginQuotation(begin);
        stringLiteralList.add(configureAST(new ConstantExpression(parseGStringBegin(ctx, beginQuotation)), ctx.GStringBegin()));

        List<ConstantExpression> partStrings =
                ctx.GStringPart().stream()
                        .map(e -> configureAST(new ConstantExpression(parseGStringPart(e, beginQuotation)), e))
                        .collect(Collectors.toList());
        stringLiteralList.addAll(partStrings);

        stringLiteralList.add(configureAST(new ConstantExpression(parseGStringEnd(ctx, beginQuotation)), ctx.GStringEnd()));

        List<Expression> values = ctx.gstringValue().stream()
                .map(e -> {
                    Expression expression = this.visitGstringValue(e);

                    if (expression instanceof ClosureExpression && !hasArrow(e)) {
                        List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements();

                        if (statementList.stream().noneMatch(DefaultGroovyMethods::asBoolean)) {
                            return configureAST(new ConstantExpression(null), e);
                        }

                        return configureAST(this.createCallMethodCallExpression(expression, new ArgumentListExpression(), true), e);
                    }

                    return expression;
                })
                .collect(Collectors.toList());

        StringBuilder verbatimText = new StringBuilder(ctx.getText().length());
        for (int i = 0, n = stringLiteralList.size(), s = values.size(); i < n; i++) {
            verbatimText.append(stringLiteralList.get(i).getValue());

            if (i == s) {
                continue;
            }

            Expression value = values.get(i);
            if (!asBoolean(value)) {
                continue;
            }

            verbatimText.append(DOLLAR_STR);
            verbatimText.append(value.getText());
        }

        return configureAST(new GStringExpression(verbatimText.toString(), stringLiteralList, values), ctx);
    }
1262384
@Override
    public Optional<CommonExpressionSegment> extract(final ParserRuleContext expressionNode, final Map<ParserRuleContext, Integer> parameterMarkerIndexes) {
        return Optional.of(new CommonExpressionSegment(expressionNode.getStart().getStartIndex(), expressionNode.getStop().getStopIndex()));
    }
775156
private StringBuffer toQueryPrefixNoSelect(String t) {

        StringBuffer sb = new StringBuffer(255);

        return sb.append(t).append(whereTrue);
    }