Example usage for java.util Properties clear

List of usage examples for java.util Properties clear

Introduction

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

Prototype

@Override
    public synchronized void clear() 

Source Link

Usage

From source file:org.jberet.support.io.OsCommandBatchletTest.java

/**
 * Runs job {@value #jobName}, where {@link OsCommandBatchlet} executes
 * simple OS commands.//from   www .j a va 2s . c o m
 *
 * @throws Exception upon errors
 */
@Test
public void simpleCommands() throws Exception {
    // run echo command, and should complete successfully with process exit code 0.
    final Properties jobParams = new Properties();
    jobParams.setProperty("commandLine", "echo This is echo from osCommandBatchlet");
    runCommand(jobParams, BatchStatus.COMPLETED, String.valueOf(0));

    // run echo command, passing the command as comma-separated list,
    // and setting custom working directory and timeout.
    // The command should complete successfully with process exit code 0.
    jobParams.clear();
    jobParams.setProperty("commandArray", "echo, abc, xyz, 123");
    jobParams.setProperty("workingDir", System.getProperty("java.io.tmpdir"));
    jobParams.setProperty("timeoutSeconds", String.valueOf(600));
    runCommand(jobParams, BatchStatus.COMPLETED, String.valueOf(0));

    // run cd command, setting the process exit code for successful completion to 999999.
    // The job execution should fail, since the process exit code 0 does not match 999999.
    jobParams.clear();
    jobParams.setProperty("commandLine", "cd ..");
    jobParams.setProperty("commandOkExitValues", String.valueOf(999999));
    runCommand(jobParams, BatchStatus.FAILED, String.valueOf(0));
}

From source file:org.latticesoft.util.common.FileUtil.java

/**
 * Loads a map with a key value pairs from a properties file.
 * Note that the file name need not have an extension of
 * ".properties"/*from w  ww .ja  va2 s  .  c  o  m*/
 * @param filename the name of the file to load
 * @param map the map to be loaded.
 * @return the same map file passed in or a new map
 * if the parameter passed in is null.
 */
public static Map loadMap(String filename, Map map) {
    InputStream is = null;
    Properties p = new Properties();
    Map retVal = map;
    if (map == null) {
        retVal = new TreeMap();
    }
    File[] files = FileUtil.listFilesAsArray(filename);
    if (files == null)
        return map;

    for (int i = 0; i < files.length; i++) {
        try {
            is = new FileInputStream(files[i]);
            p.load(is);
            retVal.putAll(p);
            p.clear();
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        } finally {
            try {
                is.close();
            } catch (Exception e) {
            }
            is = null;
        }
    }
    return retVal;
}

From source file:org.latticesoft.util.common.FileUtil.java

/**
 * Loads a map from a inputstream//from ww  w. j  ava  2s.  c o  m
 * @param is the inputstream
 * @param map the map to load to
 * @param closeStream close the stream after loading
 * @return the same map after loading
 */
public static Map loadMap(InputStream is, Map map, boolean closeStream) {
    Properties p = new Properties();
    Map retVal = map;
    if (map == null) {
        retVal = new TreeMap();
    }
    try {
        p.load(is);
        retVal.putAll(p);
        p.clear();
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    } finally {
        if (closeStream) {
            try {
                is.close();
            } catch (Exception e) {
            }
        }
        is = null;
    }
    return retVal;
}

From source file:org.latticesoft.util.container.SystemProperties.java

private void init(String conf) {
    if (log.isDebugEnabled()) {
        log.debug("Initialization");
    }//w w w.j  a  v  a2  s . c  o  m

    if (conf == null) {
        if (log.isDebugEnabled()) {
            log.debug("Null config directory cannot initialize");
        }
        return;
    }
    if (log.isDebugEnabled()) {
        log.debug("Conf:" + conf);
    }
    char c = conf.charAt(conf.length() - 1);
    if (c != '/' && c != '\\') {
        conf += "/";
    }
    File f = new File(conf);
    if (!f.isDirectory()) {
        if (log.isDebugEnabled()) {
            log.debug("Location is not a directory");
        }
        return;
    }
    String[] filelist = f.list(new FileExtensionFilter("properties"));
    for (int i = 0; i < filelist.length; i++) {
        InputStream is = null;
        Properties p = new Properties();
        try {
            is = new FileInputStream(conf + filelist[i]);
            p.load(is);
            this.map.putAll(p);
            Iterator iter = p.keySet().iterator();
            while (iter.hasNext()) {
                Object o = iter.next();
                this.source.put(o, filelist[i]);
            }
            p.clear();
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("Exception caught", e);
            }
        } finally {
            try {
                is.close();
            } catch (Exception e) {
            }
            is = null;
        }
    }
    String classname = this.getClass().getName();
    SystemProperties.START = (String) this.map.get(classname + ".START");
    SystemProperties.END = (String) this.map.get(classname + ".END");
    if (SystemProperties.START == null || SystemProperties.END == null || SystemProperties.END.trim().equals("")
            || SystemProperties.START.trim().equals("")) {
        SystemProperties.START = "${";
        SystemProperties.END = "}";
    }
}

From source file:org.marketcetera.strategy.LanguageTestBase.java

/**
 * Tests what happens if a runtime error occurs in the strategy script.
 *
 * @throws Exception if an error occurs//from w  ww  . ja va  2  s  . com
 */
@Test
public void runtimeError() throws Exception {
    // runtime error in onStart
    final StrategyCoordinates strategy = getStrategyCompiles();
    final Properties parameters = new Properties();
    parameters.setProperty("shouldFailOnStart", "true");
    final ModuleURN strategyURN = moduleManager.createModule(StrategyModuleFactory.PROVIDER_URN, null,
            strategy.getName(), getLanguage(), strategy.getFile(), parameters, null, null);
    // failed "onStart" means that the strategy is in error status and will not receive any data
    new ExpectedFailure<ModuleException>(FAILED_TO_START) {
        @Override
        protected void run() throws Exception {
            moduleManager.start(strategyURN);
        }
    };
    // "onStart" has completed, but verify that the last statement in the strategy was never executed
    verifyPropertyNull("onStart");
    // verify the status of the strategy
    verifyStrategyStatus(strategyURN, FAILED);
    setPropertiesToNull();
    parameters.clear();
    AbstractRunningStrategy.setProperty("shouldFailOnStop", "true");
    // runtime error in onStop
    ModuleURN strategyURN2 = createStrategy(strategy.getName(), getLanguage(), strategy.getFile(), parameters,
            null, null);
    doSuccessfulStartTest(strategyURN2);
    stopStrategy(strategyURN2);
    AbstractRunningStrategy.setProperty("shouldFailOnStop", null);
    // runtime error in each callback
    doCallbackFailsTest("shouldFailOnAsk",
            new String[] { "onBid", "onCancel", "onExecutionReport", "onTrade", "onOther", "onDividend" });
    doCallbackFailsTest("shouldFailOnBid",
            new String[] { "onAsk", "onCancel", "onExecutionReport", "onTrade", "onOther", "onDividend" });
    doCallbackFailsTest("shouldFailOnExecutionReport",
            new String[] { "onAsk", "onBid", "onCancel", "onTrade", "onOther", "onDividend" });
    doCallbackFailsTest("shouldFailOnTrade",
            new String[] { "onAsk", "onBid", "onCancel", "onExecutionReport", "onOther", "onDividend" });
    doCallbackFailsTest("shouldFailOnOther",
            new String[] { "onAsk", "onBid", "onCancel", "onExecutionReport", "onTrade", "onDividend" });
    doCallbackFailsTest("shouldFailOnDividend",
            new String[] { "onAsk", "onBid", "onCancel", "onExecutionReport", "onTrade", "onOther" });
}

From source file:org.marketcetera.strategy.LanguageTestBase.java

/**
 * Tests a strategy's ability to suggest trades.
 *
 * @throws Exception if an error occurs//from   ww w.  jav  a2  s .  co  m
 */
@Test
public void suggestions() throws Exception {
    Properties parameters = new Properties();
    // null suggestion
    parameters.setProperty("orderShouldBeNull", "true");
    doSuggestionTest(parameters, new OrderSingleSuggestion[0]);
    // null score
    parameters.clear();
    doSuggestionTest(parameters, new OrderSingleSuggestion[0]);
    // null identifier
    parameters.setProperty("score", "1");
    doSuggestionTest(parameters, new OrderSingleSuggestion[0]);
    // zero length identifier
    parameters.setProperty("identifier", "");
    doSuggestionTest(parameters, new OrderSingleSuggestion[0]);
    // first complete suggestion
    parameters.setProperty("identifier", "some identifier");
    OrderSingleSuggestion expectedSuggestion = Factory.getInstance().createOrderSingleSuggestion();
    expectedSuggestion.setScore(new BigDecimal("1"));
    expectedSuggestion.setIdentifier("some identifier");
    OrderSingle suggestedOrder = Factory.getInstance().createOrderSingle();
    expectedSuggestion.setOrder(suggestedOrder);
    doSuggestionTest(parameters, new OrderSingleSuggestion[] { expectedSuggestion });
    // add an account
    parameters.setProperty("account", "some account");
    suggestedOrder.setAccount("some account");
    expectedSuggestion.setOrder(suggestedOrder);
    doSuggestionTest(parameters, new OrderSingleSuggestion[] { expectedSuggestion });
    // add order type
    parameters.setProperty("orderType", OrderType.Market.name());
    suggestedOrder.setOrderType(OrderType.Market);
    expectedSuggestion.setOrder(suggestedOrder);
    doSuggestionTest(parameters, new OrderSingleSuggestion[] { expectedSuggestion });
    // add price
    parameters.setProperty("price", "100.23");
    suggestedOrder.setPrice(new BigDecimal("100.23"));
    expectedSuggestion.setOrder(suggestedOrder);
    doSuggestionTest(parameters, new OrderSingleSuggestion[] { expectedSuggestion });
    // add quantity
    parameters.setProperty("quantity", "10000");
    suggestedOrder.setQuantity(new BigDecimal("10000"));
    expectedSuggestion.setOrder(suggestedOrder);
    doSuggestionTest(parameters, new OrderSingleSuggestion[] { expectedSuggestion });
    // add side
    parameters.setProperty("side", Side.Buy.name());
    suggestedOrder.setSide(Side.Buy);
    expectedSuggestion.setOrder(suggestedOrder);
    doSuggestionTest(parameters, new OrderSingleSuggestion[] { expectedSuggestion });
    // add symbol
    parameters.setProperty("symbol", "METC");
    suggestedOrder.setInstrument(new Equity("METC"));
    expectedSuggestion.setOrder(suggestedOrder);
    doSuggestionTest(parameters, new OrderSingleSuggestion[] { expectedSuggestion });
}

From source file:org.marketcetera.strategy.LanguageTestBase.java

/**
 * Tests a strategy's ability to send <code>FIX</code> messages.
 *
 * @throws Exception if an error occurs//  w  ww  .  j av a 2s.  com
 */
@Test
public void sendMessages() throws Exception {
    Properties parameters = new Properties();
    Date messageDate = new Date();
    parameters.setProperty("date", Long.toString(messageDate.getTime()));
    // null message
    parameters.setProperty("nullMessage", "true");
    doMessageTest(parameters, new FIXOrder[0]);
    // null broker
    parameters.clear();
    parameters.setProperty("date", Long.toString(messageDate.getTime()));
    parameters.setProperty("nullBroker", "true");
    doMessageTest(parameters, new FIXOrder[0]);
    // send a valid message
    parameters.clear();
    parameters.setProperty("date", Long.toString(messageDate.getTime()));
    Message msg = FIXVersion.FIX_SYSTEM.getMessageFactory().newBasicOrder();
    msg.setField(new TransactTime(messageDate));
    doMessageTest(parameters,
            new FIXOrder[] { Factory.getInstance().createOrder(msg, new BrokerID("some-broker")) });
}

From source file:org.marketcetera.strategy.LanguageTestBase.java

/**
 * Tests {@link AbstractRunningStrategy#getOptionPositionsAsOf(Date, String...)}. 
 *
 * @throws Exception if an unexpected error occurs
 *///w ww  .  j a  v  a  2  s  .  c  om
@Test
public void optionPositionsAsOf() throws Exception {
    MockClient client = new MockClient();
    Option validOption1 = null;
    Option validOption2 = null;
    for (Instrument instrument : positions.keySet()) {
        if (instrument instanceof Option && validOption1 == null) {
            validOption1 = (Option) instrument;
        } else {
            if (instrument instanceof Option && validOption2 == null) {
                validOption2 = (Option) instrument;
            }
        }
    }
    assertNotNull(validOption1);
    assertNotNull(validOption2);
    Position position1 = positions.get(validOption1);
    Position position2 = positions.get(validOption2);
    assertNotNull(position1);
    assertNotNull(position2);
    String invalidSymbol = "there-is-no-position-for-this-symbol-" + System.nanoTime();
    Option invalidOption = new Option(invalidSymbol, DateUtils.dateToString(new Date(), DateUtils.DAYS),
            EventTestBase.generateDecimalValue(), OptionType.Call);
    assertFalse(positions.containsKey(invalidOption));
    // null option roots
    doOptionPositionsAsOfTest(null, new Date(), null, null);
    // empty option roots
    doOptionPositionsAsOfTest(new String[0], new Date(), null, null);
    String[] optionRoots = new String[] { validOption1.getSymbol(), invalidOption.getSymbol(), null };
    Date date = new Date();
    // a mix of valid and invalid
    doOptionPositionsAsOfTest(optionRoots, date, null, client.getOptionPositionsAsOf(date, optionRoots));
    // null date
    doOptionPositionsAsOfTest(new String[] { validOption1.getSymbol() }, null, null, null);
    optionRoots = new String[] { invalidOption.getSymbol() };
    date = new Date();
    // option doesn't exist
    doOptionPositionsAsOfTest(optionRoots, date, null, client.getOptionPositionsAsOf(date, optionRoots));
    // call fails
    MockClient.getPositionFails = true;
    doOptionPositionsAsOfTest(new String[] { validOption1.getSymbol() }, new Date(), null, null);
    MockClient.getPositionFails = false;
    // date in the past (before position begins)
    optionRoots = new String[] { validOption1.getSymbol(), validOption2.getSymbol() };
    Interval<BigDecimal> openingBalance1 = position1.getPositionView().get(0);
    Interval<BigDecimal> openingBalance2 = position2.getPositionView().get(0);
    date = new Date(Math.min(openingBalance1.getDate().getTime(), openingBalance2.getDate().getTime()) - 1000); // 1s before the open of the position
    doOptionPositionsAsOfTest(optionRoots, date, null, client.getOptionPositionsAsOf(date, optionRoots));
    // date in the past (after position begins)
    List<Interval<BigDecimal>> view = position1.getPositionView();
    int median = view.size() / 2;
    assertTrue("Position " + position1 + " contains no data!", median > 0);
    Interval<BigDecimal> dataPoint = position1.getPositionView().get(median);
    date = dataPoint.getDate();
    assertTrue(date.getTime() < System.currentTimeMillis());
    // found a date somewhere in the middle of the position and earlier than today
    doOptionPositionsAsOfTest(optionRoots, date, null, client.getOptionPositionsAsOf(date, optionRoots));
    // date exactly now
    date = new Date();
    doOptionPositionsAsOfTest(optionRoots, date, null, client.getOptionPositionsAsOf(date, optionRoots));
    // pick a data point two weeks into the future
    date = new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 14));
    doOptionPositionsAsOfTest(optionRoots, date, null, client.getOptionPositionsAsOf(date, optionRoots));
    // do a pair of special tests that need special handling
    Properties parameters = new Properties();
    parameters.setProperty("nullOptionRoot", "true");
    doOptionPositionsAsOfTest(new String[] { validOption1.getSymbol() }, date, parameters, null);
    parameters.clear();
    parameters.setProperty("emptyOptionRoot", "true");
    doOptionPositionsAsOfTest(new String[] { validOption1.getSymbol() }, date, parameters, null);
}

From source file:org.marketcetera.strategy.StrategyTestBase.java

/**
 * Sets the values in the common strategy storage area for some well-known testing keys to null.
 *//* ww w .ja va 2 s.  c om*/
protected void setPropertiesToNull() {
    Properties properties = AbstractRunningStrategy.getProperties();
    properties.clear();
    verifyNullProperties();
}

From source file:org.mili.core.templating.MockFactory.java

/**
 * Prepare.//from  w  w w  . j  a va2s.c  o m
 *
 * @throws Exception the exception
 */
public static void prepare() throws Exception {
    FileUtils.deleteDirectory(DIR);
    DIR.mkdirs();
    FileUtils.writeStringToFile(FILE_TEMPLATE_WITH_ONE, MockFactory.getTemplateWithOne());
    FileUtils.writeStringToFile(FILE_OTHER_TEMPLATE_WITH_ONE, MockFactory.getOtherTemplateWithOne());
    FileUtils.writeStringToFile(FILE_TEMPLATE_WITH_ONE_INNER, MockFactory.getTemplateWithInner());
    FileUtils.writeStringToFile(FILE_DEFECTEND_TEMPLATE_WITH_ONE, MockFactory.getDefectEndTemplateWithOne());
    FileUtils.writeStringToFile(FILE_DEFECTEND_TEMPLATE_WITH_ONE, MockFactory.getDefectEndTemplateWithOne());
    FileUtils.writeStringToFile(FILE_DEFECTEND_TEMPLATE_WITH_ONE_INNER,
            MockFactory.getDefectEndTemplateWithOneInner());
    FileUtils.writeStringToFile(FILE_DEFECTCONTENT_TEMPLATE_WITH_ONE_INNER,
            MockFactory.getDefectContentTemplateWithOneInner());
    // default
    Properties properties = new Properties();
    properties.put("key-with-value", "a");
    properties.put("key-with-empty-value", "");
    properties.put("one-more", "b");
    OutputStream os = new FileOutputStream(FILE_DEFAULT_COMPONENT_SHEET);
    properties.store(os, "TEST");
    os.close();
    // comp 1
    properties.clear();
    properties.put("key-with-value", "c");
    properties.put("key-with-empty-value", "");
    os = new FileOutputStream(FILE_COMPONENT_SHEET);
    properties.store(os, "TEST");
    os.close();
}