List of usage examples for java.text ParsePosition ParsePosition
public ParsePosition(int index)
From source file:easyJ.common.validate.GenericTypeValidator.java
/** * Checks if the value can safely be converted to a short primitive. * //from w w w . ja v a2 s . c o m * @param value * The value validation is being performed on. * @param locale * The locale to use to parse the number (system default if * null)vv * @return the converted Short value. */ public static Short formatShort(String value, Locale locale) { Short result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getNumberInstance(locale); } else { formatter = NumberFormat.getNumberInstance(Locale.getDefault()); } formatter.setParseIntegerOnly(true); ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) { result = new Short(num.shortValue()); } } } return result; }
From source file:org.orcid.core.cli.MigrateFundingAmountToANumericValue.java
private BigDecimal getAmountAsBigDecimal(String amount, String currencyCode, Locale locale) throws Exception { try {//from w ww .j av a 2 s . c o m ParsePosition parsePosition = new ParsePosition(0); NumberFormat numberFormat = NumberFormat.getInstance(locale); Number number = null; if (!PojoUtil.isEmpty(currencyCode)) { Currency currency = Currency.getInstance(currencyCode); String currencySymbol = currency.getSymbol(); number = numberFormat.parse(amount.replace(currencySymbol, StringUtils.EMPTY), parsePosition); } else { number = numberFormat.parse(amount, parsePosition); } if (parsePosition.getIndex() != amount.length()) throw new Exception("Unable to parse amount into BigDecimal"); return new BigDecimal(number.toString()); } catch (Exception e) { throw e; } }
From source file:com.feilong.core.text.DateFormatUtilTemp.java
/** * <code>dateString</code> ?. * // w w w . j a va 2 s . c o m * @param dateString * the date string * @param pattern * {@link com.feilong.core.DatePattern} ? * @param locale * , null, {@link Locale#getDefault()} * @return <code>dateString</code> null, {@link NullPointerException}<br> * <code>dateString</code> blank, {@link IllegalArgumentException}<br> * <code>pattern</code> null, {@link NullPointerException}<br> * <code>pattern</code> blank, {@link IllegalArgumentException}<br> * ? {@link java.text.SimpleDateFormat#parse(String, ParsePosition)} * @see SimpleDateFormat#parse(String) * @see SimpleDateFormat#parse(String, ParsePosition) */ public static Date parse(String dateString, String pattern, Locale locale) { Validate.notBlank(dateString, "dateString can't be null/empty!"); Validate.notBlank(pattern, "pattern can't be null/empty!"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, ObjectUtils.defaultIfNull(locale, Locale.getDefault())); //? java.text.DateFormat#parse(String) ParseException checked Exception return simpleDateFormat.parse(dateString, new ParsePosition(0));//?, null }
From source file:org.lingcloud.molva.ocl.util.GenericTypeValidator.java
/** * Checks if the value can safely be converted to a short primitive. * //from ww w . j ava2 s. c o m * @param value * The value validation is being performed on. * @param locale * The locale to use to parse the number (system default if * null)vv * @return the converted Short value. */ public static Short formatShort(String value, Locale locale) { Short result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getNumberInstance(locale); } else { formatter = NumberFormat.getNumberInstance(Locale.getDefault()); } formatter.setParseIntegerOnly(true); ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) { result = Short.valueOf(num.shortValue()); } } } return result; }
From source file:org.polymap.rhei.field.NumberValidator.java
public M transform2Model(String fieldValue) throws Exception { if (fieldValue == null) { return null; } else if (fieldValue instanceof String) { ParsePosition pp = new ParsePosition(0); Number result = nf.parse((String) fieldValue, pp); if (pp.getErrorIndex() > -1 || pp.getIndex() < ((String) fieldValue).length()) { throw new ParseException("field value: " + fieldValue, pp.getErrorIndex()); }//from w w w. ja v a 2s.co m log.debug("value: " + fieldValue + " -> " + result.doubleValue()); // XXX check max digits if (Float.class.isAssignableFrom(targetClass)) { return (M) Float.valueOf(result.floatValue()); } else if (Double.class.isAssignableFrom(targetClass)) { return (M) Double.valueOf(result.floatValue()); } else if (Integer.class.isAssignableFrom(targetClass)) { return (M) Integer.valueOf(result.intValue()); } else if (Long.class.isAssignableFrom(targetClass)) { return (M) Long.valueOf(result.longValue()); } else { throw new RuntimeException("Unsupported target type: " + targetClass); } } else { throw new RuntimeException("Unhandled field value type: " + fieldValue); } }
From source file:gov.vha.isaac.ucum.UCUMParser.java
/** * Execute the jSciense parser// w w w . j a va2 s. c o m * @param value * @param textToParseForUnit * @return */ public static ParsedUCUM jScienceParser(String value, String textToParseForUnit) { try { // Not sure if this is threadsafe... so no reuse javax.measure.unit.UnitFormat jScienceParser = javax.measure.unit.UnitFormat.getUCUMInstance(); javax.measure.unit.Unit<?> unit = jScienceParser.parseObject(textToParseForUnit, new ParsePosition(0)); if (unit != null) { return new ParsedUCUM(textToParseForUnit, value, unit); } } catch (Exception e) { // noop } return null; }
From source file:ro.cs.logaudit.web.servlet.ReportServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("doPost START"); ServletOutputStream sos = null;//from www .j a v a 2 s. c om StopWatch sw = new StopWatch(); sw.start("Retrieve report"); try { //create the bean containing the report parameters which will be passed to the Report Web Service Client AuditEventsReportParams reportParams = new AuditEventsReportParams(); //Retrieve the start date param for the report request SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm"); Date startDate = sdf.parse(ServletRequestUtils.getStringParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_START_DATE_PARAM), new ParsePosition(0)); if (startDate != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_START_DATE_PARAM, startDate); } //Retrieve the end date param for the report request Date endDate = sdf.parse(ServletRequestUtils.getStringParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_END_DATE_PARAM), new ParsePosition(0)); if (endDate != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_END_DATE_PARAM, endDate); } //Retrieve the personId param for the report request String personId = ServletRequestUtils.getStringParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PERSON_ID_PARAM); if (personId != null && personId != "") { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PERSON_ID_PARAM, Integer.valueOf(personId)); } //Retrieve the message param for the report request String message = ServletRequestUtils.getStringParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MESSAGE_PARAM); if (message != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MESSAGE_PARAM, message); } //Retrieve the event param for the report request String event = ServletRequestUtils.getStringParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_EVENT_PARAM); if (event != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_EVENT_PARAM, event); } //Retrieve the moduleId param for the report request Integer moduleId = ServletRequestUtils.getIntParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM); if (moduleId != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM, moduleId); } //Retrieve the reportTitle param for the report request String reportTitle = ServletRequestUtils.getStringParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PARAM_REPORT_TITLE); if (reportTitle != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PARAM_REPORT_TITLE, reportTitle); } //Retrieve the orientation param for the report request String orientation = ServletRequestUtils.getRequiredStringParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORIENTATION_PARAM); if (orientation != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORIENTATION_PARAM, orientation); } //Retrieve the report format param for the report request String format = ServletRequestUtils.getRequiredStringParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_FORMAT_PARAM); if (format != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_FORMAT_PARAM, format.toLowerCase()); } //Retrieve the organisationId param for the report request Integer organisationId = ServletRequestUtils.getIntParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORGANISATION_ID_PARAM); if (organisationId != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORGANISATION_ID_PARAM, organisationId); } reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_LOCALE_PARAM, request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME) .toString().toLowerCase().substring(0, 2)); //if the attachment param exists on the request, it means that the generated report must be a whole html page with head and body tags, //otherwise the report must be embeddable in an existent html page(no head and body tags) if (ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) != null) { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_HTML_IS_EMBEDDABLE, false); } else { reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_HTML_IS_EMBEDDABLE, true); } //Servlet's OutputStream sos = response.getOutputStream(); //get the requested report DataHandler reportFileReceived = ReportsWebServiceClient.getInstance() .getAuditEventsReport(reportParams); //set the response content type if (format.toLowerCase().equals("html")) { response.setContentType("text/html"); if (ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) != null) { response.setHeader("Content-Disposition", "attachment; filename=\"".concat(reportTitle).concat(".html\"")); } else { response.setHeader("Content-Disposition", "inline; filename=\"".concat(reportTitle).concat(".html\"")); } } else if (format.toLowerCase().equals("pdf")) { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "inline; filename=\"".concat(reportTitle).concat(".pdf\"")); } else if (format.toLowerCase().equals("doc")) { response.setContentType("application/msword"); response.setHeader("Content-Disposition", "attachment; filename=\"".concat(reportTitle).concat(".doc\"")); } else if (format.toLowerCase().equals("xls")) { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=\"".concat(reportTitle).concat(".xls\"")); } //write the received report bytes stream to response output stream byte buffer[] = new byte[4096]; BufferedInputStream bis = new BufferedInputStream(reportFileReceived.getInputStream()); int size = 0; int i; while ((i = bis.read(buffer, 0, 4096)) != -1) { sos.write(buffer, 0, i); size += i; } if (size == 0) { response.setContentType("text/plain"); sos.write("No content !".getBytes()); } bis.close(); response.setContentLength(size); logger.debug("**** report transfer completed !"); } catch (Exception ex) { logger.error("", ex); response.setContentType("text/html"); String exceptionCode = null; ; if (((Integer) ServletRequestUtils.getIntParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM)) .equals(new Integer(IConstant.NOM_MODULE_OM_LABEL_KEY))) { exceptionCode = ICodeException.AUDITOM_REPORT_CREATE; } else if (((Integer) ServletRequestUtils.getIntParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM)) .equals(new Integer(IConstant.NOM_MODULE_DM_LABEL_KEY))) { exceptionCode = ICodeException.AUDITDM_REPORT_CREATE; } else if (((Integer) ServletRequestUtils.getIntParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM)) .equals(new Integer(IConstant.NOM_MODULE_CM_LABEL_KEY))) { exceptionCode = ICodeException.AUDITCM_REPORT_CREATE; } else if (((Integer) ServletRequestUtils.getIntParameter(request, IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM)) .equals(new Integer(IConstant.NOM_MODULE_TS_LABEL_KEY))) { exceptionCode = ICodeException.AUDITTS_REPORT_CREATE; } response.getWriter().write("<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head> <script type=\"text/javascript\" src=\"js/cs/cs_common.js\"></script>" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/style.css\"/> " + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/fonts-min.css\" /> " + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/container.css\" /> </head> " + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/button.css\" />" + "<body> <div id=\"errorsContainer\" class=\"errorMessagesDiv\"> " + "<table class=\"errorMessagesTable\">" + "<tr>" + "<td>" + "</td>" + "<td>" + "<div class=\"hd\">" + "<div id=\"closeErrors\" class=\"messagesCloseButon\"></div>" + "</div>" + "</td>" + "</tr>" + "<tr>" + "<td>" + "<div class=\"bd\">" + "<div style=\"width:470px\"> " + messageSource.getMessage(CREATE_ERROR, new Object[] { exceptionCode, ControllerUtils.getInstance().getFormattedCurrentTime() }, (Locale) request.getSession() .getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME)) + "<br/> " + "</div>" + "</div>" + "</td>" + "<td>" + "</td>" + "</tr>" + "</table>" + "<div class=\"ft\"> </div>" + "</div>" + "<script> " + "if(typeof(YAHOO.widget.Module) != \"undefined\") { " + "YAHOO.audit.errorsContainer = new YAHOO.widget.Module(\"errorsContainer\", {visible:true} ); " + "YAHOO.audit.errorsContainer.render() ;" + "YAHOO.audit.errorsContainer.show();" + "YAHOO.util.Event.addListener(\"closeErrors\", \"click\", function () { " + "YAHOO.audit.errorsContainer.hide();" + "YAHOO.audit.errorsContainer.destroy(); " + "}, YAHOO.audit.errorsContainer, true);" + "}" + "</script> </body></html>"); response.getWriter().flush(); } finally { if (sos != null) { //Flushing and Closing OutputStream sos.flush(); sos.close(); logger.debug("**** servlet output stream closed."); } } logger.debug("doPost END"); //list all the tasks performed logger.debug(sw.prettyPrint()); sw.stop(); }
From source file:com.xylocore.copybook.runtime.converters.SimpleDateFormatDateConverter.java
@Override protected Object decodeExternalNumeric(DataUsageCategory aDataUsageCategory, ExternalNumericPICMarshaller aPICMarshaller, CopybookContext aContext, int aOffset, int aDigits, SignType aSignType, SignPosition aSignPosition, int aPrecision, int aScalingPosition) { assert aPICMarshaller != null; assert aContext != null; long myValue = aPICMarshaller.decodeAsLong(aContext, aOffset, aDigits, aSignType, aSignPosition, aPrecision, aScalingPosition);/*from w w w. j a va 2 s .c o m*/ Date myDate; if (!aContext.isError()) { StringBuilder myBuffer = aContext.getWorkStringBuilder(pattern.length()); FormatHelper.formatNumber(myBuffer, myValue, pattern.length(), true, FormatHelper.Justify.Right); SimpleDateFormat myDateFormat = DateHelper.getThreadLocalSimpleDateFormat(pattern); ParsePosition myParsePosition = new ParsePosition(0); myDate = myDateFormat.parse(myBuffer.toString(), myParsePosition); if (myDate == null) { aContext.setError(CopybookError.InvalidDateFormat, null); } } else { myDate = null; } return myDate; }
From source file:edu.usu.sdl.openstorefront.web.rest.service.NotificationService.java
@POST @APIDescription("Sends recent change email to all user that are flag to be notified or an email via the query param") @RequireAdmin/*from ww w . j a v a 2 s. c o m*/ @Path("/recent-changes") public Response recentChanges( @QueryParam("lastRunDts") @APIDescription("MM/dd/yyyy or Unix Epoch - (Defaults to the beginning of the current day in server time)") String lastRunDtsValue, @QueryParam("emailAddress") @APIDescription("Set to send a preview email just to that address") String emailAddress) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy"); Date lastRunDts; if (StringUtils.isBlank(lastRunDtsValue)) { lastRunDts = TimeUtil.beginningOfDay(TimeUtil.currentDate()); } else { lastRunDts = simpleDateFormat.parse(lastRunDtsValue, new ParsePosition(0)); if (lastRunDts == null) { if (StringUtils.isNumeric(lastRunDtsValue)) { lastRunDts = new Date(Convert.toLong(lastRunDtsValue)); } } } if (lastRunDts != null) { TaskRequest taskRequest = new TaskRequest(); taskRequest.setAllowMultiple(true); taskRequest.setName("Send Recent Change Email"); String email = ""; if (StringUtils.isNotBlank(emailAddress)) { email = " Email: " + emailAddress; } taskRequest.setDetails("Start Date: " + lastRunDts + email); service.getAsyncProxy(service.getUserService(), taskRequest).sendRecentChangeEmail(lastRunDts, emailAddress); } else { throw new OpenStorefrontRuntimeException("Unable to parse last run dts", "Check last run dts param format (MM/dd/yyyy) "); } return Response.ok().build(); }
From source file:ltt.intership.data.StreamRenderer.java
private void renderTimeStamp(JSONObject post, Post p) { String dateStr = post.optString("created_time"); SimpleDateFormat formatter = getDateFormat(); ParsePosition pos = new ParsePosition(0); Date date = formatter.parse(dateStr, pos); p.setTime(date);/*from w w w .java 2s. co m*/ }