Example usage for java.util Properties putAll

List of usage examples for java.util Properties putAll

Introduction

In this page you can find the example usage for java.util Properties putAll.

Prototype

@Override
    public synchronized void putAll(Map<?, ?> t) 

Source Link

Usage

From source file:org.apache.ctakes.ytex.kernel.ClassifierEvalUtil.java

private List<String> getWeightParams(File trainFile, String svmType) throws IOException {
    if ("libsvm".equals(svmType)) {
        String label = FileUtil.parseLabelFromFileName(trainFile.getName());
        // default label to 0
        label = label != null && label.length() > 0 ? label : "0";
        Properties weightProps = new Properties();
        weightProps.putAll(props);
        if (props.getProperty("kernel.classweights") != null) {
            Properties tmp = FileUtil.loadProperties(props.getProperty("kernel.classweights"), false);
            if (tmp != null)
                weightProps.putAll(tmp);
        }/*ww  w. j  a v a2 s .c  o m*/
        String weights = weightProps.getProperty("kernel.weight." + label);
        if (weights != null && weights.length() > 0) {
            return Arrays.asList(weights.split(","));
        }
    }
    return new ArrayList<String>(0);
}

From source file:com.hp.application.automation.tools.run.RunFromAlmBuilder.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {

    // get the alm server settings
    AlmServerSettingsModel almServerSettingsModel = getAlmServerSettingsModel();

    if (almServerSettingsModel == null) {
        listener.fatalError(//from w w w  .  j  av  a 2 s .  c o m
                "An ALM server is not defined. Go to Manage Jenkins->Configure System and define your ALM server under Application Lifecycle Management");
        return false;
    }

    EnvVars env = null;
    try {
        env = build.getEnvironment(listener);
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    VariableResolver<String> varResolver = build.getBuildVariableResolver();

    // now merge them into one list
    Properties mergedProperties = new Properties();

    mergedProperties.putAll(almServerSettingsModel.getProperties());
    mergedProperties.putAll(runFromAlmModel.getProperties(env, varResolver));

    String encAlmPass = "";
    try {

        encAlmPass = EncryptionUtils.Encrypt(runFromAlmModel.getAlmPassword(), EncryptionUtils.getSecretKey());

        mergedProperties.remove(RunFromAlmModel.ALM_PASSWORD_KEY);
        mergedProperties.put(RunFromAlmModel.ALM_PASSWORD_KEY, encAlmPass);

    } catch (Exception e) {
        build.setResult(Result.FAILURE);
        listener.fatalError("problem in qcPassword encription");
    }

    Date now = new Date();
    Format formatter = new SimpleDateFormat("ddMMyyyyHHmmssSSS");
    String time = formatter.format(now);

    // get a unique filename for the params file
    ParamFileName = "props" + time + ".txt";
    ResultFilename = "Results" + time + ".xml";
    //KillFileName = "stop" + time + ".txt";

    mergedProperties.put("runType", RunType.Alm.toString());
    mergedProperties.put("resultsFilename", ResultFilename);

    // get properties serialized into a stream
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        mergedProperties.store(stream, "");
    } catch (IOException e) {
        build.setResult(Result.FAILURE);
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String propsSerialization = stream.toString();
    InputStream propsStream = IOUtils.toInputStream(propsSerialization);

    // get the remote workspace filesys
    FilePath projectWS = build.getWorkspace();

    // Get the URL to the Script used to run the test, which is bundled
    // in the plugin
    URL cmdExeUrl = Hudson.getInstance().pluginManager.uberClassLoader.getResource(HpToolsLauncher_SCRIPT_NAME);
    if (cmdExeUrl == null) {
        listener.fatalError(HpToolsLauncher_SCRIPT_NAME + " not found in resources");
        return false;
    }

    FilePath propsFileName = projectWS.child(ParamFileName);
    FilePath CmdLineExe = projectWS.child(HpToolsLauncher_SCRIPT_NAME);

    try {
        // create a file for the properties file, and save the properties
        propsFileName.copyFrom(propsStream);

        // Copy the script to the project workspace
        CmdLineExe.copyFrom(cmdExeUrl);
    } catch (IOException e1) {
        build.setResult(Result.FAILURE);
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        // Run the HpToolsLauncher.exe
        AlmToolsUtils.runOnBuildEnv(build, launcher, listener, CmdLineExe, ParamFileName);
    } catch (IOException ioe) {
        Util.displayIOException(ioe, listener);
        build.setResult(Result.FAILURE);
        return false;
    } catch (InterruptedException e) {
        build.setResult(Result.ABORTED);
        PrintStream out = listener.getLogger();
        // kill processes
        //FilePath killFile = projectWS.child(KillFileName);
        /* try {
        out.println("Sending abort command");
        killFile.write("\n", "UTF-8");
        while (!killFile.exists())
            Thread.sleep(1000);
        Thread.sleep(1500);
                
        } catch (IOException e1) {
        //build.setResult(Result.FAILURE);
        // TODO Auto-generated catch block
        e1.printStackTrace();
        } catch (InterruptedException e1) {
        //build.setResult(Result.FAILURE);
        // TODO Auto-generated catch block
        e1.printStackTrace();
        }*/

        try {
            AlmToolsUtils.runHpToolsAborterOnBuildEnv(build, launcher, listener, ParamFileName);
        } catch (IOException e1) {
            Util.displayIOException(e1, listener);
            build.setResult(Result.FAILURE);
            return false;
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        out.println("Operation was aborted by user.");
        //build.setResult(Result.FAILURE);
    }
    return true;

}

From source file:it.geosolutions.geobatch.imagemosaic.MetadataPresentationOnlineTest.java

protected File createDatastorePropFromFixtures() throws IOException {
    // create datastore file
    Properties datastore = new Properties();
    datastore.putAll(getPostgisParams());
    datastore.remove(JDBCDataStoreFactory.DBTYPE.key);
    datastore.setProperty("SPI", "org.geotools.data.postgis.PostgisNGDataStoreFactory");
    datastore.setProperty(PostgisNGDataStoreFactory.LOOSEBBOX.key, "true");
    datastore.setProperty(PostgisNGDataStoreFactory.ESTIMATED_EXTENTS.key, "false");

    File datastoreFile = new File(getTempDir(), "datastore.properties");
    LOGGER.info("Creating  " + datastoreFile);
    FileOutputStream out = new FileOutputStream(datastoreFile);
    datastore.store(out, "Datastore file created from fixtures");
    out.flush();/*from   w  w  w . j av a2 s.  com*/
    out.close();
    return datastoreFile;
}

From source file:org.ameba.system.NestedReloadableResourceBundleMessageSource.java

private PropertiesHolder refreshClassPathProperties(String filename, PropertiesHolder propHolder) {
    Properties properties = new Properties();
    long lastModified = -1;
    try {//  w w  w .  ja  v a  2  s . c  o m
        Resource[] resources = resolver.getResources(filename + PROPERTIES_SUFFIX);
        for (Resource resource : resources) {
            String sourcePath = resource.getURI().toString().replace(PROPERTIES_SUFFIX, "");
            PropertiesHolder holder = super.refreshProperties(sourcePath, propHolder);
            properties.putAll(holder.getProperties());
            if (lastModified < resource.lastModified())
                lastModified = resource.lastModified();
        }
    } catch (IOException ignored) {
    }
    return new PropertiesHolder(properties, lastModified);
}

From source file:org.apache.cloudstack.spring.module.model.impl.DefaultModuleDefinitionSet.java

protected ApplicationContext getDefaultsContext() {
    URL config = DefaultModuleDefinitionSet.class.getResource(DEFAULT_CONFIG_XML);
    URL additional = DefaultModuleDefinitionSet.class.getResource(DEFAULT_CONFIG_XML_ADDITION);
    Resource[] configs = additional == null ? new Resource[] { new UrlResource(config) }
            : new Resource[] { new UrlResource(config), new UrlResource(additional) };

    ResourceApplicationContext context = new ResourceApplicationContext(configs);
    context.setApplicationName("/defaults");
    context.refresh();//  w w w  .ja v a 2  s.c om

    @SuppressWarnings("unchecked")
    final List<Resource> resources = (List<Resource>) context.getBean(DEFAULT_CONFIG_RESOURCES);

    withModule(new WithModule() {
        @Override
        public void with(ModuleDefinition def, Stack<ModuleDefinition> parents) {
            for (Resource defaults : def.getConfigLocations()) {
                resources.add(defaults);
            }
        }
    });

    configProperties = (Properties) context.getBean(DEFAULT_CONFIG_PROPERTIES);
    for (Resource resource : resources) {
        load(resource, configProperties);
    }

    Properties newProps = new Properties();
    newProps.putAll(configProperties);
    configProperties = newProps;

    for (Resource resource : (Resource[]) context.getBean(MODULE_PROPERITES)) {
        load(resource, configProperties);
    }

    configProperties.putAll(System.getProperties());
    configProperties.putAll(getEnvValues());

    String[] profiles = configProperties.getProperty(SERVER_PROFILE, "").trim().split("\\s*,\\s*");
    if (profiles.length > 0) {
        for (String profile : profiles) {
            Resource resource = context.getResource(String.format(SERVER_PROFILE_FORMAT, profile));
            load(resource, configProperties);
        }
    }

    parseExcludes();
    parseProfiles();

    return context;
}

From source file:nl.nn.adapterframework.util.AppConstants.java

private synchronized void load(ClassLoader classLoader, String directory, String filename, String suffix) {
    StringTokenizer tokenizer = new StringTokenizer(filename, ",");
    while (tokenizer.hasMoreTokens()) {
        String theFilename = tokenizer.nextToken().trim();
        try {/* w ww  .j a  v a2 s.  co  m*/
            if (StringResolver.needsResolution(theFilename)) {
                Properties props = Misc.getEnvironmentVariables();
                props.putAll(System.getProperties());
                theFilename = StringResolver.substVars(theFilename, props);
            }
            InputStream is = null;
            if (directory != null) {
                File file = new File(directory + "/" + theFilename);
                if (file.exists()) {
                    is = new FileInputStream(file);
                } else {
                    log.debug("cannot find file [" + theFilename
                            + "] to load additional properties from, ignoring");
                }
            }
            URL url = null;
            if (is == null) {
                url = ClassUtils.getResourceURL(classLoader, theFilename);
                if (url == null) {
                    log.debug("cannot find resource [" + theFilename
                            + "] to load additional properties from, ignoring");
                } else {
                    is = url.openStream();
                }
            }
            if (is != null) {
                load(is);
                if (url != null) {
                    log.info("Application constants loaded from url [" + url.toString() + "]");
                } else {
                    log.info("Application constants loaded from file [" + theFilename + "]");
                }
                if (getProperty(additionalPropertiesFileKey) != null) {
                    // prevent reloading of the same file over and over again
                    String loadFile = getProperty(additionalPropertiesFileKey);
                    this.remove(additionalPropertiesFileKey);
                    String loadFileSuffix = getProperty(additionalPropertiesFileKey + ".SUFFIX");
                    if (StringUtils.isNotEmpty(loadFileSuffix)) {
                        load(classLoader, directory, loadFile, loadFileSuffix);
                    } else {
                        load(classLoader, directory, loadFile);
                    }
                }
            }
            if (suffix != null) {
                String baseName = FilenameUtils.getBaseName(theFilename);
                String extension = FilenameUtils.getExtension(theFilename);
                String suffixedFilename = baseName + "_" + suffix
                        + (StringUtils.isEmpty(extension) ? "" : "." + extension);
                load(classLoader, directory, suffixedFilename);
            }
        } catch (IOException e) {
            log.error("error reading [" + propertiesFileName + "]", e);
        }
    }
}

From source file:org.apache.falcon.oozie.feed.FeedRetentionCoordinatorBuilder.java

@Override
public List<Properties> buildCoords(Cluster cluster, Path buildPath) throws FalconException {
    org.apache.falcon.entity.v0.feed.Cluster feedCluster = FeedHelper.getCluster(entity, cluster.getName());
    if (feedCluster == null) {
        return null;
    }// w ww. ja v a  2 s .c  o  m

    COORDINATORAPP coord = new COORDINATORAPP();
    String coordName = getEntityName();
    coord.setName(coordName);

    Date endDate = feedCluster.getValidity().getEnd();
    if (RuntimeProperties.get().getProperty("falcon.retention.keep.instances.beyond.validity", "true")
            .equalsIgnoreCase("false")) {
        int retentionLimitinSecs = FeedHelper.getRetentionLimitInSeconds(entity, cluster.getName());
        endDate = DateUtils.addSeconds(endDate, retentionLimitinSecs);
    }
    coord.setEnd(SchemaHelper.formatDateUTC(endDate));

    if (feedCluster.getValidity().getEnd().before(new Date())) {
        Date startDate = DateUtils.addMinutes(endDate, -1);
        coord.setStart(SchemaHelper.formatDateUTC(startDate));
    } else {
        coord.setStart(SchemaHelper.formatDateUTC(new Date()));
    }
    coord.setTimezone(entity.getTimezone().getID());
    Frequency entityFrequency = entity.getFrequency();
    Frequency defaultFrequency = new Frequency("hours(24)");
    if (DateUtil.getFrequencyInMillis(entityFrequency) < DateUtil.getFrequencyInMillis(defaultFrequency)) {
        coord.setFrequency("${coord:hours(6)}");
    } else {
        coord.setFrequency("${coord:days(1)}");
    }

    Path coordPath = getBuildPath(buildPath);
    Properties props = createCoordDefaultConfiguration(coordName);

    WORKFLOW workflow = new WORKFLOW();
    Properties wfProps = OozieOrchestrationWorkflowBuilder.get(entity, cluster, Tag.RETENTION).build(cluster,
            coordPath);
    workflow.setAppPath(getStoragePath(wfProps.getProperty(OozieEntityBuilder.ENTITY_PATH)));
    props.putAll(getProperties(coordPath, coordName));
    // Add the custom properties set in feed. Else, dryrun won't catch any missing props.
    props.putAll(EntityUtil.getEntityProperties(entity));
    workflow.setConfiguration(getConfig(props));
    ACTION action = new ACTION();
    action.setWorkflow(workflow);

    coord.setAction(action);

    Path marshalPath = marshal(cluster, coord, coordPath);
    return Arrays.asList(getProperties(marshalPath, coordName));
}

From source file:org.apache.archiva.rest.services.DefaultCommonServices.java

private void loadResource(final Properties finalProperties, String resourceName, String locale)
        throws IOException {
    Properties properties = new Properties();
    try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName)) {
        if (is != null) {
            properties.load(is);//w w  w  . j av  a2s.  co  m
            finalProperties.putAll(properties);
        } else {
            if (!StringUtils.equalsIgnoreCase(locale, "en")) {
                log.info("cannot load resource {}", resourceName);
            }
        }
    }
}

From source file:com.netflix.lipstick.Main.java

static int run(String args[], PigProgressNotificationListener listener) {
    int rc = 1;// w w w .jav a2  s. c o  m
    boolean verbose = false;
    boolean gruntCalled = false;
    String logFileName = null;

    try {
        Configuration conf = new Configuration(false);
        GenericOptionsParser parser = new GenericOptionsParser(conf, args);
        conf = parser.getConfiguration();

        Properties properties = new Properties();
        PropertiesUtil.loadDefaultProperties(properties);
        properties.putAll(ConfigurationUtil.toProperties(conf));

        String[] pigArgs = parser.getRemainingArgs();

        boolean userSpecifiedLog = false;
        boolean checkScriptOnly = false;

        BufferedReader pin = null;
        boolean debug = false;
        boolean dryrun = false;
        boolean embedded = false;
        List<String> params = new ArrayList<String>();
        List<String> paramFiles = new ArrayList<String>();
        HashSet<String> optimizerRules = new HashSet<String>();

        CmdLineParser opts = new CmdLineParser(pigArgs);
        opts.registerOpt('4', "log4jconf", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('b', "brief", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('c', "check", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('d', "debug", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('e', "execute", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('f', "file", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('g', "embedded", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('h', "help", CmdLineParser.ValueExpected.OPTIONAL);
        opts.registerOpt('i', "version", CmdLineParser.ValueExpected.OPTIONAL);
        opts.registerOpt('l', "logfile", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('m', "param_file", CmdLineParser.ValueExpected.OPTIONAL);
        opts.registerOpt('p', "param", CmdLineParser.ValueExpected.OPTIONAL);
        opts.registerOpt('r', "dryrun", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('t', "optimizer_off", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('v', "verbose", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('w', "warning", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('x', "exectype", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('F', "stop_on_failure", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('M', "no_multiquery", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('P', "propertyFile", CmdLineParser.ValueExpected.REQUIRED);

        ExecMode mode = ExecMode.UNKNOWN;
        String file = null;
        String engine = null;
        ExecType execType = ExecType.MAPREDUCE;
        String execTypeString = properties.getProperty("exectype");
        if (execTypeString != null && execTypeString.length() > 0) {
            execType = ExecType.fromString(execTypeString);
        }

        // set up client side system properties in UDF context
        UDFContext.getUDFContext().setClientSystemProps(properties);

        char opt;
        while ((opt = opts.getNextOpt()) != CmdLineParser.EndOfOpts) {
            switch (opt) {
            case '4':
                String log4jconf = opts.getValStr();
                if (log4jconf != null) {
                    properties.setProperty(LOG4J_CONF, log4jconf);
                }
                break;

            case 'b':
                properties.setProperty(BRIEF, "true");
                break;

            case 'c':
                checkScriptOnly = true;
                break;

            case 'd':
                String logLevel = opts.getValStr();
                if (logLevel != null) {
                    properties.setProperty(DEBUG, logLevel);
                }
                debug = true;
                break;

            case 'e':
                mode = ExecMode.STRING;
                break;

            case 'f':
                mode = ExecMode.FILE;
                file = opts.getValStr();
                break;

            case 'g':
                embedded = true;
                engine = opts.getValStr();
                break;

            case 'F':
                properties.setProperty("stop.on.failure", "" + true);
                break;

            case 'h':
                String topic = opts.getValStr();
                if (topic != null)
                    if (topic.equalsIgnoreCase("properties"))
                        printProperties();
                    else {
                        System.out.println("Invalide help topic - " + topic);
                        usage();
                    }
                else
                    usage();
                return ReturnCode.SUCCESS;

            case 'i':
                System.out.println(getVersionString());
                return ReturnCode.SUCCESS;

            case 'l':
                // call to method that validates the path to the log file
                // and sets up the file to store the client side log file
                String logFileParameter = opts.getValStr();
                if (logFileParameter != null && logFileParameter.length() > 0) {
                    logFileName = validateLogFile(logFileParameter, null);
                } else {
                    logFileName = validateLogFile(logFileName, null);
                }
                userSpecifiedLog = true;
                properties.setProperty("pig.logfile", (logFileName == null ? "" : logFileName));
                break;

            case 'm':
                paramFiles.add(opts.getValStr());
                break;

            case 'M':
                // turns off multiquery optimization
                properties.setProperty("opt.multiquery", "" + false);
                break;

            case 'p':
                params.add(opts.getValStr());
                break;

            case 'r':
                // currently only used for parameter substitution
                // will be extended in the future
                dryrun = true;
                break;

            case 't':
                optimizerRules.add(opts.getValStr());
                break;

            case 'v':
                properties.setProperty(VERBOSE, "" + true);
                verbose = true;
                break;

            case 'w':
                properties.setProperty("aggregate.warning", "" + false);
                break;

            case 'x':
                try {
                    execType = ExecType.fromString(opts.getValStr());
                } catch (IOException e) {
                    throw new RuntimeException("ERROR: Unrecognized exectype.", e);
                }
                break;

            case 'P': {
                InputStream inputStream = null;
                try {
                    FileLocalizer.FetchFileRet localFileRet = FileLocalizer.fetchFile(properties,
                            opts.getValStr());
                    inputStream = new BufferedInputStream(new FileInputStream(localFileRet.file));
                    properties.load(inputStream);
                } catch (IOException e) {
                    throw new RuntimeException("Unable to parse properties file '" + opts.getValStr() + "'");
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
                break;

            default: {
                Character cc = Character.valueOf(opt);
                throw new AssertionError("Unhandled option " + cc.toString());
            }
            }
        }
        // create the context with the parameter
        PigContext pigContext = new PigContext(execType, properties);

        // create the static script state object
        String commandLine = LoadFunc.join((AbstractList<String>) Arrays.asList(args), " ");
        ScriptState scriptState = ScriptState.start(commandLine, pigContext);

        pigContext.getProperties().setProperty("pig.cmd.args", commandLine);

        if (logFileName == null && !userSpecifiedLog) {
            logFileName = validateLogFile(properties.getProperty("pig.logfile"), null);
        }

        pigContext.getProperties().setProperty("pig.logfile", (logFileName == null ? "" : logFileName));

        // configure logging
        configureLog4J(properties, pigContext);
        log.info(getVersionString().replace("\n", ""));

        if (logFileName != null) {
            log.info("Logging error messages to: " + logFileName);
        }

        if (!Boolean.valueOf(properties.getProperty(PROP_FILT_SIMPL_OPT, "false"))) {
            // turn off if the user has not explicitly turned on this
            // optimization
            optimizerRules.add("FilterLogicExpressionSimplifier");
        }

        if (optimizerRules.size() > 0) {
            pigContext.getProperties().setProperty("pig.optimizer.rules",
                    ObjectSerializer.serialize(optimizerRules));
        }

        if (properties.get("udf.import.list") != null)
            PigContext.initializeImportList((String) properties.get("udf.import.list"));

        PigContext.setClassLoader(pigContext.createCl(null));
        if (listener != null) {
            scriptState.registerListener(listener);
        }
        if (properties.getProperty("pig.listeners") != null) {
            for (String clsName : properties.getProperty("pig.listeners").split(":")) {
                // TODO: Is there a better/cleaner way to create these
                // listeners?
                scriptState.registerListener((PigProgressNotificationListener) PigContext.getClassLoader()
                        .loadClass(clsName).newInstance());
            }
        } else {
            scriptState.registerListener(new com.netflix.lipstick.listeners.LipstickPPNL());
        }

        // construct the parameter substitution preprocessor
        LipstickGrunt grunt = null;
        BufferedReader in;
        String substFile = null;

        paramFiles = fetchRemoteParamFiles(paramFiles, properties);
        pigContext.setParams(params);
        pigContext.setParamFiles(paramFiles);

        switch (mode) {

        case FILE: {
            String remainders[] = opts.getRemainingArgs();
            pigContext.getProperties().setProperty(PigContext.PIG_CMD_ARGS_REMAINDERS,
                    ObjectSerializer.serialize(remainders));
            FileLocalizer.FetchFileRet localFileRet = FileLocalizer.fetchFile(properties, file);
            if (localFileRet.didFetch) {
                properties.setProperty("pig.jars.relative.to.dfs", "true");
            }

            scriptState.setFileName(file);

            if (embedded) {
                return runEmbeddedScript(pigContext, localFileRet.file.getPath(), engine);
            } else {
                SupportedScriptLang type = determineScriptType(localFileRet.file.getPath());
                if (type != null) {
                    return runEmbeddedScript(pigContext, localFileRet.file.getPath(),
                            type.name().toLowerCase());
                }
            }

            in = new BufferedReader(new FileReader(localFileRet.file));

            // run parameter substitution preprocessor first
            substFile = file + ".substituted";

            pin = runParamPreprocessor(pigContext, in, substFile, debug || dryrun || checkScriptOnly);
            if (dryrun) {
                if (dryrun(substFile, pigContext)) {
                    log.info("Dry run completed. Substituted pig script is at " + substFile
                            + ". Expanded pig script is at " + file + ".expanded");
                } else {
                    log.info("Dry run completed. Substituted pig script is at " + substFile);
                }
                return ReturnCode.SUCCESS;
            }

            logFileName = validateLogFile(logFileName, file);
            pigContext.getProperties().setProperty("pig.logfile", logFileName);

            // Set job name based on name of the script
            pigContext.getProperties().setProperty(PigContext.JOB_NAME, "PigLatin:" + new File(file).getName());

            if (!debug) {
                new File(substFile).deleteOnExit();
            }

            scriptState.setScript(new File(file));

            grunt = new LipstickGrunt(pin, pigContext);
            gruntCalled = true;

            if (checkScriptOnly) {
                grunt.checkScript(substFile);
                System.err.println(file + " syntax OK");
                rc = ReturnCode.SUCCESS;
            } else {
                int results[] = grunt.exec();
                rc = getReturnCodeForStats(results);
            }

            return rc;
        }

        case STRING: {
            if (checkScriptOnly) {
                System.err.println("ERROR:" + "-c (-check) option is only valid "
                        + "when executing pig with a pig script file)");
                return ReturnCode.ILLEGAL_ARGS;
            }
            // Gather up all the remaining arguments into a string and pass
            // them into
            // grunt.
            StringBuffer sb = new StringBuffer();
            String remainders[] = opts.getRemainingArgs();
            for (int i = 0; i < remainders.length; i++) {
                if (i != 0)
                    sb.append(' ');
                sb.append(remainders[i]);
            }

            scriptState.setScript(sb.toString());

            in = new BufferedReader(new StringReader(sb.toString()));

            grunt = new LipstickGrunt(in, pigContext);
            gruntCalled = true;
            int results[] = grunt.exec();
            return getReturnCodeForStats(results);
        }

        default:
            break;
        }

        // If we're here, we don't know yet what they want. They may have
        // just
        // given us a jar to execute, they might have given us a pig script
        // to
        // execute, or they might have given us a dash (or nothing) which
        // means to
        // run grunt interactive.
        String remainders[] = opts.getRemainingArgs();
        if (remainders == null) {
            if (checkScriptOnly) {
                System.err.println("ERROR:" + "-c (-check) option is only valid "
                        + "when executing pig with a pig script file)");
                return ReturnCode.ILLEGAL_ARGS;
            }
            // Interactive
            mode = ExecMode.SHELL;
            ConsoleReader reader = new ConsoleReader(System.in, new OutputStreamWriter(System.out));
            reader.setDefaultPrompt("grunt> ");
            final String HISTORYFILE = ".pig_history";
            String historyFile = System.getProperty("user.home") + File.separator + HISTORYFILE;
            reader.setHistory(new History(new File(historyFile)));
            ConsoleReaderInputStream inputStream = new ConsoleReaderInputStream(reader);
            grunt = new LipstickGrunt(new BufferedReader(new InputStreamReader(inputStream)), pigContext);
            grunt.setConsoleReader(reader);
            gruntCalled = true;
            grunt.run();
            return ReturnCode.SUCCESS;
        } else {
            pigContext.getProperties().setProperty(PigContext.PIG_CMD_ARGS_REMAINDERS,
                    ObjectSerializer.serialize(remainders));

            // They have a pig script they want us to run.
            mode = ExecMode.FILE;

            FileLocalizer.FetchFileRet localFileRet = FileLocalizer.fetchFile(properties, remainders[0]);
            if (localFileRet.didFetch) {
                properties.setProperty("pig.jars.relative.to.dfs", "true");
            }

            scriptState.setFileName(remainders[0]);

            if (embedded) {
                return runEmbeddedScript(pigContext, localFileRet.file.getPath(), engine);
            } else {
                SupportedScriptLang type = determineScriptType(localFileRet.file.getPath());
                if (type != null) {
                    return runEmbeddedScript(pigContext, localFileRet.file.getPath(),
                            type.name().toLowerCase());
                }
            }

            in = new BufferedReader(new FileReader(localFileRet.file));

            // run parameter substitution preprocessor first
            substFile = remainders[0] + ".substituted";
            pin = runParamPreprocessor(pigContext, in, substFile, debug || dryrun || checkScriptOnly);
            if (dryrun) {
                if (dryrun(substFile, pigContext)) {
                    log.info("Dry run completed. Substituted pig script is at " + substFile
                            + ". Expanded pig script is at " + remainders[0] + ".expanded");
                } else {
                    log.info("Dry run completed. Substituted pig script is at " + substFile);
                }
                return ReturnCode.SUCCESS;
            }

            logFileName = validateLogFile(logFileName, remainders[0]);
            pigContext.getProperties().setProperty("pig.logfile", logFileName);

            if (!debug) {
                new File(substFile).deleteOnExit();
            }

            // Set job name based on name of the script
            pigContext.getProperties().setProperty(PigContext.JOB_NAME,
                    "PigLatin:" + new File(remainders[0]).getName());

            scriptState.setScript(localFileRet.file);

            grunt = new LipstickGrunt(pin, pigContext);
            gruntCalled = true;

            if (checkScriptOnly) {
                grunt.checkScript(substFile);
                System.err.println(remainders[0] + " syntax OK");
                rc = ReturnCode.SUCCESS;
            } else {
                int results[] = grunt.exec();
                rc = getReturnCodeForStats(results);
            }
            return rc;
        }

        // Per Utkarsh and Chris invocation of jar file via pig depricated.
    } catch (ParseException e) {
        usage();
        rc = ReturnCode.PARSE_EXCEPTION;
        PigStatsUtil.setErrorMessage(e.getMessage());
    } catch (org.apache.pig.tools.parameters.ParseException e) {
        // usage();
        rc = ReturnCode.PARSE_EXCEPTION;
        PigStatsUtil.setErrorMessage(e.getMessage());
    } catch (IOException e) {
        if (e instanceof PigException) {
            PigException pe = (PigException) e;
            rc = (pe.retriable()) ? ReturnCode.RETRIABLE_EXCEPTION : ReturnCode.PIG_EXCEPTION;
            PigStatsUtil.setErrorMessage(pe.getMessage());
            PigStatsUtil.setErrorCode(pe.getErrorCode());
        } else {
            rc = ReturnCode.IO_EXCEPTION;
            PigStatsUtil.setErrorMessage(e.getMessage());
        }

        if (!gruntCalled) {
            LogUtils.writeLog(e, logFileName, log, verbose, "Error before Pig is launched");
        }
    } catch (Throwable e) {
        rc = ReturnCode.THROWABLE_EXCEPTION;
        PigStatsUtil.setErrorMessage(e.getMessage());
        if (!gruntCalled) {
            LogUtils.writeLog(e, logFileName, log, verbose, "Error before Pig is launched");
        }
    } finally {
        // clear temp files
        FileLocalizer.deleteTempFiles();
        // PerformanceTimerFactory.getPerfTimerFactory().dumpTimers();
    }

    return rc;
}

From source file:io.swagger.assert4j.maven.RunMojo.java

private File filterRecipe(File file) throws MavenFilteringException, MojoFailureException {
    if (!targetDirectory.exists()) {
        if (!targetDirectory.mkdirs()) {
            throw new MojoFailureException("Couldn't create target directory: " + targetDirectory);
        }/*from  w  w  w  .j  ava2 s.c o  m*/
    }

    Resource fileResource = new Resource();
    fileResource.setDirectory(recipeDirectory.getAbsolutePath());

    String filename = file.getAbsolutePath().substring(recipeDirectory.getAbsolutePath().length());

    fileResource.addInclude(filename);
    fileResource.setFiltering(true);

    MavenResourcesExecution resourcesExecution = new MavenResourcesExecution();
    resourcesExecution.setOutputDirectory(targetDirectory);
    resourcesExecution.setResources(Lists.newArrayList(fileResource));
    resourcesExecution.setOverwrite(true);
    resourcesExecution.setSupportMultiLineFiltering(true);
    resourcesExecution.setEncoding(Charset.defaultCharset().toString());

    if (properties != null && !properties.isEmpty()) {
        Properties props = new Properties();
        props.putAll(properties);
        getLog().debug("Adding additional properties: " + properties.toString());
        resourcesExecution.setAdditionalProperties(props);
    }

    resourcesExecution.setMavenProject(mavenProject);
    resourcesExecution.setMavenSession(mavenSession);
    resourcesExecution.setUseDefaultFilterWrappers(true);

    resourcesFiltering.filterResources(resourcesExecution);

    return new File(targetDirectory, filename);
}