Read config file and return the config as {@link Map}.

@return the options from config file
@throws MojoExecutionException
the mojo execution exception
181215
private Map<String, String> getOptionsFromConfigFile(String newConfigFile) throws MojoExecutionException {

        this.getLog().debug("Using search path at: " + this.basedir.getAbsolutePath());
        this.resourceManager.addSearchPath(FileResourceLoader.ID, this.basedir.getAbsolutePath());

        try (InputStream configInput = this.resourceManager.getResourceAsInputStream(newConfigFile)) {
            return new ConfigReader().read(configInput);
        } catch (ResourceNotFoundException e) {
            throw new MojoExecutionException("Cannot find config file [" + newConfigFile + "]");
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot read config file [" + newConfigFile + "]", e);
        } catch (SAXException e) {
            throw new MojoExecutionException("Cannot parse config file [" + newConfigFile + "]", e);
        } catch (ConfigReadException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
46345
public Map<String, ? extends Object> getOptionValues()
    {
        Map<String, Object> opts = new HashMap<String, Object>();
        for (Option opt : options)
        {
            if (opt.wasGiven()) opts.put( opt.getName(), opt.getValue() );
        }

        return opts;
    }
342628
protected Xpp3Dom createSREConfiguration() throws MojoExecutionException, MojoFailureException {
		final Xpp3Dom xmlConfiguration = new Xpp3Dom("configuration"); //$NON-NLS-1$
		final Xpp3Dom xmlArchive = new Xpp3Dom("archive"); //$NON-NLS-1$
		xmlConfiguration.addChild(xmlArchive);

		final String mainClass = getMainClass();
		if (mainClass.isEmpty()) {
			throw new MojoFailureException("the main class of the SRE is missed"); //$NON-NLS-1$
		}
		final Xpp3Dom xmlManifest = new Xpp3Dom("manifest"); //$NON-NLS-1$
		xmlArchive.addChild(xmlManifest);
		final Xpp3Dom xmlManifestMainClass = new Xpp3Dom("mainClass"); //$NON-NLS-1$
		xmlManifestMainClass.setValue(mainClass);
		xmlManifest.addChild(xmlManifestMainClass);

		final Xpp3Dom xmlSections = new Xpp3Dom("manifestSections"); //$NON-NLS-1$
		xmlArchive.addChild(xmlSections);
		final Xpp3Dom xmlSection = new Xpp3Dom("manifestSection"); //$NON-NLS-1$
		xmlSections.addChild(xmlSection);
		final Xpp3Dom xmlSectionName = new Xpp3Dom("name"); //$NON-NLS-1$
		xmlSectionName.setValue(SREConstants.MANIFEST_SECTION_SRE);
		xmlSection.addChild(xmlSectionName);
		final Xpp3Dom xmlManifestEntries = new Xpp3Dom("manifestEntries"); //$NON-NLS-1$
		xmlSection.addChild(xmlManifestEntries);

		ManifestUpdater updater = getManifestUpdater();
		if (updater == null) {
			updater = new ManifestUpdater() {

				@Override
				public void addSREAttribute(String name, String value) {
					assert name != null && !name.isEmpty();
					if (value != null && !value.isEmpty()) {
						getLog().debug("Adding to SRE manifest: " + name + " = " + value);  //$NON-NLS-1$//$NON-NLS-2$
						final Xpp3Dom xmlManifestEntry = new Xpp3Dom(name);
						xmlManifestEntry.setValue(value);
						xmlManifestEntries.addChild(xmlManifestEntry);
					}
				}

				@Override
				public void addMainAttribute(String name, String value) {
					//
				}

			};
		}

		buildManifest(updater, mainClass);

		return xmlConfiguration;
	}
136698
private List<StringKeyValueBean> loadConfiguration(){
		List<StringKeyValueBean> result = new LinkedList<StringKeyValueBean>();
		Resource resource = null;
		if (primaryConfigFileLocation == null){
			return result;		// fail silently because we must be in test
		}else{
			resource = new ClassPathResource(primaryConfigFileLocation);
			if (!resource.exists()){
				if (secondaryConfigFileLocation == null){
					return result;		// fail silently because we must be in test
				}
				resource = new ClassPathResource(secondaryConfigFileLocation);
			}
		}

		Properties properties = null;
		try {
			properties = PropertiesLoaderUtils.loadProperties(resource);
			
			// sort them, make the more specific ones at the top, and "*"/".*" at the bottom
			List<StringKeyValueBean> sorted = new ArrayList<StringKeyValueBean>(properties.size());
			for (Entry<Object, Object> entry: properties.entrySet()){
				sorted.add(new StringKeyValueBean(entry.getKey().toString(), entry.getValue().toString()));
			}
			Collections.sort(sorted, new Comparator<StringKeyValueBean>(){
				@Override
				public int compare(StringKeyValueBean b0,	StringKeyValueBean b1) {
					if (b0.getKey().equals(b1.getKey())){
						return 0;
					}
					if ("*".equals(b0.getKey()) || ".*".equals(b0.getKey())){
						return 1;
					}else if ("*".equals(b1.getKey()) || ".*".equals(b1.getKey())){
						return -1;
					}
					return b1.getKey().compareTo(b0.getKey());
				}
			});
			result.addAll(sorted);
		} catch (Exception e) {
			logger.warn("Cannot load environments configuration file from class path: " + 
					(resource == null ? "<null>" : resource.getDescription()), e);
		}
		
		return result;
	}
67653
public java.util.Map<java.lang.String, alluxio.grpc.ConfigProperties> getPathConfigsMap() {
    return internalGetPathConfigs().getMap();
  }
354058
public void execute ()
        throws MojoExecutionException
    {
        if (mapFile == null) mapFile = new File(base, "compmap.txt");
        if (actionDef == null) actionDef = new File(base, "actions.xml");

        ComponentBundler bundler = new ComponentBundler(mapFile, actionDef) {
            @Override protected boolean keepRawPngs () { return keepRawPngs; }
            @Override protected boolean uncompressed () { return false; }
            @Override protected void logInfo (String message) { getLog().info(message); }
            @Override protected void logWarn (String message) { getLog().warn(message); }
        };

        if (bundleDirectories == null) {
            bundleDirectories = findBundleDirs();
        }
        for (BundleDirectory bdir : bundleDirectories) {
            getLog().info("Processing " + bdir);
            File root = new File(base, bdir.root);

            // create the scanner
            DirectoryScanner scanner = new DirectoryScanner();
            scanner.setBasedir(new File(root, bdir.path));
            scanner.setIncludes(includes.toArray(new String[0]));
            scanner.setExcludes(excludes.toArray(new String[0]));
            scanner.scan();

            File targetDir = new File(targetBase, bdir.root);
            File target = new File(new File(targetDir, bdir.path), "components.jar");
            List<Tuple<File,List<String>>> sourceDirs = Lists.newArrayList();
            sourceDirs.add(Tuple.newTuple(scanner.getBasedir(),
                                          Arrays.asList(scanner.getIncludedFiles())));
            bundler.execute(root.getPath(), target, sourceDirs);
        }
    }
574554
public java.util.List<java.util.Map<String, String>> getConfigurations() {
        return configurations;
    }
290522
public Map<String, Object> parse(JBakeConfiguration config, File file) {
        this.configuration = config;
        List<String> fileContents;
        try (InputStream is = new FileInputStream(file)) {

            fileContents = IOUtils.readLines(is, config.getRenderEncoding());
        } catch (IOException e) {
            LOGGER.error("Error while opening file {}", file, e);

            return null;
        }

        boolean hasHeader = hasHeader(fileContents);
        ParserContext context = new ParserContext(
                file,
                fileContents,
                config,
                hasHeader
        );

        if (hasHeader) {
            // read header from file
            processDefaultHeader(context);
        }
        // then read engine specific headers
        processHeader(context);

        setModelDefaultsIfNotSetInHeader(context);
        sanitizeTags(context);

        if (context.getType().isEmpty() || context.getStatus().isEmpty()) {
            // output error
            LOGGER.warn("Parsing skipped (missing type or status value in header meta data) for file {}!", file);
            return null;
        }

        // generate default body
        processDefaultBody(context);

        // eventually process body using specific engine
        if (validate(context)) {
            processBody(context);
        } else {
            LOGGER.error("Incomplete source file ({}) for markup engine: {}", file, getClass().getSimpleName());
            return null;
        }
        // TODO: post parsing plugins to hook in here?

        return context.getDocumentModel();
    }
344643
void createTotalSpecifications(final File dir, final String packageDirectory) throws MojoExecutionException {

        if (dir.equals(null)) {
            throw new MojoExecutionException("Could not read from directory " + dir.getPath());
        }
        final File[] files = dir.listFiles();
        if (files == null) {
            return;
        }
        final File[] providedContextFiles = dir.listFiles((java.io.FileFilter) FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter(), FileFilterUtils.nameFileFilter("providedcontext.json")));
        if (providedContextFiles.length == 1) {
            final File parent = providedContextFiles[0].getParentFile();
            final File outputDir = new File(getSpecificationOutput() + File.separator + packageDirectory.substring(0,packageDirectory.lastIndexOf(File.separator)));
            outputDir.mkdirs();
            try {
                generateTotalSpecification(parent, outputDir);
            } catch (final CodeGenException e) {
                throw new MojoExecutionException("Couldn't create total specification",e);
            }
        }
        for (File entry : dir.listFiles()) {
            if (entry.isDirectory()) {
                createTotalSpecifications(entry, (packageDirectory == null) ? entry.getName() : packageDirectory + File.separator + entry.getName());
            }
        }
    }
1289837
public static void copyConfiguration(AbstractWisdomWatcherMojo mojo, MavenResourcesFiltering filtering) throws
            IOException {
        File in = new File(mojo.basedir, Constants.CONFIGURATION_SRC_DIR);
        if (in.isDirectory()) {
            File out = new File(mojo.getWisdomRootDirectory(), Constants.CONFIGURATION_DIR);
            filterAndCopy(mojo, filtering, in, out);
        } else {
            mojo.getLog().warn("No configuration directory (src/main/configuration) - use this mode at your own risk");
            mojo.getLog().warn("A fake application configuration is going to be created, " +
                    "using a fake application secret, do not use this file in production");
            // No configuration directory, generate a fake application configuration
            File conf = new File(mojo.getWisdomRootDirectory(), "conf");
            mojo.getLog().debug("Creating conf directory " + conf.mkdirs());
            File output = new File(conf, "application.conf");
            ApplicationSecretGenerator.generateFakeConfiguration(output);
        }
    }
1367771
protected Map<String, Object> createContext() {
    Map<String, Object> context = Maps.newHashMap();

    context.put("log", createLogger());
    context.put("container", containerHelper);
    context.put("plugin", pluginDescriptor);
    context.put("pluginContext", getPluginContext());
    context.put("mojo", mojoExecution);
    context.put("basedir", basedir);
    context.put("project", project);
    context.put("properties", createProperties());
    context.put("session", session);
    context.put("settings", settings);
    context.put("ant", MagicContext.ANT_BUILDER);
    context.put("fail", new FailClosureTarget());

    return context;
  }
131015
protected Collection<ResourceFile> getAllResourceFiles()
        throws MojoExecutionException
    {
        try
        {
            Set<ResourceFile> sourcesAndResources = new HashSet<ResourceFile>();
            Set<String> sourcesAndResourcesPath = new HashSet<String>();
            sourcesAndResourcesPath.addAll( getProject().getCompileSourceRoots() );
            for ( Resource resource : getProject().getResources() )
            {
                sourcesAndResourcesPath.add( resource.getDirectory() );
            }

            for ( String name : getModules() )
            {
                GwtModule module = readModule( name );

                sourcesAndResources.add( getDescriptor( module, sourcesAndResourcesPath ) );
                int count = 1;

                for ( String source : module.getSources() )
                {
                    getLog().debug( "GWT sources from " + name + '.' + source );
                    Collection<ResourceFile> files = getAsResources( module, source, sourcesAndResourcesPath,
                                                                     "**/*.java" );
                    sourcesAndResources.addAll( files );
                    count += files.size();

                    Collection<ResourceFile> uifiles = getAsResources( module, source, sourcesAndResourcesPath,
                            "**/*.ui.xml" );
                    sourcesAndResources.addAll( uifiles );
                    count += uifiles.size();
                }
                for ( String source : module.getSuperSources() )
                {
                    getLog().debug( "GWT super-sources from " + name + '.' + source );
                    Collection<ResourceFile> files = getAsResources( module, source, sourcesAndResourcesPath,
                                                                     "**/*.java" );
                    sourcesAndResources.addAll( files );
                    count += files.size();

                    Collection<ResourceFile> uifiles = getAsResources( module, source, sourcesAndResourcesPath,
                            "**/*.ui.xml" );
                    sourcesAndResources.addAll( uifiles );
                    count += uifiles.size();
                }
                getLog().info( count + " source files from GWT module " + name );
            }
            return sourcesAndResources;
        }
        catch ( GwtModuleReaderException e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }
915046
private SARLConfiguration readCompileConfiguration(
			ProjectConfigurationRequest request, MojoExecution mojo, IProgressMonitor monitor)
					throws CoreException {
		final SARLConfiguration config = new SARLConfiguration();

		final MavenProject project = request.getMavenProject();

		final File input = getParameterValue(project, "input", File.class, mojo, monitor); //$NON-NLS-1$
		final File output = getParameterValue(project, "output", File.class, mojo, monitor); //$NON-NLS-1$
		final File binOutput = getParameterValue(project, "binOutput", File.class, mojo, monitor); //$NON-NLS-1$
		final File testInput = getParameterValue(project, "testInput", File.class, mojo, monitor); //$NON-NLS-1$
		final File testOutput = getParameterValue(project, "testOutput", File.class, mojo, monitor); //$NON-NLS-1$
		final File testBinOutput = getParameterValue(project, "testBinOutput", File.class, mojo, monitor); //$NON-NLS-1$

		config.setInput(input);
		config.setOutput(output);
		config.setBinOutput(binOutput);
		config.setTestInput(testInput);
		config.setTestOutput(testOutput);
		config.setTestBinOutput(testBinOutput);

		final String inputCompliance = getParameterValue(project, "source", String.class, mojo, monitor); //$NON-NLS-1$
		final String outputCompliance = getParameterValue(project, "target", String.class, mojo, monitor); //$NON-NLS-1$

		config.setInputCompliance(inputCompliance);
		config.setOutputCompliance(outputCompliance);

		final String encoding = getParameterValue(project, "encoding", String.class, mojo, monitor); //$NON-NLS-1$
		config.setEncoding(encoding);

		return config;
	}
96981
protected OutputStream initOutput(final File file)
        throws MojoExecutionException {
        // stream to return
        final OutputStream stream;
        // plenty of things can go wrong...
        try {
            // directory?
            if (file.isDirectory()) {
            throw new MojoExecutionException("File "
                + file.getAbsolutePath() + " is directory!");
            }
            // already exists && can't remove it?
            if (file.exists() && !file.delete()) {
            throw new MojoExecutionException("Could not remove file: "
                + file.getAbsolutePath());
            }
            // get directory above file file
            final File fileDirectory = file.getParentFile();
            // does not exist && create it?
            if (!fileDirectory.exists() && !fileDirectory.mkdirs()) {
            throw new MojoExecutionException(
                "Could not create directory: "
                    + fileDirectory.getAbsolutePath());
            }
            // moar wtf: parent directory is no directory?
            if (!fileDirectory.isDirectory()) {
            throw new MojoExecutionException("Not a directory: "
                + fileDirectory.getAbsolutePath());
            }
            // file file is for any reason not creatable?
            if (!file.createNewFile()) {
            throw new MojoExecutionException("Could not create file: "
                + file.getAbsolutePath());
            }
            // finally create some file
            stream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Could not find file: "
                + file.getAbsolutePath(), e);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not write to file: "
                + file.getAbsolutePath(), e);
        }
        // return
        return stream;
    }
947652
@Override
  protected Options getOptions() {
    final Options options = super.getOptions();

    final Option filenameOption =
        new Option("f", "the name of the output file, default name is " + DEFAULT_FILENAME
            + " [optional]");
    filenameOption.setArgName("FILENAME");
    filenameOption.setLongOpt("filename");
    filenameOption.setRequired(false);
    filenameOption.setArgs(1);

    options.addOption(filenameOption);

    final Option errorFilenameOption =
        new Option("ef", "the name of the error output file, default name is "
            + DEFAULT_ERROR_FILENAME + " [optional]");
    errorFilenameOption.setArgName("ERRORFILENAME");
    errorFilenameOption.setLongOpt("errorfilename");
    errorFilenameOption.setRequired(false);
    errorFilenameOption.setArgs(1);

    options.addOption(errorFilenameOption);

    final Option verboseOption = new Option("ve", "verbose logging, default is false [optional]");
    verboseOption.setArgName("VERBOSE");
    verboseOption.setLongOpt("verbose");
    verboseOption.setRequired(false);
    verboseOption.setArgs(1);
    verboseOption.setType(Boolean.class);

    options.addOption(verboseOption);

    return options;

  }
213230
@Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        if (this.skipFormatting) {
            getLog().info("Formatting is skipped");
            return;
        }

        long startClock = System.currentTimeMillis();

        if (StringUtils.isEmpty(this.encoding)) {
            this.encoding = ReaderFactory.FILE_ENCODING;
            getLog().warn("File encoding has not been set, using platform encoding (" + this.encoding
                    + ") to format source files, i.e. build is platform dependent!");
        } else {
            if (!Charset.isSupported(this.encoding)) {
                throw new MojoExecutionException("Encoding '" + this.encoding + "' is not supported");
            }
            getLog().info("Using '" + this.encoding + "' encoding to format source files.");
        }

        List<File> files = new ArrayList<>();
        if (this.directories != null) {
            for (File directory : this.directories) {
                if (directory.exists() && directory.isDirectory()) {
                    files.addAll(addCollectionFiles(directory));
                }
            }
        } else {
            // Using defaults of source main and test dirs
            if (this.sourceDirectory != null && this.sourceDirectory.exists() && this.sourceDirectory.isDirectory()) {
                files.addAll(addCollectionFiles(this.sourceDirectory));
            }
            if (this.testSourceDirectory != null && this.testSourceDirectory.exists()
                    && this.testSourceDirectory.isDirectory()) {
                files.addAll(addCollectionFiles(this.testSourceDirectory));
            }
        }

        int numberOfFiles = files.size();
        Log log = getLog();
        log.info("Number of files to be formatted: " + numberOfFiles);

        if (numberOfFiles > 0) {
            createCodeFormatter();
            ResultCollector rc = new ResultCollector();
            Properties hashCache = readFileHashCacheFile();

            String basedirPath = getBasedirPath();
            for (int i = 0, n = files.size(); i < n; i++) {
                File file = files.get(i);
                if (file.exists()) {
                    if (file.canWrite()) {
                        formatFile(file, rc, hashCache, basedirPath);
                    } else {
                        rc.readOnlyCount++;
                    }
                } else {
                    rc.failCount++;
                }
            }

            storeFileHashCache(hashCache);

            long endClock = System.currentTimeMillis();

            log.info("Successfully formatted:          " + rc.successCount + FILE_S);
            log.info("Fail to format:                  " + rc.failCount + FILE_S);
            log.info("Skipped:                         " + rc.skippedCount + FILE_S);
            log.info("Read only skipped:               " + rc.readOnlyCount + FILE_S);
            log.info("Approximate time taken:          " + ((endClock - startClock) / 1000) + "s");
        }
    }
1265361
protected CommandLine getDotCommandLine(Set<String> generatedFiles)
			throws MojoExecutionException {
		CommandLine cl = new CommandLine(command);
		if (isVerbose()) {
			cl.addArgument("-v");
		}
		cl.addArgument("-Tpng");
		cl.addArgument("-O");
		for (String generatedFile : generatedFiles) {
			if (generatedFile.endsWith(".dot")) {
				cl.addArgument(generatedFile);
			}
		}
		if (isVerbose()) {
			getLog().info("Commandline: " + cl);
		}
		return cl;
	}