Java Code Examples for java.text.SimpleDateFormat

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, under directory /AndroidNolesCore/src/util/.

Source file: News.java

  43 
vote

private SimpleDateFormat getDateFormat(String format){
  SimpleDateFormat sdf=mThreadDate.get();
  if (sdf == null) {
    sdf=new SimpleDateFormat(format,Locale.US);
    mThreadDate.set(sdf);
  }
  return sdf;
}
 

Example 2

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

Source file: ClinicaltrialsImporter.java

  41 
vote

private static Date guessDate(DateStruct startDate2){
  Date startDate=null;
  SimpleDateFormat sdf=new SimpleDateFormat("MMM yyyy");
  try {
    if (startDate2 != null)     startDate=sdf.parse(startDate2.getContent());
  }
 catch (  ParseException e) {
    System.err.println("ClinicalTrialsImporter:: Couldn't parse date. Left empty.");
  }
  return startDate;
}
 

Example 3

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/.

Source file: Utils.java

  40 
vote

/** 
 * Replace the time and date to the format given in the config with the corresponding date and time
 * @author Lathanael
 * @param
 * @return timeFormatted
 */
public static String replaceDateAndTimeFormat(final Date date){
  String timeFormatted="";
  final String format=ConfigEnum.DT_FORMAT.getString();
  final SimpleDateFormat formater=new SimpleDateFormat(format);
  final Date serverTime=date;
  timeFormatted=formater.format(serverTime);
  return timeFormatted;
}
 

Example 4

From project AndroidSensorLogger, under directory /libraries/opencsv-2.3-src-with-libs/opencsv-2.3/src/au/com/bytecode/opencsv/.

Source file: ResultSetHelperService.java

  40 
vote

private String handleDate(ResultSet rs,int columnIndex) throws SQLException {
  java.sql.Date date=rs.getDate(columnIndex);
  String value=null;
  if (date != null) {
    SimpleDateFormat dateFormat=new SimpleDateFormat("dd-MMM-yyyy");
    value=dateFormat.format(date);
  }
  return value;
}
 

Example 5

From project Absolute-Android-RSS, under directory /src/com/AA/Other/.

Source file: DateFunctions.java

  38 
vote

/** 
 * Creates a Calendar object based off a string with this format <Day name:3 letters>, DD <Month name: 3 letters> YYYY HH:MM:SS +0000
 * @param date - The string we are to convert to a calendar date
 * @return - The calendar date object that this string represents
 */
public static Calendar makeDate(String date){
  Date d=null;
  Calendar calendar=Calendar.getInstance();
  try {
    SimpleDateFormat format=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    d=format.parse(date);
    calendar.setTime(d);
  }
 catch (  ParseException e) {
    e.printStackTrace();
  }
  return calendar;
}
 

Example 6

From project AdServing, under directory /modules/db/src/main/java/test/ad/date/.

Source file: DateParse.java

  37 
vote

public static void main(String[] args) throws Exception {
  SimpleDateFormat df=new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
  Date d=df.parse("2010.06.25.08.36.33");
  System.out.println(DateTools.dateToString(d,Resolution.SECOND));
  System.out.println(DateTools.stringToDate(DateTools.dateToString(d,Resolution.SECOND)).toString());
  System.out.println(d.toString());
  System.out.println(new Date().toString());
}
 

Example 7

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/controller/.

Source file: BaseFormController.java

  37 
vote

/** 
 * Set up a custom property editor for converting form inputs to real objects.
 * @param request the current request
 * @param binder the data binder
 */
@InitBinder protected void initBinder(final HttpServletRequest request,final ServletRequestDataBinder binder){
  binder.registerCustomEditor(Integer.class,null,new CustomNumberEditor(Integer.class,null,true));
  binder.registerCustomEditor(Long.class,null,new CustomNumberEditor(Long.class,null,true));
  binder.registerCustomEditor(byte[].class,new ByteArrayMultipartFileEditor());
  final SimpleDateFormat dateFormat=new SimpleDateFormat(this.getText("date.format",request.getLocale()));
  dateFormat.setLenient(false);
  binder.registerCustomEditor(Date.class,null,new CustomDateEditor(dateFormat,true));
}
 

Example 8

From project andlytics, under directory /src/com/github/andlyticsproject/.

Source file: AdmobActivity.java

  37 
vote

private void loadChartData(List<Admob> statsForApp){
  if (statsForApp != null && statsForApp.size() > 0) {
    updateCharts(statsForApp);
    SimpleDateFormat dateFormat=new SimpleDateFormat(Preferences.getDateFormatLong(AdmobActivity.this));
    if (statsForApp.size() > 0) {
      timetext=dateFormat.format(statsForApp.get(0).getDate()) + " - " + dateFormat.format(statsForApp.get(statsForApp.size() - 1).getDate());
      updateChartHeadline();
    }
  }
}
 

Example 9

From project android-bankdroid, under directory /src/com/liato/bankdroid/.

Source file: Helpers.java

  37 
vote

/** 
 * Determines what year a transaction belongs to. If the given <code>day</code> of the given <code>month</code> for the current year is in the future the transaction is probably from last year.
 * @param month     The month, where January is 1.
 * @param day       The day of the month, starting from 1.
 * @return          An ISO 8601 formatted date.
 */
public static String getTransactionDate(int month,int day){
  month--;
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  Calendar cal=Calendar.getInstance();
  int currentYear=cal.get(Calendar.YEAR);
  cal.set(currentYear,month,day,0,0);
  if (cal.getTime().after(Calendar.getInstance().getTime())) {
    cal.add(Calendar.YEAR,-1);
  }
  return sdf.format(cal.getTime());
}
 

Example 10

From project android_packages_apps_Nfc, under directory /src/com/android/nfc/handover/.

Source file: HandoverManager.java

  37 
vote

synchronized File generateMultiplePath(String beamRoot){
  String format="yyyy-MM-dd";
  SimpleDateFormat sdf=new SimpleDateFormat(format);
  String newPath=beamRoot + "beam-" + sdf.format(new Date());
  File newFile=new File(newPath);
  int count=0;
  while (newFile.exists()) {
    newPath=beamRoot + "beam-" + sdf.format(new Date())+ "-"+ Integer.toString(count);
    newFile=new File(newPath);
    count++;
  }
  return newFile;
}
 

Example 11

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

Source file: DateFormPropertyRenderer.java

  36 
vote

@Override public String getFieldValue(FormProperty formProperty,Field field){
  PopupDateField dateField=(PopupDateField)field;
  Date selectedDate=(Date)dateField.getValue();
  if (selectedDate != null) {
    String datePattern=(String)formProperty.getType().getInformation("datePattern");
    SimpleDateFormat dateFormat=new SimpleDateFormat(datePattern);
    return dateFormat.format(selectedDate);
  }
  return null;
}
 

Example 12

From project akela, under directory /src/main/java/com/mozilla/pig/filter/date/.

Source file: DateInRange.java

  36 
vote

public DateInRange(String startDateStr,String endDateStr,String dateEntryFormat) throws ParseException {
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  Date startDate=sdf.parse(startDateStr);
  startTime=DateUtil.getTimeAtResolution(startDate.getTime(),Calendar.DATE);
  Date endDate=sdf.parse(endDateStr);
  endTime=DateUtil.getEndTimeAtResolution(endDate.getTime(),Calendar.DATE);
  edf=new SimpleDateFormat(dateEntryFormat);
}
 

Example 13

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/.

Source file: NewsActivity.java

  36 
vote

@Override protected String getCategoryOfItem(int itemId){
  String date=super.getCategoryOfItem(itemId).substring(0,10);
  Log.d(Constants.PROJECT_TAG,date);
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  new Date(10,10,10);
  try {
    return ((String)DateFormat.format("d MMMM yyyy",sdf.parse(date)));
  }
 catch (  ParseException e) {
    Log.e(Constants.PROJECT_TAG,"Error parsing date",e);
  }
  return date;
}
 

Example 14

From project AmDroid, under directory /AmDroid/src/main/java/com/jaeckel/amenoid/fragments/.

Source file: AmenDetailFragment.java

  36 
vote

public static String format(Date firstPostedAt){
  SimpleDateFormat fmt=new SimpleDateFormat("dd. MMMMM yyyy - HH:mm");
  if (firstPostedAt != null) {
    return fmt.format(firstPostedAt);
  }
  return "<date unknown>";
}
 

Example 15

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/aladdin/test/.

Source file: Log.java

  36 
vote

/** 
 * ????????????????
 * @return
 */
private static String getLogName(){
  StringBuffer logPath=new StringBuffer();
  logPath.append(System.getProperty("user.home"));
  logPath.append("\\" + filename);
  File file=new File(logPath.toString());
  if (!file.exists())   file.mkdir();
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  logPath.append("\\" + sdf.format(new Date()) + ".log");
  System.out.println(logPath.toString());
  return logPath.toString();
}
 

Example 16

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/scheduling/.

Source file: TimeServerImpl.java

  36 
vote

public String formatCurrentTime(String formatString){
  SimpleDateFormat simpleDateFormat;
  try {
    simpleDateFormat=new SimpleDateFormat(formatString);
  }
 catch (  IllegalArgumentException e) {
    throw new IllegalArgumentException("Dateformat string had a problem :" + formatString + " "+ e.getMessage(),e);
  }
  return simpleDateFormat.format(getCurrentDate());
}
 

Example 17

From project android-client, under directory /xwiki-android-core/src/org/xwiki/android/xmodel/xobjects/.

Source file: XDateProperty.java

  36 
vote

public String toString(){
  String fmt=getDateFormat();
  if (fmt != null) {
    SimpleDateFormat sdf=new SimpleDateFormat(fmt);
    return sdf.format(value);
  }
  if (value != null) {
    return value.toGMTString();
  }
 else {
    return null;
  }
}
 

Example 18

From project android-joedayz, under directory /Proyectos/AndroidFoursquare/src/com/mycompany/fsq/.

Source file: FoursquareApp.java

  36 
vote

private String timeMilisToString(long milis){
  SimpleDateFormat sd=new SimpleDateFormat("yyyyMMdd");
  Calendar calendar=Calendar.getInstance();
  calendar.setTimeInMillis(milis);
  return sd.format(calendar.getTime());
}
 

Example 19

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: ErrorReporter.java

  36 
vote

private void sendEmail(String body){
  Intent sendIntent=new Intent(Intent.ACTION_SEND);
  SimpleDateFormat df1=new SimpleDateFormat("EEE MMM dd HH:mm:ss ",Locale.US);
  SimpleDateFormat df2=new SimpleDateFormat(" yyyy",Locale.US);
  Date ts=new Date();
  TimeZone tz=TimeZone.getDefault();
  String subject=String.format("Bug Report on %s%s%s",df1.format(ts),tz.getID(),df2.format(ts));
  sendIntent.putExtra(Intent.EXTRA_EMAIL,new String[]{getString(R.string.error_email)});
  sendIntent.putExtra(Intent.EXTRA_TEXT,body);
  sendIntent.putExtra(Intent.EXTRA_SUBJECT,subject);
  sendIntent.setType("message/rfc822");
  startActivity(Intent.createChooser(sendIntent,"Send Error Report"));
}
 

Example 20

From project ant4eclipse, under directory /org.ant4eclipse.lib.pde/src/org/ant4eclipse/lib/pde/tools/.

Source file: PdeBuildHelper.java

  36 
vote

/** 
 * Returns a qualifier that should be used if the plugin's version contains the word "qualifier" as qualifier. <p> <p> The context qualifier can explizitly set by using the ant4eclipse.contextQualifier System property. Note that this is intended mainly for testing, since otherwise you can specify a qualifier in the build.properties
 */
public static final String getResolvedContextQualifier(){
  if (CONTEXT_QUALIFIER == null) {
    CONTEXT_QUALIFIER=System.getProperty(CONTEXT_QUALIFIER_PROPERTY);
    if (CONTEXT_QUALIFIER == null) {
      SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmm");
      CONTEXT_QUALIFIER=simpleDateFormat.format(new Date());
    }
  }
  return CONTEXT_QUALIFIER;
}
 

Example 21

From project any23, under directory /core/src/main/java/org/apache/any23/rdf/.

Source file: RDFUtils.java

  36 
vote

/** 
 * This method allows to obtain an <a href="http://www.w3.org/TR/xmlschema-2/#date">XML Schema</a> compliant date providing a textual representation of a date and textual a pattern for parsing it.
 * @param dateToBeParsed the String containing the date.
 * @param format the pattern as descibed in {@link java.text.SimpleDateFormat}
 * @return a {@link String} representing the date
 * @throws java.text.ParseException
 * @throws javax.xml.datatype.DatatypeConfigurationException
 */
public static String getXSDDate(String dateToBeParsed,String format) throws ParseException, DatatypeConfigurationException {
  SimpleDateFormat simpleDateFormat=new SimpleDateFormat(format);
  Date date=simpleDateFormat.parse(dateToBeParsed);
  GregorianCalendar gc=new GregorianCalendar();
  gc.setTime(date);
  XMLGregorianCalendar xml=DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
  xml.setTimezone(0);
  return xml.toString();
}
 

Example 22

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

Source file: XmlTestReport.java

  36 
vote

private static String timestamp(){
  SimpleDateFormat dateFormat=new SimpleDateFormat(DATETIME_PATTERN);
  dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
  dateFormat.setLenient(true);
  return dateFormat.format(new Date());
}
 

Example 23

From project autopsy, under directory /thunderbirdparser/src/org/sleuthkit/autopsy/thunderbirdparser/.

Source file: ThunderbirdMetadata.java

  36 
vote

private static DateFormat createDateFormat(String format,TimeZone timezone){
  SimpleDateFormat sdf=new SimpleDateFormat(format,new DateFormatSymbols(Locale.US));
  if (timezone != null) {
    sdf.setTimeZone(timezone);
  }
  return sdf;
}
 

Example 24

From project aviator, under directory /src/main/java/com/googlecode/aviator/runtime/function/system/.

Source file: Date2StringFunction.java

  36 
vote

@Override public AviatorObject call(Map<String,Object> env,AviatorObject arg1,AviatorObject arg2){
  Date date=(Date)arg1.getValue(env);
  String format=FunctionUtils.getStringValue(arg2,env);
  SimpleDateFormat dateFormat=DateFormatCache.getOrCreateDateFormat(format);
  return new AviatorString(dateFormat.format(date));
}
 

Example 25

From project b3log-latke, under directory /latke/src/test/java/org/b3log/latke/testhelper/.

Source file: MockConverSupport.java

  36 
vote

@Override public Object convert(final String pName,final Object value,final Class<?> clazz){
  if (clazz == java.util.Date.class) {
    final String data=(String)value;
    final SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
    try {
      return format.parse(data);
    }
 catch (    final ParseException e) {
      e.printStackTrace();
    }
  }
  return super.convert(pName,value,clazz);
}
 

Example 26

From project babel, under directory /src/babel/content/corpora/accessors/.

Source file: EuroParlCorpusAccessor.java

  36 
vote

public InputStreamReader getCurDayReader(){
  InputStreamReader retReader=null;
  SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd");
  m_fileNameFilter.setPrefix(FILENAME_PREFIX + sdf.format(m_curDate.getTime()));
  m_files.gather();
  try {
    retReader=new InputStreamReader(new SequenceInputStream(m_files),m_encoding);
  }
 catch (  Exception e) {
    throw new IllegalStateException(e.toString());
  }
  return retReader;
}
 

Example 27

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: MavenArtifact.java

  36 
vote

public Date getTimestampAsDate() throws IOException {
  long lastModified=getTimestamp();
  SimpleDateFormat bdf=getDateFormat();
  Date tsDate;
  try {
    tsDate=bdf.parse(bdf.format(new Date(lastModified)));
  }
 catch (  ParseException pe) {
    throw new IOException(pe.getMessage());
  }
  return tsDate;
}
 

Example 28

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

Source file: CalendarUtil.java

  36 
vote

public static SimpleDateFormat newSimpleDateFormat(String pattern,Locale locale,TimeZone zone){
  SimpleDateFormat df=new SimpleDateFormat(pattern,locale);
  df.setTimeZone(zone);
  df.setCalendar(newCalendar(zone));
  return df;
}
 

Example 29

From project bdd-security, under directory /src/main/java/net/continuumsecurity/runner/.

Source file: StoryRunner.java

  36 
vote

private void copyResultsToStampedReportsDir() throws IOException {
  SimpleDateFormat formatter=new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss",Locale.getDefault());
  File dirName=new File(REPORTS_DIR + File.separator + formatter.format(new Date()));
  FileUtils.forceMkdir(dirName);
  FileUtils.copyDirectory(new File(LATEST_REPORTS),dirName);
}
 

Example 30

From project beam-meris-icol, under directory /src/main/java/org/esa/beam/meris/icol/utils/.

Source file: LandsatUtils.java

  36 
vote

/** 
 * Converts a date string from yyyy-mm-dd to dd-MMM-yyyy
 * @param input
 * @return converted
 */
public static String convertDate(String input){
  String converted="";
  try {
    SimpleDateFormat sdfSource=new SimpleDateFormat("yyyy-MM-dd");
    Date date=sdfSource.parse(input);
    SimpleDateFormat sdfDestination=new SimpleDateFormat("dd-MMM-yyyy");
    converted=sdfDestination.format(date);
    System.out.println("Converted date is : " + converted);
  }
 catch (  ParseException pe) {
    System.out.println("Parse Exception : " + pe.getMessage());
  }
  return converted;
}
 

Example 31

From project big-data-plugin, under directory /test-src/org/pentaho/hbase/.

Source file: HBaseValueMetaTest.java

  36 
vote

@Test public void testDecodeKeyValueSignedDate() throws Exception {
  CommonHBaseBytesUtil bu=new CommonHBaseBytesUtil();
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  Date aDate=sdf.parse("1969-08-28");
  long negTime=aDate.getTime();
  long negTimeOrig=negTime;
  negTime^=(1L << 63);
  byte[] testVal=bu.toBytes(negTime);
  Mapping dummy=new Mapping("DummyTable","DummyMapping","MyKey",Mapping.KeyType.DATE);
  Object result=HBaseValueMeta.decodeKeyValue(testVal,dummy,bu);
  assertTrue(result instanceof Date);
  assertEquals(((Date)result).getTime(),negTimeOrig);
}
 

Example 32

From project Blitz, under directory /src/com/laxser/blitz/controllers/.

Source file: ToolsController.java

  36 
vote

@Get("startupInfo") public String startupInfo(){
  SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String time=simpleDateFormat.format(startupTime);
  String startup=String.format("<strong>startup</strong>=%s",time);
  return Utils.wrap(startup);
}
 

Example 33

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

Source file: AbstractGenerator.java

  35 
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 34

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

Source file: TimeChart.java

  35 
vote

/** 
 * Returns the date format pattern to be used, based on the date range.
 * @param start the start date in milliseconds
 * @param end the end date in milliseconds
 * @return the date format
 */
private DateFormat getDateFormat(double start,double end){
  if (mDateFormat != null) {
    SimpleDateFormat format=null;
    try {
      format=new SimpleDateFormat(mDateFormat);
      return format;
    }
 catch (    Exception e) {
    }
  }
  DateFormat format=SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM);
  double diff=end - start;
  if (diff > DAY && diff < 5 * DAY) {
    format=SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT,SimpleDateFormat.SHORT);
  }
 else   if (diff < DAY) {
    format=SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM);
  }
  return format;
}
 

Example 35

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/validation/.

Source file: DateConverter.java

  35 
vote

public DateConverter(String attributeName,String format){
  this.attributeName=attributeName;
  this.message="attribute {0} does not conform to format: {1}";
  df=new SimpleDateFormat(format);
  this.format=format;
}
 

Example 36

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

Source file: HeadsUpConfiguration.java

  35 
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 37

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

Source file: LocalTrendsDeserializer.java

  35 
vote

private static Date toDate(String dateString){
  try {
    return new SimpleDateFormat(LOCAL_TREND_DATE_FORMAT).parse(dateString);
  }
 catch (  ParseException e) {
    return null;
  }
}
 

Example 38

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

Source file: DtppActivity.java

  35 
vote

protected void showDtppSummary(Cursor[] result){
  LinearLayout topLayout=(LinearLayout)findViewById(R.id.dtpp_detail_layout);
  Cursor cycle=result[1];
  cycle.moveToFirst();
  mTppCycle=cycle.getString(cycle.getColumnIndex(DtppCycle.TPP_CYCLE));
  String from=cycle.getString(cycle.getColumnIndex(DtppCycle.FROM_DATE));
  String to=cycle.getString(cycle.getColumnIndex(DtppCycle.TO_DATE));
  SimpleDateFormat df=new SimpleDateFormat("HHmm'Z' MM/dd/yy");
  df.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
  Date fromDate=null;
  Date toDate=null;
  try {
    fromDate=df.parse(from);
    toDate=df.parse(to);
  }
 catch (  ParseException e1) {
  }
  Date now=new Date();
  if (now.getTime() > toDate.getTime()) {
    mExpired=true;
  }
  RelativeLayout item=(RelativeLayout)inflate(R.layout.grouped_detail_item);
  TextView tv=(TextView)item.findViewById(R.id.group_name);
  LinearLayout layout=(LinearLayout)item.findViewById(R.id.group_details);
  tv.setText(String.format("Chart Cycle %s",mTppCycle));
  Cursor dtpp=result[2];
  dtpp.moveToFirst();
  String tppVolume=dtpp.getString(0);
  addRow(layout,"Volume",tppVolume);
  addRow(layout,"Valid",TimeUtils.formatDateRange(getActivity(),fromDate.getTime(),toDate.getTime()));
  if (mExpired) {
    addRow(layout,"WARNING: This chart cycle has expired.");
  }
  topLayout.addView(item,new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
}
 

Example 39

From project AlarmApp-Android, under directory /src/org/alarmapp/util/.

Source file: DateUtil.java

  35 
vote

private static SimpleDateFormat getFormatter(){
  if (formatter == null) {
    formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
  }
  return formatter;
}
 

Example 40

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

Source file: ChatApplication.java

  35 
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 41

From project almira-sample, under directory /almira-sample-webapp/src/main/java/almira/sample/web/.

Source file: AbstractBasePage.java

  35 
vote

/** 
 * Constructor.
 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value="SE_INNER_CLASS",justification="Cannot call getSession() from static inner class") AbstractBasePage(){
  super();
  add(new Label("pageTitle",new ResourceModel("catapult.title")));
  add(new BookmarkablePageLink<Void>("homeLink",IndexPage.class));
  add(new BookmarkablePageLink<Void>("adminLink",AdminPage.class));
  add(new LocaleDropDownPanel("localeSelectPanel",Arrays.asList(new Locale("es"),new Locale("de"),new Locale("en"),new Locale("fr"),new Locale("it"))));
  add(new Label("version",((MainApplication)getApplication()).getVersion()));
  add(new Label("session",new PropertyModel<String>(this,"session.id")));
  add(new SearchPanel("searchPanel"));
  add(new Label("footertext",footerTextService.getText()));
  add(new Label("clock",new Model<String>(){
    @Override public String getObject(){
      final SimpleDateFormat dateFormat=new SimpleDateFormat("dd-MM-yyyy | HH:mm:ss.mmm",getSession().getLocale());
      return dateFormat.format(new Date());
    }
  }
));
}
 

Example 42

From project and-bible, under directory /AndBible/src/org/apache/commons/lang/time/.

Source file: DateUtils.java

  35 
vote

/** 
 * <p>Parses a string representing a date by trying a variety of different parsers.</p> <p>The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.</p>
 * @param str  the date to parse, not null
 * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
 * @param lenient Specify whether or not date/time parsing is to be lenient.
 * @return the parsed date
 * @throws IllegalArgumentException if the date string or pattern array is null
 * @throws ParseException if none of the date patterns were suitable
 * @see java.util.Calender#isLenient()
 */
private static Date parseDateWithLeniency(String str,String[] parsePatterns,boolean lenient) throws ParseException {
  if (str == null || parsePatterns == null) {
    throw new IllegalArgumentException("Date and Patterns must not be null");
  }
  SimpleDateFormat parser=new SimpleDateFormat();
  parser.setLenient(lenient);
  ParsePosition pos=new ParsePosition(0);
  for (  String parsePattern : parsePatterns) {
    String pattern=parsePattern;
    if (parsePattern.endsWith("ZZ")) {
      pattern=pattern.substring(0,pattern.length() - 1);
    }
    parser.applyPattern(pattern);
    pos.setIndex(0);
    String str2=str;
    if (parsePattern.endsWith("ZZ")) {
      str2=str.replaceAll("([-+][0-9][0-9]):([0-9][0-9])$","$1$2");
    }
    Date date=parser.parse(str2,pos);
    if (date != null && pos.getIndex() == str2.length()) {
      return date;
    }
  }
  throw new ParseException("Unable to parse the date: " + str,-1);
}
 

Example 43

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

Source file: DateUtils.java

  35 
vote

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

Example 44

From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/example/android/samplesync/client/.

Source file: NetworkUtilities.java

  35 
vote

/** 
 * Fetches the list of friend data updates from the server
 * @param account The account being synced.
 * @param authtoken The authtoken stored in AccountManager for this account
 * @param lastUpdated The last time that sync was performed
 * @return list The list of updates received from the server.
 */
public static List<User> fetchFriendUpdates(Account account,String authtoken,Date lastUpdated) throws JSONException, ParseException, IOException, AuthenticationException {
  final ArrayList<User> friendList=new ArrayList<User>();
  final ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair(PARAM_USERNAME,account.name));
  params.add(new BasicNameValuePair(PARAM_PASSWORD,authtoken));
  if (lastUpdated != null) {
    final SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    params.add(new BasicNameValuePair(PARAM_UPDATED,formatter.format(lastUpdated)));
  }
  Log.i(TAG,params.toString());
  HttpEntity entity=null;
  entity=new UrlEncodedFormEntity(params);
  final HttpPost post=new HttpPost(FETCH_FRIEND_UPDATES_URI);
  post.addHeader(entity.getContentType());
  post.setEntity(entity);
  maybeCreateHttpClient();
  final HttpResponse resp=mHttpClient.execute(post);
  final String response=EntityUtils.toString(resp.getEntity());
  if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    final JSONArray friends=new JSONArray(response);
    Log.d(TAG,response);
    for (int i=0; i < friends.length(); i++) {
      friendList.add(User.valueOf(friends.getJSONObject(i)));
    }
  }
 else {
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
      Log.e(TAG,"Authentication exception in fetching remote contacts");
      throw new AuthenticationException();
    }
 else {
      Log.e(TAG,"Server error in fetching remote contacts: " + resp.getStatusLine());
      throw new IOException();
    }
  }
  return friendList;
}
 

Example 45

From project android-thaiime, under directory /latinime/src/com/sugree/inputmethod/latin/.

Source file: Utils.java

  35 
vote

private UsabilityStudyLogUtils(){
  mDate=new Date();
  mDateFormat=new SimpleDateFormat("dd MMM HH:mm:ss.SSS");
  HandlerThread handlerThread=new HandlerThread("UsabilityStudyLogUtils logging task",Process.THREAD_PRIORITY_BACKGROUND);
  handlerThread.start();
  mLoggingHandler=new Handler(handlerThread.getLooper());
}
 

Example 46

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

Source file: DayArrayAdapter.java

  35 
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 47

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/provider/.

Source file: BooksStore.java

  35 
vote

public ContentValues getContentValues(){
  final SimpleDateFormat format=new SimpleDateFormat("MMMM yyyy");
  final ContentValues values=new ContentValues();
  values.put(INTERNAL_ID,mStorePrefix + mInternalId);
  values.put(EAN,mEan);
  values.put(ISBN,mIsbn);
  values.put(TITLE,mTitle);
  values.put(AUTHORS,TextUtilities.join(mAuthors,", "));
  values.put(PUBLISHER,mPublisher);
  values.put(REVIEWS,TextUtilities.join(mDescriptions,"\n\n"));
  values.put(PAGES,mPages);
  if (mLastModified != null) {
    values.put(LAST_MODIFIED,mLastModified.getTimeInMillis());
  }
  values.put(PUBLICATION,mPublicationDate != null ? format.format(mPublicationDate) : "");
  values.put(DETAILS_URL,mDetailsUrl);
  values.put(TINY_URL,mImages.get(ImageSize.TINY));
  return values;
}
 

Example 48

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

Source file: SaveTrip.java

  35 
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 49

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

Source file: DefaultTypeAdapters.java

  35 
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 50

From project android_packages_apps_Gallery, under directory /src/com/android/camera/.

Source file: VideoCamera.java

  35 
vote

private void createVideoPath(){
  long dateTaken=System.currentTimeMillis();
  String title=createName(dateTaken);
  String displayName=title + ".3gp";
  String cameraDirPath=ImageManager.CAMERA_IMAGE_BUCKET_NAME;
  File cameraDir=new File(cameraDirPath);
  cameraDir.mkdirs();
  SimpleDateFormat dateFormat=new SimpleDateFormat(getString(R.string.video_file_name_format));
  Date date=new Date(dateTaken);
  String filepart=dateFormat.format(date);
  String filename=cameraDirPath + "/" + filepart+ ".3gp";
  ContentValues values=new ContentValues(7);
  values.put(Video.Media.TITLE,title);
  values.put(Video.Media.DISPLAY_NAME,displayName);
  values.put(Video.Media.DATE_TAKEN,dateTaken);
  values.put(Video.Media.MIME_TYPE,"video/3gpp");
  values.put(Video.Media.DATA,filename);
  mCameraVideoFilename=filename;
  Log.v(TAG,"Current camera video filename: " + mCameraVideoFilename);
  mCurrentVideoValues=values;
}
 

Example 51

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

Source file: SaveCopyTask.java

  35 
vote

public SaveCopyTask(Context context,Uri sourceUri,Callback callback){
  this.context=context;
  this.sourceUri=sourceUri;
  this.callback=callback;
  saveFileName=new SimpleDateFormat(TIME_STAMP_NAME).format(new Date(System.currentTimeMillis()));
}
 

Example 52

From project android_packages_inputmethods_LatinIME, under directory /java/src/com/android/inputmethod/latin/.

Source file: Utils.java

  35 
vote

private UsabilityStudyLogUtils(){
  mDate=new Date();
  mDateFormat=new SimpleDateFormat("dd MMM HH:mm:ss.SSS");
  HandlerThread handlerThread=new HandlerThread("UsabilityStudyLogUtils logging task",Process.THREAD_PRIORITY_BACKGROUND);
  handlerThread.start();
  mLoggingHandler=new Handler(handlerThread.getLooper());
}
 

Example 53

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

Source file: MainApp.java

  35 
vote

@Override public String getVersion(){
  String rev=getBuildRevision();
  Date date=getBuildDate();
  StringBuilder result=new StringBuilder();
  result.append(getVersionNumber());
  if (!"".equals(rev) || date != null) {
    result.append(" (");
    boolean added=false;
    if (!"".equals(rev)) {
      result.append("rev. ");
      result.append(rev);
      added=true;
    }
    if (date != null) {
      result.append(added ? ", built " : "");
      SimpleDateFormat d=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      result.append(d.format(date));
    }
    result.append(")");
  }
  return result.toString();
}
 

Example 54

From project Apertiurm-Androind-app-devlopment, under directory /ApertiumAndroid/src/org/apertium/android/SMS/.

Source file: SmsArrayAdapter.java

  35 
vote

@Override public View getView(int position,View convertView,ViewGroup parent){
  View v=convertView;
  if (v == null) {
    LayoutInflater vi=(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v=vi.inflate(id,null);
  }
  final SMSobject o=items.get(position);
  if (o != null) {
    TextView t1=(TextView)v.findViewById(R.id.TextView_Sender);
    TextView t2=(TextView)v.findViewById(R.id.TextView_Body);
    TextView t3=(TextView)v.findViewById(R.id.TextView_Date);
    SimpleDateFormat sdf=new SimpleDateFormat("dd MMM");
    Date resultdate=new Date(o.getDate());
    if (t1 != null)     t1.setText(o.getSender());
    if (t2 != null)     t2.setText(o.getBody());
    if (t3 != null)     t3.setText(sdf.format(resultdate));
  }
  return v;
}
 

Example 55

From project apps-for-android, under directory /Photostream/src/com/google/android/photostream/.

Source file: Flickr.java

  35 
vote

private boolean parseUpdated(XmlPullParser parser,Calendar reference) throws IOException, XmlPullParserException {
  int type;
  String name;
  final int depth=parser.getDepth();
  while (((type=parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
    if (type != XmlPullParser.START_TAG) {
      continue;
    }
    name=parser.getName();
    if (RESPONSE_TAG_UPDATED.equals(name)) {
      if (parser.next() == XmlPullParser.TEXT) {
        final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
          final String text=parser.getText().replace('T',' ').replace('Z',' ');
          final Calendar calendar=new GregorianCalendar();
          calendar.setTimeInMillis(format.parse(text).getTime());
          return calendar.after(reference);
        }
 catch (        ParseException e) {
        }
      }
    }
  }
  return false;
}
 

Example 56

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

Source file: CalendarEditor.java

  35 
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 57

From project ATHENA, under directory /src/main/java/com/synaptik/athena/.

Source file: AthenaTestSuite.java

  35 
vote

protected String getTimestamp(){
  String result="";
  long start=Long.MAX_VALUE;
  for (  AthenaTest test : tests) {
    if (test.result.start < start) {
      start=test.result.start;
    }
  }
  if (start == Long.MAX_VALUE) {
    start=System.currentTimeMillis();
  }
  Date d=new Date(start);
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
  result=sdf.format(d);
  return result;
}
 

Example 58

From project azure4j-blog-samples, under directory /ACSManagementService/src/com/persistent/azure/acs/.

Source file: RelyingPartyCreator.java

  35 
vote

/** 
 * Assigns relying party key and addresses to the relying party.
 * @param relyingParty
 * @param name
 * @throws Exception
 */
private void assignRelyingPartyKeyAndAddresses(RelyingParty relyingParty,String name) throws Exception {
  RelyingPartyKey relyingPartyKey=new RelyingPartyKey();
  relyingPartyKey.setDisplayName(name);
  relyingPartyKey.setType("X509Certificate");
  relyingPartyKey.setUsage("Signing");
  relyingPartyKey.setValue(getCertificateBytes(name));
  relyingPartyKey.setRelyingPartyId(relyingParty.getId());
  Calendar calendar=Calendar.getInstance();
  SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
  dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
  String startDate=dateFormat.format(calendar.getTime());
  relyingPartyKey.setStartDate(dateFormat.parse(startDate));
  calendar.add(Calendar.DAY_OF_YEAR,364);
  String endDate=dateFormat.format(calendar.getTime());
  relyingPartyKey.setEndDate(dateFormat.parse(endDate));
  relyingPartyKey.setPassword(certPassword.getBytes());
  relyingPartyKey.setIsPrimary(true);
  managementService.addEntity(relyingPartyKey);
  assignRealm(relyingParty);
  assignReturnURL(relyingParty);
}
 

Example 59

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

Source file: Meeting.java

  35 
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 60

From project BeeQueue, under directory /lib/src/hyperic-sigar-1.6.4/bindings/java/examples/.

Source file: Ps.java

  35 
vote

private static String getStartTime(long time){
  if (time == 0) {
    return "00:00";
  }
  long timeNow=System.currentTimeMillis();
  String fmt="MMMd";
  if ((timeNow - time) < ((60 * 60 * 24) * 1000)) {
    fmt="HH:mm";
  }
  return new SimpleDateFormat(fmt).format(new Date(time));
}
 

Example 61

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

Source file: MarketplaceCoupon.java

  35 
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 62

From project BetterShop_1, under directory /src/me/jascotty2/lib/bukkit/.

Source file: ServerInfo.java

  35 
vote

public static String serverRunTimeSpan(String startTime){
  Date uploadDate=null;
  try {
    SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
    uploadDate=formatter.parse(startTime.trim());
  }
 catch (  ParseException ex) {
    Logger.getAnonymousLogger().log(Level.SEVERE,"Error parsing log start date",ex);
    return ex.getMessage();
  }
  long sec=((new Date()).getTime() - uploadDate.getTime()) / 1000;
  int mon=(int)(sec / 2592000);
  sec-=mon * 2592000;
  int day=(int)(sec / 86400);
  sec-=day * 86400;
  int hr=(int)(sec / 3600);
  sec-=hr * 3600;
  int min=(int)(sec / 60);
  sec=sec % 60;
  String timeSpan="";
  if (mon > 0) {
    timeSpan+=mon + " Months, ";
  }
  if (day > 0) {
    timeSpan+=day + " Days, ";
  }
  if (hr > 0) {
    timeSpan+=hr + " Hours, ";
  }
  if (min > 0) {
    timeSpan+=min + " Minutes, ";
  }
  return timeSpan + sec + " Sec";
}
 

Example 63

From project Bifrost, under directory /src/main/java/com/craftfire/bifrost/scripts/forum/.

Source file: SMF.java

  35 
vote

@Override public void updateUser(ScriptUser user) throws SQLException {
  HashMap<String,Object> data=new HashMap<String,Object>();
  if (this.getVersionRanges()[0].inVersionRange(this.getVersion())) {
    data.put("membername",user.getUsername());
    data.put("realname",user.getNickname());
    data.put("emailaddress",user.getEmail());
    data.put("memberip",user.getRegIP());
    data.put("memberip2",user.getLastIP());
    data.put("dateregistered",user.getRegDate().getTime() / 1000);
    data.put("lastlogin",user.getLastLogin().getTime() / 1000);
  }
 else   if (this.getVersionRanges()[1].inVersionRange(this.getVersion())) {
    data.put("member_name",user.getUsername());
    data.put("real_name",user.getNickname());
    data.put("email_address",user.getEmail());
    data.put("member_ip",user.getRegIP());
    data.put("member_ip2",user.getLastIP());
    data.put("date_registered",user.getRegDate().getTime() / 1000);
    data.put("last_login",user.getLastLogin().getTime() / 1000);
  }
  data.put("avatar",user.getAvatarURL());
  if (user.getPassword().length() != 40) {
    data.put("passwd",hashPassword(user.getUsername(),user.getPassword()));
  }
  data.put("usertitle",user.getUserTitle());
  SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
  data.put("birthdate",format.format(user.getBirthday()));
  int genderID=0;
  if (user.getGender() != null && user.getGender() == Gender.FEMALE) {
    genderID=1;
  }
  data.put("gender",genderID);
  int activated=0;
  if (user.isActivated()) {
    activated=1;
  }
  data.put("is_activated",activated);
  this.getDataManager().updateFields(data,"members","`" + this.membernamefield + "` = '"+ user.getUsername()+ "'");
  data.clear();
}
 

Example 64

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

Source file: BioportalRssModuleParser.java

  35 
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 65

From project Birthdays, under directory /src/com/rexmenpara/birthdays/util/.

Source file: DateUtility.java

  35 
vote

public static Date parseDate(String dateString) throws ParseException {
  Date date=null;
  try {
    java.text.DateFormat srcFormatter=SimpleDateFormat.getInstance();
    date=srcFormatter.parse(dateString);
  }
 catch (  ParseException e) {
    if (dateString.matches(DateFormat.GENERIC)) {
      SimpleDateFormat srcFormatter=new SimpleDateFormat("yyyy-MM-dd");
      date=srcFormatter.parse(dateString);
    }
 else     if (dateString.matches(DateFormat.FULL_TS_SMALL)) {
      SimpleDateFormat srcFormatter=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
      date=srcFormatter.parse(dateString);
    }
 else     if (dateString.matches(DateFormat.FULL_TS_MS)) {
      SimpleDateFormat srcFormatter=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      date=srcFormatter.parse(dateString);
    }
 else     if (dateString.matches(DateFormat.FULL_TS_TIMEZONE)) {
      SimpleDateFormat srcFormatter=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
      date=srcFormatter.parse(dateString);
    }
 else     if (dateString.matches(DateFormat.EPOCH_MS) || dateString.matches(DateFormat.EPOCH_NEG)) {
      date=new Date(Long.parseLong(dateString));
    }
 else     if (dateString.matches(DateFormat.GENERIC_NOYEAR)) {
      SimpleDateFormat srcFormatter=new SimpleDateFormat("--MM-dd");
      date=srcFormatter.parse(dateString);
      date.setYear(0);
    }
 else {
      throw new ParseException("Unknown date type - " + dateString,0);
    }
  }
  return date;
}
 

Example 66

From project blacktie, under directory /integration-tests/src/test/java/org/jboss/narayana/blacktie/jatmibroker/xatmi/.

Source file: CSControl.java

  35 
vote

private TestProcess startClient(String testname,ProcessBuilder builder) throws IOException, InterruptedException {
  String runTime=new SimpleDateFormat("yyMMddHHmmss").format(new Date());
  FileOutputStream ostream=new FileOutputStream(REPORT_DIR + "/test-" + testname+ "-"+ runTime+ "-out.txt");
  FileOutputStream estream=new FileOutputStream(REPORT_DIR + "/test-" + testname+ "-"+ runTime+ "-err.txt");
  TestProcess client=new TestProcess(ostream,estream,"client",builder);
  Thread thread=new Thread(client);
  thread.start();
  log.debug("startClient: waiting to join with client thread ...");
  thread.join();
  log.debug("startClient: joined - waiting for client process to exit");
  client.getProcess().waitFor();
  log.debug("startClient: done");
  return client;
}
 

Example 67

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

Source file: Utils.java

  35 
vote

public static String getMonthName(int month){
  if (mMonthNameFormatter == null)   mMonthNameFormatter=new SimpleDateFormat("MMMM");
  if (mCalendar == null)   mCalendar=Calendar.getInstance();
  mCalendar.set(Calendar.MONTH,month - 1 + java.util.Calendar.JANUARY);
  return mMonthNameFormatter.format(mCalendar.getTime());
}
 

Example 68

From project box-android-sdk, under directory /BoxAndroidLibrarySample/src/com/box/androidlib/sample/activity/.

Source file: Browse.java

  35 
vote

@Override public boolean onOptionsItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()) {
case MENU_ID_UPLOAD:
    Intent intent=new Intent();
  intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file picker"),1);
Toast.makeText(getApplicationContext(),"Install ASTRO FILE MANAGER if you don't already have an app that can handle file choosing",Toast.LENGTH_LONG).show();
return true;
case MENU_ID_CREATE_FOLDER:
final Box box=Box.getInstance(Constants.API_KEY);
Date d=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-DD HH.mm.ss");
String new_folder_name=sdf.format(d);
box.createFolder(authToken,folderId,new_folder_name,false,new CreateFolderListener(){
@Override public void onComplete(final BoxFolder boxFolder,final String status){
if (status.equals(CreateFolderListener.STATUS_CREATE_OK)) {
Toast.makeText(getApplicationContext(),"Folder created - " + boxFolder.getFolderName(),Toast.LENGTH_SHORT).show();
refresh();
}
 else {
Toast.makeText(getApplicationContext(),"Folder creation failed - " + status,Toast.LENGTH_LONG).show();
}
}
@Override public void onIOException(final IOException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Folder creation failed - " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
);
return true;
}
return false;
}
 

Example 69

From project brix-cms, under directory /brix-demo/src/main/java/org/brixcms/demo/web/tile/time/.

Source file: TimeLabel.java

  35 
vote

/** 
 * {@inheritDoc}
 */
@Override public String getObject(){
  JcrNode tileNode=this.tileNode.getObject();
  String format=tileNode.hasProperty("format") ? tileNode.getProperty("format").getString() : null;
  if (format == null) {
    format="MM/dd/yyyy HH:mm:ss z";
  }
  DateFormat fmt=new SimpleDateFormat(format);
  return fmt.format(new Date());
}
 

Example 70

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

Source file: DataManagement.java

  34 
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 71

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

Source file: TestController.java

  34 
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 72

From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.

Source file: CatchAPI.java

  34 
vote

private long parse3339(String time){
  if (time == null || time.length() == 0) {
    return 0;
  }
  if (timestamper != null) {
    try {
      timestamper.parse3339(time);
    }
 catch (    TimeFormatException e) {
      log("caught a TimeFormatException parsing timestamp: \"" + time + '"',e);
      return 0;
    }
    return timestamper.normalize(false);
  }
 else {
    Date timestamp=new Date();
    if (rfc3339 == null) {
      rfc3339=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      rfc3339.setTimeZone(TimeZone.getTimeZone("GMT+0"));
      rfc3339.setLenient(true);
    }
    try {
      timestamp=rfc3339.parse(time);
    }
 catch (    ParseException e) {
      log("caught a ParseException parsing timestamp: \"" + time + '"',e);
      return 0;
    }
    return timestamp.getTime();
  }
}
 

Example 73

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

Source file: Time2Activity.java

  34 
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 74

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

Source file: Time2Activity.java

  34 
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 75

From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/widget/.

Source file: DateIndexer.java

  34 
vote

public DateIndexer(Context context,Cursor cursor,int sortedColumnIndex){
  mCursor=cursor;
  mColumnIndex=sortedColumnIndex;
  mIntFormat=new SimpleDateFormat("yyyyDDD");
  GregorianCalendar calendar=new GregorianCalendar();
  mCursor.moveToFirst();
  long firstDateLong=mCursor.getLong(mColumnIndex);
  mCursor.moveToLast();
  long lastDateLong=mCursor.getLong(mColumnIndex);
  Calendar startDate=Calendar.getInstance();
  startDate.setTimeInMillis(lastDateLong);
  Calendar endDate=Calendar.getInstance();
  endDate.setTimeInMillis(firstDateLong);
  mSectionCount=daysBetween(startDate,endDate);
  mSections=new String[mSectionCount];
  mSectionDates=new int[mSectionCount];
  mSectionPositions=new int[mSectionCount];
  calendar.setTimeInMillis(firstDateLong);
  for (int i=0; i < mSectionCount; i++) {
    mSections[i]=Util.formatDate(context,calendar.getTimeInMillis());
    mSectionDates[i]=Integer.parseInt(mIntFormat.format(calendar.getTime()));
    mSectionPositions[i]=-1;
    calendar.add(GregorianCalendar.DATE,-1);
  }
}
 

Example 76

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

Source file: DateUtil.java

  34 
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 77

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

Source file: LoggingManager.java

  34 
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 78

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

Source file: LoggingManager.java

  34 
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 79

From project Backyard-Brains-Android-App, under directory /src/com/backyardbrains/.

Source file: FileListActivity.java

  34 
vote

@Override public View getView(int position,View convertView,ViewGroup parent){
  FileListViewHolder holder;
  View rowView=convertView;
  if (rowView == null) {
    LayoutInflater balloon=mContext.getLayoutInflater();
    rowView=balloon.inflate(R.layout.file_list_row_layout,null,true);
    holder=new FileListViewHolder();
    holder.filenameView=(TextView)rowView.findViewById(R.id.filename);
    holder.filesizeView=(TextView)rowView.findViewById(R.id.filesize);
    holder.filedateView=(TextView)rowView.findViewById(R.id.file_date);
    rowView.setTag(holder);
  }
 else {
    holder=(FileListViewHolder)rowView.getTag();
  }
  holder.filenameView.setText(mFiles[position].getName());
  holder.filesizeView.setText(getWaveLengthString(mFiles[position].length()));
  holder.filedateView.setText(new SimpleDateFormat("MMM d, yyyy HH:mm a").format(new Date(mFiles[position].lastModified())));
  return rowView;
}
 

Example 80

From project bagheera, under directory /src/main/java/com/mozilla/bagheera/sink/.

Source file: SequenceFileSink.java

  34 
vote

public SequenceFileSink(String namespace,String baseDirPath,String dateFormat,long maxFileSize,boolean useBytesValue) throws IOException {
  LOG.info("Initializing writer for namespace: " + namespace);
  conf=new Configuration();
  conf.setBoolean("fs.automatic.close",false);
  hdfs=FileSystem.newInstance(conf);
  this.useBytesValue=useBytesValue;
  this.maxFileSize=maxFileSize;
  sdf=new SimpleDateFormat(dateFormat);
  if (!baseDirPath.endsWith(Path.SEPARATOR)) {
    baseDir=new Path(baseDirPath + Path.SEPARATOR + namespace+ Path.SEPARATOR+ sdf.format(new Date(System.currentTimeMillis())));
  }
 else {
    baseDir=new Path(baseDirPath + namespace + Path.SEPARATOR+ sdf.format(new Date(System.currentTimeMillis())));
  }
  initWriter();
  stored=Metrics.newMeter(new MetricName("bagheera","sink.hdfs.",namespace + ".stored"),"messages",TimeUnit.SECONDS);
}
 

Example 81

From project BibleQuote-for-Android, under directory /src/com/BibleQuote/utils/.

Source file: Log.java

  34 
vote

/** 
 * ?????????? ?????-????????? ???????. ???????? ?????? ?????, ?????? ??????? ????, ?????? ?????????, ????? ???????
 * @param context
 */
public static void Init(Context context){
  String state=Environment.getExternalStorageState();
  if (Environment.MEDIA_MOUNTED.equals(state)) {
    logFile=new File(DataConstants.FS_APP_DIR_NAME,"log.txt");
    if (logFile.exists()) {
      logFile.delete();
    }
    String myversion;
    try {
      myversion=context.getPackageManager().getPackageInfo(context.getPackageName(),0).versionName;
    }
 catch (    NameNotFoundException e) {
      myversion="0.00.01";
    }
    Write("Log " + new SimpleDateFormat("dd-MMM-yy G hh:mm aaa").format(Calendar.getInstance().getTime()));
    Write("Current version package: " + myversion);
    Write("Default language: " + Locale.getDefault().getDisplayLanguage());
    Write("Device model: " + android.os.Build.BRAND + " "+ android.os.Build.MODEL);
    Write("Device display: " + android.os.Build.BRAND + " "+ android.os.Build.DISPLAY);
    Write("Android OS: " + android.os.Build.VERSION.RELEASE);
    Write("====================================");
  }
}
 

Example 82

From project blueprint-namespaces, under directory /blueprint/blueprint-annotation-itest/src/test/java/org/apache/aries/blueprint/itests/.

Source file: AbstractIntegrationTest.java

  34 
vote

protected void testBlueprintContainer(BundleContext bc,Bundle bundle) throws Exception {
  BlueprintContainer blueprintContainer=getBlueprintContainerForBundle(bc == null ? bundleContext : bc,"org.apache.aries.blueprint.sample",5000);
  assertNotNull(blueprintContainer);
  Object obj=blueprintContainer.getComponentInstance("bar");
  assertNotNull(obj);
  assertEquals(Bar.class,obj.getClass());
  Bar bar=(Bar)obj;
  assertNotNull(bar.getContext());
  assertEquals("Hello FooBar",bar.getValue());
  assertNotNull(bar.getList());
  assertEquals(2,bar.getList().size());
  assertEquals("a list element",bar.getList().get(0));
  assertEquals(Integer.valueOf(5),bar.getList().get(1));
  obj=blueprintContainer.getComponentInstance("foo");
  assertNotNull(obj);
  assertEquals(Foo.class,obj.getClass());
  Foo foo=(Foo)obj;
  assertEquals(5,foo.getA());
  assertEquals(10,foo.getB());
  assertSame(bar,foo.getBar());
  assertEquals(Currency.getInstance("PLN"),foo.getCurrency());
  assertEquals(new SimpleDateFormat("yyyy.MM.dd").parse("2009.04.17"),foo.getDate());
  assertTrue(foo.isInitialized());
  assertFalse(foo.isDestroyed());
  obj=getOsgiService(bc == null ? bundleContext : bc,Foo.class,null,5000);
  assertNotNull(obj);
  assertSame(foo,obj);
  bundle.stop();
  Thread.sleep(1000);
  try {
    blueprintContainer=getBlueprintContainerForBundle(bc == null ? bundleContext : bc,"org.apache.aries.blueprint.sample",1);
    fail("BlueprintContainer should have been unregistered");
  }
 catch (  Exception e) {
  }
  assertTrue(foo.isInitialized());
  assertTrue(foo.isDestroyed());
}
 

Example 83

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/util/.

Source file: DateUtils.java

  33 
vote

private static ThreadLocal<SimpleDateFormat> threadLocalDateFormat(final String pattern){
  ThreadLocal<SimpleDateFormat> tl=new ThreadLocal<SimpleDateFormat>(){
    protected SimpleDateFormat initialValue(){
      SimpleDateFormat df=new SimpleDateFormat(pattern);
      df.setTimeZone(TimeZone.getTimeZone("GMT"));
      return df;
    }
  }
;
  return tl;
}