Example usage for java.util Calendar HOUR

List of usage examples for java.util Calendar HOUR

Introduction

In this page you can find the example usage for java.util Calendar HOUR.

Prototype

int HOUR

To view the source code for java.util Calendar HOUR.

Click Source Link

Document

Field number for get and set indicating the hour of the morning or afternoon.

Usage

From source file:com.zimbra.cs.imap.ImapRequest.java

Date readDate(boolean datetime, boolean checkRange) throws ImapParseException {
    String dateStr = (peekChar() == '"' ? readQuoted() : readAtom());
    if (dateStr.length() < (datetime ? 26 : 10)) {
        throw new ImapParseException(tag, "invalid date format");
    }/*  w  w  w  .jav  a2 s.c  o  m*/
    Calendar cal = new GregorianCalendar();
    cal.clear();

    int pos = 0, count;
    if (datetime && dateStr.charAt(0) == ' ') {
        pos++;
    }
    count = 2 - pos - (datetime || dateStr.charAt(1) != '-' ? 0 : 1);
    validateDigits(dateStr, pos, count, cal, Calendar.DAY_OF_MONTH);
    pos += count;
    validateChar(dateStr, pos, '-');
    pos++;
    validateMonth(dateStr, pos, cal);
    pos += 3;
    validateChar(dateStr, pos, '-');
    pos++;
    validateDigits(dateStr, pos, 4, cal, Calendar.YEAR);
    pos += 4;

    if (datetime) {
        validateChar(dateStr, pos, ' ');
        pos++;
        validateDigits(dateStr, pos, 2, cal, Calendar.HOUR);
        pos += 2;
        validateChar(dateStr, pos, ':');
        pos++;
        validateDigits(dateStr, pos, 2, cal, Calendar.MINUTE);
        pos += 2;
        validateChar(dateStr, pos, ':');
        pos++;
        validateDigits(dateStr, pos, 2, cal, Calendar.SECOND);
        pos += 2;
        validateChar(dateStr, pos, ' ');
        pos++;
        boolean zonesign = dateStr.charAt(pos) == '+';
        validateChar(dateStr, pos, zonesign ? '+' : '-');
        pos++;
        int zonehrs = validateDigits(dateStr, pos, 2, cal, -1);
        pos += 2;
        int zonemins = validateDigits(dateStr, pos, 2, cal, -1);
        pos += 2;
        cal.set(Calendar.ZONE_OFFSET, (zonesign ? 1 : -1) * (60 * zonehrs + zonemins) * 60000);
        cal.set(Calendar.DST_OFFSET, 0);
    }

    if (pos != dateStr.length()) {
        throw new ImapParseException(tag, "excess characters at end of date string");
    }
    Date date = cal.getTime();
    if (checkRange && date.getTime() < 0) {
        throw new ImapParseException(tag, "date out of range");
    }
    return date;
}

From source file:com.emcopentechnologies.viprcloudstorage.WAStorageClient.java

/**
 * Generates SAS URL for blob in Cloud storage account
 * @param storageAccountName//w  ww. j a va 2  s  .  com
 * @param storageAccountKey
 * @param containerName
 * @param strBlobURL
 * @return SAS URL
 * @throws Exception
 */
public static String generateSASURL(String storageAccountName, String storageAccountKey, String containerName,
        String saBlobEndPoint) throws Exception {
    StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(storageAccountName,
            storageAccountKey);
    URL blobURL = new URL(saBlobEndPoint);
    String saBlobURI = new StringBuilder().append(blobURL.getProtocol()).append("://")
            .append(storageAccountName).append(".").append(blobURL.getHost()).append("/").toString();
    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(credentials, new URI(saBlobURI),
            new URI(getCustomURI(storageAccountName, QUEUE, saBlobURI)),
            new URI(getCustomURI(storageAccountName, TABLE, saBlobURI)));
    // Create the blob client.
    CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient();
    CloudBlobContainer container = blobClient.getContainerReference(containerName);

    // At this point need to throw an error back since container itself did not exist.
    if (!container.exists()) {
        throw new Exception("WAStorageClient: generateSASURL: Container " + containerName
                + " does not exist in storage account " + storageAccountName);
    }

    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
    GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.setTime(new Date());

    //policy.setSharedAccessStartTime(calendar.getTime());
    calendar.add(Calendar.HOUR, 1);
    policy.setSharedAccessExpiryTime(calendar.getTime());
    policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ));

    BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
    containerPermissions.getSharedAccessPolicies().put("jenkins" + System.currentTimeMillis(), policy);
    container.uploadPermissions(containerPermissions);

    // Create a shared access signature for the container.
    String sas = container.generateSharedAccessSignature(policy, null);

    return sas;
}

From source file:de.forsthaus.webui.logging.loginlog.SecLoginlogListCtrl.java

/**
 * when the "search/filter" button is clicked. It searches over a period. <br>
 * Checks if EndDate not before StartDate.<br>
 * /*from w  w w .  j a  v  a2  s  .  c om*/
 * @param event
 */
public void onClick$button_SecLoginlogList_bb_SearchDate(Event event) throws Exception {

    if (!(this.dbox_LoginLog_DateFrom.getValue() == null) && !(this.dbox_LoginLog_DateTo.getValue() == null)) {

        if (this.dbox_LoginLog_DateFrom.getValue().after(this.dbox_LoginLog_DateTo.getValue())) {
            MultiLineMessageBox.doSetTemplate();
            MultiLineMessageBox.show(Labels.getLabel("message_EndDate_Before_BeginDate"));
        } else {
            Date dateFrom = this.dbox_LoginLog_DateFrom.getValue();
            Date dateTo = this.dbox_LoginLog_DateTo.getValue();

            final Calendar calFrom = Calendar.getInstance();
            calFrom.setTime(dateFrom);
            calFrom.set(Calendar.AM_PM, 0);
            calFrom.set(Calendar.HOUR, 0);
            calFrom.set(Calendar.MINUTE, 0);
            calFrom.set(Calendar.SECOND, 1);
            dateFrom = calFrom.getTime();

            final Calendar calTo = Calendar.getInstance();
            calTo.setTime(dateTo);
            calTo.set(Calendar.AM_PM, 1);
            calTo.set(Calendar.HOUR, 11);
            calTo.set(Calendar.MINUTE, 59);
            calTo.set(Calendar.SECOND, 59);
            dateTo = calTo.getTime();

            // ++ create the searchObject and init sorting ++//
            final HibernateSearchObject<SecLoginlog> soSecLoginlog = new HibernateSearchObject<SecLoginlog>(
                    SecLoginlog.class, getCountRows());
            // deeper loading of the relations to prevent the lazy
            // loading problem.
            soSecLoginlog.addFetch("ip2Country.countryCode");
            soSecLoginlog.addSort("lglLogtime", true);

            soSecLoginlog.addFilter(new Filter("lglLogtime", dateFrom, Filter.OP_GREATER_OR_EQUAL));
            soSecLoginlog.addFilter(new Filter("lglLogtime", dateTo, Filter.OP_LESS_OR_EQUAL));

            // Set the ListModel
            getPagedListWrapper().init(soSecLoginlog, this.listBoxSecUserlog, this.paging_SecUserLogList);

            this.checkbox_SecLoginlogList_ShowAll.setChecked(false);
        }
    }
}

From source file:com.kircherelectronics.accelerationfilter.activity.AccelerationPlotActivity.java

/**
 * Write the logged data out to a persisted file.
 *///from   ww w  . j av a  2 s . c om
private void writeLogToFile() {
    Calendar c = Calendar.getInstance();
    String filename = "AccelerationFilter-" + c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"
            + c.get(Calendar.DAY_OF_MONTH) + "-" + c.get(Calendar.HOUR) + "-" + c.get(Calendar.MINUTE) + "-"
            + c.get(Calendar.SECOND) + ".csv";

    File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "AccelerationFilter"
            + File.separator + "Logs");
    if (!dir.exists()) {
        dir.mkdirs();
    }

    File file = new File(dir, filename);

    FileOutputStream fos;
    byte[] data = log.getBytes();
    try {
        fos = new FileOutputStream(file);
        fos.write(data);
        fos.flush();
        fos.close();

        CharSequence text = "Log Saved";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(this, text, duration);
        toast.show();
    } catch (FileNotFoundException e) {
        CharSequence text = e.toString();
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(this, text, duration);
        toast.show();
    } catch (IOException e) {
        // handle exception
    } finally {
        // Update the MediaStore so we can view the file without rebooting.
        // Note that it appears that the ACTION_MEDIA_MOUNTED approach is
        // now blocked for non-system apps on Android 4.4.
        MediaScannerConnection.scanFile(this, new String[] { file.getPath() }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(final String path, final Uri uri) {

                    }
                });
    }
}

From source file:org.openmeetings.app.data.calendar.daos.AppointmentDaoImpl.java

public List<Appointment> getAppointmentsByRange(Long userId, Date starttime, Date endtime) {
    try {/*from w  ww . ja  v a 2 s.com*/

        Calendar calstart = Calendar.getInstance();
        calstart.setTime(starttime);
        calstart.set(Calendar.HOUR, 0);

        Calendar calend = Calendar.getInstance();
        calend.setTime(endtime);
        calend.set(Calendar.HOUR, 23);
        calend.set(Calendar.MINUTE, 59);

        log.debug("Start " + calstart.getTime() + " End " + calend.getTime());

        TypedQuery<Appointment> query = em.createNamedQuery("appointmentsInRange", Appointment.class);
        query.setParameter("deleted", "true");
        query.setParameter("starttime", calstart.getTime());
        query.setParameter("endtime", calend.getTime());
        query.setParameter("userId", userId);

        List<Appointment> listAppoints = new ArrayList<Appointment>(query.getResultList());
        TypedQuery<Appointment> q1 = em.createNamedQuery("joinedAppointmentsInRange", Appointment.class);
        q1.setParameter("starttime", calstart.getTime());
        q1.setParameter("endtime", calend.getTime());
        q1.setParameter("userId", userId);
        for (Appointment a : q1.getResultList()) {
            a.setIsConnectedEvent(true); //TODO need to be reviewed
            listAppoints.add(a);
        }

        for (Appointment appointment : listAppoints) {
            log.debug("" + appointment);

            appointment.setMeetingMember(
                    meetingMemberDao.getMeetingMemberByAppointmentId(appointment.getAppointmentId()));

        }

        return listAppoints;
    } catch (Exception ex2) {
        log.error("[getAppointmentsByRange]: ", ex2);
    }
    return null;
}

From source file:com.f8full.casserolesencours.CasserolesEnCoursActivity.java

public void onViewerModeClick(View view) {
    //TODO: View only my data on the map
    /*if(mViewOnMasterID == null)
    {//  ww  w.  ja  v  a 2 s .  c  o  m
       toastMessage(getString(R.string.anonimizeRequired));
    return;
    }*/

    String timeFilter = ((Spinner) findViewById(R.id.timeFilterSpinner)).getSelectedItem().toString();
    String distanceFilter = ((Spinner) findViewById(R.id.distanceFilterSpinner)).getSelectedItem().toString();

    String whereClause = "";

    if (distanceFilter.equals("--") == false)
    //time filtering requested by user
    {
        if (mAlohar.getPlaceManager().getCurrentLocation().getLatitude() == 0.0
                || mAlohar.getPlaceManager().getCurrentLocation().getLongitude() == 0.0) {
            //Location not available
            toastMessage(getString(R.string.locationFilterError));
        } else {
            String WhereClauseDistanceFilter = "";

            switch (((Spinner) findViewById(R.id.distanceFilterSpinner)).getSelectedItemPosition()) {
            case 1:
                WhereClauseDistanceFilter = "100";
                break;
            case 2:
                WhereClauseDistanceFilter = "300";
                break;
            case 3:
                WhereClauseDistanceFilter = "500";
                break;
            case 4:
                WhereClauseDistanceFilter = "1000";
                break;
            case 5:
                WhereClauseDistanceFilter = "20000";
                break;
            }

            //double testLat = 45.5334;
            //double testLong = -73.5838;

            //WHERE Pharmacy='yes' AND 
            whereClause += "WHERE ST_INTERSECTS(Location, CIRCLE(LATLNG("
                    + Double.toString(mAlohar.getPlaceManager().getCurrentLocation().getLatitude())
                    //+ Double.toString(testLat)
                    + "," + Double.toString(mAlohar.getPlaceManager().getCurrentLocation().getLongitude())
                    //+ Double.toString(testLong)
                    + ")," + WhereClauseDistanceFilter + ")) ";
            //37.3242,-121.9806),5000))"
        }
    }

    if (timeFilter.equals("--") == false)
    //time filtering requested by user
    {
        if (whereClause.isEmpty() == false) {
            whereClause += "AND ";
        } else {
            whereClause += "WHERE ";
        }

        Calendar cl = Calendar.getInstance();
        cl.setTime(new Date());
        switch (((Spinner) findViewById(R.id.timeFilterSpinner)).getSelectedItemPosition()) {
        case 1:
            cl.add(Calendar.MINUTE, -5);
            break;
        case 2:
            cl.add(Calendar.MINUTE, -15);
            break;
        case 3:
            cl.add(Calendar.MINUTE, -45);
            break;
        case 4:
            cl.add(Calendar.HOUR, -2);
            break;
        }

        whereClause += "Date>='" + DateFormat.getDateTimeInstance().format(cl.getTime()) + "' ";
    }

    //1cmlx9aChHUYTWwYivaZucr7NHNsP_ulvEPX1FoM is master table public view ID
    String fromTableID = "1cmlx9aChHUYTWwYivaZucr7NHNsP_ulvEPX1FoM";

    if (((CheckBox) findViewById(R.id.myDataCheckbox)).isChecked()) {
        fromTableID = mViewOnMasterID;
    }

    //excellent, just do a request to grab the locations and pass them around

    final String SqlQuery = "SELECT Date, Location, Description FROM " + fromTableID + " " + whereClause
            + "ORDER BY Date DESC LIMIT " + ((EditText) findViewById(R.id.nbIconsMax)).getText();

    final boolean myLocationEnabled = !(((CheckBox) findViewById(R.id.worldMapChkBx)).isChecked());
    final boolean timeColored = ((CheckBox) findViewById(R.id.timeColoredCheckbox)).isChecked();

    new Thread((new Runnable() {

        public void run() {
            try {

                String encodedQuery = URLEncoder.encode(SqlQuery, "UTF-8");

                GoogleUrl GUrl = new GoogleUrl(SERVICE_URL + "?sql=" + encodedQuery + "&encid=true");

                HttpRequest request = mGOOGClient.getRequestFactory().buildGetRequest(GUrl);
                HttpHeaders headers = new HttpHeaders();

                headers.setContentLength("0");//Required so that Fusion Table API considers request
                request.setHeaders(headers);

                HttpResponse response = request.execute();

                if (response.getStatusCode() == 200) {
                    //Here I have my data
                    InputStreamReader inputStreamReader = new InputStreamReader(response.getContent());
                    BufferedReader bufferedStreamReader = new BufferedReader(inputStreamReader);
                    CSVReader reader = new CSVReader(bufferedStreamReader);
                    // The first line is the column names, and the remaining lines are the rows.
                    List<String[]> csvLines = reader.readAll();

                    List<String> columns = Arrays.asList(csvLines.get(0));
                    List<String[]> rows = csvLines.subList(1, csvLines.size());

                    if (rows.size() == 0) {
                        toastMessage("Table vide !");
                        return;
                    }

                    ArrayList<String> rowData = new ArrayList<String>();

                    for (String[] row : rows) {
                        String toAdd = "";
                        for (String cell : row) {
                            //No , in data, or things are gonna go horribly wrong here
                            toAdd += cell + "|";
                        }

                        //I have this last pesky separator ,it will give me an empty String on the other side
                        rowData.add(toAdd);
                    }

                    Intent mapIntent = new Intent(getApplicationContext(),
                            CasserolesEnCoursViewerActivity.class);
                    mapIntent.putStringArrayListExtra("rowsData", rowData);
                    mapIntent.putExtra("timeColored", timeColored);
                    mapIntent.putExtra("myLocation", myLocationEnabled);

                    if (myLocationEnabled)
                        toastMessage(getString(R.string.lastContributionTapHintLocal));
                    else
                        toastMessage(getString(R.string.lastContributionTapHintWorld));
                    //mapIntent.putExtra("relativeTime", ((CheckBox)findViewById(R.id.relativeTimeCheckbox)).isChecked());
                    startActivity(mapIntent);

                }

            } catch (HttpResponseException e) {
                if (e.getStatusCode() == 401) {
                    mGOOGCredential.setAccessToken(null);

                    SharedPreferences.Editor editor2 = mPrefs.edit();
                    editor2.remove(PREF_REFRESH_TOKEN);
                    editor2.commit();

                    toastMessage("OAuth login required, redirecting...");

                    //This last Constant is weird
                    startActivityForResult(
                            new Intent().setClass(getApplicationContext(), OAuth2AccessTokenActivity.class),
                            REQUEST_OAUTH2_AUTHENTICATE);

                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    })).start();
}

From source file:com.concursive.connect.web.modules.calendar.utils.CalendarView.java

/**
 * Gets the calendarEndDate attribute of the CalendarView object
 *
 * @param source Description of the Parameter
 * @return The calendarEndDate value//from   w  ww. j  a  va  2  s  . c o m
 */
public String getCalendarEndDate(String source) {
    int displayMonth = 0;
    int displayDay = 0;
    int displayYear = 0;
    if (source != null) {
        if (calendarInfo.isAgendaView() && source.equalsIgnoreCase("calendarDetails")) {
            Calendar today = Calendar.getInstance(timeZone, locale);
            today.set(Calendar.HOUR, 0);
            today.set(Calendar.MINUTE, 0);
            today.set(Calendar.SECOND, 0);
            today.set(Calendar.MILLISECOND, 0);
            today.add(Calendar.DATE, AGENDA_DAY_COUNT);
            displayMonth = today.get(Calendar.MONTH) + 1;
            displayDay = today.get(Calendar.DAY_OF_MONTH);
            displayYear = today.get(Calendar.YEAR);
        } else if (!source.equalsIgnoreCase("Calendar")) {
            if (calendarInfo.getCalendarView().equalsIgnoreCase("day")) {
                Calendar tmpCal = Calendar.getInstance(locale);
                tmpCal.set(Calendar.HOUR, 0);
                tmpCal.set(Calendar.MINUTE, 0);
                tmpCal.set(Calendar.SECOND, 0);
                tmpCal.set(Calendar.MILLISECOND, 0);
                tmpCal.set(calendarInfo.getYearSelected(), calendarInfo.getMonthSelected() - 1,
                        calendarInfo.getDaySelected());
                tmpCal.add(java.util.Calendar.DATE, +1);
                displayMonth = tmpCal.get(Calendar.MONTH) + 1;
                displayDay = tmpCal.get(Calendar.DAY_OF_MONTH);
                displayYear = tmpCal.get(Calendar.YEAR);
            } else if (calendarInfo.getCalendarView().equalsIgnoreCase("week")) {
                Calendar newDate = Calendar.getInstance(timeZone, locale);
                newDate.set(Calendar.HOUR, 0);
                newDate.set(Calendar.MINUTE, 0);
                newDate.set(Calendar.SECOND, 0);
                newDate.set(Calendar.MILLISECOND, 0);
                newDate.set(calendarInfo.getYearSelected(), calendarInfo.getStartMonthOfWeek() - 1,
                        calendarInfo.getStartDayOfWeek());
                newDate.add(Calendar.DATE, 7);
                displayMonth = newDate.get(Calendar.MONTH) + 1;
                displayDay = newDate.get(Calendar.DATE);
                displayYear = newDate.get(Calendar.YEAR);
            } else {
                displayMonth = calNext.get(Calendar.MONTH) + 1;
                displayYear = calNext.get(Calendar.YEAR);
                displayDay = numberOfCells - getEndCell(cal) - 1;
            }
        } else {
            Calendar tmpCal = Calendar.getInstance(locale);
            tmpCal.set(Calendar.HOUR, 0);
            tmpCal.set(Calendar.MINUTE, 0);
            tmpCal.set(Calendar.SECOND, 0);
            tmpCal.set(Calendar.MILLISECOND, 0);
            tmpCal.set(calNext.get(Calendar.YEAR), calNext.get(Calendar.MONTH),
                    (numberOfCells - getEndCell(cal) - 1));
            tmpCal.add(java.util.Calendar.DATE, +1);
            displayMonth = tmpCal.get(Calendar.MONTH) + 1;
            displayDay = tmpCal.get(Calendar.DAY_OF_MONTH);
            displayYear = tmpCal.get(Calendar.YEAR);
        }
    } else {
        LOG.warn("getCalendarEndDate() source is NULL");
    }
    LOG.debug("End Day: " + displayMonth + "/" + displayDay + "/" + displayYear);
    return (displayMonth + "/" + displayDay + "/" + displayYear);
}

From source file:com.cttapp.bby.mytlc.layer8apps.CalendarHandler.java

private ArrayList<Shift> buildShifts() {
    Preferences pf = new Preferences(this);

    String address = pf.getAddress();

    String timeAdjust = pf.getTimezone();

    String eventName = pf.getEventName();

    int time = 0;

    if (timeAdjust != null) {
        time = Integer.parseInt(timeAdjust);
    }//from w  w  w  .  j a v  a  2s  .c o  m

    ArrayList<Shift> shifts = new ArrayList<Shift>();

    for (int x = finalDays.size() - 1; x >= 0; x--) {
        String[] work = finalDays.get(x);
        Calendar beginTime = Calendar.getInstance();
        /************
         * Below we create variables for our day, month and year.  We then
         * check to see if the scheduled day is next month or next year so
         * we know to increase our variables properly
         *************/
        int workDay = Integer.parseInt(work[0].trim());
        int workMonth = beginTime.get(Calendar.MONTH);
        int workYear = beginTime.get(Calendar.YEAR);
        /************
         * If the day of the month for work is prior to todays date, then
         * we check if we're in December.  We increase the month and year
         * where necessary
         *************/
        if (workDay < beginTime.get(Calendar.DAY_OF_MONTH) && workMonth != 12) {
            workMonth += 1;
        } else if (workDay < beginTime.get(Calendar.DAY_OF_MONTH)) {
            workMonth = 1;
            workYear += 1;
        }
        /************
         * If the shift starts in the PM, add 12 hours
         * to the time
         *************/

        int workSHour = Integer.parseInt(work[1].substring(0, 2));
        if (work[1].substring(6, 8).equalsIgnoreCase("PM") && workSHour != 12) {
            workSHour += 12;
        } else if (work[1].substring(6, 8).equalsIgnoreCase("AM") && workSHour == 12) {
            workSHour = 0;
        }

        int workSMinute = Integer.parseInt(work[1].substring(3, 5));
        beginTime.set(workYear, workMonth, workDay, workSHour, workSMinute);

        beginTime.add(Calendar.HOUR, time);

        int workEHour = Integer.parseInt(work[1].substring(11, 13));
        /************
         * If the shift ends in the PM, add 12 hours
         * to the time
         *************/
        if (work[1].substring(17, 19).equalsIgnoreCase("PM") && workEHour != 12) {
            workEHour += 12;
        } else if (work[1].substring(17, 19).equalsIgnoreCase("AM") && workEHour == 12) {
            workEHour = 0;
        }

        int workEMinute = Integer.parseInt(work[1].substring(14, 16));
        Calendar endTime = Calendar.getInstance();

        if (workEHour < workSHour) {
            workDay += 1;
        }
        endTime.set(workYear, workMonth, workDay, workEHour, workEMinute);

        endTime.add(Calendar.HOUR, time);

        shifts.add(new Shift(eventName, work[2], (address == null) ? "" : address, beginTime, endTime));
    }

    return shifts;
}

From source file:edu.hawaii.soest.kilonalu.utilities.TextOutputPlugin.java

/**
 * Converts data for a time range.//from ww w.  j  av  a  2 s.  co m
 * 
 * @param map             the channel map
 * @param startTime       the start time for the data
 * @param endTime         the end time for the data
 * @param baseTime        the base elasped time for the conversion
 * @return                the number of data frames written to disk
 * @throws SAPIException  if there is an error getting the data from the
 *                        server
 * @throws IOException    if there is an error writing the file
 */
private int convertData(ChannelMap map, ChannelMap cmap, double startTime, double endTime, double duration,
        double baseTime) throws SAPIException, IOException {
    logger.debug("TextOutputPlugin.convertData() called.");

    sink.Subscribe(map, startTime, 0.0, "absolute");
    //sink.Subscribe(map, startTime, duration, "absolute");

    int frameCount = 0;
    int fetchRetryCount = 0;

    while (doTextConversion) {
        ChannelMap m = sink.Fetch(10000); // fetch with 10 sec timeout

        if (m.GetIfFetchTimedOut()) {
            if (++fetchRetryCount < 10) {
                logger.debug("Warning: Request for data timed out, retrying.");
                continue;
            } else {
                logger.debug("Error: Unable to get data from server.");
                break;
            }
        } else {
            fetchRetryCount = 0;
        }

        int index = m.GetIndex(channelPath);
        if (index < 0) {
            break;
        }

        byte[][] data = m.GetDataAsByteArray(index); // uses local byte order??
        for (int i = 0; i < data.length; i++) {
            ByteBuffer ensembleBuffer = ByteBuffer.allocate(data[i].length);
            // create an Ensemble
            ensembleBuffer.put(data[i]);
            Ensemble ensemble = new Ensemble(ensembleBuffer);
            logger.info("Ensemble is valid: " + ensemble.isValid());

            if (ensemble.isValid()) {
                int ensYear = (ensemble.getRealTimeY2KClockCentury() * 100)
                        + ensemble.getRealTimeY2KClockYear();
                int ensMonth = ensemble.getRealTimeY2KClockMonth() - 1; // 0 start
                int ensDay = ensemble.getRealTimeY2KClockDay();
                int ensHour = ensemble.getRealTimeY2KClockHour();
                int ensMinute = ensemble.getRealTimeY2KClockMinute();
                int ensSecond = ensemble.getRealTimeY2KClockSecond();
                int ensHundredths = ensemble.getRealTimeY2KClockHundredths();

                logger.debug("ensYear      : " + ensYear);
                logger.debug("ensMonth     : " + ensMonth);
                logger.debug("ensDay       : " + ensDay);
                logger.debug("ensHour      : " + ensHour);
                logger.debug("ensMinute    : " + ensMinute);
                logger.debug("ensSecond    : " + ensSecond);
                logger.debug("ensHundredths: " + ensHundredths);

                Calendar ensCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
                ensCalendar.set(ensYear, ensMonth, ensDay, ensHour, ensMinute, ensSecond);
                ensCalendar.add(Calendar.HOUR, 10); // set observation time to GMT
                ensCalendar.add(Calendar.MILLISECOND, ensHundredths * 10);

                // set the data frame timestamp to the observation timestamp
                double[] times = new double[1];
                times[0] = (double) (ensCalendar.getTime().getTime() / 1000);
                logger.debug("Observation time: = " + RBNBUtilities.secondsToISO8601(times[0]));
                cmap.PutTimes(times);

                String[] channelList = new String[cmap.NumberOfChannels()];
                for (int j = 0; j < channelList.length; j++) {
                    channelList[j] = cmap.GetName(j);
                    // add temperature data channel
                    if (channelList[j].equals("temperature")) {
                        //logger.debug("Temperature: " + ensemble.getTemperature());
                        cmap.PutDataAsFloat32(cmap.GetIndex(channelList[j]),
                                new float[] { ensemble.getTemperature() });
                    }
                    // add pressure data channel
                    if (channelList[j].equals("pressure")) {
                        //logger.debug("Pressure: " + ensemble.getPressure());
                        cmap.PutDataAsFloat32(cmap.GetIndex(channelList[j]),
                                new float[] { ensemble.getPressure() });
                    }
                    // add salinity data channel
                    if (channelList[j].equals("salinity")) {
                        //logger.debug("Salinity: " + ensemble.getSalinity());
                        cmap.PutDataAsInt32(cmap.GetIndex(channelList[j]),
                                new int[] { ensemble.getSalinity() });
                    }
                }
                // Flush the data frame to rbnb
                source.Flush(cmap);
                logger.debug("Flushed data to data turbine.");
            }

        }
        //doTextConversion = false;
    }

    return frameCount;
}

From source file:br.org.indt.ndg.server.instance.SystemPropertiesInstance.java

public static String getTimestamp() {
    StringBuffer s = new StringBuffer();
    Calendar c = Calendar.getInstance();
    s.append(c.get(Calendar.HOUR));
    s.append(":");
    s.append(c.get(Calendar.MINUTE));
    s.append(":");
    s.append(c.get(Calendar.SECOND));
    s.append(" ");
    s.append(c.get(Calendar.DAY_OF_MONTH));
    s.append("-");
    s.append(c.get(Calendar.MONTH));
    s.append("-");
    s.append(c.get(Calendar.YEAR));

    return s.toString();
}