类java.text.ParseException源码实例Demo

下面列出了怎么用java.text.ParseException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: cachecloud   文件: AppController.java
/**
 * 应用日报查询
 */
@RequestMapping("/daily")
public ModelAndView appDaily(HttpServletRequest request,
                              HttpServletResponse response, Model model, Long appId) throws ParseException {
    // 1. 应用信息
    AppDesc appDesc = appService.getByAppId(appId);
    model.addAttribute("appDesc", appDesc);

    // 2. 日期
    String dailyDateParam = request.getParameter("dailyDate");
    Date date;
    if (StringUtils.isBlank(dailyDateParam)) {
        date = DateUtils.addDays(new Date(), -1);
    } else {
        date = DateUtil.parseYYYY_MM_dd(dailyDateParam);
    }
    model.addAttribute("dailyDate", dailyDateParam);

    // 3. 日报
    AppDailyData appDailyData = appDailyDataCenter.getAppDailyData(appId, date);
    model.addAttribute("appDailyData", appDailyData);

    return new ModelAndView("app/appDaily");
}
 
源代码2 项目: alfresco-remote-api   文件: PublicApiClient.java
public AuditEntry getAuditEntry(String applicationId, String entryId, Map<String, String> param, int expectedStatus)
        throws PublicApiException, ParseException
{
    HttpResponse response = getSingle("audit-applications", applicationId, "audit-entries",entryId,
            param, "Failed to get Audit Application " + applicationId, expectedStatus);

    if (response != null && response.getJsonResponse() != null)
    {
        JSONObject jsonList = (JSONObject) response.getJsonResponse().get("entry");
        if (jsonList != null)
        {
            return AuditEntry.parseAuditEntry(jsonList);
        }
    }
    return null;
}
 
源代码3 项目: alfresco-remote-api   文件: WebScriptUtil.java
public static Date getDate(JSONObject json) throws ParseException
{
    if(json == null)
    {
        return null;
    }
    String dateTime = json.optString(DATE_TIME);
    if(dateTime == null)
    {
        return null;
    }
    String format = json.optString(FORMAT);
    if(format!= null && ISO8601.equals(format) == false)
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.parse(dateTime);
    }
    return ISO8601DateFormat.parse(dateTime);
}
 
源代码4 项目: zxpoly   文件: HexValue4Field.java
public HexValue4Field() {
  super();
  final JFormattedTextField.AbstractFormatter FORMAT;
  try {
    final MaskFormatter formatter = new MaskFormatter("HHHH");
    formatter.setPlaceholderCharacter('0');
    formatter.setValidCharacters(ALLOWED_CHARS);
    formatter.setAllowsInvalid(false);
    FORMAT = formatter;
  } catch (ParseException ex) {
    throw new Error("Can't prepare formatter", ex);
  }

  setFormatter(FORMAT);
  refreshTextValue();
}
 
源代码5 项目: Alite   文件: PropertyListParser.java
/**
 * Parses a property list from a file.
 *
 * @param f The property list file.
 * @return The root object in the property list. This is usually a NSDictionary but can also be a NSArray.
 * @throws javax.xml.parsers.ParserConfigurationException If a document builder for parsing a XML property list
 *                                                        could not be created. This should not occur.
 * @throws java.io.IOException If any IO error occurs while reading the file.
 * @throws org.xml.sax.SAXException If any parse error occurs.
 * @throws com.dd.plist.PropertyListFormatException If the given property list has an invalid format.
 * @throws java.text.ParseException If a date string could not be parsed.
 */
public static NSObject parse(File f) throws IOException, PropertyListFormatException, ParseException, ParserConfigurationException, SAXException {
    FileInputStream fis = new FileInputStream(f);
    int type = determineType(fis);
    fis.close();
    switch(type) {
        case TYPE_BINARY:
            return BinaryPropertyListParser.parse(f);
        case TYPE_XML:
            return XMLPropertyListParser.parse(f);
        case TYPE_ASCII:
            return ASCIIPropertyListParser.parse(f);
        default:
            throw new PropertyListFormatException("The given file is not a property list of a supported format.");
    }
}
 
源代码6 项目: hudi   文件: HoodieWriteClient.java
/**
 * Commit Compaction and track metrics.
 */
protected void completeCompaction(HoodieCommitMetadata metadata, JavaRDD<WriteStatus> writeStatuses, HoodieTable<T> table,
                                  String compactionCommitTime) {

  List<HoodieWriteStat> writeStats = writeStatuses.map(WriteStatus::getStat).collect();
  finalizeWrite(table, compactionCommitTime, writeStats);
  LOG.info("Committing Compaction " + compactionCommitTime + ". Finished with result " + metadata);
  CompactHelpers.completeInflightCompaction(table, compactionCommitTime, metadata);

  if (compactionTimer != null) {
    long durationInMs = metrics.getDurationInMs(compactionTimer.stop());
    try {
      metrics.updateCommitMetrics(HoodieActiveTimeline.COMMIT_FORMATTER.parse(compactionCommitTime).getTime(),
          durationInMs, metadata, HoodieActiveTimeline.COMPACTION_ACTION);
    } catch (ParseException e) {
      throw new HoodieCommitException("Commit time is not of valid format. Failed to commit compaction "
          + config.getBasePath() + " at time " + compactionCommitTime, e);
    }
  }
  LOG.info("Compacted successfully on commit " + compactionCommitTime);
}
 
源代码7 项目: java-swing-tips   文件: MainPanel.java
private static void createAndShowGui() {
  Class<?> clz = MainPanel.class;
  try (InputStream is = clz.getResourceAsStream("button.xml")) {
    SynthLookAndFeel synth = new SynthLookAndFeel();
    synth.load(is, clz);
    UIManager.setLookAndFeel(synth);
  } catch (IOException | ParseException | UnsupportedLookAndFeelException ex) {
    ex.printStackTrace();
    Toolkit.getDefaultToolkit().beep();
  }
  // try {
  //   SynthLookAndFeel synth = new SynthLookAndFeel();
  //   synth.load(clz.getResource("button.xml"));
  //   UIManager.setLookAndFeel(synth);
  // } catch (IOException | ParseException | UnsupportedLookAndFeelException ex) {
  //   ex.printStackTrace();
  // }
  JFrame frame = new JFrame("@[email protected]");
  frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  frame.getContentPane().add(new MainPanel());
  frame.pack();
  frame.setLocationRelativeTo(null);
  frame.setVisible(true);
}
 
源代码8 项目: openjdk-jdk9   文件: ExsltDatetime.java
/**
 * Get the start of zone information if the input ends
 * with 'Z' or +/-hh:mm. If a zone string is not
 * found, return -1; if the zone string is invalid,
 * return -2.
 */
private static int getZoneStart (String datetime)
{
  if (datetime.indexOf("Z") == datetime.length()-1)
    return datetime.length()-1;
  else if (datetime.length() >=6
            && datetime.charAt(datetime.length()-3) == ':'
            && (datetime.charAt(datetime.length()-6) == '+'
                || datetime.charAt(datetime.length()-6) == '-'))
  {
    try
    {
      SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
      dateFormat.setLenient(false);
      Date d = dateFormat.parse(datetime.substring(datetime.length() -5));
      return datetime.length()-6;
    }
    catch (ParseException pe)
    {
      System.out.println("ParseException " + pe.getErrorOffset());
      return -2; // Invalid.
    }

  }
    return -1; // No zone information.
}
 
源代码9 项目: YiBo   文件: GMTDateGsonAdapter.java
@Override
public Date deserialize(JsonElement json, final Type typeOfT,
		JsonDeserializationContext context) throws JsonParseException {
	if (json.isJsonNull()) {
           return null;
       }
       if (!json.isJsonPrimitive()) {
           throw new JsonParseException("it' not json primitive");
       }
       final JsonPrimitive primitive = (JsonPrimitive) json;
       if (!primitive.isString()) {
           throw new JsonParseException("Expected string for date type");
       }
       try {
       	synchronized (dateFormat) {
               return dateFormat.parse(primitive.getAsString());
		}
       } catch (ParseException e) {
           throw new JsonParseException("Not a date string");
       }
}
 
源代码10 项目: danyuan-application   文件: DateUtils.java
/**
 * 从日期FROM到日期TO的天数
 *
 * @param dateStrFrom
 *            日期FROM("yyyy-MM-dd")
 * @param dateStrTo
 *            日期TO("yyyy-MM-dd")
 * @author 2015/06/11 Jinhui
 * @return int 天数
 */
public static int getDaysIn2Day(String dateStrFrom, String dateStrTo) {
	
	if (StringUtils.isEmpty(dateStrFrom) || StringUtils.isEmpty(dateStrTo)) {
		return 0;
	}
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	Calendar fromCalendar = Calendar.getInstance();
	Calendar toCalendar = Calendar.getInstance();
	try {
		fromCalendar.setTime(sdf.parse(dateStrFrom.trim()));
		toCalendar.setTime(sdf.parse(dateStrTo.trim()));
	} catch (ParseException ex) {
		throw new RuntimeException(ex);
	}
	long day = (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (24 * 60 * 60 * 1000);
	
	return ConvUtils.convToInt(day);
}
 
源代码11 项目: lucene-solr   文件: TestVersion.java
public void testParseLenientlyExceptions() {
  ParseException expected = expectThrows(ParseException.class, () -> {
    Version.parseLeniently("LUCENE");
  });
  assertTrue(expected.getMessage().contains("LUCENE"));

  expected = expectThrows(ParseException.class, () -> {
    Version.parseLeniently("LUCENE_610");
  });
  assertTrue(expected.getMessage().contains("LUCENE_610"));

  expected = expectThrows(ParseException.class, () -> {
    Version.parseLeniently("LUCENE61");
  });
  assertTrue(expected.getMessage().contains("LUCENE61"));

  expected = expectThrows(ParseException.class, () -> {
    Version.parseLeniently("LUCENE_7.0.0");
  });
  assertTrue(expected.getMessage().contains("LUCENE_7.0.0"));
}
 
源代码12 项目: springbootexamples   文件: CourseController.java
@RequestMapping("/dates")
public String dates(Model model) throws ParseException{
	Date date = new Date();
	model.addAttribute("date",date);
	
	String dateStr = "2018-05-30";
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	Date date2 =  sdf.parse(dateStr); 
	Date[] datesArray = new Date[2];
	datesArray[0] = date;
	datesArray[1] = date2;
	model.addAttribute("datesArray",datesArray);
	
	List<Date> datesList = new ArrayList<Date>();
	datesList.add(date);
	datesList.add(date2);
	model.addAttribute("datesList",datesList);
	return "/course/dates";
}
 
/**
 * Tests without EQUALITY
 * 
 * @throws ParseException
 */
@Test
public void testNoqualityMR() throws ParseException
{
    String value = "( 2.5.4.58 NAME 'attributeCertificateAttribute' " + "DESC 'attribute certificate use ;binary' "
        + "SYNTAX 1.3.6.1.4.1.1466.115.121.1.8 ) ";
    AttributeType attributeType = parser.parse( value );

    assertEquals( "2.5.4.58", attributeType.getOid() );
    assertEquals( 1, attributeType.getNames().size() );
    assertEquals( "attributeCertificateAttribute", attributeType.getNames().get( 0 ) );
    assertEquals( "attribute certificate use ;binary", attributeType.getDescription() );
    assertNull( attributeType.getSuperiorOid() );
    assertNull( attributeType.getEqualityOid() );
    assertEquals( "1.3.6.1.4.1.1466.115.121.1.8", attributeType.getSyntaxOid() );
    assertEquals( UsageEnum.USER_APPLICATIONS, attributeType.getUsage() );
    assertEquals( 0, attributeType.getExtensions().size() );
}
 
源代码14 项目: j2objc   文件: NumberRegressionTests.java
/**
 * NumberFormat does not parse negative zero.
 */
@Test
public void Test4162852() throws ParseException {
    for (int i=0; i<2; ++i) {
        NumberFormat f = (i == 0) ? NumberFormat.getInstance()
            : NumberFormat.getPercentInstance();
        double d = -0.0;
        String s = f.format(d);
        double e = f.parse(s).doubleValue();
        logln("" +
              d + " -> " +
              '"' + s + '"' + " -> " +
          e);
        if (e != 0.0 || 1.0/e > 0.0) {
            logln("Failed to parse negative zero");
        }
    }
}
 
源代码15 项目: openjdk-jdk8u-backup   文件: ExsltDatetime.java
/**
 * Get the start of zone information if the input ends
 * with 'Z' or +/-hh:mm. If a zone string is not
 * found, return -1; if the zone string is invalid,
 * return -2.
 */
private static int getZoneStart (String datetime)
{
  if (datetime.indexOf("Z") == datetime.length()-1)
    return datetime.length()-1;
  else if (datetime.length() >=6
            && datetime.charAt(datetime.length()-3) == ':'
            && (datetime.charAt(datetime.length()-6) == '+'
                || datetime.charAt(datetime.length()-6) == '-'))
  {
    try
    {
      SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
      dateFormat.setLenient(false);
      Date d = dateFormat.parse(datetime.substring(datetime.length() -5));
      return datetime.length()-6;
    }
    catch (ParseException pe)
    {
      System.out.println("ParseException " + pe.getErrorOffset());
      return -2; // Invalid.
    }

  }
    return -1; // No zone information.
}
 
源代码16 项目: development   文件: SupplierRevenueShareBuilder.java
public RDOSupplierRevenueShareReports buildReports()
        throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, ParseException {
    if (sqlData == null || sqlData.isEmpty()) {
        return new RDOSupplierRevenueShareReports();
    }

    RDOSupplierRevenueShareReports result = new RDOSupplierRevenueShareReports();
    result.setEntryNr(idGen.nextValue());
    result.setServerTimeZone(DateConverter.getCurrentTimeZoneAsUTCString());

    for (ReportData data : sqlData) {
        xmlDocument = XMLConverter.convertToDocument(data.getResultXml(),
                false);
        result.getReports().add(build(data, result.getEntryNr()));
    }
    return result;
}
 
源代码17 项目: pingid-api-playground   文件: User.java
@SuppressWarnings("unused")
private Date parseDate(String dateToParse) {

	SimpleDateFormat PingIDDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	PingIDDateFormat.setTimeZone(TimeZone.getTimeZone("America/Denver"));
	
	if (dateToParse != null) {
		try {
			return PingIDDateFormat.parse(dateToParse);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	
	return null;
}
 
/**
 * Validate Log Parser with prod data
 *
 * @throws ParseException
 * @throws URISyntaxException
 * @throws StorageException
 * @throws IOException
 * @throws InterruptedException
 */
@Test
public void testCloudAnalyticsClientParseProdLogs() throws ParseException, URISyntaxException, StorageException,
        IOException {

    Calendar startTime = new GregorianCalendar();
    startTime.add(GregorianCalendar.HOUR_OF_DAY, -2);

    Iterator<LogRecord> logRecordsIterator = (this.client.listLogRecords(StorageService.BLOB, startTime.getTime(),
            null, null, null)).iterator();

    while (logRecordsIterator.hasNext()) {
        // Makes sure there's no exceptions thrown and that no records are null.
        // Primarily a sanity check.
        LogRecord rec = logRecordsIterator.next();
        System.out.println(rec.getRequestUrl());
        assertNotNull(rec);
    }
}
 
源代码19 项目: mars-sim   文件: NumberTextField.java
/**
 * Tries to parse the user input to a number according to the provided
 * NumberFormat
 */
private void parseAndFormatInput() {
    try {
        String input = getText();
        if (input == null || input.length() == 0) {
            return;
        }
        Number parsedNumber = nf.parse(input);
        BigDecimal newValue = new BigDecimal(parsedNumber.toString());
        setNumber(newValue);
        selectAll();
    } catch (ParseException ex) {
        // If parsing fails keep old number
        setText(nf.format(number.get()));
    }
}
 
源代码20 项目: cellery-security   文件: Utils.java
public static Map<String, Object> getCustomClaims(SignedJWT signedJWT) throws ParseException {

        return signedJWT.getJWTClaimsSet().getClaims().entrySet()
                .stream()
                .filter(x -> !FILTERED_CLAIMS.contains(x.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }
 
private static YearMonthDay getWhenProcessedBySibsFrom(String[] fields) {
    try {
        return new YearMonthDay(new SimpleDateFormat(DATE_FORMAT).parse(fields[4].substring(0, DATE_FORMAT.length())));
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}
 
源代码22 项目: Collection-Android   文件: DateUtils.java
static Date parseStr2Date(String str){
    try {
        if(str.endsWith(".SSS")){
            return DF_SSS.parse(str);
        }else{
            return DF.parse(str);
        }
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }
}
 
源代码23 项目: graylog-plugin-aggregates   文件: ChartFactory.java
public static JFreeChart generateTimeSeriesChart(String title, List<HistoryAggregateItem> history, String timespan, Calendar cal) throws ParseException {
			
	TimeSeries series = initializeSeries(timespan, cal, history);
		  
	TimeSeriesCollection dataset = new TimeSeriesCollection();  
	dataset.addSeries(series);
	IntervalXYDataset idataset = new XYBarDataset(dataset, 1);
	
	
	JFreeChart chart = org.jfree.chart.ChartFactory.createXYBarChart(  
			title, // Title  
			"Date/time",         // X-axis Label
			true,
			"Hits",       // Y-axis Label  
			idataset,        // Dataset
			PlotOrientation.VERTICAL,  
			true,          // Show legend  
			true,          // Use tooltips  
			false          // Generate URLs  
			);
	
	chart.setBackgroundPaint(Color.WHITE);
	chart.setBorderPaint(Color.BLACK);
	
	XYPlot plot = (XYPlot)chart.getPlot();
	plot.setBackgroundPaint(Color.LIGHT_GRAY);
	
	plot.getRenderer().setSeriesPaint(0, Color.BLUE);
	plot.setDomainGridlinePaint(Color.GRAY);
       plot.setRangeGridlinePaint(Color.GRAY);
	chart.removeLegend();

	return chart;
}
 
源代码24 项目: astor   文件: FastDateParserTest.java
@Test
public void testParseNumerics() throws ParseException {
    Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
    cal.clear();
    cal.set(2003, 1, 10, 15, 33, 20);
    cal.set(Calendar.MILLISECOND, 989);

    DateParser fdf = getInstance("yyyyMMddHHmmssSSS", NEW_YORK, Locale.US);
    assertEquals(cal.getTime(), fdf.parse("20030210153320989"));
}
 
private SiteMembershipRequest getSiteMembershipRequest(String networkId, String runAsUserId, String personId) throws PublicApiException, ParseException
{
	publicApiClient.setRequestContext(new RequestContext(networkId, runAsUserId));

	int skipCount = 0;
	int maxItems = Integer.MAX_VALUE;
	Paging paging = getPaging(skipCount, maxItems);
	ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(personId, createParams(paging, null));
	List<SiteMembershipRequest> list = resp.getList();
	int size = list.size();
	assertTrue(size > 0);
	int idx = random.nextInt(size);
	SiteMembershipRequest request = list.get(idx);
	return request;
}
 
源代码26 项目: kogito-runtimes   文件: SmileRandomForest.java
/**
 * Build a set of features compatible with Smile's datasets from the map of input data
 *
 * @param data A map containing the input attribute names as keys and the attribute values as values.
 * @return A feature vector as a array of doubles.
 */
protected double[] buildFeatures(Map<String, Object> data) {
    final double[] features = new double[numAttributes];
    for (int i = 0; i < numAttributes; i++) {
        final String attrName = attributeNames.get(i);
        try {
            features[i] = smileAttributes.get(attrName).valueOf(data.get(attrName).toString());
        } catch (ParseException e) {
            logger.error(UNABLE_PARSE_TEXT, e);
        }
    }
    return features;
}
 
源代码27 项目: SimpleFlatMapper   文件: CsvMapperOptionalTest.java
private void testMapDbObject(CsvMapperBuilder<Optional<DbFinalObject>> builder)
	throws IOException, ParseException {
addDbObjectFields(builder);
CsvMapper<Optional<DbFinalObject>> mapper = builder.mapper();

List<Optional<DbFinalObject>> list = mapper.forEach(CsvMapperImplTest.dbObjectCsvReader(), new ListCollector<Optional<DbFinalObject>>()).getList();
assertEquals(1, list.size());
DbHelper.assertDbObjectMapping(list.get(0).get());
  }
 
源代码28 项目: cachecloud   文件: AppController.java
/**
 * 命令曲线
 * @param firstCommand 第一条命令
 */
@RequestMapping("/commandAnalysis")
public ModelAndView appCommandAnalysis(HttpServletRequest request,
                                       HttpServletResponse response, Model model, Long appId, String firstCommand) throws ParseException {
    // 1.获取app的VO
    AppDetailVO appDetail = appStatsCenter.getAppDetail(appId);
    model.addAttribute("appDetail", appDetail);

    // 2.返回日期
    TimeBetween timeBetween = getTimeBetween(request, model, "startDate", "endDate");

    // 3.是否超过1天
    if (timeBetween.getEndTime() - timeBetween.getStartTime() > TimeUnit.DAYS.toMillis(1)) {
        model.addAttribute("betweenOneDay", 0);
    } else {
        model.addAttribute("betweenOneDay", 1);
    }

    // 4.获取top命令
    List<AppCommandStats> allCommands = appStatsCenter.getTopLimitAppCommandStatsList(appId, timeBetween.getStartTime(), timeBetween.getEndTime(), 20);
    model.addAttribute("allCommands", allCommands);
    if (StringUtils.isBlank(firstCommand) && CollectionUtils.isNotEmpty(allCommands)) {
        model.addAttribute("firstCommand", allCommands.get(0).getCommandName());
    } else {
        model.addAttribute("firstCommand", firstCommand);
    }
    model.addAttribute("appId", appId);
    // 返回标签名
    return new ModelAndView("app/appCommandAnalysis");
}
 
源代码29 项目: sis   文件: GridMapping.java
/**
 * Creates a coordinate reference system by parsing a Well Known Text (WKT) string. The WKT is presumed
 * to use the GDAL flavor of WKT 1, and warnings are redirected to decoder listeners.
 */
private static CoordinateReferenceSystem createFromWKT(final Node node, final String wkt) throws ParseException {
    final WKTFormat f = new WKTFormat(node.getLocale(), node.decoder.getTimeZone());
    f.setConvention(org.apache.sis.io.wkt.Convention.WKT1_COMMON_UNITS);
    final CoordinateReferenceSystem crs = (CoordinateReferenceSystem) f.parseObject(wkt);
    final Warnings warnings = f.getWarnings();
    if (warnings != null) {
        final LogRecord record = new LogRecord(Level.WARNING, warnings.toString());
        record.setLoggerName(Modules.NETCDF);
        record.setSourceClassName(Variable.class.getCanonicalName());
        record.setSourceMethodName("getGridGeometry");
        node.decoder.listeners.warning(record);
    }
    return crs;
}
 
源代码30 项目: Raigad   文件: CronTimer.java
public Trigger getTrigger() throws ParseException {
    if (StringUtils.isNotBlank(triggerName)) {
        return new CronTrigger("CronTrigger" + triggerName, Scheduler.DEFAULT_GROUP, cronExpression);
    } else {
        return new CronTrigger("CronTrigger", Scheduler.DEFAULT_GROUP, cronExpression);
    }
}