Example usage for org.joda.time DateTime toString

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

Introduction

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

Prototype

@ToString
public String toString() 

Source Link

Document

Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ).

Usage

From source file:eu.interedition.web.metadata.DublinCoreMetadata.java

License:Apache License

public DublinCoreMetadata(DateTime dateTime) {
    this.created = dateTime;
    this.updated = dateTime;
    this.date = dateTime.toString();
}

From source file:eu.itesla_project.computation.mpi.CsvMpiStatistics.java

License:Mozilla Public License

@Override
public void logTaskStart(int taskId, int jobId, int taskIndex, DateTime startTime, int slaveRank,
        int slaveThread, long inputMessageSize) {
    try {//from w  w  w.  ja  v  a 2s . com
        internalWriter.write(TASK_START_KEY);
        internalWriter.write(CSV_SEPARATOR);
        internalWriter.write(Integer.toString(taskId));
        internalWriter.write(CSV_SEPARATOR);
        internalWriter.write(Integer.toString(jobId));
        internalWriter.write(CSV_SEPARATOR);
        internalWriter.write(Integer.toString(taskIndex));
        internalWriter.write(CSV_SEPARATOR);
        internalWriter.write(startTime.toString());
        internalWriter.write(CSV_SEPARATOR);
        internalWriter.write(Integer.toString(slaveRank));
        internalWriter.write(CSV_SEPARATOR);
        internalWriter.write(Integer.toString(slaveThread));
        internalWriter.write(CSV_SEPARATOR);
        internalWriter.write(Long.toString(inputMessageSize));
        internalWriter.newLine();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.itesla_project.modules.histo.tools.HistoDbPrintAttributesTool.java

License:Mozilla Public License

private static void format(InputStream is, boolean zipped) throws IOException {
    Table table;//from  w ww.  j av a 2 s. com
    CsvPreference prefs = new CsvPreference.Builder('"', ',', "\r\n").build();
    try (ICsvListReader reader = new CsvListReader(createReader(is, zipped), prefs)) {
        String[] header = reader.getHeader(true);
        table = new Table(header.length, BorderStyle.CLASSIC_WIDE);
        for (String cell : header) {
            table.addCell(cell);
        }
        List<String> row;
        while ((row = reader.read()) != null) {
            for (int i = 0; i < row.size(); i++) {
                String cell = row.get(i);
                if (header[i].equals(HistoDbMetaAttributeId.datetime.toString())) {
                    DateTime datetime = new DateTime(Long.parseLong(cell) * 1000L);
                    table.addCell(datetime.toString());
                } else {
                    table.addCell(cell);
                }
            }
        }
    }
    System.out.println(table.render());
}

From source file:eu.itesla_project.online.tools.OnlineWorkflowTool.java

License:Mozilla Public License

@Override
public void run(CommandLine line) throws Exception {

    OnlineWorkflowStartParameters startconfig = OnlineWorkflowStartParameters.loadDefault();

    String host = line.getOptionValue(OnlineWorkflowCommand.HOST);
    String port = line.getOptionValue(OnlineWorkflowCommand.PORT);
    String threads = line.getOptionValue(OnlineWorkflowCommand.THREADS);
    if (host != null)
        startconfig.setJmxHost(host);/*from  www  . j  a  v a  2 s .c  om*/
    if (port != null)
        startconfig.setJmxPort(Integer.valueOf(port));
    if (threads != null)
        startconfig.setThreads(Integer.valueOf(threads));

    Set<DateTime> baseCasesSet = null;

    OnlineWorkflowParameters params = OnlineWorkflowParameters.loadDefault();
    boolean atLeastOneBaseCaseLineParam = line.hasOption(OnlineWorkflowCommand.CASE_TYPE)
            || line.hasOption(OnlineWorkflowCommand.COUNTRIES)
            || line.hasOption(OnlineWorkflowCommand.BASE_CASE)
            || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL);
    boolean allNeededBaseCaseLineParams = line.hasOption(OnlineWorkflowCommand.CASE_TYPE)
            && line.hasOption(OnlineWorkflowCommand.COUNTRIES)
            && (line.hasOption(OnlineWorkflowCommand.BASE_CASE)
                    || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL));

    if (line.hasOption(OnlineWorkflowCommand.CASE_FILE)) {
        if (atLeastOneBaseCaseLineParam) {
            showHelp("parameter " + OnlineWorkflowCommand.CASE_FILE
                    + " cannot be used together with parameters: " + OnlineWorkflowCommand.CASE_TYPE + ", "
                    + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE + ", "
                    + OnlineWorkflowCommand.BASECASES_INTERVAL);
            return;
        }
        params.setCaseFile(line.getOptionValue(OnlineWorkflowCommand.CASE_FILE));
    } else {
        if (params.getCaseFile() != null) {
            if (atLeastOneBaseCaseLineParam) {
                if (!allNeededBaseCaseLineParams) {
                    showHelp("to override default parameter " + OnlineWorkflowCommand.CASE_FILE
                            + ", all these parameters must be specified: " + OnlineWorkflowCommand.CASE_TYPE
                            + ", " + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE
                            + " or " + OnlineWorkflowCommand.BASECASES_INTERVAL);
                    return;
                }
                params.setCaseFile(null);
            }
        }
        if (line.hasOption(OnlineWorkflowCommand.CASE_TYPE))
            params.setCaseType(CaseType.valueOf(line.getOptionValue(OnlineWorkflowCommand.CASE_TYPE)));
        if (line.hasOption(OnlineWorkflowCommand.COUNTRIES)) {
            params.setCountries(Arrays.stream(line.getOptionValue(OnlineWorkflowCommand.COUNTRIES).split(","))
                    .map(Country::valueOf).collect(Collectors.toSet()));
        }
        if (line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL)) {
            Interval basecasesInterval = Interval
                    .parse(line.getOptionValue(OnlineWorkflowCommand.BASECASES_INTERVAL));
            OnlineConfig oConfig = OnlineConfig.load();
            CaseRepository caseRepo = oConfig.getCaseRepositoryFactoryClass().newInstance()
                    .create(new LocalComputationManager());
            baseCasesSet = caseRepo.dataAvailable(params.getCaseType(), params.getCountries(),
                    basecasesInterval);
            System.out.println("Base cases available for interval " + basecasesInterval.toString());
            baseCasesSet.forEach(x -> {
                System.out.println(" " + x);
            });
        }
        if (baseCasesSet == null) {
            baseCasesSet = new HashSet<>();
            String base = line.getOptionValue(OnlineWorkflowCommand.BASE_CASE);
            if (base != null) {
                baseCasesSet.add(DateTime.parse(base));
            } else {
                baseCasesSet.add(params.getBaseCaseDate());
            }
        }
    }

    String histo = line.getOptionValue(OnlineWorkflowCommand.HISTODB_INTERVAL);
    if (histo != null)
        params.setHistoInterval(Interval.parse(histo));

    String states = line.getOptionValue(OnlineWorkflowCommand.STATES);
    if (states != null)
        params.setStates(Integer.parseInt(states));

    String timeHorizon = line.getOptionValue(OnlineWorkflowCommand.TIME_HORIZON);
    if (timeHorizon != null)
        params.setTimeHorizon(TimeHorizon.fromName(timeHorizon));

    String workflowid = line.getOptionValue(OnlineWorkflowCommand.WORKFLOW_ID);
    if (workflowid != null)
        params.setOfflineWorkflowId(workflowid);

    String feAnalysisId = line.getOptionValue(OnlineWorkflowCommand.FEANALYSIS_ID);
    if (feAnalysisId != null)
        params.setFeAnalysisId(feAnalysisId);

    String rulesPurity = line.getOptionValue(OnlineWorkflowCommand.RULES_PURITY);
    if (rulesPurity != null)
        params.setRulesPurityThreshold(Double.parseDouble(rulesPurity));

    if (line.hasOption(OnlineWorkflowCommand.STORE_STATES))
        params.setStoreStates(true);

    if (line.hasOption(OnlineWorkflowCommand.ANALYSE_BASECASE))
        params.setAnalyseBasecase(true);

    if (line.hasOption(OnlineWorkflowCommand.VALIDATION)) {
        params.setValidation(true);
        params.setStoreStates(true); // if validation then store states
        params.setAnalyseBasecase(true); // if validation then analyze base case
    }

    Set<SecurityIndexType> securityIndexes = null;
    if (line.hasOption(OnlineWorkflowCommand.SECURITY_INDEXES)) {
        if (!"ALL".equals(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES)))
            securityIndexes = Arrays
                    .stream(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES).split(","))
                    .map(SecurityIndexType::valueOf).collect(Collectors.toSet());
        params.setSecurityIndexes(securityIndexes);
    }

    if (line.hasOption(OnlineWorkflowCommand.MERGE_OPTIMIZED))
        params.setMergeOptimized(true);

    String limitReduction = line.getOptionValue(OnlineWorkflowCommand.LIMIT_REDUCTION);
    if (limitReduction != null)
        params.setLimitReduction(Float.parseFloat(limitReduction));

    if (line.hasOption(OnlineWorkflowCommand.HANDLE_VIOLATION_IN_N)) {
        params.setHandleViolationsInN(true);
        params.setAnalyseBasecase(true); // if I need to handle violations in N, I need to analyze base case
    }

    String constraintMargin = line.getOptionValue(OnlineWorkflowCommand.CONSTRAINT_MARGIN);
    if (constraintMargin != null)
        params.setConstraintMargin(Float.parseFloat(constraintMargin));

    String urlString = "service:jmx:rmi:///jndi/rmi://" + startconfig.getJmxHost() + ":"
            + startconfig.getJmxPort() + "/jmxrmi";

    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    Map<String, String> jmxEnv = new HashMap<>();
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, jmxEnv);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();

    ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME);
    LocalOnlineApplicationMBean application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name,
            LocalOnlineApplicationMBean.class, false);

    if (line.hasOption(OnlineWorkflowCommand.START_CMD)) {
        if (params.getCaseFile() != null) {
            System.out.println("starting Online Workflow, caseFile " + params.getCaseFile());
            String workflowId = application.startWorkflow(startconfig, params);
            System.out.println("workflowId=" + workflowId);

        } else {
            for (DateTime basecase : baseCasesSet) {
                params.setBaseCaseDate(basecase);
                System.out.println("starting Online Workflow, basecase " + basecase.toString());
                String workflowId = application.startWorkflow(startconfig, params);
                System.out.println("workflowId=" + workflowId);
            }
        }
    } else if (line.hasOption(OnlineWorkflowCommand.SHUTDOWN_CMD)) {
        application.shutdown();
    } else {
        showHelp("");
    }

}

From source file:fi.csc.idp.stepup.impl.TvilioSMSReceiverStepUpAccount.java

License:Open Source License

/**
 * Verify targets response can be found from tvilio. Response can be used only once successfully.
 *
 *
 * @param response is ignored.//from  w  w w  .j ava 2 s  .  c  o m
 * @return true if response was verified successfully
 * @throws Exception if something unexpected occurred
 */
@Override
public boolean doVerifyResponse(String response) throws Exception {

    log.debug("Verificating totp response {}", response);
    Twilio.init(accountSid, authToken);

    // We fetch all messages of past 24h
    DateTime rangeDateSentStart = new DateTime().minusDays(1);
    log.debug("Searching for messages sent since {}", rangeDateSentStart.toString());
    for (int i = 0; i < numberOfChecks; i++) {
        log.debug("Locating messages");
        ResourceSet<Message> messages = Message.reader().setDateSent(rangeDateSentStart).read();
        for (Message message : messages) {
            log.debug("Message sid {}", message.getSid());
            // has to be received by us, doublecheck
            if (!(message.getDirection() == Direction.INBOUND)) {
                log.debug("Message discarded, not inbound");
                continue;
            }
            // has to match target, doublecheck
            log.debug("Located message from {}", message.getFrom());
            log.debug("Comparing to {}", getTarget());
            if (!cmpNumbers(message.getFrom(), new PhoneNumber(getTarget()))) {
                log.debug("Message discarded, not sent by user");
                continue;
            }
            long sent = message.getDateSent().toDate().getTime();
            long current = new Date().getTime();
            log.debug("Message sent {}", message.getDateSent().toDate());
            // message has to have been sent no more that eventWindow time
            // before check
            if (current - sent > eventWindow) {
                log.debug("Message discarded, too old message");
                continue;
            }
            if (getChallenge().length() > 0 && (!getChallenge().equals(message.getBody()))) {
                log.debug("Message discarded, challenge not replied");
                continue;
            }

            msgLock.lock();
            if (usedMessages.containsKey(message.getSid())) {
                msgLock.unlock();
                log.debug("Message discarded, already used");
                continue;
            }
            cleanMessages();
            log.debug("Adding {} {} to the list of used verification messages", message.getSid(),
                    message.getDateSent());
            usedMessages.put(message.getSid(), message.getDateSent());
            msgLock.unlock();
            return true;
        }
        if (numberOfChecks > 0) {
            Thread.sleep(intervalOfChecks);
        }

    }
    return false;
}

From source file:fi.vm.sade.osoitepalvelu.kooste.webapp.OrganisaatioCacheHealthCheck.java

License:EUPL

@Override
public Object checkHealth() throws Throwable {
    final StopWatch watch = new StopWatch();
    final long count = organisaatioRepository.count();
    final DateTime oldestEntry = organisaatioRepository.findOldestCachedEntry();
    if (oldestEntry == null) {
        throw new IllegalStateException("No cached organisatios.");
    }//  w  ww .  j  ava2  s . com
    if (!isCacheUsable(oldestEntry)) {
        throw new IllegalStateException("Organisaatio-cache too old. Oldest entry from " + oldestEntry);
    }
    final long resultTook = watch.stop();
    return new LinkedHashMap<Object, Object>() {
        private static final long serialVersionUID = 6709620862376707410L;
        {
            put("status", "OK");
            put("organisaatiot-count", count);
            put("oldest-entry", oldestEntry.toString());
            put("response-time", "" + resultTook + " ms");
        }
    };
}

From source file:flow_model.DPSpaceShared.java

License:GNU General Public License

private void processIncommingOutputFile(Sim_event ev) {
    DPGridlet gl = (DPGridlet) ev.get_data();
    gl.getUsedLink().addOutputTransfer(gl.getGridletOutputSize());//update link statistics
    //write("received output file of a gridlet " + gl.getGridletID());
    //add new input file to
    if (addOutputFile(gl)) {
        //send confirmation to sender
        //send without network delay
        super.sim_schedule(gl.getSenderID(), GridSimTags.SCHEDULE_NOW, RiftTags.OUTPUT_TRANSFER_ACK, gl);
        //remember the time when the last output was received. For makespan calculation
        this.lastOutputReceived = GridSim.clock();
        this.incommingTransferFailureFlag = 0.0;
        //if source and destination check, if all files are process
        //print the progress
        if (this.isInputSource && this.initialNomberOfFiles != 0
                && (this.readyOutputFiles.size() % (this.initialNomberOfFiles / 20) == 0)) {
            DateTime now = DateTime.now();
            System.out.println(now.toString() + " " + super.get_name() + " " + this.readyOutputFiles.size()
                    + " / " + this.initialNomberOfFiles);
        }//from   w ww  . j av a 2s.  c  om

    } else {
        this.receiveErrorCounter++;
        this.incommingTransferFailureFlag = 1.0;
        //send failure back to sender 
        //send without network delay      
        super.sim_schedule(gl.getSenderID(), GridSimTags.SCHEDULE_NOW, RiftTags.OUTPUT_TRANSFER_FAIL, gl);
        return;
    }

    if (planIsSet) {
        processFiles();
    }

}

From source file:fr.gouv.vitam.mdbes.ParserIngest.java

License:Open Source License

/**
 *
 * @param typeField/*  w  w  w . j  av a  2s .co  m*/
 * @param rank
 * @param lstart
 * @param cpt
 * @return the equivalent BSon object for the current Field
 * @throws InvalidExecOperationException
 */
private BasicDBObject getDbObject(final TypeField typeField, final long rank, final long lstart,
        final AtomicLong cpt) throws InvalidExecOperationException {
    final BasicDBObject subobj = new BasicDBObject();
    String val = null;
    switch (typeField.type) {
    case constant:
        setValue(subobj, typeField, typeField.prefix);
        break;
    case constantArray:
        subobj.put(typeField.name, typeField.listeValeurs);
        break;
    case random:
        switch (typeField.ftype) {
        case date:
            final long curdate = System.currentTimeMillis();
            final Date date = new Date(curdate - rnd.nextInt());
            final DateTime dateTime = new DateTime(date);
            if (typeField.saveName != null) {
                context.savedNames.put(typeField.saveName, dateTime.toString());
            }
            subobj.put(typeField.name, date);
            break;
        case nombre:
            final Long lnval = rnd.nextLong();
            if (typeField.saveName != null) {
                context.savedNames.put(typeField.saveName, lnval.toString());
            }
            subobj.put(typeField.name, lnval);
            break;
        case nombrevirgule:
            final Double dnval = rnd.nextDouble();
            if (typeField.saveName != null) {
                context.savedNames.put(typeField.saveName, dnval.toString());
            }
            subobj.put(typeField.name, dnval);
            break;
        case chaine:
        default:
            val = randomString(32);
            val = getValue(typeField, val);
            subobj.put(typeField.name, val);
            break;
        }
        break;
    case save:
        val = getValue(typeField, "");
        setValue(subobj, typeField, val);
        break;
    case liste:
        final int rlist = rnd.nextInt(typeField.listeValeurs.length);
        val = typeField.listeValeurs[rlist];
        val = getValue(typeField, val);
        setValue(subobj, typeField, val);
        break;
    case listeorder:
        long i = rank - lstart;
        if (i >= typeField.listeValeurs.length) {
            i = typeField.listeValeurs.length - 1;
        }
        val = typeField.listeValeurs[(int) i];
        val = getValue(typeField, val);
        setValue(subobj, typeField, val);
        break;
    case serie:
        AtomicLong newcpt = cpt;
        long j = newcpt.get();
        if (typeField.idcpt != null) {
            newcpt = context.cpts.get(typeField.idcpt);
            // System.out.println("CPT replaced by: "+typeField.idcpt);
            if (newcpt == null) {
                newcpt = cpt;
                LOGGER.error("wrong cpt name: " + typeField.idcpt);
            } else {
                j = newcpt.getAndIncrement();
                // System.out.println("increment: "+j+" for "+typeField.name);
            }
        }
        if (typeField.modulo > 0) {
            j = j % typeField.modulo;
        }
        val = (typeField.prefix != null ? typeField.prefix : "") + j;
        val = getValue(typeField, val);
        setValue(subobj, typeField, val);
        break;
    case subfield:
        final BasicDBObject subobjs = new BasicDBObject();
        for (final TypeField field : typeField.subfields) {
            final BasicDBObject obj = getDbObject(field, rank, lstart, cpt);
            if (obj != null) {
                subobjs.putAll((BSONObject) obj);
            } else {
                return null;
            }
        }
        subobj.put(typeField.name, subobjs);
        break;
    case interval:
        final int newval = rnd.nextInt(typeField.low, typeField.high + 1);
        val = getValue(typeField, "" + newval);
        setValue(subobj, typeField, val);
        break;
    case select:
        final BasicDBObject request = new BasicDBObject();
        for (final TypeField field : typeField.subfields) {
            final String name = field.name;
            final String arg = getValue(field, "");
            request.append(name, arg);
        }
        if (simulate) {
            LOGGER.error("NotAsking: " + request);
            return null;
        }
        final DAip maip = (DAip) MongoDbAccess.VitamCollections.Cdaip.getCollection().findOne(request,
                new BasicDBObject(typeField.name, 1));
        if (maip != null) {
            // System.out.println("Select: "+typeField.name+":"+ maip.get(typeField.name));
            val = getValue(typeField, (String) maip.get(typeField.name));
            setValue(subobj, typeField, val);
        } else {
            // LOGGER.error("NotFound: "+request);
            return null;
        }
        break;
    default:
        throw new InvalidExecOperationException("Incorrect type: " + typeField.type);
    }
    return subobj;
}

From source file:fr.gouv.vitam.query.construct.request.InRequest.java

License:Open Source License

/**
 * In Request constructor/* w  w w .  java  2  s.  co m*/
 *
 * @param inRequest
 *            in, nin
 * @param variableName
 * @param value
 * @throws InvalidCreateOperationException
 */
public InRequest(final REQUEST inRequest, final String variableName, final Date value)
        throws InvalidCreateOperationException {
    super();
    switch (inRequest) {
    case in:
    case nin: {
        if (variableName == null || variableName.trim().isEmpty()) {
            throw new InvalidCreateOperationException(
                    "Request " + inRequest + " cannot be created with empty variable name");
        }
        final ObjectNode sub = ((ObjectNode) currentObject).putObject(inRequest.exactToken());
        final ArrayNode array = sub.putArray(variableName.trim());
        final DateTime dateTime = new DateTime(value);
        final String sdate = dateTime.toString();
        ObjectNode elt = JsonHandler.createObjectNode().put(DATE, sdate);
        array.add(elt);
        stringVals = new HashSet<String>();
        stringVals.add(sdate);
        currentObject = array;
        currentREQUEST = inRequest;
        setReady(true);
        break;
    }
    default:
        throw new InvalidCreateOperationException("Request " + inRequest + " is not an In or Search Request");
    }
}

From source file:fr.gouv.vitam.query.construct.request.InRequest.java

License:Open Source License

/**
 * In Request constructor// w w w.  j a v  a  2  s  .c o  m
 *
 * @param inRequest
 *            in, nin
 * @param variable
 * @param values
 * @throws InvalidCreateOperationException
 */
public InRequest(final REQUEST inRequest, final String variable, final Date... values)
        throws InvalidCreateOperationException {
    super();
    if (variable == null || variable.trim().isEmpty()) {
        throw new InvalidCreateOperationException(
                "Request " + inRequest + " cannot be created with empty variable name");
    }
    switch (inRequest) {
    case in:
    case nin: {
        final ObjectNode sub = ((ObjectNode) currentObject).putObject(inRequest.exactToken());
        final ArrayNode array = sub.putArray(variable.trim());
        stringVals = new HashSet<String>();
        for (final Date value : values) {
            final DateTime dateTime = new DateTime(value);
            final String sdate = dateTime.toString();
            if (!stringVals.contains(sdate)) {
                ObjectNode elt = JsonHandler.createObjectNode().put(DATE, sdate);
                array.add(elt);
                stringVals.add(sdate);
            }
        }
        currentObject = array;
        break;
    }
    default:
        throw new InvalidCreateOperationException("Request " + inRequest + " is not an In Request");
    }
    currentREQUEST = inRequest;
    setReady(true);
}