Java Code Examples for java.text.DateFormat

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project android-joedayz, under directory /Proyectos/Socrates/src/commons/.

Source file: Utilities.java

  20 
vote

public static Date stringToDate(String format,String date){
  DateFormat df=new SimpleDateFormat(format);
  try {
    return df.parse(date);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 2

From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/core/util/.

Source file: DateUtils.java

  19 
vote

/** 
 * Accepts strings in ISO 8601 format. This includes the following cases: <ul> <li>2009-08-15T12:50:03+01:00</li> <li>2009-08-15T12:50:03+0200</li> <li>2010-04-07T04:00:00Z</li> </ul>
 */
public static long parseIso8601Date(String dateStr) throws ParseException {
  String timezone=dateStr.substring(19);
  timezone=timezone.replaceAll(":","");
  if ("Z".equals(timezone)) {
    timezone="+0000";
  }
  String cleanedDateStr=dateStr.substring(0,19) + timezone;
  DateFormat f=cDateFormat.get().get();
  Date d=f.parse(cleanedDateStr);
  return d.getTime();
}
 

Example 3

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generator/model/.

Source file: AbstractGenerator.java

  18 
vote

public Map<String,Object> createArguments(){
  Map<String,Object> args=new TreeMap<String,Object>();
  Calendar calendar=Calendar.getInstance();
  args.put("year",calendar.get(Calendar.YEAR));
  DateFormat formatter=new SimpleDateFormat("MMMM d, yyyy, HH:mm:ss",Locale.US);
  args.put("datetime",formatter.format(new Date()));
  formatter=new SimpleDateFormat("MMMM d, yyyy",Locale.US);
  args.put("date",formatter.format(new Date()));
  return args;
}
 

Example 4

From project acceleo-modules, under directory /psm-gen-scala/plugins/com.github.sbegaudeau.acceleo.modules.psm.gen.scala/src/com/github/sbegaudeau/acceleo/modules/psm/gen/scala/services/.

Source file: CommonServices.java

  18 
vote

/** 
 * Get the date in a long format : January 12, 1952
 * @return String representing the long format date
 */
public static String genLongDate(){
  Date date=new Date();
  Locale locale=Locale.getDefault();
  DateFormat dateFormatShort=DateFormat.getDateInstance(DateFormat.LONG,locale);
  return dateFormatShort.format(date);
}
 

Example 5

From project addis, under directory /application/src/main/java/org/drugis/addis/util/jaxb/.

Source file: JAXBConvertor.java

  18 
vote

public static XMLGregorianCalendar dateToXml(Date date){
  DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
  String strDate=dateFormat.format(date);
  try {
    XMLGregorianCalendar xmlDate=DatatypeFactory.newInstance().newXMLGregorianCalendar(strDate);
    return xmlDate;
  }
 catch (  DatatypeConfigurationException e) {
    throw new RuntimeException(e);
  }
}
 

Example 6

From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/utils/request/.

Source file: RequestHelper.java

  18 
vote

private static void addTimeCondition(HttpServletRequest request,AdRequest adRequest){
  String strOffSet=request.getParameter(RequestHelper.offset);
  int offset=Integer.parseInt(strOffSet);
  offset=offset * 60000;
  String[] ids=TimeZone.getAvailableIDs(offset);
  Calendar temp=Calendar.getInstance();
  temp.setTimeZone(TimeZone.getTimeZone(ids[0]));
  DateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
  DateFormat timeFormat=new SimpleDateFormat("HHmm");
  adRequest.setTime(timeFormat.format(temp.getTime()));
  adRequest.setDate(dateFormat.format(temp.getTime()));
  adRequest.setDay(Day.getDayForJava(temp.get(Calendar.DAY_OF_WEEK)));
}
 

Example 7

From project agile, under directory /agile-api/src/main/java/org/headsupdev/agile/api/.

Source file: HeadsUpConfiguration.java

  18 
vote

public Date getBuildDate(){
  if (parsedBuildDate == null) {
    DateFormat formatter=new SimpleDateFormat("yyyy/MM/dd kk:mm");
    try {
      parsedBuildDate=formatter.parse(buildProperties.getProperty(BUILD_KEY_DATE));
    }
 catch (    ParseException e) {
      Manager.getLogger("HeadsUpConfiguration").error("Failed to parse build date",e);
      return new Date();
    }
  }
  return parsedBuildDate;
}
 

Example 8

From project Airports, under directory /src/com/nadmm/airports/utils/.

Source file: DataUtils.java

  18 
vote

public static String getTimeZoneAsString(TimeZone tz){
  Date now=new Date();
  String tzName=tz.getDisplayName(tz.inDaylightTime(now),TimeZone.SHORT);
  DateFormat tzFormat=new SimpleDateFormat("'(UTC'Z')'");
  tzFormat.setTimeZone(tz);
  return String.format("%s %s",tzName,tzFormat.format(now));
}
 

Example 9

From project alljoyn_java, under directory /samples/android/chat/src/org/alljoyn/bus/sample/chat/.

Source file: ChatApplication.java

  18 
vote

/** 
 * Whenever a user in the channel types a message, it needs to result in the history being updated with the nickname of the user originating the message and the message itself.  We keep a history list of a given  maximum size just for general principles.  This history list contains the local time at which the message was recived, the nickname of the  user who originated the message and the message itself.  We send a change notification to all observers indicating that the history has changed when we modify it.
 */
private void addHistoryItem(String nickname,String message){
  if (mHistory.size() == HISTORY_MAX) {
    mHistory.remove(0);
  }
  DateFormat dateFormat=new SimpleDateFormat("HH:mm");
  Date date=new Date();
  mHistory.add("[" + dateFormat.format(date) + "] ("+ nickname+ ") "+ message);
  notifyObservers(HISTORY_CHANGED_EVENT);
}
 

Example 10

From project android-wheel-datetime-picker, under directory /src/kankan/wheel/widget/adapters/.

Source file: DayArrayAdapter.java

  18 
vote

@Override public View getItem(int index,View cachedView,ViewGroup parent){
  int day=-daysCount / 2 + index;
  Calendar newCalendar=(Calendar)calendar.clone();
  newCalendar.roll(Calendar.DAY_OF_YEAR,day);
  View view=super.getItem(index,cachedView,parent);
  TextView monthday=(TextView)view.findViewById(R.id.time2_monthday);
  DateFormat format=new SimpleDateFormat("M ? dd ?");
  monthday.setText(format.format(newCalendar.getTime()));
  monthday.setTextColor(0xFF111111);
  return view;
}
 

Example 11

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/data/.

Source file: LocalMediaItem.java

  18 
vote

@Override public MediaDetails getDetails(){
  MediaDetails details=super.getDetails();
  details.addDetail(MediaDetails.INDEX_PATH,filePath);
  details.addDetail(MediaDetails.INDEX_TITLE,caption);
  DateFormat formater=DateFormat.getDateTimeInstance();
  details.addDetail(MediaDetails.INDEX_DATETIME,formater.format(new Date(dateTakenInMs)));
  if (GalleryUtils.isValidLocation(latitude,longitude)) {
    details.addDetail(MediaDetails.INDEX_LOCATION,new double[]{latitude,longitude});
  }
  if (fileSize > 0)   details.addDetail(MediaDetails.INDEX_SIZE,fileSize);
  return details;
}
 

Example 12

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/.

Source file: MainApp.java

  18 
vote

public Date getBuildDate(){
  Date result=null;
  try {
    DateFormat format=new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
    result=format.parse(versionProperties.getProperty("build_date"));
  }
 catch (  Exception ex) {
    log.debug(null,ex);
  }
  return result;
}
 

Example 13

From project aranea, under directory /admin-api/src/main/java/no/dusken/aranea/admin/editor/.

Source file: CalendarEditor.java

  18 
vote

@Override public String getAsText(){
  DateFormat formatter=new SimpleDateFormat(format,new Locale("no"));
  Calendar cal=(GregorianCalendar)getValue();
  if (cal != null) {
    return formatter.format(cal.getTime());
  }
 else {
    return null;
  }
}
 

Example 14

From project baseunits, under directory /src/main/java/jp/xet/baseunits/wicket/.

Source file: CalendarDateTextField.java

  18 
vote

/** 
 * Try to get datePattern from user session locale. If it is not possible, it will return {@link #DEFAULT_PATTERN}
 * @return CalendarDate pattern
 */
private static String defaultdatePattern(){
  Locale locale=Session.get().getLocale();
  if (locale != null) {
    DateFormat format=DateFormat.getDateInstance(DateFormat.SHORT,locale);
    if (format instanceof SimpleDateFormat) {
      return ((SimpleDateFormat)format).toPattern();
    }
  }
  return DEFAULT_PATTERN;
}
 

Example 15

From project bbb-java, under directory /src/main/java/org/mconf/bbb/api/.

Source file: Meeting.java

  18 
vote

private Date parseDate(String date){
  DateFormat dateFormat=new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy",Locale.CANADA);
  try {
    date=date.replace(date.substring(20,24),"");
    return dateFormat.parse(date);
  }
 catch (  Exception e) {
    return new Date();
  }
}
 

Example 16

From project bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/rest/.

Source file: BioportalRssModuleParser.java

  18 
vote

public Module parse(Element element){
  Namespace ns=Namespace.getNamespace(NS_URI);
  String date=element.getChildText("date",ns);
  DateFormat formatter=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
  try {
    return new DateModule(formatter.parse(date));
  }
 catch (  ParseException e) {
    throw new RuntimeException(e);
  }
}
 

Example 17

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/util/.

Source file: WalletUtils.java

  18 
vote

public static void writeKeys(final Writer out,final List<ECKey> keys) throws IOException {
  final DateFormat format=Iso8601Format.newDateTimeFormatT();
  out.write("# KEEP YOUR PRIVATE KEYS SAFE! Anyone who can read this can spend your Bitcoins.\n");
  for (  final ECKey key : keys) {
    out.write(key.getPrivateKeyEncoded(Constants.NETWORK_PARAMETERS).toString());
    if (key.getCreationTimeSeconds() != 0) {
      out.write(' ');
      out.write(format.format(new Date(key.getCreationTimeSeconds() * 1000)));
    }
    out.write('\n');
  }
}
 

Example 18

From project brix-cms, under directory /brix-core/src/main/java/org/brixcms/plugin/site/folder/.

Source file: ListFolderNodesTab.java

  18 
vote

@Override protected CharSequence convertToString(Object object){
  if (object == null) {
    return "";
  }
 else {
    DateFormat df=DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);
    return df.format((Date)object);
  }
}
 

Example 19

From project brix-cms-plugins, under directory /brix-hierarchical-node-plugin/src/main/java/brix/plugin/hierarchical/folder/.

Source file: ListFolderNodesTab.java

  18 
vote

@Override protected CharSequence convertToString(Object object){
  if (object == null) {
    return "";
  }
 else {
    DateFormat df=DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);
    return df.format((Date)object);
  }
}
 

Example 20

From project camel-persistence-part2, under directory /route-one-tx-manager/src/main/java/com/fusesource/examples/persistence/part2/.

Source file: ProcessIncidents.java

  18 
vote

public Incident extract(Exchange exchange) throws ParseException {
  Map<String,Object> model=(Map<String,Object>)exchange.getIn().getBody();
  String key="com.fusesource.examples.persistence.part2.model.Incident";
  DateFormat format=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  String currentDate=format.format(new Date());
  Date creationDate=format.parse(currentDate);
  Incident incident=(Incident)model.get(key);
  incident.setCreationDate(creationDate);
  incident.setCreationUser("file");
  return incident;
}
 

Example 21

From project cloudify, under directory /cloudify/package_build/gigaspaces/src/java/com/j_spaces/kernel/.

Source file: CloudifyVersion.java

  18 
vote

@Override public String getTag(){
  DateFormat dateFormat=DateFormat.getDateInstance(DateFormat.SHORT);
  String date=dateFormat.format(new Date());
  String tag="build" + BUILD_NUM + "_"+ date;
  return tag;
}
 

Example 22

From project commons-logging, under directory /src/test/org/apache/commons/logging/simple/.

Source file: DateTimeCustomConfigTestCase.java

  18 
vote

/** 
 * Checks that the date time format has been successfully set 
 */
protected void checkDecoratedDateTime(){
  assertEquals("Expected date format to be set","dd.mm.yyyy",((DecoratedSimpleLog)log).getDateTimeFormat());
  Date now=new Date();
  DateFormat formatter=((DecoratedSimpleLog)log).getDateTimeFormatter();
  SimpleDateFormat sampleFormatter=new SimpleDateFormat("dd.mm.yyyy");
  assertEquals("Date should be formatters to pattern dd.mm.yyyy",sampleFormatter.format(now),formatter.format(now));
}
 

Example 23

From project Cooking-to-Goal, under directory /lib/db-derby-10.7.1.1-bin/demo/programs/vtis/java/org/apache/derbyDemo/vtis/core/.

Source file: StringColumnVTI.java

  18 
vote

/** 
 * <p> Translate a date/time expression into the corresponding long number of milliseconds. </p>
 */
private long parseDateTime(String columnValue) throws SQLException {
  try {
    DateFormat df=DateFormat.getDateTimeInstance();
    java.util.Date rawDate=df.parse(columnValue);
    return rawDate.getTime();
  }
 catch (  ParseException e) {
    throw wrap(e);
  }
}
 

Example 24

From project cotopaxi-core, under directory /src/main/java/br/octahedron/util/.

Source file: DateUtil.java

  18 
vote

public static DateFormat dateFormat(String dateFormat,TimeZone timeZone){
  DateFormat formatter=formatters.get(dateFormat);
  if (formatter == null) {
    formatter=formatters.put(dateFormat,new SimpleDateFormat(dateFormat));
  }
  if (timeZone != null) {
    formatter.setTimeZone(timeZone);
  }
  return formatter;
}
 

Example 25

From project daily-money, under directory /dailymoney/src/com/bottleworks/dailymoney/ui/.

Source file: DetailListHelper.java

  18 
vote

public void reloadData(List<Detail> data){
  listViewData=data;
  ;
  listViewMapList.clear();
  DateFormat dateFormat=Contexts.instance().getDateFormat();
  for (  Detail det : listViewData) {
    Map<String,Object> row=toDetailMap(det,dateFormat);
    listViewMapList.add(row);
  }
  listViewAdapter.notifyDataSetChanged();
}
 

Example 26

From project des, under directory /daemon/lib/apache-log4j-1.2.16/src/main/java/org/apache/log4j/lf5/util/.

Source file: DateFormatManager.java

  18 
vote

public String format(Date date,String pattern){
  DateFormat formatter=null;
  formatter=getDateFormatInstance();
  if (formatter instanceof SimpleDateFormat) {
    formatter=(SimpleDateFormat)(formatter.clone());
    ((SimpleDateFormat)formatter).applyPattern(pattern);
  }
  return formatter.format(date);
}
 

Example 27

From project Diver, under directory /ca.uvic.chisel.javasketch/src/ca/uvic/chisel/javasketch/ui/internal/presentation/properties/.

Source file: GeneralDetailsPropertySection.java

  18 
vote

/** 
 * @param traceModel
 */
private void refreshTrace(ITrace traceModel){
  DateFormat format=DateFormat.getDateInstance(DateFormat.LONG);
  try {
    traceTime.setText(format.format(traceModel.getTraceTime()));
    analysisTime.setText(format.format(traceModel.getDataTime()));
    threadCount.setText(traceModel.getThreads().size() + "");
  }
 catch (  NullPointerException e) {
  }
  setTopControl(traceDetails);
}
 

Example 28

From project dmix, under directory /LastFM-java/src/examples/.

Source file: UserExample.java

  18 
vote

public static void main(String[] args){
  String key="b25b959554ed76058ac220b7b2e0a026";
  String user="JRoar";
  Chart<Artist> chart=User.getWeeklyArtistChart(user,10,key);
  DateFormat format=DateFormat.getDateInstance();
  String from=format.format(chart.getFrom());
  String to=format.format(chart.getTo());
  System.out.printf("Charts for %s for the week from %s to %s:%n",user,from,to);
  Collection<Artist> artists=chart.getEntries();
  for (  Artist artist : artists) {
    System.out.println(artist.getName());
  }
}
 

Example 29

From project dolphin, under directory /ipmsg/src/util/.

Source file: Util.java

  18 
vote

public static String format(final Date d,final String format){
  if (formats.get(format) != null) {
    if (popularDateFormat == null)     popularDateFormat=formats.get(format);
    return popularDateFormat.format(d);
  }
  DateFormat f=new SimpleDateFormat(format);
  formats.put(format,f);
  return f.format(d);
}
 

Example 30

From project dozer, under directory /core/src/test/java/org/dozer/converters/.

Source file: ConverterTest.java

  18 
vote

@Test public void testAccessors() throws Exception {
  DateFormat dateFormat=DateFormat.getDateInstance(DateFormat.LONG);
  CalendarConverter cc=new CalendarConverter(dateFormat);
  assertEquals(dateFormat,cc.getDateFormat());
  StringConverter sc=new StringConverter(null);
  DateFormatContainer dfc=new DateFormatContainer(null);
  sc.setDateFormatContainer(dfc);
  assertEquals(dfc,sc.getDateFormatContainer());
}
 

Example 31

From project E12Planner, under directory /src/com/neoware/europlanner/.

Source file: Player.java

  18 
vote

public Player(String pos,String number,String name,String dob){
  mPos=pos;
  mNumber=number;
  mName=name;
  DateFormat format=DateFormat.getDateInstance(DateFormat.LONG,Locale.US);
  try {
    mDateOfBirth=format.parse(dob);
  }
 catch (  ParseException pe) {
    Assert.fail(pe.getMessage());
  }
}
 

Example 32

From project EasySOA, under directory /samples/Talend-Airport-Service/SimpleProvider_0.1/SimpleProvider/src/routines/system/.

Source file: TypeConvert.java

  18 
vote

/** 
 * No.448 String.8 to Date
 */
public static Date String2Date(String o){
  if (o == null)   return null;
  DateFormat d=DateFormat.getDateInstance();
  try {
    return d.parse(o);
  }
 catch (  ParseException e) {
    throw ConvertTypeIllegalArgumentException.forInputArgument(o);
  }
}
 

Example 33

From project echo2, under directory /src/exampleapp/chatclient/src/java/echo2example/chatclient/.

Source file: Messages.java

  18 
vote

/** 
 * Formats a date with the specified locale.
 * @param date the date to be formatted.
 * @return a localized String representation of the date
 */
public static final String formatDateTimeMedium(Date date){
  Locale locale=ApplicationInstance.getActive().getLocale();
  DateFormat df=(DateFormat)DATE_FORMAT_MEDIUM_MAP.get(locale);
  if (df == null) {
    df=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM,locale);
    DATE_FORMAT_MEDIUM_MAP.put(locale,df);
  }
  return date == null ? null : df.format(date);
}
 

Example 34

From project echo3, under directory /src/server-java-examples/chatclient/src/java/chatclient/.

Source file: Messages.java

  18 
vote

/** 
 * Formats a date with the specified locale.
 * @param date the date to be formatted.
 * @return a localized String representation of the date
 */
public static final String formatDateTimeMedium(Date date){
  Locale locale=ApplicationInstance.getActive().getLocale();
  DateFormat df=(DateFormat)DATE_FORMAT_MEDIUM_MAP.get(locale);
  if (df == null) {
    df=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM,locale);
    DATE_FORMAT_MEDIUM_MAP.put(locale,df);
  }
  return date == null ? null : df.format(date);
}
 

Example 35

From project egit-github, under directory /org.eclipse.egit.github.core/src/org/eclipse/egit/github/core/client/.

Source file: DateFormatter.java

  18 
vote

public JsonElement serialize(Date date,Type type,JsonSerializationContext context){
  final DateFormat primary=formats[0];
  String formatted;
synchronized (primary) {
    formatted=primary.format(date);
  }
  return new JsonPrimitive(formatted);
}
 

Example 36

From project ehour, under directory /eHour-wicketweb/src/main/java/net/rrm/ehour/ui/common/converter/.

Source file: DateConverter.java

  18 
vote

public Object convertToObject(String value,Locale locale){
  DateFormat dateFormatter=initFormatter(dateStyle);
  try {
    return dateFormatter.parseObject(value);
  }
 catch (  ParseException e) {
    return null;
  }
}
 

Example 37

From project ElectricSleep, under directory /src/com/androsz/electricsleepbeta/app/.

Source file: SleepMonitoringService.java

  18 
vote

private Intent addExtrasToSaveSleepIntent(final Intent saveIntent){
  saveIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
  saveIntent.putExtra(EXTRA_ID,hashCode());
  saveIntent.putExtra(StartSleepReceiver.EXTRA_ALARM,alarmTriggerSensitivity);
  final DateFormat sdf=DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT,Locale.getDefault());
  DateFormat sdf2=DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT,Locale.getDefault());
  final Date now=new Date();
  if (dateStarted.getDate() == now.getDate()) {
    sdf2=DateFormat.getTimeInstance(DateFormat.SHORT);
  }
  saveIntent.putExtra(EXTRA_NAME,sdf.format(dateStarted) + " " + getText(R.string.to)+ " "+ sdf2.format(now));
  return saveIntent;
}
 

Example 38

From project AChartEngine, under directory /achartengine/src/org/achartengine/chart/.

Source file: TimeChart.java

  17 
vote

/** 
 * The graphical representation of the labels on the X axis.
 * @param xLabels the X labels values
 * @param xTextLabelLocations the X text label locations
 * @param canvas the canvas to paint to
 * @param paint the paint to be used for drawing
 * @param left the left value of the labels area
 * @param top the top value of the labels area
 * @param bottom the bottom value of the labels area
 * @param xPixelsPerUnit the amount of pixels per one unit in the chart labels
 * @param minX the minimum value on the X axis in the chart
 * @param maxX the maximum value on the X axis in the chart
 */
@Override protected void drawXLabels(List<Double> xLabels,Double[] xTextLabelLocations,Canvas canvas,Paint paint,int left,int top,int bottom,double xPixelsPerUnit,double minX,double maxX){
  int length=xLabels.size();
  if (length > 0) {
    boolean showLabels=mRenderer.isShowLabels();
    boolean showGridY=mRenderer.isShowGridY();
    DateFormat format=getDateFormat(xLabels.get(0),xLabels.get(length - 1));
    for (int i=0; i < length; i++) {
      long label=Math.round(xLabels.get(i));
      float xLabel=(float)(left + xPixelsPerUnit * (label - minX));
      if (showLabels) {
        paint.setColor(mRenderer.getXLabelsColor());
        canvas.drawLine(xLabel,bottom,xLabel,bottom + mRenderer.getLabelsTextSize() / 3,paint);
        drawText(canvas,format.format(new Date(label)),xLabel,bottom + mRenderer.getLabelsTextSize() * 4 / 3,paint,mRenderer.getXLabelsAngle());
      }
      if (showGridY) {
        paint.setColor(mRenderer.getGridColor());
        canvas.drawLine(xLabel,bottom,xLabel,top,paint);
      }
    }
  }
  drawXTextLabels(xTextLabelLocations,canvas,paint,true,left,top,bottom,xPixelsPerUnit,minX,maxX);
}
 

Example 39

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/ui/custom/.

Source file: PrettyTimeLabel.java

  17 
vote

protected void init(){
  final I18nManager i18nManager=ExplorerApp.get().getI18nManager();
  if (date != null) {
    DateFormat dateFormat=null;
    if (showTime) {
      dateFormat=new SimpleDateFormat(Constants.DEFAULT_TIME_FORMAT);
    }
 else {
      dateFormat=new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
    }
    if (labelTemplate != null) {
      super.setValue(MessageFormat.format(labelTemplate,new HumanTime(i18nManager).format(date)));
    }
 else {
      super.setValue(new HumanTime(i18nManager).format(date));
    }
    setDescription(dateFormat.format(date));
  }
 else {
    super.setValue(noDateCaption);
    setDescription(noDateCaption);
  }
}
 

Example 40

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.

Source file: DataManagement.java

  17 
vote

/** 
 * Based on http://www.vogella.de/articles/RSSFeed/article.html
 */
private String generateRSS(AppUserInfo user,BaseReportInfo report,List<DataRowInfo> reportDataRows) throws XMLStreamException, ObjectNotFoundException {
  XMLOutputFactory outputFactory=XMLOutputFactory.newInstance();
  StringWriter stringWriter=new StringWriter();
  XMLEventWriter eventWriter=outputFactory.createXMLEventWriter(stringWriter);
  XMLEventFactory eventFactory=XMLEventFactory.newInstance();
  XMLEvent end=eventFactory.createDTD("\n");
  StartDocument startDocument=eventFactory.createStartDocument();
  eventWriter.add(startDocument);
  eventWriter.add(end);
  StartElement rssStart=eventFactory.createStartElement("","","rss");
  eventWriter.add(rssStart);
  eventWriter.add(eventFactory.createAttribute("version","2.0"));
  eventWriter.add(end);
  eventWriter.add(eventFactory.createStartElement("","","channel"));
  eventWriter.add(end);
  this.createNode(eventWriter,"title",report.getModule().getModuleName() + " - " + report.getReportName());
  String reportLink="https://appserver.gtportalbase.com/agileBase/AppController.servlet?return=gui/display_application&set_table=" + report.getParentTable().getInternalTableName() + "&set_report="+ report.getInternalReportName();
  this.createNode(eventWriter,"link",reportLink);
  this.createNode(eventWriter,"description","A live data feed from www.agilebase.co.uk");
  DateFormat dateFormatter=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
  Date lastDataChangeDate=new Date(getLastCompanyDataChangeTime(user.getCompany()));
  this.createNode(eventWriter,"pubdate",dateFormatter.format(lastDataChangeDate));
  for (  DataRowInfo reportDataRow : reportDataRows) {
    eventWriter.add(eventFactory.createStartElement("","","item"));
    eventWriter.add(end);
    this.createNode(eventWriter,"title",buildEventTitle(report,reportDataRow,false));
    this.createNode(eventWriter,"description",reportDataRow.toString());
    String rowLink=reportLink + "&set_row_id=" + reportDataRow.getRowId();
    this.createNode(eventWriter,"link",rowLink);
    this.createNode(eventWriter,"guid",rowLink);
    eventWriter.add(end);
    eventWriter.add(eventFactory.createEndElement("","","item"));
    eventWriter.add(end);
  }
  eventWriter.add(eventFactory.createEndElement("","","channel"));
  eventWriter.add(end);
  eventWriter.add(eventFactory.createEndElement("","","rss"));
  eventWriter.add(end);
  return stringWriter.toString();
}
 

Example 41

From project ALP, under directory /workspace/alp-reporter-fe/src/main/java/com/lohika/alp/reporter/fe/controller/.

Source file: TestController.java

  17 
vote

@RequestMapping(method=RequestMethod.GET,value="/results/test",headers=Headers.ACCEPT_HTML) public String getTest(@CookieValue(value=ALPCookies.ALPfrom,required=false) String from,@CookieValue(value=ALPCookies.ALPtill,required=false) String till,@CookieValue(value=ALPCookies.ALPsuite,required=false) String suite,@CookieValue(value=ALPCookies.ALPtest,required=false) String section,Model model,@ModelAttribute("testFilter") TestFilter filter) throws ParseException {
  if (from != null) {
    DateFormat formatter=new SimpleDateFormat("yy-MM-dd");
    Date f=(Date)formatter.parse(from);
    filter.setFrom(f);
  }
  if (till != null) {
    DateFormat formatter=new SimpleDateFormat("yy-MM-dd");
    Date t=(Date)formatter.parse(till);
    filter.setTill(t);
  }
  if (suite != null)   filter.setSuite(suite);
  if (section != null)   filter.setTest(section);
  setDefaultPeriod(filter);
  List<Test> list=testDAO.listTest(filter);
  Map<Test,TestSummary> map=testDAO.getTestSummaryMap(list);
  model.addAttribute("tests",list);
  model.addAttribute("summaryMap",map);
  model.addAttribute("testFilter",filter);
  return "test";
}
 

Example 42

From project android-wheel, under directory /wheel-demo/src/kankan/wheel/demo/.

Source file: Time2Activity.java

  17 
vote

@Override public View getItem(int index,View cachedView,ViewGroup parent){
  int day=-daysCount / 2 + index;
  Calendar newCalendar=(Calendar)calendar.clone();
  newCalendar.roll(Calendar.DAY_OF_YEAR,day);
  View view=super.getItem(index,cachedView,parent);
  TextView weekday=(TextView)view.findViewById(R.id.time2_weekday);
  if (day == 0) {
    weekday.setText("");
  }
 else {
    DateFormat format=new SimpleDateFormat("EEE");
    weekday.setText(format.format(newCalendar.getTime()));
  }
  TextView monthday=(TextView)view.findViewById(R.id.time2_monthday);
  if (day == 0) {
    monthday.setText("Today");
    monthday.setTextColor(0xFF0000F0);
  }
 else {
    DateFormat format=new SimpleDateFormat("MMM d");
    monthday.setText(format.format(newCalendar.getTime()));
    monthday.setTextColor(0xFF111111);
  }
  return view;
}
 

Example 43

From project android-wheel_1, under directory /wheel-demo/src/kankan/wheel/demo/.

Source file: Time2Activity.java

  17 
vote

@Override public View getItem(int index,View cachedView,ViewGroup parent){
  int day=-daysCount / 2 + index;
  Calendar newCalendar=(Calendar)calendar.clone();
  newCalendar.roll(Calendar.DAY_OF_YEAR,day);
  View view=super.getItem(index,cachedView,parent);
  TextView weekday=(TextView)view.findViewById(R.id.time2_weekday);
  if (day == 0) {
    weekday.setText("");
  }
 else {
    DateFormat format=new SimpleDateFormat("EEE");
    weekday.setText(format.format(newCalendar.getTime()));
  }
  TextView monthday=(TextView)view.findViewById(R.id.time2_monthday);
  if (day == 0) {
    monthday.setText("Today");
    monthday.setTextColor(0xFF0000F0);
  }
 else {
    DateFormat format=new SimpleDateFormat("MMM d");
    monthday.setText(format.format(newCalendar.getTime()));
    monthday.setTextColor(0xFF111111);
  }
  return view;
}
 

Example 44

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: DownloadTask.java

  17 
vote

private long getMDTM(@NotNull File file) throws IOException {
  URLConnection c=getConnection();
  if ("FtpURLConnection".equals(c.getClass().getSimpleName())) {
    c.connect();
    try {
      Object ftpClient=ClassUtils.fieldValue(c,"ftp");
      ClassUtils.invokeNonPublic(ftpClient,"issueCommandCheck","MDTM " + file.getName());
      String result=(String)ClassUtils.invoke(ftpClient,"getResponseString");
      DateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
      df.setTimeZone(TimeZone.getTimeZone("GMT"));
      return df.parse(result.substring(4,result.length() - 1)).getTime();
    }
 catch (    Exception e) {
    }
  }
  return 0;
}
 

Example 45

From project asterisk-java, under directory /src/main/java/org/asteriskjava/util/.

Source file: DateUtil.java

  17 
vote

/** 
 * Converts a date in the form of "yy-MM-dd HH:mm:ss" to a Date object using the given time zone.
 * @param s date string in the form of "yy-MM-dd HH:mm:ss"
 * @param tz the timezone to use or <code>null</code> for the default time zone.
 * @return the corresponding Java date object or <code>null</code> if it is not parsable.
 */
public static Date parseDateTime(String s,TimeZone tz){
  DateFormat df;
  if (s == null) {
    return null;
  }
  df=new SimpleDateFormat(DATE_TIME_PATTERN);
  if (tz != null) {
    df.setTimeZone(tz);
  }
  try {
    return df.parse(s);
  }
 catch (  ParseException e) {
    return null;
  }
}
 

Example 46

From project AuthDB, under directory /src/main/java/com/craftfire/util/managers/.

Source file: LoggingManager.java

  17 
vote

public void stackTrace(String pluginName,StackTraceElement[] stack,String function,int linenumber,String classname,String file){
  advancedWarning("StackTrace Error",pluginName);
  plainWarning("Class name: " + classname,pluginName);
  plainWarning("File name: " + file,pluginName);
  plainWarning("Function name: " + function,pluginName);
  plainWarning("Error line: " + linenumber,pluginName);
  if (PluginManager.config.logging_enabled) {
    DateFormat LogFormat=new SimpleDateFormat(PluginManager.config.logformat);
    Date date=new Date();
    plainWarning("Check log file: " + PluginManager.plugin.getDataFolder() + "\\logs\\error\\"+ LogFormat.format(date)+ "-error.log",pluginName);
  }
 else {
    plainWarning("Enable logging in the config to get more information about the error.",pluginName);
  }
  logError("--------------------------- STACKTRACE ERROR ---------------------------",pluginName);
  logError("Class name: " + classname,pluginName);
  logError("File name: " + file,pluginName);
  logError("Function name: " + function,pluginName);
  logError("Error line: " + linenumber,pluginName);
  logError("--------------------------- STACKTRACE START ---------------------------",pluginName);
  for (int i=0; i < stack.length; i++) {
    logError(stack[i].toString());
  }
  logError("---------------------------- STACKTRACE END ----------------------------",pluginName);
}
 

Example 47

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/casemodule/.

Source file: Case.java

  17 
vote

/** 
 * Convert the Java timezone ID to the "formatted" string that can be accepted by the C/C++ code. Example: "America/New_York" converted to "EST5EDT", etc
 * @param timezoneID
 * @return
 */
public static String convertTimeZone(String timezoneID){
  String result="";
  TimeZone zone=TimeZone.getTimeZone(timezoneID);
  int offset=zone.getRawOffset() / 1000;
  int hour=offset / 3600;
  int min=(offset % 3600) / 60;
  DateFormat dfm=new SimpleDateFormat("z");
  dfm.setTimeZone(zone);
  boolean hasDaylight=zone.useDaylightTime();
  String first=dfm.format(new GregorianCalendar(2010,1,1).getTime()).substring(0,3);
  String second=dfm.format(new GregorianCalendar(2011,6,6).getTime()).substring(0,3);
  int mid=hour * -1;
  result=first + Integer.toString(mid);
  if (min != 0) {
    result=result + ":" + Integer.toString(min);
  }
  if (hasDaylight) {
    result=result + second;
  }
  return result;
}
 

Example 48

From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.

Source file: LoggingManager.java

  17 
vote

public void stackTrace(StackTraceElement[] stack,String function,int linenumber,String classname,String file){
  advancedWarning("StackTrace Error");
  plainWarning("Class name: " + classname);
  plainWarning("File name: " + file);
  plainWarning("Function name: " + function);
  plainWarning("Error line: " + linenumber);
  if (Config.plugin_logging) {
    DateFormat LogFormat=new SimpleDateFormat(Config.plugin_logformat);
    Date date=new Date();
    plainWarning("Check log file: " + plugin.getDataFolder() + "\\logs\\error\\"+ LogFormat.format(date)+ "-error.log");
  }
 else {
    plainWarning("Enable logging in the config to get more information about the error.");
  }
  logError("--------------------------- STACKTRACE ERROR ---------------------------");
  logError("Class name: " + classname);
  logError("File name: " + file);
  logError("Function name: " + function);
  logError("Error line: " + linenumber);
  logError("BabelCraft version: " + Variables.pluginVersion);
  Plugin[] plugins=plugin.getServer().getPluginManager().getPlugins();
  int counter=0;
  StringBuffer pluginsList=new StringBuffer();
  while (plugins.length > counter) {
    pluginsList.append(plugins[counter].getDescription().getName() + " " + plugins[counter].getDescription().getVersion()+ ", ");
    counter++;
  }
  logError("Plugins: " + pluginsList.toString());
  logError("--------------------------- STACKTRACE START ---------------------------");
  for (int i=0; i < stack.length; i++) {
    logError(stack[i].toString());
  }
  logError("---------------------------- STACKTRACE END ----------------------------");
}
 

Example 49

From project BetterShop_1, under directory /src/me/jascotty2/bettershop/.

Source file: Updater.java

  17 
vote

public static boolean IsUpToDate(boolean log){
  long t=readUpdatedFile();
  long d=System.currentTimeMillis() - t;
  if (d > 0 && d < BetterShop.lastUpdated_gracetime * 60000) {
    BetterShopLogger.Log("Recently Updated: skipping update check");
    return true;
  }
  try {
    DateFormat formatter=new SimpleDateFormat("MM/dd/yy HH:mm Z",Locale.US);
    Date pluginDate=formatter.parse(BetterShop.lastUpdatedStr);
    return update.isUpToDate(BetterShop.bettershopPlugin.getDescription().getVersion(),pluginDate,BetterShop.lastUpdated_gracetime * 60000,log ? BetterShopLogger.getLogger() : null);
  }
 catch (  ParseException ex) {
    BetterShopLogger.Severe(ex);
  }
  return true;
}
 

Example 50

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.

Source file: Logger.java

  17 
vote

/** 
 * Write the exception stacktrace to the error log file 
 * @param e The exception to log
 */
public static void logError(Exception e,String msg){
  DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date date=new Date();
  String now=dateFormat.format(date);
  StringWriter sw=new StringWriter();
  PrintWriter pw=new PrintWriter(sw);
  e.printStackTrace(pw);
  String error="An Exception Occured @ " + now + "\n"+ "In Phone "+ Build.MODEL+ " ("+ Build.VERSION.SDK_INT+ ") \n"+ msg+ "\n"+ sw.toString();
  try {
    Log.e("BC Logger",error);
    BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(StorageUtils.getErrorLog()),"utf8"),8192);
    out.write(error);
    out.close();
  }
 catch (  Exception e1) {
  }
}
 

Example 51

From project BusFollower, under directory /src/net/argilo/busfollower/.

Source file: Util.java

  17 
vote

private static String getHumanReadableTime(Context context,Date date){
  StringBuffer result=new StringBuffer();
  DateFormat formatter=android.text.format.DateFormat.getTimeFormat(context);
  formatter.setTimeZone(TimeZone.getTimeZone("America/Toronto"));
  result.append(formatter.format(date));
  result.append(" (");
  long difference=date.getTime() - Calendar.getInstance().getTimeInMillis();
  if (difference >= 0) {
    int differenceMinutes=(int)((difference + 30000) / 60000);
    result.append(context.getResources().getQuantityString(R.plurals.minutes,differenceMinutes,differenceMinutes));
  }
 else {
    int differenceMinutes=(int)((-difference + 30000) / 60000);
    result.append(context.getResources().getQuantityString(R.plurals.minutesAgo,differenceMinutes,differenceMinutes));
  }
  result.append(")");
  return result.toString();
}
 

Example 52

From project CalendarPortlet, under directory /src/test/java/org/jasig/portlet/calendar/mvc/controller/.

Source file: AjaxCalendarControllerTest.java

  17 
vote

@Test public void testAddLongEventToDateMap() throws IOException, URISyntaxException, ParseException {
  TimeZone tz=TimeZone.getTimeZone("America/Los Angeles");
  DateFormat df=new SimpleDateFormat("EEEE MMMM d");
  df.setTimeZone(tz);
  Calendar cal=Calendar.getInstance(tz);
  cal.set(Calendar.YEAR,2011);
  cal.set(Calendar.MONTH,0);
  cal.set(Calendar.DATE,3);
  cal.set(Calendar.HOUR_OF_DAY,4);
  cal.set(Calendar.MINUTE,0);
  cal.set(Calendar.SECOND,0);
  cal.set(Calendar.MILLISECOND,0);
  Date start=cal.getTime();
  cal.add(Calendar.DATE,1);
  Date periodStart=cal.getTime();
  cal.add(Calendar.DATE,1);
  Date end=cal.getTime();
  Period period=new Period(new DateTime(periodStart),new DateTime(end));
  VEvent event=new VEvent(new DateTime(start),new DateTime(end),"Test Event");
  List<CalendarDisplayEvent> events=new ArrayList<CalendarDisplayEvent>();
}
 

Example 53

From project camel-aries-blueprint-tutorial, under directory /reportincident.routing/src/main/java/org/apache/camel/example/reportincident/internal/.

Source file: IncidentSaver.java

  17 
vote

public void process(Exchange exchange) throws ParseException {
  int count=0;
  List<Map<String,Object>> models=new ArrayList<Map<String,Object>>();
  Map<String,Object> model=new HashMap<String,Object>();
  models=(List<Map<String,Object>>)exchange.getIn().getBody();
  String origin=(String)exchange.getIn().getHeader("origin");
  LOG.debug("Header origin : " + origin);
  Iterator<Map<String,Object>> it=models.iterator();
  DateFormat format=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  String currentDate=format.format(new Date());
  Date creationDate=format.parse(currentDate);
  while (it.hasNext()) {
    model=it.next();
    LOG.debug("Model retrieved");
    for (    String key : model.keySet()) {
      LOG.debug("Object retrieved : " + model.get(key).toString());
      Incident incident=(Incident)model.get(key);
      incident.setCreationDate(creationDate);
      incident.setCreationUser(origin);
      LOG.debug("Count : " + count + ", "+ incident.toString());
      incidentService.saveIncident(incident);
      LOG.debug("org.apache.camel.example.reportincident.model.Incident saved");
    }
    count++;
  }
  LOG.debug("Nber of CSV records received by the csv bean : " + count);
}
 

Example 54

From project camel-osgi-servicemix-tutorial, under directory /routing/src/main/java/org/fusesource/devoxx/reportincident/internal/.

Source file: IncidentSaver.java

  17 
vote

public void process(Exchange exchange) throws ParseException {
  int count=0;
  List<Map<String,Object>> models=new ArrayList<Map<String,Object>>();
  Map<String,Object> model=new HashMap<String,Object>();
  models=(List<Map<String,Object>>)exchange.getIn().getBody();
  String origin=(String)exchange.getIn().getHeader("origin");
  LOG.debug("Header origin : " + origin);
  Iterator<Map<String,Object>> it=models.iterator();
  DateFormat format=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  String currentDate=format.format(new Date());
  Date creationDate=format.parse(currentDate);
  while (it.hasNext()) {
    model=it.next();
    LOG.debug("Model retrieved");
    for (    String key : model.keySet()) {
      LOG.debug("Object retrieved : " + model.get(key).toString());
      Incident incident=(Incident)model.get(key);
      incident.setCreationDate(creationDate);
      incident.setCreationUser(origin);
      LOG.debug("Count : " + count + ", "+ incident.toString());
      incidentService.saveIncident(incident);
      LOG.debug(">>> org.fusesource.devoxx.reportincident.model.Incident saved");
    }
    count++;
  }
  LOG.debug("Nber of CSV records received by the csv bean : " + count);
}
 

Example 55

From project camel-osgi-tutorial, under directory /reportincident.routing/src/main/java/org/apache/camel/example/reportincident/internal/.

Source file: IncidentSaver.java

  17 
vote

public void process(Exchange exchange) throws ParseException {
  int count=0;
  List<Map<String,Object>> models=new ArrayList<Map<String,Object>>();
  Map<String,Object> model=new HashMap<String,Object>();
  models=(List<Map<String,Object>>)exchange.getIn().getBody();
  String origin=(String)exchange.getIn().getHeader("origin");
  LOG.debug("Header origin : " + origin);
  Iterator<Map<String,Object>> it=models.iterator();
  DateFormat format=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  String currentDate=format.format(new Date());
  Date creationDate=format.parse(currentDate);
  while (it.hasNext()) {
    model=it.next();
    LOG.debug("Model retrieved");
    for (    String key : model.keySet()) {
      LOG.debug("Object retrieved : " + model.get(key).toString());
      Incident incident=(Incident)model.get(key);
      incident.setCreationDate(creationDate);
      incident.setCreationUser(origin);
      LOG.debug("Count : " + count + ", "+ incident.toString());
      incidentService.saveIncident(incident);
      LOG.debug("Incident saved");
    }
    count++;
  }
  LOG.debug("Nber of CSV records received by the csv bean : " + count);
}
 

Example 56

From project Carolina-Digital-Repository, under directory /metadata/src/main/java/edu/unc/lib/dl/util/.

Source file: LOC6392BExtractor.java

  17 
vote

public static void main(String[] args){
  ClassPathResource isoFile=new ClassPathResource("/edu/unc/lib/dl/standards/ISO-639-2_utf-8.txt");
  BufferedReader br=null;
  Document xml=new Document().setRootElement(new Element("option-set"));
  xml.getRootElement().setAttribute("label","ISO 639-2 Languages");
  xml.getRootElement().setAttribute("authority-term","iso639-2b");
  xml.getRootElement().setAttribute("type","code");
  xml.getRootElement().setAttribute("url","http://www.loc.gov/standards/iso639-2/");
  xml.getRootElement().setAttribute("contextElement","languageTerm");
  xml.getRootElement().setAttribute("contextNamespace","http://www.loc.gov/mods/v3");
  try {
    DateFormat df=DateFormat.getDateInstance(DateFormat.SHORT);
    Date now=new java.util.Date(isoFile.getFile().lastModified());
    xml.getRootElement().setAttribute("date",df.format(now));
    br=new BufferedReader(new InputStreamReader(isoFile.getInputStream(),"utf-8"));
    for (String s=br.readLine(); s != null; s=br.readLine()) {
      String[] m=s.split("\\|");
      if (m.length > 1) {
        String value=m[0];
        String label=m[3].split(";")[0];
        Element option=new Element("option");
        option.addContent(new Element("value").setText(value));
        option.addContent(new Element("label").setText(label));
        xml.getRootElement().addContent(option);
        System.err.println(label + " -> " + value);
      }
    }
    File outFile=new File("/tmp/ISO-639-2_utf-8.xml");
    XMLOutputter out=new XMLOutputter();
    out.setFormat(Format.getPrettyFormat());
    out.output(xml,new FileOutputStream(outFile));
  }
 catch (  IOException e) {
    e.printStackTrace();
    throw new RuntimeException(e);
  }
}
 

Example 57

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/.

Source file: DateUtilities.java

  17 
vote

@Deprecated public static Date parseDate(String dateString,DateFormat[] dateFormats,boolean fixYear) throws ParseException {
  for (int ii=0; ii < dateFormats.length; ii++) {
    try {
      DateFormat format=dateFormats[ii];
      format.setLenient(false);
      Date date=format.parse(dateString);
      if (fixYear && (date.getYear() < 1900)) {
        date.setYear(date.getYear() + 1900);
      }
      return date;
    }
 catch (    ParseException dateParseException) {
      continue;
    }
  }
  String exceptionMessage="Could not parse the field " + "'" + dateString + "'"+ " as a date.";
  throw new ParseException(exceptionMessage,0);
}
 

Example 58

From project Cloud9, under directory /src/attic/edu/cloud9/collection/spinn3r/.

Source file: Spinn3rItem.java

  17 
vote

public Date getPubDate(){
  if (mPubDate == null) {
    int start=mItem.indexOf("<pubDate>");
    int end=mItem.indexOf("</pubDate>",start);
    String s=mItem.substring(start + 9,end);
    try {
      DateFormat format=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
      mPubDate=format.parse(s);
    }
 catch (    ParseException e) {
      e.printStackTrace();
    }
  }
  return mPubDate;
}
 

Example 59

From project coala, under directory /modules/coala-ipf/coala-ipf-xds/src/test/java/org/openehealth/coala/xds/test/.

Source file: XDSTransactorIti41Test.java

  17 
vote

private DocumentEntry createDocumentEntry(Author author,Identifiable patientID,Code policy) throws XDSConfigurationErrorException {
  try {
    if (patientID == null)     throw new XDSRequestFailedException("PatientID must not be null");
    consentCounter=1;
    DocumentEntry docEntry=new DocumentEntry();
    if (author != null)     docEntry.getAuthors().add(author);
    docEntry.setAvailabilityStatus(AvailabilityStatus.APPROVED);
    String langCode=xdsConfiguration.getConsentLanguageCode();
    setConsentClassCode(docEntry,langCode);
    setConsentConfidentialityCode(docEntry,langCode);
    DateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
    docEntry.setCreationTime(dateFormat.format(new Date()));
    docEntry.setEntryUuid("newConsent" + consentCounter);
    consentCounter++;
    docEntry.setServiceStartTime("20110705171421");
    docEntry.setServiceStopTime("20120705171421");
    docEntry.getEventCodeList().add(policy);
    setConsentFormatCode(docEntry,langCode);
    String uniqueId="2.16.840.1.113883.3.37.900.5.2";
    uniqueId+="." + patientID.getId() + "."+ dateFormat.format(new Date());
    setHealthcareFacilityTypeCode(docEntry);
    docEntry.setLanguageCode(langCode);
    docEntry.setMimeType("text/xml");
    docEntry.setPatientId(patientID);
    setPracticeSettingCode(docEntry);
    docEntry.setRepositoryUniqueId("1.2.840.113619.20.2.2.1");
    docEntry.setSourcePatientId(patientID);
    docEntry.setTitle(new LocalizedString("Consent for" + patientID.getId(),langCode,encoding));
    setConsentTypeCode(docEntry,langCode);
    docEntry.setUniqueId(uniqueId);
    return docEntry;
  }
 catch (  MissingResourceException e) {
    throw new XDSConfigurationErrorException("Configuration file seems to be corrupted. Check for missing properties.");
  }
catch (  ClassCastException e2) {
    throw new XDSConfigurationErrorException("Configuration file seems to be corrupted. Check for missing properties.");
  }
}
 

Example 60

From project codjo-standalone-common, under directory /src/main/java/net/codjo/utils/sql/.

Source file: AbstractDetailWindow.java

  17 
vote

/** 
 * Converti le texte dans le format bd.
 * @param textValue  Valeur sous forme String
 * @param columnName Le nom physique de la colonne
 * @param sqlType    type sql du format
 * @return Valeur convertie.
 * @throws IllegalArgumentException TODO
 */
protected Object translateValue(String textValue,String columnName,int sqlType){
  if ("".equals(textValue)) {
    return null;
  }
switch (sqlType) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
    return textValue;
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
  return Integer.decode(textValue);
case Types.FLOAT:
return new Float(StringUtil.removeAllCharOccurrence(textValue,','));
case Types.DOUBLE:
return new Double(StringUtil.removeAllCharOccurrence(textValue,','));
case Types.NUMERIC:
return new BigDecimal(StringUtil.removeAllCharOccurrence(textValue,','));
case Types.BIT:
return new Boolean(textValue);
case Types.DATE:
case Types.TIMESTAMP:
DateFormat df=DateFormat.getDateInstance(DateFormat.SHORT,Locale.FRANCE);
df.setLenient(false);
try {
return df.parse(textValue);
}
 catch (ParseException ex) {
throw new IllegalArgumentException("Mauvais format de date" + " pour le champ " + columnName + " (format DD/MM/AAAA)");
}
default :
throw new IllegalArgumentException("Type SQL non supporte : " + columnName);
}
}
 

Example 61

From project com.juick.android, under directory /src/com/juick/android/api/.

Source file: JuickMessage.java

  17 
vote

public static JuickMessage parseJSON(JSONObject json) throws JSONException {
  JuickMessage jmsg=new JuickMessage();
  jmsg.MID=json.getInt("mid");
  if (json.has("rid")) {
    jmsg.RID=json.getInt("rid");
  }
  jmsg.Text=json.getString("body").replace("&quot;","\"");
  jmsg.User=JuickUser.parseJSON(json.getJSONObject("user"));
  try {
    DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    jmsg.Timestamp=df.parse(json.getString("timestamp"));
  }
 catch (  ParseException e) {
  }
  if (json.has("tags")) {
    JSONArray tags=json.getJSONArray("tags");
    for (int n=0; n < tags.length(); n++) {
      jmsg.tags.add(tags.getString(n).replace("&quot;","\""));
    }
  }
  if (json.has("replies")) {
    jmsg.replies=json.getInt("replies");
  }
  if (json.has("photo")) {
    jmsg.Photo=json.getJSONObject("photo").getString("small");
  }
  if (json.has("video")) {
    jmsg.Video=json.getJSONObject("video").getString("mp4");
  }
  return jmsg;
}
 

Example 62

From project CraftCommons, under directory /src/main/java/com/craftfire/commons/managers/.

Source file: LoggingManager.java

  17 
vote

public void stackTrace(final Exception e,HashMap<Integer,String> extra){
  advancedWarning("Stacktrace Error");
  warning("Class name: " + e.getStackTrace()[1].getClassName());
  warning("Error message: " + e.getMessage());
  warning("Error cause: " + e.getCause());
  warning("File name: " + e.getStackTrace()[1].getFileName());
  warning("Function name: " + e.getStackTrace()[1].getMethodName());
  warning("Error line: " + e.getStackTrace()[1].getLineNumber());
  if (this.logging) {
    DateFormat LogFormat=new SimpleDateFormat(this.format);
    Date date=new Date();
    warning("Check log file: " + this.directory + "error\\"+ LogFormat.format(date)+ "-error.log");
  }
 else {
    warning("Enable logging in the config to get more information about the error.");
  }
  logError("--------------------------- STACKTRACE ERROR ---------------------------");
  logError("Class name: " + e.getStackTrace()[1].getClassName());
  logError("Error message: " + e.getMessage());
  logError("Error cause: " + e.getCause());
  logError("File name: " + e.getStackTrace()[1].getFileName());
  logError("Function name: " + e.getStackTrace()[1].getMethodName());
  logError("Error line: " + e.getStackTrace()[1].getLineNumber());
  if (extra != null) {
    for (    int id : extra.keySet()) {
      logError(extra.get(id));
    }
  }
  logError("--------------------------- STACKTRACE START ---------------------------");
  for (int i=0; i < e.getStackTrace().length; i++) {
    logError(e.getStackTrace()[i].toString());
  }
  logError("---------------------------- STACKTRACE END ----------------------------");
}
 

Example 63

From project cvs-plugin, under directory /src/main/java/hudson/scm/.

Source file: CVSChangeLogSet.java

  17 
vote

public void toFile(final java.io.File changelogFile) throws IOException {
  String encoding=((CVSSCM.DescriptorImpl)Jenkins.getInstance().getDescriptorOrDie(CVSSCM.class)).getChangelogEncoding();
  PrintStream output=new PrintStream(new FileOutputStream(changelogFile),true,encoding);
  DateFormat format=new SimpleDateFormat(CHANGE_DATE_FORMATTER_PATTERN);
  output.println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
  output.println("<changelog>");
  for (  CVSChangeLog entry : this) {
    output.println("\t<entry>");
    output.println("\t\t<changeDate>" + format.format(entry.getChangeDate()) + "</changeDate>");
    output.println("\t\t<author><![CDATA[" + entry.getAuthor() + "]]></author>");
    for (    CVSChangeLogSet.File file : entry.getFiles()) {
      output.println("\t\t<file>");
      output.println("\t\t\t<name><![CDATA[" + file.getName() + "]]></name>");
      if (file.getFullName() != null) {
        output.println("\t\t\t<fullName><![CDATA[" + file.getFullName() + "]]></fullName>");
      }
      output.println("\t\t\t<revision>" + file.getRevision() + "</revision>");
      final String previousRevision=file.getPrevrevision();
      if (previousRevision != null) {
        output.println("\t\t\t<prevrevision>" + previousRevision + "</prevrevision>");
      }
      if (file.isDead()) {
        output.println("\t\t\t<dead />");
      }
      output.println("\t\t</file>");
    }
    output.println("\t\t<msg><![CDATA[" + entry.getMsg() + "]]></msg>");
    output.println("\t</entry>");
  }
  output.println("</changelog>");
  output.flush();
  output.close();
}
 

Example 64

From project data-access, under directory /src/org/pentaho/platform/dataaccess/datasource/wizard/csv/.

Source file: FileUtils.java

  17 
vote

public FileInfo[] listFiles(){
  List<FileInfo> fileList=new ArrayList<FileInfo>();
  String relativePath=PentahoSystem.getSystemSetting("file-upload-defaults/relative-path",String.valueOf(DEFAULT_RELATIVE_UPLOAD_FILE_PATH));
  String path=PentahoSystem.getApplicationContext().getSolutionPath(relativePath);
  File folder=new File(path);
  if (folder.exists()) {
    File files[]=folder.listFiles();
    for (    File file : files) {
      String name=file.getName();
      if (file.isFile()) {
        long lastModified=file.lastModified();
        DateFormat fmt=LocaleHelper.getShortDateFormat(true,true);
        Date modified=new Date();
        modified.setTime(lastModified);
        String modifiedStr=fmt.format(modified);
        long size=file.length();
        FileInfo info=new FileInfo();
        info.setModified(modifiedStr);
        info.setName(name);
        info.setSize(size);
        fileList.add(info);
      }
    }
  }
  return fileList.toArray(new FileInfo[fileList.size()]);
}
 

Example 65

From project devoxx-2011-hands-on-lab, under directory /routing/src/main/java/org/fusesource/devoxx/reportincident/internal/.

Source file: IncidentSaver.java

  17 
vote

public void process(Exchange exchange) throws ParseException {
  int count=0;
  List<Map<String,Object>> models=new ArrayList<Map<String,Object>>();
  Map<String,Object> model=new HashMap<String,Object>();
  models=(List<Map<String,Object>>)exchange.getIn().getBody();
  String origin=(String)exchange.getIn().getHeader("origin");
  LOG.debug("Header origin : " + origin);
  Iterator<Map<String,Object>> it=models.iterator();
  DateFormat format=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  String currentDate=format.format(new Date());
  Date creationDate=format.parse(currentDate);
  while (it.hasNext()) {
    model=it.next();
    LOG.debug("Model retrieved");
    for (    String key : model.keySet()) {
      LOG.debug("Object retrieved : " + model.get(key).toString());
      Incident incident=(Incident)model.get(key);
      incident.setCreationDate(creationDate);
      incident.setCreationUser(origin);
      LOG.debug("Count : " + count + ", "+ incident.toString());
      incidentService.saveIncident(incident);
      LOG.debug(">>> org.fusesource.devoxx.reportincident.model.Incident saved");
    }
    count++;
  }
  LOG.debug("Nber of CSV records received by the csv bean : " + count);
}
 

Example 66

From project drools-planner, under directory /drools-planner-examples/src/main/java/org/drools/planner/examples/nurserostering/domain/.

Source file: ShiftDate.java

  17 
vote

public String determineNextDateString(){
  TimeZone LOCAL_TIMEZONE=TimeZone.getTimeZone("GMT");
  Calendar calendar=Calendar.getInstance();
  calendar.setTimeZone(LOCAL_TIMEZONE);
  calendar.clear();
  DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
  dateFormat.setCalendar(calendar);
  Date date;
  try {
    date=dateFormat.parse(dateString);
  }
 catch (  ParseException e) {
    throw new IllegalStateException("Could not parse shiftDate (" + this + ")'s dateString ("+ dateString+ ").");
  }
  calendar.setTime(date);
  calendar.add(Calendar.DAY_OF_YEAR,1);
  return dateFormat.format(calendar.getTime());
}
 

Example 67

From project Dual-Battery-Widget, under directory /lib/AChartEngine/src/org/achartengine/chart/.

Source file: TimeChart.java

  17 
vote

/** 
 * The graphical representation of the labels on the X axis.
 * @param xLabels the X labels values
 * @param xTextLabelLocations the X text label locations
 * @param canvas the canvas to paint to
 * @param paint the paint to be used for drawing
 * @param left the left value of the labels area
 * @param top the top value of the labels area
 * @param bottom the bottom value of the labels area
 * @param xPixelsPerUnit the amount of pixels per one unit in the chart labels
 * @param minX the minimum value on the X axis in the chart
 * @param maxX the maximum value on the X axis in the chart
 */
@Override protected void drawXLabels(List<Double> xLabels,Double[] xTextLabelLocations,Canvas canvas,Paint paint,int left,int top,int bottom,double xPixelsPerUnit,double minX,double maxX){
  int length=xLabels.size();
  if (length > 0) {
    boolean showLabels=mRenderer.isShowLabels();
    boolean showGridY=mRenderer.isShowGridY();
    DateFormat format=getDateFormat(xLabels.get(0),xLabels.get(length - 1));
    for (int i=0; i < length; i++) {
      long label=Math.round(xLabels.get(i));
      float xLabel=(float)(left + xPixelsPerUnit * (label - minX));
      if (showLabels) {
        paint.setColor(mRenderer.getXLabelsColor());
        canvas.drawLine(xLabel,bottom,xLabel,bottom + mRenderer.getLabelsTextSize() / 3,paint);
        drawText(canvas,format.format(new Date(label)),xLabel,bottom + mRenderer.getLabelsTextSize() * 4 / 3,paint,mRenderer.getXLabelsAngle());
      }
      if (showGridY) {
        paint.setColor(mRenderer.getGridColor());
        canvas.drawLine(xLabel,bottom,xLabel,top,paint);
      }
    }
  }
  drawXTextLabels(xTextLabelLocations,canvas,paint,true,left,top,bottom,xPixelsPerUnit,minX,maxX);
}
 

Example 68

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/dummy/.

Source file: RequestProcessor.java

  15 
vote

private void processLoginRequest(Request m,BufferedWriter w) throws AclsException {
  LoginRequest login=(LoginRequest)m;
  String timestamp=DateFormat.getInstance().format(new Date());
  List<String> accounts=Arrays.asList("general","special");
  Response r;
  if (!login.getPassword().equals("secret")) {
    r=new RefusedResponse(ResponseType.VIRTUAL_LOGIN_REFUSED);
  }
 else   if (login.getUserName().equals("junior")) {
    r=new LoginResponse(ResponseType.VIRTUAL_LOGIN_ALLOWED,login.getUserName(),"CMMMM",timestamp,accounts,Certification.NONE,true);
  }
 else   if (login.getUserName().equals("badboy")) {
    r=new LoginResponse(ResponseType.VIRTUAL_LOGIN_ALLOWED,login.getUserName(),"CMMMM",timestamp,accounts,Certification.NONE,false);
  }
 else {
    r=new LoginResponse(ResponseType.VIRTUAL_LOGIN_ALLOWED,login.getUserName(),"CMMMM",timestamp,accounts,Certification.VALID,false);
  }
  sendResponse(w,r);
}
 

Example 69

From project agorava-twitter, under directory /agorava-twitter-cdi/src/main/java/org/agorava/twitter/jackson/.

Source file: AbstractTrendsList.java

  15 
vote

public AbstractTrendsList(Map<String,List<Trend>> trends,DateFormat dateFormat){
  list=new ArrayList<Trends>(trends.size());
  for (Iterator<Entry<String,List<Trend>>> trendsIt=trends.entrySet().iterator(); trendsIt.hasNext(); ) {
    Entry<String,List<Trend>> entry=trendsIt.next();
    list.add(new Trends(toDate(entry.getKey(),dateFormat),entry.getValue()));
  }
  Collections.sort(list,new Comparator<Trends>(){
    public int compare(    Trends t1,    Trends t2){
      return t1.getTime().getTime() > t2.getTime().getTime() ? -1 : 1;
    }
  }
);
}
 

Example 70

From project android-client_2, under directory /src/org/mifos/androidclient/util/ui/.

Source file: DateUtils.java

  15 
vote

private static DateFormat getInstance(){
  if (sFormatter == null) {
    sFormatter=new SimpleDateFormat(DEFAULT_DATE_FORMAT);
  }
  return sFormatter;
}
 

Example 71

From project androidannotations, under directory /AndroidAnnotations/functional-test-1-5-tests/src/test/java/com/googlecode/androidannotations/test15/roboguice/.

Source file: FakeDateProvider.java

  15 
vote

public void setDate(String dateString){
  try {
    date=DateFormat.getDateInstance(DateFormat.LONG,Locale.US).parse(dateString);
  }
 catch (  ParseException e) {
    throw new RuntimeException("bad date!!");
  }
}
 

Example 72

From project androidtracks, under directory /src/org/sfcta/cycletracks/.

Source file: SaveTrip.java

  15 
vote

void activateSubmitButton(){
  final Button btnSubmit=(Button)findViewById(R.id.ButtonSubmit);
  final Intent xi=new Intent(this,ShowMap.class);
  btnSubmit.setEnabled(true);
  btnSubmit.setOnClickListener(new View.OnClickListener(){
    public void onClick(    View v){
      TripData trip=TripData.fetchTrip(SaveTrip.this,tripid);
      trip.populateDetails();
      if (purpose.equals("")) {
        Toast.makeText(getBaseContext(),"You must select a trip purpose before submitting! Choose from the purposes above.",Toast.LENGTH_SHORT).show();
        return;
      }
      EditText notes=(EditText)findViewById(R.id.NotesField);
      String fancyStartTime=DateFormat.getInstance().format(trip.startTime);
      SimpleDateFormat sdf=new SimpleDateFormat("m");
      sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
      String minutes=sdf.format(trip.endTime - trip.startTime);
      String fancyEndInfo=String.format("%1.1f miles, %s minutes.  %s",(0.0006212f * trip.distance),minutes,notes.getEditableText().toString());
      trip.updateTrip(purpose,fancyStartTime,fancyEndInfo,notes.getEditableText().toString());
      trip.updateTripStatus(TripData.STATUS_COMPLETE);
      resetService();
      InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(v.getWindowToken(),0);
      Intent i=new Intent(getApplicationContext(),MainInput.class);
      startActivity(i);
      xi.putExtra("showtrip",trip.tripid);
      xi.putExtra("uploadTrip",true);
      startActivity(xi);
      SaveTrip.this.finish();
    }
  }
);
}
 

Example 73

From project Android_1, under directory /org.eclipse.ecf.provider.zookeeper/src/org/eclipse/ecf/provider/zookeeper/util/.

Source file: PrettyPrinter.java

  15 
vote

public static void prompt(int type,IServiceInfo serviceInfo){
  String token="";
  String time=DateFormat.getInstance().format(Calendar.getInstance().getTime()) + ". ";
switch (type) {
case PUBLISHED:
    token="Service Published: ";
  break;
case UNPUBLISHED:
token="Service Unpublished: ";
break;
case ACTIVATED:
token="Discovery Service Activated. ";
break;
case DEACTIVATED:
token="Discovery Service Deactivated.";
break;
case PUBLISH_DELAYED:
token="Service Publication Delayed: ";
break;
case UNPUBLISH_DELAYED:
token="Service Unpublication Delayed: ";
break;
case REMOTE_AVAILABLE:
token="Service Discovered: ";
break;
case REMOTE_UNAVAILABLE:
token="Service Undiscovered: ";
break;
}
System.err.println(prompt + token + time+ ((serviceInfo != null) ? serviceInfo : ""));
}
 

Example 74

From project android_8, under directory /src/com/google/gson/.

Source file: DefaultTypeAdapters.java

  15 
vote

DefaultDateTypeAdapter(DateFormat enUsFormat,DateFormat localFormat){
  this.enUsFormat=enUsFormat;
  this.localFormat=localFormat;
  this.iso8601Format=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",Locale.US);
  this.iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
}
 

Example 75

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/utility/.

Source file: CalendarUtilities.java

  15 
vote

static public String buildMessageTextFromEntityValues(Context context,ContentValues entityValues,StringBuilder sb){
  if (sb == null) {
    sb=new StringBuilder();
  }
  Resources resources=context.getResources();
  Date date=new Date(entityValues.getAsLong(Events.DTSTART));
  boolean allDayEvent=false;
  if (entityValues.containsKey(Events.ALL_DAY)) {
    Integer ade=entityValues.getAsInteger(Events.ALL_DAY);
    allDayEvent=(ade != null) && (ade == 1);
  }
  boolean recurringEvent=!entityValues.containsKey(Events.ORIGINAL_SYNC_ID) && entityValues.containsKey(Events.RRULE);
  String dateTimeString;
  int res;
  if (allDayEvent) {
    dateTimeString=DateFormat.getDateInstance().format(date);
    res=recurringEvent ? R.string.meeting_allday_recurring : R.string.meeting_allday;
  }
 else {
    dateTimeString=DateFormat.getDateTimeInstance().format(date);
    res=recurringEvent ? R.string.meeting_recurring : R.string.meeting_when;
  }
  sb.append(resources.getString(res,dateTimeString));
  String location=null;
  if (entityValues.containsKey(Events.EVENT_LOCATION)) {
    location=entityValues.getAsString(Events.EVENT_LOCATION);
    if (!TextUtils.isEmpty(location)) {
      sb.append("\n");
      sb.append(resources.getString(R.string.meeting_where,location));
    }
  }
  String desc=entityValues.getAsString(Events.DESCRIPTION);
  if (desc != null) {
    sb.append("\n--\n");
    sb.append(desc);
  }
  return sb.toString();
}
 

Example 76

From project android_packages_apps_phone, under directory /src/com/android/phone/.

Source file: DataUsageListener.java

  15 
vote

private void updateUI(){
  if (mPolicyThreshold == 0)   return;
  int dataUsedPercent=(int)((mDataUsed * 100) / mPolicyThreshold);
  long cycleTime=mEnd.getTimeInMillis() - mStart.getTimeInMillis();
  long currentTime=GregorianCalendar.getInstance().getTimeInMillis() - mStart.getTimeInMillis();
  int cycleThroughPercent=(cycleTime == 0) ? 0 : (int)((currentTime * 100) / cycleTime);
  Calendar cal=Calendar.getInstance();
  cal.setTimeInMillis(cycleTime - currentTime);
  int daysLeft=cal.get(Calendar.DAY_OF_YEAR);
  if (daysLeft >= 365)   daysLeft=0;
  if (mCurrentUsagePref != null) {
    if (mCurrentThrottleRate > 0) {
      mCurrentUsagePref.setSummary(mContext.getString(R.string.throttle_data_rate_reduced_subtext,toReadable(mPolicyThreshold),mCurrentThrottleRate));
    }
 else {
      mCurrentUsagePref.setSummary(mContext.getString(R.string.throttle_data_usage_subtext,toReadable(mDataUsed),dataUsedPercent,toReadable(mPolicyThreshold)));
    }
  }
  if (mTimeFramePref != null) {
    mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext,cycleThroughPercent,daysLeft,DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime())));
  }
  if (mThrottleRatePref != null) {
    mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext,mPolicyThrottleValue));
  }
  if (mSummaryPref != null && mSummaryPrefEnabled) {
    if (mCurrentThrottleRate > 0) {
      mSummaryPref.setSummary(mContext.getString(R.string.throttle_data_rate_reduced_subtext,toReadable(mPolicyThreshold),mCurrentThrottleRate));
    }
 else {
      mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext,toReadable(mDataUsed),dataUsedPercent,toReadable(mPolicyThreshold),daysLeft,DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime())));
    }
  }
}
 

Example 77

From project apg, under directory /src/org/thialfihar/android/apg/ui/widget/.

Source file: KeyEditor.java

  15 
vote

private void setExpiryDate(GregorianCalendar date){
  mExpiryDate=date;
  if (date == null) {
    mExpiryDateButton.setText(R.string.none);
  }
 else {
    mExpiryDateButton.setText(DateFormat.getDateInstance().format(date.getTime()));
  }
}
 

Example 78

From project arastreju, under directory /arastreju.sge/src/main/java/org/arastreju/sge/model/nodes/views/.

Source file: SNTimeSpec.java

  15 
vote

/** 
 * {@inheritDoc}
 */
@Override public String toString(){
switch (getTimeMask()) {
case DATE:
    return DateFormat.getDateInstance().format(getTimeValue());
case TIME_OF_DAY:
  return DateFormat.getTimeInstance().format(getTimeValue());
case TIMESTAMP:
return DateFormat.getDateTimeInstance().format(getTimeValue());
default :
throw new NotYetSupportedException(getTimeMask());
}
}
 

Example 79

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/activities/marketplace/.

Source file: MarketplaceCoupon.java

  15 
vote

private void loadData(){
  try {
    String currencyName="Bedollars";
    if (Beintoo.virtualCurrencyData != null) {
      currencyName=Beintoo.virtualCurrencyData.get("currencyName");
      findViewById(R.id.buy_bedollar_logo).setVisibility(View.GONE);
      findViewById(R.id.buy_sendgift_bedollar_logo).setVisibility(View.GONE);
    }
    if ((Beintoo.virtualCurrencyData == null) && (MarketplaceList.userBedollars == null || MarketplaceList.userBedollars < price)) {
      ((ImageView)findViewById(R.id.buy_bedollar_logo)).setImageDrawable(mContext.getResources().getDrawable(R.drawable.b01));
      ((ImageView)findViewById(R.id.buy_sendgift_bedollar_logo)).setImageDrawable(mContext.getResources().getDrawable(R.drawable.b01));
    }
    Double price=(vgood.getVirtualCurrencyPrice() != null) ? vgood.getVirtualCurrencyPrice() : vgood.getBedollars();
    ((TextView)findViewById(R.id.coupon_name)).setText(vgood.getName());
    ((TextView)findViewById(R.id.coupon_name)).setSingleLine(true);
    ((TextView)findViewById(R.id.coupon_bedollars)).setText(mContext.getString(R.string.price) + price + " "+ currencyName);
    ((TextView)findViewById(R.id.coupon_bedollars_buy)).setText(price + " " + ((!currencyName.equals("Bedollars")) ? " " + currencyName : ""));
    ((TextView)findViewById(R.id.coupon_bedollars_sendgift)).setText(price + " " + ((!currencyName.equals("Bedollars")) ? " " + currencyName : ""));
    ((TextView)findViewById(R.id.coupon_title_large)).setText((vgood.getName().length() > 22) ? vgood.getName().substring(0,22) + "..." : vgood.getName());
    ((TextView)findViewById(R.id.coupon_desc)).setText(vgood.getDescription());
    SimpleDateFormat dateFormatter=new SimpleDateFormat("d-MMM-y HH:mm:ss",Locale.ENGLISH);
    dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date msgDate=dateFormatter.parse(vgood.getEnddate());
    dateFormatter.setTimeZone(TimeZone.getDefault());
    ((TextView)findViewById(R.id.coupon_valid)).setText(mContext.getString(R.string.challEnd) + " " + DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.SHORT,Locale.getDefault()).format(msgDate));
    ImageView img=(ImageView)findViewById(R.id.coupon_image);
    img.setTag(vgood.getImageUrl());
    ImageManager imageDisplayer=new ImageManager(mContext);
    imageDisplayer.displayImage(vgood.getImageUrl(),mContext,img);
    imageDisplayer.interrupThread();
    if (vgood.getRating() != null)     ((RatingBar)findViewById(R.id.vgood_rating)).setRating(vgood.getRating());
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 80

From project BSPAN---Bluetooth-Sensor-Processing-for-Android, under directory /AndroidSpineServer/src/spine/datamodel/serviceMessages/.

Source file: ServiceInfoMessage.java

  15 
vote

public String toString(){
  String date=DateFormat.getDateInstance(DateFormat.LONG).format(new Date());
  String time=DateFormat.getTimeInstance(DateFormat.LONG).format(new Date());
  String fin=date + " " + time;
  return super.toString() + "\n Time: " + fin;
}
 

Example 81

From project Calendar-Application, under directory /com/toedter/calendar/.

Source file: JSpinnerDateEditor.java

  15 
vote

public JSpinnerDateEditor(){
  super(new SpinnerDateModel());
  dateFormatter=(SimpleDateFormat)DateFormat.getDateInstance(DateFormat.MEDIUM);
  ((JSpinner.DateEditor)getEditor()).getTextField().addFocusListener(this);
  DateUtil dateUtil=new DateUtil();
  setMinSelectableDate(dateUtil.getMinSelectableDate());
  setMaxSelectableDate(dateUtil.getMaxSelectableDate());
  ((JSpinner.DateEditor)getEditor()).getTextField().setFocusLostBehavior(JFormattedTextField.PERSIST);
  addChangeListener(this);
}
 

Example 82

From project callmeter, under directory /src/de/ub0r/android/callmeter/ui/.

Source file: Common.java

  15 
vote

/** 
 * Format a  {@link Calendar}.
 * @param context {@link Context}
 * @param cal {@link Calendar}
 * @return formated date
 */
public static String formatDate(final Context context,final Calendar cal){
  if (dateFormat == null) {
    if (dateFormater == null) {
      dateFormater=android.text.format.DateFormat.getDateFormat(context);
    }
    return dateFormater.format(cal.getTime());
  }
 else {
    return String.format(dateFormat,cal,cal,cal);
  }
}
 

Example 83

From project caseconductor-platform, under directory /utest-common/src/main/java/com/utest/util/.

Source file: DateUtil.java

  15 
vote

/** 
 * Returns a correctly formatted String representing a Date, according to the Locale but forcing 4-digit years.
 */
public static String dateToString(final Date date,final Locale locale){
  final SimpleDateFormat df=(SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT,locale);
  final String pattern=DateUtil.formatYear(df.toPattern());
  final SimpleDateFormat dateFormat=new SimpleDateFormat(pattern);
  final String dateStr=dateFormat.format(date);
  return dateStr;
}
 

Example 84

From project com.idega.content, under directory /src/java/com/idega/content/themes/helpers/business/.

Source file: ThemeChangerBean.java

  15 
vote

private String getDummyArticle(Locale locale,String title,String body,boolean addImage){
  IWTimestamp timestamp=new IWTimestamp(new Date());
  StringBuilder content=new StringBuilder(CONTENT_PARAGRAPH_TITLE).append(title).append(CONTENT_PARAGRAPH_DATE);
  content.append(timestamp.getLocaleDate(locale,DateFormat.MEDIUM)).append(CONTENT_PARAGRAPH_LINK);
  if (addImage) {
    content.append("<div class=\"image-right\">").append(IMAGE_START).append(ThemesConstants.SINGLE_QUOTE);
    content.append(ThemesConstants.BASE_THEME_IMAGES);
    content.append(ThemesConstants.THEME_IMAGES.get(helper.getRandomNumber(ThemesConstants.THEME_IMAGES.size())));
    content.append(ThemesConstants.SINGLE_QUOTE).append(CoreConstants.SPACE).append(IMAGE_END).append("</div>");
  }
  content.append(body);
  content.append("<div class=\"content_item_comments_style\">").append("<div>").append("<a href=\"javascript:void(0)\">Comments(").append(helper.getRandomNumber(20)).append(")</a>").append(" ").append("<a href=\"javascript:void(0)\">").append("<img title=\"Atom feed\" src=\"").append(ContentUtil.getBundle().getVirtualPathWithFileNameString("images/feed.png")).append("\" name=\"Atom feed\" alt=\"\"/>").append("</a>").append("</div>").append("<div>").append("<a href=\"javascript:void(0)\">Add your comment</a>").append("</div>").append("</div>");
  content.append(CONTENT_PARAGRAPH_END).append(CONTENT_PARAGRAPH_END);
  return content.toString();
}
 

Example 85

From project CommitCoin, under directory /src/commitcoin/.

Source file: CommitCoinDownloadListener.java

  15 
vote

/** 
 * Called when download progress is made.
 * @param pct  the percentage of chain downloaded, estimated
 * @param date the date of the last block downloaded
 */
protected void progress(double pct,int blocksSoFar,Date date){
  log.info(String.format("Chain download %d%% done with %d blocks to go, block date %s",(int)pct,blocksSoFar,DateFormat.getDateTimeInstance().format(date)));
  if (print) {
    System.out.println(String.format("Chain download %d%% done with %d blocks to go, block date %s",(int)pct,blocksSoFar,DateFormat.getDateTimeInstance().format(date)));
  }
}
 

Example 86

From project components, under directory /camel/camel-core/src/main/java/org/switchyard/component/camel/config/model/v1/.

Source file: V1BaseCamelBindingModel.java

  15 
vote

protected final Date getDateConfig(String configName,DateFormat format){
  String value=getConfig(configName);
  if (value == null) {
    return null;
  }
 else {
    try {
      return format.parse(value);
    }
 catch (    java.text.ParseException parseEx) {
      throw new IllegalArgumentException("Failed to parse " + configName + " as a date.",parseEx);
    }
  }
}
 

Example 87

From project dawn-workflow, under directory /org.dawb.passerelle.common/src/org/dawb/passerelle/common/actors/.

Source file: AbstractDataMessageTransformer.java

  15 
vote

private DataMessageComponent getDespatch() throws ProcessingException {
  try {
    ActorUtils.setActorExecuting(this,true);
    final DataMessageComponent despatch=getTransformedMessage(cache);
    if (despatch != null)     setDataNames(despatch,cache);
    if (despatch == null)     return null;
    despatch.putScalar("operation.time." + getName(),DateFormat.getDateTimeInstance().format(new Date()));
    despatch.putScalar("operation.type." + getName(),getOperationName());
    return despatch;
  }
  finally {
    ActorUtils.setActorExecuting(this,false);
  }
}
 

Example 88

From project dev-examples, under directory /irc-client/src/main/java/org/ircclient/controller/.

Source file: ChatBean.java

  15 
vote

@Override protected void onMessage(String channel,String sender,String login,String hostname,String message){
  try {
    Message messageObject=new Message(message,sender,DateFormat.getInstance().format(new Date()));
    getTopicsContext().publish(new TopicKey("chat",getMessagesSubtopic()),messageObject);
  }
 catch (  MessageException e) {
    LOGGER.error(e.getMessage(),e);
  }
}
 

Example 89

From project DownloadProvider, under directory /src/com/mozillaonline/providers/downloads/ui/.

Source file: DownloadAdapter.java

  15 
vote

public DownloadAdapter(Context context,Cursor cursor,DownloadSelectListener selectionListener){
  super(context,cursor);
  mContext=context;
  mCursor=cursor;
  mResources=mContext.getResources();
  mDownloadSelectionListener=selectionListener;
  mDateFormat=DateFormat.getDateInstance(DateFormat.SHORT);
  mTimeFormat=DateFormat.getTimeInstance(DateFormat.SHORT);
  mIdColumnId=cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
  mTitleColumnId=cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE);
  mStatusColumnId=cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
  mReasonColumnId=cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);
  mTotalBytesColumnId=cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
  mCurrentBytesColumnId=cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
  mMediaTypeColumnId=cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIA_TYPE);
  mDateColumnId=cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
}
 

Example 90

From project droolsjbpm-tools, under directory /drools-eclipse/org.jbpm.eclipse.task/src/main/java/org/jbpm/eclipse/task/views/.

Source file: TaskView.java

  15 
vote

public String getColumnText(Object obj,int index){
  if (obj instanceof TaskSummary) {
    TaskSummary taskSummary=(TaskSummary)obj;
switch (index) {
case 0:
      return taskSummary.getName();
case 1:
    Status status=taskSummary.getStatus();
  return status == null ? null : STATUSSES.get(status);
case 2:
User user=taskSummary.getActualOwner();
if (user == null) {
return null;
}
return user.getId();
case 3:
return DateFormat.getDateTimeInstance().format(taskSummary.getCreatedOn());
case 4:
return taskSummary.getDescription();
default :
throw new IllegalArgumentException("Unknown column index: " + index);
}
}
return getText(obj);
}
 

Example 91

From project DTE, under directory /src/cl/nic/dte/util/.

Source file: XMLUtil.java

  15 
vote

/** 
 * Verifica si una firma XML embedida es v&aacute;lida seg&uacute;n define el est&aacute;ndar XML Signature (<a href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core Validation</a>), y si el certificado era v&aacute;lido en la fecha dada. <p> Esta rutina <b>NO</b> verifica si el certificado embedido en &lt;KeyInfo&gt; es v&aacute;lido (eso debe verificarlo con la autoridad certificadora que emiti&oacute; el certificado), pero si verifica que la llave utilizada para verificar corresponde a la contenida en el certificado.
 * @param xml el nodo &lt;Signature&gt;
 * @param date una fecha en la que se verifica la validez del certificado
 * @return el resultado de la verificaci&oacute;n
 * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext)
 * @see cl.nic.dte.VerifyResult
 * @see cl.nic.dte.extension.DTEDefTypeExtensionHandler
 * @see #getCertificate(XMLSignature)
 */
public static VerifyResult verifySignature(Node xml,Date date){
  try {
    XMLSignatureFactory fac=XMLSignatureFactory.getInstance("DOM");
    KeyValueKeySelector ksel=new KeyValueKeySelector();
    DOMValidateContext valContext=new DOMValidateContext(ksel,xml);
    XMLSignature signature=fac.unmarshalXMLSignature(valContext);
    X509Certificate x509=getCertificate(signature);
    if (x509 == null) {
      return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG,false,Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NO509")));
    }
    try {
      x509.checkValidity(date);
    }
 catch (    CertificateExpiredException e) {
      String message=Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID");
      message=message.replaceAll("%1",DateFormat.getDateInstance().format(date));
      message=message.replaceAll("%2",DateFormat.getDateInstance().format(x509.getNotBefore()));
      message=message.replaceAll("%3",DateFormat.getDateInstance().format(x509.getNotAfter()));
      return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG,false,message));
    }
catch (    CertificateNotYetValidException e) {
      String message=Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID");
      message=message.replaceAll("%1",DateFormat.getDateInstance().format(date));
      message=message.replaceAll("%2",DateFormat.getDateInstance().format(x509.getNotBefore()));
      message=message.replaceAll("%3",DateFormat.getDateInstance().format(x509.getNotAfter()));
      return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG,false,message));
    }
    return (verifySignature(signature,valContext));
  }
 catch (  MarshalException e1) {
    return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG,false,Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNMARSHAL") + ": " + e1.getMessage()));
  }
}
 

Example 92

From project EasyBan, under directory /src/uk/org/whoami/easyban/commands/.

Source file: BanInfoCommand.java

  15 
vote

@Override protected void execute(CommandSender cs,Command cmnd,String cmd,String[] args){
  if (args.length == 0) {
    return;
  }
  HashMap<String,String> info=database.getBanInformation(args[0]);
  if (info == null) {
    cs.sendMessage(args[0] + m._(" is not banned"));
    return;
  }
  cs.sendMessage(args[0] + m._(" is banned"));
  if (info.containsKey("admin")) {
    cs.sendMessage(m._("Admin: ") + info.get("admin"));
  }
  if (info.containsKey("reason")) {
    cs.sendMessage(m._("Reason: ") + info.get("reason"));
  }
  if (info.containsKey("until")) {
    Long unix=new Long(info.get("until"));
    if (unix != 100000) {
      Date until=new Date(unix);
      cs.sendMessage(m._("Until: ") + DateFormat.getDateTimeInstance().format(until));
    }
  }
}
 

Example 93

From project Eclipse, under directory /com.mobilesorcery.sdk.profiling.ui/src/com/mobilesorcery/sdk/profiling/ui/views/.

Source file: ProfilingSessionLabelProvider.java

  15 
vote

public String getText(Object element){
  if (element instanceof IProfilingSession) {
    IProfilingSession session=(IProfilingSession)element;
    Calendar timestamp=session.getStartTime();
    String timestampStr=DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.LONG).format(timestamp.getTime());
    return session.getName() + " " + timestampStr;
  }
 else {
    return super.getText(element);
  }
}
 

Example 94

From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.dashboard.ui/src/org/springsource/ide/eclipse/dashboard/internal/ui/editors/.

Source file: FeedsLabelProvider.java

  15 
vote

public String getColumnText(Object element,int index){
  if (element instanceof StubSyndEntryImpl) {
    return removeHtmlEntities(((StubSyndEntryImpl)element).getText());
  }
  if (element instanceof SyndEntry) {
    SyndEntry entry=(SyndEntry)element;
    SyndFeed feed=feedsMap.get(entry);
    if (feed == null) {
      return null;
    }
    String title=entry.getTitle();
    Date entryDate=new Date(0);
    if (entry.getUpdatedDate() != null) {
      entryDate=entry.getUpdatedDate();
    }
 else {
      entryDate=entry.getPublishedDate();
    }
    String dateString="";
    if (entryDate != null) {
      dateString=DateFormat.getDateInstance(DateFormat.SHORT).format(entryDate);
    }
    String entryAuthor="";
    if (entry.getAuthor() != null && entry.getAuthor().trim() != "") {
      entryAuthor=" by " + entry.getAuthor();
    }
    if (feedType.equals(DashboardMainPage.FeedType.BLOG) && dateString.length() > 0 && entryAuthor.length() > 0) {
      return removeHtmlEntities(title + " (" + dateString+ entryAuthor+ ")");
    }
    return removeHtmlEntities(title);
  }
  return null;
}
 

Example 95

From project elephant-twin, under directory /com.twitter.elephanttwin/src/main/java/com/twitter/elephanttwin/util/.

Source file: DateUtil.java

  15 
vote

/** 
 * Parse date with using given format. Returns null in case of errors.
 */
public static Calendar fromString(String dateStr,DateFormat df){
  try {
    return fromDate(df.parse(dateStr));
  }
 catch (  ParseException e) {
    LOG.warn("Could not parse date " + dateStr + " with dateformat "+ df,e);
    return null;
  }
}