Example usage for org.joda.time DateTime minusMinutes

List of usage examples for org.joda.time DateTime minusMinutes

Introduction

In this page you can find the example usage for org.joda.time DateTime minusMinutes.

Prototype

public DateTime minusMinutes(int minutes) 

Source Link

Document

Returns a copy of this datetime minus the specified number of minutes.

Usage

From source file:org.springframework.xd.dirt.rest.metrics.AggregateCountersController.java

License:Apache License

/**
 * Return a default value for the interval start if none has been provided.
 *//*from   w  w  w .ja  v a  2 s. co  m*/
private DateTime providedOrDefaultFromValue(DateTime from, DateTime to, AggregateCountResolution resolution) {
    if (from != null) {
        return from;
    }
    switch (resolution) {
    case minute:
        return to.minusMinutes(59);
    case hour:
        return to.minusHours(23);
    case day:
        return to.minusDays(6);
    case month:
        return to.minusMonths(11);
    case year:
        return to.minusYears(4);
    default:
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
}

From source file:org.wildfly.metrics.server.Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    final Server server = new Server();

    Undertow http = Undertow.builder().addHttpListener(4444, "localhost")
            .setHandler(path().addPrefixPath("/api/put", exchange -> {
                Map<String, Deque<String>> params = exchange.getQueryParameters();

                server.writeMetric(params.get("metric").getFirst(),
                        Long.valueOf(params.get("value").getFirst()));
            })/*from w w w  .  ja  v  a2s  . com*/

                    .addPrefixPath("/api/get", exchange -> {
                        Map<String, Deque<String>> params = exchange.getQueryParameters();

                        List<Long[]> values = server.readSlice(params.get("metric").getFirst(), () -> {
                            return new long[] { 0, System.currentTimeMillis() };
                        });

                        payload(exchange, params, values);

                    })

                    .addPrefixPath("/api/get15s", exchange -> {
                        Map<String, Deque<String>> params = exchange.getQueryParameters();

                        List<Long[]> values = server.readSlice(params.get("metric").getFirst(), () -> {
                            DateTime dt = new DateTime();
                            DateTime offset = dt.minusSeconds(15);
                            return new long[] { offset.getMillis(), System.currentTimeMillis() };
                        });

                        payload(exchange, params, values);
                    })

                    .addPrefixPath("/api/get30s", exchange -> {
                        Map<String, Deque<String>> params = exchange.getQueryParameters();

                        List<Long[]> values = server.readSlice(params.get("metric").getFirst(), () -> {
                            DateTime dt = new DateTime();
                            DateTime offset = dt.minusSeconds(30);
                            return new long[] { offset.getMillis(), System.currentTimeMillis() };
                        });

                        payload(exchange, params, values);
                    })

                    .addPrefixPath("/api/get1m", exchange -> {
                        Map<String, Deque<String>> params = exchange.getQueryParameters();

                        List<Long[]> values = server.readSlice(params.get("metric").getFirst(), () -> {
                            DateTime dt = new DateTime();
                            DateTime offset = dt.minusMinutes(1);
                            return new long[] { offset.getMillis(), System.currentTimeMillis() };
                        });

                        payload(exchange, params, values);
                    })

                    .addPrefixPath("/api/get1h", exchange -> {
                        Map<String, Deque<String>> params = exchange.getQueryParameters();

                        List<Long[]> values = server.readSlice(params.get("metric").getFirst(), () -> {
                            DateTime dt = new DateTime();
                            DateTime offset = dt.minusHours(1);
                            return new long[] { offset.getMillis(), System.currentTimeMillis() };
                        });

                        payload(exchange, params, values);
                    })

                    .addPrefixPath("/", exchange -> {
                        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                        exchange.getResponseSender().send("Metric Server");
                    }))
            .build();

    server.start();
    http.start();

    System.out.println("Press enter to exit ...");
    System.in.read();

    http.stop();
    server.stop();
}

From source file:proxi.model.DataFixer.java

License:Open Source License

private static DateTime paisCommentaryDateText2DateTime(Commentary commentary) {
    DateTime dt = new DateTime();
    String date = commentary.getDate().toLowerCase(); // .replaceAll(" - ",
    // " ").replaceAll(":",
    // " ");/*w w w.  j av  a2s . c  om*/
    if (date.contains("menos de")) {
        return dt;
    } else if (date.contains("minutos") || date.contains("minuto")) {
        String[] dateParts = date.split(" ");
        int minutes = Integer.parseInt(dateParts[1]);
        return dt.minusMinutes(minutes);
    } else if (date.contains("horas") || date.contains("hora")) {
        String[] dateParts = date.split(" ");
        int hours = Integer.parseInt(dateParts[1]);
        return dt.minusHours(hours);
    }
    return null;
}

From source file:singlejartest.Explorer30MinDoubleRepeat.java

License:Open Source License

public static void main(String[] args) throws Exception {
    // get the instance of the IClient interface
    final ITesterClient client = TesterFactory.getDefaultInstance();
    final ClimberProperties properties = new ClimberProperties();

    // set the listener that will receive system events
    client.setSystemListener(new ISystemListener() {
        @Override// w  w w.jav a 2s .c om
        public void onStart(long processId) {
            LOGGER.info("Strategy started: " + processId);
            try {
                strategyRunningSignal.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onStop(long processId) {
            LOGGER.info("Strategy stopped: " + processId);
            if (client.getStartedStrategies().size() == 0) {
                // System.exit(0);
                strategyRunningSignal.delete();
            }
        }

        @Override
        public void onConnect() {
            LOGGER.info("Connected");
        }

        @Override
        public void onDisconnect() {
            // tester doesn't disconnect
        }
    });

    if (args.length < 1) {
        LOGGER.error("One argument needed: name of config file");
        System.exit(1);
    }

    try {
        properties.load(new FileInputStream(args[0]));
    } catch (IOException e) {
        LOGGER.error("Can't open or can't read properties file " + args[0] + "...");
        System.exit(1);
    }

    properties.validate(LOGGER);

    LOGGER.info("Connecting...");
    // connect to the server using jnlp, user name and password
    // connection is needed for data downloading
    client.connect(jnlpUrl, properties.getProperty("username"), properties.getProperty("password"));

    // wait for it to connect
    int i = 10; // wait max ten seconds
    while (i > 0 && !client.isConnected()) {
        Thread.sleep(1000);
        i--;
    }
    if (!client.isConnected()) {
        LOGGER.error("Failed to connect Dukascopy servers");
        System.exit(1);
    }

    // set instruments that will be used in testing. To set different
    // timeframe per pair format is <pair>,<timeframe>;<pair>,<timeframe>...
    StringTokenizer st = new StringTokenizer(properties.getProperty("pairsToCheck"), ";");
    Set<Instrument> instruments = new HashSet<Instrument>();
    while (st.hasMoreTokens()) {
        String nextPair = st.nextToken();
        StringTokenizer st2 = new StringTokenizer(nextPair, ",");
        instruments.add(Instrument.fromString(st2.nextToken()));
    }

    LOGGER.info("Subscribing instruments...");
    client.setSubscribedInstruments(instruments);
    // setting initial deposit
    client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(),
            Double.parseDouble(properties.getProperty("initialdeposit", "50000.0")));
    client.setCacheDirectory(new File(properties.getProperty("cachedir")));

    // key idea is here: ignore config file and setup test interval
    // artificially to last two 30min intervals
    // round to last 30min ended
    DateTime roundedEnd = FXUtils.calcEndBar();
    DateTime startInterval = new DateTime(roundedEnd.minusMinutes(60));

    client.setDataInterval(DataLoadingMethod.ALL_TICKS, startInterval.getMillis(), roundedEnd.getMillis());
    int attempt = 0;
    requestedCallSignal = new File("requestedCall.bin");
    requestedCallSignal.createNewFile();
    // load data
    while (!requestedBarDone() && attempt < 20) {
        LOGGER.info("Downloading data");
        Future<?> future = client.downloadData(null);
        Thread.sleep(15000); // this timeout helped
        // wait for downloading to complete
        future.get();
        // start the strategy
        if (!strategyRunningSignal.exists()) {
            attempt++;
            LOGGER.info("Starting strategy, attempt " + attempt);
            client.startStrategy(new TwoTFStatsCollector(properties), new LoadingProgressListener() {
                @Override
                public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
                    LOGGER.info(information);
                }

                @Override
                public void loadingFinished(boolean allDataLoaded, long startTime, long endTime,
                        long currentTime) {
                }

                @Override
                public boolean stopJob() {
                    return false;
                }
            });
            Thread.sleep(30000);
        }
    }
    if (requestedCallSignal.exists()) {
        requestedCallSignal.delete();
        LOGGER.info("Unsuccessful run after " + attempt + " attempts");
    } else
        LOGGER.info("Successful run after " + attempt + " attempts");
    if (strategyRunningSignal.exists())
        strategyRunningSignal.delete();
    System.exit(0);
}

From source file:singlejartest.Explorer30MinRepeat.java

License:Open Source License

public static void main(String[] args) throws Exception {
    // get the instance of the IClient interface
    final ITesterClient client = TesterFactory.getDefaultInstance();
    final ClimberProperties properties = new ClimberProperties();
    // set the listener that will receive system events
    client.setSystemListener(new ISystemListener() {
        @Override/* www.  j  a  v a 2  s  .  co  m*/
        public void onStart(long processId) {
            LOGGER.info("Strategy started: " + processId);
        }

        @Override
        public void onStop(long processId) {
            LOGGER.info("Strategy stopped: " + processId);
            // TODO: find a way to run in Java repeadetly
            if (client.getStartedStrategies().size() == 0) {
                System.exit(0);
            }
        }

        @Override
        public void onConnect() {
            LOGGER.info("Connected");
        }

        @Override
        public void onDisconnect() {
            // tester doesn't disconnect
        }
    });

    if (args.length < 2) {
        LOGGER.error("Two arguments needed: name of config file and explorer class ID");
        System.exit(1);
    }

    try {
        properties.load(new FileInputStream(args[0]));
    } catch (IOException e) {
        LOGGER.error("Can't open or can't read properties file " + args[0] + "...");
        System.exit(1);
    }

    properties.validate(LOGGER);

    LOGGER.info("Connecting...");
    // connect to the server using jnlp, user name and password
    // connection is needed for data downloading
    client.connect(jnlpUrl, properties.getProperty("username"), properties.getProperty("password"));

    // wait for it to connect
    int i = 10; // wait max ten seconds
    while (i > 0 && !client.isConnected()) {
        Thread.sleep(1000);
        i--;
    }
    if (!client.isConnected()) {
        LOGGER.error("Failed to connect Dukascopy servers");
        System.exit(1);
    }

    // set instruments that will be used in testing
    StringTokenizer st = new StringTokenizer(properties.getProperty("pairsToCheck"), ";");
    Set<Instrument> instruments = new HashSet<Instrument>();
    while (st.hasMoreTokens()) {
        String nextPair = st.nextToken();
        instruments.add(Instrument.fromString(nextPair));
    }

    LOGGER.info("Subscribing instruments...");
    client.setSubscribedInstruments(instruments);
    // setting initial deposit
    client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(),
            Double.parseDouble(properties.getProperty("initialdeposit", "50000.0")));
    client.setCacheDirectory(new File(properties.getProperty("cachedir")));

    // String input = new String();
    // while (!input.equals("stop")) {
    // TODO: find a way to run repeatedly in Java !

    // key idea is here: ignore config file and setup test interval
    // artificially to last two 30min intervals
    // round to last 30min ended
    DateTime roundedEnd = FXUtils.calcEndBar();
    DateTime startInterval = new DateTime(roundedEnd.minusMinutes(60));

    // TODO: trying with just 30min and above...
    client.setDataInterval(DataLoadingMethod.ALL_TICKS, startInterval.getMillis(), roundedEnd.getMillis());
    // client.setDataInterval(Period.THIRTY_MINS, null, null,
    // startInterval.getMillis(), roundedEnd.getMillis());
    // load data
    LOGGER.info("Downloading data");
    Future<?> future = client.downloadData(null);
    // wait for downloading to complete
    Thread.sleep(15000); // this timeout helped
    future.get();
    // start the strategy
    LOGGER.info("Starting strategy");
    IStrategy strategyToRun = null;
    if (args[1].equals("mailer"))
        strategyToRun = new TwoTFStatsCollector(properties);
    else if (args[1].equals("ranges"))
        strategyToRun = new RangeExplorerComplex(properties);
    else {
        LOGGER.error("explorer class ID not valid. Valid values: [mailer, ranges]");
        System.exit(1);
    }
    client.startStrategy(strategyToRun, new LoadingProgressListener() {
        @Override
        public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
            LOGGER.info(information);
        }

        @Override
        public void loadingFinished(boolean allDataLoaded, long startTime, long endTime, long currentTime) {
        }

        @Override
        public boolean stopJob() {
            return false;
        }
    });
    // input =
    // System.console().readLine("Explorer TwoTFStatsCollector is running. Type \"stop\" to stop it: ");
    // }
    // now it's running
}

From source file:singlejartest.Explorer30or5MinRepeat.java

License:Open Source License

public static void main(String[] args) throws Exception {
    // get the instance of the IClient interface
    final ITesterClient client = TesterFactory.getDefaultInstance();
    final ClimberProperties properties = new ClimberProperties();
    // set the listener that will receive system events
    client.setSystemListener(new ISystemListener() {
        @Override/* w  w  w.j  a v a2s.c o  m*/
        public void onStart(long processId) {
            LOGGER.info("Strategy started: " + processId);
        }

        @Override
        public void onStop(long processId) {
            LOGGER.info("Strategy stopped: " + processId);
            // TODO: find a way to run in Java repeadetly
            if (client.getStartedStrategies().size() == 0) {
                System.exit(0);
            }
        }

        @Override
        public void onConnect() {
            LOGGER.info("Connected");
        }

        @Override
        public void onDisconnect() {
            // tester doesn't disconnect
        }
    });

    if (args.length < 2) {
        LOGGER.error("Two arguments needed: name of config file and explorer class ID");
        System.exit(1);
    }

    try {
        properties.load(new FileInputStream(args[0]));
    } catch (IOException e) {
        LOGGER.error("Can't open or can't read properties file " + args[0] + "...");
        System.exit(1);
    }

    properties.validate(LOGGER);

    LOGGER.info("Connecting...");
    // connect to the server using jnlp, user name and password
    // connection is needed for data downloading
    client.connect(jnlpUrl, properties.getProperty("username"), properties.getProperty("password"));

    // wait for it to connect
    int i = 10; // wait max ten seconds
    while (i > 0 && !client.isConnected()) {
        Thread.sleep(1000);
        i--;
    }
    if (!client.isConnected()) {
        LOGGER.error("Failed to connect Dukascopy servers");
        System.exit(1);
    }

    // set instruments that will be used in testing
    StringTokenizer st = new StringTokenizer(properties.getProperty("pairsToCheck"), ";");
    Set<Instrument> instruments = new HashSet<Instrument>();
    while (st.hasMoreTokens()) {
        String nextPair = st.nextToken();
        instruments.add(Instrument.fromString(nextPair));
    }

    LOGGER.info("Subscribing instruments...");
    client.setSubscribedInstruments(instruments);
    // setting initial deposit
    client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(),
            Double.parseDouble(properties.getProperty("initialdeposit", "50000.0")));
    client.setCacheDirectory(new File(properties.getProperty("cachedir")));

    // String input = new String();
    // while (!input.equals("stop")) {
    // TODO: find a way to run repeatedly in Java !

    // key idea is here: ignore config file and setup test interval
    // artificially to last two 30min intervals
    // round to last 30min ended
    DateTime roundedEnd = calcEndBar();
    DateTime startInterval = new DateTime(roundedEnd.minusMinutes(5));

    client.setDataInterval(Period.TICK, null, null, startInterval.getMillis(), roundedEnd.getMillis());
    // load data
    LOGGER.info("Downloading data");
    Future<?> future = client.downloadData(null);
    // wait for downloading to complete
    future.get();
    // start the strategy
    LOGGER.info("Starting strategy");
    IStrategy strategyToRun = null;
    if (args[1].equals("mailer"))
        strategyToRun = new TwoTFStatsCollector(properties);
    else if (args[1].equals("ranges"))
        strategyToRun = new RangeExplorerComplex(properties);
    else {
        LOGGER.error("explorer class ID not valid. Valid values: [mailer, ranges]");
        System.exit(1);
    }
    client.startStrategy(strategyToRun, new LoadingProgressListener() {
        @Override
        public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
            LOGGER.info(information);
        }

        @Override
        public void loadingFinished(boolean allDataLoaded, long startTime, long endTime, long currentTime) {
        }

        @Override
        public boolean stopJob() {
            return false;
        }
    });
    // input =
    // System.console().readLine("Explorer TwoTFStatsCollector is running. Type \"stop\" to stop it: ");
    // }
    // now it's running
}

From source file:singlejartest.Strategy30MinRepeat.java

License:Open Source License

public static void main(String[] args) throws Exception {
    // get the instance of the IClient interface
    final ITesterClient client = TesterFactory.getDefaultInstance();
    final Properties properties = new Properties();
    // set the listener that will receive system events
    client.setSystemListener(new ISystemListener() {
        @Override/* ww  w  .j a va2  s . c om*/
        public void onStart(long processId) {
            LOGGER.info("Strategy started: " + processId);
        }

        @Override
        public void onStop(long processId) {
            LOGGER.info("Strategy stopped: " + processId);
            // TODO: find a way to run in Java repeadetly
            if (client.getStartedStrategies().size() == 0) {
                System.exit(0);
            }
        }

        @Override
        public void onConnect() {
            LOGGER.info("Connected");
        }

        @Override
        public void onDisconnect() {
            // tester doesn't disconnect
        }
    });

    if (args.length < 2) {
        LOGGER.error("Two arguments needed: name of config file and explorer class ID");
        System.exit(1);
    }

    try {
        properties.load(new FileInputStream(args[0]));
    } catch (IOException e) {
        LOGGER.error("Can't open or can't read properties file " + args[0] + "...");
        System.exit(1);
    }

    LOGGER.info("Connecting...");
    // connect to the server using jnlp, user name and password
    // connection is needed for data downloading
    client.connect(jnlpUrl, properties.getProperty("username"), properties.getProperty("password"));

    // wait for it to connect
    int i = 10; // wait max ten seconds
    while (i > 0 && !client.isConnected()) {
        Thread.sleep(1000);
        i--;
    }
    if (!client.isConnected()) {
        LOGGER.error("Failed to connect Dukascopy servers");
        System.exit(1);
    }

    // set instruments that will be used in testing
    StringTokenizer st = new StringTokenizer(properties.getProperty("pairsToCheck"), ";");
    Set<Instrument> instruments = new HashSet<Instrument>();
    while (st.hasMoreTokens()) {
        String nextPair = st.nextToken();
        instruments.add(Instrument.fromString(nextPair));
    }

    LOGGER.info("Subscribing instruments...");
    client.setSubscribedInstruments(instruments);
    // setting initial deposit
    client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(),
            Double.parseDouble(properties.getProperty("initialdeposit", "50000.0")));
    client.setCacheDirectory(new File(properties.getProperty("cachedir")));

    // key idea is here: ignore config file and setup test interval
    // artificially to last two 30min intervals
    // round to last 30min ended
    DateTime roundedEnd = calcEndBar();
    DateTime startInterval = new DateTime(roundedEnd.minusMinutes(30));

    client.setDataInterval(Period.TICK, null, null, startInterval.getMillis(), roundedEnd.getMillis());
    // load data
    LOGGER.info("Downloading data");
    Future<?> future = client.downloadData(null);
    // wait for downloading to complete
    future.get();
    // start the strategy
    LOGGER.info("Starting strategy");
    IStrategy strategyToRun = new CalledStrategy();
    client.startStrategy(strategyToRun, new LoadingProgressListener() {
        @Override
        public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
            LOGGER.info(information);
        }

        @Override
        public void loadingFinished(boolean allDataLoaded, long startTime, long endTime, long currentTime) {
        }

        @Override
        public boolean stopJob() {
            return false;
        }
    });
    // now it's running
}