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:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldDefaultValue.java

/**
 * @return String, the DB-Value of the a Value 
 *//* w w w  .ja va 2 s .c om*/
public String getDBValue() {
    // prevent that any null value fills content column of extendedFieldValue
    if (value == null) {
        value = "";
    }

    // only if datatype is Timestamp, JSCalendar or Number. Otherwise DB-Value = Value
    if (value != null && value.length() > 0) {
        if (ExtendedFieldDataTypes.TIMESTAMP == datatype || ExtendedFieldDataTypes.JSCALENDAR == datatype) {
            try {
                // the Milliseconds from 1.1.1970 will be stored as String
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                return String.valueOf(sdf.parse(value).getTime());
            } catch (ParseException e) {
                log.debug("Invalid TIMESTAMP: " + value);
            }
        } else if (ExtendedFieldDataTypes.NUMBER == datatype) {
            try {
                // a Double Value will be stored String
                return String.valueOf(new DecimalFormat(format).parse(value).doubleValue());
            } catch (ParseException e) {
                log.debug("Invalid NUMBER: " + value);
            }
        }
    }

    return value;
}

From source file:com.persistent.cloudninja.web.security.CNAuthenticationProcessingFilter.java

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws ServletException, IOException {
    User user = userDetailsService.getCurrentUser();
    String currentCookie = getCookie(request);
    Cookie newCookie = createCookie(user, currentCookie);

    String[] cookievalArray = newCookie.getValue().split("!");
    // get the tenant id
    String tenantId = cookievalArray[1];

    synchronized (userActivityQueue) {
        try {//from   ww  w.ja  va 2 s .  com
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            String date = dateFormat.format(calendar.getTime());

            UserActivityQueueMessage message;

            message = new UserActivityQueueMessage(cookievalArray[1], cookievalArray[0],
                    dateFormat.parse(date));

            userActivityQueue.add(message);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    // create Cookie containing logo url
    Cookie logoCookie = createLogoCookie(tenantId);

    response.addCookie(newCookie);
    response.addCookie(logoCookie);
    super.successfulAuthentication(request, response, authResult);
}

From source file:com.aurel.track.dbase.jobs.DatabaseBackupJob.java

@Override
public void execute(JobExecutionContext context) {
    LOGGER.info("DataBaseBackupJob was triggered at " + new Date());
    if (!ClusterBL.getIAmTheMaster()) {
        return;//  w ww.j  av  a2 s .  c om
    }
    LOGGER.info("Execute DatabaseBackupJob at " + new Date() + "...");
    if (!ApplicationBean.getInstance().getSiteBean().getIsDatabaseBackupJobOn()) {
        LOGGER.info("Database backup job config is off! Exit DatabaseBackupJob.");
        return;
    }
    JobDetail jobDetail = context.getJobDetail();
    JobDataMap jobDataMap = jobDetail.getJobDataMap();

    Scheduler scheduler = context.getScheduler();

    // Check if a job with the same name is currently running.
    // If so, skip this one.

    try {
        int count = 0;
        for (JobExecutionContext cont : scheduler.getCurrentlyExecutingJobs()) {
            JobDetail jd = cont.getJobDetail();
            if (jd.getKey().equals(jobDetail.getKey())) {
                ++count;
            }
        }
        if (count > 1) {
            return;
        }
    } catch (Exception e) { // Scheduler exception
        LOGGER.error(e.getMessage());
    }

    CronTrigger trigger = (CronTrigger) context.getTrigger();
    Date nextFire = trigger.getNextFireTime();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    LOGGER.info("Backup job next firing time: " + dateFormat.format(nextFire));
    LOGGER.debug("Cron-Exp.: " + trigger.getCronExpression());

    PropertiesConfiguration tcfg = null;
    try {
        tcfg = ApplicationBean.getInstance().getDbConfig();
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }

    Date now = new Date();
    String backupName = DatabaseBackupBL.formatBackupName(now);

    Boolean includeAttachments = ApplicationBean.getInstance().getSiteBean().getIncludeAttachments();

    if (includeAttachments == null) {
        includeAttachments = jobDataMap.getBooleanFromString("includeAttachments").booleanValue();
    }

    boolean keepAllBackups = false;

    Integer backupNumber = ApplicationBean.getInstance().getSiteBean().getNoOfBackups();
    if (backupNumber == null || backupNumber.intValue() <= 0) {
        try {
            backupNumber = jobDataMap.getIntFromString("backupNumber");
        } catch (Exception ex) {
            backupNumber = 15;
        }
    }
    try {
        keepAllBackups = jobDataMap.getBooleanFromString("keepAllBackups").booleanValue();
    } catch (Exception e) {
        keepAllBackups = false;
    }

    ApplicationBean appBean = ApplicationBean.getInstance();
    if (appBean.isBackupInProgress()) {
        LOGGER.info("Another backup is already in progress...");
        return;
    }
    appBean.setBackupInProgress(true);
    try {
        DatabaseBackupBL.zipDatabase(backupName, includeAttachments, tcfg);
        LOGGER.info("Backup created succesfully as:" + backupName);
        if (!keepAllBackups) {
            DatabaseBackupBL.checkBackupNumber(backupNumber);
        }
    } catch (DatabaseBackupBLException e) {
        LOGGER.error("Can't create backup");
        LOGGER.error(e);
    }
    appBean.setBackupInProgress(false);
    LOGGER.info("Done executing DatabaseBackupJob!");
}

From source file:com.hichinaschool.flashcards.libanki.Utils.java

/**
 *  Returns the effective date of the present moment.
 *  If the time is prior the cut-off time (9:00am by default as of 11/02/10) return yesterday,
 *  otherwise today/*from   www . java  2  s  .c o  m*/
 *  Note that the Date class is java.sql.Date whose constructor sets hours, minutes etc to zero
 *
 * @param utcOffset The UTC offset in seconds we are going to use to determine today or yesterday.
 * @return The date (with time set to 00:00:00) that corresponds to today in Anki terms
 */
public static Date genToday(double utcOffset) {
    // The result is not adjusted for timezone anymore, following libanki model
    // Timezone adjustment happens explicitly in Deck.updateCutoff(), but not in Deck.checkDailyStats()
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    cal.setTimeInMillis(System.currentTimeMillis() - (long) utcOffset * 1000l);
    Date today = Date.valueOf(df.format(cal.getTime()));
    return today;
}

From source file:org.geoserver.ows.AbstractURLPublisher.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    URL url = getUrl(request);/*from   ww w  . ja  v  a  2 s.c  om*/

    // if not found return a 404
    if (url == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    File file = DataUtilities.urlToFile(url);
    if (file != null && file.exists() && file.isDirectory()) {
        String uri = request.getRequestURI().toString();
        uri += uri.endsWith("/") ? "index.html" : "/index.html";

        response.addHeader("Location", uri);
        response.sendError(HttpServletResponse.SC_MOVED_TEMPORARILY);

        return null;
    }

    // set the mime if known by the servlet container, set nothing otherwise
    // (Tomcat behaves like this when it does not recognize the file format)
    String mime = getServletContext().getMimeType(new File(url.getFile()).getName());
    if (mime != null) {
        response.setContentType(mime);
    }

    // set the content length and content type
    URLConnection connection = null;
    InputStream input = null;
    try {
        connection = url.openConnection();
        long length = connection.getContentLength();
        if (length > 0 && length <= Integer.MAX_VALUE) {
            response.setContentLength((int) length);
        }

        long lastModified = connection.getLastModified();
        if (lastModified > 0) {
            SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.ENGLISH);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String formatted = format.format(new Date(lastModified)) + " GMT";
            response.setHeader("Last-Modified", formatted);
        }

        // Guessing the charset (and closing the stream)
        EncodingInfo encInfo = null;
        OutputStream output = null;
        final byte[] b4 = new byte[4];
        int count = 0;
        // open the output
        input = connection.getInputStream();

        // Read the first four bytes, and determine charset encoding
        count = input.read(b4);
        encInfo = XmlCharsetDetector.getEncodingName(b4, count);
        response.setCharacterEncoding(encInfo.getEncoding() != null ? encInfo.getEncoding() : "UTF-8");

        // send out the first four bytes read
        output = response.getOutputStream();
        output.write(b4, 0, count);

        // copy the content to the output
        byte[] buffer = new byte[8192];
        int n = -1;
        while ((n = input.read(buffer)) != -1) {
            output.write(buffer, 0, n);
        }
    } finally {
        if (input != null)
            input.close();
    }

    return null;
}

From source file:com.hichinaschool.flashcards.libanki.Utils.java

public static void printDate(String name, double date) {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    cal.setTimeInMillis((long) date * 1000);
    // Log.d(AnkiDroidApp.TAG, "Value of " + name + ": " + cal.getTime().toGMTString());
}

From source file:com.zimbra.examples.extns.samlprovider.SamlAuthToken.java

/**
 * Constructs instance from a SAML assertion element.
 *
 * @param samlAssertionElt/*from   w  w  w .  ja v  a  2s.co  m*/
 * @throws AuthTokenException
 */
public SamlAuthToken(Element samlAssertionElt) throws AuthTokenException {
    Element authnStmtElt;
    try {
        id = samlAssertionElt.getAttribute("ID");
        Element subjectElt = samlAssertionElt.getElement("Subject");
        Element nameIdElt = subjectElt.getElement("NameID");
        subjectNameId = nameIdElt.getTextTrim();
        Element conditionsElt = samlAssertionElt.getElement("Conditions");
        String notOnOrAfter = conditionsElt.getAttribute("NotOnOrAfter");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        expires = dateFormat.parse(notOnOrAfter);
        authnStmtElt = samlAssertionElt.getElement("AuthnStatement");
    } catch (Exception e) {
        ZimbraLog.extensions.error(e);
        throw new AuthTokenException("Error in parsing SAML auth token", e);
    }
    if (authnStmtElt == null)
        throw new AuthTokenException("SAML auth token does not contain any authentication statement");
}

From source file:ee.ria.xroad.confproxy.commandline.ConfProxyUtilViewConf.java

/**
 * Print the configuration proxy instance properties to the commandline.
 * @param instance configuration proxy instance name
 * @param conf configuration proxy properties instance
 * @throws Exception if errors occur when reading properties
 *//*from   w w  w.j av  a2s .  com*/
private void displayInfo(final String instance, final ConfProxyProperties conf) throws Exception {
    ConfigurationAnchorV2 anchor = null;
    String anchorError = null;
    try {
        anchor = new ConfigurationAnchorV2(conf.getProxyAnchorPath());
    } catch (Exception e) {
        anchorError = "'" + ConfProxyProperties.ANCHOR_XML + "' could not be loaded: " + e;
    }
    String delimiter = "==================================================";

    System.out.println("Configuration for proxy '" + instance + "'");
    int validityInterval = conf.getValidityIntervalSeconds();
    System.out.println("Validity interval: "
            + (validityInterval < 0 ? VALIDITY_INTERVAL_NA_MSG : validityInterval + " s."));
    System.out.println();

    System.out.println(ConfProxyProperties.ANCHOR_XML);
    System.out.println(delimiter);
    if (anchorError == null) {
        System.out.println("Instance identifier: " + anchor.getInstanceIdentifier());
        SimpleDateFormat sdf = new SimpleDateFormat("z yyyy-MMM-d hh:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("Generated at:        " + sdf.format(anchor.getGeneratedAt()));
        System.out.println("Hash:                " + anchorHash(conf));
    } else {
        System.out.println(anchorError);
    }
    System.out.println();

    System.out.println("Configuration URL");
    System.out.println(delimiter);
    if (conf.getConfigurationProxyURL().equals("0.0.0.0")) {
        System.out.println("configuration-proxy.address has not been" + " configured in 'local.ini'!");
    } else {
        System.out.println(conf.getConfigurationProxyURL() + "/" + OutputBuilder.SIGNED_DIRECTORY_NAME);
    }
    System.out.println();

    System.out.println("Signing keys and certificates");
    System.out.println(delimiter);

    System.out.println(ACTIVE_SIGNING_KEY_ID + ":");
    String activeKey = conf.getActiveSigningKey();
    System.out.println("\t" + (activeKey == null ? ACTIVE_KEY_NA_MSG : activeKey) + certInfo(activeKey, conf));
    List<String> inactiveKeys = conf.getKeyList();
    if (!inactiveKeys.isEmpty()) {
        System.out.println(SIGNING_KEY_ID_PREFIX + "*:");
        inactiveKeys.forEach(k -> System.out.println("\t" + k + certInfo(k, conf)));
    }
    System.out.println();
}

From source file:org.jasig.schedassist.impl.caldav.DefaultCaldavDialectImpl.java

/**
 * Convert the date to a String using the format:
 * <pre>//from  w w w  .  j a  v  a 2  s.  c  o  m
 yyyyMMdd'T'HHmmssZ
 </pre>
 *
 * @param date
 * @return
 */
protected String formatDateTime(Date date) {
    SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    return df.format(date);
}

From source file:org.forgerock.openicf.connectors.elastic.ElasticConnector.java

private String getNowTime() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    return sdf.format(new Date());
}