List of usage examples for java.text DateFormat MEDIUM
int MEDIUM
To view the source code for java.text DateFormat MEDIUM.
Click Source Link
From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java
private String doConvertToString(Map<String, Object> context, Object value) { String result = null;/* ww w . j ava 2s .c o 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:org.gnenc.yams.portlet.AccountManagement.java
public void removeAccountOnSchedule(ActionRequest actionRequest, ActionResponse actionResponse) { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); Account callingAccount = null;// ww w. j a va 2 s.com try { callingAccount = ActionUtil.accountFromEmailAddress(themeDisplay.getUser().getEmailAddress()); } catch (Exception e1) { e1.printStackTrace(); } String jspPage = null; String backURL = DAOParamUtil.getString(actionRequest, "backURL"); String dateString = DAOParamUtil.getString(actionRequest, "remove-date"); Date date = null; Date noticeDate = null; DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM); try { date = new SimpleDateFormat("MM/dd/yy").parse(dateString); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, -6); noticeDate = cal.getTime(); } catch (ParseException e1) { SessionErrors.add(actionRequest, "remove-account-failed"); jspPage = PortletUtil.ACCT_MGMT_ACCOUNT_REMOVE_JSP; } Account account = ActionUtil.accountFromUidNumber(DAOParamUtil.getString(actionRequest, "uidNumber")); actionResponse.setRenderParameter("uidNumber", account.getAttribute("uidNumber")); actionResponse.setRenderParameter("backURL", backURL); if (PermissionsChecker.hasPermission(callingAccount, account, PermissionsChecker.PERMISSION_ACCOUNT_REMOVE)) { try { // Send email 7 days before removal JobQueueLocalServiceUtil.addJob(themeDisplay.getUserId(), account.getMail().get(0), account.getDisplayName(), "Scheduled removal of " + account.getMail().get(0), PortletUtil.JOB_ACTION_REMOVE_EMAIL_NOTICE, noticeDate); // Remove the account on the date JobQueueLocalServiceUtil.addJob(themeDisplay.getUserId(), account.getMail().get(0), account.getDisplayName(), "Scheduled removal of " + account.getMail().get(0), PortletUtil.JOB_ACTION_REMOVE, date); // Send an email immediately MailEngine.send(PropsValues.JOB_FROM_EMAIL_ADDRESS, account.getMail().get(0), PropsValues.JOB_REMOVE_NOTICE_EMAIL_SUBJECT, PropsValues.JOB_REMOVE_NOTICE_EMAIL_BODY + "\n\nRemoval date: " + df.format(date)); } catch (Exception e) { SessionErrors.add(actionRequest, "remove-account-failed"); e.printStackTrace(); jspPage = PortletUtil.ACCT_MGMT_ACCOUNT_REMOVE_JSP; } jspPage = PortletUtil.SEARCH_VIEW_JSP; } else { SessionErrors.add(actionRequest, "insufficient-privileges"); jspPage = PortletUtil.ACCT_MGMT_ACCOUNT_REMOVE_JSP; } writeActionLog(actionRequest, account.getMail().get(0), account.getDisplayName(), account.getAttribute("esuccEntity"), "Scheduled account removal for " + df.format(date)); actionResponse.setRenderParameter("jspPage", jspPage); }
From source file:net.sf.jasperreports.engine.fill.DefaultChartTheme.java
/** * Sets all the axis formatting options. This includes the colors and fonts to use on * the axis as well as the color to use when drawing the axis line. * * @param axis the axis to format// w w w. java2s . c o m * @param labelFont the font to use for the axis label * @param labelColor the color of the axis label * @param tickLabelFont the font to use for each tick mark value label * @param tickLabelColor the color of each tick mark value label * @param tickLabelMask formatting mask for the label. If the axis is a NumberAxis then * the mask should be <code>java.text.DecimalFormat</code> mask, and * if it is a DateAxis then the mask should be a * <code>java.text.SimpleDateFormat</code> mask. * @param verticalTickLabels flag to draw tick labels at 90 degrees * @param lineColor color to use when drawing the axis line and any tick marks */ protected void configureAxis(Axis axis, JRFont labelFont, Color labelColor, JRFont tickLabelFont, Color tickLabelColor, String tickLabelMask, Boolean verticalTickLabels, Color lineColor, boolean isRangeAxis, Comparable<?> axisMinValue, Comparable<?> axisMaxValue) { axis.setLabelFont(fontUtil.getAwtFont(getFont(labelFont), getLocale())); axis.setTickLabelFont(fontUtil.getAwtFont(getFont(tickLabelFont), getLocale())); if (labelColor != null) { axis.setLabelPaint(labelColor); } if (tickLabelColor != null) { axis.setTickLabelPaint(tickLabelColor); } if (lineColor != null) { axis.setAxisLinePaint(lineColor); axis.setTickMarkPaint(lineColor); } TimeZone timeZone = chartContext.getTimeZone(); if (axis instanceof DateAxis && timeZone != null) { // used when no mask is set ((DateAxis) axis).setTimeZone(timeZone); } // FIXME use locale for formats if (tickLabelMask != null) { if (axis instanceof NumberAxis) { NumberFormat fmt = NumberFormat.getInstance(getLocale()); if (fmt instanceof DecimalFormat) { ((DecimalFormat) fmt).applyPattern(tickLabelMask); } ((NumberAxis) axis).setNumberFormatOverride(fmt); } else if (axis instanceof DateAxis) { DateFormat fmt; if (tickLabelMask.equals("SHORT") || tickLabelMask.equals("DateFormat.SHORT")) { fmt = DateFormat.getDateInstance(DateFormat.SHORT, getLocale()); } else if (tickLabelMask.equals("MEDIUM") || tickLabelMask.equals("DateFormat.MEDIUM")) { fmt = DateFormat.getDateInstance(DateFormat.MEDIUM, getLocale()); } else if (tickLabelMask.equals("LONG") || tickLabelMask.equals("DateFormat.LONG")) { fmt = DateFormat.getDateInstance(DateFormat.LONG, getLocale()); } else if (tickLabelMask.equals("FULL") || tickLabelMask.equals("DateFormat.FULL")) { fmt = DateFormat.getDateInstance(DateFormat.FULL, getLocale()); } else { fmt = new SimpleDateFormat(tickLabelMask, getLocale()); } if (timeZone != null) { fmt.setTimeZone(timeZone); } ((DateAxis) axis).setDateFormatOverride(fmt); } // ignore mask for other axis types. } if (verticalTickLabels != null && axis instanceof ValueAxis) { ((ValueAxis) axis).setVerticalTickLabels(verticalTickLabels); } setAxisBounds(axis, isRangeAxis, axisMinValue, axisMaxValue); }
From source file:com.opensymphony.xwork2.validator.AnnotationValidationConfigurationBuilder.java
private Date parseDateString(String value, String format) { SimpleDateFormat d0 = null;/*from w ww . j a v a 2s. 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:DDTDate.java
/** * Creates the output the user indicated in the input (outputType component) subject to the requested style (outputStyle) component * @return/*from w ww .j a va2s . co m*/ */ private String createOutput() { String result = ""; try { // If needed, adjust the reference date by the number and type of units specified - as per the time zone if (getUnits() != 0) { //setReferenceDate(getReferenceDateAdjustedForTimeZone()); getReferenceDate().add(getDurationType(), getUnits()); } // Create date formatters to be used for all varieties - the corresponding date variables are always set for convenience purposes DateFormat shortFormatter = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat mediumFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM); DateFormat longFormatter = DateFormat.getDateInstance(DateFormat.LONG); DateFormat fullFormatter = DateFormat.getDateInstance(DateFormat.FULL); // Build the specific formatter specified DateFormat formatter = null; switch (getOutputStyle().toLowerCase()) { case "medium": { formatter = mediumFormatter; break; } case "long": { formatter = longFormatter; break; } case "full": { formatter = fullFormatter; break; } default: formatter = shortFormatter; } // output style switch // construct the specified result - one at a time MutableDateTime theReferenceDate = getReferenceDate(); //getReferenceDateAdjustedForTimeZone(); switch (getOutputType().toLowerCase()) { case "date": { result = formatter.format(theReferenceDate.toDate()); break; } case "time": { switch (getOutputStyle().toLowerCase()) { case "short": { result = theReferenceDate.toString("hh:mm:ss"); break; } default: result = theReferenceDate.toString("hh:mm:ss.SSS"); } break; } // separate time components case "hour": case "minute": case "second": case "hour24": { String tmp = theReferenceDate.toString("hh:mm:ss"); if (tmp.toString().contains(":")) { String[] hms = split(tmp.toString(), ":"); if (hms.length > 2) { switch (getOutputType().toLowerCase()) { case "hour": { // Hour - '12' result = hms[0]; break; } case "minute": { // Minutes - '34' result = hms[1]; break; } case "second": { // Second - '56' result = hms[2]; break; } case "hour24": { // Hour - '23' result = theReferenceDate.toString("HH"); break; } default: result = hms[0]; } // switch for individual time component } // three parts of time components } // timestamp contains separator ":" break; } // Hours, Minutes, Seconds case "year": { switch (getOutputStyle().toLowerCase()) { case "short": { result = theReferenceDate.toString("yy"); break; } default: result = theReferenceDate.toString("yyyy"); } break; } case "month": { switch (getOutputStyle().toLowerCase()) { case "short": { result = theReferenceDate.toString("M"); break; } case "medium": { // padded with 0 result = theReferenceDate.toString("MM"); break; } case "long": { // short name 'Feb' result = theReferenceDate.toString("MMM"); break; } default: // Full name 'September' result = theReferenceDate.toString("MMMM"); } break; } case "day": { switch (getOutputStyle().toLowerCase()) { case "short": { result = theReferenceDate.toString("d"); break; } case "medium": { result = theReferenceDate.toString("dd"); break; } default: result = theReferenceDate.toString("dd"); } } case "doy": { result = theReferenceDate.toString("D"); break; } case "dow": { switch (getOutputStyle().toLowerCase()) { case "short": { result = theReferenceDate.toString("E"); break; } case "medium": { DateTime dt = new DateTime(theReferenceDate.toDate()); DateTime.Property dowDTP = dt.dayOfWeek(); result = dowDTP.getAsText(); break; } default: result = theReferenceDate.toString("E"); } break; } // day of week case "zone": { result = theReferenceDate.toString("zzz"); break; } case "era": { result = theReferenceDate.toString("G"); break; } case "ampm": { result = theReferenceDate.toString("a"); break; } default: { setException("Invalid Output Unit - cannot set output"); } // Create full date variables for the short, medium, long, full styles } // output type switch } // try constructing result catch (Exception e) { setException(e); } finally { return result; } }
From source file:org.pengyou.ooo.OpenDialog.java
private String formatList(String[] t) { String res = new String(); if (t[2] == "COLLECTION") { if (t[4].length() > SPACES_FILE - 4) res = t[4].substring(0, SPACES_FILE - 5) + ""; else/*from ww w. ja v a2 s. co m*/ res = t[4]; res = " " + res; } else { if (t[4].length() > SPACES_FILE - 2) res = t[4].substring(0, SPACES_FILE - 3) + ""; else res = t[4]; } while (res.length() < SPACES_FILE) res += " "; res += t[6]; while (res.length() < SPACES_AUTHOR) res += " "; Locale locale = Locale.FRENCH; Date date = null; String s = null; try { date = DateFormat.getDateTimeInstance().parse(t[5]); s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(date); res += s; while (res.length() < SPACES_CDATE) res += " "; } catch (ParseException e) { e.printStackTrace(); log.log(Level.DEBUG, e.getLocalizedMessage()); } date = null; s = null; try { date = DateFormat.getDateTimeInstance().parse(t[3]); s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(date); res += s; while (res.length() < SPACES_EDATE) res += " "; } catch (ParseException e) { e.printStackTrace(); log.log(Level.DEBUG, e.getLocalizedMessage()); } return res; }
From source file:com.appeaser.sublimepickerlibrary.recurrencepicker.RecurrenceOptionCreator.java
void initializeLayout() { int weekButtonUnselectedTextColor, weekButtonSelectedTextColor, weekButtonSelectedCircleColor; final TypedArray a = getContext().obtainStyledAttributes(R.styleable.RecurrenceOptionCreator); try {//from w w w. j a v a 2 s .c o m mHeaderBackgroundColor = a.getColor(R.styleable.RecurrenceOptionCreator_spHeaderBackground, 0); int endDateFormat = a.getInt(R.styleable.RecurrenceOptionCreator_spEndDateFormat, 1); mEndDateFormatter = DateFormat.getDateInstance( endDateFormat == 0 ? DateFormat.SHORT : DateFormat.MEDIUM, Locale.getDefault()); weekButtonUnselectedTextColor = a.getColor( R.styleable.RecurrenceOptionCreator_spWeekButtonUnselectedTextColor, SUtils.COLOR_ACCENT); weekButtonSelectedTextColor = a.getColor( R.styleable.RecurrenceOptionCreator_spWeekButtonSelectedTextColor, SUtils.COLOR_TEXT_PRIMARY_INVERSE); weekButtonSelectedCircleColor = a.getColor( R.styleable.RecurrenceOptionCreator_spWeekButtonSelectedCircleColor, SUtils.COLOR_ACCENT); } finally { a.recycle(); } mResources = getResources(); LayoutInflater.from(getContext()).inflate(R.layout.recurrence_picker, this); mRecurrencePicker = findViewById(R.id.recurrence_picker); mDateOnlyPicker = (RecurrenceEndDatePicker) findViewById(R.id.date_only_picker); mDateOnlyPicker.setVisibility(View.GONE); // OK/Cancel buttons mButtonLayout = (DecisionButtonLayout) findViewById(R.id.roc_decision_button_layout); mButtonLayout.applyOptions(mButtonLayoutCallback); SUtils.setViewBackground(findViewById(R.id.freqSpinnerHolder), mHeaderBackgroundColor, SUtils.CORNER_TOP_LEFT | SUtils.CORNER_TOP_RIGHT); /** EFrequency Spinner {Repeat daily, Repeat weekly, Repeat monthly, Repeat yearly} **/ mFreqSpinner = (Spinner) findViewById(R.id.freqSpinner); mFreqSpinner.setOnItemSelectedListener(this); ArrayAdapter<CharSequence> freqAdapter = ArrayAdapter.createFromResource(getContext(), R.array.recurrence_freq, R.layout.roc_freq_spinner_item); freqAdapter.setDropDownViewResource(R.layout.roc_spinner_dropdown_item); mFreqSpinner.setAdapter(freqAdapter); Drawable freqSpinnerBg = ContextCompat.getDrawable(getContext(), R.drawable.abc_spinner_mtrl_am_alpha); PorterDuffColorFilter cfFreqSpinner = new PorterDuffColorFilter(SUtils.COLOR_TEXT_PRIMARY_INVERSE, PorterDuff.Mode.SRC_IN); if (freqSpinnerBg != null) { freqSpinnerBg.setColorFilter(cfFreqSpinner); SUtils.setViewBackground(mFreqSpinner, freqSpinnerBg); } mInterval = (EditText) findViewById(R.id.interval); mInterval.addTextChangedListener(new minMaxTextWatcher(1, INTERVAL_DEFAULT, INTERVAL_MAX) { @Override void onChange(int v) { if (mIntervalResId != -1 && mInterval.getText().toString().length() > 0) { mModel.interval = v; updateIntervalText(); mInterval.requestLayout(); } } }); mIntervalPreText = (TextView) findViewById(R.id.intervalPreText); mIntervalPostText = (TextView) findViewById(R.id.intervalPostText); /** End Spinner {Forever, Until a date, For a number of events} **/ mEndNeverStr = mResources.getString(R.string.recurrence_end_continously); mEndDateLabel = mResources.getString(R.string.recurrence_end_date_label); mEndCountLabel = mResources.getString(R.string.recurrence_end_count_label); mEndSpinnerArray.add(mEndNeverStr); mEndSpinnerArray.add(mEndDateLabel); mEndSpinnerArray.add(mEndCountLabel); mEndSpinner = (Spinner) findViewById(R.id.endSpinner); mEndSpinner.setOnItemSelectedListener(this); mEndSpinnerAdapter = new EndSpinnerAdapter(getContext(), mEndSpinnerArray, R.layout.roc_end_spinner_item, R.id.spinner_item, R.layout.roc_spinner_dropdown_item); mEndSpinner.setAdapter(mEndSpinnerAdapter); mEndCount = (EditText) findViewById(R.id.endCount); mEndCount.addTextChangedListener(new minMaxTextWatcher(1, COUNT_DEFAULT, COUNT_MAX) { @Override void onChange(int v) { if (mModel.endCount != v) { mModel.endCount = v; updateEndCountText(); mEndCount.requestLayout(); } } }); mPostEndCount = (TextView) findViewById(R.id.postEndCount); mEndDateTextView = (TextView) findViewById(R.id.endDate); mEndDateTextView.setOnClickListener(this); SUtils.setViewBackground(mEndDateTextView, SUtils.createButtonBg(getContext(), SUtils.COLOR_BUTTON_NORMAL, SUtils.COLOR_CONTROL_HIGHLIGHT)); // set default & checked state colors WeekButton.setStateColors(weekButtonUnselectedTextColor, weekButtonSelectedTextColor); // AOSP code handled this differently. It has been refactored to // let Android decide if we have enough space to show // all seven 'WeekButtons' inline. In this case, 'mWeekGroup2' // will be null (see @layout-w460dp/week_buttons). mWeekGroup = (LinearLayout) findViewById(R.id.weekGroup); mWeekGroup2 = (LinearLayout) findViewById(R.id.weekGroup2); // Only non-null when available width is < 460dp // Used only for positioning 'WeekButtons' in two rows // of 4 & 3. View eighthWeekDay = findViewById(R.id.week_day_8); if (eighthWeekDay != null) eighthWeekDay.setVisibility(View.INVISIBLE); // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7 //String[] dayOfWeekString = new DateFormatSymbols().getWeekdays(); mMonthRepeatByDayOfWeekStrs = new String[7][]; // from Time.SUNDAY as 0 through Time.SATURDAY as 6 mMonthRepeatByDayOfWeekStrs[0] = mResources.getStringArray(R.array.repeat_by_nth_sun); mMonthRepeatByDayOfWeekStrs[1] = mResources.getStringArray(R.array.repeat_by_nth_mon); mMonthRepeatByDayOfWeekStrs[2] = mResources.getStringArray(R.array.repeat_by_nth_tues); mMonthRepeatByDayOfWeekStrs[3] = mResources.getStringArray(R.array.repeat_by_nth_wed); mMonthRepeatByDayOfWeekStrs[4] = mResources.getStringArray(R.array.repeat_by_nth_thurs); mMonthRepeatByDayOfWeekStrs[5] = mResources.getStringArray(R.array.repeat_by_nth_fri); mMonthRepeatByDayOfWeekStrs[6] = mResources.getStringArray(R.array.repeat_by_nth_sat); // In Time.java day of week order e.g. Sun = 0 int idx = RecurrenceUtils.getFirstDayOfWeek(); // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7 String[] dayOfWeekString = new DateFormatSymbols().getShortWeekdays(); // CheckableDrawable's width & height int expandedWidthHeight = mResources.getDimensionPixelSize(R.dimen.week_button_state_on_circle_size); WeekButton[] tempWeekButtons = new WeekButton[7]; tempWeekButtons[0] = (WeekButton) findViewById(R.id.week_day_1); tempWeekButtons[1] = (WeekButton) findViewById(R.id.week_day_2); tempWeekButtons[2] = (WeekButton) findViewById(R.id.week_day_3); tempWeekButtons[3] = (WeekButton) findViewById(R.id.week_day_4); tempWeekButtons[4] = (WeekButton) findViewById(R.id.week_day_5); tempWeekButtons[5] = (WeekButton) findViewById(R.id.week_day_6); tempWeekButtons[6] = (WeekButton) findViewById(R.id.week_day_7); for (int i = 0; i < mWeekByDayButtons.length; i++) { mWeekByDayButtons[idx] = tempWeekButtons[i]; SUtils.setViewBackground(mWeekByDayButtons[idx], new CheckableDrawable(weekButtonSelectedCircleColor, false, expandedWidthHeight)); mWeekByDayButtons[idx].setTextColor(weekButtonUnselectedTextColor); mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setOnCheckedChangeListener(this); if (++idx >= 7) { idx = 0; } } mMonthRepeatByRadioGroup = (RadioGroup) findViewById(R.id.monthGroup); mMonthRepeatByRadioGroup.setOnCheckedChangeListener(this); mRepeatMonthlyByNthDayOfWeek = (RadioButton) findViewById(R.id.repeatMonthlyByNthDayOfTheWeek); mRepeatMonthlyByNthDayOfMonth = (RadioButton) findViewById(R.id.repeatMonthlyByNthDayOfMonth); }
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 ww w . j a v a2 s. 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.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/*w w w .j a v a 2s . 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.hoteia.qalingo.core.web.mvc.factory.impl.BackofficeViewBeanFactoryImpl.java
/** * @throws Exception/*from ww w . j a v a 2s . co m*/ * */ public CatalogCategoryViewBean buildVirtualCatalogCategoryViewBean(final RequestData requestData, final CatalogCategoryVirtual catalogCategory, boolean fullPopulate) throws Exception { final MarketArea currentMarketArea = requestData.getMarketArea(); final CatalogCategoryViewBean catalogCategoryViewBean = new CatalogCategoryViewBean(); if (catalogCategory != null) { final String categoryCode = catalogCategory.getCode(); catalogCategoryViewBean.setName(catalogCategory.getBusinessName()); catalogCategoryViewBean.setCode(categoryCode); catalogCategoryViewBean.setDescription(catalogCategory.getDescription()); if (catalogCategory.getDefaultParentCatalogCategory() != null) { // TODO : Denis : fetch optim - cache : we reload entity to fetch the defaultParentCatalogCategory CatalogCategoryVirtual defaultParentCatalogCategory = catalogCategoryService .getVirtualCatalogCategoryById(catalogCategory.getDefaultParentCatalogCategory().getId()); catalogCategoryViewBean.setDefaultParentCategory( buildVirtualCatalogCategoryViewBean(requestData, defaultParentCatalogCategory, false)); } DateFormat dateFormat = requestUtil.getFormatDate(requestData, DateFormat.MEDIUM, DateFormat.MEDIUM); Date createdDate = catalogCategory.getDateCreate(); if (createdDate != null) { catalogCategoryViewBean.setCreatedDate(dateFormat.format(createdDate)); } else { catalogCategoryViewBean.setCreatedDate(Constants.NOT_AVAILABLE); } Date updatedDate = catalogCategory.getDateUpdate(); if (updatedDate != null) { catalogCategoryViewBean.setUpdatedDate(dateFormat.format(updatedDate)); } else { catalogCategoryViewBean.setUpdatedDate(Constants.NOT_AVAILABLE); } if (fullPopulate) { if (catalogCategory.getCatalogCategories() != null) { catalogCategoryViewBean.setSubCategories(buildVirtualCatalogCategoryViewBeans(requestData, new ArrayList<CatalogCategoryVirtual>(catalogCategory.getCatalogCategories()), fullPopulate)); } List<CatalogCategoryVirtualAttribute> globalAttributes = catalogCategory .getCatalogCategoryGlobalAttributes(); for (Iterator<CatalogCategoryVirtualAttribute> iterator = globalAttributes.iterator(); iterator .hasNext();) { CatalogCategoryVirtualAttribute catalogCategoryVirtualAttribute = (CatalogCategoryVirtualAttribute) iterator .next(); catalogCategoryViewBean.getGlobalAttributes().put( catalogCategoryVirtualAttribute.getAttributeDefinition().getCode(), catalogCategoryVirtualAttribute.getValueAsString()); } List<CatalogCategoryVirtualAttribute> marketAreaAttributes = catalogCategory .getCatalogCategoryMarketAreaAttributes(currentMarketArea.getId()); for (Iterator<CatalogCategoryVirtualAttribute> iterator = marketAreaAttributes.iterator(); iterator .hasNext();) { CatalogCategoryVirtualAttribute catalogCategoryVirtualAttribute = (CatalogCategoryVirtualAttribute) iterator .next(); catalogCategoryViewBean.getMarketAreaAttributes().put( catalogCategoryVirtualAttribute.getAttributeDefinition().getCode(), catalogCategoryVirtualAttribute.getValueAsString()); } List<ProductMarketingViewBean> productMarketingViewBeans = buildProductMarketingViewBeans( requestData, catalogCategory, new ArrayList<ProductMarketing>(catalogCategory.getProductMarketings()), true); catalogCategoryViewBean.setProductMarketings(productMarketingViewBeans); int countProduct = catalogCategory.getProductMarketings().size(); for (Iterator<CatalogCategoryViewBean> iterator = catalogCategoryViewBean.getSubCategories() .iterator(); iterator.hasNext();) { CatalogCategoryViewBean subCategoryViewBean = (CatalogCategoryViewBean) iterator.next(); countProduct = countProduct + subCategoryViewBean.getCountProduct(); } catalogCategoryViewBean.setCountProduct(countProduct); List<Asset> assets = catalogCategory.getAssetsIsGlobal(); for (Iterator<Asset> iterator = assets.iterator(); iterator.hasNext();) { Asset asset = (Asset) iterator.next(); catalogCategoryViewBean.getAssets().add(buildAssetViewBean(requestData, asset)); } } catalogCategoryViewBean.setDetailsUrl(backofficeUrlService.generateUrl(BoUrls.VIRTUAL_CATEGORY_DETAILS, requestData, catalogCategory)); catalogCategoryViewBean.setEditUrl( backofficeUrlService.generateUrl(BoUrls.VIRTUAL_CATEGORY_EDIT, requestData, catalogCategory)); } return catalogCategoryViewBean; }