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

public String toString(String pattern) 

Source Link

Document

Output the instant using the specified format pattern.

Usage

From source file:com.pacoapp.paco.ui.RawDataActivity.java

License:Open Source License

private void fillData() {
    List<String> nameAndTime = new ArrayList<String>();
    for (Event event : experiment.getEvents()) {
        StringBuilder buf = new StringBuilder();
        boolean first = true;
        for (Output output : event.getResponses()) {
            if (first) {
                first = false;//from w  w  w.j  a  v  a2  s. c  om
            } else {
                buf.append(",");
            }
            buf.append(output.getName());
            buf.append("=");
            Input2 input = ExperimentHelper.getInputWithName(experiment.getExperimentDAO(), output.getName(),
                    null);
            if (input != null && input.getResponseType() != null
                    && (input.getResponseType().equals(Input2.PHOTO)
                            || input.getResponseType().equals(Input2.SOUND))) {
                buf.append("<multimedia:" + input.getResponseType() + ">");
            } else {
                buf.append(output.getAnswer());
            }
        }
        DateTime responseTime = event.getResponseTime();
        String signalTime = null;
        if (responseTime == null) {
            DateTime scheduledTime = event.getScheduledTime();
            if (scheduledTime != null) {
                signalTime = scheduledTime.toString(df) + ": " + getString(R.string.missed_signal_value);
            } else {
                signalTime = getString(R.string.missed_signal_value);
            }
        } else {
            signalTime = responseTime.toString(df);
        }
        nameAndTime.add(signalTime + ": " + buf.toString());
    }
    list = (ListView) findViewById(R.id.eventList);
    list.setAdapter(new ArrayAdapter(this, R.layout.schedule_row, nameAndTime));
}

From source file:com.pinterest.teletraan.worker.AutoPromoter.java

License:Apache License

public <E> E getScheduledCheckResult(EnvironBean currEnvBean, PromoteBean promoteBean, List<E> candidates,
        Function<E, Long> timeSupplier) throws Exception {

    E ret = null;/*from  w w  w.ja va2s  .c  o m*/

    //If we have a cron schedule set, foreach candidates, we compute the earilest due
    // time per schedule for the build.
    CronExpression cronExpression = new CronExpression(promoteBean.getSchedule());
    for (E bean : candidates) {
        DateTime checkTime = new DateTime(timeSupplier.apply(bean));
        if (promoteBean.getDelay() > 0) {
            checkTime.plusMinutes(promoteBean.getDelay());
        }
        DateTime autoDeployDueDate = new DateTime(cronExpression.getNextValidTimeAfter(checkTime.toDate()));
        LOG.info("Auto deploy due time is {} for check time {} for Environment {}",
                autoDeployDueDate.toString(ISODateTimeFormat.dateTime()), checkTime.toString(),
                currEnvBean.getEnv_name());

        if (!autoDeployDueDate.isAfterNow()) {
            ret = bean;
            break;
        }
    }
    return ret;
}

From source file:com.ro.ssc.app.client.service.impl.DataProviderImplHelper.java

public static List<DailyData> getListPerDay(Map<String, User> userData, LocalTime time,
        Map<String, Map<String, ShiftData>> shiftData, Set<String> excludedGates, String userName,
        DateTime iniDate, DateTime endDate) {
    List<DailyData> result = new ArrayList();
    Collections.sort(userData.get(userName).getEvents(),
            (c1, c2) -> c1.getEventDateTime().compareTo(c2.getEventDateTime()));
    Map<Pair<DateTime, DateTime>, List<Pair<Event, Event>>> eventsPerDay;
    Map<DateTime, List<Event>> wrongPerDay;
    Set<String> usedDates = new HashSet<>();
    String userId = userData.get(userName).getUserId().trim();
    if (Configuration.IS_EXPIRED.getAsBoolean()) {
        eventsPerDay = splitPerDay(time,
                applyExcludeLogic(excludedGates, userData.get(userName).getEvents()).get(0), iniDate, endDate);
        wrongPerDay = splitPerDayWrong(time,
                applyExcludeLogic(excludedGates, userData.get(userName).getEvents()).get(1), iniDate, endDate);
    } else {//ww  w  .j  a v a  2 s  .  c  o m
        eventsPerDay = splitPerDay(time,
                applyExcludeLogic2(excludedGates, userData.get(userName).getEvents()).get(0), iniDate, endDate);
        wrongPerDay = splitPerDayWrong(time,
                applyExcludeLogic2(excludedGates, userData.get(userName).getEvents()).get(1), iniDate, endDate);

    }

    for (DateTime date = iniDate.withTimeAtStartOfDay(); date
            .isBefore(endDate.plusDays(1).withTimeAtStartOfDay()); date = date.plusDays(1)) {
        final DateTime currentDateAsDateTime = date;

        for (Map.Entry<Pair<DateTime, DateTime>, List<Pair<Event, Event>>> entry : eventsPerDay.entrySet()) {
            if (entry.getKey().getKey().withTimeAtStartOfDay().isEqual(currentDateAsDateTime)) {

                Long duration = 0l;
                for (Pair<Event, Event> pair : entry.getValue()) {
                    duration = duration + pair.getValue().getEventDateTime().getMillis()
                            - pair.getKey().getEventDateTime().getMillis();
                }
                Long pause = entry.getKey().getValue().getMillis() - entry.getKey().getKey().getMillis()
                        - duration;
                Long overtime = 0l;
                Long latetime = 0l;
                Long earlytime = 0l;
                if (shiftData.containsKey(userId)) {
                    final Map<String, ShiftData> shiftDataMapForUser = shiftData.get(userId);
                    if (shiftDataMapForUser.containsKey(currentDateAsDateTime.toString(dtf3))) {

                        ShiftData shiftDataInCurrentDate = shiftDataMapForUser
                                .get(currentDateAsDateTime.toString(dtf3));
                        if (shiftDataInCurrentDate.getShiftId().equals("0")) {
                            if (shiftDataInCurrentDate.isHasOvertime()) {
                                overtime = duration;
                            }
                        } else {
                            LocalTime officialStart = LocalTime
                                    .from(dtf4.parse(shiftDataInCurrentDate.getShiftStartHour()));
                            LocalTime officialEnd = LocalTime
                                    .from(dtf4.parse(shiftDataInCurrentDate.getShiftEndHour()));
                            long dailyPause = Long.valueOf(shiftDataInCurrentDate.getShiftBreakTime()) * 1000
                                    * 60l;
                            long dailyHours = officialEnd.isAfter(officialStart)
                                    ? 1000 * (officialEnd.toSecondOfDay() - officialStart.toSecondOfDay())
                                    : 1000 * (officialEnd.toSecondOfDay()
                                            + (24 * 60 * 60 - officialStart.toSecondOfDay()));
                            if (shiftDataInCurrentDate.isHasOvertime()) {

                                if (pause > dailyPause) {
                                    overtime = duration - dailyHours + dailyPause;
                                } else {
                                    overtime = duration + pause - dailyHours;
                                    duration = duration - (dailyPause - pause) > 0
                                            ? duration - (dailyPause - pause)
                                            : 0;
                                    pause = dailyPause;
                                }
                                log.debug(userName + " data " + currentDateAsDateTime.toString(dtf3)
                                        + " overtime " + overtime);
                            } else {
                                if (duration < dailyHours - dailyPause) {
                                    overtime = duration - dailyHours + dailyPause;
                                }
                            }
                            earlytime = entry.getKey().getValue().getSecondOfDay() < officialEnd.toSecondOfDay()
                                    ? 1000 * (officialEnd.toSecondOfDay()
                                            - entry.getKey().getValue().getSecondOfDay())
                                    : 0l;
                            latetime = entry.getKey().getKey().getSecondOfDay() > officialStart.toSecondOfDay()
                                    ? 1000 * (entry.getKey().getKey().getSecondOfDay()
                                            - officialStart.toSecondOfDay())
                                    : 0l;
                        }
                    }
                }
                result.add(new DailyData(userId, date, entry.getKey().getKey().toString(dtf),
                        entry.getKey().getValue().toString(dtf), earlytime, duration, duration, pause, overtime,
                        latetime, wrongPerDay.get(currentDateAsDateTime)));
                usedDates.add(currentDateAsDateTime.toString(dtf3));
            }

        }

    }

    for (String day : getNeededPresence(userData, shiftData, userName, iniDate, endDate)) {

        if (!usedDates.contains(day)) {
            ShiftData shiftDataInCurrentDate = shiftData.get(userId).get(day);
            LocalTime officialStart = LocalTime.from(dtf4.parse(shiftDataInCurrentDate.getShiftStartHour()));
            LocalTime officialEnd = LocalTime.from(dtf4.parse(shiftDataInCurrentDate.getShiftEndHour()));
            long dailyPause = Long.valueOf(shiftDataInCurrentDate.getShiftBreakTime()) * 1000 * 60l;
            long dailyHours = officialEnd.isAfter(officialStart)
                    ? 1000 * (officialEnd.toSecondOfDay() - officialStart.toSecondOfDay())
                    : 1000 * (officialEnd.toSecondOfDay() + (24 * 60 * 60 - officialStart.toSecondOfDay()));

            if (wrongPerDay.containsKey(DateTime.parse(day, dtf3))) {
                if (wrongPerDay.get(DateTime.parse(day, dtf3)).size() > 0) {
                    String ev = wrongPerDay.get(DateTime.parse(day, dtf3)).get(0).getEventDateTime()
                            .toString(dtf);
                    Boolean isIn = wrongPerDay.get(DateTime.parse(day, dtf3)).get(0).getAddr().contains("In");

                    result.add(new DailyData(userId, DateTime.parse(day, dtf3), isIn == true ? ev : "",
                            isIn == false ? ev : "", 0, 0, 0, 0, dailyPause - dailyHours, 0,
                            wrongPerDay.get(DateTime.parse(day, dtf3))));
                } else {
                    result.add(new DailyData(userId, DateTime.parse(day, dtf3), "", "", 0, 0, 0, 0,
                            dailyPause - dailyHours, 0, new ArrayList<>()));

                }
            } else {
                result.add(new DailyData(userId, DateTime.parse(day, dtf3), "", "", 0, 0, 0, 0,
                        dailyPause - dailyHours, 0, new ArrayList<>()));

            }
        }
    }

    return result;
}

From source file:com.rubenlaguna.en4j.sync.SyncAction.java

License:Open Source License

public void actionPerformed(ActionEvent e) {
    // TODO implement action body
    final SynchronizationService sservice = Lookup.getDefault().lookup(SynchronizationService.class);

    Runnable task = new Runnable() {

        public void run() {
            DateTime startTime = new DateTime();
            StatusDisplayer.getDefault().setStatusText("Sync started at " + startTime.toString("HH:mm"));

            if (toolbarPresenter.startAnimator()) { //dont run if it was already running
                sservice.sync();/*  w ww. j a v a  2s  .  c  o m*/
                toolbarPresenter.stopAnimator();
                if (sservice.isSyncFailed()) {
                    StatusDisplayer.getDefault().setStatusText("Sync failed.");
                } else {
                    DateTime finishTime = new DateTime();
                    Duration dur = new Duration(startTime, finishTime);
                    Minutes minutes = dur.toPeriod().toStandardMinutes();
                    Seconds seconds = dur.toPeriod().minus(minutes).toStandardSeconds();
                    final String message = "sync finished at " + finishTime.toString("HH:mm") + ". Sync took "
                            + minutes.getMinutes() + " minutes and " + seconds.getSeconds() + " seconds.";
                    final StatusDisplayer.Message sbMess = StatusDisplayer.getDefault().setStatusText(message,
                            1);
                    RP.post(new Runnable() {
                        public void run() {
                            sbMess.clear(10000);
                        }
                    });
                }
            }
        }
    };
    RP.post(task);
}

From source file:com.salesmanBuddy.dao.JDBCSalesmanBuddyDAO.java

License:Open Source License

private String printTimeDateForReports(DateTime time) {
    DateTimeFormatter fmt = DateTimeFormat.forPattern("EEEE MMMM d, yyyy 'at' K a");
    return time.toString(fmt);
}

From source file:com.sam.moca.server.db.translate.BaseDialect.java

License:Open Source License

@Override
public PreparedStatement prepareStatement(Connection conn, SQLBinder binder, BindList bindList)
        throws SQLException, MissingVariableException {
    PreparedStatement pstmt;//from   w w  w . j ava2  s.c o m
    CallableStatement call = null;

    if (!bindList.hasReferences()) {
        pstmt = conn.prepareStatement(binder.getBoundStatement(), ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_READ_ONLY);
    } else {
        call = conn.prepareCall(binder.getBoundStatement(), ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_READ_ONLY);
        pstmt = call;
    }

    // Go through the passed-in bound variables. If it's a
    // reference type, register it as an in/out parameter.
    // Otherwise, just set its value on the CallableStatement.
    List<String> bindNames = binder.getNames();
    for (int i = 0; i < bindNames.size(); i++) {
        String name = bindNames.get(i);
        Object value = bindList.getValue(name);
        MocaType type = bindList.getType(name);

        // If the variable is not present but used, it's
        // an error.
        if (type == null) {
            throw new MissingVariableException(name);
        }

        // Handle reference types
        if (type.equals(MocaType.INTEGER_REF)) {
            call.registerOutParameter(i + 1, Types.INTEGER);
        } else if (type.equals(MocaType.DOUBLE_REF)) {
            call.registerOutParameter(i + 1, Types.DOUBLE);
        } else if (type.equals(MocaType.STRING_REF)) {
            call.registerOutParameter(i + 1, Types.VARCHAR);
        }

        // Set input variables
        if (value == null) {
            pstmt.setNull(i + 1, type.getSQLType());
        } else if (type == MocaType.DATETIME) {
            if (value instanceof Date) {
                // For now we have to bind date times as strings
                // so that we don't have issues with oracle to_date
                // and to keep people from having to change all their
                // to_date calls
                Date timestamp = (Date) value;
                DateTime dateTime = new DateTime(timestamp.getTime());
                pstmt.setString(i + 1, dateTime.toString("YYYYMMddHHmmss"));
            } else {
                pstmt.setString(i + 1, String.valueOf(value));
            }
        } else {
            pstmt.setObject(i + 1, value);
        }
    }

    return pstmt;
}

From source file:com.sam.moca.server.db.translate.OracleDialect.java

License:Open Source License

@Override
public PreparedStatement prepareStatement(Connection conn, SQLBinder binder, BindList bindList)
        throws SQLException, MissingVariableException {

    Collection<String> foundNames = new LinkedHashSet<String>(binder.getNames());

    // If using reference variables, we must bind by position.
    if (bindList.hasReferences()) {
        return super.prepareStatement(conn, binder, bindList);
    } else {// w ww. j  a v a 2 s.  co m
        // If the statement starts with select, it's probably OK to bind by
        // name.  Otherwise, use the default JDBC positional binding
        // behavior.
        String sql = binder.getOriginalStatement().trim();

        if (sql.length() < 6 || !sql.substring(0, 6).equalsIgnoreCase("select")) {
            return super.prepareStatement(conn, binder, bindList);
        }

        PreparedStatement pstmt = conn.prepareStatement(binder.getOriginalStatement(),
                ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

        // If for some reason, we don't have an OraclePreparedStatement, then we may be using an alternate driver.  Just
        // set parameters by index.
        if (!(pstmt instanceof OraclePreparedStatement)) {
            pstmt.close();
            return super.prepareStatement(conn, binder, bindList);
        }

        // Oracle's extension of PreparedStatement allows us to bind variables by name.
        OraclePreparedStatement ostmt = (OraclePreparedStatement) pstmt;

        for (String name : foundNames) {

            // If the variable is not present but used, it's an error.
            if (!bindList.contains(name)) {
                throw new MissingVariableException(name);
            }

            Object value = bindList.getValue(name);
            MocaType type = bindList.getType(name);

            // Set input variables
            if (value == null) {
                ostmt.setNullAtName(name, type.getSQLType());
            } else if (type == MocaType.DATETIME) {
                if (value instanceof Date) {
                    // For now we have to bind date times as strings
                    // so that we don't have issues with oracle to_date
                    // and to keep people from having to change all their
                    // to_date calls
                    Date timestamp = (Date) value;
                    DateTime dateTime = new DateTime(timestamp.getTime());
                    ostmt.setStringAtName(name, dateTime.toString("YYYYMMddHHmmss"));
                } else {
                    ostmt.setStringAtName(name, String.valueOf(value));
                }
            } else {
                ostmt.setObjectAtName(name, value);
            }
        }

        return ostmt;
    }
}

From source file:com.sam.moca.server.log.MocaTraceMessaging.java

License:Open Source License

/***
 * A method that will log library version information.
 * @param MocaContext//from   ww w  .  j  av  a 2  s . c  o m
 * @see MocaContext
 */
public static void logLibraryVersions(MocaContext moca) {
    DateTime date = new DateTime();
    moca.logInfo("Tracing started " + date.toString("MM/dd/yyyy") + " at " + date.toString("HH:mm:ss"));

    String regFile = System.getProperty("com.sam.moca.config");
    if (regFile == null) {
        regFile = System.getenv("MOCA_REGISTRY");
    }

    moca.logInfo("");
    moca.logInfo("   Registry: " + (regFile != null ? regFile : "Not set"));
    // TODO the old version output host, port
    moca.logInfo("");
    moca.logInfo("Category        Library         Version");
    moca.logInfo("--------------- --------------- -------------------------");

    MocaResults results = DefaultServerContext.listLibraryVersions(moca, null);

    RowIterator rowIter = results.getRows();

    // Now we want to output the component library versions
    while (rowIter.next()) {
        String category = rowIter.getString("category");
        String library = rowIter.getString("library_name");
        String version = rowIter.getString("version");

        /* Log the library information to the new trace file. */
        moca.logInfo(String.format("%-15.15s %-15.15s %-25.25s", category != null ? category : "",
                library != null ? library : "", version != null ? version : ""));

    }
}

From source file:com.softtek.mdm.web.institution.UserController.java

/**
  * ??map/*ww  w.j a v  a 2  s  . c  o  m*/
  * 
  * @param uid
  * @param session
  * @return
  * @throws IOException
  */
private Map<String, String> getUserInfoMap(Integer uid, HttpSession session) throws IOException {
    UserModel user = null;
    try {
        user = userService.findOne(uid);
    } catch (Exception e) {
        logger.error("Method findOne invoked by userSerive cause error and the reason is: " + e.getMessage());
        throw e;
    }
    Map<String, String> maps = new HashMap<String, String>();
    maps.put("username", user.getUsername());
    maps.put("realname", user.getRealname());
    StructureModel temp = null;
    try {
        temp = structureService.getParents(user.getStructure().getId());
    } catch (Exception e) {
        logger.error("Method getParents invoked by structureService cause error and the reason is: "
                + e.getMessage());
        throw e;
    }
    if (temp != null) {
        String belongStr = temp.getName();
        while (temp.getParent() != null) {
            belongStr = StringUtil.insert(belongStr, temp.getParent().getName() + "/");
            temp = temp.getParent();
        }
        maps.put("department", belongStr);
    }
    maps.put("phone", user.getPhone());
    maps.put("email", user.getEmail());
    DateTime dt = new DateTime(user.getCreateTime().getTime());
    maps.put("createtime", dt.toString("yyyy/MM/dd HH:mm:ss"));
    OrganizationModel organization = (OrganizationModel) session
            .getAttribute(SessionStatus.SOFTTEK_ORGANIZATION.toString());
    List<VirtualGroupModel> vtllist = (List<VirtualGroupModel>) userVirtualGroupService
            .findVtlGroupsByUser(organization.getId(), user.getId());
    String belongVtls = "";
    if (vtllist != null) {
        for (VirtualGroupModel vtl : vtllist) {
            belongVtls = StringUtil.insert(belongVtls, vtl.getName() + "/");
        }
        maps.put("vtl", StringUtil.truncate(belongVtls, belongVtls.length() - 1));
    } else {
        maps.put("vtl", "");
    }
    maps.put("mark", user.getMark());
    maps.put("weight", user.getWeight() == null ? "0" : user.getWeight().toString());
    maps.put("gender", user.getGender() == null ? "0" : user.getGender().toString());
    maps.put("sign", user.getSign());
    maps.put("address", user.getAddress());
    maps.put("office", user.getOffice_phone());
    maps.put("position", user.getPosition());
    return maps;
}

From source file:com.sos.jobnet.utils.TimeKeyCalculator.java

License:Apache License

public TimeKeyCalculator(DateTime timeValue, DateTimeFormatter format, DurationFieldType type) {
    this.timeValue = timeValue;
    this.format = format;
    this.type = type;
    this.timeKey = timeValue.toString(format);
    this.calculatedTimeValue = timeValue.toMutableDateTime();
}