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.maxpowered.amazon.advertising.api.SignedRequestsHelper.java

/**
 * Generate a ISO-8601 format timestamp as required by Amazon.
 *
 * @return ISO-8601 format timestamp.//from   ww  w  . j  ava2  s .c  o  m
 */
private String timestamp() {
    String timestamp = null;
    final Calendar cal = Calendar.getInstance();
    final DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    dfm.setTimeZone(TimeZone.getTimeZone("GMT"));
    timestamp = dfm.format(cal.getTime());
    return timestamp;
}

From source file:de.schildbach.wallet.ui.backup.BackupWalletDialogFragment.java

private void backupWallet() {
    passwordView.setEnabled(false);/*from  ww  w.  j a va  2s .c o  m*/
    passwordAgainView.setEnabled(false);

    final DateFormat dateFormat = Iso8601Format.newDateFormat();
    dateFormat.setTimeZone(TimeZone.getDefault());

    final StringBuilder filename = new StringBuilder(Constants.Files.EXTERNAL_WALLET_BACKUP);
    filename.append('-');
    filename.append(dateFormat.format(new Date()));

    final Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType(Constants.MIMETYPE_WALLET_BACKUP);
    intent.putExtra(Intent.EXTRA_TITLE, filename.toString());
    startActivityForResult(intent, REQUEST_CODE_CREATE_DOCUMENT);
}

From source file:pl.datamatica.traccar.api.GPXParser.java

public Result parse(InputStream inputStream, Device device)
        throws XMLStreamException, ParseException, IOException {
    Result result = new Result();

    TimeZone tz = TimeZone.getTimeZone("UTC");
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    DateFormat dateFormatWithMS = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    dateFormat.setTimeZone(tz);
    dateFormatWithMS.setTimeZone(tz);//from   w  ww  .j a  v a 2  s  .c  o  m

    XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(inputStream);
    ObjectMapper jsonMapper = new ObjectMapper();

    result.positions = new LinkedList<>();
    Position position = null;
    Stack<String> extensionsElements = new Stack<>();
    boolean extensionsStarted = false;
    Map<String, Object> other = null;

    while (xsr.hasNext()) {
        xsr.next();
        if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) {
            if (xsr.getLocalName().equalsIgnoreCase("trkpt")) {
                position = new Position();
                position.setLongitude(Double.parseDouble(xsr.getAttributeValue(null, "lon")));
                position.setLatitude(Double.parseDouble(xsr.getAttributeValue(null, "lat")));
                position.setValid(Boolean.TRUE);
                position.setDevice(device);
            } else if (xsr.getLocalName().equalsIgnoreCase("time")) {
                if (position != null) {
                    String strTime = xsr.getElementText();
                    if (strTime.length() == 20) {
                        position.setTime(dateFormat.parse(strTime));
                    } else {
                        position.setTime(dateFormatWithMS.parse(strTime));
                    }
                }
            } else if (xsr.getLocalName().equalsIgnoreCase("ele") && position != null) {
                position.setAltitude(Double.parseDouble(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("address") && position != null) {
                position.setAddress(StringEscapeUtils.unescapeXml(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("protocol") && position != null) {
                position.setProtocol(xsr.getElementText());
            } else if (xsr.getLocalName().equalsIgnoreCase("speed") && position != null) {
                position.setSpeed(Double.parseDouble(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("power") && position != null) {
                position.setPower(Double.parseDouble(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("course") && position != null) {
                position.setCourse(Double.parseDouble(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("other") && position != null) {
                position.setOther(StringEscapeUtils.unescapeXml(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("extensions")) {
                other = new LinkedHashMap<>();
                extensionsStarted = true;
            } else if (position != null && extensionsStarted && other != null) {
                extensionsElements.push(xsr.getLocalName());
            }
        } else if (xsr.getEventType() == XMLStreamReader.END_ELEMENT) {
            if (xsr.getLocalName().equalsIgnoreCase("trkpt")) {
                if (other == null) {
                    other = new HashMap<>();
                }

                if (position.getOther() != null) {
                    if (position.getOther().startsWith("<")) {
                        XMLStreamReader otherReader = XMLInputFactory.newFactory()
                                .createXMLStreamReader(new StringReader(position.getOther()));
                        while (otherReader.hasNext()) {
                            if (otherReader.next() == XMLStreamReader.START_ELEMENT
                                    && !otherReader.getLocalName().equals("info")) {
                                other.put(otherReader.getLocalName(), otherReader.getElementText());
                            }
                        }
                    } else {
                        Map<String, Object> parsedOther = jsonMapper.readValue(position.getOther(),
                                LinkedHashMap.class);
                        other.putAll(parsedOther);
                    }
                }

                if (other.containsKey("protocol") && position.getProtocol() == null) {
                    position.setProtocol(other.get("protocol").toString());
                } else if (!other.containsKey("protocol") && position.getProtocol() == null) {
                    position.setProtocol("gpx_import");
                }

                other.put("import_type", (result.positions.isEmpty() ? "import_start" : "import"));

                position.setOther(jsonMapper.writeValueAsString(other));

                result.positions.add(position);
                if (result.latestPosition == null
                        || result.latestPosition.getTime().compareTo(position.getTime()) < 0) {
                    result.latestPosition = position;
                }
                position = null;
                other = null;
            } else if (xsr.getLocalName().equalsIgnoreCase("extensions")) {
                extensionsStarted = false;
            } else if (extensionsStarted) {
                extensionsElements.pop();
            }
        } else if (extensionsStarted && other != null && xsr.getEventType() == XMLStreamReader.CHARACTERS
                && !xsr.getText().trim().isEmpty() && !extensionsElements.empty()) {
            String name = "";
            for (int i = 0; i < extensionsElements.size(); i++) {
                name += (name.length() > 0 ? "-" : "") + extensionsElements.get(i);
            }

            other.put(name, xsr.getText());
        }
    }

    if (result.positions.size() > 1) {
        Position last = ((LinkedList<Position>) result.positions).getLast();
        Map<String, Object> parsedOther = jsonMapper.readValue(last.getOther(), LinkedHashMap.class);
        parsedOther.put("import_type", "import_end");
        last.setOther(jsonMapper.writeValueAsString(parsedOther));
    }

    return result;
}

From source file:com.nebkat.plugin.geoip.GeoIpPlugin.java

public void geoIp(CommandEvent e, String host) {
    if (e.getParams().length < 2) {
        return;/*from  ww  w .jav a 2 s  .  c  o  m*/
    }

    GeoIp location = getGeoIp(host);

    if (location == null) {
        Irc.message(e.getSession(), e.getTarget(),
                e.getSource().getNick() + ": Error fetching geolocation data for (invalid?) host " + host);
        return;
    }

    List<String> information = new ArrayList<>();
    // Country
    if (!Utils.empty(location.country_name)) {
        information.add("country: \"" + location.country_name + "\"");
    } else if (!Utils.empty(location.country_code)) {
        information.add("country: \"" + location.country_code + "\"");
    }

    // Region
    if (!Utils.empty(location.region_name)) {
        information.add("region: \"" + location.region_name + "\"");
    }

    // City
    if (!Utils.empty(location.city)) {
        information.add("city: \"" + location.city + "\"");
    }

    // Lat/long
    if (location.latitude != 0f && location.longitude != 0f) {
        information.add("latlong: {" + location.latitude + ", " + location.longitude + "}");
    }

    // Time
    if (location.country_code != null && location.region_code != null) {
        String timeZone = GeoTimeZones.timeZoneByCountryAndRegion(location.country_code, location.region_code);
        if (timeZone != null) {
            DateFormat date = new SimpleDateFormat("E HH:mm z");
            date.setTimeZone(TimeZone.getTimeZone(timeZone));
            information.add("time: \"" + date.format(new Date()) + "\"");
        }
    }

    String result = location.ip + ": {" + Utils.implode(information, ", ") + "}";
    Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": " + result);
}

From source file:org.apache.usergrid.tools.CollectionIterator.java

@Override
public void runTool(CommandLine line) throws Exception {

    startSpring();/*  www  .ja v a  2  s  . c  o  m*/

    String applicationOption = line.getOptionValue(APPLICATION_ARG);
    String entityTypeOption = line.getOptionValue(ENTITY_TYPE_ARG);
    String removeConnectionsOption = line.getOptionValue(REMOVE_CONNECTIONS_ARG);
    String earliestTimestampOption = line.getOptionValue(EARLIEST_TIMESTAMP_ARG);
    String latestTimestampOption = line.getOptionValue(LATEST_TIMESTAMP_ARG);
    String secondsInPastOption = line.getOptionValue(SECONDS_IN_PAST_ARG);

    if (isBlank(applicationOption)) {
        throw new RuntimeException("Application ID not provided.");
    }
    final UUID app = UUID.fromString(line.getOptionValue(APPLICATION_ARG));

    if (isBlank(entityTypeOption)) {
        throw new RuntimeException("Entity type (singular collection name) not provided.");
    }
    String entityType = entityTypeOption;

    final boolean removeOrphans = !isBlank(removeConnectionsOption)
            && removeConnectionsOption.toLowerCase().equals("yes");

    if (!isBlank(secondsInPastOption) && !isBlank(latestTimestampOption)) {
        throw new RuntimeException("Can't specify both latest timestamp and seconds in past options.");
    }

    long earliest = 0L;
    if (!isBlank(earliestTimestampOption)) {
        try {
            earliest = Long.parseLong(earliestTimestampOption);
        } catch (Exception e) {
            throw new RuntimeException("Cannot convert earliest timestamp to long: " + earliestTimestampOption);
        }
    }
    final long earliestTimestamp = earliest;

    long currentTimestamp = System.currentTimeMillis();

    // default to DEFAULT_SECONDS_IN_PAST
    long latest = currentTimestamp - (DEFAULT_SECONDS_IN_PAST * 1000L);
    if (!isBlank(latestTimestampOption)) {
        try {
            latest = Long.parseLong(latestTimestampOption);
        } catch (Exception e) {
            throw new RuntimeException("Cannot convert latest timestamp to long: " + latestTimestampOption);
        }
    } else if (!isBlank(secondsInPastOption)) {
        try {
            long secondsInPast = Long.parseLong(secondsInPastOption);
            latest = currentTimestamp - (secondsInPast * 1000L);
        } catch (Exception e) {
            throw new RuntimeException("Cannot convert seconds in past to long: " + secondsInPastOption);
        }
    }
    final long latestTimestamp = latest;

    logger.info("Starting Tool: CollectionIterator");
    logger.info("Orphans {} be deleted", removeOrphans ? "WILL" : "will not");
    logger.info("Timestamp range {} to {}", Long.toString(earliestTimestamp), Long.toString(latestTimestamp));
    logger.info("Using Cassandra consistency level: {}",
            System.getProperty("usergrid.read.cl", "CL_LOCAL_QUORUM"));

    em = emf.getEntityManager(app);
    EntityRef headEntity = new SimpleEntityRef("application", app);

    CollectionService collectionService = injector.getInstance(CollectionService.class);
    String collectionName = InflectionUtils.pluralize(entityType);
    String simpleEdgeType = CpNamingUtils.getEdgeTypeFromCollectionName(collectionName);
    logger.info("simpleEdgeType: {}", simpleEdgeType);

    ApplicationScope applicationScope = new ApplicationScopeImpl(new SimpleId(app, "application"));
    Id applicationScopeId = applicationScope.getApplication();
    logger.info("applicationScope.getApplication(): {}", applicationScopeId);
    EdgeSerialization edgeSerialization = injector.getInstance(EdgeSerialization.class);

    Query query = new Query();
    query.setCollection(collectionName);
    query.setLimit(1000);

    com.google.common.base.Optional<String> queryString = com.google.common.base.Optional.absent();

    CollectionInfo collection = getDefaultSchema().getCollection(headEntity.getType(), collectionName);

    GraphManagerFactory gmf = injector.getInstance(GraphManagerFactory.class);
    GraphManager gm = gmf.createEdgeManager(applicationScope);

    final SimpleSearchByEdgeType search = new SimpleSearchByEdgeType(applicationScopeId, simpleEdgeType,
            Long.MAX_VALUE, SearchByEdgeType.Order.DESCENDING, Optional.absent(), false);

    gm.loadEdgesFromSource(search).map(markedEdge -> {

        UUID uuid = markedEdge.getTargetNode().getUuid();
        try {
            EntityRef entityRef = new SimpleEntityRef(entityType, uuid);
            org.apache.usergrid.persistence.Entity retrieved = em.get(entityRef);

            long timestamp = 0;
            String dateString = "NOT TIME-BASED";
            if (UUIDUtils.isTimeBased(uuid)) {
                timestamp = UUIDUtils.getTimestampInMillis(uuid);
                Date uuidDate = new Date(timestamp);
                DateFormat df = new SimpleDateFormat();
                df.setTimeZone(TimeZone.getTimeZone("GMT"));
                dateString = df.format(uuidDate) + " GMT";
            }

            if (retrieved != null) {

                logger.info("{} - {} - entity data found", uuid, dateString);
            } else {
                if (removeOrphans && timestamp >= earliestTimestamp && timestamp <= latestTimestamp) {
                    logger.info("{} - {} - entity data NOT found, REMOVING", uuid, dateString);
                    try {
                        //em.removeItemFromCollection(headEntity, collectionName, entityRef );
                        logger.info("entityRef.asId(): {}", entityRef.asId());
                        MutationBatch batch = edgeSerialization.deleteEdge(applicationScope, markedEdge,
                                UUIDUtils.newTimeUUID());
                        logger.info("BATCH: {}", batch);
                        batch.execute();
                    } catch (Exception e) {
                        logger.error("{} - exception while trying to remove orphaned connection, {}", uuid,
                                e.getMessage());
                    }
                } else if (removeOrphans) {
                    logger.info(
                            "{} - {} ({}) - entity data NOT found, not removing because timestamp not in range",
                            uuid, dateString, timestamp);
                } else {
                    logger.info("{} - {} ({}) - entity data NOT found", uuid, dateString, timestamp);
                }
            }
        } catch (Exception e) {
            logger.error("{} - exception while trying to load entity data, {} ", uuid, e.getMessage());
        }

        return markedEdge;
    }).toBlocking().lastOrDefault(null);

}

From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java

@DefaultHandler
public Resolution sign() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("success", false);
    EntityManager em = Stripersist.getEntityManager();
    CycloramaAccount account = em.find(CycloramaAccount.class, accountId);
    if (imageId != null && account != null) {

        try {/* w w w  . j av  a2s.c  o m*/
            apiKey = "K3MRqDUdej4JGvohGfM5e78xaTUxmbYBqL0tSHsNWnwdWPoxizYBmjIBGHAhS3U1";

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            df.setTimeZone(TimeZone.getTimeZone("GMT"));

            String date = df.format(new Date());
            String token = "X" + account.getUsername() + "&" + imageId + "&" + date + "Z";

            String privateBase64Key = account.getPrivateBase64Key();

            if (privateBase64Key == null || privateBase64Key.equals("")) {
                log.error("Kon private key voor aanmaken TID niet ophalen!");
            }

            tid = getTIDFromBase64EncodedString(privateBase64Key, token);

            json.put("tid", tid);
            json.put("imageId", imageId);
            json.put("apiKey", apiKey);
            json.put("success", true);
        } catch (Exception ex) {
            json.put("message", ex.getLocalizedMessage());
        }
    }

    // return new ForwardResolution("/WEB-INF/jsp/app/globespotter.jsp");
    return new StreamingResolution("application/json", json.toString());
}

From source file:ch.bfh.uniboard.accesscontrolled.AccessControlledService.java

protected Element createMessageElement(byte[] message, Attributes alpha) {
    StringMonoid stringSpace = StringMonoid.getInstance(Alphabet.PRINTABLE_ASCII);
    Z z = Z.getInstance();//from  w  ww  .ja  v  a  2s  .  c  om
    ByteArrayMonoid byteSpace = ByteArrayMonoid.getInstance();

    Element messageElement = byteSpace.getElement(message);

    List<Element> alphaElements = new ArrayList<>();
    //itterate over alpha until one reaches the property = signature
    for (Map.Entry<String, Value> e : alpha.getEntries()) {
        if (e.getKey().equals(ATTRIBUTE_NAME_SIG)) {
            break;
        }
        Element tmp;
        if (e.getValue() instanceof ByteArrayValue) {
            tmp = byteSpace.getElement(((ByteArrayValue) e.getValue()).getValue());
            alphaElements.add(tmp);
        } else if (e.getValue() instanceof DateValue) {
            TimeZone timeZone = TimeZone.getTimeZone("UTC");
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            dateFormat.setTimeZone(timeZone);
            String stringDate = dateFormat.format(((DateValue) e.getValue()).getValue());
            tmp = stringSpace.getElement(stringDate);
            alphaElements.add(tmp);
        } else if (e.getValue() instanceof IntegerValue) {
            tmp = z.getElement(((IntegerValue) e.getValue()).getValue());
            alphaElements.add(tmp);
        } else if (e.getValue() instanceof StringValue) {
            tmp = stringSpace.getElement(((StringValue) e.getValue()).getValue());
            alphaElements.add(tmp);
        } else {
            logger.log(Level.SEVERE, "Unsupported Value type.");
        }

    }
    DenseArray immuElements = DenseArray.getInstance(alphaElements);
    Element alphaElement = Tuple.getInstance(immuElements);
    return Pair.getInstance(messageElement, alphaElement);
}

From source file:org.apache.roller.weblogger.ui.struts2.editor.EntryBean.java

public Timestamp getPubTime(Locale locale, TimeZone timezone) {

    Timestamp pubtime = null;/*  w w w  . j  a v a  2 s .c  o  m*/

    if (!StringUtils.isEmpty(getDateString()))
        try {
            log.debug("pubtime vals are " + getDateString() + ", " + getHours() + ", " + getMinutes() + ", "
                    + getSeconds());

            // first convert the specified date string into an actual Date obj
            // TODO: at some point this date conversion should be locale sensitive,
            // however at this point our calendar widget does not take into account
            // locales and only operates in the standard English US locale.

            // Don't require user add preceding '0' of month and day.
            DateFormat df = new SimpleDateFormat("M/d/yy");
            df.setTimeZone(timezone);
            Date newDate = df.parse(getDateString());

            log.debug("dateString yields date - " + newDate);

            // Now handle the time from the hour, minute and second combos
            Calendar cal = Calendar.getInstance(timezone, locale);
            cal.setTime(newDate);
            cal.set(Calendar.HOUR_OF_DAY, getHours());
            cal.set(Calendar.MINUTE, getMinutes());
            cal.set(Calendar.SECOND, getSeconds());
            pubtime = new Timestamp(cal.getTimeInMillis());

            log.debug("pubtime is " + pubtime);
        } catch (Exception e) {
            log.error("Error calculating pubtime", e);
        }

    return pubtime;
}

From source file:org.grails.datastore.bson.json.JsonWriter.java

@Override
protected void doWriteDateTime(long value) {
    DateFormat df = new SimpleDateFormat(ISO_8601);
    df.setTimeZone(UTC);
    try {//from ww  w  .j a va2 s .co m
        writeNameHelper(getName());
        writer.write(JsonToken.QUOTE);
        Date date = new Date(value);
        writer.write(df.format(date));
        writer.write(JsonToken.QUOTE);
        setState(getNextState());
    } catch (IOException e) {
        throwBsonException(e);
    }
}

From source file:org.unitedinternet.cosmo.model.filter.EventStampFilter.java

private void updateFloatingTimes() {
    if (dstart != null) {
        Value v = Value.DATE_TIME;/* w  w w  . ja  v  a 2  s  .c  om*/
        fstart = fstart == null ? (DateTime) Dates.getInstance(dstart, v) : fstart;
        if (fstart instanceof DateTime) {
            ((DateTime) fstart).setUtc(false);
            // if the timezone is null then default system timezone is used
            ((DateTime) fstart).setTimeZone((timezone != null) ? timezone : null);
        }
    }
    if (dend != null) {
        Value v = Value.DATE_TIME;
        fend = fend == null ? (DateTime) Dates.getInstance(dend, v) : fend;
        if (fend instanceof DateTime) {
            ((DateTime) fend).setUtc(false);
            // if the timezone is null then default system timezone is used
            ((DateTime) fend).setTimeZone((timezone != null) ? timezone : null);
        }
    }

    DateFormat df = new SimpleDateFormat("yyyyMMdd");
    TimeZone tz = getTimezone();
    if (tz != null) {
        //for some reason ical4j's TimeZone for a valid ID (i.e. Europe/Bucharest) has raw offset 0
        df.setTimeZone(java.util.TimeZone.getTimeZone(tz.getID()));
    }

    if (fstart != null && fstart.getClass() == net.fortuna.ical4j.model.Date.class) {
        try {
            dstart = new DateTime(df.parse(fstart.toString()).getTime());
            dstart.setUtc(true);
        } catch (ParseException e) {
            LOG.error("Error occured while parsing fstart [" + fstart.toString() + "]", e);
        }
    }

    if (fend != null && fend.getClass() == net.fortuna.ical4j.model.Date.class) {
        try {
            dend = new DateTime(df.parse(fend.toString()).getTime());
            dend.setUtc(true);
        } catch (ParseException e) {
            LOG.error("Error occured while parsing fend [" + fend.toString() + "]", e);
        }
    }
}