Java Code Examples for java.text.ParseException#getMessage()

The following examples show how to use java.text.ParseException#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: gson_common_deserializer.java    From bitshares_wallet with MIT License 6 votes vote down vote up
@Override
public Date deserialize(JsonElement json,
                        Type typeOfT,
                        JsonDeserializationContext context) throws JsonParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {
        Date dateResult = simpleDateFormat.parse(json.getAsString());

        return dateResult;
    } catch (ParseException e) {
        e.printStackTrace();
        throw new JsonParseException(e.getMessage() + json.getAsString());
    }
}
 
Example 2
Source File: ConditionRouter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public ConditionRouter(URL url) {
    this.url = url;
    this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
    this.force = url.getParameter(Constants.FORCE_KEY, false);
    try {
        String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
        if (rule == null || rule.trim().length() == 0) {
            throw new IllegalArgumentException("Illegal route rule!");
        }
        rule = rule.replace("consumer.", "").replace("provider.", "");
        int i = rule.indexOf("=>");
        String whenRule = i < 0 ? null : rule.substring(0, i).trim();
        String thenRule = i < 0 ? rule.trim() : rule.substring(i + 2).trim();
        Map<String, MatchPair> when = StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<String, MatchPair>() : parseRule(whenRule);
        Map<String, MatchPair> then = StringUtils.isBlank(thenRule) || "false".equals(thenRule) ? null : parseRule(thenRule);
        // NOTE: When条件是允许为空的,外部业务来保证类似的约束条件
        this.whenCondition = when;
        this.thenCondition = then;
    } catch (ParseException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example 3
Source File: CustomDateEditor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse the Date from the given text, using the specified DateFormat.
 */
@Override
public void setAsText(String text) throws IllegalArgumentException {
	if (this.allowEmpty && !StringUtils.hasText(text)) {
		// Treat empty String as null value.
		setValue(null);
	}
	else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
		throw new IllegalArgumentException(
				"Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
	}
	else {
		try {
			setValue(this.dateFormat.parse(text));
		}
		catch (ParseException ex) {
			throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
		}
	}
}
 
Example 4
Source File: Distribution.java    From m2x-android with MIT License 6 votes vote down vote up
@Override
public void fromJson(JSONObject jsonObject) throws JSONException {
    id = jsonObject.optString("id", null);
    name = jsonObject.optString("name", null);
    description = jsonObject.optString("description", null);
    visibility = Visibility.parse(jsonObject.optString("visibility", null));
    status = jsonObject.optString("status", null);
    url = jsonObject.optString("url", null);
    key = jsonObject.optString("key", null);
    try {
        if (!jsonObject.isNull("created"))
            created = DateUtils.stringToDateTime(jsonObject.getString("created"));
        if (!jsonObject.isNull("updated"))
            updated = DateUtils.stringToDateTime(jsonObject.getString("updated"));
    } catch (ParseException e) {
        throw new JSONException(e.getMessage());
    }
    if (!jsonObject.isNull("metadata")) {
        metadata = ArrayUtils.jsonObjectToMap(jsonObject.getJSONObject("metadata"));
    }
    if (!jsonObject.isNull("devices")) {
        devices = Devices.fromJsonObject(jsonObject.getJSONObject("devices"));
    }
}
 
Example 5
Source File: gson_common_deserializer.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Date deserialize(JsonElement json,
                        Type typeOfT,
                        JsonDeserializationContext context) throws JsonParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {
        Date dateResult = simpleDateFormat.parse(json.getAsString());

        return dateResult;
    } catch (ParseException e) {
        e.printStackTrace();
        throw new JsonParseException(e.getMessage() + json.getAsString());
    }
}
 
Example 6
Source File: GXCommon.java    From gurux.dlms.java with GNU General Public License v2.0 6 votes vote down vote up
public static GXDateTime getDateTime(final Object value) {
    GXDateTime dt;
    if (value instanceof GXDateTime) {
        dt = (GXDateTime) value;
    } else if (value instanceof java.util.Date) {
        dt = new GXDateTime((java.util.Date) value);
        dt.getSkip().add(DateTimeSkips.MILLISECOND);
    } else if (value instanceof java.util.Calendar) {
        dt = new GXDateTime((java.util.Calendar) value);
        dt.getSkip().add(DateTimeSkips.MILLISECOND);
    } else if (value instanceof String) {
        DateFormat f = new SimpleDateFormat();
        try {
            dt = new GXDateTime(f.parse(value.toString()));
            dt.getSkip().add(DateTimeSkips.MILLISECOND);
        } catch (ParseException e) {
            throw new IllegalArgumentException(
                    "Invalid date time value." + e.getMessage());
        }
    } else {
        throw new IllegalArgumentException("Invalid date format.");
    }
    return dt;
}
 
Example 7
Source File: DateUtil.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 获取两个日期之间的所有日期列表
 * @param startDate 起始日期,格式为yyyyMMdd
 * @param  endDate  结束日期,格式为yyyyMMdd
 * @return 返回值不包含起始日期和结束日期
 */
public static List<Integer> getCrossDayList(String startDate, String endDate){
    List<Integer> dayList = new ArrayList<>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Calendar startDay = Calendar.getInstance();
    Calendar endDay = Calendar.getInstance();
    try {
        startDay.setTime(sdf.parse(startDate));
        endDay.setTime(sdf.parse(endDate));
    } catch (ParseException e) {
        throw new IllegalArgumentException("无效入参:" + e.getMessage());
    }
    //起始日期大于等于结束日期,则返回空列表
    if(startDay.compareTo(endDay) >= 0){
        return dayList;
    }
    while(true){
        //日期+1,并判断是否到达了结束日
        startDay.add(Calendar.DATE, 1);
        if(startDay.compareTo(endDay) == 0){
            break;
        }
        dayList.add(Integer.parseInt(DateFormatUtils.format(startDay.getTime(), "yyyyMMdd")));
    }
    return dayList;
}
 
Example 8
Source File: JStaticJavaFile.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
protected  void build(OutputStream os) throws IOException {
    InputStream is = source.openStream();

    BufferedReader r = new BufferedReader(new InputStreamReader(is));
    PrintWriter w = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os)));
    LineFilter filter = createLineFilter();
    int lineNumber=1;

    try {
        String line;
        while((line=r.readLine())!=null) {
            line = filter.process(line);
            if(line!=null)
                w.println(line);
            lineNumber++;
        }
    } catch( ParseException e ) {
        throw new IOException("unable to process "+source+" line:"+lineNumber+"\n"+e.getMessage());
    }

    w.close();
    r.close();
}
 
Example 9
Source File: EventDateMappings.java    From unitime with Apache License 2.0 6 votes vote down vote up
@Override
@PreAuthorize("checkPermission('EventDateMappingEdit')")
public void save(Record record, SessionContext context, Session hibSession) {
	try {
		Formats.Format<Date> dateFormat = Formats.getDateFormat(Formats.Pattern.DATE_EVENT);
		EventDateMapping mapping = new EventDateMapping();
		mapping.setSession(SessionDAO.getInstance().get(context.getUser().getCurrentAcademicSessionId()));
		mapping.setClassDate(dateFormat.parse(record.getField(0)));
		mapping.setEventDate(dateFormat.parse(record.getField(1)));
		mapping.setNote(record.getField(2));
		record.setUniqueId((Long)hibSession.save(mapping));
		ChangeLog.addChange(hibSession,
				context,
				mapping,
				dateFormat.format(mapping.getClassDate()) + " &rarr; " + dateFormat.format(mapping.getEventDate()),
				Source.SIMPLE_EDIT, 
				Operation.CREATE,
				null,
				null);
	} catch (ParseException e) {
		throw new GwtRpcException(e.getMessage(), e);
	}
}
 
Example 10
Source File: JdbcJobConfigurationRepository.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
private Object createValue(final String value, final ParameterType parameterType) {
    if (ParameterType.LONG.equals(parameterType)) {
        return Long.parseLong(value);
    } else if (ParameterType.STRING.equals(parameterType)) {
        return value;
    } else if (ParameterType.DOUBLE.equals(parameterType)) {
        return Double.parseDouble(value);
    } else if (ParameterType.DATE.equals(parameterType)) {
        try {
            return this.dateFormat.parse(value);
        } catch (final ParseException e) {
            throw new SpringBatchLightminApplicationException(e, e.getMessage());
        }
    } else {
        throw new SpringBatchLightminApplicationException("Unsupported ParameterType: "
                + parameterType.getClazz().getSimpleName());
    }
}
 
Example 11
Source File: UserInfo.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 5 votes vote down vote up
UserInfo(JSONObject obj) throws JSONException {
    this.nickname = obj.getString("n");
    this.idCode = obj.getString("idc");

    try {
        this.sigil = Name.Sigil.parse(obj.getString("?"));
    } catch (ParseException ex) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) throw new JSONException(ex);
        else throw new JSONException(ex.getMessage());
    }
}
 
Example 12
Source File: DateUtil.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 日期比较,当baseDate小于compareDate时,返回TRUE,当大于等于时,返回false
 *
 * @param format
 *            日期字符串格式
 * @param baseDate
 *            被比较的日期
 * @param compareDate
 *            比较日期
 * @return
 */
public static boolean before(String format, String baseDate,
                             String compareDate) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
    try {
        Date base = simpleDateFormat.parse(baseDate);
        Date compare = simpleDateFormat.parse(compareDate);

        return compare.before(base);
    } catch (ParseException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 13
Source File: DateTranslator.java    From mdw with Apache License 2.0 5 votes vote down vote up
public Object toObject(String str) throws TranslationException {
    try {
        return new SimpleDateFormat(dateFormat).parse(str);
    }
    catch (ParseException ex) {
        try {
            // service dates can now be passed in ISO format
            return Date.from(Instant.parse(str));
        }
        catch (DateTimeParseException ex2) {
            throw new TranslationException(ex.getMessage(), ex);
        }
    }
}
 
Example 14
Source File: CronUtils.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 返回一个字符串值,表示该消息无效Cron表达式给出有效性
 *
 * @param cronExpression Cron表达式
 * @return String 无效时返回表达式错误描述,如果有效返回null
 */
public static String getInvalidMessage(String cronExpression)
{
    try
    {
        new CronExpression(cronExpression);
        return null;
    }
    catch (ParseException pe)
    {
        return pe.getMessage();
    }
}
 
Example 15
Source File: Command.java    From m2x-android with MIT License 5 votes vote down vote up
@Override
public void fromJson(JSONObject jsonObject) throws JSONException {
    if (!jsonObject.isNull("status")) status = CommandStatus.parse(jsonObject.getString("status"));
    if (!jsonObject.isNull("received_at")) try {
        receivedAt = DateUtils.stringToDateTime(jsonObject.getString("received_at"));
    } catch (ParseException e) {
        throw new JSONException(e.getMessage());
    }
    if (!jsonObject.isNull("response_data")) {
        responseData = ArrayUtils.jsonObjectToMap(jsonObject);
    }
}
 
Example 16
Source File: NetscapeDraftSpec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
  * Parse the cookie attribute and update the corresponsing {@link Cookie}
  * properties as defined by the Netscape draft specification
  *
  * @param attribute {@link NameValuePair} cookie attribute from the
  * <tt>Set- Cookie</tt>
  * @param cookie {@link Cookie} to be updated
  * @throws MalformedCookieException if an exception occurs during parsing
  */
public void parseAttribute(
    final NameValuePair attribute, final Cookie cookie)
    throws MalformedCookieException {
        
    if (attribute == null) {
        throw new IllegalArgumentException("Attribute may not be null.");
    }
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null.");
    }
    final String paramName = attribute.getName().toLowerCase();
    final String paramValue = attribute.getValue();

    if (paramName.equals("expires")) {

        if (paramValue == null) {
            throw new MalformedCookieException(
                "Missing value for expires attribute");
        }
        try {
            DateFormat expiryFormat = new SimpleDateFormat(
                "EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
            Date date = expiryFormat.parse(paramValue);
            cookie.setExpiryDate(date);
        } catch (ParseException e) {
            throw new MalformedCookieException("Invalid expires "
                + "attribute: " + e.getMessage());
        }
    } else {
        super.parseAttribute(attribute, cookie);
    }
}
 
Example 17
Source File: JsonServlet.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private Date requiredDate ( final HttpServletRequest request, final String parameter ) throws ServletException
{
    final String dateToParse = requiredString ( request, parameter );
    try
    {
        return Utils.isoDateFormat.parse ( dateToParse );
    }
    catch ( final ParseException e )
    {
        throw new ServletException ( "parameter '" + parameter + "' threw " + e.getMessage () );
    }
}
 
Example 18
Source File: DateUtil.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 日期比较,当baseDate大于compareDate时,返回TRUE,当小于等于时,返回false
 * @param format
 *            日期字符串格式
 * @param baseDate
 *            被比较的日期
 * @param compareDate
 *            比较日期
 * @return
 */
public static boolean after(String format, String baseDate,
                             String compareDate) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
    try {
        Date base = simpleDateFormat.parse(baseDate);
        Date compare = simpleDateFormat.parse(compareDate);

        return compare.after(base);
    } catch (ParseException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 19
Source File: MappingReader.java    From openccg with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Starts reading from the next mapping group.
 * @return The next {@link MappingGroup} found by reading from the underlying reader.
 * @throws IOException If a {@link ParseException} is encountered when calling
 * {@link MappingFormat#parseMapping(String)} based on the underlying input, or if one is thrown by the
 * underlying reader. An IOException is also thrown if the number of mappings in the
 * {@linkplain MappingGroup#getLength() current group} could not be read. 
 */
public MappingGroup nextGroup() throws IOException {
	checkMappingCount();
	mappingCount = 0;
	
	MappingGroup previous = (currentGroup == null) ? null : currentGroup;
	int newCount = mappingQueue.size();
	
	currentGroup = (newCount == 0)
		? null : new MappingGroup(mappingQueue.peek().phraseNumber, newCount);
	
	boolean eog = false;
	
	while(!eog) {
		StringBuilder sb = new StringBuilder();
		
		int i;
		while((i = in.read()) != -1) {
			char c = (char)i;
			
			if(skipLF) {
				skipLF = false;
				if(c == '\n') {
					continue;
				}
			}
			
			if(c == '\r') {
				skipLF = true;
			}
			
			if(format.encodingScheme.isMappingDelimiter(c)) {
				break;
			}
			else if(format.encodingScheme.isGroupDelimiter(c)) {
				eog = true;
				break;
			}
			else {
				sb.append(c); 
			}
		}
		
		if(sb.length() == 0) {
			break; // for EOF and end of group
		}
		
		Mapping a = null;
		try {
			a = format.parseMapping(sb.toString());
		}
		catch(ParseException pe) {
			throw new IOException(((currentGroup == null) ? ""
					: "group " + currentGroup.phraseNumber + ": ") + "problem formatting mapping "
					+ sb.toString() + " at offset " + pe.getErrorOffset() + ": " + pe.getMessage(), pe);
		}
		
		// if the format allows null IDs, use previous's running counter
		if(currentGroup == null) {
			Integer I = (a.phraseNumber == null)
				? (previous == null) ? format.encodingScheme.getPhraseNumberBase().start
						: previous.phraseNumber + 1
				: a.phraseNumber;
			
			currentGroup = new MappingGroup(I, 0);
		}
		
		if(a.phraseNumber == null) {
			// have to copy because phraseNumber is immutable (and final)
			a = a.copyWithPhraseNumber(currentGroup.phraseNumber);
		}
		
		if(!currentGroup.phraseNumber.equals(a.phraseNumber)) {
			eog = true;
		}
		else {
			newCount++; // only increment if should be read
		}			
		
		if(!mappingQueue.offer(a)) { // save for next read
			throw new IOException("unable to read mapping");
		}
	}
	
	if(currentGroup != null) {
		currentGroup.length = newCount;
	}
	
	return (currentGroup == null || currentGroup.length == 0) ? null : currentGroup;
}
 
Example 20
Source File: WorkflowDataAccess.java    From mdw with Apache License 2.0 4 votes vote down vote up
protected String buildActivityWhere(Query query) throws DataAccessException {
    long instanceId = query.getLongFilter("instanceId");
    if (instanceId > 0)
        return "where ai.activity_instance_id = " + instanceId + "\n"; // ignore other criteria

    StringBuilder sb = new StringBuilder();
    sb.append("where ai.process_instance_id = pi.process_instance_id");

    // masterRequestId
    String masterRequestId = query.getFilter("masterRequestId");
    if (masterRequestId != null)
        sb.append(" and pi.master_request_id = '" + masterRequestId + "'\n");

    // status
    String status = query.getFilter("status");
    if (status != null && !status.equals("[Any]")) {
        if (status.equals("[Stuck]")) {
            sb.append(" and ai.status_cd in (")
                    .append(WorkStatus.STATUS_IN_PROGRESS)
                    .append(",").append(WorkStatus.STATUS_FAILED)
                    .append(",").append(WorkStatus.STATUS_WAITING)
                    .append(")\n");
        }
        else {
            sb.append(" and ai.status_cd = ").append(WorkStatuses.getCode(status)).append("\n");
        }
    }
    // startDate
    try {
        Date startDate = query.getDateFilter("startDate");
        if (startDate != null) {
            String start = getOracleDateFormat().format(startDate);
            if (db.isMySQL())
                sb.append(" and ai.start_dt >= STR_TO_DATE('").append(start).append("','%d-%M-%Y')\n");
            else
                sb.append(" and ai.start_dt >= '").append(start).append("'\n");
        }
    }
    catch (ParseException ex) {
        throw new DataAccessException(ex.getMessage(), ex);
    }

    // activity => <procId>:A<actId>
    String activity = query.getFilter("activity");
    if (activity != null) {
        if (db.isOracle()) {
            sb.append(" and (pi.PROCESS_ID || ':A' || ai.ACTIVITY_ID) = '" + activity + "'");
        }
        else {
            sb.append(" and CONCAT(pi.PROCESS_ID, ':A', ai.ACTIVITY_ID) = '" + activity + "'");
        }
    }

    return sb.toString();
}