Parses the logging config proto into a {@link ValidatedLoggingConfig}.

@throws IllegalArgumentException if there is an error during parsing.
519090
public static ValidatedLoggingConfig create(LoggingConfig configProto) {
    Map<String, ValidatedLoggableElement> elementsByName = new LinkedHashMap<>();
    Map<Long, ValidatedLoggableElement> elementsById = new LinkedHashMap<>();
    elementsByName.put(UNDEFINED_VE.getName(), UNDEFINED_VE);
    elementsById.put(UNDEFINED_VE.getId(), UNDEFINED_VE);
    // perfect duplicates are allowed, though not encouraged.
    for (LoggableElement element : ImmutableSet.copyOf(configProto.getElementList())) {
      String name = element.getName();
      checkArgument(BaseUtils.isDottedIdentifier(name), "'%s' is not a valid identifier", name);
      checkArgument(
          MIN_ID_VALUE <= element.getId() && element.getId() <= MAX_ID_VALUE,
          "ID %s for '%s' must be between %s and %s (inclusive).",
          element.getId(),
          name,
          MIN_ID_VALUE,
          MAX_ID_VALUE);
      ValidatedLoggableElement elementConfig = ValidatedLoggableElement.create(element);
      ValidatedLoggableElement oldWithSameId =
          elementsById.put(elementConfig.getId(), elementConfig);
      if (oldWithSameId != null) {
        throw new IllegalArgumentException(
            String.format(
                "Found 2 LoggableElements with the same id %d: %s and %s",
                elementConfig.getId(), oldWithSameId.getName(), elementConfig.getName()));
      }
      ValidatedLoggableElement oldWithSameName =
          elementsByName.put(elementConfig.getName(), elementConfig);
      if (oldWithSameName != null) {
        throw new IllegalArgumentException(
            String.format(
                "Found 2 LoggableElements with the same name %s, their ids are %d and %d",
                elementConfig.getName(), oldWithSameName.getId(), elementConfig.getId()));
      }
    }
    return new ValidatedLoggingConfig(ImmutableMap.copyOf(elementsByName));
  }
1152879
public static void validArgument(boolean expression, String message, Object... messageArgs) {
    if (!expression) {
      throw new IllegalArgumentException(format(message, messageArgs));
    }
  }
790635
public Appender parse( String pattern ) throws IllegalArgumentException
	{
		List<Appender> appenders = new ArrayList<Appender>();
		int prev = 0;
		int pos = 0;
		while ((pos = pattern.indexOf(VAR_START, pos)) >= 0)
		{
			// Add text between beginning/end of last variable
			if ( pos > prev )
			{
				appenders.add(new TextAppender(pattern.substring(prev, pos)));
			}

			// Move to real variable name beginning
			pos += VAR_START_LEN;

			// Next close bracket (not necessarily the variable end bracket if
			// there is a default value with nested variables
			int endVariable = pattern.indexOf(VAR_CLOSE, pos);
			if ( endVariable < 0 )
			{
				throw new IllegalArgumentException(format(
						"Syntax error in property value ''{0}'', missing close bracket ''{1}'' for variable beginning at col {2}: ''{3}''", pattern,
						VAR_CLOSE, pos - VAR_START_LEN, pattern.substring(pos - VAR_START_LEN)));
			}

			// Try to skip eventual internal variable here
			int nextVariable = pattern.indexOf(VAR_START, pos);
			// Just used to throw exception with more accurate message
			int lastEndVariable = endVariable;
			boolean hasNested = false;
			while (nextVariable >= 0 && nextVariable < endVariable)
			{
				hasNested = true;
				endVariable = pattern.indexOf(VAR_CLOSE, endVariable + VAR_CLOSE_LEN);
				// Something is badly closed
				if ( endVariable < 0 )
				{
					throw new IllegalArgumentException(format(
							"Syntax error in property value ''{0}'', missing close bracket ''{1}'' for variable beginning at col {2}: ''{3}''",
							pattern, VAR_CLOSE, nextVariable, pattern.substring(nextVariable, lastEndVariable)));
				}
				nextVariable = pattern.indexOf(VAR_START, nextVariable + VAR_START_LEN);
				lastEndVariable = endVariable;
			}
			// The chunk to process
			final String rawKey = pattern.substring(pos - VAR_START_LEN, endVariable + VAR_CLOSE_LEN);
			// Key without variable start and end symbols
			final String key = pattern.substring(pos, endVariable);

			int pipeIndex = key.indexOf(PIPE_SEPARATOR);

			boolean hasKeyVariables = false;
			boolean hasDefault = false;
			boolean hasDefaultVariables = false;

			// There is a pipe
			if ( pipeIndex >= 0 )
			{
				// No nested property detected, simple default part
				if ( !hasNested )
				{
					hasDefault = true;
					hasDefaultVariables = false;
				}
				// There is a pipe and nested variable,
				// determine if pipe is for the current variable or a nested key
				// variable
				else
				{
					int nextStartKeyVariable = key.indexOf(VAR_START);
					hasKeyVariables = pipeIndex > nextStartKeyVariable;
					if ( hasKeyVariables )
					{
						// ff${fdf}|${f}
						int nextEndKeyVariable = key.indexOf(VAR_CLOSE, nextStartKeyVariable + VAR_START_LEN);
						pipeIndex = key.indexOf(PIPE_SEPARATOR, nextEndKeyVariable + VAR_CLOSE_LEN);
						while (pipeIndex >= 0 && pipeIndex > nextStartKeyVariable)
						{
							pipeIndex = key.indexOf(PIPE_SEPARATOR, nextEndKeyVariable + VAR_CLOSE_LEN);
							nextStartKeyVariable = key.indexOf(VAR_START, nextStartKeyVariable + VAR_START_LEN);
							// No more nested variable
							if ( nextStartKeyVariable < 0 )
							{
								break;
							}
							nextEndKeyVariable = key.indexOf(VAR_CLOSE, nextEndKeyVariable + VAR_CLOSE_LEN);
							if ( nextEndKeyVariable < 0 )
							{
								throw new IllegalArgumentException(
										format("Syntax error in property value ''{0}'', missing close bracket ''{1}'' for variable beginning at col {2}: ''{3}''",
												pattern, VAR_CLOSE, nextStartKeyVariable, key.substring(nextStartKeyVariable)));
							}
						}
					}

					// nested variables are only for key, current variable does
					// not have a default value
					if ( pipeIndex >= 0 )
					{
						hasDefault = true;
						hasDefaultVariables = key.indexOf(VAR_START, pipeIndex) >= 0;
					}

				}
			}
			// No pipe, there is key variables if nested elements have been
			// detected
			else
			{
				hasKeyVariables = hasNested;
			}

			// Construct variable appenders
			String keyPart = null;
			String defaultPart = null;
			if ( hasDefault )
			{
				keyPart = key.substring(0, pipeIndex).trim();
				defaultPart = key.substring(pipeIndex + PIPE_SEPARATOR_LEN).trim();
			} else
			{
				keyPart = key.trim();
			}
			// Choose TextAppender when relevant to avoid unecessary parsing when it's clearly not needed
			appenders.add(new KeyAppender(this, rawKey, hasKeyVariables ? parse(keyPart) : new TextAppender(keyPart), !hasDefault ? null
					: (hasDefaultVariables ? parse(defaultPart) : new TextAppender(defaultPart))));

			prev = endVariable + VAR_CLOSE_LEN;
			pos = prev;
		}

		if ( prev < pattern.length() )
		{
			appenders.add(new TextAppender(pattern.substring(prev)));
		}

		return appenders.size() == 1 ? appenders.get(0) : new MixinAppender(pattern, appenders);
	}
189176
public static void registerMavenLogger(Log innerLogger) {
		if (INSTANCE == null) {
			INSTANCE = new MavenLoggerFactory(innerLogger);
		}

		if (INSTANCE.innerLogger != innerLogger) {
			throw new IllegalArgumentException(
					"You've previously register a org.apache.maven.plugin.logging.Log that is NOT the one that you're passing !");
		}
	}
722663
private Map<String, String> parseArgsIntoMap(String[] args) {
        Map<String, String> parms = new HashMap<String, String>();

        for (int i = 0; i < args.length; i++) {
            String key = args[i];
            if (!isKeyword(key)) {
                throw new ValidatorProcessUsageException("'" + key
                        + "' is not a keyword.");
            }
            if (!ALL_PARAMETERS.contains(key)) {
                throw new ValidatorProcessUsageException("'" + key
                        + "' is not a recognized keyword.");
            }
            if (i >= args.length - 1) {
                parms.put(key, null);
            } else {
                String value = args[i + 1];
                if (isKeyword(value)) {
                    parms.put(key, null);
                } else {
                    parms.put(key, value);
                    i++;
                }
            }
        }

        return parms;
    }
1203272
@SuppressWarnings("checkstyle:avoidhidingcauseexception")
  public static ConfigurationBuilder parseToConfigurationBuilder(final String[] args,
                                                                 final Class<? extends Name<?>>... argClasses)
      throws ParseException {
    final CommandLine commandLine;
    try {
      commandLine = new CommandLine().processCommandLine(args, argClasses);
    } catch (final IOException e) {
      // processCommandLine() converts ParseException into IOException. This reverts that to make exception handling
      // more straight forward.
      throw new ParseException(e.getMessage());
    }

    // processCommandLine() indicates that it might return null. We need to guard users of this one from that
    if (commandLine == null) {
      throw new ParseException("Unable to parse the command line and the parser returned null.");
    } else {
      return commandLine.getBuilder();
    }
  }
60999
public BucketLoggingConfigurationHandler parseLoggingStatusResponse(InputStream inputStream)
            throws IOException {
        BucketLoggingConfigurationHandler handler = new BucketLoggingConfigurationHandler();
        parseXmlInputStream(handler, inputStream);
        return handler;
    }
890235
public void validateSSLConfig() throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "validateSSLConfig");

        try {
            if (Boolean.parseBoolean(getProperty(Constants.SSLPROP_VALIDATION_ENABLED))) {
                JSSEProviderFactory.getInstance().getSSLContext(null, this);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    Tr.exit(tc, "validateSSLConfig -> true");
                return;
            }

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                Tr.exit(tc, "validateSSLConfig not enabled.");
            return;
        } catch (Exception e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                Tr.exit(tc, "validateSSLConfig -> false");
            throw e;
        }
    }
1339905
public void configureLogging(final LoggingSettings loggingSettings) {

        final Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
        final LoggerContext context = root.getLoggerContext();

        // Reset prior configuration
        context.reset();

        // Propagate level changes to java.util.logging
        final LevelChangePropagator propagator = new LevelChangePropagator();
        propagator.setContext(context);
        propagator.setResetJUL(true);

        // Set base threshold for all other loggers.
        root.setLevel(loggingSettings.getLevel());

        // Loop through explicitly configured loggers and set the levels
        for (final Map.Entry<String, Level> entry : loggingSettings.getLoggers().entrySet()) {
            ((Logger)LoggerFactory.getLogger(entry.getKey())).setLevel(entry.getValue());
        }

        if (loggingSettings.getLogFile().isEnabled()) {
            root.addAppender(getFileAppender(loggingSettings.getLogFile(), context));
        }

        if (loggingSettings.getConsole().isEnabled()) {
            root.addAppender(getConsoleAppender(loggingSettings.getConsole(), context));
        }
    }
1084439
@Override
    public void setConfiguration(
                    final Properties config
                    )
    throws ValidityException
    {
        String  pattern = config.getProperty( "pattern" );
        if (pattern == null) {
            throw new ValidityException( "no 'pattern' parameter" );
        }

        try {
            _formatter = new SimpleDateFormat( pattern );
                         //throws IllegalArgumentException
        } catch (Exception ex) {
            throw new ValidityException( "invalid 'pattern' parameter: "
                            + ex.getMessage() );
        }
    }
350238
@Override
    public InputStream validateResource(InputStream configDocInputStream, String docLocation) throws ConfigValidationException {

        errorMsgIssued = false;
        InputStream returnInputStream = null;

        try {
            // Reads the input stream into an output stream where we can copy it
            byte[] bfr = new byte[4096];
            int len = 0;
            ByteArrayOutputStream bfrOutputStream = new ByteArrayOutputStream();
            while ((len = configDocInputStream.read(bfr, 0, bfr.length)) > -1)
                bfrOutputStream.write(bfr, 0, len);
            configDocInputStream.close();
            bfrOutputStream.close();

            // Makes two copies of the input stream (one for us and one for the
            // the configuration document parser)
            InputStream validatorInputStream =
                            new ByteArrayInputStream(bfrOutputStream.toByteArray());
            returnInputStream = new ByteArrayInputStream(bfrOutputStream.toByteArray());

            // Parses the document to be verified
            Document document = dbFactory.newDocumentBuilder().parse(validatorInputStream);

            // Verifies the signature
            verifyDocument(document, docLocation);
        }

        // An error occurred while attempting to verify the document signature
        catch (Throwable t) {
            if (!errorMsgIssued) {
                if (t instanceof SAXException)
                    printErrorMessage("error.configValidator.parseFailed",
                                      docLocation, t.getMessage());
                else if (t instanceof MarshalException)
                    printErrorMessage("error.configValidator.unmarshalFailed",
                                      docLocation, t.getMessage());
                else
                    printErrorMessage("error.configValidator.error",
                                      docLocation, t.getMessage());
            }

            FFDCFilter.processException(t, CLASS_NAME, "138", this, new Object[] { docLocation });

            returnInputStream = null;

            // Throw exception to terminate the server
            throw new ConfigValidationException("Configuration parsing encountered an invalid document", docLocation);
        }

        return returnInputStream;
    }
924474
@Override
    public ValidationResult<?> validate(final OptionalConfigurationComponent<?> configurationComponent) {
        if (configurationComponent instanceof ValidatingConfigurationComponent) {
            @SuppressWarnings("rawtypes")
            final ValidatingConfigurationComponent<?> validatingComponent = (ValidatingConfigurationComponent) configurationComponent;
            return validatingComponent.validate();
        } else {
            final Class<?> componentClass = configurationComponent.getClass();
            final Validator<?> validator = validators.get(componentClass);
            if (validator != null) {
                @SuppressWarnings({"unchecked", "rawtypes"})
                final ValidationResult<?> validationResult = ((Validator) validator).validate(configurationComponent);
                return validationResult;
            } else {
                throw new IllegalArgumentException("No validator for class " + componentClass.getCanonicalName());
            }
        }
    }
1179435
private void parseDebugOutputConfig(final Node node,
			final ConfigSettings config)
	{

		String name, value;
		Node nnode;
		NodeList list = node.getChildNodes();

		int length = list.getLength();
		for (int i = 0; i < length; i++) {
			nnode = list.item(i);

			name = nnode.getNodeName().toUpperCase();
			if (name.equals(KEY_DEBUG_PATH)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				value = value.substring(1, value.length() - 1);

				config.setConfigParameter(ConfigurationKeys.LOGGING_PATH_DEBUG,
						value);

			}
			else if (name.equals(KEY_DEBUG_ENABLED)) {

				Boolean enabled = Boolean.parseBoolean(nnode.getChildNodes()
						.item(0).getNodeValue());
				config.setConfigParameter(ConfigurationKeys.MODE_DEBUG_OUTPUT,
						enabled);
			}
		}
	}
678456
protected AbstractConfigValue rawParseValue(ConfigOrigin origin, ConfigParseOptions finalOptions)
            throws IOException {
        Reader reader = reader(finalOptions);

        // after reader() we will have loaded the Content-Type.
        ConfigSyntax contentType = contentType();

        ConfigParseOptions optionsWithContentType;
        if (contentType != null) {
            if (ConfigImpl.traceLoadsEnabled() && finalOptions.getSyntax() != null)
                trace("Overriding syntax " + finalOptions.getSyntax()
                        + " with Content-Type which specified " + contentType);

            optionsWithContentType = finalOptions.setSyntax(contentType);
        } else {
            optionsWithContentType = finalOptions;
        }

        try {
            return rawParseValue(reader, origin, optionsWithContentType);
        } finally {
            reader.close();
        }
    }
937303
private void parseDebugConfig(final Node node, final ConfigSettings config)
	{

		String name;
		Boolean value;
		Node nnode;
		NodeList list = node.getChildNodes();

		int length = list.getLength();
		for (int i = 0; i < length; i++) {
			nnode = list.item(i);

			name = nnode.getNodeName().toUpperCase();
			if (name.equals(KEY_VERIFICATION_DIFF)) {

				value = Boolean.parseBoolean(nnode.getChildNodes().item(0)
						.getNodeValue());
				config.setConfigParameter(ConfigurationKeys.VERIFICATION_DIFF,
						value);

			}
			else if (name.equals(KEY_VERIFICATION_ENCODING)) {

				value = Boolean.parseBoolean(nnode.getChildNodes().item(0)
						.getNodeValue());

				config.setConfigParameter(
						ConfigurationKeys.VERIFICATION_ENCODING, value);

			}
			else if (name.equals(KEY_STATISTICAL_OUTPUT)) {

				value = Boolean.parseBoolean(nnode.getChildNodes().item(0)
						.getNodeValue());
				config.setConfigParameter(
						ConfigurationKeys.MODE_STATISTICAL_OUTPUT, value);

			}
			else if (name.equals(SUBSECTION_DEBUG_OUTPUT)) {

				parseDebugOutputConfig(nnode, config);
			}
		}
	}
501160
public GatewayConfigDocument parse(final File configFile) throws Exception {
        long time = 0;
        if (LOGGER.isDebugEnabled()) {
            time = System.currentTimeMillis();
        }

        // For errors and logging (KG-1379) we need to report the real config file name,
        // which is not always 'gateway-config.xml'.
        String configFileName = configFile.getName();

        // Validate the gateway-config
        GatewayConfigDocument config = null;
        XmlOptions parseOptions = new XmlOptions();
        parseOptions.setLoadLineNumbers();
        parseOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT);
        parseOptions.setLoadStripWhitespace();
        parseOptions.setLoadStripComments();

        File translatedConfigFile;
        try {
            translatedConfigFile = getTranslatedConfigFile(configFile);
        } catch (Exception e) {
            Throwable rootCause = getRootCause(e);
            if (rootCause == null) {
                rootCause = e;
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.error("Error upgrading XML: " + rootCause, rootCause);

            } else {
                LOGGER.error("Error upgrading XML: " + rootCause);
            }

            // If it's not an IllegalArgumentException, wrap it in a
            // GatewayConfigParserException
            if (e instanceof IllegalArgumentException) {
                throw e;

            } else {
                throw new GatewayConfigParserException(e.getMessage());
            }
        }

        List<String> xmlParseErrors = new ArrayList<>();
        try {
            config = GatewayConfigDocument.Factory.parse(new FileInputStream(translatedConfigFile), parseOptions);

        } catch (Exception e) {
            // track the parse error so that we don't make the 2nd pass through the file
            xmlParseErrors.add("Invalid XML: " + getRootCause(e).getMessage());
        }

        if (xmlParseErrors.isEmpty()) {
            // The properties used in parameter substitution are now proper XMLBeans
            // and should be injected after an initial parse
            GatewayConfigDocument.GatewayConfig gatewayConfig = config.getGatewayConfig();
            PropertiesType properties = gatewayConfig.getProperties();
            Map<String, String> propertiesMap = new HashMap<>();
            if (properties != null) {
                for (PropertyType propertyType : properties.getPropertyArray()) {
                    propertiesMap.put(propertyType.getName(), propertyType.getValue());
                }
            }

            // make a second pass through the file now, injecting the properties and performing XSL translations
            InputStream xmlInjectedIn = new PipedInputStream();
            OutputStream xmlInjectedOut = new PipedOutputStream((PipedInputStream) xmlInjectedIn);
            ExecutorService xmlInjectedExecutor = Executors.newSingleThreadExecutor();
            Future<Boolean> xmlInjectedFuture = xmlInjectedExecutor.submit(new XMLParameterInjector(new FileInputStream(
                    translatedConfigFile), xmlInjectedOut, propertiesMap, configuration, xmlParseErrors));

            // trace injected xml
            if (LOGGER.isTraceEnabled()) {
                xmlInjectedIn = bufferToTraceLog(xmlInjectedIn,
                        "Gateway config file '" + configFileName + "' post parameter injection", LOGGER);
            }

            // Pass gateway-config through the pre-parse transformer
            InputStream xmlTransformedIn = new PipedInputStream();
            OutputStream xmlTransformedOut = new PipedOutputStream((PipedInputStream) xmlTransformedIn);
            ExecutorService xmlTransformedExecutor = Executors.newSingleThreadExecutor();
            Future<Boolean> xmlTransformedFuture = xmlTransformedExecutor.submit(
                    new XSLTransformer(xmlInjectedIn, xmlTransformedOut, GATEWAY_CONFIG_ANNOTATE_TYPES_XSL));

            // trace transformed xml
            if (LOGGER.isTraceEnabled()) {
                xmlTransformedIn = bufferToTraceLog(xmlTransformedIn,
                        "Gateway config file '" + configFileName + "' post XSL transformation", LOGGER);
            }

            try {
                config = GatewayConfigDocument.Factory.parse(xmlTransformedIn, parseOptions);
            } catch (Exception e) {
                // If parsing with previous namespace was also unsuccessful,
                // process errors top down, failing fast, for user level errors
               try {
                    if (xmlInjectedFuture.get()) {
                        if (xmlTransformedFuture.get()) {
                            throw e;
                        }
                    }
                } catch (Exception n) {
                    xmlParseErrors.add("Invalid XML: " + getRootCause(n).getMessage());
                }
            } finally {
                xmlInjectedFuture.cancel(true);
                xmlInjectedExecutor.shutdownNow();
                xmlTransformedFuture.cancel(true);
                xmlTransformedExecutor.shutdownNow();
            }
        }

        validateGatewayConfig(config, xmlParseErrors);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("parsed " + " gateway config file '" + configFileName + "' in [" + (System.currentTimeMillis() - time) +
                    " ms]");
        }

        return config;
    }
700610
private void parse()
    {
        this.elements = new ArrayList<>();

        try {
            for (Tokenizer tokenizer = new Tokenizer(this.rawVersion); tokenizer.next();) {
                Element element = new Element(tokenizer);
                this.elements.add(element);
                if (element.getVersionType() != Type.STABLE) {
                    this.type = element.getVersionType();
                }
            }

            trimPadding(this.elements);
        } catch (Exception e) {
            // Make sure to never fail no matter what
            LOGGER.error("Failed to parse version [" + this.rawVersion + "]", e);
            this.elements.add(new Element(this.rawVersion));
        }
    }