Parse the option "sessionVariable" to ensure having no injection. semi-column not in string
will be replaced by comma.

@param sessionVariable option value
@return parsed String
505545
public static String parseSessionVariables(String sessionVariable) {
    StringBuilder out = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    Parse state = Parse.Normal;
    boolean iskey = true;
    boolean singleQuotes = true;
    boolean first = true;
    String key = null;

    char[] chars = sessionVariable.toCharArray();

    for (char car : chars) {

      if (state == Parse.Escape) {
        sb.append(car);
        state = singleQuotes ? Parse.Quote : Parse.String;
        continue;
      }

      switch (car) {
        case '"':
          if (state == Parse.Normal) {
            state = Parse.String;
            singleQuotes = false;
          } else if (state == Parse.String && !singleQuotes) {
            state = Parse.Normal;
          }
          break;

        case '\'':
          if (state == Parse.Normal) {
            state = Parse.String;
            singleQuotes = true;
          } else if (state == Parse.String && singleQuotes) {
            state = Parse.Normal;
          }
          break;

        case '\\':
          if (state == Parse.String) {
            state = Parse.Escape;
          }
          break;

        case ';':
        case ',':
          if (state == Parse.Normal) {
            if (!iskey) {
              if (!first) {
                out.append(",");
              }
              out.append(key);
              out.append(sb.toString());
              first = false;
            } else {
              key = sb.toString().trim();
              if (!key.isEmpty()) {
                if (!first) {
                  out.append(",");
                }
                out.append(key);
                first = false;
              }
            }
            iskey = true;
            key = null;
            sb = new StringBuilder();
            continue;
          }
          break;

        case '=':
          if (state == Parse.Normal && iskey) {
            key = sb.toString().trim();
            iskey = false;
            sb = new StringBuilder();
          }
          break;

        default:
          //nothing
      }

      sb.append(car);
    }

    if (!iskey) {
      if (!first) {
        out.append(",");
      }
      out.append(key);
      out.append(sb.toString());
    } else {
      String tmpkey = sb.toString().trim();
      if (!tmpkey.isEmpty() && !first) {
        out.append(",");
      }
      out.append(tmpkey);
    }
    return out.toString();
  }
849043
private static org.hibernate.engine.spi.EntityKey getOptionalObjectKey(QueryParameters queryParameters, SharedSessionContractImplementor session) {
		final Object optionalObject = queryParameters.getOptionalObject();
		final Serializable optionalId = queryParameters.getOptionalId();
		final String optionalEntityName = queryParameters.getOptionalEntityName();

		if ( optionalObject != null && optionalEntityName != null ) {
			return session.generateEntityKey( optionalId, session.getEntityPersister( optionalEntityName, optionalObject ) );
		}
		else {
			return null;
		}
	}
1137261
def parse_session_token(self):
        
        session_file = os.path.join(self.file_path, 'session_token')
        # Only try to extract the strings if the file exists
        if os.path.isfile(session_file):
            # Create a list to store the data from the file
            session_list = list()
            with open(session_file, 'r') as session_token:
                for line in session_token:
                    # Split the description e.g. secret= from the line
                    value, data = line.split('=')
                    # Add each string to the list
                    session_list.append(data.rstrip())
            # Extract the appropriate variable from the list
            self.session_secret = session_list[0]
            self.session_token = session_list[1]
87520
private static ValidationResult validateFormatStringVariable(
      ExpressionTree formatStringTree,
      final Symbol formatStringSymbol,
      final List<? extends ExpressionTree> args,
      final VisitorState state) {
    if (formatStringSymbol.getKind() != ElementKind.LOCAL_VARIABLE) {
      return ValidationResult.create(
          null,
          String.format(
              "Variables used as format strings that are not local variables must be compile time"
                  + " constants.\n%s is neither a local variable nor a compile time constant.",
              formatStringTree));
    }

    // Find the Tree for the block in which the variable is defined. If it is not defined in this
    // class (though it may have been in a super class). We require compile time constant values in
    // that case.
    Symbol owner = formatStringSymbol.owner;
    TreePath path = TreePath.getPath(state.getPath(), formatStringTree);
    while (path != null && ASTHelpers.getSymbol(path.getLeaf()) != owner) {
      path = path.getParentPath();
    }

    // A local variable must be declared in a parent tree to be accessed. This case should be
    // impossible.
    if (path == null) {
      throw new IllegalStateException(
          String.format(
              "Could not find the Tree where local variable %s is declared. "
                  + "This should be impossible.",
              formatStringTree));
    }

    // Scan down from the scope where the variable was declared
    ValidationResult result =
        path.getLeaf()
            .accept(
                new TreeScanner<ValidationResult, Void>() {
                  @Override
                  public ValidationResult visitVariable(VariableTree node, Void unused) {
                    if (ASTHelpers.getSymbol(node) == formatStringSymbol) {
                      if (node.getInitializer() == null) {
                        return ValidationResult.create(
                            null,
                            String.format(
                                "Variables used as format strings must be initialized when they are"
                                    + " declared.\nInvalid declaration: %s",
                                node));
                      }
                      return validateStringFromAssignment(node, node.getInitializer(), args, state);
                    }
                    return super.visitVariable(node, unused);
                  }

                  @Override
                  public ValidationResult reduce(ValidationResult r1, ValidationResult r2) {
                    if (r1 == null && r2 == null) {
                      return null;
                    }
                    return MoreObjects.firstNonNull(r1, r2);
                  }
                },
                null);

    return result;
  }
246869
public static function getCheckStrFromSession($sessionVariable, $expected_value)
    {

        $success = false;

        $session_value = $_SESSION[$sessionVariable];
        if ($expected_value === $session_value) {
            echo(' checked="checked" ');

            $success = true;

        }

        return $success;
    }
821714
private static String formatParameterValueAsUnescapedVariableTemplate(final Object parameterValue) {
        // Get the value
        if (parameterValue == null) { // If null (= NO_VALUE), empty String
            return "";
        }
        // If it is not multivalued (e.g. non-List) simply escape and return
        if (!(parameterValue instanceof List<?>)) {
            return parameterValue.toString();
        }
        // It is multivalued, so iterate and escape each item (no need to escape the comma separating them, it's an allowed char)
        final List<?> values = (List<?>)parameterValue;
        final int valuesLen = values.size();
        final StringBuilder strBuilder = new StringBuilder(valuesLen * 16);
        for (int i = 0; i < valuesLen; i++) {
            final Object valueItem = values.get(i);
            if (strBuilder.length() > 0) {
                strBuilder.append(',');
            }
            strBuilder.append(valueItem == null? "" : valueItem.toString());
        }
        return strBuilder.toString();
    }
54080
public com.google.protobuf.ByteString
      getVariableNameBytes() {
    java.lang.Object ref = variableName_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b = 
          com.google.protobuf.ByteString.copyFromUtf8(
              (java.lang.String) ref);
      variableName_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }
783201
protected String getVersionString(int sessionVersion) {
        String sessionVersionString = _versionPrefix;
        if (_versionPrefixLength > 0) {
            if (sessionVersion > 0) {
                StringBuffer sb = new StringBuffer();
                sb.append(_versionPrefix).append(sessionVersion);
                sessionVersionString = sb.substring(sb.length() - _versionPrefixLength, sb.length());
            }
        } else {
            sessionVersionString = "";
        }
        return sessionVersionString;
    }
1043931
private String nameViewOrVariable(final String prefix,
									  final String intermediateName,
									  final String suffix,
									  final Collection<String> alreadyDefinedNames,
									  boolean putQuote) {
		int borderLength = prefix.length() + suffix.length();
		int signatureVarLength = intermediateName.length();

		if (borderLength >= (NAME_MAX_LENGTH - NAME_NUMBER_LENGTH))  {
			throw new IllegalArgumentException("The prefix and the suffix are too long (their accumulated length must " +
					"be less than " + (NAME_MAX_LENGTH - NAME_NUMBER_LENGTH) + ")");
		}

		/**
		 * If the length limit is not reached, processes as usual.
		 */
		if (signatureVarLength + borderLength <= NAME_MAX_LENGTH) {
			String unquotedName = buildDefaultName(prefix, intermediateName, suffix);
			String name = putQuote ? sqlQuote(unquotedName) : unquotedName;
			return name;
		}

		String shortenIntermediateNamePrefix = intermediateName.substring(0, NAME_MAX_LENGTH - borderLength
				- NAME_NUMBER_LENGTH);

		/**
		 * Naive implementation
		 */
		for (int i = 0; i < Math.pow(10, NAME_NUMBER_LENGTH); i++) {
			String unquotedVarName = buildDefaultName(prefix, shortenIntermediateNamePrefix + i, suffix);
			String mainVarName = putQuote ? sqlQuote(unquotedVarName) : unquotedVarName;
			if (!alreadyDefinedNames.contains(mainVarName)) {
				return mainVarName;
			}
		}

		// TODO: find a better exception
		throw new RuntimeException("Impossible to create a new variable/view " + prefix + shortenIntermediateNamePrefix
				+ "???" + suffix + " : already " + Math.pow(10, NAME_NUMBER_LENGTH) + " of them.");
	}
375401
public String getVariableQualifiedName(VariableElement var) {
    String shortName = getVariableShortName(var);
    if (ElementUtil.isGlobalVar(var)) {
      String className = getFullName(ElementUtil.getDeclaringClass(var));
      if (ElementUtil.isEnumConstant(var)) {
        // Enums are declared in an array, so we use a macro to shorten the
        // array access expression.
        return "JreEnum(" + className + ", " + shortName + ")";
      }
      return className + '_' + shortName;
    }
    return shortName;
  }
1281150
public static String toVariableName(Object o, String defaultValue) {
	String str = toString(o, null);

	if (str == null || !Decision.isVariableName(str)) return defaultValue;
	return str;
    }
1105871
@Override
	protected List<String> getVariablesToIgnore() {

		List<String> variablesToIgnore = new ArrayList<> ();
		variablesToIgnore.add( "^" + Pattern.quote( MILLI_TIME ) + "$" );
		variablesToIgnore.add( "^" + Pattern.quote( NANO_TIME ) + "$" );
		variablesToIgnore.add( "^" + Pattern.quote( SMART_INDEX ) + "$" );
		variablesToIgnore.add( "^" + Pattern.quote( RANDOM_UUID ) + "$" );

		for( String var : this.context.variables.keySet())
			variablesToIgnore.add( "^\\$\\(" + Pattern.quote( var ) + "\\)$" );

		variablesToIgnore.add( "^" + Pattern.quote( FORMATTED_TIME_PREFIX ) + "[^)]*\\)$" );
		variablesToIgnore.add( "^" + Pattern.quote( EXISTING_INDEX_PREFIX ) + "[^)]*\\)$" );
		return variablesToIgnore;
	}


	/**
	 * Extracts the date pattern for a "formatted time" variable.
	 * @param group a formatted time
	 * @return a non-null string
	 */
	static String extractDatePattern( String group ) {
		return group.substring( FORMATTED_TIME_PREFIX.length(), group.length() - 2 ).trim();
	}


	/**
	 * Replaces variables in instance names.
	 * @param value an expression that can reference other variables (not null)
	 * @param context a context (not null)
	 * @param parentInstancePath the parent instance path (may be null)
	 * @param context a non-null map with context information
	 * @return the updated value, or null if an <code>$(existing_index ...)</code> variable failed to be resolved
	 */
	static String replaceVariables( String value, Context context, String parentInstancePath ) {

		long nanoTime = System.nanoTime();
		long milliTime = TimeUnit.MILLISECONDS.convert( nanoTime, TimeUnit.NANOSECONDS );

		// Simple replacements
		value = value.replace( NANO_TIME, String.valueOf( nanoTime ));
		value = value.replace( MILLI_TIME, String.valueOf( milliTime ));
		value = value.replace( RANDOM_UUID, UUID.randomUUID().toString());

		// A little more complex
		if( value.startsWith( FORMATTED_TIME_PREFIX )
				&& value.endsWith( ")" )) {

			String datePattern = extractDatePattern( value );
			SimpleDateFormat sdf = new SimpleDateFormat( datePattern );

			// We replace the whole value as such variables were validated and span over a entire line
			value = sdf.format( new Date( milliTime ));
		}

		// Even more complex
		int smartCpt = 0;
		if( value.contains( SMART_INDEX )) {
			for( int cpt = 1; smartCpt == 0; cpt++ ) {
				String testName = value.replace( SMART_INDEX, String.valueOf( cpt ));
				String testPath = "/" + testName;
				if( parentInstancePath != null )
					testPath = parentInstancePath + testPath;

				if( ! context.instanceExists( testPath )) {
					smartCpt = cpt;
				}
			}
		}

		value = value.replace( SMART_INDEX, String.valueOf( smartCpt ));

		// To perform in last: deal with existing indexes
		boolean disabled = false;
		Pattern fullPattern = Pattern.compile( EXISTING_INDEX_PATTERN );
		Matcher m = fullPattern.matcher( value );
		if( value.contains( EXISTING_INDEX_PREFIX )
				&& m.matches()) {

			String minOrMax = m.group( 2 );
			String prefix = m.group( 1 );
			String suffix = m.group( 6 );
			String bound = m.group( 5 );
			String instanceNamePattern = "/" + prefix + "(\\d+)" + suffix;
			if( parentInstancePath != null )
				instanceNamePattern = parentInstancePath + instanceNamePattern;

			// Find the index
			int cpt = findIndex( instanceNamePattern, context, bound, "MIN".equals( minOrMax ));

			// If cpt is negative, do not replace anything, nothing matches the requirements.
			// We just return null for the variable's value.
			if( cpt < 0 )
				disabled = true;
			else
				value = m.replaceAll( "$1" + String.valueOf( cpt ) + "$6" );
		}

		// Disabled variable => return null
		if( disabled )
			value = null;

		// Inject other variables, if necessary.
		// Disabled variables are contagious, this is managed during the parsing.
		else
			value = CommandsParser.injectContextVariables( value, context.variables );

		return value;
	}


	/**
	 * @param instanceNamePattern
	 * @param context
	 * @param bound
	 * @param findMinimum true to get the minimum value, false for the maximum
	 * @return -1 if no matching instance was found, a positive integer otherwise
	 */
	private static int findIndex( String instanceNamePattern, Context context, String bound, boolean findMinimum ) {

		// Find all the matching indexes?
		Pattern pattern = Pattern.compile( instanceNamePattern );
		SortedSet<Integer> foundIndexes = new TreeSet<> ();
		for( String instancePath : context.instancePathToComponentName.keySet()) {
			Matcher m = pattern.matcher( instancePath );
			if( ! m .find())
				continue;

			int index = Integer.parseInt( m.group( 1 ));
			foundIndexes.add( index );
		}

		// Exclude indexes that are out of bound
		if( bound != null ) {
			bound = bound.trim();
			int min = 0, max = Integer.MAX_VALUE;
			int value = Integer.parseInt( bound.substring( 1 ).trim());
			if( '<' == bound.charAt( 0 ))
				max = value;
			else
				min = value;

			Set<Integer> toRemove = new HashSet<> ();
			for( Integer index : foundIndexes ) {
				if( index <= min || index >= max )
					toRemove.add( index );
			}

			foundIndexes.removeAll( toRemove );
		}

		// Eventually, decide whether we want the tail or the head
		int result;
		if( foundIndexes.isEmpty())
			result = -1;
		else if( findMinimum )
			result = foundIndexes.first();
		else
			result = foundIndexes.last();

		return result;
	}
759338
public static String removeSessionId(String sessionId, String page) {
        String regexp = ";?jsessionid=" + Pattern.quote(sessionId);
        return page.replaceAll(regexp, "");
    }
329612
private void parseTemplateVariables() throws MiniTemplator.TemplateSyntaxException {
        int p = 0;
        while (true) {
            p = templateText.indexOf("${", p);
            if (p == -1) {
                break;
            }
            int p0 = p;
            p = templateText.indexOf("}", p);
            if (p == -1) {
                throw new MiniTemplator.TemplateSyntaxException(
                        "Invalid variable reference in template at offset " + p0 + ".");
            }
            p++;
            String varName = templateText.substring(p0 + 2, p - 1).trim();
            if (varName.length() == 0) {
                throw new MiniTemplator.TemplateSyntaxException(
                        "Empty variable name in template at offset " + p0 + ".");
            }
            registerVariableReference(varName, p0, p);
        }
    }
583600
public JsStatement var(String variable)
	{
		JsStatement statement = new JsStatement();
		statements.add(statement);
		return statement.append(variable);
	}
1212708
@Override
    public Object resolveVariable(QName variableName) {
        final Map<String, ?> variables = this.localVariables.get();
        if (variables == null) {
            return null;
        }

        final String localPart = variableName.getLocalPart();
        return variables.get(localPart);
    }
331596
Object getDefaultValue(Session session) {

        return defaultExpression == null ? null
                                         : defaultExpression.getValue(session,
                                         dataType);
    }