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.pentaho.reporting.libraries.formula.typing.DefaultTypeRegistry.java

public String convertToText(final Type type1, final Object value) throws EvaluationException {
    if (value == null) {
        return "";
    }//from w  w w  . j av  a 2 s  . c  om

    // already converted or compatible
    if (type1.isFlagSet(Type.TEXT_TYPE)) {
        // no need to check whatever it is a String
        return computeStringValue(value);
    }

    if (type1.isFlagSet(Type.LOGICAL_TYPE)) {
        if (value instanceof Boolean) {
            final Boolean b = (Boolean) value;
            if (Boolean.TRUE.equals(b)) {
                return "TRUE";
            } else {
                return "FALSE";
            }
        } else {
            throw TypeConversionException.getInstance();
        }
    }

    // 2 types of numeric : numbers and dates
    if (type1.isFlagSet(Type.NUMERIC_TYPE)) {
        final LocalizationContext localizationContext = context.getLocalizationContext();
        if (type1.isFlagSet(Type.DATETIME_TYPE) || type1.isFlagSet(Type.DATE_TYPE)
                || type1.isFlagSet(Type.TIME_TYPE)) {
            final Date d = convertToDate(type1, value);
            final List dateFormats = localizationContext.getDateFormats(type1);
            if (dateFormats != null && dateFormats.size() >= 1) {
                final DateFormat format = (DateFormat) dateFormats.get(0);
                return format.format(d);
            } else {
                // fallback
                return DateFormat
                        .getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, localizationContext.getLocale())
                        .format(d);
            }
        } else {
            try {
                final Number n = convertToNumber(type1, value);
                final List<NumberFormat> numberFormats = localizationContext.getNumberFormats();
                if (numberFormats.isEmpty()) {
                    // use the canonical format ..
                    return NumberFormat.getNumberInstance(localizationContext.getLocale()).format(n);
                } else {
                    numberFormats.get(0).format(n);
                }
            } catch (EvaluationException nfe) {
                // ignore ..
            }
        }
    }

    return computeStringValue(value);
}

From source file:org.ejbca.core.model.ra.ExtendedInformation.java

/** Implementation of UpgradableDataHashMap function upgrade. */
public void upgrade() {
    if (Float.compare(LATEST_VERSION, getVersion()) != 0) {
        // New version of the class, upgrade
        String msg = intres.getLocalizedMessage("endentity.extendedinfoupgrade", new Float(getVersion()));
        log.info(msg);/*from ww  w.  j  a v  a2  s .co m*/

        if (data.get(SUBJECTDIRATTRIBUTES) == null) {
            data.put(SUBJECTDIRATTRIBUTES, "");
        }
        if (data.get(MAXFAILEDLOGINATTEMPTS) == null) {
            setMaxLoginAttempts(DEFAULT_MAXLOGINATTEMPTS);
        }
        if (data.get(REMAININGLOGINATTEMPTS) == null) {
            setRemainingLoginAttempts(DEFAULT_REMAININGLOGINATTEMPTS);
        }
        // In EJBCA 4.0.0 we changed the date format
        if (getVersion() < 3) {
            final DateFormat oldDateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT,
                    Locale.US);
            final FastDateFormat newDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm");
            try {
                final String oldCustomStartTime = getCustomData(ExtendedInformation.CUSTOM_STARTTIME);
                if (!isEmptyOrRelative(oldCustomStartTime)) {
                    // We use an absolute time format, so we need to upgrade
                    final String newCustomStartTime = newDateFormat
                            .format(oldDateFormat.parse(oldCustomStartTime));
                    setCustomData(ExtendedInformation.CUSTOM_STARTTIME, newCustomStartTime);
                    if (log.isDebugEnabled()) {
                        log.debug("Upgraded " + ExtendedInformation.CUSTOM_STARTTIME + " from \""
                                + oldCustomStartTime + "\" to \"" + newCustomStartTime
                                + "\" in ExtendedInformation.");
                    }
                }
            } catch (ParseException e) {
                log.error("Unable to upgrade " + ExtendedInformation.CUSTOM_STARTTIME
                        + " in extended user information.", e);
            }
            try {
                final String oldCustomEndTime = getCustomData(ExtendedInformation.CUSTOM_ENDTIME);
                if (!isEmptyOrRelative(oldCustomEndTime)) {
                    // We use an absolute time format, so we need to upgrade
                    final String newCustomEndTime = newDateFormat.format(oldDateFormat.parse(oldCustomEndTime));
                    setCustomData(ExtendedInformation.CUSTOM_ENDTIME, newCustomEndTime);
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Upgraded " + ExtendedInformation.CUSTOM_ENDTIME + " from \"" + oldCustomEndTime
                                        + "\" to \"" + newCustomEndTime + "\" in ExtendedInformation.");
                    }
                }
            } catch (ParseException e) {
                log.error("Unable to upgrade " + ExtendedInformation.CUSTOM_ENDTIME
                        + " in extended user information.", e);
            }
        }
        // In 4.0.2 we further specify the storage format by saying that UTC TimeZone is implied instead of local server time
        if (getVersion() < 4) {
            final String[] timePatterns = { "yyyy-MM-dd HH:mm" };
            final String oldStartTime = getCustomData(ExtendedInformation.CUSTOM_STARTTIME);
            if (!isEmptyOrRelative(oldStartTime)) {
                try {
                    final String newStartTime = ValidityDate
                            .formatAsUTC(DateUtils.parseDateStrictly(oldStartTime, timePatterns));
                    setCustomData(ExtendedInformation.CUSTOM_STARTTIME, newStartTime);
                    if (log.isDebugEnabled()) {
                        log.debug("Upgraded " + ExtendedInformation.CUSTOM_STARTTIME + " from \"" + oldStartTime
                                + "\" to \"" + newStartTime + "\" in EndEntityProfile.");
                    }
                } catch (ParseException e) {
                    log.error("Unable to upgrade " + ExtendedInformation.CUSTOM_STARTTIME
                            + " to UTC in EndEntityProfile! Manual interaction is required (edit and verify).",
                            e);
                }
            }
            final String oldEndTime = getCustomData(ExtendedInformation.CUSTOM_ENDTIME);
            if (!isEmptyOrRelative(oldEndTime)) {
                // We use an absolute time format, so we need to upgrade
                try {
                    final String newEndTime = ValidityDate
                            .formatAsUTC(DateUtils.parseDateStrictly(oldEndTime, timePatterns));
                    setCustomData(ExtendedInformation.CUSTOM_ENDTIME, newEndTime);
                    if (log.isDebugEnabled()) {
                        log.debug("Upgraded " + ExtendedInformation.CUSTOM_ENDTIME + " from \"" + oldEndTime
                                + "\" to \"" + newEndTime + "\" in EndEntityProfile.");
                    }
                } catch (ParseException e) {
                    log.error("Unable to upgrade " + ExtendedInformation.CUSTOM_ENDTIME
                            + " to UTC in EndEntityProfile! Manual interaction is required (edit and verify).",
                            e);
                }
            }
        }
        data.put(VERSION, new Float(LATEST_VERSION));
    }
}

From source file:org.apache.struts2.components.Date.java

public boolean end(Writer writer, String body) {
    String msg = null;//from  ww  w .ja v a  2s  .c om
    ValueStack stack = getStack();
    java.util.Date date = null;
    // find the name on the valueStack, and cast it to a date
    try {
        date = (java.util.Date) findValue(name);
    } catch (Exception e) {
        LOG.error("Could not convert object with key '" + name + "' to a java.util.Date instance");
        // bad date, return a blank instead ?
        msg = "";
    }

    //try to find the format on the stack
    if (format != null) {
        format = findString(format);
    }
    if (date != null) {
        TextProvider tp = findProviderInStack();
        if (tp != null) {
            if (nice) {
                msg = formatTime(tp, date);
            } else {
                if (format == null) {
                    String globalFormat = null;

                    // if the format is not specified, fall back using the
                    // defined property DATETAG_PROPERTY
                    globalFormat = tp.getText(DATETAG_PROPERTY);

                    // if tp.getText can not find the property then the
                    // returned string is the same as input =
                    // DATETAG_PROPERTY
                    if (globalFormat != null && !DATETAG_PROPERTY.equals(globalFormat)) {
                        msg = new SimpleDateFormat(globalFormat, ActionContext.getContext().getLocale())
                                .format(date);
                    } else {
                        msg = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM,
                                ActionContext.getContext().getLocale()).format(date);
                    }
                } else {
                    msg = new SimpleDateFormat(format, ActionContext.getContext().getLocale()).format(date);
                }
            }
            if (msg != null) {
                try {
                    if (getId() == null) {
                        writer.write(msg);
                    } else {
                        stack.getContext().put(getId(), msg);
                    }
                } catch (IOException e) {
                    LOG.error("Could not write out Date tag", e);
                }
            }
        }
    }
    return super.end(writer, "");
}

From source file:org.apache.empire.struts2.jsp.controls.TextInputControl.java

protected DateFormat getDateFormat(DataType dataType, Locale locale, Column column) {
    DateFormat df;//from   w  ww.  j ava  2s . c o  m
    if (dataType == DataType.DATE)
        df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
    else
        df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
    return df;
}

From source file:hudson.scm.CVSSCM.java

private void configureDate(ArgumentListBuilder cmd, Date date) { // #192
    if (isTag)/*from  ww  w .  j  a v  a 2 s .c  o  m*/
        return; // don't use the -D option.
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US);
    df.setTimeZone(TimeZone.getTimeZone("UTC")); // #209
    cmd.add("-D", df.format(date));
}

From source file:at.alladin.rmbt.mapServer.MarkerResource.java

@Post("json")
public String request(final String entity) {
    addAllowOrigin();/*from  w  w w .  j  a  va  2s .c  om*/

    final MapServerOptions mso = MapServerOptions.getInstance();
    final Classification classification = Classification.getInstance();

    JSONObject request = null;

    final JSONObject answer = new JSONObject();

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            String lang = request.optString("language");

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang))
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

            //                System.out.println(request.toString(4));

            final JSONObject coords = request.getJSONObject("coords");

            final int zoom;
            double geo_x = 0;
            double geo_y = 0;
            int size = 0;

            boolean useXY = false;
            boolean useLatLon = false;

            if (coords.has("x") && coords.has("y"))
                useXY = true;
            else if (coords.has("lat") && coords.has("lon"))
                useLatLon = true;

            if (coords.has("z") && (useXY || useLatLon)) {
                zoom = coords.optInt("z");
                if (useXY) {
                    geo_x = coords.optDouble("x");
                    geo_y = coords.optDouble("y");
                } else if (useLatLon) {
                    final double tmpLat = coords.optDouble("lat");
                    final double tmpLon = coords.optDouble("lon");
                    geo_x = GeoCalc.lonToMeters(tmpLon);
                    geo_y = GeoCalc.latToMeters(tmpLat);
                    //                        System.out.println(String.format("using %f/%f", geo_x, geo_y));
                }

                if (coords.has("size"))
                    size = coords.getInt("size");

                if (zoom != 0 && geo_x != 0 && geo_y != 0) {
                    double radius = 0;
                    if (size > 0)
                        radius = size * GeoCalc.getResFromZoom(256, zoom); // TODO use real tile size
                    else
                        radius = CLICK_RADIUS * GeoCalc.getResFromZoom(256, zoom); // TODO use real tile size
                    final double geo_x_min = geo_x - radius;
                    final double geo_x_max = geo_x + radius;
                    final double geo_y_min = geo_y - radius;
                    final double geo_y_max = geo_y + radius;

                    String hightlightUUIDString = null;
                    UUID highlightUUID = null;

                    final JSONObject mapOptionsObj = request.getJSONObject("options");
                    String optionStr = mapOptionsObj.optString("map_options");
                    if (optionStr == null || optionStr.length() == 0) // set
                                                                      // default
                        optionStr = "mobile/download";

                    final MapOption mo = mso.getMapOptionMap().get(optionStr);

                    final List<SQLFilter> filters = new ArrayList<>(mso.getDefaultMapFilters());
                    filters.add(mso.getAccuracyMapFilter());

                    final JSONObject mapFilterObj = request.getJSONObject("filter");

                    final Iterator<?> keys = mapFilterObj.keys();

                    while (keys.hasNext()) {
                        final String key = (String) keys.next();
                        if (mapFilterObj.get(key) instanceof Object)
                            if (key.equals("highlight"))
                                hightlightUUIDString = mapFilterObj.getString(key);
                            else {
                                final MapFilter mapFilter = mso.getMapFilterMap().get(key);
                                if (mapFilter != null)
                                    filters.add(mapFilter.getFilter(mapFilterObj.getString(key)));
                            }
                    }

                    if (hightlightUUIDString != null)
                        try {
                            highlightUUID = UUID.fromString(hightlightUUIDString);
                        } catch (final Exception e) {
                            highlightUUID = null;
                        }

                    if (conn != null) {
                        PreparedStatement ps = null;
                        ResultSet rs = null;

                        final StringBuilder whereSQL = new StringBuilder(mo.sqlFilter);
                        for (final SQLFilter sf : filters)
                            whereSQL.append(" AND ").append(sf.where);

                        final String sql = String.format("SELECT"
                                + (useLatLon ? " geo_lat lat, geo_long lon"
                                        : " ST_X(t.location) x, ST_Y(t.location) y")
                                + ", t.time, t.timezone, t.speed_download, t.speed_upload, t.ping_median, t.network_type,"
                                + " t.signal_strength, t.lte_rsrp, t.wifi_ssid, t.network_operator_name, t.network_operator,"
                                + " t.network_sim_operator, t.roaming_type, t.public_ip_as_name, " //TODO: sim_operator obsoled by sim_name
                                + " pMob.shortname mobile_provider_name," // TODO: obsoleted by mobile_network_name
                                + " prov.shortname provider_text, t.open_test_uuid,"
                                + " COALESCE(mnwk.shortname,mnwk.name) mobile_network_name,"
                                + " COALESCE(msim.shortname,msim.name) mobile_sim_name"
                                + (highlightUUID == null ? "" : " , c.uid, c.uuid") + " FROM v_test t"
                                + " LEFT JOIN mccmnc2name mnwk ON t.mobile_network_id=mnwk.uid"
                                + " LEFT JOIN mccmnc2name msim ON t.mobile_sim_id=msim.uid"
                                + " LEFT JOIN provider prov" + " ON t.provider_id=prov.uid"
                                + " LEFT JOIN provider pMob" + " ON t.mobile_provider_id=pMob.uid"
                                + (highlightUUID == null ? ""
                                        : " LEFT JOIN client c ON (t.client_id=c.uid AND c.uuid=?)")
                                + " WHERE" + " %s"
                                + " AND location && ST_SetSRID(ST_MakeBox2D(ST_Point(?,?), ST_Point(?,?)), 900913)"
                                + " ORDER BY" + (highlightUUID == null ? "" : " c.uid ASC,") + " t.uid DESC"
                                + " LIMIT 5", whereSQL);

                        //                            System.out.println("SQL: " + sql);
                        ps = conn.prepareStatement(sql);

                        int i = 1;

                        if (highlightUUID != null)
                            ps.setObject(i++, highlightUUID);

                        for (final SQLFilter sf : filters)
                            i = sf.fillParams(i, ps);
                        ps.setDouble(i++, geo_x_min);
                        ps.setDouble(i++, geo_y_min);
                        ps.setDouble(i++, geo_x_max);
                        ps.setDouble(i++, geo_y_max);

                        //                            System.out.println("SQL: " + ps.toString());
                        if (ps.execute()) {

                            final Locale locale = new Locale(lang);
                            final Format format = new SignificantFormat(2, locale);

                            final JSONArray resultList = new JSONArray();

                            rs = ps.getResultSet();

                            while (rs.next()) {
                                final JSONObject jsonItem = new JSONObject();

                                JSONArray jsonItemList = new JSONArray();

                                // RMBTClient Info
                                if (highlightUUID != null && rs.getString("uuid") != null)
                                    jsonItem.put("highlight", true);

                                final double res_x = rs.getDouble(1);
                                final double res_y = rs.getDouble(2);
                                final String openTestUUID = rs.getObject("open_test_uuid").toString();

                                jsonItem.put("lat", res_x);
                                jsonItem.put("lon", res_y);
                                jsonItem.put("open_test_uuid", "O" + openTestUUID);
                                // marker.put("uid", uid);

                                final Date date = rs.getTimestamp("time");
                                final String tzString = rs.getString("timezone");
                                final TimeZone tz = TimeZone.getTimeZone(tzString);
                                final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                                        DateFormat.MEDIUM, locale);
                                dateFormat.setTimeZone(tz);
                                jsonItem.put("time_string", dateFormat.format(date));

                                final int fieldDown = rs.getInt("speed_download");
                                JSONObject singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_DOWNLOAD"));
                                final String downloadString = String.format("%s %s",
                                        format.format(fieldDown / 1000d),
                                        labels.getString("RESULT_DOWNLOAD_UNIT"));
                                singleItem.put("value", downloadString);
                                singleItem.put("classification",
                                        Classification.classify(classification.THRESHOLD_DOWNLOAD, fieldDown));
                                // singleItem.put("help", "www.rtr.at");

                                jsonItemList.put(singleItem);

                                final int fieldUp = rs.getInt("speed_upload");
                                singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_UPLOAD"));
                                final String uploadString = String.format("%s %s",
                                        format.format(fieldUp / 1000d), labels.getString("RESULT_UPLOAD_UNIT"));
                                singleItem.put("value", uploadString);
                                singleItem.put("classification",
                                        Classification.classify(classification.THRESHOLD_UPLOAD, fieldUp));
                                // singleItem.put("help", "www.rtr.at");

                                jsonItemList.put(singleItem);

                                final long fieldPing = rs.getLong("ping_median");
                                final int pingValue = (int) Math.round(rs.getDouble("ping_median") / 1000000d);
                                singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_PING"));
                                final String pingString = String.format("%s %s", format.format(pingValue),
                                        labels.getString("RESULT_PING_UNIT"));
                                singleItem.put("value", pingString);
                                singleItem.put("classification",
                                        Classification.classify(classification.THRESHOLD_PING, fieldPing));
                                // singleItem.put("help", "www.rtr.at");

                                jsonItemList.put(singleItem);

                                final int networkType = rs.getInt("network_type");

                                final String signalField = rs.getString("signal_strength");
                                if (signalField != null && signalField.length() != 0) {
                                    final int signalValue = rs.getInt("signal_strength");
                                    final int[] threshold = networkType == 99 || networkType == 0
                                            ? classification.THRESHOLD_SIGNAL_WIFI
                                            : classification.THRESHOLD_SIGNAL_MOBILE;
                                    singleItem = new JSONObject();
                                    singleItem.put("title", labels.getString("RESULT_SIGNAL"));
                                    singleItem.put("value",
                                            signalValue + " " + labels.getString("RESULT_SIGNAL_UNIT"));
                                    singleItem.put("classification",
                                            Classification.classify(threshold, signalValue));
                                    jsonItemList.put(singleItem);
                                }

                                final String lteRsrpField = rs.getString("lte_rsrp");
                                if (lteRsrpField != null && lteRsrpField.length() != 0) {
                                    final int lteRsrpValue = rs.getInt("lte_rsrp");
                                    final int[] threshold = classification.THRESHOLD_SIGNAL_RSRP;
                                    singleItem = new JSONObject();
                                    singleItem.put("title", labels.getString("RESULT_LTE_RSRP"));
                                    singleItem.put("value",
                                            lteRsrpValue + " " + labels.getString("RESULT_LTE_RSRP_UNIT"));
                                    singleItem.put("classification",
                                            Classification.classify(threshold, lteRsrpValue));
                                    jsonItemList.put(singleItem);
                                }

                                jsonItem.put("measurement", jsonItemList);

                                jsonItemList = new JSONArray();

                                singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_NETWORK_TYPE"));
                                singleItem.put("value", Helperfunctions.getNetworkTypeName(networkType));

                                jsonItemList.put(singleItem);

                                if (networkType == 98 || networkType == 99) // mobile wifi or browser
                                {
                                    String providerText = MoreObjects.firstNonNull(
                                            rs.getString("provider_text"), rs.getString("public_ip_as_name"));
                                    if (!Strings.isNullOrEmpty(providerText)) {
                                        if (providerText.length() > (MAX_PROVIDER_LENGTH + 3)) {
                                            providerText = providerText.substring(0, MAX_PROVIDER_LENGTH)
                                                    + "...";
                                        }

                                        singleItem = new JSONObject();
                                        singleItem.put("title", labels.getString("RESULT_PROVIDER"));
                                        singleItem.put("value", providerText);
                                        jsonItemList.put(singleItem);
                                    }
                                    if (networkType == 99) // mobile wifi
                                    {
                                        if (highlightUUID != null && rs.getString("uuid") != null) // own test
                                        {
                                            final String ssid = rs.getString("wifi_ssid");
                                            if (ssid != null && ssid.length() != 0) {
                                                singleItem = new JSONObject();
                                                singleItem.put("title", labels.getString("RESULT_WIFI_SSID"));
                                                singleItem.put("value", ssid.toString());
                                                jsonItemList.put(singleItem);
                                            }
                                        }
                                    }
                                } else // mobile
                                {
                                    String networkOperator = rs.getString("network_operator");
                                    String mobileNetworkName = rs.getString("mobile_network_name");
                                    String simOperator = rs.getString("network_sim_operator");
                                    String mobileSimName = rs.getString("mobile_sim_name");
                                    final int roamingType = rs.getInt("roaming_type");
                                    //network
                                    if (!Strings.isNullOrEmpty(networkOperator)) {
                                        final String mobileNetworkString;
                                        if (roamingType != 2) { //not international roaming - display name of home network
                                            if (Strings.isNullOrEmpty(mobileSimName))
                                                mobileNetworkString = networkOperator;
                                            else
                                                mobileNetworkString = String.format("%s (%s)", mobileSimName,
                                                        networkOperator);
                                        } else { //international roaming - display name of network
                                            if (Strings.isNullOrEmpty(mobileSimName))
                                                mobileNetworkString = networkOperator;
                                            else
                                                mobileNetworkString = String.format("%s (%s)",
                                                        mobileNetworkName, networkOperator);
                                        }

                                        singleItem = new JSONObject();
                                        singleItem.put("title", labels.getString("RESULT_MOBILE_NETWORK"));
                                        singleItem.put("value", mobileNetworkString);
                                        jsonItemList.put(singleItem);
                                    }
                                    //home network (sim)
                                    else if (!Strings.isNullOrEmpty(simOperator)) {
                                        final String mobileNetworkString;

                                        if (Strings.isNullOrEmpty(mobileSimName))
                                            mobileNetworkString = simOperator;
                                        else
                                            mobileNetworkString = String.format("%s (%s)", mobileSimName,
                                                    simOperator);

                                        /*
                                        if (!Strings.isNullOrEmpty(mobileProviderName)) {
                                           mobileNetworkString = mobileProviderName;
                                        } else {
                                           mobileNetworkString = simOperator;
                                        }
                                        */

                                        singleItem = new JSONObject();
                                        singleItem.put("title", labels.getString("RESULT_HOME_NETWORK"));
                                        singleItem.put("value", mobileNetworkString);
                                        jsonItemList.put(singleItem);
                                    }

                                    if (roamingType > 0) {
                                        singleItem = new JSONObject();
                                        singleItem.put("title", labels.getString("RESULT_ROAMING"));
                                        singleItem.put("value",
                                                Helperfunctions.getRoamingType(labels, roamingType));
                                        jsonItemList.put(singleItem);
                                    }
                                }

                                jsonItem.put("net", jsonItemList);

                                resultList.put(jsonItem);

                                if (resultList.length() == 0)
                                    System.out.println("Error getting Results.");
                                // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"),
                                // new Object[] {uuid}));

                            }

                            answer.put("measurements", resultList);
                        } else
                            System.out.println("Error executing SQL.");
                    } else
                        System.out.println("No Database Connection.");
                }
            } else
                System.out.println("Expected request is missing.");

        } catch (final JSONException e) {
            System.out.println("Error parsing JSDON Data " + e.toString());
        } catch (final SQLException e) {
            e.printStackTrace();
        }
    else
        System.out.println("No Request.");

    return answer.toString();

}

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

/**
 * Create a Message List./*w  ww . j av a2s  .c  om*/
 * Fetches a list of headers in folder foldername for part list_part.
 * The messagelist will be stored in the "MESSAGES" environment.
 *
 * @param foldername folder for which a message list should be built
 * @param list_part part of list to display (1 = last xx messages, 2 = total-2*xx - total-xx messages)
 */
public void createMessageList(String folderhash, int list_part) throws NoSuchFolderException {
    long time_start = System.currentTimeMillis();
    TimeZone tz = TimeZone.getDefault();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
            user.getPreferredLocale());
    df.setTimeZone(tz);

    try {
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);
        Element xml_current = model.setCurrentFolder(folderhash);
        Element xml_messagelist = model.getMessageList(xml_folder);

        if (folder == null) {
            throw new NoSuchFolderException(folderhash);
        }

        long fetch_start = System.currentTimeMillis();

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

        /* Calculate first and last message to show */
        int total_messages = folder.getMessageCount();
        int new_messages = folder.getNewMessageCount();
        int show_msgs = user.getMaxShowMessages();

        xml_messagelist.setAttribute("total", total_messages + "");
        xml_messagelist.setAttribute("new", new_messages + "");

        log.debug("Total: " + total_messages);

        /* Handle small messagelists correctly */
        if (total_messages < show_msgs) {
            show_msgs = total_messages;
        }
        /* Don't accept list-parts smaller than 1 */
        if (list_part < 1) {
            list_part = 1;
        }
        for (int k = 0; k < list_part; k++) {
            total_messages -= show_msgs;
        }
        /* Handle beginning of message list */
        if (total_messages < 0) {
            total_messages = 0;
        }
        int first = total_messages + 1;
        int last = total_messages + show_msgs;
        /* Set environment variable */
        setEnv();
        xml_current.setAttribute("first_msg", first + "");
        xml_current.setAttribute("last_msg", last + "");
        xml_current.setAttribute("list_part", list_part + "");

        /* Fetch headers */
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        log.debug("Last: " + last + ", first: " + first);
        Message[] msgs = folder.getMessages(first, last);
        log.debug(msgs.length + " messages fetching...");
        folder.fetch(msgs, fp);
        long fetch_stop = System.currentTimeMillis();

        Map header = new Hashtable(15);

        Flags.Flag[] sf;
        String from, to, cc, bcc, replyto, subject;
        String messageid;

        for (int i = msgs.length - 1; i >= 0; i--) {
            //              if(((MimeMessage)msgs[i]).getMessageID() == null) {
            //                  folder.close(false);
            //                  folder.open(Folder.READ_WRITE);
            //                  ((MimeMessage)msgs[i]).setHeader("Message-ID","<"+user.getLogin()+"."+System.currentTimeMillis()+".jwebmail@"+user.getDomain()+">");
            //                  ((MimeMessage)msgs[i]).saveChanges();
            //                  folder.close(false);
            //                  folder.open(Folder.READ_ONLY);
            //              }

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

            XMLMessage xml_message = model.getMessage(xml_folder, msgs[i].getMessageNumber() + "", messageid);

            /* Addresses */
            from = "";
            replyto = "";
            to = "";
            cc = "";
            bcc = "";
            try {
                from = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getFrom()));
            } catch (UnsupportedEncodingException e) {
                from = Helper.joinAddress(msgs[i].getFrom());
            }
            try {
                replyto = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getReplyTo()));
            } catch (UnsupportedEncodingException e) {
                replyto = Helper.joinAddress(msgs[i].getReplyTo());
            }
            try {
                to = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO)));
            } catch (UnsupportedEncodingException e) {
                to = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO));
            }
            try {
                cc = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC)));
            } catch (UnsupportedEncodingException e) {
                cc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC));
            }
            try {
                bcc = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC)));
            } catch (UnsupportedEncodingException e) {
                bcc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC));
            }
            if (from == "")
                from = getStringResource("unknown sender");
            if (to == "")
                to = getStringResource("unknown recipient");

            /* Flags */
            sf = msgs[i].getFlags().getSystemFlags();
            String basepath = parent.getBasePath();

            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");
            }
            if (msgs[i] instanceof MimeMessage
                    && ((MimeMessage) msgs[i]).getContentType().toUpperCase().startsWith("MULTIPART/")) {
                xml_message.setAttribute("attachment", "true");
            }

            if (msgs[i] instanceof MimeMessage) {
                int size = ((MimeMessage) msgs[i]).getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");
            }

            /* Subject */
            subject = "";
            if (msgs[i].getSubject() != null) {
                try {
                    subject = MimeUtility.decodeText(msgs[i].getSubject());
                } catch (UnsupportedEncodingException ex) {
                    subject = msgs[i].getSubject();
                    log.warn("Unsupported Encoding: " + ex.getMessage());
                }
            }
            if (subject == null || subject.equals("")) {
                subject = getStringResource("no subject");
            }

            /* Set all of what we found into the DOM */
            xml_message.setHeader("FROM", from);
            try {
                // hmm, why decode subject twice? Though it doesn't matter..
                xml_message.setHeader("SUBJECT", MimeUtility.decodeText(subject));
            } catch (UnsupportedEncodingException e) {
                xml_message.setHeader("SUBJECT", subject);
                log.warn("Unsupported Encoding: " + e.getMessage());
            }
            xml_message.setHeader("TO", to);
            xml_message.setHeader("CC", cc);
            xml_message.setHeader("BCC", bcc);
            xml_message.setHeader("REPLY-TO", replyto);

            /* Date */
            Date d = msgs[i].getSentDate();
            String ds = "";
            if (d != null) {
                ds = df.format(d);
            }
            xml_message.setHeader("DATE", ds);
        }
        long time_stop = System.currentTimeMillis();
        // try {
        // XMLCommon.writeXML(model.getRoot(),new FileOutputStream("/tmp/wmdebug"),"");
        // } catch(IOException ex) {}

        log.debug("Construction of message list took " + (time_stop - time_start)
                + " ms. Time for IMAP transfer was " + (fetch_stop - fetch_start) + " ms.");
        folder.close(false);
    } catch (NullPointerException e) {
        log.error("Failed to construct message list", e);
        throw new NoSuchFolderException(folderhash);
    } catch (MessagingException ex) {
        log.error("Failed to construct message list.  " + "For some reason, contuing anyways.", ex);
    }
}

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

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

    String encodedPrivateKey = "30820276020100300d06092a864886f70d0101010500048202603082025c"
            + "02010002818100a9fee3017954c99b248d1486830c71b2e0ea3f9b7a2763"
            + "1bed8a731f5bd7e1edf856bc3fb7c63dedbeb5bb0de474e7792b3aa7e7b2"
            + "274c03a47c7d89b1935eaef172c6395f2322f1ed9e61ae46d716b4b4394c"
            + "1a802db05a2d7c3d1d41a3e8afc65ff8dada7414744f1ee1540e50ee7fb8"
            + "db437b20c5ee33a82b9d575cfbc951020301000102818004f84ab2b45562"
            + "3f82e60cff91bd3f65b765a1ce6dd7d0f1f413e421ba91a92d47e161478b"
            + "9be41b9b43bce03f199bdad304b7fbf21d6bff7f439477fe150ce38c312f"
            + "c015f3c89291aaa42c4c106f623dfd9f76acad2f1c77b590f038ffbb25f9"
            + "14b6f7ead769808ddd0e2d648442620b50518d9b7fb132b2fa1fa3e9d628"
            + "41024100e69ab3765120d0e0ba5dc21bf384b2f553211b4b1902175454c6"
            + "2f1b0f8ad385d78490539308c9fd5145ae36cc2a6d364fdd97d83d9b6623"
            + "a987db239e716055024100bcb77acf1e9829ab5b2c9a5e73d343db857474"
            + "a529ba52ca256655eb7d760e85d3c68eec9500e3db0494c8f77cb8058593"
            + "6e52a9290149367392d74ecdc3510d024100bd15723b7cb024b56ffabad3"
            + "c26c3774f2b1bdb8690c0ee7060feec6088b737f56450b368be4740332e5"
            + "a8c0a3cdd1f8eba9adfd101ee0b43329036584604075024055465b9a27ea"
            + "fe394e33b375a6c4fa4ec1d943b4364cd9883aaa297d05ee48d5b4426ee6"
            + "fcd5b02091cb619c63a10bedb6170e071e5e5464e4889ffe1e007a290240"
            + "7b60d23994a2ec38db909678446ed56d32455bf684141b9ee0aec68b2025"
            + "1d4d94fd2beebf02074559b811ae1130d2e2aa3bec2e9bccb06969104856" + "00c70759";

    String encodedPublicKey = "30819f300d06092a864886f70d010101050003818d0030818902818100a9"
            + "fee3017954c99b248d1486830c71b2e0ea3f9b7a27631bed8a731f5bd7e1"
            + "edf856bc3fb7c63dedbeb5bb0de474e7792b3aa7e7b2274c03a47c7d89b1"
            + "935eaef172c6395f2322f1ed9e61ae46d716b4b4394c1a802db05a2d7c3d"
            + "1d41a3e8afc65ff8dada7414744f1ee1540e50ee7fb8db437b20c5ee33a8" + "2b9d575cfbc9510203010001";

    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  w  w . j av  a 2s . c om
    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.KEYENCIPHERMENT);
    keyUsage.add(KeyUsageType.NONREPUDIATION);

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

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

    BigInteger serialNumber = new BigInteger("115fcd741088707366e9727452c9770", 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, false);
    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("ValidCertificate", privateKey, null, chain);
}

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

private Object doConvertToDate(Map<String, Object> context, Object value, Class toType) {
    Date result = null;//from w w w . j av  a2s  .  c o  m

    if (value instanceof String && value != null && ((String) value).length() > 0) {
        String sa = (String) value;
        Locale locale = getLocale(context);

        DateFormat df = null;
        if (java.sql.Time.class == toType) {
            df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
        } else if (java.sql.Timestamp.class == toType) {
            Date check = null;
            SimpleDateFormat dtfmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT,
                    DateFormat.MEDIUM, locale);
            SimpleDateFormat fullfmt = new SimpleDateFormat(dtfmt.toPattern() + MILLISECOND_FORMAT, locale);

            SimpleDateFormat dfmt = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);

            SimpleDateFormat[] fmts = { fullfmt, dtfmt, dfmt };
            for (SimpleDateFormat fmt : fmts) {
                try {
                    check = fmt.parse(sa);
                    df = fmt;
                    if (check != null) {
                        break;
                    }
                } catch (ParseException ignore) {
                }
            }
        } else if (java.util.Date.class == toType) {
            Date check = null;
            DateFormat[] dfs = getDateFormats(locale);
            for (DateFormat df1 : dfs) {
                try {
                    check = df1.parse(sa);
                    df = df1;
                    if (check != null) {
                        break;
                    }
                } catch (ParseException ignore) {
                }
            }
        }
        //final fallback for dates without time
        if (df == null) {
            df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        }
        try {
            df.setLenient(false); // let's use strict parsing (XW-341)
            result = df.parse(sa);
            if (!(Date.class == toType)) {
                try {
                    Constructor constructor = toType.getConstructor(new Class[] { long.class });
                    return constructor.newInstance(new Object[] { Long.valueOf(result.getTime()) });
                } catch (Exception e) {
                    throw new XWorkException(
                            "Couldn't create class " + toType + " using default (long) constructor", e);
                }
            }
        } catch (ParseException e) {
            throw new XWorkException("Could not parse date", e);
        }
    } else if (Date.class.isAssignableFrom(value.getClass())) {
        result = (Date) value;
    }
    return result;
}

From source file:org.parakoopa.gmnetgate.punch.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  w  w. j  a v  a 2 s. co 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;
    }
    DateFormat date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
    /* CONSOLE OUTPUT */
    if (!Mediator.quiet) {
        System.out.println(date.format(new Date()) + " : " + str);
    }
    /* FILE LOG */
    if (Mediator.log != null) {
        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);
        }
    }
}