Example usage for java.text DateFormat getDateTimeInstance

List of usage examples for java.text DateFormat getDateTimeInstance

Introduction

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

Prototype

public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale) 

Source Link

Document

Gets the date/time formatter with the given formatting styles for the given locale.

Usage

From source file:org.jboss.dashboard.ui.taglib.formatter.Formatter.java

/**
 * Given an object it returns a string representation.
 *///from   www . jav  a 2 s  .c om
public String formatObject(Object obj) {
    if (obj == null)
        return null;

    if (obj instanceof String) {
        return (String) obj;
    }
    if (obj instanceof Number) {
        if (numberFormat == null)
            numberFormat = NumberFormat.getNumberInstance(getLocale());
        return numberFormat.format(obj);
    }
    if (obj instanceof Date) {
        if (dateTimeFormat == null)
            dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale());
        String dateStr = dateTimeFormat.format(obj);
        if (dateStr.indexOf("/") == 1)
            dateStr = "0" + dateStr;
        return dateStr;
    }
    return null;
}

From source file:org.pentaho.platform.scheduler.SchedulerAdminUIComponent.java

/**
 * This formatter works with a date/time string with this format:
 * May 21, 2008 8:29:21 PM/* w  w w. j av a 2s  . co  m*/
 * 
 * NOTE: the formatter cannot be shared across threads (since DateFormat implementations
 * are not guaranteed to be thread safe) or across sessions (since different 
 * sessions may have different locales). So create a new one an each call.
 * @return
 */
private DateFormat getDateTimeFormatter() {
    return DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, LocaleHelper.getLocale());
}

From source file:mitm.common.security.certificate.GenerateTestCertificates.java

private void generateCertificateKeyUsageNotForEncryption() throws Exception {
    X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder();

    String encodedPrivateKey = "30820276020100300d06092a864886f70d0101010500048202603082025c"
            + "0201000281810096383c89ad7b3c3be9dfcb24c1ba2b19f681847eaf862c"
            + "eec3cb2daf20da3f68f30221b46444c259228cc84f35095af19d2496a486"
            + "b4e818ce17241dd792a6c6ad07f8601c728f71f8016e1dbc5905fade3ecf"
            + "37b6374f4668bb3a5de16059125cea11ef3bd712a375dd33894670faa18b"
            + "8c733227a530ec569fcb5ade02523d020301000102818030202c24df934f"
            + "a4d234845c6e443a72c2ea938c12a7a5d5889c9b32341037a863d2170237"
            + "ed5f66370f6b4d14ecbe5a11c21b10f2a71a8477e22a0bf578623d5e961d"
            + "41151118d6114296baa55c479a33de26ef872f61eb59388bddb43c970614"
            + "52983edf79e71def89879820f06667b237be04b1fb18eaa203fb59d82ebc"
            + "71024100c9b7820310a62a3815564519a038bcfd99965ed9adf494214fca"
            + "d0d08019b9ba6821bcfc9faf448f1650e9e7aeba6b9ce3e7d6f9449c1897"
            + "d7dd7d0f4e8c39fb024100bea50896dc44c9cd710611e229fd7fe01c06f8"
            + "db7ea4428c99b243ba26937eaedfd9fae5eed02e292a8a4c7092320e29dc"
            + "143223b85cfeb43efbb1603ebce72702407bc7f82819575e20fc36ec4045"
            + "698bcfb327eb1c78fad4cb7c4360d0114bb805035170bf34de409bed7dc9"
            + "8b3a557b23d356b93c4d35dc81911d81589b42c17102406eb7cfc6358469"
            + "a2bb8a27e6ae364006baa03df4d396b7e389fb62a4007556745f22ec388f"
            + "3a2e24d044e361d935e2cde2b783eb04ce5549feee13b46e9b2caf024100"
            + "a8c35546c2241ce9b90b14c667d2b83512a6ad3b50f1511696c3eb7f608b"
            + "c292bad19c4fe11b466a045ebfdb92f371199369e22e5ce6a16578c9a25c" + "7b67e997";

    String encodedPublicKey = "30819f300d06092a864886f70d010101050003818d003081890281810096"
            + "383c89ad7b3c3be9dfcb24c1ba2b19f681847eaf862ceec3cb2daf20da3f"
            + "68f30221b46444c259228cc84f35095af19d2496a486b4e818ce17241dd7"
            + "92a6c6ad07f8601c728f71f8016e1dbc5905fade3ecf37b6374f4668bb3a"
            + "5de16059125cea11ef3bd712a375dd33894670faa18b8c733227a530ec56" + "9fcb5ade02523d0203010001";

    PrivateKey privateKey = decodePrivateKey(encodedPrivateKey);
    PublicKey publicKey = decodePublicKey(encodedPublicKey);

    X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder();

    String email = "test@example.com";

    subjectBuilder.setCommonName("Valid certificate");
    subjectBuilder.setEmail(email);//from   ww w. j  a  va2  s  . com
    subjectBuilder.setCountryCode("NL");
    subjectBuilder.setLocality("Amsterdam");
    subjectBuilder.setState("NH");

    AltNamesBuilder altNamesBuider = new AltNamesBuilder();
    altNamesBuider.setRFC822Names(email);

    X500Principal subject = subjectBuilder.buildPrincipal();
    GeneralNames altNames = altNamesBuider.buildAltNames();

    // use TreeSet because we want a deterministic certificate (ie. hash should not change)
    Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>();

    keyUsage.add(KeyUsageType.DIGITALSIGNATURE);
    keyUsage.add(KeyUsageType.NONREPUDIATION);

    Set<ExtendedKeyUsageType> extendedKeyUsage = new TreeSet<ExtendedKeyUsageType>();

    extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH);
    extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION);

    BigInteger serialNumber = new BigInteger("1178c336c7b51cadd4ccecdd14daf22", 16);

    Date now = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.UK)
            .parse("21-Nov-2007 10:38:35");

    certificateBuilder.setSubject(subject);
    certificateBuilder.setAltNames(altNames, true);
    certificateBuilder.setKeyUsage(keyUsage, true);
    certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true /* critical */);
    certificateBuilder.setNotBefore(DateUtils.addDays(now, -20));
    certificateBuilder.setNotAfter(DateUtils.addYears(now, 20));
    certificateBuilder.setPublicKey(publicKey);
    certificateBuilder.setSerialNumber(serialNumber);
    certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateBuilder.addSubjectKeyIdentifier(true);

    X509Certificate certificate = certificateBuilder.generateCertificate(caPrivateKey, caCertificate);

    assertNotNull(certificate);

    certificates.add(certificate);

    Certificate[] chain = new Certificate[] { certificate, caCertificate, rootCertificate };

    keyStore.setKeyEntry("KeyUsageNotForEncryption", privateKey, null, chain);
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private String doConvertToString(Map<String, Object> context, Object value) {
    String result = null;/*from  ww w.jav  a  2  s . co m*/

    if (value instanceof int[]) {
        int[] x = (int[]) value;
        List<Integer> intArray = new ArrayList<Integer>(x.length);

        for (int aX : x) {
            intArray.add(Integer.valueOf(aX));
        }

        result = StringUtils.join(intArray, ", ");
    } else if (value instanceof long[]) {
        long[] x = (long[]) value;
        List<Long> longArray = new ArrayList<Long>(x.length);

        for (long aX : x) {
            longArray.add(Long.valueOf(aX));
        }

        result = StringUtils.join(longArray, ", ");
    } else if (value instanceof double[]) {
        double[] x = (double[]) value;
        List<Double> doubleArray = new ArrayList<Double>(x.length);

        for (double aX : x) {
            doubleArray.add(new Double(aX));
        }

        result = StringUtils.join(doubleArray, ", ");
    } else if (value instanceof boolean[]) {
        boolean[] x = (boolean[]) value;
        List<Boolean> booleanArray = new ArrayList<Boolean>(x.length);

        for (boolean aX : x) {
            booleanArray.add(new Boolean(aX));
        }

        result = StringUtils.join(booleanArray, ", ");
    } else if (value instanceof Date) {
        DateFormat df = null;
        if (value instanceof java.sql.Time) {
            df = DateFormat.getTimeInstance(DateFormat.MEDIUM, getLocale(context));
        } else if (value instanceof java.sql.Timestamp) {
            SimpleDateFormat dfmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT,
                    DateFormat.MEDIUM, getLocale(context));
            df = new SimpleDateFormat(dfmt.toPattern() + MILLISECOND_FORMAT);
        } else {
            df = DateFormat.getDateInstance(DateFormat.SHORT, getLocale(context));
        }
        result = df.format(value);
    } else if (value instanceof String[]) {
        result = StringUtils.join((String[]) value, ", ");
    }

    return result;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder./*w  w  w.  j av  a2s  . com*/
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}

From source file:com.opensymphony.xwork2.validator.AnnotationValidationConfigurationBuilder.java

private Date parseDateString(String value, String format) {

    SimpleDateFormat d0 = null;/*  w w  w  .  j av a2 s.  c o  m*/
    if (StringUtils.isNotEmpty(format)) {
        d0 = new SimpleDateFormat(format);
    }
    SimpleDateFormat d1 = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG,
            Locale.getDefault());
    SimpleDateFormat d2 = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM,
            Locale.getDefault());
    SimpleDateFormat d3 = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
            Locale.getDefault());
    SimpleDateFormat[] dfs = (d0 != null ? new SimpleDateFormat[] { d0, d1, d2, d3 }
            : new SimpleDateFormat[] { d1, d2, d3 });
    for (SimpleDateFormat df : dfs)
        try {
            Date check = df.parse(value);
            if (check != null) {
                return check;
            }
        } catch (ParseException ignore) {
        }
    return null;
}

From source file:mitm.common.security.certificate.GenerateTestCertificates.java

private void generateCertificateKeyUsageNotForSigning() throws Exception {
    X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder();

    String encodedPrivateKey = "30820278020100300d06092a864886f70d0101010500048202623082025e"
            + "02010002818100c5ca31e3581e600cd09c7892837aecedc10d4b5eeb9d1d"
            + "77ac0ab497deeb842b6fe3cdd3d021bb9680691310387259acc73e6d8173"
            + "fa734069d0d9216c58eae254f68a075f8f9fa99c77c0383f1736be7e697a"
            + "859f476de03c54cb171e984f29b42813244625ff75916bb66b2839cfb661"
            + "acafbf045b08d682544c3a832e9f6102030100010281805a7f5328344f61"
            + "9f3b6bfc76fd15a78679483dee265bf2f9a88c15694fa3ef0b78dc8076a3"
            + "ca6b6c4740cc6a25899ca2435fbaf6fa3be3b3db36a5c277328ff544736c"
            + "6042e589f910f3c1df23701dec59a8e2679cde9e9984fc6032b6c8734416"
            + "07f062afdd59ac5d48a902b02915892d8b07ed222ba63986e02c7c2b3e3a"
            + "09024100f252c537b30837deb16283ac2691229a9d1a90d0832e9717a6b9"
            + "7321026d8a9ed001d0ce192794e1a1466371cec0e68f06a3def7daed21a0"
            + "32fc101021e98e3f024100d0f3fa76613b4320d47817741841c4bd36c19a"
            + "4a01bb57c39e854a4678d237e08b27ff4778eca5440e04856f64be56bc8b"
            + "67b42d32f3450fb63d2d5be1b3aa5f024100a8a1cf1af6dd063c54073188"
            + "908239a98d20da9c305e30c945be128f6b281dea6ce8868d9655c436cc4b"
            + "b69291860e2c843b6fc3de375d4a2590e200c808c7730241008e673832a5"
            + "61360691c6a6754072d21a01cf3fcf600ec569540792ef2438604c6f89fa"
            + "b842f9444875252fab1305852749fa8b18a2b8984074fa8c8729f2c01102"
            + "4100808c7c7d221cd46df7a56112b0fd424ca4b2755a416bf8ba23a7b292"
            + "253157c35eac72069a07b0145cc48bb3f15cc3f2b1e924be4af863801ba3" + "ad0d909505c8";

    String encodedPublicKey = "30819f300d06092a864886f70d010101050003818d0030818902818100c5"
            + "ca31e3581e600cd09c7892837aecedc10d4b5eeb9d1d77ac0ab497deeb84"
            + "2b6fe3cdd3d021bb9680691310387259acc73e6d8173fa734069d0d9216c"
            + "58eae254f68a075f8f9fa99c77c0383f1736be7e697a859f476de03c54cb"
            + "171e984f29b42813244625ff75916bb66b2839cfb661acafbf045b08d682" + "544c3a832e9f610203010001";

    PrivateKey privateKey = decodePrivateKey(encodedPrivateKey);
    PublicKey publicKey = decodePublicKey(encodedPublicKey);

    X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder();

    String email = "test@example.com";

    subjectBuilder.setCommonName("Valid certificate");
    subjectBuilder.setEmail(email);/*from w ww  .  ja  v  a2  s .c  o  m*/
    subjectBuilder.setCountryCode("NL");
    subjectBuilder.setLocality("Amsterdam");
    subjectBuilder.setState("NH");

    AltNamesBuilder altNamesBuider = new AltNamesBuilder();
    altNamesBuider.setRFC822Names(email);

    X500Principal subject = subjectBuilder.buildPrincipal();
    GeneralNames altNames = altNamesBuider.buildAltNames();

    // use TreeSet because we want a deterministic certificate (ie. hash should not change)
    Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>();

    keyUsage.add(KeyUsageType.KEYENCIPHERMENT);

    Set<ExtendedKeyUsageType> extendedKeyUsage = new TreeSet<ExtendedKeyUsageType>();

    extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH);
    extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION);

    BigInteger serialNumber = new BigInteger("1178c38151374d6c4b29f891b9b4a77", 16);

    Date now = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.UK)
            .parse("21-Nov-2007 10:38:35");

    certificateBuilder.setSubject(subject);
    certificateBuilder.setAltNames(altNames, true);
    certificateBuilder.setKeyUsage(keyUsage, true);
    certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true /* critical */);
    certificateBuilder.setNotBefore(DateUtils.addDays(now, -20));
    certificateBuilder.setNotAfter(DateUtils.addYears(now, 20));
    certificateBuilder.setPublicKey(publicKey);
    certificateBuilder.setSerialNumber(serialNumber);
    certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateBuilder.addSubjectKeyIdentifier(true);

    X509Certificate certificate = certificateBuilder.generateCertificate(caPrivateKey, caCertificate);

    assertNotNull(certificate);

    certificates.add(certificate);

    Certificate[] chain = new Certificate[] { certificate, caCertificate, rootCertificate };

    keyStore.setKeyEntry("KeyUsageNotForSigning", privateKey, null, chain);
}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

/** In EJBCA 4.0.0 we changed the date format to ISO 8601. This verifies the that we still accept old requests, but returns UserDataVOWS objects using the new DateFormat 
 * @throws AuthorizationDeniedException */
@Test/*from   w ww  . j a v  a 2  s  .  c  o  m*/
public void test36EjbcaWsHelperTimeFormatConversion()
        throws CADoesntExistsException, ClassCastException, EjbcaException, AuthorizationDeniedException {
    log.trace(">test36EjbcaWsHelperTimeFormatConversion()");
    final Date nowWithOutSeconds = new Date((new Date().getTime() / 60000) * 60000); // To avoid false negatives.. we will loose precision when we convert back and forth..
    final String oldTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.US)
            .format(nowWithOutSeconds);
    final String newTimeFormatStorage = FastDateFormat
            .getInstance("yyyy-MM-dd HH:mm", TimeZone.getTimeZone("UTC")).format(nowWithOutSeconds);
    final String newTimeFormatRequest = FastDateFormat
            .getInstance("yyyy-MM-dd HH:mm:ssZZ", TimeZone.getTimeZone("CEST")).format(nowWithOutSeconds);
    final String newTimeFormatResponse = FastDateFormat
            .getInstance("yyyy-MM-dd HH:mm:ssZZ", TimeZone.getTimeZone("UTC")).format(nowWithOutSeconds);
    final String relativeTimeFormat = "0123:12:31";
    log.debug("oldTimeFormat=" + oldTimeFormat);
    log.debug("newTimeFormatStorage=" + newTimeFormatStorage);
    log.debug("newTimeFormatRequest=" + newTimeFormatRequest);
    // Convert from UserDataVOWS with US Locale DateFormat to endEntityInformation
    final org.ejbca.core.protocol.ws.objects.UserDataVOWS userDataVoWs = new org.ejbca.core.protocol.ws.objects.UserDataVOWS(
            "username", "password", false, "CN=User U", "CA1", null, null, 10, "P12", "EMPTY", "ENDUSER", null);
    userDataVoWs.setStartTime(oldTimeFormat);
    userDataVoWs.setEndTime(oldTimeFormat);
    final EndEntityInformation endEntityInformation1 = EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3,
            4, 5);
    assertEquals("CUSTOM_STARTTIME in old format was not correctly handled (VOWS to VO).", newTimeFormatStorage,
            endEntityInformation1.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_STARTTIME));
    assertEquals("CUSTOM_ENDTIME in old format was not correctly handled (VOWS to VO).", newTimeFormatStorage,
            endEntityInformation1.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_ENDTIME));
    // Convert from UserDataVOWS with standard DateFormat to endEntityInformation
    userDataVoWs.setStartTime(newTimeFormatRequest);
    userDataVoWs.setEndTime(newTimeFormatRequest);
    final EndEntityInformation endEntityInformation2 = EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3,
            4, 5);
    assertEquals("ExtendedInformation.CUSTOM_STARTTIME in new format was not correctly handled.",
            newTimeFormatStorage,
            endEntityInformation2.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_STARTTIME));
    assertEquals("ExtendedInformation.CUSTOM_ENDTIME in new format was not correctly handled.",
            newTimeFormatStorage,
            endEntityInformation2.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_ENDTIME));
    // Convert from UserDataVOWS with relative date format to endEntityInformation
    userDataVoWs.setStartTime(relativeTimeFormat);
    userDataVoWs.setEndTime(relativeTimeFormat);
    final EndEntityInformation endEntityInformation3 = EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3,
            4, 5);
    assertEquals("ExtendedInformation.CUSTOM_STARTTIME in relative format was not correctly handled.",
            relativeTimeFormat,
            endEntityInformation3.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_STARTTIME));
    assertEquals("ExtendedInformation.CUSTOM_ENDTIME in relative format was not correctly handled.",
            relativeTimeFormat,
            endEntityInformation3.getExtendedinformation().getCustomData(ExtendedInformation.CUSTOM_ENDTIME));
    // Convert from endEntityInformation with standard DateFormat to UserDataVOWS
    final org.ejbca.core.protocol.ws.objects.UserDataVOWS userDataVoWs1 = EjbcaWSHelper
            .convertEndEntityInformation(endEntityInformation1, "CA1", "EEPROFILE", "CERTPROFILE",
                    "HARDTOKENISSUER", "P12");
    // We expect that the server will respond using UTC
    assertEquals("CUSTOM_STARTTIME in new format was not correctly handled (VO to VOWS).",
            newTimeFormatResponse, userDataVoWs1.getStartTime());
    assertEquals("CUSTOM_ENDTIME in new format was not correctly handled (VO to VOWS).", newTimeFormatResponse,
            userDataVoWs1.getEndTime());
    // Convert from EndEntityInformation with relative date format to UserDataVOWS
    final org.ejbca.core.protocol.ws.objects.UserDataVOWS userDataVoWs3 = EjbcaWSHelper
            .convertEndEntityInformation(endEntityInformation3, "CA1", "EEPROFILE", "CERTPROFILE",
                    "HARDTOKENISSUER", "P12");
    assertEquals("CUSTOM_STARTTIME in relative format was not correctly handled (VO to VOWS).",
            relativeTimeFormat, userDataVoWs3.getStartTime());
    assertEquals("CUSTOM_ENDTIME in relative format was not correctly handled (VO to VOWS).",
            relativeTimeFormat, userDataVoWs3.getEndTime());
    // Try some invalid start time date format
    userDataVoWs.setStartTime("12:32 2011-02-28"); // Invalid
    userDataVoWs.setEndTime("2011-02-28 12:32:00+00:00"); // Valid
    try {
        EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3, 4, 5);
        fail("Conversion of illegal time format did not generate exception.");
    } catch (EjbcaException e) {
        assertEquals("Unexpected error code in exception.", ErrorCode.FIELD_VALUE_NOT_VALID, e.getErrorCode());
    }
    // Try some invalid end time date format
    userDataVoWs.setStartTime("2011-02-28 12:32:00+00:00"); // Valid
    userDataVoWs.setEndTime("12:32 2011-02-28"); // Invalid
    try {
        EjbcaWSHelper.convertUserDataVOWS(userDataVoWs, 1, 2, 3, 4, 5);
        fail("Conversion of illegal time format did not generate exception.");
    } catch (EjbcaException e) {
        assertEquals("Unexpected error code in exception.", ErrorCode.FIELD_VALUE_NOT_VALID, e.getErrorCode());
    }
    log.trace("<test36EjbcaWsHelperTimeFormatConversion()");
}

From source file:org.pentaho.platform.repository.subscription.SubscriptionHelper.java

/**
 * This formatter works with a date/time string with this format: May 21, 2008 8:29:21 PM
 * //from  w w w  .  ja  v a 2s. co  m
 * NOTE: the formatter cannot be shared across threads (since DateFormat implementations are not guaranteed to be thread safe) or across sessions (since
 * different sessions may have different locales). So create a new one an each call.
 * 
 * @return
 */
public static DateFormat getDateTimeFormatter() {
    return DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, LocaleHelper.getLocale());
}

From source file:DateFormatUtils.java

/**
 * <p>Gets a date/time formatter instance using the specified style,
 * time zone and locale.</p>//from   w  ww .j  av a  2  s . com
 * 
 * @param dateStyle  date style: FULL, LONG, MEDIUM, or SHORT
 * @param timeStyle  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted date
 * @param locale  optional locale, overrides system locale
 * @return a localized standard date/time formatter
 * @throws IllegalArgumentException if the Locale has no date/time
 *  pattern defined
 */
public static synchronized FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone,
        Locale locale) {

    Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle));
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    key = new Pair(key, locale);

    FastDateFormat format = (FastDateFormat) cDateTimeInstanceCache.get(key);
    if (format == null) {
        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle,
                    locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cDateTimeInstanceCache.put(key, format);

        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date time pattern for locale: " + locale);
        }
    }
    return format;
}