List of usage examples for java.text DateFormat SHORT
int SHORT
To view the source code for java.text DateFormat SHORT.
Click Source Link
From source file:org.lingcloud.molva.ocl.util.GenericTypeValidator.java
/** * <p>/*w w w . j a v a 2s . c om*/ * * Checks if the field is a valid date. The <code>Locale</code> is used with * <code>java.text.DateFormat</code>. The setLenient method is set to * <code>false</code> for all. * </p> * * @param value * The value validation is being performed on. * @param locale * The Locale to use to parse the date (system default if null) * @return the converted Date value. */ public static Date formatDate(String value, Locale locale) { Date date = null; if (value == null) { return null; } try { DateFormat formatter = null; if (locale != null) { formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale); } else { formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); } formatter.setLenient(false); date = formatter.parse(value); } catch (ParseException e) { // Bad date so return null if (log.isDebugEnabled()) { log.debug("Date parse failed value=[" + value + "], " + "locale=[" + locale + "] " + e); } } return date; }
From source file:org.totschnig.myexpenses.dialog.TransactionDetailFragment.java
public void fillData(Transaction o) { final FragmentActivity ctx = getActivity(); mLayout.findViewById(R.id.progress).setVisibility(View.GONE); mTransaction = o;/*from ww w . ja v a2 s . c o m*/ if (mTransaction == null) { TextView error = (TextView) mLayout.findViewById(R.id.error); error.setVisibility(View.VISIBLE); error.setText(R.string.transaction_deleted); return; } boolean doShowPicture = false; if (mTransaction.getPictureUri() != null) { doShowPicture = true; if (mTransaction.getPictureUri().getScheme().equals("file")) { if (!new File(mTransaction.getPictureUri().getPath()).exists()) { Toast.makeText(getActivity(), R.string.image_deleted, Toast.LENGTH_SHORT).show(); doShowPicture = false; } } } AlertDialog dlg = (AlertDialog) getDialog(); if (dlg != null) { Button btn = dlg.getButton(AlertDialog.BUTTON_POSITIVE); if (btn != null) { if (mTransaction.crStatus != Transaction.CrStatus.VOID) { btn.setEnabled(true); } else { btn.setVisibility(View.GONE); } } btn = dlg.getButton(AlertDialog.BUTTON_NEUTRAL); if (btn != null) { btn.setVisibility(doShowPicture ? View.VISIBLE : View.GONE); } } mLayout.findViewById(R.id.Table).setVisibility(View.VISIBLE); int title; boolean type = mTransaction.getAmount().getAmountMinor() > 0 ? ExpenseEdit.INCOME : ExpenseEdit.EXPENSE; if (mTransaction instanceof SplitTransaction) { mLayout.findViewById(R.id.SplitContainer).setVisibility(View.VISIBLE); //TODO: refactor duplicated code with SplitPartList title = R.string.split_transaction; View emptyView = mLayout.findViewById(R.id.empty); ListView lv = (ListView) mLayout.findViewById(R.id.list); // Create an array to specify the fields we want to display in the list String[] from = new String[] { KEY_LABEL_MAIN, KEY_AMOUNT }; // and an array of the fields we want to bind those fields to int[] to = new int[] { R.id.category, R.id.amount }; // Now create a simple cursor adapter and set it to display mAdapter = new SplitPartAdapter(ctx, R.layout.split_part_row, null, from, to, 0, mTransaction.getAmount().getCurrency()); lv.setAdapter(mAdapter); lv.setEmptyView(emptyView); LoaderManager manager = getLoaderManager(); if (manager.getLoader(SPLIT_PART_CURSOR) != null && !manager.getLoader(SPLIT_PART_CURSOR).isReset()) { manager.restartLoader(SPLIT_PART_CURSOR, null, this); } else { manager.initLoader(SPLIT_PART_CURSOR, null, this); } } else { if (mTransaction instanceof Transfer) { title = R.string.transfer; ((TextView) mLayout.findViewById(R.id.AccountLabel)).setText(R.string.transfer_from_account); ((TextView) mLayout.findViewById(R.id.CategoryLabel)).setText(R.string.transfer_to_account); } else { title = type ? R.string.income : R.string.expense; } } String amountText; String accountLabel = Account.getInstanceFromDb(mTransaction.accountId).label; if (mTransaction instanceof Transfer) { ((TextView) mLayout.findViewById(R.id.Account)).setText(type ? mTransaction.label : accountLabel); ((TextView) mLayout.findViewById(R.id.Category)).setText(type ? accountLabel : mTransaction.label); if (((Transfer) mTransaction).isSameCurrency()) { amountText = formatCurrencyAbs(mTransaction.getAmount()); } else { String self = formatCurrencyAbs(mTransaction.getAmount()); String other = formatCurrencyAbs(mTransaction.getTransferAmount()); amountText = type == ExpenseEdit.EXPENSE ? (self + " => " + other) : (other + " => " + self); } } else { ((TextView) mLayout.findViewById(R.id.Account)).setText(accountLabel); if ((mTransaction.getCatId() != null && mTransaction.getCatId() > 0)) { ((TextView) mLayout.findViewById(R.id.Category)).setText(mTransaction.label); } else { mLayout.findViewById(R.id.CategoryRow).setVisibility(View.GONE); } amountText = formatCurrencyAbs(mTransaction.getAmount()); } //noinspection SetTextI18n ((TextView) mLayout.findViewById(R.id.Date)) .setText(DateFormat.getDateInstance(DateFormat.FULL).format(mTransaction.getDate()) + " " + DateFormat.getTimeInstance(DateFormat.SHORT).format(mTransaction.getDate())); ((TextView) mLayout.findViewById(R.id.Amount)).setText(amountText); if (!mTransaction.comment.equals("")) { ((TextView) mLayout.findViewById(R.id.Comment)).setText(mTransaction.comment); } else { mLayout.findViewById(R.id.CommentRow).setVisibility(View.GONE); } if (!mTransaction.referenceNumber.equals("")) { ((TextView) mLayout.findViewById(R.id.Number)).setText(mTransaction.referenceNumber); } else { mLayout.findViewById(R.id.NumberRow).setVisibility(View.GONE); } if (!mTransaction.payee.equals("")) { ((TextView) mLayout.findViewById(R.id.Payee)).setText(mTransaction.payee); ((TextView) mLayout.findViewById(R.id.PayeeLabel)).setText(type ? R.string.payer : R.string.payee); } else { mLayout.findViewById(R.id.PayeeRow).setVisibility(View.GONE); } if (mTransaction.methodId != null) { ((TextView) mLayout.findViewById(R.id.Method)) .setText(PaymentMethod.getInstanceFromDb(mTransaction.methodId).getLabel()); } else { mLayout.findViewById(R.id.MethodRow).setVisibility(View.GONE); } if (Account.getInstanceFromDb(mTransaction.accountId).type.equals(AccountType.CASH)) { mLayout.findViewById(R.id.StatusRow).setVisibility(View.GONE); } else { TextView tv = (TextView) mLayout.findViewById(R.id.Status); tv.setBackgroundColor(mTransaction.crStatus.color); tv.setText(mTransaction.crStatus.toString()); } if (mTransaction.originTemplate == null) { mLayout.findViewById(R.id.PlannerRow).setVisibility(View.GONE); } else { ((TextView) mLayout.findViewById(R.id.Plan)) .setText(mTransaction.originTemplate.getPlan() == null ? getString(R.string.plan_event_deleted) : Plan.prettyTimeInfo(getActivity(), mTransaction.originTemplate.getPlan().rrule, mTransaction.originTemplate.getPlan().dtstart)); } dlg.setTitle(title); if (doShowPicture) { ImageView image = ((ImageView) dlg.getWindow().findViewById(android.R.id.icon)); image.setVisibility(View.VISIBLE); image.setScaleType(ImageView.ScaleType.CENTER_CROP); Picasso.with(ctx).load(mTransaction.getPictureUri()).fit().into(image); } }
From source file:com.appeligo.search.actions.account.BaseAccountAction.java
public void setEarliestSmsTime(String earliestSmsTime) { DateFormat format = SimpleDateFormat.getTimeInstance(DateFormat.SHORT); try {//from ww w. ja v a 2 s .c om this.earliestSmsTime = new Time(format.parse(earliestSmsTime).getTime()); } catch (ParseException e) { log.error("Format from account_macros.vm was wrong", e); } catch (Throwable t) { t.printStackTrace(); } }
From source file:com.drunkendev.confluence.plugins.attachments.PurgeAttachmentsJob.java
private void mailResultsHtml(Map<String, List<MailLogEntry>> mailEntries1, Date started, Date ended) throws MailException { String p = settingsManager.getGlobalSettings().getBaseUrl(); String subject = "Purged old attachments"; DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); for (Map.Entry<String, List<MailLogEntry>> n : mailEntries1.entrySet()) { List<MailLogEntry> entries = n.getValue(); Collections.sort(entries, new Comparator<MailLogEntry>() { @Override/*from w ww.j a va 2 s .co m*/ public int compare(MailLogEntry o1, MailLogEntry o2) { Attachment a1 = o1.getAttachment(); Attachment a2 = o2.getAttachment(); int comp = ObjectUtils.compare(a1.getSpace().getName(), a2.getSpace().getName()); if (comp != 0) return comp; comp = ObjectUtils.compare(a1.getDisplayTitle(), a2.getDisplayTitle()); if (comp != 0) return comp; return 0; } }); StringBuilder sb = new StringBuilder(); sb.append( "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en-US\" lang=\"en-US\">"); sb.append("<head>"); //sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />") sb.append("<title>").append(subject).append("</title>"); sb.append("<style type=\"text/css\">"); sb.append( "body { font-family: Helvetica, Arial, sans-serif; font-size: 10pt; width: 100%; color: #333; text-align: left; }"); sb.append("a { color: #326ca6; text-decoration: none; }"); sb.append("a:hover { color: #336ca6; text-decoration: underline; }"); sb.append("a:active { color: #326ca6; }"); sb.append("div.note { border: solid 1px #F0C000; padding: 5px; background-color: #FFFFCE; }"); sb.append("table { border-collapse: collapse; padding: 0; border: 0 none; }"); sb.append( "th, td { padding: 5px 7px; border: solid 1px #ddd; text-align: left; vertical-align: top; color: #333; margin: 0; }"); sb.append("th { background-color: #f0f0f0 }"); sb.append("tr.deleted td { background-color: #FFE7E7; /* border: solid 1px #DF9898; */ }"); sb.append("</style>"); sb.append("</head>"); sb.append("<body>"); sb.append("<p>"); sb.append("This message is to inform you that the following prior"); sb.append(" attachment versions have been removed from confluence"); sb.append(" in order to conserve space. Current versions have not"); sb.append(" been deleted."); sb.append("</p>"); sb.append("<p>"); sb.append("Versions deleted are listed in the 'Versions Deleted'"); sb.append(" column. Rows shown in red have been processed, all"); sb.append(" other rows are in report-only mode."); sb.append("</p>"); sb.append("<p><strong>Started</strong>: ").append(df.format(started)) .append(" <strong>Ended</strong>: ").append(df.format(ended)).append("</p>"); long deleted = 0; long report = 0; for (MailLogEntry me : entries) { if (me.isReportOnly()) { report += me.getSpaceSaved(); } else { deleted += me.getSpaceSaved(); } } if (deleted > 0) { sb.append("<p>"); sb.append("A total of ").append(FileSize.format(deleted)).append(" space has been reclaimed."); sb.append("</p>"); } if (report > 0) { sb.append("<p>"); sb.append("A total of ").append(FileSize.format(report)) .append(" can be reclaimed from those in report mode."); sb.append("</p>"); } sb.append("<table>"); sb.append("<thead>"); sb.append("<tr>"); sb.append("<th>").append("Space").append("</th>"); sb.append("<th>").append("File Name").append("</th>"); sb.append("<th>").append("Space Freed").append("</th>"); //sb.append("<th>").append("Global Settings?").append("</th>"); sb.append("<th>").append("Version").append("</th>"); sb.append("<th>").append("Versions Deleted").append("</th>"); sb.append("</tr>"); sb.append("</thead>"); sb.append("<tbody>"); for (MailLogEntry me : entries) { Attachment a = me.getAttachment(); sb.append("<tr"); if (!me.isReportOnly()) { sb.append(" class=\"deleted\""); } sb.append(">"); sb.append("<td>"); sb.append("<a href=\"").append(p).append(a.getSpace().getUrlPath()).append("\">") .append(a.getSpace().getName()).append("</a>"); sb.append("</td>"); sb.append("<td>"); sb.append("<a href=\"").append(p).append(a.getContent().getAttachmentsUrlPath()).append("\">") .append(a.getDisplayTitle()).append("</a>"); sb.append("</td>"); sb.append("<td>").append(me.getSpaceSavedPretty()).append("</td>"); //sb.append("<td>").append(me.isGlobalSettings() ? "Yes" : "No").append("</td>"); sb.append("<td>").append(a.getAttachmentVersion()).append("</td>"); sb.append("<td>"); int c = 0; for (Integer dl : me.getDeletedVersions()) { if (c++ > 0) { sb.append(", "); } sb.append(dl); } sb.append("</td>"); sb.append("</tr>"); } sb.append("</tbody></table>"); sb.append("<p>"); sb.append("This message has been sent by the confluence mail tools"); sb.append(" - attachment purger."); sb.append("</p>"); sb.append("</body></html>"); ConfluenceMailQueueItem mail = new ConfluenceMailQueueItem(n.getKey(), subject, sb.toString(), ConfluenceMailQueueItem.MIME_TYPE_HTML); mailQueueTaskManager.getTaskQueue("mail").addTask(mail); LOG.debug("Mail Sent"); } }
From source file:org.freeplane.features.format.ScannerController.java
private Scanner createScanner(Locale loc) { final Scanner s = new Scanner(new String[] { loc.toString() }, false); s.setFirstChars("+-0123456789,."); final String tNumber = IFormattedObject.TYPE_NUMBER; final String tDate = IFormattedObject.TYPE_DATETIME; final DateFormat shortDateTimeFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, loc); if (shortDateTimeFormat instanceof SimpleDateFormat) { s.addParser(Parser.createParser(Parser.STYLE_DATE, tDate, ((SimpleDateFormat) shortDateTimeFormat).toPattern(), loc, "short datetime format")); }//from w w w . ja v a 2s . c o m final DateFormat shortDateFormat = SimpleDateFormat.getDateInstance(DateFormat.SHORT, loc); if (shortDateFormat instanceof SimpleDateFormat) { s.addParser(Parser.createParser(Parser.STYLE_DATE, tDate, ((SimpleDateFormat) shortDateFormat).toPattern(), loc, "short date format")); } s.addParser(Parser.createParser(Parser.STYLE_DECIMAL, tNumber, null, loc, "number format")); s.addParser( Parser.createParser(Parser.STYLE_ISODATE, tDate, null, loc, "ISO reader for date and date/time")); s.addParser(Parser.createParser(Parser.STYLE_NUMBERLITERAL, tNumber, null, loc, "support dot as decimal separator (if nothing else matches)")); return s; }
From source file:org.wings.session.PortletWingServlet.java
public final PortletSessionServlet getSessionServlet(HttpServletRequest request, HttpServletResponse response, boolean createSessionServlet) throws ServletException { // WingS-Portlet-Bridge: for the bridge we are using the portletSession to // seperate between the instances of one portlet through the portlet scope RenderRequest renderRequest = (RenderRequest) request.getAttribute(Const.REQUEST_ATTR_RENDER_REQUEST); if (renderRequest == null) { log.error("WingS-Portlet-Bridge: cant get RenderRequest because " + "the request attribute " + Const.REQUEST_ATTR_RENDER_REQUEST + " is null!"); }// w w w . j av a 2 s . c o m final PortletSession portletSession = renderRequest.getPortletSession(); // WingS-Portlet-Bridge: get the wings mainclass for current mode String lookupName = "SessionServlet"; lookupName = "SessionServlet:" + (String) renderRequest.getAttribute(Const.REQUEST_ATTR_WINGS_CLASS); log.info("WingS-Portlet-Bridge: loaded mainclass " + lookupName + " for PortletSessionServlet identificaction"); // it should be enough to synchronize on the http session object... synchronized (portletSession) { PortletSessionServlet sessionServlet = null; if (portletSession != null) { // WingS-Portlet-Bridge: changed for portlet scope sessionServlet = (PortletSessionServlet) portletSession.getAttribute(lookupName, PortletSession.PORTLET_SCOPE); } // Sanity check - maybe this is a stored/deserialized session servlet? if (sessionServlet != null && !sessionServlet.isValid()) { sessionServlet.destroy(); sessionServlet = null; log.debug("session servlet exists but is not valid"); } /* * we are only interested in a new session, if the response is * not null. If it is null, then we just called getSessionServlet() * for lookup purposes and are satisfied, if we don't get anything. */ if (sessionServlet == null) { if (createSessionServlet) { log.info("no session servlet, create new one"); sessionServlet = newSession(request, response); portletSession.setAttribute(lookupName, sessionServlet, PortletSession.PORTLET_SCOPE); } else { return null; } } if (log.isDebugEnabled()) { StringBuilder message = new StringBuilder().append("session id: ") .append(request.getRequestedSessionId()).append(", created at: ") .append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT) .format(new java.util.Date(portletSession.getCreationTime()))) .append(", identified via:") .append(request.isRequestedSessionIdFromCookie() ? " cookie" : "") .append(request.isRequestedSessionIdFromURL() ? " URL" : "").append(", expiring after: ") .append(portletSession.getMaxInactiveInterval()).append("s "); log.debug(message.toString()); //log.debug("session valid " + request.isRequestedSessionIdValid()); //log.debug("session httpsession id " + httpSession.getId()); //log.debug("session httpsession new " + httpSession.isNew()); //log.debug("session last accessed at " + // new java.util.Date(httpSession.getLastAccessedTime())); //log.debug("session expiration timeout (s) " + // httpSession.getMaxInactiveInterval()); //log.debug("session contains wings session " + // (httpSession.getAttribute(lookupName) != null)); } sessionServlet.getSession().getExternalizeManager().setResponse(response); /* Handling of the requests character encoding. * -------------------------------------------- * The following block is needed for a correct handling of * non-ISO-8859-1 data: * * Using LocaleCharacterSet and/or charset.properties we can * advise the client to use i.e. UTF-8 as character encoding. * Once told the browser consequently also encodes his requests * in the choosen characterset of the sings session. This is * achieved by adding the HTML code * <meta http-equiv="Content-Type" content="text/html;charset="<charset>"> * to the generated pages. * * If the user hasn't overridden the encoding in their browser, * then all form data (e.g. mueller) is submitted with data encoded * like m%C3%BCller because byte pair C3 BC is how the german * u-umlaut is represented in UTF-8. If the form is * iso-8859-1 encoded then you get m%FCller, because byte FC is * how it is presented in iso-8859-1. * * So the browser behaves correctly by sending his form input * correctly encoded in the advised character encoding. The issue * is that the servlet container is typically unable to determine * the correct encoding of this form data. By proposal the browser * should als declare the used character encoding for his data. * But actual browsers omit this information and hence the servlet * container is unable to guess the right encoding (Tomcat actually * thenalways guesses ISO 8859-1). This results in totally * scrumbled up data for all non ISO-8859-1 character encodings. * With the block below we tell the servlet container about the * character encoding we expect in the browsers request and hence * the servlet container can do the correct decoding. * This has to be done at very first, otherwise the servlet * container will ignore this setting. */ if ((request.getCharacterEncoding() == null)) { // was servlet container able to identify encoding? try { String sessionCharacterEncoding = sessionServlet.getSession().getCharacterEncoding(); // We know better about the used character encoding than tomcat log.debug("Advising servlet container to interpret request as " + sessionCharacterEncoding); request.setCharacterEncoding(sessionCharacterEncoding); } catch (UnsupportedEncodingException e) { log.warn("Problem on applying current session character encoding", e); } } return sessionServlet; } }
From source file:com.appeligo.search.actions.account.BaseAccountAction.java
public String getLatestSmsTime() { if (latestSmsTime == null) { return "8:00 PM"; }/*www . j a va 2s . c o m*/ DateFormat format = SimpleDateFormat.getTimeInstance(DateFormat.SHORT); return format.format(latestSmsTime); }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Create a Message List./*from w w w.j a v a 2 s . 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:com.ehret.mixit.fragment.PeopleDetailFragment.java
private void addPeopleSession(Member membre) { //On recupere aussi la liste des sessions de l'utilisateur List<Talk> conferences = ConferenceFacade.getInstance().getSessionMembre(membre, getActivity()); //On vide les lments sessionLayout.removeAllViews();//from w w w.j a va2 s. co m //On affiche les liens que si on a recuperer des choses if (conferences != null && !conferences.isEmpty()) { //On ajoute un table layout TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT); TableLayout tableLayout = new TableLayout(getActivity().getBaseContext()); tableLayout.setLayoutParams(tableParams); if (mInflater != null) { for (final Talk conf : conferences) { LinearLayout row = (LinearLayout) mInflater.inflate(R.layout.item_talk, tableLayout, false); row.setBackgroundResource(R.drawable.row_transparent_background); //Dans lequel nous allons ajouter le contenu que nous faisons mapp dans TextView horaire = (TextView) row.findViewById(R.id.talk_horaire); TextView talkImageText = (TextView) row.findViewById(R.id.talkImageText); TextView talkSalle = (TextView) row.findViewById(R.id.talk_salle); ImageView imageFavorite = (ImageView) row.findViewById(R.id.talk_image_favorite); ImageView langImage = (ImageView) row.findViewById(R.id.talk_image_language); ((TextView) row.findViewById(R.id.talk_name)).setText(conf.getTitle()); ((TextView) row.findViewById(R.id.talk_shortdesciptif)).setText(conf.getSummary().trim()); SimpleDateFormat sdf = new SimpleDateFormat("EEE"); if (conf.getStart() != null && conf.getEnd() != null) { horaire.setText(String.format(getResources().getString(R.string.periode), sdf.format(conf.getStart()), DateFormat.getTimeInstance(DateFormat.SHORT).format(conf.getStart()), DateFormat.getTimeInstance(DateFormat.SHORT).format(conf.getEnd()))); } else { horaire.setText(getResources().getString(R.string.pasdate)); } if (conf.getLang() != null && "ENGLISH".equals(conf.getLang())) { langImage.setImageDrawable(getResources().getDrawable(R.drawable.en)); } else { langImage.setImageDrawable(getResources().getDrawable(R.drawable.fr)); } Salle salle = Salle.INCONNU; if (conf instanceof Talk && Salle.INCONNU != Salle.getSalle(conf.getRoom())) { salle = Salle.getSalle(conf.getRoom()); } talkSalle.setText(String.format(getResources().getString(R.string.Salle), salle.getNom())); talkSalle.setBackgroundColor(getResources().getColor(salle.getColor())); if (conf instanceof Talk) { if ("Workshop".equals(((Talk) conf).getFormat())) { talkImageText.setText("Atelier"); } else { talkImageText.setText("Talk"); } } else { talkImageText.setText("L.Talk"); } row.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TypeFile typeFile; int page = 6; if (conf instanceof Talk) { if ("Workshop".equals(((Talk) conf).getFormat())) { typeFile = TypeFile.workshops; page = 4; } else { typeFile = TypeFile.talks; page = 3; } } else { typeFile = TypeFile.lightningtalks; } ((HomeActivity) getActivity()).changeCurrentFragment(SessionDetailFragment.newInstance( typeFile.toString(), conf.getIdSession(), page), typeFile.toString()); } }); //On regarde si la conf fait partie des favoris SharedPreferences settings = getActivity().getSharedPreferences(UIUtils.PREFS_FAVORITES_NAME, 0); boolean trouve = false; for (String key : settings.getAll().keySet()) { if (key.equals(String.valueOf(conf.getIdSession()))) { trouve = true; imageFavorite.setImageDrawable( getActivity().getResources().getDrawable(R.drawable.ic_action_important)); break; } } if (!trouve) { imageFavorite.setImageDrawable( getActivity().getResources().getDrawable(R.drawable.ic_action_not_important)); } tableLayout.addView(row); } } sessionLayout.addView(tableLayout); } else { titleSessions.getLayoutParams().height = 0; } }
From source file:mobisocial.bento.anyshare.util.DBHelper.java
public long storeLinkobjInDatabase(DbObj obj, Context context) { long localId = -1; // if replace entry, set ID long hash = obj.getHash(); Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_html); byte[] raw = BitmapHelper.bitmapToBytes(icon); String feedname = obj.getFeedName(); long parentid = 0; try {// w w w. j a va 2 s. c om if (obj.getJson().has("target_relation") && obj.getJson().getString("target_relation").equals("parent") && obj.getJson().has("target_hash")) { parentid = objIdForHash(obj.getJson().getLong("target_hash")); } } catch (JSONException e) { e.printStackTrace(); } DbUser usr = obj.getSender(); String sender = ""; if (usr != null) { sender = usr.getName(); } long timestamp = 0; String title = ""; try { timestamp = Long.parseLong(obj.getJson().getString("timestamp")); title = obj.getJson().getString("title"); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // add object long objId = (localId == -1) ? getNextId() : localId; String desc = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT) .format(new Date(timestamp)); if (!sender.isEmpty()) { desc += " by " + sender; } ContentValues cv = new ContentValues(); cv.put(ItemObject._ID, objId); cv.put(ItemObject.FEEDNAME, feedname); cv.put(ItemObject.TITLE, title); cv.put(ItemObject.DESC, desc); cv.put(ItemObject.TIMESTAMP, timestamp); cv.put(ItemObject.OBJHASH, hash); cv.put(ItemObject.PARENT_ID, parentid); if (raw != null) { cv.put(ItemObject.RAW, raw); } long newObjId = getWritableDatabase().insertOrThrow(ItemObject.TABLE, null, cv); return objId; }