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.farrelltonsolar.classic.CalendarAdapter.java

License:Apache License

public CalendarAdapter(Context c, DateTime monthCalendar) {
    month = monthCalendar;//w w  w . ja va 2  s  . c  o m
    today = DateTime.now().withTimeAtStartOfDay();
    context = c;
    this.items = new ArrayList<String>();
    try {
        refreshDays(month);
    } catch (Exception ex) {
        Log.w(getClass().getName(), String.format("CalendarAdapter refreshDays failed ex: %s", ex));
    }
}

From source file:ca.farrelltonsolar.classic.DayLabelAdapter.java

License:Apache License

public DayLabelAdapter(Context context, LabelOrientation orientation) {
    mContext = context;
    today = DateTime.now().withTimeAtStartOfDay();
}

From source file:ca.farrelltonsolar.classic.DayLogCalendar.java

License:Apache License

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    theView = inflater.inflate(R.layout.day_log_calendar, container, false);
    Bundle args = getArguments();/*from w  ww.j  ava 2 s  .  c  om*/
    int monthOffset = args != null ? args.getInt(ARG_MONTH) : 0;
    month = DateTime.now().minusMonths(monthOffset).withTimeAtStartOfDay().withDayOfMonth(1);
    adapter = new CalendarAdapter(this.getActivity(), month);
    GridView gridview = (GridView) theView.findViewById(R.id.gridview);
    gridview.setAdapter(adapter);
    gridview.setVelocityScale(5);

    TextView title = (TextView) theView.findViewById(R.id.title);
    title.setText(month.toString("MMMM yyyy"));
    View linearLayout = theView.findViewById(R.id.headerlayout);
    DateTime days = month;

    for (int i = 0; i < 7; i++) {
        int d = ((i + 6) % 7) + 1;
        days = days.withDayOfWeek(d);
        TextView aDay = new TextView(theView.getContext());
        aDay.setText(DateTimeFormat.forPattern("E").print(days));
        aDay.setGravity(Gravity.CENTER);
        aDay.setTextColor(Color.BLACK);
        aDay.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
        ((LinearLayout) linearLayout).addView(aDay);

    }

    return theView;
}

From source file:ca.farrelltonsolar.classic.ModbusTask.java

License:Apache License

@Override
public void run() {
    //        Log.d(getClass().getName(), String.format("ModbusTask begin run for %s on thread is %s", chargeControllerInfo.toString(), Thread.currentThread().getName()));
    try {//from ww w  . j a v a  2s.  c om
        synchronized (lock) {
            boolean connected = isConnected();
            if (connected == false) {
                connected = connect();
            }
            if (connected) {
                if (initialReadingLoaded == false) {
                    initialReadingLoaded = true;
                    MonitorApplication.chargeControllers().setReachable(chargeControllerInfo.deviceIpAddress(),
                            chargeControllerInfo.port(), true);
                    if (lookForTriStar() == DeviceType.Classic) {
                        lookForWhizBangJr();
                        loadBoilerPlateInfo();
                    }
                }
                GetModbusReadings();
                if (!foundTriStar) {
                    if (dayLogEntry.isEmpty()) {
                        loadDayLogs();
                    } else {
                        DateTime logDate = dayLogEntry.getLogDate();
                        if (logDate.isBefore(DateTime.now().withTimeAtStartOfDay())) { // still good?
                            loadDayLogs();
                        }
                    }
                    dayLogEntry.broadcastLogs(context, Constants.CA_FARRELLTONSOLAR_CLASSIC_DAY_LOGS);
                    if (minuteLogEntry.isEmpty()) {
                        loadMinuteLogs();
                    } else {
                        DateTime logDate = minuteLogEntry.getLogDate();
                        if (logDate.isBefore(DateTime.now().minusHours(1))) { // still good?
                            loadMinuteLogs();
                        }
                    }
                    minuteLogEntry.broadcastLogs(context, Constants.CA_FARRELLTONSOLAR_CLASSIC_MINUTE_LOGS);
                }
            }
        }

    } catch (Exception e1) {
        Log.w(getClass().getName(), String.format("Failed to run due to exception ex: %s", e1));
        e1.printStackTrace();
        disconnect();
    }
    //        Log.d(getClass().getName(), "end run");

}

From source file:ca.farrelltonsolar.classic.ModbusTask.java

License:Apache License

private void loadDayLogs() throws ModbusException {
    String dayLogCacheName = chargeControllerInfo.dayLogCacheName();
    try {// w  ww.j  ava 2s. c o  m
        Bundle dayLogs = BundleCache.getInstance(context).getBundle(dayLogCacheName);
        if (dayLogs != null && dayLogs.size() > 0) {
            dayLogEntry = new LogEntry(dayLogs);
            DateTime logDate = dayLogEntry.getLogDate();
            if (logDate.isAfter(DateTime.now().withTimeAtStartOfDay())) { // still good?
                Log.d(getClass().getName(), "DayLog cache still good to go");
                return;
            }
            Log.d(getClass().getName(), "DayLog cache stale, reload data from modbus");
        }
        dayLogEntry.set(Constants.CLASSIC_KWHOUR_DAILY_CATEGORY,
                ReadLogs(365, Constants.CLASSIC_KWHOUR_DAILY_CATEGORY, Constants.MODBUS_FILE_DAILIES_LOG, 1));
        dayLogEntry.set(Constants.CLASSIC_FLOAT_TIME_DAILY_CATEGORY, ReadLogs(365,
                Constants.CLASSIC_FLOAT_TIME_DAILY_CATEGORY, Constants.MODBUS_FILE_DAILIES_LOG, 1));
        dayLogEntry.set(Constants.CLASSIC_HIGH_POWER_DAILY_CATEGORY, ReadLogs(365,
                Constants.CLASSIC_HIGH_POWER_DAILY_CATEGORY, Constants.MODBUS_FILE_DAILIES_LOG, 1));
        dayLogEntry.set(Constants.CLASSIC_HIGH_TEMP_DAILY_CATEGORY, ReadLogs(365,
                Constants.CLASSIC_HIGH_TEMP_DAILY_CATEGORY, Constants.MODBUS_FILE_DAILIES_LOG, 1));
        dayLogEntry.set(Constants.CLASSIC_HIGH_PV_VOLT_DAILY_CATEGORY, ReadLogs(365,
                Constants.CLASSIC_HIGH_PV_VOLT_DAILY_CATEGORY, Constants.MODBUS_FILE_DAILIES_LOG, 1));
        dayLogEntry.set(Constants.CLASSIC_HIGH_BATTERY_VOLT_DAILY_CATEGORY, ReadLogs(365,
                Constants.CLASSIC_HIGH_BATTERY_VOLT_DAILY_CATEGORY, Constants.MODBUS_FILE_DAILIES_LOG, 1));
        Log.d(getClass().getName(), "Completed reading Day logs");
        dayLogEntry.setLogDate(DateTime.now());
        BundleCache.getInstance(context).putBundle(dayLogCacheName, dayLogEntry.getLogs());
        BroadcastToast(context.getString(R.string.toast_day_logs));
    } catch (ModbusIOException ex) {
        if (ex.isEOF()) {
            Log.w(getClass().getName(), String.format("loadDayLogs reached EOF ex: %s", ex));
            dayLogEntry.setLogDate(DateTime.now());
            BundleCache.getInstance(context).putBundle(dayLogCacheName, dayLogEntry.getLogs());
            BroadcastToast(context.getString(R.string.toast_day_logs));
            return;
        }
        BundleCache.getInstance(context).clearCache(dayLogCacheName);
        dayLogEntry = new LogEntry();
        dayLogEntry.setLogDate(DateTime.now().plusMinutes(5)); // try it again later
        Log.w(getClass().getName(), String.format("loadDayLogs failed ex: %s", ex));
    } catch (Exception ex) {
        BundleCache.getInstance(context).clearCache(dayLogCacheName);
        dayLogEntry = new LogEntry();
        dayLogEntry.setLogDate(DateTime.now().plusMinutes(5)); // try it again later
        Log.w(getClass().getName(), String.format("loadDayLogs failed ex: %s", ex));
    }
}

From source file:ca.farrelltonsolar.classic.ModbusTask.java

License:Apache License

private void loadMinuteLogs() throws ModbusException {
    String minuteLogCacheName = chargeControllerInfo.minuteLogCacheName();
    try {/*from w w  w.j  ava 2  s  .  c  o m*/
        Bundle minuteLog = BundleCache.getInstance(context).getBundle(minuteLogCacheName);
        if (minuteLog != null && minuteLog.size() > 0) {
            minuteLogEntry = new LogEntry(minuteLog);
            DateTime logDate = minuteLogEntry.getLogDate();
            if (logDate.isAfter(DateTime.now().minusHours(1))) { // still good?
                Log.d(getClass().getName(), "MinuteLog cache still good to go");
                return;
            }
            Log.d(getClass().getName(), "MinuteLog cache stale, reload data from modbus");
        }
        int requiredEntries = ReadMinuteLogTimestamps(); // sum of minutes log up to 24 hours
        minuteLogEntry.set(Constants.CLASSIC_POWER_HOURLY_CATEGORY, ReadLogs(requiredEntries,
                Constants.CLASSIC_POWER_HOURLY_CATEGORY, Constants.MODBUS_FILE_MINUTES_LOG, 1));
        minuteLogEntry.set(Constants.CLASSIC_INPUT_VOLTAGE_HOURLY_CATEGORY, ReadLogs(requiredEntries,
                Constants.CLASSIC_INPUT_VOLTAGE_HOURLY_CATEGORY, Constants.MODBUS_FILE_MINUTES_LOG, 10));
        minuteLogEntry.set(Constants.CLASSIC_BATTERY_VOLTAGE_HOURLY_CATEGORY, ReadLogs(requiredEntries,
                Constants.CLASSIC_BATTERY_VOLTAGE_HOURLY_CATEGORY, Constants.MODBUS_FILE_MINUTES_LOG, 10));
        minuteLogEntry.set(Constants.CLASSIC_OUTPUT_CURRENT_HOURLY_CATEGORY, ReadLogs(requiredEntries,
                Constants.CLASSIC_OUTPUT_CURRENT_HOURLY_CATEGORY, Constants.MODBUS_FILE_MINUTES_LOG, 10));
        minuteLogEntry.set(Constants.CLASSIC_ENERGY_HOURLY_CATEGORY, ReadLogs(requiredEntries,
                Constants.CLASSIC_ENERGY_HOURLY_CATEGORY, Constants.MODBUS_FILE_MINUTES_LOG, 10));
        minuteLogEntry.set(Constants.CLASSIC_CHARGE_STATE_HOURLY_CATEGORY, ReadLogs(requiredEntries,
                Constants.CLASSIC_CHARGE_STATE_HOURLY_CATEGORY, Constants.MODBUS_FILE_MINUTES_LOG, 256));
        Log.d(getClass().getName(), "Completed reading minute logs");
        minuteLogEntry.setLogDate(DateTime.now());
        BundleCache.getInstance(context).putBundle(minuteLogCacheName, minuteLogEntry.getLogs());
        BroadcastToast(context.getString(R.string.toast_minute_logs));
    } catch (ModbusIOException ex) {
        if (ex.isEOF()) {
            Log.w(getClass().getName(), String.format("loadMinuteLogs reached EOF ex: %s", ex));
            minuteLogEntry.setLogDate(DateTime.now());
            BundleCache.getInstance(context).putBundle(minuteLogCacheName, minuteLogEntry.getLogs());
            BroadcastToast(context.getString(R.string.toast_minute_logs));
            return;
        }
        BundleCache.getInstance(context).clearCache(minuteLogCacheName);
        minuteLogEntry = new LogEntry();
        minuteLogEntry.setLogDate(DateTime.now().plusMinutes(5)); // try it again later
        Log.w(getClass().getName(), String.format("loadDayLogs failed ex: %s", ex));

    } catch (Exception ex) {
        BundleCache.getInstance(context).clearCache(minuteLogCacheName);
        minuteLogEntry = new LogEntry();
        minuteLogEntry.setLogDate(DateTime.now().plusMinutes(5)); // try it again later
        Log.w(getClass().getName(), String.format("LoadMinuteLogs failed ex: %s", ex));
    }
}

From source file:ca.farrelltonsolar.classic.PVOutputService.java

License:Apache License

private String getLogDate() {
    DateTime today = DateTime.now().withTimeAtStartOfDay();
    return DateTimeFormat.forPattern("yyyy-MM-dd").print(today);
}

From source file:ca.farrelltonsolar.classic.PVOutputUploader.java

License:Apache License

private boolean doUpload(ChargeController controller) throws InterruptedException, IOException {
    String uploadDateString = controller.uploadDate();
    String SID = controller.getSID();
    String fName = controller.getPVOutputLogFilename();
    if (fName != null && fName.length() > 0 && SID != null && SID.length() > 0) {
        DateTime logDate = PVOutputService.LogDate();
        int numberOfDays = Constants.PVOUTPUT_RECORD_LIMIT;
        if (uploadDateString.length() > 0) {
            DateTime uploadDate = DateTime.parse(uploadDateString, DateTimeFormat.forPattern("yyyy-MM-dd"));
            numberOfDays = Days.daysBetween(uploadDate, logDate).getDays();
        }//  ww w  .j  a va2s . co m
        numberOfDays = numberOfDays > Constants.PVOUTPUT_RECORD_LIMIT ? Constants.PVOUTPUT_RECORD_LIMIT
                : numberOfDays; // limit to 20 days as per pvOutput limits
        if (numberOfDays > 0) {
            Log.d(getClass().getName(), String.format("PVOutput uploading: %s for %d days on thread: %s", fName,
                    numberOfDays, Thread.currentThread().getName()));
            DateTime now = DateTime.now();
            String UploadDate = DateTimeFormat.forPattern("yyyy-MM-dd").print(now);
            Bundle logs = load(fName);
            float[] mData = logs.getFloatArray(String.valueOf(Constants.CLASSIC_KWHOUR_DAILY_CATEGORY)); // kWh/day
            boolean uploadDateRecorded = false;
            for (int i = 0; i < numberOfDays; i++) {
                logDate = logDate.minusDays(1); // latest log entry is for yesterday
                Socket pvOutputSocket = Connect(pvOutput);
                DataOutputStream outputStream = new DataOutputStream(
                        new BufferedOutputStream(pvOutputSocket.getOutputStream()));
                String dateStamp = DateTimeFormat.forPattern("yyyyMMdd").print(logDate);
                StringBuilder feed = new StringBuilder("GET /service/r2/addoutput.jsp");
                feed.append("?key=");
                feed.append(APIKey);
                feed.append("&sid=");
                feed.append(SID);
                feed.append("&d=");
                feed.append(dateStamp);
                feed.append("&g=");
                String wh = String.valueOf(mData[i] * 100);
                feed.append(wh);
                feed.append("\r\n");
                feed.append("Host: ");
                feed.append(pvOutput);
                feed.append("\r\n");
                feed.append("\r\n");
                String resp = feed.toString();
                outputStream.writeBytes(resp);
                outputStream.flush();
                pvOutputSocket.close();
                if (uploadDateRecorded == false) {
                    controller.setUploadDate(UploadDate);
                    uploadDateRecorded = true;
                }
                Thread.sleep(Constants.PVOUTPUT_RATE_LIMIT); // rate limit
            }
            return true;
        }
    }
    return false;
}

From source file:ca.phon.app.project.mergewizard.DeriveSessionWizard.java

License:Open Source License

/**
 * Perform the merge./*ww  w .java  2s .co  m*/
 */
private void doMerge() {

    String corpus = step1.getMergedCorpusName();
    String session = step1.getMergedSessionName();

    List<SessionPath> sessions = step1.getSelectedSessions();
    Collections.sort(sessions);

    final Project project = getProject();
    // first make sure we have a corpus
    if (!project.getCorpora().contains(step1.getMergedCorpusName())) {

        LOGGER.info("Creating corpus '" + corpus + "'");
        try {
            project.addCorpus(corpus, "");
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
            return;
        }

    }

    // check session name
    if (project.getCorpusSessions(corpus).contains(session)) {
        LOGGER.severe("A session with name '" + corpus + "." + session + "' already exists.");
        return;
    }

    // create the new session
    LOGGER.info("Creating session '" + corpus + "." + session + "'");
    final SessionFactory factory = SessionFactory.newFactory();
    try {
        final Session mergedSession = factory.createSession(corpus, session);

        final DateFormatter pdf = new DateFormatter();
        // merge sessions
        // keep track of session/media to see if we can sucessfully copy the data over
        String mergedDate = null;
        boolean checkDate = true;
        String mergedMedia = null;
        boolean checkMedia = true;
        for (SessionPath loc : sessions) {
            final Session t = step2.getSessionAtLocation(loc);
            final RecordFilter filter = step2.getFilterForLocation(loc);

            LOGGER.info("Merging data from session '" + loc.getCorpus() + "." + loc.getSession() + "'");
            if (checkDate) {
                String tDate = pdf.format(t.getDate());
                if (mergedDate == null) {
                    mergedDate = tDate;
                } else {
                    if (!mergedDate.equals(tDate)) {
                        LOGGER.warning("Session dates do not match, setting merged session date to today.");
                        mergedDate = pdf.format(DateTime.now());
                        checkDate = false;
                    }
                }
            }

            if (checkMedia) {
                if (mergedMedia == null) {
                    mergedMedia = t.getMediaLocation();
                } else {
                    if (!mergedMedia.equals(t.getMediaLocation())) {
                        LOGGER.warning("Session media locations do not match, leaving media field blank.");
                        mergedMedia = "";
                        checkMedia = false;
                    }
                }
            }

            // merge this session info
            SessionMerger.mergeSession(mergedSession, t, filter);
        }

        if (mergedDate != null) {
            final DateTime dt = DateTime.now();
            mergedSession.setDate(dt);
        }

        if (mergedMedia != null) {
            mergedSession.setMediaLocation(mergedMedia);
        }

        // save
        final UUID writeLock = project.getSessionWriteLock(mergedSession);
        project.saveSession(mergedSession, writeLock);
        project.releaseSessionWriteLock(mergedSession, writeLock);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        return;
    }

}

From source file:ca.phon.app.project.ProjectArchiveEP.java

License:Open Source License

@Override
public void pluginStart(Map<String, Object> initInfo) {
    //make sure we have a project
    if (initInfo.get("project") == null) {
        throw new IllegalArgumentException("project cannot be null");
    }//from w w  w  . jav a  2s.c  o  m

    Object v = initInfo.get("project");
    if (!(v instanceof Project)) {
        throw new IllegalArgumentException("project object does not implement IPhonProject interface");
    }
    project = (Project) v;

    // display options UI

    // default output file
    //      PhonDateFormat pdf = new PhonDateFormat(PhonDateFormat.YEAR_LONG);
    //      String today = pdf.format(Calendar.getInstance());
    final String today = DateFormatter.dateTimeToString(DateTime.now());

    String zipFileName = project.getName() + "-" + today + ".zip";
    File archiveDir = new File(Workspace.userWorkspace().getWorkspaceFolder(), "archives");
    if (!archiveDir.exists()) {
        archiveDir.mkdirs();
    }

    File zipFile = new File(archiveDir, zipFileName);

    // create and execute task
    final ProjectArchiveTask task = new ProjectArchiveTask(project, zipFile);
    task.performTask();

}