Example usage for java.util TimeZone getOffset

List of usage examples for java.util TimeZone getOffset

Introduction

In this page you can find the example usage for java.util TimeZone getOffset.

Prototype

public int getOffset(long date) 

Source Link

Document

Returns the offset of this time zone from UTC at the specified date.

Usage

From source file:org.mycontroller.standalone.mysensors.MySensorsMessageEngine.java

private void internalSubMessageTypeSelector(MySensorsRawMessage mySensorsRawMessage) {
    //Get node, if node not available create
    Node node = getNode(mySensorsRawMessage);
    //ResourcesLogs message data
    if (ResourcesLogsUtils.isLevel(LOG_LEVEL.NOTICE)) {
        this.setSensorOtherData(LOG_LEVEL.NOTICE, mySensorsRawMessage,
                MESSAGE_TYPE_INTERNAL.get(mySensorsRawMessage.getSubType()).getText(), null);
    }//from w  ww  .j a  va  2s  . c o m

    _logger.debug("Message Type:{}", MESSAGE_TYPE_INTERNAL.get(mySensorsRawMessage.getSubType()).toString());
    switch (MESSAGE_TYPE_INTERNAL.get(mySensorsRawMessage.getSubType())) {
    case I_BATTERY_LEVEL:
        if (mySensorsRawMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Battery Level:[nodeId:{},Level:{}%]", mySensorsRawMessage.getNodeEui(),
                mySensorsRawMessage.getPayload());
        node.setBatteryLevel(mySensorsRawMessage.getPayload());
        updateNode(node);
        //Update battery level in to metrics table
        MetricsBatteryUsage batteryUsage = MetricsBatteryUsage.builder().node(node)
                .timestamp(System.currentTimeMillis()).aggregationType(AGGREGATION_TYPE.RAW)
                .avg(mySensorsRawMessage.getPayloadDouble()).samples(1).build();

        DaoUtils.getMetricsBatteryUsageDao().create(batteryUsage);

        break;
    case I_TIME:
        if (mySensorsRawMessage.isTxMessage()) {
            return;
        }
        TimeZone timeZone = TimeZone.getDefault();
        long utcTime = System.currentTimeMillis();
        long timeOffset = timeZone.getOffset(utcTime);
        long localTime = utcTime + timeOffset;
        mySensorsRawMessage.setPayload(String.valueOf(localTime / 1000));
        mySensorsRawMessage.setTxMessage(true);
        _logger.debug("Time Message:[{}]", mySensorsRawMessage);
        ObjectFactory.getRawMessageQueue().putMessage(mySensorsRawMessage.getRawMessage());
        _logger.debug("Time request resolved.");
        break;
    case I_VERSION:
        _logger.debug("Gateway version requested by {}! Message:{}", AppProperties.APPLICATION_NAME,
                mySensorsRawMessage);
        break;
    case I_ID_REQUEST:
        try {
            int nodeId = MySensorsUtils.getNextNodeId(mySensorsRawMessage.getGatewayId());
            mySensorsRawMessage.setPayload(nodeId);
            mySensorsRawMessage.setSubType(MESSAGE_TYPE_INTERNAL.I_ID_RESPONSE.ordinal());
            mySensorsRawMessage.setTxMessage(true);
            ObjectFactory.getRawMessageQueue().putMessage(mySensorsRawMessage.getRawMessage());
            _logger.debug("New Id[{}] sent to node", nodeId);
        } catch (NodeIdException ex) {
            _logger.error("Unable to generate new node Id,", ex);
            //ResourcesLogs message data
            if (ResourcesLogsUtils.isLevel(LOG_LEVEL.ERROR)) {
                this.setSensorOtherData(LOG_LEVEL.ERROR, mySensorsRawMessage,
                        MESSAGE_TYPE_INTERNAL.get(mySensorsRawMessage.getSubType()).getText(), ex.getMessage());
            }

        }
        break;
    case I_INCLUSION_MODE:
        _logger.warn("Inclusion mode not supported by this controller! Message:{}", mySensorsRawMessage);
        break;
    case I_CONFIG:
        if (mySensorsRawMessage.isTxMessage()) {
            return;
        }
        mySensorsRawMessage.setPayload(MySensorsUtils.getMetricType());
        mySensorsRawMessage.setTxMessage(true);
        ObjectFactory.getRawMessageQueue().putMessage(mySensorsRawMessage.getRawMessage());
        _logger.debug("Configuration sent as follow[M/I]?:{}", mySensorsRawMessage.getPayload());
        break;
    case I_LOG_MESSAGE:
        if (mySensorsRawMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Node trace-log message[nodeId:{},sensorId:{},message:{}]",
                mySensorsRawMessage.getNodeEui(), mySensorsRawMessage.getChildSensorId(),
                mySensorsRawMessage.getPayload());
        break;
    case I_SKETCH_NAME:
        if (mySensorsRawMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Internal Message[type:{},name:{}]",
                MESSAGE_TYPE_INTERNAL.get(mySensorsRawMessage.getSubType()), mySensorsRawMessage.getPayload());
        node = getNode(mySensorsRawMessage);
        node.setName(mySensorsRawMessage.getPayload());
        updateNode(node);
        break;
    case I_SKETCH_VERSION:
        if (mySensorsRawMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Internal Message[type:{},version:{}]",
                MESSAGE_TYPE_INTERNAL.get(mySensorsRawMessage.getSubType()), mySensorsRawMessage.getPayload());
        node = getNode(mySensorsRawMessage);
        node.setVersion(mySensorsRawMessage.getPayload());
        updateNode(node);
        break;
    case I_REBOOT:
        break;
    case I_GATEWAY_READY:
        if (mySensorsRawMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Gateway Ready[nodeId:{},message:{}]", mySensorsRawMessage.getNodeEui(),
                mySensorsRawMessage.getPayload());
        break;

    case I_ID_RESPONSE:
        _logger.debug("Internal Message, Type:I_ID_RESPONSE[{}]", mySensorsRawMessage);
        return;
    case I_HEARTBEAT:
    case I_HEARTBEAT_RESPONSE:
        if (mySensorsRawMessage.isTxMessage()) {
            return;
        }
        node = getNode(mySensorsRawMessage);
        node.setState(STATE.UP);
        updateNode(node);
        break;
    default:
        _logger.warn(
                "Internal Message[type:{},payload:{}], This type may not be supported (or) not implemented yet",
                MESSAGE_TYPE_INTERNAL.get(mySensorsRawMessage.getSubType()), mySensorsRawMessage.getPayload());
        break;
    }
}

From source file:org.eclipse.uomo.util.impl.Iso8601Date.java

/**
 * //from   ww  w.  j  a v  a  2s . c  o  m
 * @param date
 *            the date to set the component fields to
 * @param timezone
 *            - what to do about timezone (CLEAR, SETLOCAL or IGNORE)
 */
public void setAsDate(Date date, int timezone) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    reset(timezone != IGNORE);
    year = cal.get(Calendar.YEAR);
    month = cal.get(Calendar.MONTH) + 1; // java Month starts from 0, but
    // ours starts from 1
    day = cal.get(Calendar.DAY_OF_MONTH);
    hour = cal.get(Calendar.HOUR_OF_DAY);
    minute = cal.get(Calendar.MINUTE);
    second = cal.get(Calendar.SECOND);
    milli = cal.get(Calendar.MILLISECOND);

    if (timezone == CLEAR) {
        tzHour = 0;
        tzMinute = 0;
        tzNegative = null;
    } else if (timezone == SETLOCAL) {
        TimeZone tzLcl = TimeZone.getDefault();
        int offset = tzLcl.getOffset(date.getTime());
        if (offset < 0) {
            tzNegative = new Boolean(true);
            offset = -offset;
        } else {
            tzNegative = new Boolean(true);
        }
        tzHour = offset / (1000 * 60 * 60);
        tzMinute = (offset - (tzHour * 1000 * 60 * 60)) / (1000 * 60);
    }
}

From source file:com.glandorf1.joe.wsprnetviewer.app.sync.WsprNetViewerSyncAdapter.java

/**
 * Parse the Document containing the wspr data in HTML format.
 * Call from 'doInBackground()', etc.//from  w w w .j  a va  2  s. c  o m
 */
public void getWsprDataFromTags(Context context, Document wsprHtml, int maxSpots, String gridsquareSetting,
        boolean drupal) throws Throwable {

    // These are the names of the objects that need to be extracted.
    // column# 0             1       2           3    4       5      6     7          8     9       10
    //   Timestamp           Call   MHz           SNR   Drift   Grid   Pwr   Reporter   RGrid   km      az
    //   2014-08-25 20:40    DL8EDC  7.040186    -4     0      JO31le     5     LA3JJ/L    JO59bh    925     11

    // Gridsquare information
    final String WSPRNET_IDX_CITY = "city_name";
    final String WSPRNET_IDX_COUNTRY_NAME = "name";
    //final String WSPRNET_IDX_COORD = "coord";
    final String WSPRNET_IDX_COORD_LAT = "lat";
    final String WSPRNET_IDX_COORD_LONG = "lon";

    // Wspr information html element indices for their 'new' drupal interface.
    //   e.g.: http://wsprnet.org/drupal/wsprnet/spots
    final int WSPRNET_IDX_TIMESTAMP = 0;
    final int WSPRNET_IDX_TX_CALLSIGN = 1;
    final int WSPRNET_IDX_TX_FREQ_MHZ = 2;
    final int WSPRNET_IDX_RX_SNR = 3;
    final int WSPRNET_IDX_RX_DRIFT = 4;
    final int WSPRNET_IDX_TX_GRIDSQUARE = 5;
    final int WSPRNET_IDX_TX_POWER = 6;
    final int WSPRNET_IDX_RX_CALLSIGN = 7;
    final int WSPRNET_IDX_RX_GRIDSQUARE = 8;
    final int WSPRNET_IDX_DISTANCE = 9;
    final int WSPRNET_IDX_AZIMUTH = 10;

    // Wspr information html element indices for their 'old' url query interface.
    //   e.g.: http://wsprnet.org/olddb?mode=html&band=all&limit=10&findcall=&findreporter=&sort=date
    final int WSPRNET_IDX_OLDDB_TIMESTAMP = 0;
    final int WSPRNET_IDX_OLDDB_TX_CALLSIGN = 1;
    final int WSPRNET_IDX_OLDDB_TX_FREQ_MHZ = 2;
    final int WSPRNET_IDX_OLDDB_RX_SNR = 3;
    final int WSPRNET_IDX_OLDDB_RX_DRIFT = 4;
    final int WSPRNET_IDX_OLDDB_TX_GRIDSQUARE = 5;
    final int WSPRNET_IDX_OLDDB_TX_POWER_DBM = 6;
    final int WSPRNET_IDX_OLDDB_TX_POWER_W = 7;
    final int WSPRNET_IDX_OLDDB_RX_CALLSIGN = 8;
    final int WSPRNET_IDX_OLDDB_RX_GRIDSQUARE = 9;
    final int WSPRNET_IDX_OLDDB_DISTANCE_KM = 10;
    final int WSPRNET_IDX_OLDDB_DISTANCE_MILES = 11;

    // Notification calculations
    double minSNR = Utility.getNotifyMinSNR(context);
    double notifyBandMHz = Utility.getNotifyBand(context), notifyBandMHzMin = notifyBandMHz - 0.001,
            notifyBandMHzMax = notifyBandMHz + 0.001;
    if (notifyBandMHz < 0.00001) {
        notifyBandMHzMin = 0;
        notifyBandMHzMax = 1e300;
    }
    String bandName = "";
    mBandNameIdx = -1; // reset which band was found for notification
    int nHits = 0, nHitsSnr = 0, nHitsBand = 0, nHitsDistance = 0, nHitsTxCall = 0, nHitsRxCall = 0,
            nHitsTxGrid = 0, nHitsRxGrid = 0;
    double notifyMinTxRxKm = Utility.getNotifyTxRxKm(context);
    // Get the tx/rx notify callsigns, but configure for wildcard matching with regex's.
    String displayTxCallsign = Utility.getNotifyCallsign(context, true),
            displayRxCallsign = Utility.getNotifyCallsign(context, false);
    String displayTxGridsquare = Utility.getNotifyGridsquare(context, true),
            displayRxGridsquare = Utility.getNotifyGridsquare(context, false);
    String notifyTxCallsign = Utility.filterCleanupMatch(displayTxCallsign),
            notifyRxCallsign = Utility.filterCleanupMatch(displayRxCallsign);
    String notifyTxGridsquare = Utility.filterCleanupMatch(displayTxGridsquare),
            notifyRxGridsquare = Utility.filterCleanupMatch(displayRxGridsquare);
    boolean snrOk = false, bandOk = false, distanceOk = false, txCallOk = false, rxCallOk = false,
            txGridOk = false, rxGridOk = false;
    boolean snrEna = true, bandEna = (notifyBandMHz < 0.00001), distanceEna = (notifyMinTxRxKm >= 0.001),
            txCallEna = (notifyTxCallsign.length() > 0), rxCallEna = (notifyRxCallsign.length() > 0),
            txGridEna = (notifyTxGridsquare.length() > 0), rxGridEna = (notifyRxGridsquare.length() > 0);

    // Delete items older than the cutoff period specified in the settings menu.
    // TODO: It might be easier to use System.currentTimeMillis(), which returns time in UTC.  BUT,
    // todo: Date objects seem to work in the local time zone; wasn't able to initialize one to UTC.
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    TimeZone tz = TimeZone.getDefault();
    int offsetUTC = tz.getOffset(cal.getTimeInMillis()) / 1000;
    int seconds = Utility.cutoffSeconds(context);
    cal.add(Calendar.SECOND, -offsetUTC);
    cal.add(Calendar.SECOND, -seconds);
    String cutoffTimestamp = WsprNetContract.getDbTimestampString(cal.getTime());
    int d;
    d = context.getContentResolver().delete(WsprNetContract.SignalReportEntry.CONTENT_URI,
            WsprNetContract.SignalReportEntry.COLUMN_TIMESTAMPTEXT + " <= ?", new String[] { cutoffTimestamp });
    Log.v(LOG_TAG, "getWsprDataFromTags: deleted " + Integer.toString(d) + " old items.");

    // Get the cutoff date for notifications.
    cal.setTime(new Date());
    seconds = Utility.updateIntervalSeconds(context);
    cal.add(Calendar.SECOND, -offsetUTC);
    cal.add(Calendar.SECOND, -seconds);
    long cutoffNotifyTimeMin = getShortTimestamp(cal.getTime());
    cal.add(Calendar.SECOND, 2 * seconds);
    long cutoffNotifyTimeMax = getShortTimestamp(cal.getTime());
    long iTimestamp = 0;

    try {
        // TODO: get city name, lat/long from gridsquare; determine how to look this up
        String cityName = context.getString(R.string.unknown_city); // generic text until the city/country is looked up
        String countryName = context.getString(R.string.unknown_country);
        double cityLatitude = Utility.gridsquareToLatitude(gridsquareSetting);
        double cityLongitude = Utility.gridsquareToLongitude(gridsquareSetting);

        Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);

        // Insert the gridsquare into the database.
        long locationID = addGridsquare(context, gridsquareSetting, cityName, countryName, cityLatitude,
                cityLongitude);
        Elements wsprHeader, wsprHeader1, wsprHeader2; // TODO: someday, match up header name instead of relying on a fixed column #
        Elements wsprData;
        if (drupal == true) {
            wsprHeader = wsprHtml
                    .select("div#block-system-main.block.block-system div.content table tbody tr:eq(0)");
            wsprData = wsprHtml
                    .select("div#block-system-main.block.block-system div.content table tbody tr:gt(0)");
        } else {
            wsprHeader1 = wsprHtml.select("html body table tbody tr:eq(0)");
            wsprHeader2 = wsprHtml.select("html body table tbody tr:eq(1)");
            wsprData = wsprHtml.select("html body table tbody tr:gt(1)");
        }

        // Get and insert the new wspr information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(wsprData.size());

        for (int i = 0; (i < wsprData.size()) && (i < maxSpots); i++) {
            Elements wsprTDRow = wsprData.get(i).select("td"); // table data row split into <td> elements
            // These are the values that will be collected.
            // column# 0             1       2           3    4       5      6     7          8     9       10
            //   Timestamp           Call   MHz           SNR   Drift   Grid   Pwr   Reporter   RGrid   km      az

            String timestamp, txCallsign, txGridsquare, rxCallsign, rxGridsquare;
            Double txFreqMhz, rxSnr, rxDrift, txPower, kmDistance, azimuth;
            if (drupal == true) {
                // Wspr information  for the 'drupal' url query interface.
                // Get wspr info from http://www.wsprnet.org/drupal/wsprnet/spots; e.g.:
                //   <table>
                //   <tr>  <th's> Timestamp           Call   MHz           SNR   Drift   Grid   Pwr   Reporter   RGrid   km      az
                //   <tr>  <td's> 2014-08-25 20:40    DL8EDC  7.040186    -4     0      JO31le     5     LA3JJ/L    JO59bh    925     11
                //   <tr>  <td's> 2014-08-25 20:40    DL8EDC  7.040183    -9     0      JO31le     5     OZ2ABB    JO65au    618     31
                //   <tr>  <td's> 2014-08-25 20:40    DL8EDC  7.040178    -14    0      JO31le     5     OH7FES    KP53bh    1919    37
                //    ... </table>
                // Note: each item in the header or row is a <td> (but not shown above.)
                // Use the Firefox plugin Firebug to determine the html structure:
                //   highlight one of the table rows, right-click on the corresponding <TR> element in the
                //   plugin, then select "Copy CSS Path"; clipboard contains, e.g.:
                //     html.js body.html.not-front.not-logged-in.one-sidebar.sidebar-first.page-wsprnet.page-wsprnet-spots div#page div#middlecontainer div#main div#squeeze div#squeeze-content div#inner-content div.region.region-content div#block-system-main.block.block-system div.content table tbody tr
                //Elements wsprHeader = wsprHtml.select("div#block-system-main.block.block-system div.content table tbody tr:eq(0)");
                //Elements wsprData = wsprHtml.select("div#block-system-main.block.block-system div.content table tbody tr:gt(0)");
                //Element wsprOneRow = wsprData.get(0);  // syntax to get specific element #
                //Elements wsprTDRow = wsprRow.select("th"); // syntax to get header elements
                //Elements wsprTDRow = wsprRow.select("td"); // syntax to get data elements

                // Get rid of "&nbsp;" (non-break space character)
                // Save timestamp as: "yyyyMMddHHmmssSSS"
                timestamp = parseTimestamp(wsprTDRow.get(WSPRNET_IDX_TIMESTAMP).text()
                        .replace(Utility.NBSP, ' ').replace(" .", ".").replace(".0000", "").trim());
                txCallsign = wsprTDRow.get(WSPRNET_IDX_TX_CALLSIGN).text().replace(Utility.NBSP, ' ').trim()
                        .toUpperCase();
                txFreqMhz = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_TX_FREQ_MHZ).text().replace(Utility.NBSP, ' ').trim());
                rxSnr = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_RX_SNR).text().replace(Utility.NBSP, ' ').trim());
                rxDrift = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_RX_DRIFT).text().replace(Utility.NBSP, ' ').trim());
                txGridsquare = wsprTDRow.get(WSPRNET_IDX_TX_GRIDSQUARE).text().replace(Utility.NBSP, ' ')
                        .trim(); // mixed case!
                txPower = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_TX_POWER).text().replace(Utility.NBSP, ' ').trim());
                rxCallsign = wsprTDRow.get(WSPRNET_IDX_RX_CALLSIGN).text().replace(Utility.NBSP, ' ').trim()
                        .toUpperCase();
                rxGridsquare = wsprTDRow.get(WSPRNET_IDX_RX_GRIDSQUARE).text().replace(Utility.NBSP, ' ')
                        .trim(); // mixed case!
                kmDistance = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_DISTANCE).text().replace(Utility.NBSP, ' ').trim());
                azimuth = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_AZIMUTH).text().replace(Utility.NBSP, ' ').trim());
            } else {
                // Wspr information  for the 'old' url query interface.
                //   e.g.: http://wsprnet.org/olddb?mode=html&band=all&limit=10&findcall=&findreporter=&sort=date
                // Save timestamp as: "yyyyMMddHHmmssSSS"
                timestamp = parseTimestamp(wsprTDRow.get(WSPRNET_IDX_OLDDB_TIMESTAMP).text()
                        .replace(Utility.NBSP, ' ').replace(" .", ".").replace(".0000", "").trim());
                txCallsign = wsprTDRow.get(WSPRNET_IDX_OLDDB_TX_CALLSIGN).text().replace(Utility.NBSP, ' ')
                        .trim().toUpperCase();
                txFreqMhz = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_OLDDB_TX_FREQ_MHZ).text().replace(Utility.NBSP, ' ').trim());
                rxSnr = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_OLDDB_RX_SNR).text().replace(Utility.NBSP, ' ').trim());
                rxDrift = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_OLDDB_RX_DRIFT).text().replace(Utility.NBSP, ' ').trim());
                txGridsquare = wsprTDRow.get(WSPRNET_IDX_OLDDB_TX_GRIDSQUARE).text().replace(Utility.NBSP, ' ')
                        .trim(); // mixed case!
                txPower = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_OLDDB_TX_POWER_DBM).text().replace(Utility.NBSP, ' ').trim());
                rxCallsign = wsprTDRow.get(WSPRNET_IDX_OLDDB_RX_CALLSIGN).text().replace(Utility.NBSP, ' ')
                        .trim().toUpperCase();
                rxGridsquare = wsprTDRow.get(WSPRNET_IDX_OLDDB_RX_GRIDSQUARE).text().replace(Utility.NBSP, ' ')
                        .trim(); // mixed case!
                kmDistance = Double.parseDouble(
                        wsprTDRow.get(WSPRNET_IDX_OLDDB_DISTANCE_KM).text().replace(Utility.NBSP, ' ').trim());
                //miDistance = Double.parseDouble(wsprTDRow.get(WSPRNET_IDX_OLDDB_DISTANCE_MILES).text().replace(Utility.NBSP, ' ').trim());
                // azimuth not provided; must calculate it ourselves
                azimuth = Utility.latLongToAzimuth(Utility.gridsquareToLatitude(txGridsquare),
                        Utility.gridsquareToLongitude(txGridsquare), Utility.gridsquareToLatitude(rxGridsquare),
                        Utility.gridsquareToLongitude(rxGridsquare));
            } // parse the html

            // Collect the values together.
            ContentValues wsprValues = new ContentValues();
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_LOC_KEY, locationID);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_TIMESTAMPTEXT, timestamp);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_TX_CALLSIGN, txCallsign);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_TX_FREQ_MHZ, txFreqMhz);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_RX_SNR, rxSnr);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_RX_DRIFT, rxDrift);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_TX_GRIDSQUARE, txGridsquare);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_TX_POWER, txPower);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_RX_CALLSIGN, rxCallsign);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_RX_GRIDSQUARE, rxGridsquare);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_DISTANCE, kmDistance);
            wsprValues.put(WsprNetContract.SignalReportEntry.COLUMN_AZIMUTH, azimuth);
            cVVector.add(wsprValues);

            // Are any reports significant enough to notify the user?
            // For now, notify user if the SNR (signal-to-noise ratio) in a report for a particular
            // band is above a threshold.  The SNR and frequency band are user preferences.
            // TODO: determine the full criteria for notifications.  E.g.:
            //         a specific frequency band has opened up,
            //         maybe to a particular region,
            //         maybe some minimum number of reports at a minimum SNR.
            try {
                iTimestamp = Long
                        .parseLong(timestamp.substring(0, WsprNetContract.TIMESTAMP_FORMAT_DB_SHORT.length()));
                if ((cutoffNotifyTimeMin > 0) && (cutoffNotifyTimeMax > 0)
                        && (cutoffNotifyTimeMin <= iTimestamp) && (iTimestamp < cutoffNotifyTimeMax)) {
                    // getFrequencyBandCheck() will check what band the TX frequency is in.
                    // frequencyBandNotifyCheck will check if it is in the notification band.
                    double bandMHz = getFrequencyBandCheck(context, txFreqMhz, mBandFrequencyTolerancePercent);
                    bandOk = !bandEna || frequencyBandNotifyCheck(bandMHz, notifyBandMHzMin, notifyBandMHzMax);
                    snrOk = !snrEna || (rxSnr >= minSNR);
                    distanceOk = !distanceEna || (kmDistance >= notifyMinTxRxKm);
                    txCallOk = !txCallEna || txCallsign.matches(notifyTxCallsign);
                    rxCallOk = !rxCallEna || rxCallsign.matches(notifyRxCallsign);
                    txGridOk = !txGridEna || txGridsquare.toUpperCase().matches(notifyTxGridsquare);
                    rxGridOk = !rxGridEna || rxGridsquare.toUpperCase().matches(notifyRxGridsquare);
                    if (bandOk && snrOk && distanceOk && txCallOk && rxCallOk && txGridOk && rxGridOk) {
                        nHits++;
                        nHitsBand += (bandEna && bandOk) ? 1 : 0;
                        nHitsSnr += (snrEna && snrOk) ? 1 : 0;
                        nHitsDistance += (distanceEna && distanceOk) ? 1 : 0;
                        nHitsTxCall += (txCallEna && txCallOk) ? 1 : 0;
                        nHitsRxCall += (rxCallEna && rxCallOk) ? 1 : 0;
                        nHitsTxGrid += (txGridEna && txGridEna) ? 1 : 0;
                        nHitsRxGrid += (rxGridEna && rxGridEna) ? 1 : 0;
                    }
                }
            } catch (Exception e) {
                // nothing to do
            }
        } // parse html tags

        // Insert items into database.
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            int ii = context.getContentResolver().bulkInsert(WsprNetContract.SignalReportEntry.CONTENT_URI,
                    cvArray);
            Log.v(LOG_TAG, "getWsprDataFromTags: inserted " + cVVector.size() + "(" + Integer.toString(ii)
                    + ") items");
        }

        // Remove items with an unreasonable timestamp (>24 hours from now); otherwise, they're displayed forever!
        // TODO: don't insert these in the first place!
        cal.setTime(new Date());
        cal.add(Calendar.HOUR, 24);
        String tomorrowTimestamp = WsprNetContract.getDbTimestampString(cal.getTime());
        d = context.getContentResolver().delete(WsprNetContract.SignalReportEntry.CONTENT_URI,
                WsprNetContract.SignalReportEntry.COLUMN_TIMESTAMPTEXT + " > ?",
                new String[] { tomorrowTimestamp });
        Log.v(LOG_TAG, "getWsprDataFromTags: deleted " + Integer.toString(d) + " invalid items.");

        // Did any reports meet the notification criteria?
        if (nHits > 0) {
            String description = "";
            if (notifyBandMHz < 0.00001) {
                bandName = "---";
            } else {
                bandName = getFrequencyBandName(context, mBandNameIdx);
                //description += context.getString(R.string.band_open) + ":";
            }
            if (nHitsTxCall > 0) {
                description += " " + context.getString(R.string.pref_filter_label_tx_callsign) + "="
                        + displayTxCallsign + ";";
            }
            if (nHitsRxCall > 0) {
                description += " " + context.getString(R.string.pref_filter_label_rx_callsign) + "="
                        + displayRxCallsign + ";";
            }
            if (nHitsTxGrid > 0) {
                description += " " + context.getString(R.string.pref_filter_label_tx_gridsquare) + "="
                        + displayTxGridsquare + ";";
            }
            if (nHitsRxGrid > 0) {
                description += " " + context.getString(R.string.pref_filter_label_rx_gridsquare) + "="
                        + displayRxGridsquare + ";";
            }
            if (nHitsDistance > 0) {
                // TODO: Display either km or miles.  See SettingsActivity.java, onPreferenceChange().
                description += " distance>="
                        + Utility.formatDistance(context, notifyMinTxRxKm, Utility.isMetric(context)) + "km;";
            }
            notifyWspr(context, bandName, description, minSNR);
        }

    } catch (Exception e) {
        Log.d(LOG_TAG, "getWsprDataFromTags exception: " + e.toString());

    }
}

From source file:org.mycontroller.standalone.message.McMessageEngine.java

private void internalSubMessageTypeSelector(McMessage mcMessage) {
    //Get node, if node not available create
    Node node = null;/* w  w  w.ja  va2s  .c o  m*/
    if (!mcMessage.getNodeEui().equalsIgnoreCase(McMessage.NODE_BROADCAST_ID)) {
        node = getNode(mcMessage);
    }
    //ResourcesLogs message data
    if (ResourcesLogsUtils.isLevel(LOG_LEVEL.NOTICE)) {
        this.setSensorOtherData(LOG_LEVEL.NOTICE, mcMessage,
                MESSAGE_TYPE_INTERNAL.fromString(mcMessage.getSubType()).getText(), null);
    }
    _logger.debug("Message Type:{}", MESSAGE_TYPE_INTERNAL.fromString(mcMessage.getSubType()).toString());
    switch (MESSAGE_TYPE_INTERNAL.fromString(mcMessage.getSubType())) {
    case I_BATTERY_LEVEL:
        if (mcMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Battery Level:[nodeId:{},Level:{}%]", mcMessage.getNodeEui(), mcMessage.getPayload());
        node.setBatteryLevel(mcMessage.getPayload());
        updateNode(node);
        //Update battery level in to metrics table
        MetricsBatteryUsage batteryUsage = MetricsBatteryUsage.builder().node(node)
                .timestamp(System.currentTimeMillis()).aggregationType(AGGREGATION_TYPE.RAW)
                .avg(McUtils.getDouble(mcMessage.getPayload())).samples(1).build();

        DaoUtils.getMetricsBatteryUsageDao().create(batteryUsage);

        break;
    case I_TIME:
        if (mcMessage.isTxMessage()) {
            return;
        }
        TimeZone timeZone = TimeZone.getDefault();
        long utcTime = System.currentTimeMillis();
        long timeOffset = timeZone.getOffset(utcTime);
        long localTime = utcTime + timeOffset;
        mcMessage.setPayload(String.valueOf(localTime / 1000));
        mcMessage.setTxMessage(true);
        _logger.debug("Time Message:[{}]", mcMessage);
        McMessageUtils.sendToProviderBridge(mcMessage);
        _logger.debug("Time request resolved.");
        break;
    case I_VERSION:
        _logger.debug("GatewayTable version requested by {}! Message:{}", AppProperties.APPLICATION_NAME,
                mcMessage);
        break;
    case I_ID_REQUEST:
        try {
            if (mcMessage.getNetworkType() == NETWORK_TYPE.MY_SENSORS) {
                int nodeId = MySensorsUtils.getNextNodeId(mcMessage.getGatewayId());
                mcMessage.setAcknowledge(false);
                mcMessage.setSubType(MESSAGE_TYPE_INTERNAL.I_ID_RESPONSE.getText());
                mcMessage.setPayload(String.valueOf(nodeId));
                mcMessage.setScreeningDone(false);
                mcMessage.setTxMessage(true);
                McMessageUtils.sendToProviderBridge(mcMessage);
                _logger.debug("New Id[{}] sent to node", nodeId);
            }
        } catch (NodeIdException ex) {
            _logger.error("Unable to generate new node Id,", ex);
            //ResourcesLogs message data
            if (ResourcesLogsUtils.isLevel(LOG_LEVEL.ERROR)) {
                this.setSensorOtherData(LOG_LEVEL.ERROR, mcMessage,
                        MESSAGE_TYPE_INTERNAL.fromString(mcMessage.getSubType()).getText(), ex.getMessage());
            }

        }
        break;
    case I_INCLUSION_MODE:
        _logger.warn("Inclusion mode not supported by this controller! Message:{}", mcMessage);
        break;
    case I_CONFIG:
        if (mcMessage.isTxMessage()) {
            return;
        }
        mcMessage.setPayload(McMessageUtils.getMetricType());
        mcMessage.setTxMessage(true);
        McMessageUtils.sendToProviderBridge(mcMessage);
        _logger.debug("Configuration sent as follow[M/I]?:{}", mcMessage.getPayload());
        break;
    case I_LOG_MESSAGE:
        if (mcMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Node trace-log message[nodeId:{},sensorId:{},message:{}]", mcMessage.getNodeEui(),
                mcMessage.getSensorId(), mcMessage.getPayload());
        break;
    case I_SKETCH_NAME:
        if (mcMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Internal Message[type:{},name:{}]",
                MESSAGE_TYPE_INTERNAL.fromString(mcMessage.getSubType()), mcMessage.getPayload());
        node = getNode(mcMessage);
        node.setName(mcMessage.getPayload());
        updateNode(node);
        break;
    case I_SKETCH_VERSION:
        if (mcMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Internal Message[type:{},version:{}]",
                MESSAGE_TYPE_INTERNAL.fromString(mcMessage.getSubType()), mcMessage.getPayload());
        node = getNode(mcMessage);
        node.setVersion(mcMessage.getPayload());
        updateNode(node);
        break;
    case I_REBOOT:
        break;
    case I_GATEWAY_READY:
        if (mcMessage.isTxMessage()) {
            return;
        }
        _logger.debug("GatewayTable Ready[nodeId:{},message:{}]", mcMessage.getNodeEui(),
                mcMessage.getPayload());
        break;

    case I_ID_RESPONSE:
        _logger.debug("Internal Message, Type:I_ID_RESPONSE[{}]", mcMessage);
        return;
    case I_HEARTBEAT:
    case I_HEARTBEAT_RESPONSE:
        if (mcMessage.isTxMessage()) {
            return;
        }
        node = getNode(mcMessage);
        node.setState(STATE.UP);
        updateNode(node);
        break;
    case I_DISCOVER:
        if (mcMessage.isTxMessage()) {
            return;
        }
    case I_DISCOVER_RESPONSE:
        if (mcMessage.isTxMessage()) {
            return;
        }
        node = getNode(mcMessage);
        node.setParentNodeEui(mcMessage.getPayload());
        updateNode(node);
        break;
    case I_DEBUG:
        if (ResourcesLogsUtils.isLevel(LOG_LEVEL.NOTICE)) {
            this.setSensorOtherData(LOG_LEVEL.NOTICE, mcMessage,
                    MESSAGE_TYPE_PRESENTATION.fromString(mcMessage.getSubType()).getText(),
                    mcMessage.getPayload());
        }
        break;
    case I_REGISTRATION_REQUEST:
        if (mcMessage.isTxMessage()) {
            return;
        }
        if (AppProperties.getInstance().getControllerSettings().getAutoNodeRegistration()) {
            mcMessage.setAcknowledge(false);
            mcMessage.setSubType(MESSAGE_TYPE_INTERNAL.I_REGISTRATION_RESPONSE.getText());
            mcMessage.setScreeningDone(false);
            mcMessage.setTxMessage(true);
            McMessageUtils.sendToProviderBridge(mcMessage);
            _logger.debug("Registration response sent to gateway:{}, node:{}", mcMessage.getGatewayId(),
                    mcMessage.getNodeEui());
        }
        break;
    case I_REGISTRATION_RESPONSE:
        if (mcMessage.isTxMessage()) {
            return;
        }
        //TODO: do some action, if controller want to react for this type of message
    case I_PRESENTATION:
        if (mcMessage.isTxMessage()) {
            return;
        }
    default:
        _logger.warn(
                "Internal Message[type:{},payload:{}], "
                        + "This type may not be supported (or) not implemented yet",
                MESSAGE_TYPE_INTERNAL.fromString(mcMessage.getSubType()), mcMessage.getPayload());
        break;
    }
}

From source file:org.apache.calcite.runtime.SqlFunctions.java

public static long toLong(java.util.Date v, TimeZone timeZone) {
    final long time = v.getTime();
    return time + timeZone.getOffset(time);
}

From source file:com.leanplum.Leanplum.java

private static void startHelper(String userId, final Map<String, ?> attributes, final boolean isBackground) {
    LeanplumPushService.onStart();/*from   w  ww .  j a v a2  s  .  c  o  m*/

    Boolean limitAdTracking = null;
    String deviceId = Request.deviceId();
    if (deviceId == null) {
        if (!userSpecifiedDeviceId && Constants.defaultDeviceId != null) {
            deviceId = Constants.defaultDeviceId;
        } else if (customDeviceId != null) {
            deviceId = customDeviceId;
        } else {
            DeviceIdInfo deviceIdInfo = Util.getDeviceId(deviceIdMode);
            deviceId = deviceIdInfo.id;
            limitAdTracking = deviceIdInfo.limitAdTracking;
        }
        Request.setDeviceId(deviceId);
    }

    if (userId == null) {
        userId = Request.userId();
        if (userId == null) {
            userId = Request.deviceId();
        }
    }
    Request.setUserId(userId);

    // Setup parameters.
    String versionName = Util.getVersionName();
    if (versionName == null) {
        versionName = "";
    }

    TimeZone localTimeZone = TimeZone.getDefault();
    Date now = new Date();
    int timezoneOffsetSeconds = localTimeZone.getOffset(now.getTime()) / 1000;

    HashMap<String, Object> params = new HashMap<>();
    params.put(Constants.Params.INCLUDE_DEFAULTS, Boolean.toString(false));
    if (isBackground) {
        params.put(Constants.Params.BACKGROUND, Boolean.toString(true));
    }
    params.put(Constants.Params.VERSION_NAME, versionName);
    params.put(Constants.Params.DEVICE_NAME, Util.getDeviceName());
    params.put(Constants.Params.DEVICE_MODEL, Util.getDeviceModel());
    params.put(Constants.Params.DEVICE_SYSTEM_NAME, Util.getSystemName());
    params.put(Constants.Params.DEVICE_SYSTEM_VERSION, Util.getSystemVersion());
    params.put(Constants.Keys.TIMEZONE, localTimeZone.getID());
    params.put(Constants.Keys.TIMEZONE_OFFSET_SECONDS, Integer.toString(timezoneOffsetSeconds));
    params.put(Constants.Keys.LOCALE, Util.getLocale());
    params.put(Constants.Keys.COUNTRY, Constants.Values.DETECT);
    params.put(Constants.Keys.REGION, Constants.Values.DETECT);
    params.put(Constants.Keys.CITY, Constants.Values.DETECT);
    params.put(Constants.Keys.LOCATION, Constants.Values.DETECT);
    if (Boolean.TRUE.equals(limitAdTracking)) {
        params.put(Constants.Params.LIMIT_TRACKING, limitAdTracking.toString());
    }
    if (attributes != null) {
        params.put(Constants.Params.USER_ATTRIBUTES, JsonConverter.toJson(attributes));
    }
    if (Constants.isDevelopmentModeEnabled) {
        params.put(Constants.Params.DEV_MODE, Boolean.TRUE.toString());
    }

    // Get the current inbox messages on the device.
    params.put(Constants.Params.INBOX_MESSAGES, LeanplumInbox.getInstance().messagesIds());

    Util.initializePreLeanplumInstall(params);

    // Issue start API call.
    Request req = Request.post(Constants.Methods.START, params);
    req.onApiResponse(new Request.ApiResponseCallback() {
        @Override
        public void response(List<Map<String, Object>> requests, JSONObject response) {
            Leanplum.handleApiResponse(response, requests);
        }
    });

    if (isBackground) {
        req.sendEventually();
    } else {
        req.sendIfConnected();
    }

    LeanplumInternal.triggerStartIssued();
}

From source file:joshuatee.wx.ModelInterfaceActivity.java

private String ConvertTimeRuntoTimeString(String run_str, String time_str) {

    int run_int = Integer.parseInt(run_str);
    int time_int = Integer.parseInt(time_str);
    int real_time_gmt = run_int + time_int;
    TimeZone tz = TimeZone.getDefault();
    Date now = new Date(System.currentTimeMillis());
    int offsetFromUtc = tz.getOffset(now.getTime()) / 1000;
    int real_time = real_time_gmt + offsetFromUtc / 60 / 60;
    int hour_of_day = real_time % 24;
    String am_pm = "";
    if (hour_of_day > 11) {
        am_pm = "pm";
        if (hour_of_day > 12) {
            hour_of_day = hour_of_day - 12;
        }/*from ww  w  .j a v  a2s .c o  m*/
    } else {
        am_pm = "am";
    }

    int day = (int) real_time / 24;

    if (hour_of_day < 0) {
        hour_of_day = 12 + hour_of_day;
        am_pm = "pm";
        day--;
    }

    Calendar calendar = Calendar.getInstance();
    int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
    int hour_of_day_local = calendar.get(Calendar.HOUR_OF_DAY);

    if (run_int >= 0 && run_int < -offsetFromUtc / 60 / 60
            && (hour_of_day_local - offsetFromUtc / 60 / 60) >= 24) {
        day++;
    }

    String future_day = "";

    switch ((day_of_week + day) % 7) {
    case Calendar.SUNDAY:
        future_day = "Sun";
        break;
    case Calendar.MONDAY:
        future_day = "Mon";
        break;
    case Calendar.TUESDAY:
        future_day = "Tue";
        break;
    case Calendar.WEDNESDAY:
        future_day = "Wed";
        break;
    case Calendar.THURSDAY:
        future_day = "Thu";
        break;
    case Calendar.FRIDAY:
        future_day = "Fri";
        break;
    case 0:

        future_day = "Sat";
        break;
    }

    //return  future_day + "  "+hour_of_day.toString()+ am_pm;
    return future_day + "  " + Integer.toString(hour_of_day) + am_pm;

}

From source file:org.sakaiproject.component.section.sakai.CourseSectionImpl.java

public static final Time convertStringToTime(String str) {
    if (StringUtils.trimToNull(str) == null) {
        return null;
    }//from  www.  ja  v  a  2  s .  c  o m
    try {
        SimpleDateFormat sdf = new SimpleDateFormat(CourseSectionImpl.TIME_FORMAT_LONG);
        return new Time(sdf.parse(str).getTime());
    } catch (Exception e) {

        // Stored in other format, with date and time zone. 
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(CourseSectionImpl.TIME_FORMAT_DATE_TZ);

            Calendar src = new GregorianCalendar();
            src.setTime(sdf.parse(str));
            src.setTimeInMillis(src.getTimeInMillis());

            TimeZone srcTz = sdf.getTimeZone();
            TimeZone userTz = timeService.getLocalTimeZone();
            TimeZone serverTz = TimeZone.getDefault();

            Calendar now = new GregorianCalendar(userTz);

            // STORED IN DAYLIGHT SAVING TIME and NOW IS STANDARD
            if (srcTz.inDaylightTime(src.getTime()) && !srcTz.inDaylightTime(now.getTime())) {
                src.setTimeInMillis(src.getTimeInMillis() + srcTz.getDSTSavings());
            }

            // STORED IN STANDAR TIME and NOW IS DAYLIGHT SAVING TIME
            if (srcTz.inDaylightTime(now.getTime()) && !srcTz.inDaylightTime(src.getTime())) {
                src.setTimeInMillis(src.getTimeInMillis() - srcTz.getDSTSavings());
            }

            // DO THE SAME IN SERVER TIMEZONE
            if (serverTz.inDaylightTime(src.getTime()) && !serverTz.inDaylightTime(now.getTime())) {
                src.setTimeInMillis(src.getTimeInMillis() - serverTz.getDSTSavings());
            }

            if (serverTz.inDaylightTime(now.getTime()) && !serverTz.inDaylightTime(src.getTime())) {
                src.setTimeInMillis(src.getTimeInMillis() + serverTz.getDSTSavings());
            }

            src.set(Calendar.DAY_OF_MONTH, now.get(Calendar.DAY_OF_MONTH));
            src.set(Calendar.YEAR, now.get(Calendar.YEAR));
            src.set(Calendar.MONTH, now.get(Calendar.MONTH));

            return new Time(src.getTimeInMillis() + userTz.getOffset(now.getTimeInMillis())
                    - serverTz.getOffset(now.getTimeInMillis()));

        } catch (Exception ex) {
            if (log.isDebugEnabled())
                log.debug("Unable to parse " + str);
            return null;
        }
    }
}

From source file:com.seajas.search.attender.service.attender.dao.ProfileDAO.java

/**
 * Find all notifiable subscribers from the given profile.
 * //from  w  w w .j  av  a2s .  c o m
 * @param calendar
 * @param profile
 * @return List<ProfileSubscriber>
 */
public List<ProfileSubscriber> findNotifiableSubscribers(final Calendar calendar,
        final List<ProfileSubscriber> subscribers) {
    if (!calendar.getTimeZone().getID().equals("UTC"))
        throw new IllegalArgumentException(
                "The given calendar must have a UTC timezone (has " + calendar.getTimeZone().getID() + ")");

    // Calculate the current time in UTC

    Integer currentHour = calendar.get(Calendar.HOUR_OF_DAY), currentMinute = calendar.get(Calendar.MINUTE),
            currentDay = calendar.get(Calendar.DAY_OF_WEEK);
    Date currentTime = new Date(calendar.getTimeInMillis());

    // Return a list of all applicable subscribers for this profile

    List<ProfileSubscriber> result = new ArrayList<ProfileSubscriber>();

    // Find all active profiles' confirmed subscribers whose notification preference fall within the current day and whose time
    // values are greater than or equal to the current hour / minute; then take 7 days for weekly updates, 1 for daily updates,
    // and 1 for weekdays where Saturday / Sunday are excluded

    for (ProfileSubscriber subscriber : subscribers) {
        Integer subscriberDay = subscriber.getNotificationDay(),
                subscriberHour = subscriber.getNotificationHour(),
                subscriberMinute = subscriber.getNotificationMinute();
        Date lastNotification = subscriber.getLastNotification();
        NotificationType subscriberType = subscriber.getNotificationType();

        // Correct for the user-specific timezone

        TimeZone timeZone = TimeZone.getTimeZone(subscriber.getTimeZone());

        // Take leap seconds into account, although we're not so precise to really care

        if (subscriberMinute != null) {
            subscriberMinute -= (int) ((timeZone.getOffset(calendar.getTimeInMillis()) % MILLISECONDS_PER_HOUR)
                    / MILLISECONDS_PER_MINUTE);

            if (subscriberMinute < 0) {
                subscriberMinute += 60;
                subscriberHour--;
            } else if (subscriberMinute > 59) {
                subscriberMinute -= 60;
                subscriberHour++;
            }
        }

        if (subscriberHour != null) {
            subscriberHour -= (int) (timeZone.getOffset(calendar.getTimeInMillis()) / MILLISECONDS_PER_HOUR);

            if (subscriberHour < 0) {
                subscriberHour += 24;

                if (subscriberDay != null)
                    subscriberDay--;
            } else if (subscriberHour > 23) {
                subscriberHour -= 24;

                if (subscriberDay != null)
                    subscriberDay++;
            }
        }

        if (subscriberDay == -1)
            subscriberDay = 6;
        else if (subscriberDay == 7)
            subscriberDay = 0;

        // Now determine the actual applicability (last_notification is stored as a UTC date, so does not need to be converted)

        if (subscriber.getIsConfirmed() && ((subscriberType.equals(NotificationType.Weekly)
                && subscriberDay.equals(currentDay) && subscriberHour <= currentHour
                && subscriberMinute <= currentMinute && dateDifference(lastNotification, currentTime) >= 6)
                || (subscriberType.equals(NotificationType.Weekdays) && currentDay != Calendar.SATURDAY
                        && currentDay != Calendar.SUNDAY && subscriberHour <= currentHour
                        && subscriberMinute <= currentMinute
                        && !DateUtils.isSameDay(lastNotification, currentTime))
                || (subscriberType.equals(NotificationType.Daily) && subscriberHour <= currentHour
                        && subscriberMinute <= currentMinute
                        && !DateUtils.isSameDay(lastNotification, currentTime)))) {
            if (logger.isInfoEnabled())
                logger.info("Adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                        + subscriber.getEmail() + "' to be notified");

            result.add(subscriber);
        } else if (logger.isDebugEnabled()) {
            if (!subscriber.getIsConfirmed())
                logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                        + subscriber.getEmail() + "' - not confirmed");
            else if (subscriberType.equals(NotificationType.Direct))
                logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                        + subscriber.getEmail()
                        + "' - direct notifications are handled by search-enricher instances");
            else if (subscriberType.equals(NotificationType.Weekly)) {
                if (!subscriberDay.equals(currentDay))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekly notification does not fall on current day");
                if (!(subscriberHour <= currentHour && subscriberMinute <= currentMinute))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekly notification falls outside of current time");
                if (!(dateDifference(lastNotification, currentTime) >= 6))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail()
                            + "' - weekly notification difference (in days) smaller than 7");
            } else if (subscriberType.equals(NotificationType.Weekdays)) {
                if (!(currentDay != Calendar.SATURDAY && currentDay != Calendar.SUNDAY))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekday notification does not fall on weekday");
                if (!(subscriberHour <= currentHour && subscriberMinute <= currentMinute))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekday notification falls outside of current time");
                if (DateUtils.isSameDay(lastNotification, currentTime))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail()
                            + "' - weekday notification difference indicates a notification has already gone out today");
            } else if (subscriberType.equals(NotificationType.Daily)) {
                if (!(subscriberHour <= currentHour && subscriberMinute <= currentMinute))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - daily notification falls outside of current time");
                if (DateUtils.isSameDay(lastNotification, currentTime))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail()
                            + "' - daily notification difference indicates a notification has already gone out today");
            }
        }
    }

    return result;
}

From source file:com.cloud.api.ApiServer.java

public void loginUser(HttpSession session, String username, String password, Long domainId, String domainPath,
        String loginIpAddress, Map<String, Object[]> requestParameters) throws CloudAuthenticationException {
    // We will always use domainId first. If that does not exist, we will use domain name. If THAT doesn't exist
    // we will default to ROOT
    if (domainId == null) {
        if (domainPath == null || domainPath.trim().length() == 0) {
            domainId = DomainVO.ROOT_DOMAIN;
        } else {/*  w w w .ja  v  a  2  s .c  o  m*/
            Domain domainObj = _domainMgr.findDomainByPath(domainPath);
            if (domainObj != null) {
                domainId = domainObj.getId();
            } else { // if an unknown path is passed in, fail the login call
                throw new CloudAuthenticationException("Unable to find the domain from the path " + domainPath);
            }
        }
    }

    UserAccount userAcct = _accountMgr.authenticateUser(username, password, domainId, loginIpAddress,
            requestParameters);
    if (userAcct != null) {
        String timezone = userAcct.getTimezone();
        float offsetInHrs = 0f;
        if (timezone != null) {
            TimeZone t = TimeZone.getTimeZone(timezone);
            s_logger.info("Current user logged in under " + timezone + " timezone");

            java.util.Date date = new java.util.Date();
            long longDate = date.getTime();
            float offsetInMs = (t.getOffset(longDate));
            offsetInHrs = offsetInMs / (1000 * 60 * 60);
            s_logger.info("Timezone offset from UTC is: " + offsetInHrs);
        }

        Account account = _accountMgr.getAccount(userAcct.getAccountId());

        // set the userId and account object for everyone
        session.setAttribute("userid", userAcct.getId());
        UserVO user = (UserVO) _accountMgr.getActiveUser(userAcct.getId());
        if (user.getUuid() != null) {
            session.setAttribute("user_UUID", user.getUuid());
        }

        session.setAttribute("username", userAcct.getUsername());
        session.setAttribute("firstname", userAcct.getFirstname());
        session.setAttribute("lastname", userAcct.getLastname());
        session.setAttribute("accountobj", account);
        session.setAttribute("account", account.getAccountName());

        session.setAttribute("domainid", account.getDomainId());
        DomainVO domain = (DomainVO) _domainMgr.getDomain(account.getDomainId());
        if (domain.getUuid() != null) {
            session.setAttribute("domain_UUID", domain.getUuid());
        }

        session.setAttribute("type", Short.valueOf(account.getType()).toString());
        session.setAttribute("registrationtoken", userAcct.getRegistrationToken());
        session.setAttribute("registered", new Boolean(userAcct.isRegistered()).toString());

        if (timezone != null) {
            session.setAttribute("timezone", timezone);
            session.setAttribute("timezoneoffset", Float.valueOf(offsetInHrs).toString());
        }

        // (bug 5483) generate a session key that the user must submit on every request to prevent CSRF, add that
        // to the login response so that session-based authenticators know to send the key back
        SecureRandom sesssionKeyRandom = new SecureRandom();
        byte sessionKeyBytes[] = new byte[20];
        sesssionKeyRandom.nextBytes(sessionKeyBytes);
        String sessionKey = Base64.encodeBase64String(sessionKeyBytes);
        session.setAttribute("sessionkey", sessionKey);

        return;
    }
    throw new CloudAuthenticationException("Failed to authenticate user " + username + " in domain " + domainId
            + "; please provide valid credentials");
}