Example usage for org.joda.time DateTime now

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

Introduction

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

Prototype

public static DateTime now() 

Source Link

Document

Obtains a DateTime set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:ca.phon.app.session.editor.actions.BackupCommandHook.java

License:Open Source License

private void backupSession(Project project, Session session) throws IOException, ZipException {
    // save current session to backup zip
    final String zipFilePath = project.getLocation() + File.separator + "backups.zip";
    // create backup zip if necessary
    final ZipFile zipFile = new ZipFile(zipFilePath);

    final DateTime dateTime = DateTime.now();
    final DateTimeFormatterBuilder formatterBuilder = new DateTimeFormatterBuilder();
    final String dateSuffix = formatterBuilder.appendYear(4, 4).appendLiteral("-").appendMonthOfYear(2)
            .appendLiteral("-").appendDayOfMonth(2).appendLiteral("_").appendHourOfDay(2).appendLiteral(".")
            .appendMinuteOfHour(2).appendLiteral(".").appendSecondOfMinute(2).toFormatter().print(dateTime);

    final String zipName = session.getName() + "_" + dateSuffix + ".xml";

    final File sessionFile = new File(project.getLocation(),
            session.getCorpus() + File.separator + session.getName() + ".xml");

    if (sessionFile.exists()) {
        if (!zipFile.getFile().exists()) {
            ZipParameters parameters = new ZipParameters();

            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

            zipFile.createZipFile(new File(project.getLocation() + File.separator + "project.xml"), parameters);
        }/*from w w w .  ja v a 2  s.  co  m*/
        // add to zip file
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

        parameters.setFileNameInZip(session.getCorpus() + File.separator + zipName);
        parameters.setSourceExternalStream(true);

        FileInputStream fin = null;
        try {
            fin = new FileInputStream(sessionFile);
            zipFile.addStream(fin, parameters);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);

        } finally {
            if (fin != null)
                fin.close();
        }
    }
}

From source file:ca.phon.app.workspace.FolderProjectList.java

License:Open Source License

public void onArchiveProject(PhonActionEvent pae) {
    final LocalProjectButton btn = (LocalProjectButton) pae.getData();
    final ProjectFactory factory = new ProjectFactory();
    try {//from  www  .ja v a  2s.c om
        final Project project = factory.openProject(btn.getProjectFile());
        final String today = DateFormatter.dateTimeToString(DateTime.now());

        File backupsDir = new File(Workspace.userWorkspaceFolder(), "backups");
        if (!backupsDir.exists()) {
            backupsDir.mkdirs();
        }
        File destFile = new File(backupsDir, project.getName() + "-" + today + ".zip");

        int fIdx = 1;
        while (destFile.exists()) {
            destFile = new File(Workspace.userWorkspaceFolder(),
                    "backups" + File.separator + project.getName() + "-" + today + "(" + (fIdx++) + ").zip");
        }

        ProjectArchiveTask task = new ProjectArchiveTask(project, destFile, true, false);
        task.setName("Archiving: " + project.getName());
        task.addTaskListener(new PhonTaskListener() {

            @Override
            public void statusChanged(PhonTask task, TaskStatus oldStatus, TaskStatus newStatus) {
                if (newStatus == TaskStatus.FINISHED) {
                    long curTime = System.currentTimeMillis();
                    long totalTime = task.getStartTime() - curTime;

                    if (totalTime < 500) {
                        try {
                            Thread.sleep(500 - totalTime);
                        } catch (InterruptedException e) {
                        }
                    }

                    // refresh
                    refresh();
                } else if (newStatus == TaskStatus.ERROR) {
                    // display dialog
                    NativeDialogs.showMessageDialog(CommonModuleFrame.getCurrentFrame(),
                            new NativeDialogListener() {
                                @Override
                                public void nativeDialogEvent(NativeDialogEvent event) {
                                }
                            }, null, "Error archiving project",
                            "Reason: " + (task.getException() != null ? task.getException().getMessage()
                                    : "no reason given"));

                    refresh();
                }
            }

            @Override
            public void propertyChanged(PhonTask task, String property, Object oldValue, Object newValue) {
            }
        });

        PhonTaskButton newBtn = new PhonTaskButton(task);

        int idx = projectButtons.indexOf(btn);
        projectButtons.remove(idx);
        projectButtons.add(idx, newBtn);
        updateProjectList();

        PhonWorker.getInstance().invokeLater(task);

        //         HashMap<String, Object> initInfo = new HashMap<String, Object>();
        //         initInfo.put("project", project);
        //         ModuleInformation mi = ResourceLocator.getInstance().getModuleInformationByAction("ca.phon.modules.project.ProjectArchiveController");
        //         LoadModule lm = new LoadModule(mi, initInfo);
        //         lm.start();
    } catch (IOException e) {
        LOGGER.severe(e.getMessage());
    } catch (ProjectConfigurationException e) {
        LOGGER.severe(e.getMessage());
    }
}

From source file:ca.phon.csv2phon.wizard.ParticipantsStep.java

License:Open Source License

public List<Participant> getParticipants() {
    List<Participant> retVal = new ArrayList<Participant>();

    if (getSettings() != null) {
        for (ParticipantType pt : getSettings().getParticipant()) {
            retVal.add(CSVParticipantUtil.copyXmlParticipant(SessionFactory.newFactory(), pt, DateTime.now()));
        }//w w  w .  jav  a2 s .co m
    }

    return retVal;
}

From source file:ca.phon.query.analysis.ReportDesignStep.java

License:Open Source License

@Override
public String op(QueryAnalysisResult obj) {
    final ReportBuilder builder = ReportBuilderFactory.getInstance().getBuilder("CSV");

    final QueryFactory qf = QueryManager.getSharedInstance().createQueryFactory();
    final Query q = qf.createQuery();
    q.setDate(DateTime.now());
    q.setName("internal");

    final ResultSet[] resultSets = new ResultSet[obj.getQueryResults().keySet().size()];
    int idx = 0;/*ww  w .ja  v  a  2 s . co  m*/
    for (SessionPath sp : obj.getQueryResults().keySet()) {
        resultSets[idx++] = obj.getQueryResults().get(sp);
    }

    final ByteArrayOutputStream bout = new ByteArrayOutputStream();

    String retVal = "";
    try {
        builder.buildReport(reportDesign, obj.getInput().getProject(), q, resultSets, bout);

        retVal = bout.toString("UTF-8");
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
    } catch (ReportBuilderException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
    return retVal;
}

From source file:ca.phon.query.db.xml.XMLQueryFactory.java

License:Open Source License

@Override
public Query createQuery() {
    // Ensure certain attributes exist with default values 
    XMLQuery query = new XMLQuery();
    query.setUUID(UUID.randomUUID());
    query.setDate(DateTime.now());
    return query;
}

From source file:ca.phon.query.db.xml.XMLQueryFactory.java

License:Open Source License

@Override
public Query createQuery(Project project) {
    // Get the next available number
    int max = 0;// ww w.j a va2 s.c  om
    File queryPath = XMLResultSetManager.getQueriesPath(project);
    if (!queryPath.exists() && !queryPath.mkdirs())
        return null;

    for (String query : queryPath.list()) {
        if (query.startsWith("query")) {
            try {
                max = Math.max(max, Integer.parseInt(query.substring(5)));
            } catch (NumberFormatException exc) {
                /* don't need to deal with this */ }
        }
    }

    ++max;

    // Ensure certain attributes exist with default values 
    XMLQuery query = new XMLQuery();
    query.setName(String.format("query%03d", max));
    query.setUUID(UUID.randomUUID());
    query.setDate(DateTime.now());
    return query;
}

From source file:ca.phon.session.io.xml.v12.XMLSessionWriter_v12.java

License:Open Source License

/**
 * Create a new jaxb version of the session
 * /* ww  w. j  a va2 s .c  o  m*/
 * @param session
 * @return an version of the session use-able by jaxb 
 */
private JAXBElement<SessionType> toSessionType(Session session) throws IOException {
    final ObjectFactory factory = new ObjectFactory();
    final SessionType retVal = factory.createSessionType();

    // header data
    retVal.setVersion("PB1.2");
    retVal.setId(session.getName());
    retVal.setCorpus(session.getCorpus());

    final HeaderType headerData = factory.createHeaderType();
    if (session.getMediaLocation() != null && session.getMediaLocation().length() > 0) {
        headerData.setMedia(session.getMediaLocation());
    }
    final DateTime date = (session.getDate() == null ? DateTime.now() : session.getDate());
    try {
        final DatatypeFactory df = DatatypeFactory.newInstance();
        final XMLGregorianCalendar cal = df.newXMLGregorianCalendar(date.toGregorianCalendar());
        cal.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
        headerData.setDate(cal);
    } catch (DatatypeConfigurationException e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
    }
    final String lang = session.getLanguage();
    if (lang != null && lang.length() > 0) {
        final String langs[] = lang.split("\\p{Space}");
        for (String l : langs) {
            headerData.getLanguage().add(l);
        }
    }
    retVal.setHeader(headerData);

    final TranscriptType transcript = factory.createTranscriptType();
    // commets
    for (int i = 0; i < session.getMetadata().getNumberOfComments(); i++) {
        final Comment c = session.getMetadata().getComment(i);
        final CommentType ct = copyComment(factory, c);
        transcript.getUOrComment().add(ct);
    }

    // participants
    final ParticipantsType parts = factory.createParticipantsType();
    for (int i = 0; i < session.getParticipantCount(); i++) {
        final Participant part = session.getParticipant(i);
        final ParticipantType pt = copyParticipant(factory, part);
        parts.getParticipant().add(pt);
    }
    retVal.setParticipants(parts);

    // transcribers
    final TranscribersType tt = factory.createTranscribersType();
    for (int i = 0; i < session.getTranscriberCount(); i++) {
        final Transcriber tr = session.getTranscriber(i);
        final TranscriberType trt = copyTranscriber(factory, tr);
        tt.getTranscriber().add(trt);
    }
    retVal.setTranscribers(tt);

    // tier info/ordering
    final UserTiersType utt = factory.createUserTiersType();
    for (int i = 0; i < session.getUserTierCount(); i++) {
        final TierDescription td = session.getUserTier(i);
        final UserTierType tierType = copyTierDescription(factory, td);
        utt.getUserTier().add(tierType);
    }
    retVal.setUserTiers(utt);

    final TierOrderType tot = factory.createTierOrderType();
    for (TierViewItem tvi : session.getTierView()) {
        final TvType tvt = copyTierViewItem(factory, tvi);
        tot.getTier().add(tvt);
    }
    retVal.setTierOrder(tot);

    // session data
    for (int i = 0; i < session.getRecordCount(); i++) {
        final Record record = session.getRecord(i);

        // insert comments first
        for (int j = 0; j < record.getNumberOfComments(); j++) {
            final Comment com = record.getComment(j);
            final CommentType ct = copyComment(factory, com);
            transcript.getUOrComment().add(ct);
        }

        // copy record data
        final RecordType rt = copyRecord(factory, retVal, record);

        rt.setId(record.getUuid().toString());

        if (record.isExcludeFromSearches())
            rt.setExcludeFromSearches(record.isExcludeFromSearches());

        // setup participant
        if (record.getSpeaker() != null) {
            for (ParticipantType pt : parts.getParticipant()) {
                if (pt.getId().equals(record.getSpeaker().getId())) {
                    rt.setSpeaker(pt);
                    break;
                }
            }
        }

        transcript.getUOrComment().add(rt);
    }
    retVal.setTranscript(transcript);

    return factory.createSession(retVal);
}

From source file:ca.phon.ui.DateTimeDocument.java

License:Open Source License

public DateTime getDateTime() {
    DateTime retVal = DateTime.now();

    String dateText = "";
    try {/*from  ww  w  .  j  a v a  2 s .c  o  m*/
        dateText = getText(0, getLength());
    } catch (BadLocationException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }

    try {
        retVal = dateFormatter.parseDateTime(dateText);
    } catch (Exception e) {
        LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
    }

    return retVal;
}

From source file:ca.phon.ui.participant.ParticipantEditor.java

License:Open Source License

public static boolean editParticipant(JFrame parent, Participant part, List<Participant> otherParts) {
    ParticipantEditor editor = new ParticipantEditor(parent, part, DateTime.now(), otherParts);
    editor.pack();// w  w  w.  j ava  2s  .c  o  m
    editor.setLocationRelativeTo(parent);
    editor.setVisible(true);

    return editor.wasCanceled;
}

From source file:ca.phon.ui.participant.ParticipantTableModel.java

License:Open Source License

private Object getValueForField(ParticipantTableField field) {
    if (field == ParticipantTableField.Name) {
        return (participant.getName() == null ? new String() : participant.getName());
    } else if (field == ParticipantTableField.Age) {
        return (participant.getAge(sessionDate) == null ? new Period() : participant.getAge(sessionDate));
    } else if (field == ParticipantTableField.Birthday) {
        return (participant.getBirthDate() == null ? DateTime.now() : participant.getBirthDate());
    } else if (field == ParticipantTableField.Education) {
        return (participant.getEducation() == null ? new String() : participant.getEducation());
    } else if (field == ParticipantTableField.Group) {
        return (participant.getGroup() == null ? new String() : participant.getGroup());
    } else if (field == ParticipantTableField.Sex) {
        return (participant.getSex() == null ? Sex.MALE : participant.getSex());
    } else if (field == ParticipantTableField.Role) {
        return (participant.getRole() == null ? new String() : participant.getRole());
    } else if (field == ParticipantTableField.Language) {
        return (participant.getLanguage() == null ? new String() : participant.getLanguage());
    } else {/*from  w  w  w.  ja v a2 s  .c  o  m*/
        return new String();
    }
}