Example usage for java.text SimpleDateFormat setTimeZone

List of usage examples for java.text SimpleDateFormat setTimeZone

Introduction

In this page you can find the example usage for java.text SimpleDateFormat 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.comcast.cmb.common.util.AuthUtil.java

public static void checkTimeStampWithFormat(String ts, String format) throws AuthenticationException {

    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date timeStamp;/*  w  w w  . j  a  va 2s. co  m*/

    try {
        timeStamp = dateFormat.parse(ts);
    } catch (ParseException ex) {
        logger.error("event=checking_timestamp timestamp=" + ts + " error_code=invalid_format", ex);
        throw new AuthenticationException(CMBErrorCodes.InvalidParameterValue,
                "Timestamp=" + ts + " is not valid");
    }

    Date now = new Date();

    if (now.getTime() - REQUEST_VALIDITY_PERIOD_MS < timeStamp.getTime()
            && now.getTime() + REQUEST_VALIDITY_PERIOD_MS > timeStamp.getTime()) {
        return;
    }

    logger.error("event=checking_timestamp timestamp=" + ts + " serverTime=" + dateFormat.format(now)
            + " error_code=timestamp_out_of_range");
    throw new AuthenticationException(CMBErrorCodes.RequestExpired,
            "Request timestamp " + ts + " must be within 900 seconds of the server time");
}

From source file:org.opendatakit.common.utils.WebUtils.java

/**
 * Return the GoogleDocs datetime string representation of a datetime.
 *
 * @param d//ww w. j a  v  a  2  s.  c o m
 * @return
 */
public static final String googleDocsDateTime(Date d) {
    if (d == null)
        return null;
    SimpleDateFormat asGoogleDoc = new SimpleDateFormat(PATTERN_GOOGLE_DOCS);
    asGoogleDoc.setTimeZone(TimeZone.getTimeZone("GMT"));
    return asGoogleDoc.format(d);
}

From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java

private static void setDateHeader(FullHttpResponse response) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    Calendar time = new GregorianCalendar();
    response.headers().set(DATE, dateFormatter.format(time.getTime()));
}

From source file:com.twitter.elephanttwin.util.DateUtil.java

/**
 * Convert epochMS to YYYYMMDD/*  w  ww.j av a  2s.  co m*/
 * @param epochMs the epoch ms
 * @param tz the timezone
 * @return the output string
 */
public static String epochMsToYyyyMmDd(long epochMs, TimeZone tz) {
    if (tz == null) {
        return DATEID_TIMESTAMP_FORMATTER.print(epochMs);
    } else {
        Calendar cal = Calendar.getInstance(UTC_TIMEZONE);
        cal.setTimeInMillis(epochMs);
        SimpleDateFormat tzDateFormat = new SimpleDateFormat(DATEID_TIMESTAMP_FORMAT);
        tzDateFormat.setTimeZone(tz);
        return tzDateFormat.format(cal.getTime());
    }
}

From source file:org.opendatakit.common.utils.WebUtils.java

/**
 * Return the GoogleDocs date string representation of a date-only datetime.
 *
 * @param d//from   ww w  . ja v a 2 s  . c om
 * @return
 */
public static final String googleDocsDateOnly(Date d) {
    if (d == null)
        return null;
    SimpleDateFormat asGoogleDocDateOnly = new SimpleDateFormat(PATTERN_GOOGLE_DOCS_DATE_ONLY);
    asGoogleDocDateOnly.setTimeZone(TimeZone.getTimeZone("GMT"));
    return asGoogleDocDateOnly.format(d);
}

From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java

private static void setDateAndCacheHeaders(HttpResponse response, FileRecord fileToCache) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    // Date header
    Calendar time = new GregorianCalendar();
    response.headers().set(DATE, dateFormatter.format(time.getTime()));

    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    response.headers().set(EXPIRES, dateFormatter.format(time.getTime()));
    response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    response.headers().set(LAST_MODIFIED, dateFormatter.format(fileToCache.getUpdateTime()));
}

From source file:com.comcast.cmb.common.util.AuthUtil.java

public static void checkExpiration(String expiration) throws AuthenticationException {

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

    Date timeStamp;/*from  ww  w . ja  va2  s .c  o  m*/

    try {
        timeStamp = dateFormat.parse(expiration);
    } catch (ParseException e) {
        logger.error("event=checking_expiration expiration=" + expiration + " error_code=invalid_format", e);
        throw new AuthenticationException(CMBErrorCodes.InvalidParameterValue,
                "Expiration " + expiration + " is not valid");
    }

    Date now = new Date();

    if (now.getTime() < timeStamp.getTime()) {
        return;
    }

    logger.error("event=checking_timestamp expiration=" + expiration + " server_time=" + dateFormat.format(now)
            + " error_code=request_expired");
    throw new AuthenticationException(CMBErrorCodes.RequestExpired,
            "Request with expiration " + expiration + " already expired");
}

From source file:com.cloudlbs.core.utils.DateUtil.java

/**
 * Slightly modified from//from ww  w  . ja v a2 s.c o  m
 * org.apache.commons.httpclient.util.DateUtil.parseDate
 * <p/>
 * Parses the date value using the given date formats.
 * 
 * @param dateValue
 *            the date value to parse
 * @param dateFormats
 *            the date formats to use
 * @param startDate
 *            During parsing, two digit years will be placed in the range
 *            <code>startDate</code> to <code>startDate + 100 years</code>.
 *            This value may be <code>null</code>. When <code>null</code> is
 *            given as a parameter, year <code>2000</code> will be used.
 * @return the parsed date
 * @throws ParseException
 *             if none of the dataFormats could parse the dateValue
 */
public static Date parseDate(String dateValue, Collection<String> dateFormats, Date startDate)
        throws ParseException {

    if (dateValue == null) {
        throw new IllegalArgumentException("dateValue is null");
    }
    if (dateFormats == null) {
        dateFormats = DEFAULT_HTTP_CLIENT_PATTERNS;
    }
    if (startDate == null) {
        startDate = DEFAULT_TWO_DIGIT_YEAR_START;
    }
    // trim single quotes around date if present
    // see issue #5279
    if (dateValue.length() > 1 && dateValue.startsWith("'") && dateValue.endsWith("'")) {
        dateValue = dateValue.substring(1, dateValue.length() - 1);
    }

    SimpleDateFormat dateParser = null;
    Iterator<String> formatIter = dateFormats.iterator();

    while (formatIter.hasNext()) {
        String format = (String) formatIter.next();
        if (dateParser == null) {
            dateParser = new SimpleDateFormat(format, Locale.US);
            dateParser.setTimeZone(GMT);
            dateParser.set2DigitYearStart(startDate);
        } else {
            dateParser.applyPattern(format);
        }
        try {
            return dateParser.parse(dateValue);
        } catch (ParseException pe) {
            // ignore this exception, we will try the next format
        }
    }

    // we were unable to parse the date
    throw new ParseException("Unable to parse the date " + dateValue, 0);
}

From source file:com.ocs.dynamo.ui.composite.table.TableUtils.java

/**
 * Formats a property value for display in a string
 * /*from  ww w  .  j  a v  a 2s.  c  om*/
 * @param entityModelFactory
 * @param entityModel
 * @param messageService
 * @param colId
 * @param value
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> String formatPropertyValue(EntityModelFactory entityModelFactory, EntityModel<T> entityModel,
        MessageService messageService, Object colId, Object value, Locale locale) {
    if (value != null) {
        AttributeModel model = entityModel.getAttributeModel((String) colId);
        if (model != null) {
            if (model.isWeek()) {
                WeekCodeConverter converter = new WeekCodeConverter();
                return converter.convertToPresentation((Date) value, String.class, null);
            } else if (Boolean.class.equals(model.getType()) || boolean.class.equals(model.getType())) {
                if (!StringUtils.isEmpty(model.getTrueRepresentation()) && Boolean.TRUE.equals(value)) {
                    return model.getTrueRepresentation();
                } else if (!StringUtils.isEmpty(model.getFalseRepresentation())
                        && Boolean.FALSE.equals(value)) {
                    return model.getFalseRepresentation();
                }
                return null;
            } else if (Date.class.equals(model.getType())) {
                // in case of a date field, use the entered display format
                SimpleDateFormat format = new SimpleDateFormat(model.getDisplayFormat());

                // ignore time zones for a pure date field (since it is not
                // clear what the time zone is anyway)
                if (!AttributeDateType.TIME.equals(model.getDateType())) {
                    format.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent()));
                }
                return format.format((Date) value);
            } else if (BigDecimal.class.equals(model.getType())) {
                return VaadinUtils.bigDecimalToString(model.isCurrency(), model.isPercentage(),
                        model.isUseThousandsGrouping(), model.getPrecision(), (BigDecimal) value, locale);
            } else if (Integer.class.equals(model.getType())) {
                return VaadinUtils.integerToString(model.isUseThousandsGrouping(), (Integer) value, locale);
            } else if (Long.class.equals(model.getType())) {
                return VaadinUtils.longToString(model.isUseThousandsGrouping(), (Long) value, locale);
            } else if (model.getType().isEnum()) {
                // in case of an enum, look it up in the message bundle
                String msg = messageService.getEnumMessage((Class<Enum<?>>) model.getType(), (Enum<?>) value);
                if (msg != null) {
                    return msg;
                }
            } else if (AbstractEntity.class.isAssignableFrom(model.getType())) {
                // check for a nested model first. If it is not there, fall
                // back to the default
                EntityModel<?> detailEntityModel = model.getNestedEntityModel();
                if (detailEntityModel == null) {
                    detailEntityModel = entityModelFactory.getModel(model.getType());
                }

                String displayProperty = detailEntityModel.getDisplayProperty();
                return formatPropertyValue(entityModelFactory, detailEntityModel, messageService,
                        displayProperty, ClassUtils.getFieldValue(value, displayProperty), locale);
            } else if (Iterable.class.isAssignableFrom(model.getType())) {
                return formatEntityCollection(entityModelFactory, value);
            } else if (value instanceof AbstractEntity) {
                Object result = ClassUtils.getFieldValue(value, colId.toString());
                return result != null ? result.toString() : null;
            } else {
                // Use string value
                return value.toString();
            }
        }
    }
    return null;
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Send UPnP discovery search message to discover devices of interest on
 * the network./*from   w  ww .j  a v a2  s .co  m*/
 *
 * @param host The multicast channel
 * @param port The multicast port
 * @param st The search target string
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void sendDiscover(String host, int port, String st) throws IOException {
    String usn = PMS.get().usn();
    String serverHost = PMS.get().getServer().getHost();
    int serverPort = PMS.get().getServer().getPort();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US);

    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

    if (st.equals(usn)) {
        usn = "";
    } else {
        usn += "::";
    }

    StringBuilder discovery = new StringBuilder();

    discovery.append("HTTP/1.1 200 OK").append(CRLF);
    discovery.append("CACHE-CONTROL: max-age=1200").append(CRLF);
    discovery.append("DATE: ").append(sdf.format(new Date(System.currentTimeMillis()))).append(" GMT")
            .append(CRLF);
    discovery.append("LOCATION: http://").append(serverHost).append(":").append(serverPort)
            .append("/description/fetch").append(CRLF);
    discovery.append("SERVER: ").append(PMS.get().getServerName()).append(CRLF);
    discovery.append("ST: ").append(st).append(CRLF);
    discovery.append("EXT: ").append(CRLF);
    discovery.append("USN: ").append(usn).append(st).append(CRLF);
    discovery.append("Content-Length: 0").append(CRLF).append(CRLF);

    sendReply(host, port, discovery.toString());
}