List of usage examples for java.text DateFormat getDateTimeInstance
public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)
From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java
private TickUnits createTickUnits(Locale locale, TimeZone zone) { TickUnits units = new TickUnits(); // date formatters DateFormat f1 = new SimpleDateFormat("HH:mm:ss.SSS", locale); DateFormat f2 = new SimpleDateFormat("HH:mm:ss", locale); DateFormat f3 = DateFormat.getTimeInstance(DateFormat.SHORT, locale); DateFormat f4 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); DateFormat f5 = new SimpleDateFormat("d-MMM", locale); DateFormat f6 = new SimpleDateFormat("MMM-yyyy", locale); DateFormat f7 = new SimpleDateFormat("yyyy", locale); // NOTE: timezone not needed on date formatters because dates have already been converted // to the appropriate timezone by the respective RegularTimePeriod (Minute, Hour, Day, etc) // see:/* w w w. j av a 2 s . com*/ // http://www.jfree.org/jfreechart/api/gjdoc/org/jfree/data/time/Hour.html#Hour:Date:TimeZone // // If you do use a timezone on the formatters and the Jive TimeZone has been set to something // other than the system timezone, time specific charts will show incorrect values. /* f1.setTimeZone(zone); f2.setTimeZone(zone); f3.setTimeZone(zone); f4.setTimeZone(zone); f5.setTimeZone(zone); f6.setTimeZone(zone); f7.setTimeZone(zone); */ // milliseconds units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 1, f1)); units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 5, DateTickUnit.MILLISECOND, 1, f1)); units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 10, DateTickUnit.MILLISECOND, 1, f1)); units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 25, DateTickUnit.MILLISECOND, 5, f1)); units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 50, DateTickUnit.MILLISECOND, 10, f1)); units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 100, DateTickUnit.MILLISECOND, 10, f1)); units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 250, DateTickUnit.MILLISECOND, 10, f1)); units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 500, DateTickUnit.MILLISECOND, 50, f1)); // seconds units.add(new DateTickUnit(DateTickUnit.SECOND, 1, DateTickUnit.MILLISECOND, 50, f2)); units.add(new DateTickUnit(DateTickUnit.SECOND, 5, DateTickUnit.SECOND, 1, f2)); units.add(new DateTickUnit(DateTickUnit.SECOND, 10, DateTickUnit.SECOND, 1, f2)); units.add(new DateTickUnit(DateTickUnit.SECOND, 30, DateTickUnit.SECOND, 5, f2)); // minutes units.add(new DateTickUnit(DateTickUnit.MINUTE, 1, DateTickUnit.SECOND, 5, f3)); units.add(new DateTickUnit(DateTickUnit.MINUTE, 2, DateTickUnit.SECOND, 10, f3)); units.add(new DateTickUnit(DateTickUnit.MINUTE, 5, DateTickUnit.MINUTE, 1, f3)); units.add(new DateTickUnit(DateTickUnit.MINUTE, 10, DateTickUnit.MINUTE, 1, f3)); units.add(new DateTickUnit(DateTickUnit.MINUTE, 15, DateTickUnit.MINUTE, 5, f3)); units.add(new DateTickUnit(DateTickUnit.MINUTE, 20, DateTickUnit.MINUTE, 5, f3)); units.add(new DateTickUnit(DateTickUnit.MINUTE, 30, DateTickUnit.MINUTE, 5, f3)); // hours units.add(new DateTickUnit(DateTickUnit.HOUR, 1, DateTickUnit.MINUTE, 5, f3)); units.add(new DateTickUnit(DateTickUnit.HOUR, 2, DateTickUnit.MINUTE, 10, f3)); units.add(new DateTickUnit(DateTickUnit.HOUR, 4, DateTickUnit.MINUTE, 30, f3)); units.add(new DateTickUnit(DateTickUnit.HOUR, 6, DateTickUnit.HOUR, 1, f3)); units.add(new DateTickUnit(DateTickUnit.HOUR, 12, DateTickUnit.HOUR, 1, f4)); // days units.add(new DateTickUnit(DateTickUnit.DAY, 1, DateTickUnit.HOUR, 1, f5)); units.add(new DateTickUnit(DateTickUnit.DAY, 2, DateTickUnit.HOUR, 1, f5)); units.add(new DateTickUnit(DateTickUnit.DAY, 7, DateTickUnit.DAY, 1, f5)); units.add(new DateTickUnit(DateTickUnit.DAY, 15, DateTickUnit.DAY, 1, f5)); // months units.add(new DateTickUnit(DateTickUnit.MONTH, 1, DateTickUnit.DAY, 1, f6)); units.add(new DateTickUnit(DateTickUnit.MONTH, 2, DateTickUnit.DAY, 1, f6)); units.add(new DateTickUnit(DateTickUnit.MONTH, 3, DateTickUnit.MONTH, 1, f6)); units.add(new DateTickUnit(DateTickUnit.MONTH, 4, DateTickUnit.MONTH, 1, f6)); units.add(new DateTickUnit(DateTickUnit.MONTH, 6, DateTickUnit.MONTH, 1, f6)); // years units.add(new DateTickUnit(DateTickUnit.YEAR, 1, DateTickUnit.MONTH, 1, f7)); units.add(new DateTickUnit(DateTickUnit.YEAR, 2, DateTickUnit.MONTH, 3, f7)); units.add(new DateTickUnit(DateTickUnit.YEAR, 5, DateTickUnit.YEAR, 1, f7)); units.add(new DateTickUnit(DateTickUnit.YEAR, 10, DateTickUnit.YEAR, 1, f7)); units.add(new DateTickUnit(DateTickUnit.YEAR, 25, DateTickUnit.YEAR, 5, f7)); units.add(new DateTickUnit(DateTickUnit.YEAR, 50, DateTickUnit.YEAR, 10, f7)); units.add(new DateTickUnit(DateTickUnit.YEAR, 100, DateTickUnit.YEAR, 20, f7)); return units; }
From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java
/** * convert a localized value into its XML Schema datatype representation. If the value given cannot be parsed with * the locale in betterForm context the default locale (US) will be used as fallback. This can be convenient for * user-agents that do not pass a localized value back. * * @param value the value to convert//from w w w . jav a 2 s .co m * @return converted value that can be used to update instance data and match the Schema datatype lexical space * @throws java.text.ParseException in case the incoming string cannot be converted into a Schema datatype representation */ protected String delocaliseValue(String value) throws XFormsException, ParseException { if (value == null || value.equals("")) { return value; } if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N).equals("true")) { Locale locale = (Locale) getModel().getContainer().getProcessor().getContext() .get(XFormsProcessorImpl.BETTERFORM_LOCALE); XFormsProcessorImpl processor = this.model.getContainer().getProcessor(); if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":float") || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":decimal") || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":double")) { NumberFormat formatter = NumberFormat.getNumberInstance(locale); formatter.setMaximumFractionDigits(Double.SIZE); BigDecimal number; try { number = strictParse(value, locale); } catch (ParseException e) { LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale); return value; } catch (NumberFormatException nfe) { LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale); return value; } catch (InputMismatchException ime) { LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale); return value; } return number.toPlainString(); } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":date")) { DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); Date d = null; try { d = df.parse(value); } catch (ParseException e) { //try the default locale - else fail with ParseException df = new SimpleDateFormat("yyyy-MM-dd"); df.setLenient(false); d = df.parse(value); } df = new SimpleDateFormat("yyyy-MM-dd"); return df.format(d); } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":dateTime")) { String timezone = ""; // int position = ; if (value.contains("GMT")) { timezone = value.substring(value.indexOf("GMT") + 3, value.length()); } else if (value.contains("+")) { timezone = value.substring(value.indexOf("+"), value.length()); } else if (value.contains("Z")) { timezone = "Z"; } DateFormat sf = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale); Date d = null; try { d = sf.parse(value); } catch (ParseException e) { //try the default locale - else fail with ParseException sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); d = null; d = sf.parse(value); } sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String converted = sf.format(d); if (!timezone.equals("")) { return converted + timezone; } return converted; } } return value; }
From source file:me.ryanhamshire.PopulationDensity.DataStore.java
private void loadPlayerDataFromFile(String source, String dest) { //load player data into memory File playerFile = new File(playerDataFolderPath + File.separator + source); BufferedReader inStream = null; try {//from w w w.j av a 2s. com PlayerData playerData = new PlayerData(); inStream = new BufferedReader(new FileReader(playerFile.getAbsolutePath())); //first line is home region coordinates String homeRegionCoordinatesString = inStream.readLine(); //second line is date of last disconnection String lastDisconnectedString = inStream.readLine(); //third line is login priority String rankString = inStream.readLine(); //convert string representation of home coordinates to a proper object RegionCoordinates homeRegionCoordinates = new RegionCoordinates(homeRegionCoordinatesString); playerData.homeRegion = homeRegionCoordinates; //parse the last disconnect date string try { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ROOT); Date lastDisconnect = dateFormat.parse(lastDisconnectedString); playerData.lastDisconnect = lastDisconnect; } catch (Exception e) { playerData.lastDisconnect = Calendar.getInstance().getTime(); } //parse priority string if (rankString == null || rankString.isEmpty()) { playerData.loginPriority = 0; } else { try { playerData.loginPriority = Integer.parseInt(rankString); } catch (Exception e) { playerData.loginPriority = 0; } } //shove into memory for quick access this.playerNameToPlayerDataMap.put(dest, playerData); } //if the file isn't found, just don't do anything (probably a new-to-server player) catch (FileNotFoundException e) { return; } //if there's any problem with the file's content, log an error message and skip it catch (Exception e) { PopulationDensity.AddLogEntry("Unable to load data for player \"" + source + "\": " + e.getMessage()); } try { if (inStream != null) inStream.close(); } catch (IOException exception) { } }
From source file:org.nuxeo.ecm.platform.ui.web.tag.fn.Functions.java
/** * Return the date format to handle date and time taking the user's locale into account. * * @since 5.9.1// w w w . j a v a2s .co m */ public static String dateAndTimeFormatter(String formatLength) { // A map to store temporary available date format FacesContext context = FacesContext.getCurrentInstance(); Locale locale = context.getViewRoot().getLocale(); int style = DateFormat.SHORT; String styleString = mapOfDateLength.get(formatLength.toLowerCase()); boolean addCentury = false; if ("shortWithCentury".toLowerCase().equals(styleString)) { addCentury = true; } else { style = Integer.parseInt(styleString); } DateFormat aDateFormat = DateFormat.getDateTimeInstance(style, style, locale); // Cast to SimpleDateFormat to make "toPattern" method available SimpleDateFormat format = (SimpleDateFormat) aDateFormat; // return the date pattern String pattern = format.toPattern(); if (style == DateFormat.SHORT && addCentury) { // hack to add century on generated pattern pattern = YEAR_PATTERN.matcher(pattern).replaceAll("yyyy"); } return pattern; }
From source file:at.alladin.rmbt.android.loopmode.LoopModeTestFragment.java
public void updateUi() { if (holder != null && loopService != null) { LoopModeResults loopModeResults = loopService.getLoopModeResults(); holder.counterText.setText(holder.strings.loopModeString + ": " + loopModeResults.getNumberOfTests() + "/" + loopModeResults.getMaxTests() + (Status.RUNNING.equals(loopModeResults.getStatus()) ? "" : " (" + (loopService.isActive() ? holder.strings.waiting : holder.strings.finished) + ")")); if (Status.RUNNING.equals(loopModeResults.getStatus())) { loopModeResults = loopService.updateLoopModeResults(true); if (holder.lastTestText.getVisibility() == View.VISIBLE) { //loop mode just switched from idle/waiting state to test mode holder.lastTestText.setVisibility(View.GONE); holder.unimportantListAdapter = null; }/* w ww . j a v a2s .co m*/ if (holder.progressBar.getVisibility() == View.GONE) { holder.progressBar.setVisibility(View.VISIBLE); holder.progressText.setVisibility(View.VISIBLE); } } else { if (holder.lastTestText.getVisibility() != View.VISIBLE) { //loop mode just switched from test mode to idle/waiting state holder.unimportantListAdapter = null; holder.lastTestText.setVisibility(View.VISIBLE); } if (holder.progressBar.getVisibility() == View.VISIBLE) { holder.progressBar.setVisibility(View.GONE); holder.progressText.setVisibility(View.GONE); } } //update or initialize the "not so important list" (reason why it's at the bottom of the view) if (holder.unimportantListAdapter != null) { holder.unimportantListAdapter.notifyDataSetChanged(); } else { //different "not so important lists", depending on current test status (running/idle) if (Status.RUNNING.equals(loopModeResults.getStatus())) { //during test mode, show current test server and client's ip final List<DetailsListItem> list = new ArrayList<DetailsListItem>(); list.add(new ServerNameItem(getActivity(), loopModeResults)); list.add(new IpAddressItem(getActivity(), loopModeResults)); holder.unimportantListAdapter = new DetailsInfoListAdapter(getActivity(), list); holder.unimportantInfoList.setAdapter(holder.unimportantListAdapter); } else { //during idle mode, show current data usage, and both loop mode trigger statuses final List<DetailsListItem> list = new ArrayList<DetailsListItem>(); list.add(new TrafficUsageItem(getActivity(), loopModeResults)); list.add(new LoopModeTriggerItem(getActivity(), loopModeResults, TriggerType.MOVEMENT)); list.add(new LoopModeTriggerItem(getActivity(), loopModeResults, TriggerType.TIME)); holder.unimportantListAdapter = new DetailsInfoListAdapter(getActivity(), list); holder.unimportantInfoList.setAdapter(holder.unimportantListAdapter); } } //update last test status if (holder.lastTestText != null && holder.lastTestText.getVisibility() == View.VISIBLE) { String lastTestResult = ""; if (loopModeResults != null && loopModeResults.getLastTestResults() != null) { final Date d = new Date(loopModeResults.getLastTestResults().getLocalStartTimeStamp()); final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()); switch (loopModeResults.getLastTestResults().getStatus()) { case OK: lastTestResult = getString(R.string.loop_test_last_status_ok); break; case REJECTED: lastTestResult = getString(R.string.loop_test_last_status_rejected); break; default: lastTestResult = getString(R.string.loop_test_last_status_error); } lastTestResult += " (" + df.format(d) + ")"; } holder.lastTestText.setText(lastTestResult); } //update measurement list (up/down/ping/qos: last/current test + median values) if (holder.measurementFragment != null) { if (!holder.measurementFragment.hasResults()) { holder.measurementFragment.initList(loopService.getLoopModeResults()); } else { holder.measurementFragment.updateList(); } } //update info list (location, network, etc...) if (holder.infoFragment != null) { if (!holder.infoFragment.hasResults()) { holder.infoFragment.initList(infoCollector); } else { holder.infoFragment.updateList(); } } //loop service is active (= at least one test still has to be run or finished) if (loopService.isActive()) { int progress = 0; String progressText = ""; int maxProgress = 100; if (rmbtService != null) { if (Status.RUNNING.equals(loopModeResults.getStatus())) { //test currently running, test mode: intermediateResult = rmbtService.getIntermediateResult(intermediateResult); if (intermediateResult != null) { progress = (int) (RMBTTestFragment.calculateProgress(intermediateResult, rmbtService.getQoSTestProgress(), rmbtService.getQoSTestSize()) * 100d); progressText = holder.strings.testRunningString + ": " + progress + "%"; maxProgress = 100; } else if (rmbtService.isConnectionError()) { } else { } } else { //no test running, waiting mode: progress = loopModeResults.getNumberOfTests(); progressText = holder.strings.loopModeString + ": " + loopModeResults.getNumberOfTests() + "/" + loopModeResults.getMaxTests(); maxProgress = loopModeResults.getMaxTests(); } holder.progressBar.setMax(maxProgress); holder.progressBar.setProgress(progress); holder.progressText.setText(progressText); } else { //connecting? } } else { holder.cancelButton.setText(R.string.loop_test_quit); } } else if (holder != null) { //service (still) not bound... } }
From source file:org.cesecore.certificates.endentity.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 w w w . ja v a2s .c om 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, Float.valueOf(LATEST_VERSION)); } }
From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java
private DateFormat[] getDateFormats(Locale locale) { DateFormat dt1 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, locale); DateFormat dt2 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale); DateFormat dt3 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); DateFormat d1 = DateFormat.getDateInstance(DateFormat.SHORT, locale); DateFormat d2 = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); DateFormat d3 = DateFormat.getDateInstance(DateFormat.LONG, locale); DateFormat rfc3399 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); DateFormat[] dfs = { dt1, dt2, dt3, rfc3399, d1, d2, d3 }; //added RFC 3339 date format (XW-473) return dfs;//from w w w . j a v a2s. co m }
From source file:com.mg.framework.utils.MiscUtils.java
/** * ? ? ?? ? <code>DATE, DATETIME, TIME</code> * * @param value /* w ww.j a va 2s. co m*/ * @param metadata * @param locale * @return ? ? ? ? ? <code>value == null</code> * @throws NullPointerException ? <code>metadata == null</code> */ public static String getDateTextRepresentation(Date value, FieldMetadata metadata, Locale locale) { if (value == null || DateTimeUtils.isBoundDateValue(value)) return StringUtils.EMPTY_STRING; if (metadata == null) return value.toString(); DateFormat df; switch (metadata.getBuiltInType()) { case DATE: df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); break; case DATETIME: df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale); break; case TIME: df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale); break; default: return value.toString(); } return df.format(value); }
From source file:net.wastl.webmail.xml.XMLUserData.java
private String formatDate(long date) { TimeZone tz = TimeZone.getDefault(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.DEFAULT, getPreferredLocale()); df.setTimeZone(tz);/* w w w . j a va 2s .co m*/ String now = df.format(new Date(date)); return now; }
From source file:org.olat.core.commons.modules.bc.components.ListRenderer.java
/** * Render a single file or folder.//from w w w.j a va 2 s.co m * * @param f The file or folder to render * @param sb StringOutput to append generated html code */ private void appendRenderedFile(FolderComponent fc, VFSItem child, String currentContainerPath, StringOutput sb, URLBuilder ubu, Translator translator, boolean iframePostEnabled, boolean canContainerVersion, Map<Long, Identity> identityMap, int pos) { // asume full access unless security callback tells us something different. boolean canWrite = child.getParentContainer().canWrite() == VFSConstants.YES; boolean canDelete = child.getParentContainer().canDelete() == VFSConstants.YES; boolean isAbstract = (child instanceof AbstractVirtualContainer); Versions versions = null; if (canContainerVersion && child instanceof Versionable) { Versionable versionable = (Versionable) child; if (versionable.getVersions().isVersioned()) { versions = versionable.getVersions(); } } boolean canVersion = versions != null && !versions.getRevisions().isEmpty(); boolean canAddToEPortfolio = FolderConfig.isEPortfolioAddEnabled(); VFSLeaf leaf = null; if (child instanceof VFSLeaf) { leaf = (VFSLeaf) child; } boolean isContainer = (leaf == null); // if not a leaf, it must be a container... MetaInfo metaInfo = null; if (child instanceof OlatRelPathImpl) { metaInfo = MetaInfoFactory.createMetaInfoFor((OlatRelPathImpl) child); } boolean lockedForUser = MetaInfoHelper.isLocked(metaInfo, fc.getIdentityEnvironnement()); String name = child.getName(); String pathAndName = currentContainerPath; if (pathAndName.length() > 0 && !pathAndName.endsWith("/")) pathAndName = pathAndName + "/"; pathAndName = pathAndName + name; String type = FolderHelper.extractFileType(child.getName(), translator.getLocale()); // tr begin, set alternating bgcolor sb.append("<tr"); bgFlag = !bgFlag; if (bgFlag) { sb.append(" class=\"b_table_odd\""); } sb.append("><td class=\"b_first_child\">"); // add checkbox for actions if user can write or delete to this directory if (canWrite || canDelete) { sb.append("<input type=\"checkbox\" class=\"b_checkbox\" name=\""); sb.append(FileSelection.FORM_ID); sb.append("\" value=\""); sb.append(StringEscapeUtils.escapeHtml(name)); sb.append("\" />"); } // browse link pre sb.append("<a href=\""); if (isContainer) { // for directories... normal module URIs ubu.buildURI(sb, null, null, pathAndName, iframePostEnabled ? AJAXFlags.MODE_TOBGIFRAME : AJAXFlags.MODE_NORMAL); sb.append("\""); if (iframePostEnabled) { // add ajax iframe target StringOutput so = new StringOutput(); ubu.appendTarget(so); sb.append(so.toString()); } } else { // for files, add PARAM_SERV command ubu.buildURI(sb, new String[] { PARAM_SERV }, new String[] { "x" }, pathAndName, AJAXFlags.MODE_NORMAL); sb.append("\" target=\"_blank\""); } // icon css sb.append(" class=\"b_with_small_icon_left "); if (isContainer) sb.append(CSSHelper.CSS_CLASS_FILETYPE_FOLDER); else sb.append(CSSHelper.createFiletypeIconCssClassFor(name)); sb.append("\""); // file metadata if (metaInfo != null) { sb.append(" ext:qtip=\"<div class='b_ext_tooltip_wrapper b_briefcase_meta'>"); if (StringHelper.containsNonWhitespace(metaInfo.getTitle())) { sb.append("<h5>").append(Formatter.escapeDoubleQuotes(metaInfo.getTitle())).append("</h5>"); } if (StringHelper.containsNonWhitespace(metaInfo.getComment())) { sb.append(Formatter.escapeDoubleQuotes(metaInfo.getComment())); } if (metaInfo.isThumbnailAvailable()) { sb.append( "<div class='b_briefcase_preview' style='width:200px; height:200px; background-image:url("); ubu.buildURI(sb, new String[] { PARAM_SERV_THUMBNAIL }, new String[] { "x" }, pathAndName, AJAXFlags.MODE_NORMAL); sb.append("); background-repeat:no-repeat; background-position:50% 50%;'> </div>"); } String author = metaInfo.getAuthor(); if (StringHelper.containsNonWhitespace(author)) { sb.append("<p>").append(Formatter.escapeDoubleQuotes(translator.translate("mf.author"))); sb.append(": ").append(Formatter.escapeDoubleQuotes(author)).append("</p>"); } sb.append("</div>\""); } sb.append(">"); // name if (isAbstract) sb.append("<i>"); sb.append(name); if (isAbstract) sb.append("</i>"); sb.append("</a></td><td>"); // filesize if (!isContainer) { // append filesize sb.append(StringHelper.formatMemory(leaf.getSize())); } sb.append("</td><td>"); // type if (isContainer) { sb.append(translator.translate("Directory")); } else { if (type.equals(TYPE_FILE)) { sb.append(translator.translate("UnknownFile")); } else { sb.append(type.toUpperCase()); sb.append(" ").append(translator.translate(TYPE_FILE)); } } sb.append("</td><td>"); if (canContainerVersion) { if (canVersion) sb.append(versions.getRevisionNr()); sb.append("</td><td>"); } // last modified long lastModified = child.getLastModified(); if (lastModified != VFSConstants.UNDEFINED) sb.append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, translator.getLocale()) .format(new Date(lastModified))); else sb.append("-"); sb.append("</td><td>"); // locked if (metaInfo != null) { if (metaInfo.isLocked()) { Identity lockedBy = identityMap.get(metaInfo.getLockedBy()); if (lockedBy == null) { lockedBy = metaInfo.getLockedByIdentity(); if (lockedBy != null) { identityMap.put(lockedBy.getKey(), lockedBy); } } sb.append("<span class=\"b_small_icon b_briefcase_locked_file_icon\" ext:qtip=\""); if (lockedBy != null) { String firstName = lockedBy.getUser().getProperty(UserConstants.FIRSTNAME, translator.getLocale()); String lastName = lockedBy.getUser().getProperty(UserConstants.LASTNAME, translator.getLocale()); String date = ""; if (metaInfo.getLockedDate() != null) { date = fc.getDateTimeFormat().format(metaInfo.getLockedDate()); } sb.append(translator.translate("Locked", new String[] { firstName, lastName, date })); } sb.append("\"> </span>"); } } sb.append("</td><td class=\"b_last_child\">"); // Info link if (canWrite) { String nameLowerCase = name.toLowerCase(); if (!lockedForUser && (nameLowerCase.endsWith(".html") || nameLowerCase.endsWith(".htm") || nameLowerCase.endsWith(".txt") || nameLowerCase.endsWith(".css"))) { sb.append("<a href=\""); ubu.buildURI(sb, new String[] { PARAM_CONTENTEDITID }, new String[] { Integer.toString(pos) }, iframePostEnabled ? AJAXFlags.MODE_TOBGIFRAME : AJAXFlags.MODE_NORMAL); sb.append("\""); if (iframePostEnabled) { // add ajax iframe target StringOutput so = new StringOutput(); ubu.appendTarget(so); sb.append(so.toString()); } sb.append(" ext:qtip=\"").append(StringEscapeUtils.escapeHtml(translator.translate("editor"))); sb.append("\" class=\"b_small_icon b_briefcase_edit_file_icon\"></a>"); } boolean canMetaData = MetaInfoHelper.canMetaInfo(child); if (canMetaData) { if (lockedForUser) { // Metadata link disabled... sb.append("<span ext:qtip=\"") .append(StringEscapeUtils.escapeHtml(translator.translate("edit"))) .append("\" class=\" b_small_icon b_briefcase_edit_meta_dis_icon\"> </span>"); } else { // Metadata edit link... also handles rename for non-OlatRelPathImpls sb.append("<a href=\""); ubu.buildURI(sb, new String[] { PARAM_EDTID }, new String[] { Integer.toString(pos) }, iframePostEnabled ? AJAXFlags.MODE_TOBGIFRAME : AJAXFlags.MODE_NORMAL); sb.append("\""); if (iframePostEnabled) { // add ajax iframe target StringOutput so = new StringOutput(); ubu.appendTarget(so); sb.append(so.toString()); } sb.append(" ext:qtip=\"").append(StringEscapeUtils.escapeHtml(translator.translate("mf.edit"))) .append("\" class=\" b_small_icon b_briefcase_edit_meta_icon\"></a>"); } } // get a link for adding a file to ePortfolio, if file-owner is the current user if (canAddToEPortfolio && !isContainer) { if (metaInfo != null) { Identity author = metaInfo.getAuthorIdentity(); if (author != null && fc.getIdentityEnvironnement().getIdentity().getKey().equals(author.getKey())) { sb.append("<a href=\""); ubu.buildURI(sb, new String[] { PARAM_EPORT }, new String[] { Integer.toString(pos) }, iframePostEnabled ? AJAXFlags.MODE_TOBGIFRAME : AJAXFlags.MODE_NORMAL); sb.append("\""); if (iframePostEnabled) { // add ajax iframe target StringOutput so = new StringOutput(); ubu.appendTarget(so); sb.append(so.toString()); } sb.append(" ext:qtip=\"") .append(StringEscapeUtils.escapeHtml(translator.translate("eportfolio"))) .append("\" class=\" b_small_icon b_eportfolio_add\"></a>"); } } } if (canVersion) { // Versions link if (lockedForUser) { sb.append("<span ext:qtip=\"") .append(StringEscapeUtils.escapeHtml(translator.translate("versions"))) .append("\" class=\" b_small_icon b_briefcase_versions_dis_icon\"> </span>"); } else { sb.append("<a href=\""); ubu.buildURI(sb, new String[] { PARAM_VERID }, new String[] { Integer.toString(pos) }, iframePostEnabled ? AJAXFlags.MODE_TOBGIFRAME : AJAXFlags.MODE_NORMAL); sb.append("\""); if (iframePostEnabled) { // add ajax iframe target StringOutput so = new StringOutput(); ubu.appendTarget(so); sb.append(so.toString()); } sb.append(" ext:qtip=\"").append(StringEscapeUtils.escapeHtml(translator.translate("versions"))) .append("\" class=\" b_small_icon b_briefcase_versions_icon\"></a>"); } } } else { sb.append(" "); } sb.append("</td></tr>"); }