Java Code Examples for java.text.ParseException

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 adg-android, under directory /src/com/analysedesgeeks/android/utils/.

Source file: DateUtils.java

  19 
vote

public Date parse(final String source) throws ParseException {
  if (source == null) {
    throw new ParseException("source is null",0);
  }
  return formater.parse(source);
}
 

Example 2

From project Briss, under directory /src/main/java/at/laborg/briss/utils/.

Source file: PageNumberParser.java

  17 
vote

/** 
 * Super simple page-number parser. It handles entries like: "1-2;34;3-16"
 * @param input String to be parsed.
 * @return
 * @throws ParseException
 */
public static Set<Integer> parsePageNumber(String input) throws ParseException {
  Pattern p=Pattern.compile("[^0-9-;]");
  Matcher m=p.matcher(input);
  if (m.find())   throw new ParseException("Allowed characters: \"0-9\" \";\" \"-\" ",0);
  StringTokenizer tokenizer=new StringTokenizer(input,";");
  Set<Integer> pNS=new HashSet<Integer>();
  while (tokenizer.hasMoreElements()) {
    pNS.addAll(extractPageNumbers(tokenizer.nextToken()));
  }
  return pNS;
}
 

Example 3

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

Source file: DateUtils.java

  16 
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 4

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/.

Source file: AmiToolsVersion.java

  16 
vote

/** 
 * Constructs a new version object by parsing a version string, which is assumed to be of the form: <major-version>.<minor-version>-<patch-version>
 * @param versionString The version string to parse for the major, minor and patch version numbers.
 * @throws ParseException If the version string parameter was not able to be parsed into the expected format.
 */
public AmiToolsVersion(String versionString) throws ParseException {
  String parseExceptionMessage="Version string '" + versionString + "' does not start with version number in the form "+ "'<major-version>.<minor-version>-<patch-version>'";
  Matcher matcher=pattern.matcher(versionString);
  if (!matcher.matches()) {
    throw new ParseException(parseExceptionMessage,-1);
  }
  try {
    majorVersion=Integer.parseInt(matcher.group(1));
    minorVersion=Integer.parseInt(matcher.group(2));
    patch=Integer.parseInt(matcher.group(3));
  }
 catch (  Throwable t) {
    throw new ParseException(parseExceptionMessage,-1);
  }
}
 

Example 5

From project Birthday-widget, under directory /Birthday/src/main/java/cz/krtinec/birthday/data/.

Source file: BirthdayProvider.java

  16 
vote

/** 
 * @param string
 * @return
 * @throws ParseException
 * @throws IllegalArgumentException
 */
public static ParseResult tryParseBDay(String string) throws ParseException {
  if (string == null) {
    throw new ParseException("Cannot parse: <null>",0);
  }
  if (string.matches(TIMESTAMP_PATTERN)) {
    LocalDate date=new DateTime(Long.parseLong(string)).withZone(DateTimeZone.UTC).toLocalDate();
    return new ParseResult(date,DateIntegrity.FULL);
  }
  Matcher m;
  for (  DatePattern pat : PATTERNS) {
    m=Pattern.compile(pat.pattern).matcher(string);
    if (m.find()) {
      string=string.substring(m.start(),m.end());
      LocalDate date=pat.format.withZone(DateTimeZone.UTC).parseDateTime(string).toLocalDate();
      return new ParseResult(date,pat.integrity);
    }
  }
  throw new ParseException("Cannot parse: " + string,0);
}
 

Example 6

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

Source file: DateUtility.java

  16 
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 7

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  15 
vote

public long getDateHeader(String name){
  String val=getHeader(name);
  if (val == null)   return -1;
  try {
    return headerdateformat.parse(val).getTime();
  }
 catch (  ParseException pe) {
    try {
      return rfc850DateFmt.parse(val).getTime();
    }
 catch (    ParseException pe1) {
      try {
        return asciiDateFmt.parse(val).getTime();
      }
 catch (      ParseException pe3) {
        throw new IllegalArgumentException("Value " + val + " can't be converted to Date using any of formats: ["+ headerdateformat.toPattern()+ "][ "+ rfc850DateFmt.toPattern()+ "]["+ asciiDateFmt.toPattern());
      }
    }
  }
}
 

Example 8

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

Source file: DateFunctions.java

  15 
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 9

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

Source file: MathHelper.java

  15 
vote

/** 
 * Computes a reasonable set of labels for a data interval and number of labels.
 * @param start start value
 * @param end final value
 * @param approxNumLabels desired number of labels
 * @return collection containing {start value, end value, increment}
 */
public static List<Double> getLabels(final double start,final double end,final int approxNumLabels){
  FORMAT.setMaximumFractionDigits(5);
  List<Double> labels=new ArrayList<Double>();
  double[] labelParams=computeLabels(start,end,approxNumLabels);
  int numLabels=1 + (int)((labelParams[1] - labelParams[0]) / labelParams[2]);
  for (int i=0; i < numLabels; i++) {
    double z=labelParams[0] + i * labelParams[2];
    try {
      z=FORMAT.parse(FORMAT.format(z)).doubleValue();
    }
 catch (    ParseException e) {
    }
    labels.add(z);
  }
  return labels;
}
 

Example 10

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

Source file: NumericValidator.java

  15 
vote

public static void main(String[] av) throws ParseException {
  String input="11 ss";
  ParsePosition pp=new ParsePosition(0);
  NumberFormat.getInstance().parse(input,pp);
  if (pp.getIndex() != (input.length() - 1))   throw new RuntimeException("failed to parse");
}
 

Example 11

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

Source file: DateFormPropertyRenderer.java

  15 
vote

@Override public Field getPropertyField(FormProperty formProperty){
  PopupDateField dateField=new PopupDateField(getPropertyLabel(formProperty));
  String datePattern=(String)formProperty.getType().getInformation("datePattern");
  dateField.setDateFormat(datePattern);
  dateField.setRequired(formProperty.isRequired());
  dateField.setRequiredError(getMessage(Messages.FORM_FIELD_REQUIRED,getPropertyLabel(formProperty)));
  dateField.setEnabled(formProperty.isWritable());
  if (formProperty.getValue() != null) {
    SimpleDateFormat dateFormat=new SimpleDateFormat(datePattern);
    try {
      Date date=dateFormat.parse(formProperty.getValue());
      dateField.setValue(date);
    }
 catch (    ParseException e) {
    }
  }
  return dateField;
}
 

Example 12

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

Source file: DoseRangeCutOffDialog.java

  15 
vote

protected JPanel buildPanel(){
  Bindings.bind(d_okButton,"enabled",d_validator);
  final FormLayout layout=new FormLayout("pref, 3dlu, pref, 3dlu, fill:pref:grow","p");
  final PanelBuilder builder=new PanelBuilder(layout);
  builder.setDefaultDialogBorder();
  final CellConstraints cc=new CellConstraints();
  final int colSpan=builder.getColumnCount();
  int row=1;
  final String variableName=GUIHelper.humanize(d_choice.getPropertyName());
  builder.addSeparator("Original range: " + RangeEdge.format(variableName,d_rangeToSplit),cc.xyw(1,row,colSpan));
  row=LayoutUtil.addRow(layout,row);
  builder.addLabel("Split range at:",cc.xy(1,row));
  final JFormattedTextField cutOffField=BasicComponentFactory.createFormattedTextField(d_cutOff,new DefaultFormatter());
  cutOffField.setColumns(5);
  cutOffField.addCaretListener(new CaretListener(){
    @Override public void caretUpdate(    final CaretEvent e){
      try {
        cutOffField.commitEdit();
        pack();
      }
 catch (      final ParseException exp) {
        return;
      }
    }
  }
);
  builder.add(cutOffField,cc.xy(3,row));
  final String unitText=d_pm.getDoseUnitPresentation().getBean().toString();
  builder.addLabel(unitText,cc.xy(5,row));
  row=LayoutUtil.addRow(layout,row);
  builder.addLabel("Bound is inclusive/exclusive for lower range:",cc.xyw(1,row,colSpan));
  row=LayoutUtil.addRow(layout,row);
  builder.add(BasicComponentFactory.createRadioButton(d_lowerOpen,false,""),cc.xy(1,row));
  builder.add(BasicComponentFactory.createLabel(d_cutOff,new FormatRange(variableName,false)),cc.xy(3,row));
  row=LayoutUtil.addRow(layout,row);
  builder.add(BasicComponentFactory.createRadioButton(d_lowerOpen,true,""),cc.xy(1,row));
  builder.add(BasicComponentFactory.createLabel(d_cutOff,new FormatRange(variableName,true)),cc.xy(3,row));
  return builder.getPanel();
}
 

Example 13

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

Source file: HeadsUpConfiguration.java

  15 
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 14

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

Source file: AbstractTrendsList.java

  15 
vote

protected Date toDate(String dateString,DateFormat dateFormat){
  if (dateString == null) {
    return null;
  }
  try {
    return dateFormat.parse(dateString);
  }
 catch (  ParseException e) {
    return null;
  }
}
 

Example 15

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/api/gson/.

Source file: LocalDateAdapter.java

  15 
vote

@Override public Date deserialize(JsonElement element,Type type,JsonDeserializationContext context) throws JsonParseException {
  try {
    return localFormat.parse(element.getAsString());
  }
 catch (  ParseException e) {
    Log.e(Constants.TAG,"",e);
    throw new JsonParseException(e);
  }
}
 

Example 16

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

Source file: DtppActivity.java

  15 
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 17

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

Source file: ConvertDateFormat.java

  15 
vote

@Override public String exec(Tuple input) throws IOException {
  if (input == null || input.size() == 0) {
    return null;
  }
  String s=null;
  try {
    Date d=inputSdf.parse((String)input.get(0));
    s=outputSdf.format(d);
  }
 catch (  ParseException e) {
    pigLogger.warn(this,"Date parsing error",ERRORS.DateParseError);
  }
  return s;
}
 

Example 18

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

Source file: DateUtil.java

  15 
vote

public static Date parse(String data){
  try {
    String date=data;
    if (data.indexOf('.') > -1)     date=data.substring(0,data.indexOf('.'));
    Date result=getFormatter().parse(date);
    return result;
  }
 catch (  ParseException e) {
    LogEx.warning("Failed to parse the date string " + data + ". Using now.");
    return new Date();
  }
}
 

Example 19

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

Source file: NewsActivity.java

  15 
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 20

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

Source file: TestController.java

  15 
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 21

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/cookie/.

Source file: DateUtils.java

  15 
vote

/** 
 * Parses the date value using the given date formats.
 * @param dateValue the date value to parse
 * @param dateFormats the date formats to use
 * @param startDate During parsing, two digit years will be placed in the range<code>startDate</code> to <code>startDate + 100 years</code>. This value may be <code>null</code>. When <code>null</code> is given as a parameter, year <code>2000</code> will be used.
 * @return the parsed date
 * @throws DateParseException if none of the dataFormats could parse the dateValue
 */
public static Date parseDate(String dateValue,String[] dateFormats,Date startDate) throws DateParseException {
  if (dateValue == null) {
    throw new IllegalArgumentException("dateValue is null");
  }
  if (dateFormats == null) {
    dateFormats=DEFAULT_PATTERNS;
  }
  if (startDate == null) {
    startDate=DEFAULT_TWO_DIGIT_YEAR_START;
  }
  if (dateValue.length() > 1 && dateValue.startsWith("'") && dateValue.endsWith("'")) {
    dateValue=dateValue.substring(1,dateValue.length() - 1);
  }
  for (  String dateFormat : dateFormats) {
    SimpleDateFormat dateParser=DateFormatHolder.formatFor(dateFormat);
    dateParser.set2DigitYearStart(startDate);
    try {
      return dateParser.parse(dateValue);
    }
 catch (    ParseException pe) {
    }
  }
  throw new DateParseException("Unable to parse the date " + dateValue);
}
 

Example 22

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

Source file: ContentAdapter.java

  15 
vote

private Date parseDate(String string){
  SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  try {
    return dateFormat.parse(string);
  }
 catch (  ParseException e) {
    return null;
  }
}
 

Example 23

From project Android, under directory /AndroidNolesCore/src/util/.

Source file: News.java

  15 
vote

private void setPublished(String date){
  try {
    mPublished=getDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(date);
  }
 catch (  ParseException e) {
    LogUtils.LOGW(LOG_TAG,"Fail to parse published date",e);
  }
}
 

Example 24

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

Source file: CatchAPI.java

  15 
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 25

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

Source file: AmericanExpress.java

  15 
vote

@Override public void updateTransactions(Account account,Urllib urlopen) throws LoginException, BankException {
  super.updateTransactions(account,urlopen);
  try {
    response=urlopen.open("https://global.americanexpress.com/myca/intl/estatement/emea/statement.do?request_type=&Face=sv_SE&BPIndex=0&sorted_index=" + account.getId());
    Matcher matcher=reTransactions.matcher(response);
    ArrayList<Transaction> transactions=new ArrayList<Transaction>();
    while (matcher.find()) {
      SimpleDateFormat sdfFrom=new SimpleDateFormat("d MMM yyyy");
      SimpleDateFormat sdfTo=new SimpleDateFormat("yyyy-MM-dd");
      Date transactionDate;
      try {
        transactionDate=sdfFrom.parse(matcher.group(1).trim());
        String strDate=sdfTo.format(transactionDate);
        transactions.add(new Transaction(strDate,Html.fromHtml(matcher.group(2)).toString().trim(),Helpers.parseBalance(matcher.group(3).trim()).negate()));
      }
 catch (      ParseException e) {
        Log.d(TAG,"Unable to parse date: " + matcher.group(1).trim());
      }
    }
    account.setTransactions(transactions);
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 26

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

Source file: PreCollectionSheetActivity.java

  15 
vote

public void onContinueCollectionSheet(View view){
  mSaveCustomer.setUserId(mLoanOfficer.getId());
  mSaveCustomer.setPaymentType((short)1);
  mSaveCustomer.setReceiptId(receiptID.getText().toString());
  mSaveCustomer.setTransactionDate(mCollectionSheetData.getDate());
  if (mSaveCustomer.getReceiptDate() != null) {
    try {
      mSaveCustomer.setReceiptDate(df.parse(dateField.getText().toString()));
    }
 catch (    ParseException e) {
      e.printStackTrace();
    }
  }
  CollectionSheetHolder.setSaveCollectionSheet(mSaveCustomer);
  Center center=CollectionSheetHolder.getSelectedCenter();
  Intent intent=new Intent().setClass(this,CollectionSheetActivity.class);
  intent.putExtra(AbstractCustomer.BUNDLE_KEY,center);
  startActivity(intent);
}
 

Example 27

From project android-rss, under directory /src/main/java/org/mcsoxford/rss/.

Source file: Dates.java

  15 
vote

/** 
 * Parses string as an RFC 822 date/time.
 * @throws RSSFault if the string is not a valid RFC 822 date/time
 */
static java.util.Date parseRfc822(String date){
  try {
    return RFC822.parse(date);
  }
 catch (  ParseException e) {
    throw new RSSFault(e);
  }
}
 

Example 28

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

Source file: DateUtils.java

  15 
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 29

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.

Source file: InternalUtils.java

  15 
vote

static Date parseDate(String c){
  if (InternalUtils.REGEX_JUST_DIGITS.matcher(c).matches())   return new Date(Long.valueOf(c));
  try {
    Date _createdAt=new Date(c);
    return _createdAt;
  }
 catch (  Exception e) {
    try {
      Date _createdAt=InternalUtils.dfMarko.parse(c);
      return _createdAt;
    }
 catch (    ParseException e1) {
      throw new TwitterException.Parsing(c,e1);
    }
  }
}
 

Example 30

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 31

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

Source file: BooksStore.java

  15 
vote

public static Book fromCursor(Cursor c){
  final Book book=new Book();
  book.mInternalId=c.getString(c.getColumnIndexOrThrow(INTERNAL_ID));
  book.mEan=c.getString(c.getColumnIndexOrThrow(EAN));
  book.mIsbn=c.getString(c.getColumnIndexOrThrow(ISBN));
  book.mTitle=c.getString(c.getColumnIndexOrThrow(TITLE));
  Collections.addAll(book.mAuthors,c.getString(c.getColumnIndexOrThrow(AUTHORS)).split(", "));
  book.mPublisher=c.getString(c.getColumnIndexOrThrow(PUBLISHER));
  book.mDescriptions.add(new Description("",c.getString(c.getColumnIndexOrThrow(REVIEWS))));
  book.mPages=c.getInt(c.getColumnIndexOrThrow(PAGES));
  final Calendar calendar=GregorianCalendar.getInstance();
  calendar.setTimeInMillis(c.getLong(c.getColumnIndexOrThrow(LAST_MODIFIED)));
  book.mLastModified=calendar;
  final SimpleDateFormat format=new SimpleDateFormat("MMMM yyyy");
  try {
    book.mPublicationDate=format.parse(c.getString(c.getColumnIndexOrThrow(PUBLICATION)));
  }
 catch (  ParseException e) {
  }
  book.mDetailsUrl=c.getString(c.getColumnIndexOrThrow(DETAILS_URL));
  book.mImages.put(ImageSize.TINY,c.getString(c.getColumnIndexOrThrow(TINY_URL)));
  return book;
}
 

Example 32

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

Source file: DefaultTypeAdapters.java

  15 
vote

private Date deserializeToDate(JsonElement json){
synchronized (localFormat) {
    try {
      return localFormat.parse(json.getAsString());
    }
 catch (    ParseException ignored) {
    }
    try {
      return enUsFormat.parse(json.getAsString());
    }
 catch (    ParseException ignored) {
    }
    try {
      return iso8601Format.parse(json.getAsString());
    }
 catch (    ParseException e) {
      throw new JsonSyntaxException(json.getAsString(),e);
    }
  }
}
 

Example 33

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/cache/.

Source file: CacheService.java

  15 
vote

public static final long fetchDateTaken(final MediaItem item){
  if (!item.isDateTakenValid() && !item.mTriedRetrievingExifDateTaken && (item.mFilePath.endsWith(".jpg") || item.mFilePath.endsWith(".jpeg"))) {
    try {
      if (DEBUG)       Log.i(TAG,"Parsing date taken from exif");
      final ExifInterface exif=new ExifInterface(item.mFilePath);
      final String dateTakenStr=exif.getAttribute(ExifInterface.TAG_DATETIME);
      if (dateTakenStr != null) {
        try {
          final Date dateTaken=mDateFormat.parse(dateTakenStr);
          return dateTaken.getTime();
        }
 catch (        ParseException pe) {
          try {
            final Date dateTaken=mAltDateFormat.parse(dateTakenStr);
            return dateTaken.getTime();
          }
 catch (          ParseException pe2) {
            if (DEBUG)             Log.i(TAG,"Unable to parse date out of string - " + dateTakenStr);
          }
        }
      }
    }
 catch (    Exception e) {
      if (DEBUG)       Log.i(TAG,"Error reading Exif information, probably not a jpeg.");
    }
    item.mTriedRetrievingExifDateTaken=true;
  }
  return -1L;
}
 

Example 34

From project annotare2, under directory /app/magetab/src/main/java/uk/ac/ebi/fg/annotare2/magetab/idf/format/.

Source file: JseTextFormatter.java

  15 
vote

@Override public Date parseDate(String str){
  try {
    return isNullOrEmpty(str) ? null : dateFormat.parse(str);
  }
 catch (  ParseException e) {
    throw new IllegalArgumentException("Date is in the wrong format: " + str);
  }
}
 

Example 35

From project anode, under directory /src/net/haltcondition/anode/.

Source file: Usage.java

  15 
vote

public void setRollOver(String str) throws ParseException {
  Date d=dateParser.parse(str);
  rollOver=new GregorianCalendar();
  rollOver.setTime(d);
  rollOver.setLenient(true);
}
 

Example 36

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

Source file: HCalendarExtractor.java

  15 
vote

private void addTextProps(HTMLDocument node,Resource evt){
  for (  String date : textSingularProps) {
    HTMLDocument.TextField val=node.getSingularTextField(date);
    conditionallyAddStringProperty(val.source(),evt,vICAL.getProperty(date),val.value());
  }
  for (  String date : textDateProps) {
    HTMLDocument.TextField val=node.getSingularTextField(date);
    try {
      conditionallyAddStringProperty(val.source(),evt,vICAL.getProperty(date),RDFUtils.getXSDDate(val.value(),DATE_FORMAT));
    }
 catch (    ParseException e) {
      conditionallyAddStringProperty(val.source(),evt,vICAL.getProperty(date),val.value());
    }
catch (    DatatypeConfigurationException e) {
      conditionallyAddStringProperty(val.source(),evt,vICAL.getProperty(date),val.value());
    }
  }
  HTMLDocument.TextField[] values=node.getPluralTextField("category");
  for (  TextField val : values) {
    conditionallyAddStringProperty(val.source(),evt,vICAL.categories,val.value());
  }
}
 

Example 37

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

Source file: Flickr.java

  15 
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 38

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

Source file: CalendarEditor.java

  15 
vote

@Override public void setAsText(String string) throws IllegalArgumentException {
  DateFormat formatter=new SimpleDateFormat(format,new Locale("no"));
  Date date;
  try {
    date=formatter.parse(string);
  }
 catch (  ParseException e) {
    throw new IllegalArgumentException("Not in right format: " + format);
  }
  Calendar cal=new GregorianCalendar();
  cal.setTime(date);
  setValue(cal);
}
 

Example 39

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

Source file: SNValue.java

  15 
vote

/** 
 * Constructor.
 * @param datatype The datatype.
 * @param value The value.
 * @param locale The locale
 */
public SNValue(ElementaryDataType datatype,Object value,Locale locale){
  if (value == null) {
    throw new IllegalArgumentException("Value may not be null");
  }
  this.datatype=datatype;
  this.locale=locale;
  try {
    this.value=convert(value,datatype);
  }
 catch (  ParseException e) {
    throw new IllegalStateException("Value not of expected type",e);
  }
}
 

Example 40

From project Archimedes, under directory /br.org.archimedes.io.xml/src/br/org/archimedes/io/xml/parsers/.

Source file: XMLUtils.java

  15 
vote

/** 
 * Returns an Archimedes Point from an org.w3c.dom.Element
 * @param node The Element
 * @return The Point
 */
protected static Point nodeToPoint(Node node){
  org.w3c.dom.Element element=(org.w3c.dom.Element)node;
  Double x, y;
  Point point=null;
  try {
    x=nf.parse(element.getAttribute("x")).doubleValue();
    y=nf.parse(element.getAttribute("y")).doubleValue();
    point=new Point(x,y);
  }
 catch (  ParseException e) {
    e.printStackTrace();
  }
  return point;
}
 

Example 41

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

Source file: WATExtractorOutput.java

  15 
vote

private void writeWARCMDRecord(OutputStream recOut,MetaData md,String targetURI,String capDateString,String recId) throws IOException {
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  OutputStreamWriter osw=new OutputStreamWriter(bos,UTF8);
  try {
    md.write(osw);
  }
 catch (  JSONException e1) {
    e1.printStackTrace();
    throw new IOException(e1);
  }
  osw.flush();
  Date capDate;
  try {
    capDate=DateUtils.getSecondsSinceEpoch(capDateString);
  }
 catch (  ParseException e) {
    e.printStackTrace();
    capDate=new Date();
  }
  recW.writeJSONMetadataRecord(recOut,bos.toByteArray(),targetURI,capDate,recId);
}
 

Example 42

From project ARCInputFormat, under directory /src/org/commoncrawl/util/shared/.

Source file: ArcFileReader.java

  15 
vote

/** 
 * process the metadata line of an ARC File Entry 
 */
private final void processMetadataLine(String metadata) throws IOException {
  StringTokenizer tokenizer=new StringTokenizer(metadata," ");
  int tokenCount=0;
  while (tokenizer.hasMoreElements() && tokenCount <= 5) {
switch (++tokenCount) {
case 1:
{
        _item.setUri(tokenizer.nextToken());
      }
    break;
case 2:
{
    _item.setHostIP(tokenizer.nextToken());
  }
break;
case 3:
{
String timeStamp=tokenizer.nextToken();
try {
  _item.setTimestamp(TIMESTAMP14.parse(timeStamp).getTime());
}
 catch (ParseException e) {
  LOG.error("Invalid Timestamp Encountered in Item Metdata. URL:" + _item.getUri() + " Timestamp:"+ timeStamp+ " Metadata:"+ metadata);
  _item.setTimestamp(0);
}
}
break;
case 4:
{
_item.setMimeType(tokenizer.nextToken());
}
break;
case 5:
{
_item.setRecordLength(Integer.parseInt(tokenizer.nextToken()));
}
break;
}
}
}
 

Example 43

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

Source file: DateUtil.java

  15 
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 44

From project ATHENA, under directory /core/apa/src/main/java/org/fracturedatlas/athena/apa/impl/jpa/.

Source file: DateTimeTicketProp.java

  15 
vote

@Override public int compareTo(Object o) throws ClassCastException {
  try {
    Date date=DateUtil.parseDate((String)o);
    log.debug("Comparing value [{}] to input of [{}]",value,date);
    return value.compareTo(date);
  }
 catch (  ParseException pe) {
    throw new ClassCastException("Could not make a date out of this [" + o + "]");
  }
}
 

Example 45

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

Source file: DateSearchPanel.java

  15 
vote

private void dateFromTextFieldFocusLost(java.awt.event.FocusEvent evt){
  String fromDateString=this.dateFromTextField.getText();
  if (!fromDateString.equals("")) {
    try {
      Date fromDate=dateFormat.parse(fromDateString);
      dateFromButtonCalendar.setTargetDate(fromDate);
    }
 catch (    ParseException ex) {
    }
  }
}
 

Example 46

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

Source file: String2DateFunction.java

  15 
vote

@Override public AviatorObject call(Map<String,Object> env,AviatorObject arg1,AviatorObject arg2){
  String source=FunctionUtils.getStringValue(arg1,env);
  String format=FunctionUtils.getStringValue(arg2,env);
  SimpleDateFormat dateFormat=DateFormatCache.getOrCreateDateFormat(format);
  try {
    return new AviatorRuntimeJavaType(dateFormat.parse(source));
  }
 catch (  ParseException e) {
    throw new ExpressionRuntimeException("Cast string to date failed",e);
  }
}
 

Example 47

From project aws-tvm-anonymous, under directory /src/com/amazonaws/tvm/.

Source file: Utilities.java

  15 
vote

/** 
 * Checks to see if the request has valid timestamp. If given timestamp falls in 30 mins window from current server timestamp
 */
public static boolean isTimestampValid(String timestamp){
  long timestampLong=0L;
  final long window=15 * 60 * 1000L;
  if (null == timestamp) {
    return false;
  }
  try {
    timestampLong=new DateUtils().parseIso8601Date(timestamp).getTime();
  }
 catch (  ParseException exception) {
    log.warning("Error parsing timestamp sent from client : " + encode(timestamp));
    return false;
  }
  Long now=new Date().getTime();
  long before15Mins=new Date(now - window).getTime();
  long after15Mins=new Date(now + window).getTime();
  return (timestampLong >= before15Mins && timestampLong <= after15Mins);
}
 

Example 48

From project aws-tvm-identity, under directory /src/com/amazonaws/tvm/.

Source file: Utilities.java

  15 
vote

/** 
 * Checks to see if the request has valid timestamp. If given timestamp falls in 30 mins window from current server timestamp
 */
public static boolean isTimestampValid(String timestamp){
  long timestampLong=0L;
  final long window=15 * 60 * 1000L;
  if (null == timestamp) {
    return false;
  }
  try {
    timestampLong=new DateUtils().parseIso8601Date(timestamp).getTime();
  }
 catch (  ParseException exception) {
    log.warning("Error parsing timestamp sent from client : " + encode(timestamp));
    return false;
  }
  Long now=new Date().getTime();
  long before15Mins=new Date(now - window).getTime();
  long after15Mins=new Date(now + window).getTime();
  return (timestampLong >= before15Mins && timestampLong <= after15Mins);
}
 

Example 49

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

Source file: MockConverSupport.java

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

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/repository/impl/.

Source file: ArchiveDateRepositoryImpl.java

  15 
vote

@Override public JSONObject getByArchiveDate(final String archiveDate) throws RepositoryException {
  long time=0L;
  try {
    time=ArchiveDate.DATE_FORMAT.parse(archiveDate).getTime();
  }
 catch (  final ParseException e) {
    LOGGER.log(Level.SEVERE,"Can not parse archive date [" + archiveDate + "]",e);
    throw new RepositoryException("Can not parse archive date [" + archiveDate + "]");
  }
  final Query query=new Query();
  query.setFilter(new PropertyFilter(ArchiveDate.ARCHIVE_TIME,FilterOperator.EQUAL,time)).setPageCount(1);
  final JSONObject result=get(query);
  final JSONArray array=result.optJSONArray(Keys.RESULTS);
  if (0 == array.length()) {
    return null;
  }
  return array.optJSONObject(0);
}
 

Example 51

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

Source file: MavenArtifact.java

  15 
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 52

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

Source file: CalendarDate.java

  15 
vote

/** 
 * [email protected] CalendarDate}???????????????????
 * @param dateString ????????????? 
 * @param pattern ?????????????
 * @return {@link CalendarDate}
 * @throws ParseException ??????????????????? 
 * @throws IllegalArgumentException [email protected] null}?????????
 * @since 1.0
 */
public static CalendarDate parse(String dateString,String pattern) throws ParseException {
  Validate.notNull(dateString);
  Validate.notNull(pattern);
  TimeZone arbitraryZone=TimeZone.getTimeZone("Universal");
  TimePoint point=TimePoint.parse(dateString,pattern,arbitraryZone);
  return CalendarDate.from(point,arbitraryZone);
}
 

Example 53

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

Source file: Meetings.java

  15 
vote

public int parse(String str) throws ParserConfigurationException, UnsupportedEncodingException, SAXException, IOException, DOMException, ParseException {
  meetings.clear();
  log.debug("parsing getMeetings response: {}",str);
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  DocumentBuilder db=dbf.newDocumentBuilder();
  Document doc=db.parse(new ByteArrayInputStream(str.getBytes("UTF-8")));
  doc.getDocumentElement().normalize();
  Node first_node=doc.getFirstChild();
  if (first_node == null) {
    log.error("Parsing a non-XML response for getMeetings");
    return JoinServiceBase.E_MOBILE_NOT_SUPPORTED;
  }
  boolean check_return_code;
  if (first_node.getNodeName().equals("meetings")) {
    log.info("The given response is a mobile getMeetings");
    check_return_code=true;
  }
 else   if (first_node.getNodeName().equals("response")) {
    log.info("The given response is a default getMeetings, or it's an error response");
    NodeList return_code_list=doc.getElementsByTagName("returncode");
    if (return_code_list == null || return_code_list.getLength() <= 0 || !return_code_list.item(0).getFirstChild().getNodeValue().equals("SUCCESS"))     return JoinServiceBase.E_UNKNOWN_ERROR;
    check_return_code=false;
  }
 else {
    return JoinServiceBase.E_MOBILE_NOT_SUPPORTED;
  }
  NodeList meetings_node=doc.getElementsByTagName("meeting");
  if (meetings_node != null) {
    for (int i=0; i < meetings_node.getLength(); ++i) {
      Meeting meeting=new Meeting();
      if (meeting.parse((Element)meetings_node.item(i),check_return_code))       meetings.add(meeting);
    }
  }
  return JoinServiceBase.E_OK;
}
 

Example 54

From project BBC-News-Reader, under directory /src/org/mcsoxford/rss/.

Source file: Dates.java

  15 
vote

/** 
 * Parses string as an RFC 822 date/time.
 * @throws RSSFault if the string is not a valid RFC 822 date/time
 */
static java.util.Date parseRfc822(String date){
  try {
    return RFC822.parse(date);
  }
 catch (  ParseException e) {
    throw new RSSFault(e);
  }
}
 

Example 55

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

Source file: EtmOp.java

  15 
vote

private void setStartStopTime(){
  try {
    if (sourceProduct.getStartTime() != null && sourceProduct.getEndTime() != null) {
      landsatStartTime=sourceProduct.getStartTime().toString().substring(0,20);
      landsatStopTime=sourceProduct.getEndTime().toString().substring(0,20);
    }
 else {
      String acquisitionDate=sourceProduct.getMetadataRoot().getElement("L1_METADATA_FILE").getElement("PRODUCT_METADATA").getAttribute("ACQUISITION_DATE").getData().getElemString();
      String centerTime=sourceProduct.getMetadataRoot().getElement("L1_METADATA_FILE").getElement("PRODUCT_METADATA").getAttribute("SCENE_CENTER_SCAN_TIME").getData().getElemString().substring(0,8);
      String landsatCenterTime=LandsatUtils.convertDate(acquisitionDate) + " " + centerTime;
      landsatStartTime=landsatCenterTime;
      landsatStopTime=landsatCenterTime;
      sourceProduct.setStartTime(ProductData.UTC.parse(landsatCenterTime));
      sourceProduct.setEndTime(ProductData.UTC.parse(landsatCenterTime));
    }
  }
 catch (  ParseException e) {
    throw new OperatorException("Start or stop time invalid or has wrong format - must be 'yyyymmdd hh:mm:ss'.");
  }
}
 

Example 56

From project Betfair-Trickle, under directory /src/main/java/uk/co/onehp/trickle/services/betfair/.

Source file: ScheduledServiceImpl.java

  15 
vote

@Override public void scheduleNextBet(){
  Scheduler scheduler=this.quartzScheduler.getObject();
  try {
    this.placeBetsTrigger.setCronExpression(nextBetSchedule());
    Date rescheduleTime=scheduler.rescheduleJob(this.placeBetsTrigger.getName(),this.placeBetsTrigger.getGroup(),this.placeBetsTrigger);
    this.log.debug(rescheduleTime);
  }
 catch (  ParseException e) {
    this.log.error(e);
  }
catch (  SchedulerException e) {
    this.log.error(e);
  }
  try {
    this.getPricesForUpcomingBetsTrigger.setCronExpression(nextBetPriceSchedule());
    Date rescheduleTime=scheduler.rescheduleJob(this.getPricesForUpcomingBetsTrigger.getName(),this.getPricesForUpcomingBetsTrigger.getGroup(),this.getPricesForUpcomingBetsTrigger);
    this.log.debug(rescheduleTime);
  }
 catch (  ParseException e) {
    this.log.error(e);
  }
catch (  SchedulerException e) {
    this.log.error(e);
  }
}
 

Example 57

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

Source file: Updater.java

  15 
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 58

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/rcputils/de/ralfebert/rcputils/tables/format/.

Source file: StringValueFormatter.java

  15 
vote

@Override public Object parse(String str){
  if (format == null) {
    return str;
  }
  try {
    return format.parseObject(str);
  }
 catch (  ParseException e) {
    throw new InvalidValueException(e.getMessage() + " for \"" + str+ "\"",e);
  }
}
 

Example 59

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

Source file: BioportalRssModuleParser.java

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

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

Source file: DetermineFirstSeenThread.java

  15 
vote

@Override public void run(){
  try {
    final URLConnection connection=new URL(Constants.BLOCKEXPLORER_BASE_URL + "address/" + address).openConnection();
    connection.connect();
    final Reader is=new InputStreamReader(new BufferedInputStream(connection.getInputStream()));
    final StringBuilder content=new StringBuilder();
    IOUtils.copy(is,content);
    is.close();
    final Matcher m=P_FIRST_SEEN.matcher(content);
    if (m.find()) {
      succeed(Iso8601Format.parseDateTime(m.group(1)));
    }
 else {
      succeed(null);
    }
  }
 catch (  final IOException x) {
    failed(x);
  }
catch (  final ParseException x) {
    failed(x);
  }
}
 

Example 61

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

Source file: ResolverFactoryImpl.java

  15 
vote

@Override public void setAsText(String text) throws IllegalArgumentException {
  if (text == null || (text=text.trim()).length() == 0) {
    return;
  }
  try {
    setValue(DatePatterns.changeType(DatePatterns.parse(text),targetType));
  }
 catch (  ParseException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 62

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

Source file: Fields.java

  15 
vote

/** 
 * Utility routine to parse a date. Parses YYYY-MM-DD and DD-MMM-YYYY format. Could be generalized even further if desired by supporting more formats.  
 * @param s		String to parse
 * @return		Parsed date
 * @throws ParseException		If parse failed.
 */
static private Date parseDate(String s) throws ParseException {
  Date d;
  try {
    d=mDateSqlSdf.parse(s);
  }
 catch (  Exception e) {
    try {
      d=mDateDispSdf.parse(s);
    }
 catch (    Exception e1) {
      java.text.DateFormat df=java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT);
      d=df.parse(s);
    }
  }
  return d;
}
 

Example 63

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

Source file: SnapshotPlugin.java

  15 
vote

public Date getCreated(Workspace workspace){
  String formatted=workspace.getAttribute(WORKSPACE_ATTRIBUTE_CREATED);
  if (formatted == null) {
    return null;
  }
 else {
    DateFormat df=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
    Date date;
    try {
      date=df.parse(formatted);
      return date;
    }
 catch (    ParseException e) {
      return null;
    }
  }
}
 

Example 64

From project build-info, under directory /build-info-api/src/main/java/org/jfrog/build/api/release/.

Source file: Promotion.java

  15 
vote

private Date getTimestampAsDate(String timestamp){
  if (timestamp == null) {
    return null;
  }
  SimpleDateFormat format=new SimpleDateFormat(Build.STARTED_FORMAT);
  try {
    return format.parse(timestamp);
  }
 catch (  ParseException e) {
    throw new RuntimeException(e);
  }
}
 

Example 65

From project C-Cat, under directory /util/src/main/java/gov/llnl/ontology/text/corpora/.

Source file: NYTDocumentReader.java

  15 
vote

private static void handlePubdata(Node node,NYTCorpusDocument ldcDocument){
  String publicationDateString=getAttributeValue(node,DATE_PUBLICATION_ATTRIBUTE);
  if (publicationDateString != null) {
    try {
      Date date=format.parse(publicationDateString);
      ldcDocument.setPublicationDate(date);
    }
 catch (    ParseException e) {
      e.printStackTrace();
      System.out.println("Error parsing date from string " + publicationDateString + " in file "+ ldcDocument.getSourceFile()+ ".");
    }
  }
  String urlString=getAttributeValue(node,EX_REF_ATTRIBUTE);
  if (urlString != null) {
    try {
      URL url=new URL(urlString);
      ldcDocument.setUrl(url);
    }
 catch (    MalformedURLException e) {
      e.printStackTrace();
      System.out.println("Error parsing url from string " + urlString + " in file "+ ldcDocument.getSourceFile()+ ".");
    }
  }
  String wordCountString=getAttributeValue(node,ITEM_LENGTH_ATTRIBUTE);
  if (wordCountString != null) {
    try {
      Integer wordCount=Integer.parseInt(wordCountString);
      ldcDocument.setWordCount(wordCount);
    }
 catch (    NumberFormatException e) {
      e.printStackTrace();
      System.out.println("Error parsing integer from string " + wordCountString + " in file "+ ldcDocument.getSourceFile()+ ".");
    }
  }
  String creatorString=getAttributeValue(node,NAME_ATTRIBUTE);
  if (creatorString != null) {
    ldcDocument.setCredit(creatorString);
  }
}
 

Example 66

From project Cafe, under directory /testservice/src/com/baidu/cafe/remote/.

Source file: SystemLib.java

  15 
vote

/** 
 * set system time
 * @param time , format "yyyy/MM/dd hh:mm:ss", e.g. "2011/11/25 17:30:00"
 */
public void setSystemTime(String time){
  try {
    SimpleDateFormat df=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    Date temp=df.parse(time);
    Calendar cal=Calendar.getInstance();
    cal.setTime(temp);
    SystemClock.setCurrentTimeMillis(cal.getTimeInMillis());
  }
 catch (  ParseException e) {
  }
}
 

Example 67

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

Source file: JTextFieldDateEditor.java

  15 
vote

public Date getDate(){
  try {
    calendar.setTime(dateFormatter.parse(getText()));
    calendar.set(Calendar.HOUR_OF_DAY,hours);
    calendar.set(Calendar.MINUTE,minutes);
    calendar.set(Calendar.SECOND,seconds);
    calendar.set(Calendar.MILLISECOND,millis);
    date=calendar.getTime();
  }
 catch (  ParseException e) {
    date=null;
  }
  return date;
}
 

Example 68

From project CalendarPortlet, under directory /src/main/java/org/jasig/portlet/calendar/adapter/.

Source file: CalendarEventsDao.java

  15 
vote

public Set<CalendarDisplayEvent> getEvents(ICalendarAdapter adapter,CalendarConfiguration calendar,Interval interval,PortletRequest request,DateTimeZone tz){
  final CalendarEventSet eventSet=adapter.getEvents(calendar,interval,request);
  final String tzKey=eventSet.getKey().concat(tz.getID());
  Element cachedElement=this.cache.get(tzKey);
  if (cachedElement != null) {
    @SuppressWarnings("unchecked") final Set<CalendarDisplayEvent> jsonEvents=(Set<CalendarDisplayEvent>)cachedElement.getValue();
    return jsonEvents;
  }
 else {
    final Set<CalendarDisplayEvent> displayEvents=new HashSet<CalendarDisplayEvent>();
    for (    VEvent event : eventSet.getEvents()) {
      try {
        displayEvents.addAll(getDisplayEvents(event,interval,tz));
      }
 catch (      ParseException e) {
        log.error("Exception parsing event",e);
      }
catch (      IOException e) {
        log.error("Exception parsing event",e);
      }
catch (      URISyntaxException e) {
        log.error("Exception parsing event",e);
      }
    }
    cachedElement=new Element(tzKey,displayEvents);
    this.cache.put(cachedElement);
    return displayEvents;
  }
}
 

Example 69

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

Source file: IncidentSaver.java

  15 
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 70

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

Source file: IncidentSaver.java

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

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

Source file: IncidentSaver.java

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

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

Source file: ProcessIncidents.java

  15 
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;
}