Example usage for org.joda.time.format ISODateTimeFormat dateHourMinuteSecond

List of usage examples for org.joda.time.format ISODateTimeFormat dateHourMinuteSecond

Introduction

In this page you can find the example usage for org.joda.time.format ISODateTimeFormat dateHourMinuteSecond.

Prototype

public static DateTimeFormatter dateHourMinuteSecond() 

Source Link

Document

Returns a formatter that combines a full date, two digit hour of day, two digit minute of hour, and two digit second of minute.

Usage

From source file:com.avid.central.obsplugin.inewslibrary.ExportStories.java

public ExportStoryData ProcessRundown(List<Story> stories, ExportConfiguration config) {
    ExportStoryData exportData = new ExportStoryData(config);

    // create a new OBS_Export
    ExportRundown _export = new ExportRundown();

    // Represents the starting time of an item, can be calculated from previous item start time or set explicitly by the user
    int currentStartTime = 0;

    // Flags the fact that the previous Story parsed was a break with a defined time
    boolean lastStoryWasBreak = false;

    // Flags the fact that we have now validated the header
    boolean headerValid = false;

    // identifiers used in exporting cue sheets
    String CueSheetLocation = "<p family=\"0\" font=\"\" pitch=\"0\">" + config.cuesheet_id + "</p>";
    String BodyStart = "<body";
    String BodyEnd = "</body>";

    // do everything inside a try {} block
    // if we encounter any of the conditions listed above which preclude exporting the rundown
    // then we throw an exception which includes the reason why
    try {/*from w  ww .  j  a v  a2s .  c  o  m*/
        // go through stories and decide what to do with each
        for (Story story : stories) {
            List<mos> vizGrapics = new ArrayList<mos>();

            // is this a break story?
            if (story.Story.getHead().getMeta().isBreak()) {
                // yes it is
                // need to get the content of the info Field
                String info = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                        config.info_field);
                if (null == info) {
                    RaiseError(String.format("field \"%s\" was not found", config.info_field));
                }

                String subject = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                        config.subject_field);
                if (null == subject) {
                    RaiseError(String.format("field \"%s\" was not found", config.subject_field));
                }

                // is it one of our "special" fields
                if (info.equalsIgnoreCase(config.obs_channel_id)) {
                    if (subject.length() == 0) {
                        // the channelID is missing so abort the export
                        RaiseError(String.format("the rundown %s was not found", config.obs_channel_id));
                    }

                    // this is the Story that contains the channel ID
                    _export.Rundown.ChannelID = subject;

                    // determine the mode, first test for MDS
                    if (subject.toUpperCase().startsWith(config.mds_prefix.toUpperCase())) {
                        exportData.setMdsMode(true);
                    } else if (!subject.toUpperCase().startsWith(config.onc_prefix.toUpperCase())
                            && config.onc_prefix.length() > 0) {
                        RaiseError(String.format("the %s was not identified as an ONC or MDS rundown",
                                config.obs_channel_id));
                    }

                } else if (info.equalsIgnoreCase(config.title_id)) {
                    if (subject.length() == 0 && exportData.getValidateFields()) {
                        // the rundown name is missing so abort the export
                        RaiseError(String.format("the rundown %s was not found", config.title_id));
                    }

                    // this is the Story that contains the rundown name
                    _export.Rundown.Title = subject;
                } else if (info.equalsIgnoreCase(config.day_id)) {
                    // this is the Story that contains the rundown day
                    if (subject.length() > 0) {
                        _export.Rundown.Day = subject;
                    }

                } else if (info.equalsIgnoreCase(config.date_id)) {
                    // this is the Story that contains the rundown date
                    if (subject.length() > 0) {
                        _export.Rundown.Date = subject;
                    }
                }

                String startTime = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                        config.start_time_field);
                if (null == startTime && exportData.getValidateFields()) {
                    RaiseError(String.format("field \"%s\" was not found", config.start_time_field));
                }

                // check for start and end time data
                if (subject.equalsIgnoreCase(config.start_id) && startTime.length() > 0) {
                    if (startTime.charAt(0) == '@') {
                        // we have an absolute start time
                        currentStartTime = Integer.parseInt(startTime.substring(1));
                        _export.Rundown.RundownStartTime = currentStartTime;
                    } else {
                        // start time is relative to start of show
                        currentStartTime = Integer.parseInt(startTime.substring(1))
                                + _export.Rundown.RundownStartTime;
                        _export.Rundown.RundownStartTime = currentStartTime;
                    }
                } else if (subject.equalsIgnoreCase(config.end_id) && startTime.length() > 0) {
                    if (startTime.charAt(0) == '@') {
                        // we have an absolute end time
                        _export.Rundown.RundownEndTime = Integer.parseInt(startTime.substring(1));
                    } else {
                        // start time is relative to start of show
                        _export.Rundown.RundownEndTime = Integer.parseInt(startTime.substring(1))
                                + _export.Rundown.RundownStartTime;
                    }

                    lastStoryWasBreak = true;
                }
            } else {
                if (!story.Story.getHead().getMeta().isFloat()) {
                    // this is not a floated Story so we must have passed the "header"
                    // if we haven't validated the "header" at this point then now is the time to do so!
                    if (!headerValid) {
                        if (-1 == _export.Rundown.RundownStartTime && exportData.getValidateFields()) {
                            // the start time has not been set so abort the export
                            RaiseError("the rundown start time is missing");
                        }

                        headerValid = true;
                    }

                    // every time we encounter a non-break, non-floated Story reset the rundown end time to unspecified
                    // it should get set to the correct value by the final break Story
                    _export.Rundown.RundownEndTime = -1;

                    // get the subject
                    String subject = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.subject_field);
                    if (null == subject) {
                        RaiseError(String.format("field \"%s\" was not found", config.subject_field));
                    }

                    if (subject.length() == 0 && exportData.getValidateFields()) {
                        RaiseError("at least one story is missing its Subject details");
                    }

                    // check for an update and retrieve modification time
                    String updatedTimestamp = null;
                    int update = GetFieldIntegerValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.update_field);
                    DateTime modificationTime = GetFieldDateValue(
                            story.Story.getFields().getStringOrBooleanOrDate(), config.modified_field);
                    if (null != modificationTime) {
                        DateTimeFormatter fmt = ISODateTimeFormat.dateHourMinuteSecond();
                        updatedTimestamp = modificationTime.toString(fmt);
                    }

                    // get the start time
                    String startTime = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.start_time_field);

                    // do we have start time data?
                    if (startTime != null && !startTime.isEmpty()) {
                        // update the running start time
                        if (startTime.charAt(0) == '@') {
                            // we have an absolute start time
                            currentStartTime = Integer.parseInt(startTime.substring(1));
                        } else {
                            // start time is relative to start of show
                            currentStartTime = Integer.parseInt(startTime.substring(1))
                                    + _export.Rundown.RundownStartTime;
                        }
                    } else {
                        // no start time specified so we need to get it from the previous item
                        // if there are not yet any stories in the list then just use the start time we are carrying forward
                        if (_export.Stories.size() > 0 && !lastStoryWasBreak) {
                            // there is at least one Story
                            currentStartTime += _export.Stories.get(_export.Stories.size() - 1).StoryDuration;
                        }
                    }

                    // get the VideoID
                    String videoID = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.video_id_field);
                    if (exportData.getMdsMode()) {
                        if (null == videoID) {
                            RaiseError(String.format("field \"%s\" was not found", config.video_id_field));
                        }
                        if (videoID.length() == 0 && exportData.getValidateFields()) {
                            RaiseError("at least one story is missing its VideoID details");
                        }
                    } else if (null == videoID || videoID.isEmpty()) {
                        videoID = "";
                    }

                    // get the Type
                    String type = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.type_field);
                    if (exportData.getMdsMode()) {
                        if (null == type) {
                            RaiseError(String.format("field \"%s\" was not found", config.type_field));
                        }
                        if (type.length() == 0 && exportData.getValidateFields()) {
                            RaiseError("at least one story is missing its type details");
                        }
                    }

                    // get the Upmix
                    String upMix = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.upmix_field);
                    if (exportData.getMdsMode()) {
                        if (null == upMix) {
                            RaiseError(String.format("field \"%s\" was not found", config.upmix_field));
                        }
                        if (upMix.length() == 0 && exportData.getValidateFields()) {
                            RaiseError("at least one story is missing its upmix details");
                        }
                    }

                    // get the Music
                    String music = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.music_field);
                    if (exportData.getMdsMode()) {
                        if (null == music || music.length() == 0) {
                            exportData.getResponse()
                                    .setMessage("At least one story is missing its music element");
                        }
                    }

                    if (!exportData.getMdsMode() && exportData.getValidateFields()) {
                        // get the Endorsement details
                        String endorseBy = GetFieldStringValue(
                                story.Story.getFields().getStringOrBooleanOrDate(), config.endorse_field);
                        if (null == endorseBy) {
                            RaiseError(String.format("field \"%s\" was not found", config.endorse_field));
                        }
                        if (endorseBy.length() == 0) {
                            exportData.getResponse().setMessage("At least one story has not been approved");
                            //                                RaiseError("at least one story has not been approved");
                        }

                        // get the Export Approval flags
                        int approved = GetFieldIntegerValue(story.Story.getFields().getStringOrBooleanOrDate(),
                                config.export_field);
                        if (approved == 0) {
                            RaiseError("at least one story is not ready for export");
                        }
                    }

                    // get VIZ production cue
                    // are there any anchored elements?
                    if (exportData.getCheckGrahics()) {
                        if (null != story.Story.getAeset() && story.Story.getAeset().getAe().size() > 0) {
                            // is there one for VIZ?
                            for (Ae ae : story.Story.getAeset().getAe()) {

                                for (Object ap : ae.getMcOrAp()) {
                                    if (ap.getClass() != Nsml.Aeset.Ae.Mc.class) {
                                        continue;
                                    }

                                    Nsml.Aeset.Ae.Mc mc = (Nsml.Aeset.Ae.Mc) ap;
                                    for (Object content : mc.getAp()) {
                                        if (content.getClass() != ApContent.class) {
                                            continue;
                                        }

                                        ApContent apContent = (ApContent) content;
                                        for (Object data : apContent.getContent()) {
                                            if (data.getClass() == String.class) {
                                                String graphic = (String) data;
                                                if (!graphic.contains(config.viz_id)) {
                                                    continue;
                                                }

                                                for (AttachmentType at : story.Story.getAesetAtts()
                                                        .getAttachment()) {
                                                    if (mc.getIdref().equals(at.getId())) {
                                                        // found it!
                                                        String graphicData = at.getValue();
                                                        if (graphicData != null) {
                                                            try {
                                                                AttachmentContent ac = AttachmentContent
                                                                        .Parse(graphicData);
                                                                if (ac != null) {
                                                                    vizGrapics.add(ac.mos);
                                                                }
                                                            } catch (Exception ex) {
                                                            }

                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (0 == vizGrapics.size()) {
                            exportData.getResponse()
                                    .setMessage("At least one story is missing its graphic element");
                        }
                    }

                    // Story looks OK so add it to the export
                    OBSStory obsStory = new OBSStory();

                    obsStory.Subject = subject;
                    obsStory.Type = type;
                    obsStory.StoryStartTime = currentStartTime;
                    obsStory.StoryDuration = GetFieldIntegerValue(
                            story.Story.getFields().getStringOrBooleanOrDate(), config.duration_field);
                    obsStory.VideoID = videoID;

                    if (exportData.getMdsMode()) {
                        obsStory.Upmix = upMix.equals("1") || upMix.equals("true");
                        obsStory.Music = music;
                        obsStory.Graphics = vizGrapics;
                    } else {
                        if (null != updatedTimestamp) {
                            obsStory.Modified = updatedTimestamp;
                            obsStory.Update = update == 1;
                        }
                    }

                    // the story body as NSML
                    String formattedBody;

                    // unformatted version of the story body
                    String unformattedBody;

                    // the contents of the script info tag
                    String scriptInfo = null;

                    // the contents of the cue sheet tag
                    String cueSheet = null;

                    int cueSheetLocation = -1;

                    // get the story body free of all formatting
                    unformattedBody = GetStoryBody(story.Story);

                    // look for escape characters in the value and encode them
                    unformattedBody = unformattedBody.replace("&", "&amp;");
                    unformattedBody = unformattedBody.replace("\"", "&quot;");
                    unformattedBody = unformattedBody.replace("<", "&lt;");
                    unformattedBody = unformattedBody.replace(">", "&gt;");
                    unformattedBody = unformattedBody.replace("'", "&apos;");

                    // now look for a cue sheet
                    cueSheetLocation = unformattedBody.indexOf(config.cuesheet_id);

                    if (cueSheetLocation >= 0) {
                        // there is a cue sheet so extract it from the unformatted body if MDS mode
                        if (exportData.getMdsMode() && unformattedBody
                                .length() > (cueSheetLocation + config.cuesheet_id.length())) {
                            cueSheet = unformattedBody
                                    .substring(cueSheetLocation + config.cuesheet_id.length());
                        }

                        // crop the cue sheet from the unformatted body
                        unformattedBody = unformattedBody.substring(0, cueSheetLocation);
                    }

                    // we now have the unformatted body free of cue sheet data together with the cue sheet if it exists

                    // are we exporting the story in its formatted version?
                    if (exportData.getRetainFormatting()) {
                        formattedBody = "";

                        // get the formatted story body
                        // first get offsets to body tags
                        int storyStart = story.StoryAsNSML.indexOf(BodyStart);
                        int storyEnd = story.StoryAsNSML.indexOf(BodyEnd);

                        // check for non-empty body
                        if (-1 != storyEnd) {
                            // make sure we extract the end tag
                            storyEnd += BodyEnd.length();
                            formattedBody = story.StoryAsNSML.substring(storyStart, storyEnd);
                            // now we have the formatted story body

                            // if the story is not empty and has a cue sheet section we need to remove it
                            cueSheetLocation = formattedBody.indexOf(CueSheetLocation);

                            if (cueSheetLocation >= 0 && unformattedBody.length() > 0) {
                                // there is a cue sheet and the story isn't empty so we need to remove the cue sheet from the formatted body
                                String script = formattedBody.substring(0, cueSheetLocation);
                                // add back the body end tag
                                script += BodyEnd;
                                scriptInfo = "<![CDATA[\n" + script + "]]>";

                            } else if (unformattedBody.length() > 0) {
                                scriptInfo = "<![CDATA[\n" + formattedBody + "]]>";
                            }

                        }

                    } else {
                        // simply export the unformatted body
                        scriptInfo = unformattedBody;
                    }

                    obsStory.ScriptInfo = scriptInfo;
                    if (exportData.getMdsMode() && null != cueSheet) {
                        obsStory.CueSheet = cueSheet;
                    }

                    _export.Stories.add(obsStory);

                    lastStoryWasBreak = false;
                }
            }
        }

        // check that we have an end time
        if (-1 == _export.Rundown.RundownEndTime) {
            if (exportData.getValidateFields()) {
                // nope, reject this one
                RaiseError("the rundown end time is missing");
            } else {
                _export.Rundown.RundownEndTime = _export.Rundown.RundownStartTime;
            }
        }

        // check for Channel ID
        if (_export.Rundown.ChannelID.length() == 0 && exportData.getValidateFields()) {
            RaiseError(String.format("the rundown %s is missing", config.obs_channel_id));
        }

        // check for Channel Name
        if (_export.Rundown.Title.length() == 0 && exportData.getValidateFields()) {
            RaiseError(String.format("the rundown %s is missing", config.title_id));
        }

        // check for Date
        if (_export.Rundown.Date.length() == 0) {
            // log a warning here (no date specified)
            // set date to today's date
            DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-mm-dd");
            _export.Rundown.Date = DateTime.now().toString(dtf);
            if (null == exportData.getResponse().getMessage()) {
                exportData.getResponse().setMessage("The date information was missing from the rundown");
            }
        }
        exportData.getResponse().setDate(_export.Rundown.Date);

        // check for Day
        if (_export.Rundown.Day.length() == 0) {
            // log a warning here (no day specified)
            // set date to today's date
            _export.Rundown.Day = String.format("%02d", DateTime.now().dayOfMonth().get());
            if (null == exportData.getResponse().getMessage()) {
                exportData.getResponse().setMessage("The day information was missing from the rundown");
            }
        }
        exportData.getResponse().setDay(_export.Rundown.Day);

        exportData.setRundownAsXml(_export.GenerateXML(exportData.getMdsMode()));

        exportData.getResponse().setChannelID(_export.Rundown.ChannelID);
        exportData.getResponse().setStartTime(_export.Rundown.GetStartTime());
        exportData.getResponse().setEndTime(_export.Rundown.GetEndTime());
        exportData.getResponse().setTitle(_export.Rundown.Title);

        exportData.getResponse().setFileName(_export.GenerateFileName());
        exportData.getResponse().setResult(1);
    } catch (Exception ex) {
        exportData.getResponse().setMessage(ex.getMessage());
    }

    return exportData;
}

From source file:com.axelor.apps.account.service.payment.PayboxService.java

License:Open Source License

/**
 * Procdure permettant de raliser un paiement avec Paybox
 * @param paymentVoucher/*from  w w w .  j a v  a2s .com*/
 *             Une saisie paiement
 * @throws AxelorException
 * @throws UnsupportedEncodingException
 */
public String paybox(PaymentVoucher paymentVoucher) throws AxelorException, UnsupportedEncodingException {

    this.checkPayboxPaymentVoucherFields(paymentVoucher);

    Company company = paymentVoucher.getCompany();

    BigDecimal paidAmount = paymentVoucher.getPaidAmount();
    Partner payerPartner = paymentVoucher.getPartner();
    //      this.checkPayboxPartnerFields(payerPartner);
    this.checkPaidAmount(payerPartner, company, paidAmount);
    this.checkPaidAmount(paymentVoucher);

    PayboxConfig payboxConfig = payboxConfigService.getPayboxConfig(company);

    // Vrification du remplissage du chemin de la cl publique Paybox
    payboxConfigService.getPayboxPublicKeyPath(payboxConfig);

    String payboxUrl = payboxConfigService.getPayboxUrl(payboxConfig);
    String pbxSite = payboxConfigService.getPayboxSite(payboxConfig);
    String pbxRang = payboxConfigService.getPayboxRang(payboxConfig);
    String pbxDevise = payboxConfigService.getPayboxDevise(payboxConfig);
    String pbxTotal = paidAmount.setScale(2).toString().replace(".", "");
    String pbxCmd = paymentVoucher.getRef(); // Identifiant de la saisie paiement
    String pbxPorteur = this.getPartnerEmail(paymentVoucher);
    String pbxRetour = payboxConfigService.getPayboxRetour(payboxConfig);
    //      String pbxEffectue = this.encodeUrl(this.replaceVariableInUrl(accountConfigService.getPayboxRetourUrlEffectue(accountConfig), paymentVoucher));
    String pbxEffectue = this.replaceVariableInUrl(payboxConfigService.getPayboxRetourUrlEffectue(payboxConfig),
            paymentVoucher);
    String pbxRefuse = this.replaceVariableInUrl(payboxConfigService.getPayboxRetourUrlRefuse(payboxConfig),
            paymentVoucher);
    String pbxAnnule = this.replaceVariableInUrl(payboxConfigService.getPayboxRetourUrlAnnule(payboxConfig),
            paymentVoucher);
    String pbxIdentifiant = payboxConfigService.getPayboxIdentifiant(payboxConfig);
    String pbxHash = payboxConfigService.getPayboxHashSelect(payboxConfig);
    String pbxHmac = payboxConfigService.getPayboxHmac(payboxConfig);

    //Date  laquelle l'empreinte HMAC a t calcule (format ISO8601)
    String pbxTime = ISODateTimeFormat.dateHourMinuteSecond().print(new DateTime());

    // Permet de restreindre les modes de paiement
    String pbxTypepaiement = "CARTE";
    String pbxTypecarte = "CB";

    String message = this.buildMessage(pbxSite, pbxRang, pbxIdentifiant, pbxTotal, pbxDevise, pbxCmd,
            pbxPorteur, pbxRetour, pbxEffectue, pbxRefuse, pbxAnnule, pbxHash, pbxTime, pbxTypepaiement,
            pbxTypecarte);

    log.debug("Message : {}", message);

    String messageHmac = this.getHmacSignature(message, pbxHmac, pbxHash);

    log.debug("Message HMAC : {}", messageHmac);

    String messageEncode = this.buildMessage(URLEncoder.encode(pbxSite, this.CHARSET),
            URLEncoder.encode(pbxRang, this.CHARSET), URLEncoder.encode(pbxIdentifiant, this.CHARSET), pbxTotal,
            URLEncoder.encode(pbxDevise, this.CHARSET), URLEncoder.encode(pbxCmd, this.CHARSET),
            URLEncoder.encode(pbxPorteur, this.CHARSET), URLEncoder.encode(pbxRetour, this.CHARSET),
            URLEncoder.encode(pbxEffectue, this.CHARSET), URLEncoder.encode(pbxRefuse, this.CHARSET),
            URLEncoder.encode(pbxAnnule, this.CHARSET), URLEncoder.encode(pbxHash, this.CHARSET),
            URLEncoder.encode(pbxTime, this.CHARSET), URLEncoder.encode(pbxTypepaiement, this.CHARSET),
            URLEncoder.encode(pbxTypecarte, this.CHARSET));

    String url = payboxUrl + messageEncode + "&PBX_HMAC=" + messageHmac;

    log.debug("Url : {}", url);

    return url;
}

From source file:com.github.christofluyten.experiment.ResultWriter.java

License:Apache License

static File createExperimentDir(File target) {
    final String timestamp = ISODateTimeFormat.dateHourMinuteSecond().print(System.currentTimeMillis())
            .replace(":", "");
    final File experimentDirectory = new File(target, timestamp);
    experimentDirectory.mkdirs();/*  ww w  .java2 s  . c o  m*/

    //    final File latest = new File(target, "latest/");
    //    if (latest.exists()) {
    //      checkState(latest.delete());
    //    }
    //    try {
    //      java.nio.file.Files.createSymbolicLink(
    //        latest.toPath(),
    //        experimentDirectory.getAbsoluteFile().toPath());
    //    } catch (final IOException e) {
    //      throw new IllegalStateException(e);
    //    }
    return experimentDirectory;
}

From source file:com.github.pennyfive.cinemafinlando.api.xml.DateTimeConverter.java

License:Apache License

@Override
public DateTime read(InputNode inputNode) throws Exception {
    return ISODateTimeFormat.dateHourMinuteSecond().parseDateTime(inputNode.getValue());
}

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

License:Apache License

static File createExperimentDir(File target) {
    final String timestamp = ISODateTimeFormat.dateHourMinuteSecond().print(System.currentTimeMillis())
            .replace(":", "");
    final File experimentDirectory = new File(target, timestamp);
    experimentDirectory.mkdirs();/*  www .  j  a  v  a 2 s .  com*/

    final File latest = new File(target, "latest/");
    if (latest.exists()) {
        checkState(latest.delete());
    }
    try {
        java.nio.file.Files.createSymbolicLink(latest.toPath(), experimentDirectory.getAbsoluteFile().toPath());
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
    return experimentDirectory;
}

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;
    }//from   w ww. j a  va  2  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

static File createExperimentDir(File target, String nameExt) {
    final String timestamp = ISODateTimeFormat.dateHourMinuteSecond().print(System.currentTimeMillis())
            .replace(":", "");
    final File experimentDirectory = new File(target, timestamp + nameExt);
    experimentDirectory.mkdirs();/*from   w  ww  .ja  v a 2 s .c o m*/

    final Path latest = Paths.get(target.getAbsolutePath(), "latest/");
    try {
        java.nio.file.Files.deleteIfExists(latest);
        java.nio.file.Files.createSymbolicLink(latest, experimentDirectory.getAbsoluteFile().toPath());
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
    return experimentDirectory;
}

From source file:com.tuplejump.stargate.Dates.java

License:Apache License

/**
 * Parses a joda based pattern, including some named ones (similar to the built in Joda ISO ones).
 *//* w w w.  jav  a2s. co m*/
public static FormatDateTimeFormatter forPattern(String input, Locale locale) {
    if (StringUtils.isNotBlank(input)) {
        input = input.trim();
    }
    if (input == null || input.length() == 0) {
        throw new IllegalArgumentException("No date pattern provided");
    }

    DateTimeFormatter formatter;
    if ("basicDate".equals(input) || "basic_date".equals(input)) {
        formatter = ISODateTimeFormat.basicDate();
    } else if ("basicDateTime".equals(input) || "basic_date_time".equals(input)) {
        formatter = ISODateTimeFormat.basicDateTime();
    } else if ("basicDateTimeNoMillis".equals(input) || "basic_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicDateTimeNoMillis();
    } else if ("basicOrdinalDate".equals(input) || "basic_ordinal_date".equals(input)) {
        formatter = ISODateTimeFormat.basicOrdinalDate();
    } else if ("basicOrdinalDateTime".equals(input) || "basic_ordinal_date_time".equals(input)) {
        formatter = ISODateTimeFormat.basicOrdinalDateTime();
    } else if ("basicOrdinalDateTimeNoMillis".equals(input)
            || "basic_ordinal_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicOrdinalDateTimeNoMillis();
    } else if ("basicTime".equals(input) || "basic_time".equals(input)) {
        formatter = ISODateTimeFormat.basicTime();
    } else if ("basicTimeNoMillis".equals(input) || "basic_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicTimeNoMillis();
    } else if ("basicTTime".equals(input) || "basic_t_Time".equals(input)) {
        formatter = ISODateTimeFormat.basicTTime();
    } else if ("basicTTimeNoMillis".equals(input) || "basic_t_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicTTimeNoMillis();
    } else if ("basicWeekDate".equals(input) || "basic_week_date".equals(input)) {
        formatter = ISODateTimeFormat.basicWeekDate();
    } else if ("basicWeekDateTime".equals(input) || "basic_week_date_time".equals(input)) {
        formatter = ISODateTimeFormat.basicWeekDateTime();
    } else if ("basicWeekDateTimeNoMillis".equals(input) || "basic_week_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicWeekDateTimeNoMillis();
    } else if ("date".equals(input)) {
        formatter = ISODateTimeFormat.date();
    } else if ("dateHour".equals(input) || "date_hour".equals(input)) {
        formatter = ISODateTimeFormat.dateHour();
    } else if ("dateHourMinute".equals(input) || "date_hour_minute".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinute();
    } else if ("dateHourMinuteSecond".equals(input) || "date_hour_minute_second".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinuteSecond();
    } else if ("dateHourMinuteSecondFraction".equals(input)
            || "date_hour_minute_second_fraction".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinuteSecondFraction();
    } else if ("dateHourMinuteSecondMillis".equals(input) || "date_hour_minute_second_millis".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinuteSecondMillis();
    } else if ("dateOptionalTime".equals(input) || "date_optional_time".equals(input)) {
        // in this case, we have a separate parser and printer since the dataOptionalTimeParser can't print
        // this sucks we should use the root local by default and not be dependent on the node
        return new FormatDateTimeFormatter(input,
                ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC),
                ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC), locale);
    } else if ("dateTime".equals(input) || "date_time".equals(input)) {
        formatter = ISODateTimeFormat.dateTime();
    } else if ("dateTimeNoMillis".equals(input) || "date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.dateTimeNoMillis();
    } else if ("hour".equals(input)) {
        formatter = ISODateTimeFormat.hour();
    } else if ("hourMinute".equals(input) || "hour_minute".equals(input)) {
        formatter = ISODateTimeFormat.hourMinute();
    } else if ("hourMinuteSecond".equals(input) || "hour_minute_second".equals(input)) {
        formatter = ISODateTimeFormat.hourMinuteSecond();
    } else if ("hourMinuteSecondFraction".equals(input) || "hour_minute_second_fraction".equals(input)) {
        formatter = ISODateTimeFormat.hourMinuteSecondFraction();
    } else if ("hourMinuteSecondMillis".equals(input) || "hour_minute_second_millis".equals(input)) {
        formatter = ISODateTimeFormat.hourMinuteSecondMillis();
    } else if ("ordinalDate".equals(input) || "ordinal_date".equals(input)) {
        formatter = ISODateTimeFormat.ordinalDate();
    } else if ("ordinalDateTime".equals(input) || "ordinal_date_time".equals(input)) {
        formatter = ISODateTimeFormat.ordinalDateTime();
    } else if ("ordinalDateTimeNoMillis".equals(input) || "ordinal_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.ordinalDateTimeNoMillis();
    } else if ("time".equals(input)) {
        formatter = ISODateTimeFormat.time();
    } else if ("tTime".equals(input) || "t_time".equals(input)) {
        formatter = ISODateTimeFormat.tTime();
    } else if ("tTimeNoMillis".equals(input) || "t_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.tTimeNoMillis();
    } else if ("weekDate".equals(input) || "week_date".equals(input)) {
        formatter = ISODateTimeFormat.weekDate();
    } else if ("weekDateTime".equals(input) || "week_date_time".equals(input)) {
        formatter = ISODateTimeFormat.weekDateTime();
    } else if ("weekyear".equals(input) || "week_year".equals(input)) {
        formatter = ISODateTimeFormat.weekyear();
    } else if ("weekyearWeek".equals(input)) {
        formatter = ISODateTimeFormat.weekyearWeek();
    } else if ("year".equals(input)) {
        formatter = ISODateTimeFormat.year();
    } else if ("yearMonth".equals(input) || "year_month".equals(input)) {
        formatter = ISODateTimeFormat.yearMonth();
    } else if ("yearMonthDay".equals(input) || "year_month_day".equals(input)) {
        formatter = ISODateTimeFormat.yearMonthDay();
    } else if (StringUtils.isNotBlank(input) && input.contains("||")) {
        String[] formats = StringUtils.split(input, "||");
        DateTimeParser[] parsers = new DateTimeParser[formats.length];

        if (formats.length == 1) {
            formatter = forPattern(input, locale).parser();
        } else {
            DateTimeFormatter dateTimeFormatter = null;
            for (int i = 0; i < formats.length; i++) {
                FormatDateTimeFormatter currentFormatter = forPattern(formats[i], locale);
                DateTimeFormatter currentParser = currentFormatter.parser();
                if (dateTimeFormatter == null) {
                    dateTimeFormatter = currentFormatter.printer();
                }
                parsers[i] = currentParser.getParser();
            }

            DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
                    .append(dateTimeFormatter.withZone(DateTimeZone.UTC).getPrinter(), parsers);
            formatter = builder.toFormatter();
        }
    } else {
        try {

            formatter = DateTimeFormat.forPattern(input);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Invalid format: [" + input + "]: " + e.getMessage(), e);
        }
    }

    return new FormatDateTimeFormatter(input, formatter.withZone(DateTimeZone.UTC), locale);
}

From source file:com.tuplejump.stargate.lucene.Dates.java

License:Apache License

/**
 * Parses a joda based pattern, including some named ones (similar to the built in Joda ISO ones).
 *///from   www . j  a  v  a 2 s. c  om
public static FormatDateTimeFormatter forPattern(String input, Locale locale) {
    if (StringUtils.isNotBlank(input)) {
        input = input.trim();
    }
    DateTimeFormatter formatter;
    if (input == null || input.length() == 0) {
        formatter = ISODateTimeFormat.yearMonthDay();
    } else if ("basicDate".equals(input) || "basic_date".equals(input)) {
        formatter = ISODateTimeFormat.basicDate();
    } else if ("basicDateTime".equals(input) || "basic_date_time".equals(input)) {
        formatter = ISODateTimeFormat.basicDateTime();
    } else if ("basicDateTimeNoMillis".equals(input) || "basic_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicDateTimeNoMillis();
    } else if ("basicOrdinalDate".equals(input) || "basic_ordinal_date".equals(input)) {
        formatter = ISODateTimeFormat.basicOrdinalDate();
    } else if ("basicOrdinalDateTime".equals(input) || "basic_ordinal_date_time".equals(input)) {
        formatter = ISODateTimeFormat.basicOrdinalDateTime();
    } else if ("basicOrdinalDateTimeNoMillis".equals(input)
            || "basic_ordinal_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicOrdinalDateTimeNoMillis();
    } else if ("basicTime".equals(input) || "basic_time".equals(input)) {
        formatter = ISODateTimeFormat.basicTime();
    } else if ("basicTimeNoMillis".equals(input) || "basic_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicTimeNoMillis();
    } else if ("basicTTime".equals(input) || "basic_t_Time".equals(input)) {
        formatter = ISODateTimeFormat.basicTTime();
    } else if ("basicTTimeNoMillis".equals(input) || "basic_t_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicTTimeNoMillis();
    } else if ("basicWeekDate".equals(input) || "basic_week_date".equals(input)) {
        formatter = ISODateTimeFormat.basicWeekDate();
    } else if ("basicWeekDateTime".equals(input) || "basic_week_date_time".equals(input)) {
        formatter = ISODateTimeFormat.basicWeekDateTime();
    } else if ("basicWeekDateTimeNoMillis".equals(input) || "basic_week_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicWeekDateTimeNoMillis();
    } else if ("date".equals(input)) {
        formatter = ISODateTimeFormat.date();
    } else if ("dateHour".equals(input) || "date_hour".equals(input)) {
        formatter = ISODateTimeFormat.dateHour();
    } else if ("dateHourMinute".equals(input) || "date_hour_minute".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinute();
    } else if ("dateHourMinuteSecond".equals(input) || "date_hour_minute_second".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinuteSecond();
    } else if ("dateHourMinuteSecondFraction".equals(input)
            || "date_hour_minute_second_fraction".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinuteSecondFraction();
    } else if ("dateHourMinuteSecondMillis".equals(input) || "date_hour_minute_second_millis".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinuteSecondMillis();
    } else if ("dateOptionalTime".equals(input) || "date_optional_time".equals(input)) {
        // in this case, we have a separate parser and printer since the dataOptionalTimeParser can't print
        // this sucks we should use the root local by default and not be dependent on the node
        return new FormatDateTimeFormatter(input,
                ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC),
                ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC), locale);
    } else if ("dateTime".equals(input) || "date_time".equals(input)) {
        formatter = ISODateTimeFormat.dateTime();
    } else if ("dateTimeNoMillis".equals(input) || "date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.dateTimeNoMillis();
    } else if ("hour".equals(input)) {
        formatter = ISODateTimeFormat.hour();
    } else if ("hourMinute".equals(input) || "hour_minute".equals(input)) {
        formatter = ISODateTimeFormat.hourMinute();
    } else if ("hourMinuteSecond".equals(input) || "hour_minute_second".equals(input)) {
        formatter = ISODateTimeFormat.hourMinuteSecond();
    } else if ("hourMinuteSecondFraction".equals(input) || "hour_minute_second_fraction".equals(input)) {
        formatter = ISODateTimeFormat.hourMinuteSecondFraction();
    } else if ("hourMinuteSecondMillis".equals(input) || "hour_minute_second_millis".equals(input)) {
        formatter = ISODateTimeFormat.hourMinuteSecondMillis();
    } else if ("ordinalDate".equals(input) || "ordinal_date".equals(input)) {
        formatter = ISODateTimeFormat.ordinalDate();
    } else if ("ordinalDateTime".equals(input) || "ordinal_date_time".equals(input)) {
        formatter = ISODateTimeFormat.ordinalDateTime();
    } else if ("ordinalDateTimeNoMillis".equals(input) || "ordinal_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.ordinalDateTimeNoMillis();
    } else if ("time".equals(input)) {
        formatter = ISODateTimeFormat.time();
    } else if ("tTime".equals(input) || "t_time".equals(input)) {
        formatter = ISODateTimeFormat.tTime();
    } else if ("tTimeNoMillis".equals(input) || "t_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.tTimeNoMillis();
    } else if ("weekDate".equals(input) || "week_date".equals(input)) {
        formatter = ISODateTimeFormat.weekDate();
    } else if ("weekDateTime".equals(input) || "week_date_time".equals(input)) {
        formatter = ISODateTimeFormat.weekDateTime();
    } else if ("weekyear".equals(input) || "week_year".equals(input)) {
        formatter = ISODateTimeFormat.weekyear();
    } else if ("weekyearWeek".equals(input)) {
        formatter = ISODateTimeFormat.weekyearWeek();
    } else if ("year".equals(input)) {
        formatter = ISODateTimeFormat.year();
    } else if ("yearMonth".equals(input) || "year_month".equals(input)) {
        formatter = ISODateTimeFormat.yearMonth();
    } else if ("yearMonthDay".equals(input) || "year_month_day".equals(input)) {
        formatter = ISODateTimeFormat.yearMonthDay();
    } else if (StringUtils.isNotBlank(input) && input.contains("||")) {
        String[] formats = StringUtils.split(input, "||");
        DateTimeParser[] parsers = new DateTimeParser[formats.length];

        if (formats.length == 1) {
            formatter = forPattern(input, locale).parser();
        } else {
            DateTimeFormatter dateTimeFormatter = null;
            for (int i = 0; i < formats.length; i++) {
                FormatDateTimeFormatter currentFormatter = forPattern(formats[i], locale);
                DateTimeFormatter currentParser = currentFormatter.parser();
                if (dateTimeFormatter == null) {
                    dateTimeFormatter = currentFormatter.printer();
                }
                parsers[i] = currentParser.getParser();
            }
            DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
                    .append(dateTimeFormatter.withZone(DateTimeZone.UTC).getPrinter(), parsers);
            formatter = builder.toFormatter();
        }
    } else {
        try {

            formatter = DateTimeFormat.forPattern(input);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Invalid format: [" + input + "]: " + e.getMessage(), e);
        }
    }

    return new FormatDateTimeFormatter(input, formatter.withZone(DateTimeZone.UTC), locale);
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo.java

License:Open Source License

protected Literal getDateTime(Map<String, String[]> queryParameters) {
    String submittedPrec = BLANK_SENTINEL;
    try {// www .j  av  a  2 s. c  om
        submittedPrec = getSubmittedPrecision(queryParameters);
    } catch (Exception e) {
        log.error("could not get submitted precsion", e);
    }

    if (BLANK_SENTINEL.equals(submittedPrec))
        return null;

    Integer year = parseToInt(getFieldName() + "-year", queryParameters);

    //this is the case where date has not been filled out at all.        
    if (year == null)
        return null;

    Integer month = parseToInt(getFieldName() + "-month", queryParameters);
    if (month == null || month == 0)
        month = 1;
    Integer day = parseToInt(getFieldName() + "-day", queryParameters);
    if (day == null || day == 0)
        day = 1;
    Integer hour = parseToInt(getFieldName() + "-hour", queryParameters);
    if (hour == null)
        hour = 0;
    Integer minute = parseToInt(getFieldName() + "-minute", queryParameters);
    if (minute == null)
        minute = 0;
    Integer second = parseToInt(getFieldName() + "-second", queryParameters);
    if (second == null)
        second = 0;

    DateTime value = new DateTime(year.intValue(), month.intValue(), day.intValue(), hour.intValue(),
            minute.intValue(), second.intValue(), 0/*millis*/
    );

    return ResourceFactory.createTypedLiteral(
            ISODateTimeFormat.dateHourMinuteSecond().print(value), /*does not include timezone*/
            XSDDatatype.XSDdateTime);
}