Example usage for java.text DateFormat SHORT

List of usage examples for java.text DateFormat SHORT

Introduction

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

Prototype

int SHORT

To view the source code for java.text DateFormat SHORT.

Click Source Link

Document

Constant for short style pattern.

Usage

From source file:org.wings.session.WingServlet.java

public final SessionServlet getSessionServlet(HttpServletRequest request, HttpServletResponse response,
        boolean createSessionServlet) throws ServletException {
    final HttpSession httpSession = request.getSession(true);

    // it should be enough to synchronize on the http session object...
    synchronized (httpSession) {
        SessionServlet sessionServlet = null;

        if (httpSession != null) {
            sessionServlet = (SessionServlet) httpSession.getAttribute(lookupName);
        }/*  w  ww  .  ja v  a 2 s. com*/

        // Sanity check - maybe this is a stored/deserialized session servlet?
        if (sessionServlet != null && !sessionServlet.isValid()) {
            sessionServlet.destroy();
            sessionServlet = null;
        }

        /*
         * we are only interested in a new session, if the response is
         * not null. If it is null, then we just called getSessionServlet()
         * for lookup purposes and are satisfied, if we don't get anything.
         */
        if (sessionServlet == null) {
            if (createSessionServlet) {
                log.info("no session servlet, create new one");
                sessionServlet = newSession(request, response);
                httpSession.setAttribute(lookupName, sessionServlet);
            } else {
                return null;
            }
        }

        if (log.isDebugEnabled()) {
            StringBuilder message = new StringBuilder().append("session id: ")
                    .append(request.getRequestedSessionId()).append(", created at: ")
                    .append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                            .format(new java.util.Date(httpSession.getCreationTime())))
                    .append(", identified via:")
                    .append(request.isRequestedSessionIdFromCookie() ? " cookie" : "")
                    .append(request.isRequestedSessionIdFromURL() ? " URL" : "").append(", expiring after: ")
                    .append(httpSession.getMaxInactiveInterval()).append("s ");
            log.debug(message.toString());
            //log.debug("session valid " + request.isRequestedSessionIdValid());
            //log.debug("session httpsession id " + httpSession.getId());
            //log.debug("session httpsession new " + httpSession.isNew());
            //log.debug("session last accessed at " +
            //        new java.util.Date(httpSession.getLastAccessedTime()));
            //log.debug("session expiration timeout (s) " +
            //        httpSession.getMaxInactiveInterval());
            //log.debug("session contains wings session " +
            //        (httpSession.getAttribute(lookupName) != null));
        }

        sessionServlet.getSession().getExternalizeManager().setResponse(response);

        /* Handling of the requests character encoding.
         * --------------------------------------------
         * The following block is needed for a correct handling of
         * non-ISO-8859-1 data:
         *
         * Using LocaleCharacterSet and/or charset.properties we can
         * advise the client to use i.e. UTF-8 as character encoding.
         * Once told the browser consequently also encodes his requests
         * in the choosen characterset of the sings session. This is
         * achieved by adding the HTML code
         * <meta http-equiv="Content-Type" content="text/html;charset="<charset>">
         * to the generated pages.
         *
         * If the user hasn't overridden the encoding in their browser,
         * then all form data (e.g. mueller) is submitted with data encoded
         * like m%C3%BCller because byte pair C3 BC is how the german
         * u-umlaut is represented in UTF-8. If the form is
         * iso-8859-1 encoded then you get m%FCller, because byte FC is
         * how it is presented in iso-8859-1.
         *
         * So the browser behaves correctly by sending his form input
         * correctly encoded in the advised character encoding. The issue
         * is that the servlet container is typically unable to determine
         * the correct encoding of this form data. By proposal the browser
         * should als declare the used character encoding for his data.
         * But actual browsers omit this information and hence the servlet
         * container is unable to guess the right encoding (Tomcat actually
         * thenalways guesses ISO 8859-1). This results in totally
         * scrumbled up data for all non ISO-8859-1 character encodings.
         * With the block below we tell the servlet container about the
         * character encoding we expect in the browsers request and hence
         * the servlet container can do the correct decoding.
         * This has to be done at very first, otherwise the servlet
         * container will ignore this setting.
         */
        if ((request.getCharacterEncoding() == null)) { // was servlet container able to identify encoding?
            try {
                String sessionCharacterEncoding = sessionServlet.getSession().getCharacterEncoding();
                // We know better about the used character encoding than tomcat
                log.debug("Advising servlet container to interpret request as " + sessionCharacterEncoding);
                request.setCharacterEncoding(sessionCharacterEncoding);
            } catch (UnsupportedEncodingException e) {
                log.warn("Problem on applying current session character encoding", e);
            }
        }

        return sessionServlet;
    }
}

From source file:org.parakoopa.udphp.mediator.Mediator.java

/**
 * Logs to the console (if quiet was not set) and to the logfile if specified
 * The logfile will also get timestamps for each event.
 * @param str String to log/*from  w ww .  ja  v a 2s  . c o m*/
 * @param verbose boolean Should this be logged only with --verbose?
 */
public static void log(String str, boolean verbose) {
    //Don't print verbose lines if not requested
    if (verbose && !Mediator.verbose)
        return;
    /* CONSOLE OUTPUT */
    if (!Mediator.quiet) {
        System.out.println(str);
    }
    /* FILE LOG */
    if (Mediator.log != null) {
        DateFormat date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
                Locale.getDefault());
        try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(Mediator.log, true)))) {
            out.println(date.format(new Date()) + " : " + str);
        } catch (IOException ex) {
            Logger.getLogger(Mediator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.alfresco.web.forms.xforms.XFormsProcessor.java

/**
 * Generates html text which bootstraps the JavaScript code that will
 * call back into the XFormsBean and get the xform and build the ui.
 *///from  w ww  .j a  v  a 2  s  .c  o  m
public void process(final Session session, final Writer out) throws FormProcessor.ProcessingException {
    final FacesContext fc = FacesContext.getCurrentInstance();
    //make the XFormsBean available for this session
    final XFormsBean xforms = (XFormsBean) FacesHelper.getManagedBean(fc, XFormsBean.BEAN_NAME);
    final AVMBrowseBean avmBrowseBean = (AVMBrowseBean) FacesHelper.getManagedBean(fc, AVMBrowseBean.BEAN_NAME);
    try {
        xforms.setXFormsSession((XFormsBean.XFormsSession) session);
    } catch (FormBuilderException fbe) {
        LOGGER.error(fbe);
        throw new ProcessingException(fbe);
    } catch (XFormsException xfe) {
        LOGGER.error(xfe);
        throw new ProcessingException(xfe);
    }

    final String contextPath = fc.getExternalContext().getRequestContextPath();
    final Document result = XMLUtil.newDocument();
    final String xformsUIDivId = "alfresco-xforms-ui";

    // this div is where the ui will write to
    final Element div = result.createElement("div");
    div.setAttribute("id", xformsUIDivId);
    result.appendChild(div);

    Element e = result.createElement("link");
    e.setAttribute("rel", "stylesheet");
    e.setAttribute("type", "text/css");
    e.setAttribute("href", contextPath + "/css/xforms.css");
    div.appendChild(e);

    // a script with config information and globals.
    e = result.createElement("script");
    e.setAttribute("type", "text/javascript");
    final StringBuilder js = new StringBuilder("\n");
    final String[] jsNamespacesObjects = { "alfresco", "alfresco.constants", "alfresco.xforms",
            "alfresco.xforms.constants" };
    for (final String jsNamespace : jsNamespacesObjects) {
        js.append(jsNamespace).append(" = typeof ").append(jsNamespace).append(" == 'undefined' ? {} : ")
                .append(jsNamespace).append(";\n");
    }
    js.append("alfresco.constants.DEBUG = ").append(LOGGER.isDebugEnabled()).append(";\n");
    js.append("alfresco.constants.WEBAPP_CONTEXT = '").append(JavaScriptUtils.javaScriptEscape(contextPath))
            .append("';\n");

    String avmWebApp = avmBrowseBean.getWebapp();

    // TODO - need better way to determine WCM vs ECM context
    js.append("alfresco.constants.AVM_WEBAPP_CONTEXT = '");
    if (avmWebApp != null) {
        js.append(JavaScriptUtils.javaScriptEscape(avmWebApp));
    }
    js.append("';\n");

    // TODO - need better way to determine WCM vs ECM context
    js.append("alfresco.constants.AVM_WEBAPP_URL = '");
    if (avmWebApp != null) {
        //Use preview store because when user upload image it appears in preview, not in main store.
        String storeName = AVMUtil.getCorrespondingPreviewStoreName(avmBrowseBean.getSandbox());
        if (storeName != null) {
            js.append(JavaScriptUtils.javaScriptEscape(
                    fc.getExternalContext().getRequestContextPath() + "/wcs/api/path/content/avm/"
                            + AVMUtil.buildStoreWebappPath(storeName, avmWebApp).replace(":", "")));
        }
    }

    js.append("';\n");

    js.append("alfresco.constants.AVM_WEBAPP_PREFIX = '");
    if (avmWebApp != null) {
        String storeName = AVMUtil.getCorrespondingPreviewStoreName(avmBrowseBean.getSandbox());
        if (storeName != null) {
            js.append(JavaScriptUtils.javaScriptEscape(fc.getExternalContext().getRequestContextPath()
                    + "/wcs/api/path/content/avm/" + AVMUtil.buildSandboxRootPath(storeName).replace(":", "")));
        }
    }

    js.append("';\n");
    js.append("alfresco.constants.LANGUAGE = '");
    String lang = Application.getLanguage(FacesContext.getCurrentInstance()).toString();
    // the language can be passed as "en_US" or just "en"
    if (lang.length() > 4)
        lang = lang.substring(0, lang.indexOf("_"));
    js.append(lang);
    js.append("';\n");
    js.append("alfresco.xforms.constants.XFORMS_UI_DIV_ID = '").append(xformsUIDivId).append("';\n");
    js.append("alfresco.xforms.constants.FORM_INSTANCE_DATA_NAME = '")
            .append(JavaScriptUtils.javaScriptEscape(session.getFormInstanceDataName())).append("';\n");
    SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.SHORT,
            Application.getLanguage(fc));
    js.append("alfresco.xforms.constants.DATE_FORMAT = '").append(sdf.toPattern()).append("';\n");
    sdf = (SimpleDateFormat) SimpleDateFormat.getTimeInstance(DateFormat.SHORT, Application.getLanguage(fc));
    js.append("alfresco.xforms.constants.TIME_FORMAT = '").append(sdf.toPattern()).append("';\n");
    sdf = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
            Application.getLanguage(fc));
    js.append("alfresco.xforms.constants.DATE_TIME_FORMAT = '").append(sdf.toPattern()).append("';\n");
    for (String[] ns : JS_NAMESPACES) {
        js.append("alfresco.xforms.constants.").append(ns[0].toUpperCase()).append("_NS = '").append(ns[1])
                .append("';\n");
        js.append("alfresco.xforms.constants.").append(ns[0].toUpperCase()).append("_PREFIX = '").append(ns[2])
                .append("';\n");
    }

    final ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance());
    js.append("alfresco.resources = {\n");
    for (String k : BUNDLE_KEYS) {
        js.append(k).append(": '").append(JavaScriptUtils.javaScriptEscape(bundle.getString(k))).append("'")
                .append(k.equals(BUNDLE_KEYS[BUNDLE_KEYS.length - 1]) ? "\n};" : ",").append("\n");
    }

    try {
        js.append("alfresco.xforms.widgetConfig = \n")
                .append(LOGGER.isDebugEnabled() ? XFormsProcessor.widgetConfig.toString(0)
                        : XFormsProcessor.widgetConfig)
                .append("\n");
    } catch (JSONException jsone) {
        LOGGER.error(jsone);
    }
    e.appendChild(result.createTextNode(js.toString()));

    div.appendChild(e);

    // include all our scripts, order is significant
    for (final String script : JS_SCRIPTS) {
        if (script == null) {
            continue;
        }
        e = result.createElement("script");
        e.setAttribute("type", "text/javascript");
        e.setAttribute("src", contextPath + script);
        e.appendChild(result.createTextNode("\n"));
        div.appendChild(e);
    }

    // output any custom scripts
    ConfigElement config = Application.getConfigService(fc).getGlobalConfig().getConfigElement("wcm");
    if (config != null) {
        // get the custom scripts to include
        ConfigElement xformsScriptsConfig = config.getChild("xforms-scripts");
        if (xformsScriptsConfig != null) {
            StringTokenizer t = new StringTokenizer(xformsScriptsConfig.getValue().trim(), ", ");
            while (t.hasMoreTokens()) {
                e = result.createElement("script");
                e.setAttribute("type", "text/javascript");
                e.setAttribute("src", contextPath + t.nextToken());
                e.appendChild(result.createTextNode("\n"));
                div.appendChild(e);
            }
        }
    }

    XMLUtil.print(result, out);
}

From source file:Dates.java

public static String dateFormatForJSCalendar(Locale locale) {
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    String date = df.format(create(1, 2, 1971)); // d, m, y
    boolean always4InYear = "es".equals(locale.getLanguage()) || "pl".equals(locale.getLanguage());
    String result = date.replaceAll("01", "%d").replaceAll("02", "%m").replaceAll("1971", "%Y")
            .replaceAll("71", always4InYear ? "%Y" : "%y").replaceAll("1", "%d").replaceAll("2", "%m");
    return result;
}

From source file:org.jumpmind.db.platform.AbstractDdlBuilder.java

/**
 * Sets the locale that is used for number and date formatting (when
 * printing default values and in generates insert/update/delete
 * statements).//  w  ww. j a v a 2 s .  c om
 *
 * @param localeStr
 *            The new locale or <code>null</code> if default formatting
 *            should be used; Format is "language[_country[_variant]]"
 */
public void setValueLocale(String localeStr) {
    if (localeStr != null) {
        int sepPos = localeStr.indexOf('_');
        String language = null;
        String country = null;
        String variant = null;

        if (sepPos > 0) {
            language = localeStr.substring(0, sepPos);
            country = localeStr.substring(sepPos + 1);
            sepPos = country.indexOf('_');
            if (sepPos > 0) {
                variant = country.substring(sepPos + 1);
                country = country.substring(0, sepPos);
            }
        } else {
            language = localeStr;
        }
        if (language != null) {
            Locale locale = null;

            if (variant != null) {
                locale = new Locale(language, country, variant);
            } else if (country != null) {
                locale = new Locale(language, country);
            } else {
                locale = new Locale(language);
            }

            valueLocale = localeStr;
            setValueDateFormat(DateFormat.getDateInstance(DateFormat.SHORT, locale));
            setValueTimeFormat(DateFormat.getTimeInstance(DateFormat.SHORT, locale));
            setValueNumberFormat(NumberFormat.getNumberInstance(locale));
            return;
        }
    }
    valueLocale = null;
    setValueDateFormat(null);
    setValueTimeFormat(null);
    setValueNumberFormat(null);
}

From source file:javadz.beanutils.locale.converters.DateLocaleConverter.java

/**
 * Convert the specified locale-sensitive input object into an output object of the
 * specified type./*  w  w  w .  ja v  a2  s . co  m*/
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the convertion
 * @return the converted Date value
 *
 * @exception org.apache.commons.beanutils.ConversionException 
 * if conversion cannot be performed successfully
 * @throws ParseException if an error occurs parsing
 */
protected Object parse(Object value, String pattern) throws ParseException {

    // Handle Date
    if (value instanceof java.util.Date) {
        return value;
    }

    // Handle Calendar
    if (value instanceof java.util.Calendar) {
        return ((java.util.Calendar) value).getTime();
    }

    if (locPattern) {
        pattern = convertLocalizedPattern(pattern, locale);
    }

    // Create Formatter - use default if pattern is null
    DateFormat formatter = pattern == null ? DateFormat.getDateInstance(DateFormat.SHORT, locale)
            : new SimpleDateFormat(pattern, locale);
    formatter.setLenient(isLenient);

    // Parse the Date
    ParsePosition pos = new ParsePosition(0);
    String strValue = value.toString();
    Object parsedValue = formatter.parseObject(strValue, pos);
    if (pos.getErrorIndex() > -1) {
        throw new ConversionException("Error parsing date '" + value + "' at position=" + pos.getErrorIndex());
    }
    if (pos.getIndex() < strValue.length()) {
        throw new ConversionException(
                "Date '" + value + "' contains unparsed characters from position=" + pos.getIndex());
    }

    return parsedValue;
}

From source file:org.apache.syncope.client.console.SyncopeConsoleSession.java

public FastDateFormat getDateFormat() {
    Locale locale = getLocale() == null ? Locale.ENGLISH : getLocale();
    return FastDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
}

From source file:mobisocial.bento.anyshare.util.DBHelper.java

private long addObjectByPostdata(long localId, Postdata postdata, long hash, byte[] raw, long parentid,
        String feedname, String sender) {
    long objId = (localId == -1) ? getNextId() : localId;
    String sizestr = "";
    if (postdata.datatype.equals(Postdata.TYPE_STREAM)) {
        if (postdata.filesize < 972) {
            sizestr = "(" + postdata.filesize + "Byte)";
        } else if (postdata.filesize < 996147) {
            sizestr = "(" + Math.floor(postdata.filesize / 1024 * 10) / 10 + "KB)";
        } else if (postdata.filesize > 0) {
            sizestr = "(" + Math.floor(postdata.filesize / 1024 / 1024 * 10) / 10 + "MB)";
        }/*from www .  j  a va 2s.c om*/
    }
    String desc = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
            .format(new Date(Long.parseLong(postdata.timestamp))) + " " + sizestr;
    if (!sender.isEmpty()) {
        desc += " by " + sender;
    }
    String title = postdata.title;

    ContentValues cv = new ContentValues();
    cv.put(ItemObject._ID, objId);
    cv.put(ItemObject.FEEDNAME, feedname);
    cv.put(ItemObject.TITLE, title);
    cv.put(ItemObject.DESC, desc);
    cv.put(ItemObject.TIMESTAMP, postdata.timestamp);
    cv.put(ItemObject.OBJHASH, hash);
    cv.put(ItemObject.PARENT_ID, parentid);

    if (raw != null) {
        cv.put(ItemObject.RAW, raw);
    }
    //        Log.d(TAG, cv.toString());

    getWritableDatabase().insertOrThrow(ItemObject.TABLE, null, cv);

    return objId;
}

From source file:org.apache.zookeeper.server.persistence.TxnLogToolkit.java

private void printTxn(byte[] bytes, String prefix) throws IOException {
    TxnHeader hdr = new TxnHeader();
    Record txn = SerializeUtils.deserializeTxn(bytes, hdr);
    String txnStr = getDataStrFromTxn(txn);
    String txns = String.format("%s session 0x%s cxid 0x%s zxid 0x%s %s %s",
            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date(hdr.getTime())),
            Long.toHexString(hdr.getClientId()), Long.toHexString(hdr.getCxid()),
            Long.toHexString(hdr.getZxid()), TraceFormatter.op2String(hdr.getType()), txnStr);
    if (prefix != null && !"".equals(prefix.trim())) {
        System.out.print(prefix + " - ");
    }/*from w ww .  j  av  a 2s  .  c o  m*/
    if (txns.endsWith("\n")) {
        System.out.print(txns);
    } else {
        System.out.println(txns);
    }
}

From source file:com.brq.wallet.activity.export.BackupToPdfActivity.java

private String getExportFileName(long exportTime) {
    Date exportDate = new Date(exportTime);
    Locale locale = getResources().getConfiguration().locale;
    String hourString = DateFormat.getDateInstance(DateFormat.SHORT, locale).format(exportDate);
    hourString = replaceInvalidFileNameChars(hourString);
    String dateString = DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(exportDate);
    dateString = replaceInvalidFileNameChars(dateString);
    return FILE_NAME_PREFIX + '-' + hourString + '-' + dateString + ".pdf";
}