Example usage for java.text DateFormat setTimeZone

List of usage examples for java.text DateFormat setTimeZone

Introduction

In this page you can find the example usage for java.text DateFormat setTimeZone.

Prototype

public void setTimeZone(TimeZone zone) 

Source Link

Document

Sets the time zone for the calendar of this DateFormat object.

Usage

From source file:com.clustercontrol.agent.winevent.WinEventMonitor.java

/**
 * XMLStAX???EventLogRecord????//from   w ww .  ja v a2 s  .c o m
 * @param eventXmlStream
 * @return EventLogRecord?
 */
private ArrayList<EventLogRecord> parseEventXML(InputStream eventXmlStream) {
    ArrayList<EventLogRecord> eventlogs = new ArrayList<EventLogRecord>();

    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();
        /**
         * OpenJDK7/OracleJDK7??"]"?2?????????????????????????????
         * ?XML?????????OpenJDK7/OracleJDK7???????/??????????
         * URL???????????????
         * 
         * URL
         * http://docs.oracle.com/javase/jp/6/api/javax/xml/stream/XMLStreamReader.html#next()
         */
        String xmlCoalescingKey = "javax.xml.stream.isCoalescing";// TODO JRE???????????????????
        if (m_log.isDebugEnabled()) {
            m_log.debug(xmlCoalescingKey + " = true");
        }
        xmlif.setProperty(xmlCoalescingKey, true);
        XMLStreamReader xmlr = xmlif.createXMLStreamReader(eventXmlStream);

        while (xmlr.hasNext()) {
            switch (xmlr.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                m_log.trace("EventType : XMLStreamConstants.START_ELEMENT");

                String localName = xmlr.getLocalName();
                m_log.trace("local name : " + localName);

                if ("Event".equals(localName)) {
                    EventLogRecord eventlog = new EventLogRecord();
                    eventlogs.add(eventlog);
                    m_log.debug("create new EventLogRecord");
                } else {
                    String attrLocalName = null;
                    String attrValue = null;

                    if (xmlr.getAttributeCount() != 0) {
                        attrLocalName = xmlr.getAttributeLocalName(0);
                        attrValue = xmlr.getAttributeValue(0);
                        m_log.trace("attribute local name : " + attrLocalName);
                        m_log.trace("attribute local value : " + attrValue);
                    }

                    if ("Provider".equals(localName)) {
                        if ("Name".equals(attrLocalName)) {
                            m_log.trace("target value : " + attrValue);

                            EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                            eventlog.setProviderName(attrValue);
                            m_log.debug("set ProviderName : " + eventlog.getProviderName());
                        }
                    }
                    // Get-WinEvent/wevtutil.exe
                    else if ("TimeCreated".equals(localName) && "SystemTime".equals(attrLocalName)) {
                        m_log.trace("target value : " + attrValue);

                        // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'"???S????????????
                        String formatedDateString = attrValue.replaceAll("\\..*Z", "");
                        m_log.trace("formatted target value : " + formatedDateString);
                        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

                        EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                        ;
                        try {
                            eventlog.setTimeCreated(sdf.parse(formatedDateString));
                        } catch (ParseException e) {
                            // do nothing
                            m_log.error("set TimeCreated Error", e);
                        }
                        m_log.debug("set TimeCreated : " + eventlog.getTimeCreated());
                    }
                    // Get-EventLog
                    if ("TimeGenerated".equals(localName) && "SystemTime".equals(attrLocalName)) {
                        m_log.trace("target value : " + attrValue);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'Z'");
                        sdf.setTimeZone(HinemosTime.getTimeZone());

                        EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                        ;
                        try {
                            eventlog.setTimeCreated(sdf.parse(attrValue));
                        } catch (ParseException e) {
                            // do nothing
                            m_log.error("set TimeCreated Error", e);
                        }
                        m_log.debug("set TimeCreated : " + eventlog.getTimeCreated());
                    } else {
                        targetProperty = localName;
                        m_log.trace("target property : " + targetProperty);
                    }
                }

                break;
            case XMLStreamConstants.SPACE:
            case XMLStreamConstants.CHARACTERS:
                m_log.trace("EventType : XMLStreamConstants.CHARACTERS, length=" + xmlr.getTextLength());
                if (targetProperty != null) {
                    try {
                        EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                        ;
                        if ("EventID".equals(targetProperty)) {
                            eventlog.setId(Integer.parseInt(new String(xmlr.getTextCharacters(),
                                    xmlr.getTextStart(), xmlr.getTextLength())));
                            m_log.debug("set EventID : " + eventlog.getId());
                        }
                        // Get-WinEvent/wevtutil.exe
                        else if ("Level".equals(targetProperty)) {
                            if (eventlog.getLevel() == WinEventConstant.UNDEFINED) {
                                eventlog.setLevel(Integer.parseInt(new String(xmlr.getTextCharacters(),
                                        xmlr.getTextStart(), xmlr.getTextLength())));
                                m_log.debug("set Level : " + eventlog.getLevel());
                            }
                        } else if ("Task".equals(targetProperty)) {
                            if (eventlog.getTask() == WinEventConstant.UNDEFINED) {
                                eventlog.setTask(Integer.parseInt(new String(xmlr.getTextCharacters(),
                                        xmlr.getTextStart(), xmlr.getTextLength())));
                                m_log.debug("set Task : " + eventlog.getTask());
                            }
                        } else if ("Keywords".equals(targetProperty)) {
                            // TODO ????????0x8080000000000000
                            //eventlog.setKeywords(Long.decode(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength())));
                            //m_log.debug("set Keywords : " + eventlog.getKeywords());
                        } else if ("EventRecordId".equals(targetProperty)) {
                            eventlog.setRecordId(Long.parseLong(new String(xmlr.getTextCharacters(),
                                    xmlr.getTextStart(), xmlr.getTextLength())));
                            m_log.debug("set RecordId : " + eventlog.getRecordId());
                        } else if ("Channel".equals(targetProperty)) {
                            eventlog.setLogName(new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength()));
                            m_log.debug("set LogName : " + eventlog.getLogName());
                        } else if ("Computer".equals(targetProperty)) {
                            eventlog.setMachineName(new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength()));
                            m_log.debug("set MachineName : " + eventlog.getMachineName());
                        } else if ("Message".equals(targetProperty)) {
                            String message = new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength());
                            message = message.replaceAll(tmpReturnCode, "\r\n");
                            message = message.replaceAll(tmpLtCode, "<");
                            message = message.replaceAll(tmpGtCode, ">");
                            eventlog.setMessage(message);
                            m_log.debug("set Message : " + eventlog.getMessage());
                        } else if ("Data".equals(targetProperty)) {
                            String data = new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength());
                            eventlog.getData().add(data);
                            m_log.debug("set Data : " + data);
                        } else {
                            m_log.debug("unknown target property : " + targetProperty);
                        }
                    } catch (NumberFormatException e) {
                        m_log.debug("number parse error", e);
                    }
                }
                targetProperty = null;
                break;
            default: // 
                break;
            }
            xmlr.next();
        }
        xmlr.close();
    } catch (XMLStreamException e) {
        m_log.warn("parseEvent() xmlstream error", e);
    }

    return eventlogs;

}

From source file:at.alladin.rmbt.controlServer.TestResultResource.java

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();//from  w  ww.  j av a2 s  . c o  m

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    System.out.println(MessageFormat.format(labels.getString("NEW_TESTRESULT"), clientIpRaw));

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            String lang = request.optString("language");

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            } else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

            //                System.out.println(request.toString(4));

            if (conn != null) {
                final Client client = new Client(conn);
                final Test test = new Test(conn);

                final String testUuid = request.optString("test_uuid");
                if (testUuid != null && test.getTestByUuid(UUID.fromString(testUuid)) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())
                        && "FINISHED".equals(test.getField("status").toString())) {

                    final Locale locale = new Locale(lang);
                    final Format format = new SignificantFormat(2, locale);

                    final JSONArray resultList = new JSONArray();

                    final JSONObject jsonItem = new JSONObject();

                    JSONArray jsonItemList = new JSONArray();

                    // RMBTClient Info
                    //also send open-uuid (starts with 'P')
                    final String openUUID = "P" + ((UUIDField) test.getField("open_uuid")).toString();
                    jsonItem.put("open_uuid", openUUID);

                    //and open test-uuid (starts with 'O')
                    final String openTestUUID = "O" + ((UUIDField) test.getField("open_test_uuid")).toString();
                    jsonItem.put("open_test_uuid", openTestUUID);

                    final Date date = ((TimestampField) test.getField("time")).getDate();
                    final long time = date.getTime();
                    final String tzString = test.getField("timezone").toString();
                    final TimeZone tz = TimeZone.getTimeZone(tzString);
                    jsonItem.put("time", time);
                    jsonItem.put("timezone", tzString);
                    final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                            DateFormat.MEDIUM, locale);
                    dateFormat.setTimeZone(tz);
                    final String timeString = dateFormat.format(date);
                    jsonItem.put("time_string", timeString);

                    final Field fieldDown = test.getField("speed_download");
                    JSONObject singleItem = new JSONObject();
                    singleItem.put("title", labels.getString("RESULT_DOWNLOAD"));
                    final String downloadString = String.format("%s %s",
                            format.format(fieldDown.doubleValue() / 1000d),
                            labels.getString("RESULT_DOWNLOAD_UNIT"));
                    singleItem.put("value", downloadString);
                    singleItem.put("classification",
                            Classification.classify(classification.THRESHOLD_DOWNLOAD, fieldDown.intValue()));

                    jsonItemList.put(singleItem);

                    final Field fieldUp = test.getField("speed_upload");
                    singleItem = new JSONObject();
                    singleItem.put("title", labels.getString("RESULT_UPLOAD"));
                    final String uploadString = String.format("%s %s",
                            format.format(fieldUp.doubleValue() / 1000d),
                            labels.getString("RESULT_UPLOAD_UNIT"));
                    singleItem.put("value", uploadString);
                    singleItem.put("classification",
                            Classification.classify(classification.THRESHOLD_UPLOAD, fieldUp.intValue()));

                    jsonItemList.put(singleItem);

                    final Field fieldPing = test.getField("ping_median");
                    String pingString = "";
                    if (!fieldPing.isNull()) {
                        final double pingValue = fieldPing.doubleValue() / 1000000d;
                        singleItem = new JSONObject();
                        singleItem.put("title", labels.getString("RESULT_PING"));
                        pingString = String.format("%s %s", format.format(pingValue),
                                labels.getString("RESULT_PING_UNIT"));
                        singleItem.put("value", pingString);
                        singleItem.put("classification",
                                Classification.classify(classification.THRESHOLD_PING, fieldPing.longValue()));

                        jsonItemList.put(singleItem);
                    }

                    final int networkType = test.getField("network_type").intValue();

                    final Field signalField = test.getField("signal_strength"); // signal strength as RSSI (GSM, UMTS, Wifi, sometimes LTE)
                    final Field lteRsrpField = test.getField("lte_rsrp"); // signal strength as RSRP, used in LTE
                    String signalString = null;
                    if (!signalField.isNull() || !lteRsrpField.isNull()) {
                        if (lteRsrpField.isNull()) { // only RSSI value, output RSSI to JSON  
                            final int signalValue = signalField.intValue();
                            final int[] threshold = networkType == 99 || networkType == 0
                                    ? classification.THRESHOLD_SIGNAL_WIFI
                                    : classification.THRESHOLD_SIGNAL_MOBILE;
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_SIGNAL"));
                            signalString = signalValue + " " + labels.getString("RESULT_SIGNAL_UNIT");
                            singleItem.put("value", signalString);
                            singleItem.put("classification", Classification.classify(threshold, signalValue));
                        } else { // use RSRP value else (RSRP value has priority if both are available (e.g. 3G/4G-test))
                            final int signalValue = lteRsrpField.intValue();
                            final int[] threshold = classification.THRESHOLD_SIGNAL_RSRP;
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_SIGNAL_RSRP"));
                            signalString = signalValue + " " + labels.getString("RESULT_SIGNAL_UNIT");
                            singleItem.put("value", signalString);
                            singleItem.put("classification", Classification.classify(threshold, signalValue));

                        }
                        jsonItemList.put(singleItem);
                    }

                    jsonItem.put("measurement", jsonItemList);

                    jsonItemList = new JSONArray();

                    singleItem = new JSONObject();
                    singleItem.put("title", labels.getString("RESULT_NETWORK_TYPE"));
                    final String networkTypeString = Helperfunctions.getNetworkTypeName(networkType);
                    singleItem.put("value", networkTypeString);

                    jsonItemList.put(singleItem);

                    if (networkType == 98 || networkType == 99) // mobile wifi or browser
                    {
                        final Field providerNameField = test.getField("provider_id_name");
                        if (!providerNameField.isNull()) {
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_OPERATOR_NAME"));
                            singleItem.put("value", providerNameField.toString());
                            jsonItemList.put(singleItem);
                        }
                        if (networkType == 99) // mobile wifi
                        {
                            final Field ssid = test.getField("wifi_ssid");
                            if (!ssid.isNull()) {
                                singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_WIFI_SSID"));
                                singleItem.put("value", ssid.toString());
                                jsonItemList.put(singleItem);
                            }

                        }
                    } else // mobile
                    {
                        final Field operatorNameField = test.getField("network_operator_name");
                        if (!operatorNameField.isNull()) {
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_OPERATOR_NAME"));
                            singleItem.put("value", operatorNameField.toString());
                            jsonItemList.put(singleItem);
                        }

                        final Field roamingTypeField = test.getField("roaming_type");
                        if (!roamingTypeField.isNull() && roamingTypeField.intValue() > 0) {
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_ROAMING"));
                            singleItem.put("value",
                                    Helperfunctions.getRoamingType(labels, roamingTypeField.intValue()));
                            jsonItemList.put(singleItem);
                        }
                    }

                    jsonItem.put("net", jsonItemList);

                    final Field latField = test.getField("geo_lat");
                    final Field longField = test.getField("geo_long");
                    boolean includeLocation = false;
                    final Field accuracyField = test.getField("geo_accuracy");
                    if (!(latField.isNull() || longField.isNull() || accuracyField.isNull())) {
                        final double accuracy = accuracyField.doubleValue();
                        if (accuracy < Double.parseDouble(getSetting("rmbt_geo_accuracy_button_limit", lang))) {
                            includeLocation = true;
                            jsonItem.put("geo_lat", latField.doubleValue());
                            jsonItem.put("geo_long", longField.doubleValue());
                        }
                    }

                    //geo location
                    JSONObject locationJson = TestResultDetailResource.getGeoLocation(this, test, settings,
                            conn, labels);
                    if (locationJson != null) {
                        if (locationJson.has("location")) {
                            jsonItem.put("location", locationJson.getString("location"));
                        }
                        if (locationJson.has("motion")) {
                            jsonItem.put("motion", locationJson.getString("motion"));
                        }
                    }

                    resultList.put(jsonItem);

                    final Field zip_code = test.getField("zip_code");
                    if (!zip_code.isNull())
                        jsonItem.put("zip_code", zip_code.intValue());

                    final Field zip_code_geo = test.getField("zip_code_geo");
                    if (!zip_code_geo.isNull())
                        jsonItem.put("zip_code_geo", zip_code_geo.intValue());

                    String providerString = test.getField("provider_id_name").toString();
                    if (providerString == null)
                        providerString = "";
                    String platformString = test.getField("plattform").toString();
                    if (platformString == null)
                        platformString = "";
                    String modelString = test.getField("model_fullname").toString();
                    if (modelString == null)
                        modelString = "";

                    String mobileNetworkString = null;
                    final Field networkOperatorField = test.getField("network_operator");
                    final Field mobileProviderNameField = test.getField("mobile_provider_name");
                    if (!networkOperatorField.isNull()) {
                        if (mobileProviderNameField.isNull())
                            mobileNetworkString = networkOperatorField.toString();
                        else
                            mobileNetworkString = String.format("%s (%s)", mobileProviderNameField,
                                    networkOperatorField);
                    }

                    /*
                    RESULT_SHARE_TEXT = My Result:\nDate/time: {0}\nDownload: {1}\nUpload: {2}\nPing: {3}\n{4}Network type: {5}\n{6}{7}Platform: {8}\nModel: {9}\n{10}\n\n
                    RESULT_SHARE_TEXT_SIGNAL_ADD = Signal strength: {0}\n
                    RESULT_SHARE_TEXT_RSRP_ADD = Signal strength (RSRP): {0}\n
                    RESULT_SHARE_TEXT_MOBILE_ADD = Mobile network: {0}\n
                    RESULT_SHARE_TEXT_PROVIDER_ADD = Operator: {0}\n
                            
                    */
                    String shareTextField4 = "";
                    if (signalString != null) //info on signal strength, field 4
                        if (lteRsrpField.isNull()) { //add RSSI if RSRP is not available
                            shareTextField4 = MessageFormat
                                    .format(labels.getString("RESULT_SHARE_TEXT_SIGNAL_ADD"), signalString);
                        } else { //add RSRP
                            shareTextField4 = MessageFormat
                                    .format(labels.getString("RESULT_SHARE_TEXT_RSRP_ADD"), signalString);
                        }
                    String shareLocation = "";
                    if (includeLocation && locationJson != null) {

                        shareLocation = MessageFormat.format(labels.getString("RESULT_SHARE_TEXT_LOCATION_ADD"),
                                locationJson.getString("location"));
                    }

                    final String shareText = MessageFormat.format(labels.getString("RESULT_SHARE_TEXT"),
                            timeString, //field 0
                            downloadString, //field 1
                            uploadString, //field 2
                            pingString, //field 3
                            shareTextField4, //contains field 4
                            networkTypeString, //field 5
                            providerString.isEmpty() ? ""
                                    : MessageFormat.format(labels.getString("RESULT_SHARE_TEXT_PROVIDER_ADD"),
                                            providerString), //field 6
                            mobileNetworkString == null ? ""
                                    : MessageFormat.format(labels.getString("RESULT_SHARE_TEXT_MOBILE_ADD"),
                                            mobileNetworkString), //field 7
                            platformString, //field 8
                            modelString, //field 9
                            //dz add location
                            shareLocation, //field 10
                            getSetting("url_open_data_prefix", lang) + openTestUUID); //field 11
                    jsonItem.put("share_text", shareText);

                    final String shareSubject = MessageFormat.format(labels.getString("RESULT_SHARE_SUBJECT"),
                            timeString //field 0
                    );
                    jsonItem.put("share_subject", shareSubject);

                    jsonItem.put("network_type", networkType);

                    if (resultList.length() == 0)
                        errorList.addError("ERROR_DB_GET_TESTRESULT");
                    // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"),
                    // new Object[] {uuid}));

                    answer.put("testresult", resultList);
                } else
                    errorList.addError("ERROR_REQUEST_NO_UUID");

            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();

    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_TESTRESULT_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.VehicleLocationInferenceServiceImpl.java

/**
 * This method is used by the queue listener to process raw messages from the message queue. 
 *
 * ***This is the main entry point for data in the MTA project.***
 */// w  w w.j av a  2 s. c om
@Override
public void handleRealtimeEnvelopeRecord(RealtimeEnvelope envelope) {
    final CcLocationReport message = envelope.getCcLocationReport();

    if (!_bundleManagementService.bundleIsReady()) {
        _skippedUpdateLogCounter++;

        // only print this every 25 times so we don't fill up the logs!
        if (_skippedUpdateLogCounter > 25) {
            _log.warn("Bundle is not ready or none is loaded--we've skipped 25 messages since last log event.");
            _skippedUpdateLogCounter = 0;
        }

        return;
    }

    verifyVehicleResultMappingToCurrentBundle();

    // construct raw record
    final NycRawLocationRecord r = new NycRawLocationRecord();
    r.setUuid(envelope.getUUID());

    r.setLatitude(message.getLatitude() / 1000000f);
    r.setLongitude(message.getLongitude() / 1000000f);

    final Angle bearing = message.getDirection();
    if (bearing != null) {
        final Integer degrees = bearing.getCdeg();
        if (degrees != null)
            r.setBearing(degrees);
    }

    r.setSpeed(message.getSpeed());

    r.setDestinationSignCode(message.getDestSignCode().toString());
    r.setDeviceId(message.getManufacturerData());

    final AgencyAndId vehicleId = new AgencyAndId(message.getVehicle().getAgencydesignator(),
            Long.toString(message.getVehicle().getVehicleId()));
    r.setVehicleId(vehicleId);

    if (!StringUtils.isEmpty(message.getOperatorID().getDesignator()))
        r.setOperatorId(message.getOperatorID().getDesignator());

    if (!StringUtils.isEmpty(message.getRunID().getDesignator()))
        r.setRunNumber(message.getRunID().getDesignator());

    if (!StringUtils.isEmpty(message.getRouteID().getRouteDesignator()))
        r.setRunRouteId(message.getRouteID().getRouteDesignator());

    final EmergencyCodes emergencyCodes = message.getEmergencyCodes();
    if (emergencyCodes != null)
        r.setEmergencyFlag(true);
    else
        r.setEmergencyFlag(false);

    final tcip_3_0_5_local.CcLocationReport gpsData = message.getLocalCcLocationReport();
    if (gpsData != null && gpsData.getNMEA() != null) {
        final NMEA nemaSentences = gpsData.getNMEA();
        final List<String> sentenceStrings = nemaSentences.getSentence();

        for (final String sentence : sentenceStrings) {
            if (sentence.startsWith("$GPGGA"))
                r.setGga(sentence);

            if (sentence.startsWith("$GPRMC"))
                r.setRmc(sentence);
        }
    }

    final DateTime time = XML_DATE_TIME_FORMAT.parseDateTime(message.getTimeReported());
    r.setTime(time.getMillis());
    r.setTimeReceived(new Date().getTime());

    // validate timestamp from bus--for debugging only
    final String RMCSentence = r.getRmc();

    if (RMCSentence != null) {
        final String[] parts = RMCSentence.split(",");
        if (parts.length == 13) {
            final String timePart = parts[1];
            final String datePart = parts[9];
            if (timePart.length() >= 6 && datePart.length() == 6) {
                try {
                    final DateFormat formatter = new SimpleDateFormat("ddMMyy HHmmss");
                    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));

                    final Date fromDRU = formatter.parse(datePart + " " + timePart);
                    final long differenceInSeconds = (fromDRU.getTime() - time.getMillis()) / 1000;

                    if (differenceInSeconds > 30 * 60) { // 30m
                        _log.debug("Vehicle " + vehicleId
                                + " has significant time difference between time from DRU and time from record\n"
                                + "Difference in seconds: " + differenceInSeconds + "\n"
                                + "Difference in hours: " + (differenceInSeconds / 60 / 60) + "\n"
                                + "Raw timestamp: " + message.getTimeReported() + "\n" + "From RMC: " + datePart
                                + " " + timePart);
                    }
                } catch (final ParseException e) {
                    _log.debug("Unparseable date: " + datePart + " " + timePart);
                }
            }
        }
    }

    synchronized (_vehicleInstancesByVehicleId) {
        final VehicleInferenceInstance i = getInstanceForVehicle(vehicleId);
        final Future<?> result = _executorService.submit(new ProcessingTask(i, r, false, false));
        _bundleManagementService.registerInferenceProcessingThread(result);
    }
}

From source file:org.projectforge.plugins.teamcal.event.TeamEventDO.java

/**
 * @param recurrenceExDate the recurrenceExDate to set
 * @return this for chaining.//from w  ww .ja  v  a 2s  .  c  om
 */
@Transient
public TeamEventDO setRecurrenceDate(final Date recurrenceDate) {
    final DateFormat df = new SimpleDateFormat(DateFormats.ISO_TIMESTAMP_MILLIS);
    // Need the user's time-zone for getting midnight of desired date.
    df.setTimeZone(PFUserContext.getTimeZone());
    // But print it as UTC date:
    final String recurrenceDateString = df.format(recurrenceDate);
    setRecurrenceDate(recurrenceDateString);
    return this;
}

From source file:net.netheos.pcsapi.providers.googledrive.GoogleDrive.java

private CFile parseCFile(CPath parentPath, JSONObject json) {
    String dateStr = json.getString("modifiedDate");
    try {/*w  w  w  .  jav a2  s  . c  om*/
        CFile cFile;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
        format.setLenient(false);

        if (dateStr.endsWith("Z")) { // ISO8601 syntax
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
        }
        Date modified = format.parse(dateStr);
        if (MIME_TYPE_DIRECTORY.equals(json.getString("mimeType"))) {
            cFile = new CFolder(parentPath.add(json.getString("title")), modified, null); // metadata
        } else {
            long fileSize;
            if (json.has("fileSize")) {
                fileSize = json.getLong("fileSize");
            } else {
                // google apps files (application/vnd.google-apps.document, application/vnd.google-apps.spreadsheet, etc.)
                // do not publish any size (they can not be downloaded, only exported).
                fileSize = -1;
            }
            cFile = new CBlob(parentPath.add(json.getString("title")), fileSize, json.getString("mimeType"),
                    modified, null); // metadata
        }
        return cFile;

    } catch (ParseException ex) {
        throw new CStorageException("Can't parse date modified: " + dateStr + " (" + ex.getMessage() + ")", ex);
    }
}

From source file:ucar.unidata.idv.control.chart.ChartHolder.java

/**
 * apply props/* w  w w .j  a  va2  s  .c om*/
 */
protected void applyPlotProperties() {
    if (plot == null) {
        return;
    }
    if (dataAreaColor != null) {
        plot.setBackgroundPaint(dataAreaColor);
    }
    if (backgroundColor != null) {
        chart.setBackgroundPaint(backgroundColor);
    }
    if ((backgroundColor != null) && (chartPanel != null)) {
        chartPanel.setBackground(backgroundColor);
    }
    if (showTitle) {
        chart.setTitle(getName());
    } else {
        chart.setTitle((String) null);
    }
    if (plot instanceof XYPlot) {
        final XYPlot p = (XYPlot) plot;
        p.setDomainGridlinesVisible(domainLineState.getVisible());
        p.setRangeGridlinesVisible(rangeLineState.getVisible());
        p.setDomainGridlinePaint(domainLineState.getColor());
        p.setRangeGridlinePaint(rangeLineState.getColor());
        p.setDomainGridlineStroke(domainLineState.getStroke());
        p.setRangeGridlineStroke(rangeLineState.getStroke());
        if (p.getDomainAxis() instanceof DateAxis && dateFormat != null) {
            final DateAxis ax = (DateAxis) p.getDomainAxis();
            final TimeZone tz = getChartManager().getControl().getIdv().getPreferenceManager()
                    .getDefaultTimeZone();
            final DateFormat df = new SimpleDateFormat(dateFormat);
            df.setTimeZone(tz);
            ax.setDateFormatOverride(df);
        }
    }
}

From source file:com.twinsoft.convertigo.engine.Context.java

public Vector<String> getCookieStrings() {
    // Use the HandleCookie Property of the transaction to return or not the cookies.
    ////from w  w w  .  ja v  a 2 s . co  m
    // We noticed a Bug in tomcat when too much cookies where set in the response to the client. This causes a 
    // IndexOutOfBoundException:  4096 in coyote.
    // To overcome this situation, now you can configure HandleCookies to false in the transaction to prevent cookies to be reflected
    // to the client.
    if (requestedObject instanceof AbstractHttpTransaction) {
        if (!((AbstractHttpTransaction) requestedObject).isHandleCookie())
            return new Vector<String>();
    }

    Vector<String> cookies = new Vector<String>();
    if (httpState != null) {
        Cookie[] httpCookies = httpState.getCookies();
        int len = httpCookies.length;
        Cookie cookie = null;
        String sCookie;

        DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        for (int i = 0; i < len; i++) {
            cookie = httpCookies[i];
            sCookie = cookie.getName() + "=" + cookie.getValue() + ";";
            sCookie += (cookie.getExpiryDate() != null) ? "expires=" + df.format(cookie.getExpiryDate()) + ";"
                    : "";
            sCookie += "path=" + cookie.getPath() + ";";
            sCookie += "domain=" + cookie.getDomain() + ";";
            sCookie += cookie.getSecure() ? "secure" : "";
            cookies.add(sCookie);
        }
    }
    return cookies;
}

From source file:org.kalypso.ogc.sensor.diagview.jfreechart.ObservationPlot.java

private void setTimezone(final ValueAxis axis) {
    if (axis instanceof DateAxis) {
        final DateAxis da = (DateAxis) axis;
        final DateFormat df = da.getDateFormatOverride() == null ? null : da.getDateFormatOverride();
        if (df != null) {
            df.setTimeZone(m_timezone);
            da.setDateFormatOverride(df);
        }//w  w  w .  j  a  v a 2  s .c  o  m

        final TickUnitSource source = createStandardDateTickUnits(m_timezone);
        da.setStandardTickUnits(source);
    }
}

From source file:org.rythmengine.utils.S.java

/**
 * Format a date with specified pattern, lang, locale and timezone. The locale
 * comes from the engine instance specified
 * /*w w  w.  j  a v  a 2  s  . c o m*/
 * @param template
 * @param date
 * @param pattern
 * @param locale
 * @param timezone
 * @return format result
 */
public static String format(ITemplate template, Date date, String pattern, Locale locale, String timezone) {
    if (null == date)
        date = new Date(0);
    if (null == locale) {
        locale = I18N.locale(template);
    }

    DateFormat df;
    if (null != pattern)
        df = new SimpleDateFormat(pattern, locale);
    else
        df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);

    if (null != timezone)
        df.setTimeZone(TimeZone.getTimeZone(timezone));

    return df.format(date);
}

From source file:org.structr.web.servlet.HtmlServlet.java

private static boolean notModifiedSince(final HttpServletRequest request, HttpServletResponse response,
        final AbstractNode node, final boolean dontCache) {

    boolean notModified = false;
    final Date lastModified = node.getLastModifiedDate();

    // add some caching directives to header
    // see http://weblogs.java.net/blog/2007/08/08/expires-http-header-magic-number-yslow
    final DateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    response.setHeader("Date", httpDateFormat.format(new Date()));

    final Calendar cal = new GregorianCalendar();
    final Integer seconds = node.getProperty(Page.cacheForSeconds);

    if (!dontCache && seconds != null) {

        cal.add(Calendar.SECOND, seconds);
        response.setHeader("Cache-Control", "max-age=" + seconds + ", s-maxage=" + seconds + "");
        response.setHeader("Expires", httpDateFormat.format(cal.getTime()));

    } else {//from w  w  w  .j ava 2 s.  c o m

        if (!dontCache) {
            response.setHeader("Cache-Control", "no-cache, must-revalidate, proxy-revalidate");
        } else {
            response.setHeader("Cache-Control",
                    "private, no-cache, no-store, max-age=0, s-maxage=0, must-revalidate, proxy-revalidate");
        }

    }

    if (lastModified != null) {

        final Date roundedLastModified = DateUtils.round(lastModified, Calendar.SECOND);
        response.setHeader("Last-Modified", httpDateFormat.format(roundedLastModified));

        final String ifModifiedSince = request.getHeader("If-Modified-Since");

        if (StringUtils.isNotBlank(ifModifiedSince)) {

            try {

                Date ifModSince = httpDateFormat.parse(ifModifiedSince);

                // Note that ifModSince has not ms resolution, so the last digits are always 000
                // That requires the lastModified to be rounded to seconds
                if ((ifModSince != null)
                        && (roundedLastModified.equals(ifModSince) || roundedLastModified.before(ifModSince))) {

                    notModified = true;

                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("Vary", "Accept-Encoding");

                }

            } catch (ParseException ex) {
                logger.log(Level.WARNING, "Could not parse If-Modified-Since header", ex);
            }

        }

    }

    return notModified;
}