Example usage for org.joda.time.format PeriodFormat getDefault

List of usage examples for org.joda.time.format PeriodFormat getDefault

Introduction

In this page you can find the example usage for org.joda.time.format PeriodFormat getDefault.

Prototype

public static PeriodFormatter getDefault() 

Source Link

Document

Gets the default formatter that outputs words in English.

Usage

From source file:com.dataartisans.flink.dataflow.translation.wrappers.streaming.FlinkAbstractParDoWrapper.java

License:Apache License

protected void checkTimestamp(WindowedValue<IN> ref, Instant timestamp) {
    if (timestamp.isBefore(ref.getTimestamp().minus(doFn.getAllowedTimestampSkew()))) {
        throw new IllegalArgumentException(String.format(
                "Cannot output with timestamp %s. Output timestamps must be no earlier than the "
                        + "timestamp of the current input (%s) minus the allowed skew (%s). See the "
                        + "DoFn#getAllowedTimestmapSkew() Javadoc for details on changing the allowed skew.",
                timestamp, ref.getTimestamp(),
                PeriodFormat.getDefault().print(doFn.getAllowedTimestampSkew().toPeriod())));
    }//from ww  w  .  ja  v a  2 s.  c  om
}

From source file:com.github.rinde.gpem17.eval.Evaluate.java

License:Apache License

public static ExperimentResults execute(Iterable<GPProgram<GpGlobal>> programs, boolean realtime,
        FileProvider.Builder scenarioFiles, File resDir, boolean createTimeStampedResDir,
        @Nullable Function<Scenario, Scenario> scenarioConverter, boolean createTmpFiles, ReauctOpt reauctOpt,
        Gendreau06ObjectiveFunction objFuncUsedAtRuntime, RpOpt routePlanner, boolean enableTimeMeasurements,
        boolean addOptaPlannerMAS, long heuristicComputationDelay, String... expArgs) {
    checkArgument(realtime ^ scenarioConverter != null);
    final long startTime = System.currentTimeMillis();

    if (createTimeStampedResDir) {
        resDir = createExperimentDir(resDir);
    } else {/*  ww  w  . j a  va  2 s  .co  m*/
        resDir.mkdirs();
    }

    boolean evolution = scenarioConverter != null;

    ResultWriter rw = new VanLonHolvoetResultWriter(resDir, GPEM17.OBJ_FUNC,
            scenarioFiles.build().get().iterator().next().getParent().toString(), realtime, true,
            createTmpFiles, evolution);
    Experiment.Builder exp = Experiment.builder().addScenarios(scenarioFiles).showGui(GPEM17.gui())
            .showGui(false)
            .usePostProcessor(new GpemPostProcessor(GPEM17.OBJ_FUNC,
                    evolution ? FailureStrategy.INCLUDE : FailureStrategy.RETRY, false))
            .computeLocal().withRandomSeed(123).repeat(3)
            // SEED_REPS,REPS,SCENARIO,CONFIG
            .withOrdering(SimulationProperty.SEED_REPS, SimulationProperty.REPS, SimulationProperty.SCENARIO,
                    SimulationProperty.CONFIG)

            .addResultListener(rw);

    if (!realtime) {
        exp.addResultListener(new SimRuntimeLogger(resDir));
    }
    if (realtime) {
        exp.setScenarioReader(ScenarioIO.readerAdapter(ScenarioConverter.TO_ONLINE_REALTIME_250))
                .withWarmup(30000).addResultListener(new CommandLineProgress(System.out))
                .withThreads((int) Math.floor((Runtime.getRuntime().availableProcessors() - 1) / 2d));
    } else if (scenarioConverter == null) {
        exp.setScenarioReader(ScenarioIO.readerAdapter(ScenarioConverter.TO_ONLINE_SIMULATED_250))
                .addResultListener(new CommandLineProgress(System.out));
    } else {
        exp.setScenarioReader(ScenarioIO.readerAdapter(scenarioConverter));
    }

    if (addOptaPlannerMAS) {
        exp.addConfiguration(createOptaPlanner(enableTimeMeasurements));
    }

    int counter = 0;
    StringBuilder sb = new StringBuilder();
    for (GPProgram<GpGlobal> prog : programs) {
        String progId = "c" + counter++;
        sb.append(progId).append(" = ").append(prog.getId()).append(System.lineSeparator());

        if (realtime) {
            exp.addConfiguration(GPEM17.createRtConfig(prog, progId, reauctOpt, objFuncUsedAtRuntime,
                    routePlanner, enableTimeMeasurements, heuristicComputationDelay));
        } else {
            exp.addConfiguration(GPEM17.createStConfig(prog, progId, reauctOpt, objFuncUsedAtRuntime,
                    enableTimeMeasurements));
        }
    }

    try {
        Files.write(sb, new File(rw.getExperimentDirectory(), "configs.txt"), Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    final Optional<ExperimentResults> results = exp.perform(System.out, expArgs);
    final long duration = System.currentTimeMillis() - startTime;
    if (!results.isPresent()) {
        return null;
    }

    final Duration dur = new Duration(startTime, System.currentTimeMillis());
    System.out.println("Done, computed " + results.get().getResults().size() + " simulations in "
            + duration / 1000d + "s (" + PeriodFormat.getDefault().print(dur.toPeriod()) + ")");
    return results.get();
}

From source file:com.github.rinde.gpem17.eval.SimRuntimeLogger.java

License:Apache License

void write() {
    lastWrite = System.currentTimeMillis();
    StringBuilder sb = new StringBuilder();
    String timestamp = ISODateTimeFormat.dateHourMinuteSecond().print(lastWrite);

    long sum = 0;
    double[] arr = new double[receivedResults.size()];
    for (int i = 0; i < receivedResults.size(); i++) {
        SimResult info = (SimResult) receivedResults.get(i).getResultObject();
        sum += info.getStats().computationTime;
        arr[i] = info.getStats().computationTime;
    }/*w  w  w .j a v  a2  s  .c o m*/
    double mean = sum / receivedResults.size();
    long sd = DoubleMath.roundToLong(new StandardDeviation().evaluate(arr, mean), RoundingMode.HALF_DOWN);
    long longMean = DoubleMath.roundToLong(mean, RoundingMode.HALF_DOWN);

    sb.append(timestamp).append(",").append(receivedSims).append("/").append(totalSims).append(", Received ")
            .append(receivedResults.size()).append(" results in last minute, avg comp time,")
            .append(PeriodFormat.getDefault().print(new Period(longMean))).append(", standard deviation,")
            .append(PeriodFormat.getDefault().print(new Period(sd))).append(System.lineSeparator());
    try {
        Files.append(sb.toString(), progressFile, Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    receivedResults.clear();
}

From source file:com.github.rinde.gpem17.evo.StatsLogger.java

License:Apache License

public void finalStatistics(final EvolutionState state, final int result) {
    super.finalStatistics(state, result);

    // convert to ms duration
    final Duration dur = new Duration(startTime, System.nanoTime()).dividedBy(1000000L);

    System.out.println("End of evolutionary run.");
    System.out.println("Total runtime: " + PeriodFormat.getDefault().print(dur.toPeriod()));

    File firstGenDir = new File(experimentDirectory, "/generation0");
    File lastGenDir = new File(experimentDirectory, "/generation" + state.generation);

    while (lastGenDir.listFiles().length != firstGenDir.listFiles().length) {
        System.out.println("Waiting for all results to be written to disk.");
        try {/*w w w  . j  ava2  s. c om*/
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
    System.out.println("Done.");

}

From source file:com.github.rinde.rinsim.experiment.CommandLineProgress.java

License:Apache License

@Override
public void receive(SimulationResult result) {
    if (result.getResultObject() instanceof FailureStrategy) {
        failures++;/*from   ww w.j  av  a  2 s.com*/
    } else {
        received++;
    }
    final Duration dur = new Duration(startTime, System.currentTimeMillis());
    printStream.println(Joiner.on("").join(received, SLASH, total, " (failures: ", failures, ", duration: ",
            PeriodFormat.getDefault().print(dur.toPeriod()), ", memory free/total/max (M): ", memorySummary(),
            ")"));
}

From source file:com.github.rinde.rinsim.experiment.CommandLineProgress.java

License:Apache License

@Override
public void doneComputing(ExperimentResults results) {
    final Duration dur = new Duration(startTime, System.currentTimeMillis());
    printStream.println("Computing done, duration: " + PeriodFormat.getDefault().print(dur.toPeriod()) + ".");
    printMemorySummary(printStream);//  w  w  w. j a va  2  s  . c  om
}

From source file:com.indeed.imhotep.iql.IQLQuery.java

License:Apache License

/**
 * Throws UncheckedTimeoutException if current time is past the provided timeout timestamp.
 * @param timeoutTS timestamp of when the query times out in milliseconds
 *///from www.j  a v a  2  s .  c  om
public void checkTimeout(long timeoutTS) {
    if (System.currentTimeMillis() > timeoutTS) {
        throw new UncheckedTimeoutException("The query took longer than the allowed timeout of "
                + executionTimeout.toString(PeriodFormat.getDefault()));
    }
}

From source file:com.mirth.connect.server.util.LoginRequirementsChecker.java

License:Open Source License

public String getPrintableLockoutPeriod() {
    return PeriodFormat.getDefault().print(Period.hours(passwordRequirements.getLockoutPeriod()));
}

From source file:com.nesscomputing.quartz.QuartzJobBinder.java

License:Apache License

private String printDuration(final Duration duration) {
    return PeriodFormat.getDefault().print(duration.toPeriod());
}

From source file:com.predic8.membrane.core.interceptor.apimanagement.rateLimiter.AMRateLimiter.java

License:Apache License

public void setResponseToServiceUnavailable(Exchange exc, PolicyRateLimit prl)
        throws UnsupportedEncodingException {
    Header hd = new Header();
    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC()
            .withLocale(Locale.US);
    hd.add("Date", dateFormatter.print(DateTime.now()));
    hd.add("X-LimitDuration", PeriodFormat.getDefault().print(prl.getInterval().toPeriod()));
    hd.add("X-LimitRequests", Integer.toString(prl.getRequests()));
    String ip = exc.getRemoteAddrIp();
    DateTime availableAgainDateTime = prl.getNextCleanup();
    hd.add("X-LimitReset", Long.toString(availableAgainDateTime.getMillis()));

    /*StringBuilder bodyString = new StringBuilder();
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    bodyString.append(ip).append(" exceeded the rate limit of ").append(prl.getRequests())
        .append(" requests per ")//  w w w  . ja va 2 s.  co m
        .append(PeriodFormat.getDefault().print(prl.getInterval().toPeriod()))
        .append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime));*/

    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen = null;
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", 429);
        jgen.writeObjectField("Message",
                "The rate limit of " + prl.getRequests() + " requests in "
                        + prl.getInterval().getStandardSeconds()
                        + " seconds is exceeded. The next requests can be made at "
                        + dtFormatter.print(availableAgainDateTime));
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException ignored) {
    }

    Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd)
            .contentType("application/json").body(os.toByteArray()).build();
    exc.setResponse(resp);
}