List of usage examples for java.text ParseException getMessage
public String getMessage()
From source file:edu.ku.brc.ui.UIHelper.java
/** * @param mask//from w w w . j av a 2 s . c o m * @return */ public static MaskFormatter createFormatterMask(final String mask) { MaskFormatter maskFormatter = null; try { maskFormatter = new MaskFormatter(mask); } catch (java.text.ParseException exc) { System.err.println("formatter is bad: " + exc.getMessage()); System.exit(-1); } return maskFormatter; }
From source file:net.cbtltd.rest.AbstractReservation.java
/** * Availability calendar./* ww w . jav a2 s .c o m*/ * * @param pos the point of sale code. * @param productid the ID of the property * @param date the date from which the calendar is to be shown. * @return Availability calendar */ protected static synchronized CalendarResponse getAvailabilityCalendar(String pos, String productid, String date) { if (productid == null || productid.isEmpty() || productid.length() > 10) { throw new ServiceException(Error.product_id, productid); } if (date == null || date.isEmpty() || date.length() != 10) { throw new ServiceException(Error.date_invalid, date); } SqlSession sqlSession = RazorServer.openSession(); CalendarResponse response = new CalendarResponse(); try { Product product = sqlSession.getMapper(ProductMapper.class).read(productid); JSONService.getPartyWithPMCheck(sqlSession, pos, product.getSupplierid()); // this method checks agent's status and throws an exception in case of agent is inactive // JSONService.getParty(sqlSession, pos); Parameter action = new Parameter(); action.setId(productid); action.setFromdate(date); JSONService.DF.parse(date); ArrayList<CalendarElement> items = sqlSession.getMapper(ReservationMapper.class) .calendarelement(action); if (items != null && !items.isEmpty()) { CalendarElement[] array = new CalendarElement[items.size()]; items.toArray(array); response.setItems(array); } } catch (ParseException x) { response.setErrorMessage(x.getMessage()); LOG.error(x.getMessage()); // throw new ServiceException(Error.date_format); } catch (Throwable x) { response.setErrorMessage(x.getMessage()); LOG.error(x.getMessage()); } finally { sqlSession.close(); } return response; }
From source file:com.zimbra.cs.mailbox.calendar.Invite.java
private static void createFromCalendar(List<Invite> toAdd, Account account, String fragment, String method, TimeZoneMap tzmap, Iterator<ZComponent> compIter, boolean sentByMe, Mailbox mbx, int mailItemId, boolean continueOnError, InviteVisitor visitor) throws ServiceException { int compNum = 0; while (compIter.hasNext()) { ZComponent comp = compIter.next(); Invite newInv = null;/*w w w . ja v a 2s . co m*/ try { MailItem.Type type; ICalTok compTypeTok = comp.getTok(); if (compTypeTok == null) continue; if (ICalTok.VTODO.equals(compTypeTok)) { type = MailItem.Type.TASK; } else { type = MailItem.Type.APPOINTMENT; } switch (compTypeTok) { case VEVENT: case VTODO: boolean isEvent = ICalTok.VEVENT.equals(compTypeTok); boolean isTodo = ICalTok.VTODO.equals(compTypeTok); try { newInv = new Invite(type, method, tzmap, false); newInv.setLocalOnly(false); // set to true later if X-ZIMBRA-LOCAL-ONLY is present if (toAdd != null) toAdd.add(newInv); List<Object> addRecurs = new ArrayList<Object>(); List<Object> subRecurs = new ArrayList<Object>(); newInv.setComponentNum(compNum); if (mbx != null) newInv.setMailboxId(mbx.getId()); newInv.setMailItemId(mailItemId); newInv.setSentByMe(sentByMe); compNum++; List<ZComponent> subcomponents = Lists.newArrayList(comp.getComponentIterator()); for (ZComponent subcomp : subcomponents) { ICalTok subCompTypeTok = subcomp.getTok(); switch (subCompTypeTok) { case VALARM: Alarm alarm = Alarm.parse(subcomp); if (alarm != null) newInv.addAlarm(alarm); break; default: // ignore all other sub components } } boolean isTodoCompleted = false; boolean sawIntendedFreeBusy = false; List<ZProperty> properties = Lists.newArrayList(comp.getPropertyIterator()); for (ZProperty prop : properties) { String propVal = prop.getValue(); ICalTok propToken = prop.getToken(); if (propToken == null) { // Skip properties with missing value. There may be parameters specified, but // it's still wrong to send a property without value. They can only lead to // parse errors later, so ignore them. if (propVal == null || propVal.length() < 1) continue; String name = prop.getName(); if (name.startsWith("X-") || name.startsWith("x-")) newInv.addXProp(prop); } else if (propToken.equals(ICalTok.CATEGORIES)) { List<String> categories = prop.getValueList(); if (categories != null && !categories.isEmpty()) { for (String cat : categories) { newInv.addCategory(cat); } } } else { // Skip properties with missing value. There may be parameters specified, but // it's still wrong to send a property without value. They can only lead to // parse errors later, so ignore them. if (propVal == null || propVal.length() < 1) continue; switch (propToken) { case ORGANIZER: newInv.setOrganizer(new ZOrganizer(prop)); break; case ATTENDEE: newInv.addAttendee(new ZAttendee(prop)); break; case DTSTAMP: ParsedDateTime dtstamp = ParsedDateTime.parse(prop, tzmap); newInv.setDtStamp(dtstamp.getUtcTime()); break; case LAST_MODIFIED: ParsedDateTime lastModified = ParsedDateTime.parse(prop, tzmap); newInv.setLastModified(lastModified.getUtcTime()); break; case RECURRENCE_ID: ParsedDateTime rid = ParsedDateTime.parse(prop, tzmap); if (DebugConfig.enableThisAndFuture) { newInv.setRecurId(new RecurId(rid, prop.paramVal(ICalTok.RANGE, null))); } else { newInv.setRecurId(new RecurId(rid, RecurId.RANGE_NONE)); } break; case SEQUENCE: newInv.setSeqNo(prop.getIntValue()); break; case DTSTART: ParsedDateTime dtstart = ParsedDateTime.parse(prop, tzmap); newInv.setDtStart(dtstart); if (!dtstart.hasTime()) newInv.setIsAllDayEvent(true); break; case DTEND: if (isEvent) { ParsedDateTime dtend = ParsedDateTime.parse(prop, tzmap); newInv.setDtEnd(dtend); if (!dtend.hasTime()) newInv.setIsAllDayEvent(true); } break; case DUE: if (isTodo) { ParsedDateTime due = ParsedDateTime.parse(prop, tzmap); // DUE is for VTODO what DTEND is for VEVENT. newInv.setDtEnd(due); if (!due.hasTime()) newInv.setIsAllDayEvent(true); } break; case DURATION: ParsedDuration dur = ParsedDuration.parse(propVal); newInv.setDuration(dur); break; case LOCATION: newInv.setLocation(propVal); break; case SUMMARY: String summary = propVal; if (summary != null) { // Make sure SUMMARY is a single line. summary = summary.replaceAll("[\\\r\\\n]+", " "); } prop.setValue(summary); newInv.setName(summary); break; case DESCRIPTION: newInv.setDescription(propVal, newInv.mDescHtml); newInv.setFragment(Fragment.getFragment(propVal, true)); break; case X_ALT_DESC: ZParameter fmttype = prop.getParameter(ICalTok.FMTTYPE); if (fmttype != null && MimeConstants.CT_TEXT_HTML.equalsIgnoreCase(fmttype.getValue())) { String html = propVal; newInv.setDescription(newInv.mDescription, html); } else { // Unknown format. Just add as an x-prop. newInv.addXProp(prop); } break; case COMMENT: newInv.addComment(propVal); break; case UID: newInv.setUid(propVal); break; case RRULE: ZRecur recur = new ZRecur(propVal, tzmap); addRecurs.add(recur); newInv.setIsRecurrence(true); break; case RDATE: if (DebugConfig.enableRdate) { RdateExdate rdate = RdateExdate.parse(prop, tzmap); addRecurs.add(rdate); newInv.setIsRecurrence(true); } break; case EXRULE: ZRecur exrecur = new ZRecur(propVal, tzmap); subRecurs.add(exrecur); newInv.setIsRecurrence(true); break; case EXDATE: RdateExdate exdate = RdateExdate.parse(prop, tzmap); subRecurs.add(exdate); newInv.setIsRecurrence(true); break; case STATUS: String status = IcalXmlStrMap.sStatusMap.toXml(propVal); if (status != null) { if (IcalXmlStrMap.STATUS_IN_PROCESS.equals(status)) { String zstatus = prop.getParameterVal(ICalTok.X_ZIMBRA_STATUS, null); if (ICalTok.X_ZIMBRA_STATUS_WAITING.toString().equals(zstatus) || ICalTok.X_ZIMBRA_STATUS_DEFERRED.toString() .equals(zstatus)) { newInv.setStatus(IcalXmlStrMap.sStatusMap.toXml(zstatus)); } else { newInv.setStatus(status); } } else { newInv.setStatus(status); if (isTodo && IcalXmlStrMap.STATUS_COMPLETED.equals(status)) isTodoCompleted = true; } } break; case TRANSP: // TRANSP is examined only when intended F/B is not supplied. if (isEvent && !sawIntendedFreeBusy) { String transp = IcalXmlStrMap.sTranspMap.toXml(propVal); if (transp != null) { newInv.setTransparency(transp); // If transparent, set intended f/b to free. // If opaque, don't set intended f/b because there are multiple possibilities. if (newInv.isTransparent()) newInv.setFreeBusy(IcalXmlStrMap.FBTYPE_FREE); } } break; case CLASS: String classProp = IcalXmlStrMap.sClassMap.toXml(propVal); if (classProp != null) newInv.setClassProp(classProp); break; case X_MICROSOFT_CDO_ALLDAYEVENT: if (isEvent) { if (prop.getBoolValue()) newInv.setIsAllDayEvent(true); } break; case X_MICROSOFT_CDO_INTENDEDSTATUS: sawIntendedFreeBusy = true; if (isEvent) { String fb = IcalXmlStrMap.sOutlookFreeBusyMap.toXml(propVal); if (fb != null) { newInv.setFreeBusy(fb); // Intended F/B takes precedence over TRANSP. if (IcalXmlStrMap.FBTYPE_FREE.equals(fb)) newInv.setTransparency(IcalXmlStrMap.TRANSP_TRANSPARENT); else newInv.setTransparency(IcalXmlStrMap.TRANSP_OPAQUE); } } break; case PRIORITY: String prio = propVal; if (prio != null) newInv.setPriority(prio); break; case PERCENT_COMPLETE: if (isTodo) { String pctComplete = propVal; if (pctComplete != null) { newInv.setPercentComplete(pctComplete); if (prop.getIntValue() == 100) isTodoCompleted = true; } } break; case COMPLETED: if (isTodo) { ParsedDateTime completed = ParsedDateTime.parseUtcOnly(propVal); newInv.setCompleted(completed.getUtcTime()); isTodoCompleted = true; } break; case CONTACT: newInv.addContact(propVal); break; case GEO: Geo geo = Geo.parse(prop); newInv.setGeo(geo); break; case URL: newInv.setUrl(propVal); break; case X_ZIMBRA_LOCAL_ONLY: if (prop.getBoolValue()) newInv.setLocalOnly(true); break; case X_ZIMBRA_DISCARD_EXCEPTIONS: newInv.addXProp(prop); break; case X_ZIMBRA_CHANGES: newInv.addXProp(prop); break; case ATTACH: Attach attach = Attach.parse(prop); if (attach.getBinaryB64Data() != null) { newInv.addIcalendarAttach(attach); } break; } } } if (isTodoCompleted) { // set the status to Completed. newInv.setStatus(IcalXmlStrMap.STATUS_COMPLETED); // set percent-complete to 100 newInv.setPercentComplete(Integer.toString(100)); if (newInv.getCompleted() == 0) // set COMPLETED property to now if not already set. newInv.setCompleted(System.currentTimeMillis()); } newInv.setIsOrganizer(account); newInv.validateDuration(); ParsedDuration duration = newInv.getDuration(); if (duration == null) { ParsedDateTime end = newInv.getEndTime(); if (end != null && newInv.getStartTime() != null) { duration = end.difference(newInv.getStartTime()); } } if (!addRecurs.isEmpty() || !subRecurs.isEmpty()) { // We have a recurrence. Make sure DTSTART is not null. ParsedDateTime st = newInv.getStartTime(); if (st == null) { ParsedDateTime et = newInv.getEndTime(); if (et != null) { if (et.hasTime()) st = et.add(ParsedDuration.NEGATIVE_ONE_SECOND); else st = et.add(ParsedDuration.NEGATIVE_ONE_DAY); newInv.setDtStart(st); } else { // Both DTSTART and DTEND are unspecified. Recurrence makes no sense! throw ServiceException.INVALID_REQUEST("recurrence used without DTSTART", null); } } } InviteInfo inviteInfo = new InviteInfo(newInv); List<IRecurrence> addRules = new ArrayList<IRecurrence>(); if (addRecurs.size() > 0) { for (Iterator<Object> iter = addRecurs.iterator(); iter.hasNext();) { Object next = iter.next(); if (next instanceof ZRecur) { ZRecur cur = (ZRecur) next; addRules.add(new Recurrence.SimpleRepeatingRule(newInv.getStartTime(), duration, cur, inviteInfo)); } else if (next instanceof RdateExdate) { RdateExdate rdate = (RdateExdate) next; addRules.add(new Recurrence.SingleDates(rdate, duration, inviteInfo)); } } } List<IRecurrence> subRules = new ArrayList<IRecurrence>(); if (subRecurs.size() > 0) { for (Iterator<Object> iter = subRecurs.iterator(); iter.hasNext();) { Object next = iter.next(); if (next instanceof ZRecur) { ZRecur cur = (ZRecur) iter.next(); subRules.add(new Recurrence.SimpleRepeatingRule(newInv.getStartTime(), duration, cur, inviteInfo)); } else if (next instanceof RdateExdate) { RdateExdate exdate = (RdateExdate) next; subRules.add(new Recurrence.SingleDates(exdate, duration, inviteInfo)); } } } if (newInv.hasRecurId()) { if (addRules.size() > 0) { newInv.setRecurrence( new Recurrence.ExceptionRule(newInv.getRecurId(), newInv.getStartTime(), duration, new InviteInfo(newInv), addRules, subRules)); } } else { if (addRules.size() > 0) { // since exclusions can't affect DtStart, just ignore them if there are no add rules newInv.setRecurrence(new Recurrence.RecurrenceRule(newInv.getStartTime(), duration, new InviteInfo(newInv), addRules, subRules)); } } String location = newInv.getLocation(); if (location == null) newInv.setLocation(""); // Process callback. if (visitor != null) visitor.visit(newInv); } catch (ParseException e) { throw ServiceException.PARSE_ERROR("Unable to parse iCalendar data: " + e.getMessage(), e); } break; } } catch (ServiceException e) { if (!continueOnError) throw e; if (newInv != null) logIcsParseImportError(newInv, e); else ZimbraLog.calendar.warn("Skipping error during ics parse/import", e); } catch (RuntimeException e) { if (!continueOnError) throw e; if (newInv != null) logIcsParseImportError(newInv, e); else ZimbraLog.calendar.warn("Skipping error during ics parse/import", e); } } }
From source file:com.yuwang.pinju.web.module.shop.action.ShopOpenFlowAction.java
/** * ?B?/*from www. j a v a2 s.co m*/ * * @param shopBusinessInfoDO * @return */ private String validateSaveBusinessShopInfo2(ShopBusinessInfoDO shopBusinessInfoDO) { StringBuffer message = new StringBuffer(); message.append(validateMember()); if (message != null && message.length() > 0) { return message.toString(); } if (shopBusinessInfoDO != null) { if (null == shopBusinessInfoDO.getEnterpriseName() || "".equals(shopBusinessInfoDO.getEnterpriseName()) || shopBusinessInfoDO.getEnterpriseName().trim().length() == 0) { message.append("????!<br> "); } else { if (null != shopBusinessInfoDO.getEnterpriseName() && shopBusinessInfoDO.getEnterpriseName().length() > 30) { message.append("????30!<br> "); } } if (null == shopBusinessInfoDO.getBusinessLicenseNumber() || "".equals(shopBusinessInfoDO.getBusinessLicenseNumber()) || shopBusinessInfoDO.getBusinessLicenseNumber().trim().length() == 0) { message.append("???! <br>"); } else { if (null != shopBusinessInfoDO.getBusinessLicenseNumber() && shopBusinessInfoDO.getBusinessLicenseNumber().length() > 18) { message.append("???18?!<br> "); } else if (!ObjectUtil.isNum(shopBusinessInfoDO.getBusinessLicenseNumber())) { message.append("??! <br>"); } } if (null == shopBusinessInfoDO.getOrganizationCodeNumber() || "".equals(shopBusinessInfoDO.getOrganizationCodeNumber()) || shopBusinessInfoDO.getOrganizationCodeNumber().trim().length() == 0) { message.append("????! <br>"); } else { if (null != shopBusinessInfoDO.getOrganizationCodeNumber() && shopBusinessInfoDO.getOrganizationCodeNumber().length() > 10) { message.append("10???\"-\"????!<br>"); } else if (!ObjectUtil.isNumZ2(shopBusinessInfoDO.getOrganizationCodeNumber())) { message.append("10???\"-\"????!<br>"); } } if (null == shopBusinessInfoDO.getBusiness() || "".equals(shopBusinessInfoDO.getBusiness()) || shopBusinessInfoDO.getBusiness().trim().length() == 0) { message.append("???!<br> "); } else { if (null != shopBusinessInfoDO.getBusiness() && shopBusinessInfoDO.getBusiness().length() > 50) { message.append("???50!<br> "); } } if (null == businessLicenseEndDate || "".equals(businessLicenseEndDate)) { message.append("???!<br> "); } else { DateFormat format1 = null; if (null != businessLicenseEndDate && !ObjectUtil.isDate(businessLicenseEndDate)) { message.append("??!<br> "); } else { String str[] = businessLicenseEndDate.split("-"); if (str.length == 3) { businessLicenseEndDate = str[0] + "-" + str[1] + "-" + str[2]; format1 = new SimpleDateFormat("yyyy-MM-dd"); try { if (null != businessLicenseEndDate && format1.parse(businessLicenseEndDate).getTime() < new Date().getTime()) { message.append("????<br> "); } } catch (ParseException e) { log.error(e.getMessage()); } } else { message.append("??!<br> "); } } } if (null == shopBusinessInfoDO.getLegalName() || "".equals(shopBusinessInfoDO.getLegalName()) || shopBusinessInfoDO.getLegalName().trim().length() == 0) { message.append("???!<br> "); } else { if (null != shopBusinessInfoDO.getLegalName() && shopBusinessInfoDO.getLegalName().length() > 20) { message.append("???20! <br>"); } else if (!ObjectUtil.isZEng(shopBusinessInfoDO.getLegalName().trim())) { message.append("??? <br>"); } } if (null == shopBusinessInfoDO.getRegistAddress() || "".equals(shopBusinessInfoDO.getRegistAddress()) || shopBusinessInfoDO.getRegistAddress().trim().length() == 0) { message.append("???!<br> "); } else { if (null != shopBusinessInfoDO.getRegistAddress() && shopBusinessInfoDO.getRegistAddress().length() > 50) { message.append("???50!<br> "); } } if (shopBusinessInfoDO.getProvince() == null || shopBusinessInfoDO.getProvince().trim().length() == 0) { message.append("???<br>"); } if (shopBusinessInfoDO.getCity() == null || shopBusinessInfoDO.getCity().trim().length() == 0) { message.append("??<br>"); } if (isHaveOuterShop == 0) { if (shopBusinessInfoDO.getOuterShopAddressUrl() == null || "".equals(shopBusinessInfoDO.getOuterShopAddressUrl()) || shopBusinessInfoDO.getOuterShopAddressUrl().trim().length() == 0) { message.append("?Url?<br>"); } else { if (shopBusinessInfoDO.getOuterShopAddressUrl() != null && !ObjectUtil .isUrlPatten(String.valueOf(shopBusinessInfoDO.getOuterShopAddressUrl()))) { message.append("?Url<br>"); } } /*if (shopBusinessInfoDO.getOuterShopLevel()==null) { message.append("<br>"); }if (shopBusinessInfoDO.getOuterShopSaleScope()==null) { message.append("<br>"); }if (shopBusinessInfoDO.getIsEnterB2c()==null) { message.append("??B2C<br>"); }*/ } // String [] alertStr = {"??","??","????","???","?","??","????","?"}; // String [] alertStr2 = {"??","??","??/??","???","?","??","????","?"}; String[] alertStr = { "??", "??", "?" }; String[] alertStr2 = { "??", "??", "?" }; //String [] alertStr3 = {"??","??","?"}; if (myFile == null || myFileFileName.length() <= 0) { //for(int i=0;i<7;i++){ for (int i = 0; i < 3; i++) { message.append(alertStr[i] + "<br>"); } } else { String fileNames[] = myFileFileName.split(","); //for(int i=0;i<7;i++){ for (int i = 0; i < myFile.length; i++) { //if(i+1<=fileNames.length){ if (null == fileNames[i] || "".equals(fileNames[i])) { message.append(alertStr[i] + "<br>"); return message.toString(); } //}else{ // message.append(alertStr[i]+"<br>"); //} if (myFile[i].length() / PinjuConstant.FILE_SIZE_K > 500) { message.append(alertStr2[i] + "<br>"); return message.toString(); } if (!FileSecurityUtils.isImageValid(myFile[i])) { message.append(alertStr2[i] + "??<br>"); return message.toString(); } } } } else { message.append("? "); } return message.toString(); }
From source file:net.cbtltd.rest.AbstractReservation.java
protected static synchronized AvailabilityResponse getAvailabilityCalendar(String pos, String productid, String fromDate, String toDate) { if (productid == null || productid.isEmpty() || productid.length() > 10) { throw new ServiceException(Error.product_id, productid); }/*from ww w .j av a 2 s . co m*/ if (fromDate != null && fromDate.length() != 10 && !fromDate.isEmpty()) { throw new ServiceException(Error.date_invalid, fromDate); } if (toDate != null && toDate.length() != 10 && !toDate.isEmpty()) { throw new ServiceException(Error.date_invalid, toDate); } SqlSession sqlSession = RazorServer.openSession(); AvailabilityResponse response = new AvailabilityResponse(); try { Product product = sqlSession.getMapper(ProductMapper.class).read(productid); if (product == null) throw new ServiceException(Error.product_id, productid); JSONService.getPartyWithPMCheck(sqlSession, pos, product.getSupplierid()); // this method checks agent's status and throws an exception in case of agent is inactive Parameter action = new Parameter(); action.setId(productid); action.setFromdate(fromDate); Date fromDateDate = null; Date toDateDate = null; if (fromDate == null || fromDate.isEmpty()) { fromDateDate = new Date(); fromDate = JSONService.DF.format(fromDateDate); action.setFromdate(fromDate); } else { JSONService.DF.setLenient(false); fromDateDate = JSONService.DF.parse(fromDate); } if (toDate == null || toDate.isEmpty()) { Calendar calendar = Calendar.getInstance(); calendar.setTime(fromDateDate); calendar.add(Calendar.DAY_OF_YEAR, 365); toDateDate = calendar.getTime(); } else { toDateDate = JSONService.DF.parse(toDate); } if (fromDateDate.after(toDateDate)) { throw new ServiceException(Error.date_range, fromDate + " - " + toDate); } ArrayList<CalendarElement> items = sqlSession.getMapper(ReservationMapper.class) .calendarelement(action); List<AvailabilityRange> ranges = AvailabilityRangeUtil.getAvailabilityList(items, fromDateDate, toDateDate); if (ranges != null && !ranges.isEmpty()) { AvailabilityRange[] array = new AvailabilityRange[ranges.size()]; ranges.toArray(array); response.setItems(array); response.setProductid(productid); } } catch (ParseException x) { response.setErrorMessage(Error.date_format.getMessage()); LOG.error(x.getMessage()); } catch (Throwable x) { response.setErrorMessage(x.getMessage()); LOG.error(x.getMessage()); } finally { sqlSession.close(); } return response; }
From source file:net.cbtltd.rest.AbstractReservation.java
/** * Get quotes for a setted date/* www .j a v a 2 s . co m*/ * * @param pos the point of sale code. * @param productid the ID of the property * @param fromDateString the date from which calculate a quote * @param todate the date to which calculate a quote * @param currency currency to calculate * @return quotes */ protected static synchronized QuoteResponse getQuotes(String pos, String productid, String fromDateString, String todate, String currency, Integer adults, Integer children) { if (productid == null || productid.isEmpty()) { throw new ServiceException(Error.product_id, productid); } if (!Time.isDateCorrectFormat(fromDateString)) { throw new ServiceException(Error.date_from, fromDateString); } if (!Time.isDateCorrectFormat(todate)) { throw new ServiceException(Error.date_to, todate); } SqlSession sqlSession = RazorServer.openSession(); QuoteResponse response = new QuoteResponse(); try { Product product = sqlSession.getMapper(ProductMapper.class).read(productid); if (product == null) { throw new ServiceException(Error.database_cannot_find, "product with [" + productid + "] id"); } if (!Product.CREATED.equals(product.getState())) { throw new ServiceException(Error.product_inactive, "product with [" + productid + "] id"); } if (StringUtils.isEmpty(currency) || !PaymentHelper.currencyExists(currency)) { currency = product.getCurrency(); } Party channelPartnerParty = JSONService.getPartyWithPMCheck(sqlSession, pos, product.getSupplierid()); // this method checks agent's status and throws an exception in case of agent is inactive if (channelPartnerParty == null) { throw new ServiceException(Error.database_cannot_find, "channel partner with pos: [" + pos + "]"); } product.setPhysicaladdress(ReservationService.getPropertyLocation(sqlSession, product)); Integer propertyManagerId = Integer.valueOf(product.getSupplierid()); if (propertyManagerId == null) { throw new ServiceException(Error.database_cannot_find, "property manager ID for product id [" + product.getId() + "]"); } PropertyManagerInfo propertyManagerInfo = sqlSession.getMapper(PropertyManagerInfoMapper.class) .readbypmid(propertyManagerId); if (propertyManagerInfo == null) { throw new ServiceException(Error.database_cannot_find, "property manager info by PM ID [" + propertyManagerId + "]"); } response.setFromTime(convertTime(propertyManagerInfo.getCheckInTime())); response.setToTime(convertTime(propertyManagerInfo.getCheckOutTime())); Date fromDate = JSONService.DF.parse(fromDateString); Date toDate = JSONService.DF.parse(todate); if (!toDate.after(fromDate)) { throw new ServiceException(Error.date_range); } Reservation reservation = new Reservation(); reservation.setOrganizationid(product.getSupplierid()); reservation.setProductid(productid); reservation.setFromdate(fromDate); reservation.setUnit(Unit.DAY); reservation.setTodate(toDate); reservation.setAltpartyid(product.getAltpartyid()); reservation.setCurrency(currency); reservation.setAdult(adults); reservation.setChild(children); reservation.setAgentid(channelPartnerParty.getId()); reservation.setQuotedetail(new ArrayList<net.cbtltd.shared.Price>()); currency = PartyService.checkbookingnetCurrency(currency, propertyManagerInfo); ReservationPrice reservationPrice = new ReservationPrice(); if (reservation.getAltpartyid() == null || !Arrays.asList(livePricingIds).contains(reservation.getAltpartyid())) { reservationPrice = ReservationService.computePrice(sqlSession, reservation, currency); response.setDamageInsurance(round( PaymentService.convertCurrency(sqlSession, product.getCurrency(), reservation.getCurrency(), product.getSecuritydeposit() != null ? product.getSecuritydeposit() : 0), 2, BigDecimal.ROUND_HALF_UP)); response.setCleaningFee(round( PaymentService.convertCurrency(sqlSession, product.getCurrency(), reservation.getCurrency(), product.getCleaningfee() != null ? product.getCleaningfee() : 0), 2, BigDecimal.ROUND_HALF_UP)); LOG.debug("Reservation [" + reservation.getId() + "] has not altparty ID."); } else { reservationPrice = PartnerService.readPrice(sqlSession, reservation, product.getAltid(), currency); if (reservationPrice.getTotal() == null || reservationPrice.getTotal() <= 0 || reservationPrice.getPrice() == null || reservationPrice.getPrice() <= 0) { throw new ServiceException(Error.product_not_available, "Total or Price is null or less/equals 0 returned from handler"); } reservationPrice = ReservationService.computeLivePrice(sqlSession, reservation, reservationPrice, currency); response.setDamageInsurance(0.0); response.setCleaningFee(0.0); } if (reservationPrice.getTotal() == null || reservationPrice.getTotal() <= 0) { throw new ServiceException(Error.product_not_available, "From:" + reservation.getFromdate() + "-" + reservation.getTodate()); } if (reservationPrice.getQuoteDetails() == null) { reservationPrice.setQuoteDetails(new ArrayList<QuoteDetail>()); } // add yield rules to quotes detail response if (reservation.getQuotedetail() != null && reservation.getQuotedetail().size() > 0) { for (Price price : reservation.getQuotedetail()) { if (price.getType() != null && price.getType().equals(Price.YIELD)) { reservationPrice.getQuoteDetails().add(new QuoteDetail(String.valueOf(price.getValue()), reservation.getCurrency(), price.getName(), Price.YIELD, "", true)); } } } // Round response quoteDetail values to tenths for (QuoteDetail quoteDetail : reservationPrice.getQuoteDetails()) { Double amount = Double.valueOf(quoteDetail.getAmount()); quoteDetail.setAmount(String.valueOf(round(amount, 2, BigDecimal.ROUND_HALF_UP))); } // Cancellation start Set<CancellationItem> cancellationItems = PaymentHelper.getCancellationItems(sqlSession, reservation); response.setCancellationItems(cancellationItems); // Cancellation end response.setReservationPrice(reservationPrice); String terms = propertyManagerInfo.getTermsLink() == null ? "" : propertyManagerInfo.getTermsLink(); response.setTermsLink(terms); // Taxes calculation ArrayList<net.cbtltd.shared.Price> pricedetails = reservation.getQuotedetail(); Double taxrate = 0.0; if (pricedetails != null) { Double tax = 0.0; for (net.cbtltd.shared.Price pricedetail : pricedetails) { pricedetail.setValue(NameId.round(pricedetail.getValue())); if (pricedetail.getValue() > 0.0 && (pricedetail.hasType(net.cbtltd.shared.Price.TAX_EXCLUDED) || pricedetail.hasType(net.cbtltd.shared.Price.TAX_INCLUDED) || pricedetail.hasType(net.cbtltd.shared.Price.TAX_ON_TAX))) { tax += pricedetail.getValue(); } } taxrate = (reservation.getQuote() == null || reservation.getQuote() <= 0.0 || tax == null) ? 0.0 : tax * 100 / (reservation.getQuote() - tax); } // End taxes response.setPrice(round(reservation.getPrice(), 2, BigDecimal.ROUND_HALF_UP)); response.setQuote(round(reservation.getQuote(), 2, BigDecimal.ROUND_HALF_UP)); response.setCurrency(reservation.getCurrency()); response.setTax(round(taxrate, 2, BigDecimal.ROUND_HALF_UP)); JSONService.LOG.debug("getDeposit " + product.getSupplierid() + ", " + fromDateString); response.setDeposit( round(ReservationService.getDeposit(sqlSession, reservation), 2, BigDecimal.ROUND_HALF_UP)); PropertyManagerSupportCC propertyManagerSupportCC = sqlSession .getMapper(PropertyManagerSupportCCMapper.class) .readbypartyid(propertyManagerInfo.getPropertyManagerId()); if (propertyManagerSupportCC == null) { // set all credit card types to false in case of inability to find the PropertyManagerSupportCC in DB propertyManagerSupportCC = new PropertyManagerSupportCC(); propertyManagerSupportCC.setNone(false); propertyManagerSupportCC.setPartyId(Integer.valueOf(product.getSupplierid())); propertyManagerSupportCC.setSupportAE(false); propertyManagerSupportCC.setSupportDINERSCLUB(false); propertyManagerSupportCC.setSupportDISCOVER(false); propertyManagerSupportCC.setSupportJCB(false); propertyManagerSupportCC.setSupportMC(false); propertyManagerSupportCC.setSupportVISA(false); LOG.error("cannot find propertyManagerSupportCC for PM [" + propertyManagerId + "] in database"); } response.setPropertyManagerSupportCC(propertyManagerSupportCC); String chargeType = PaymentHelper.getChargeType(propertyManagerInfo, reservation); // Setting amounts to both of payments. If deposit is 100%, than second payment is 0. Double firstPayment = round(PaymentHelper.getFirstPayment(reservation, propertyManagerInfo), 2, BigDecimal.ROUND_HALF_UP); Double secondPayment = round(PaymentHelper.getSecondPayment(reservation, propertyManagerInfo), 2, BigDecimal.ROUND_HALF_UP); if (PaymentHelper.isDepositPaymentMethod(chargeType)) { response.setFirstPayment(firstPayment); DateFormat DF = new SimpleDateFormat("yyyy-MM-dd"); response.setSecondPayment(round(PaymentHelper.getSecondPayment(reservation, propertyManagerInfo), 2, BigDecimal.ROUND_HALF_UP)); response.setSecondPaymentDate( DF.format(PaymentHelper.getSecondChargeDate(reservation, propertyManagerInfo))); } else { response.setFirstPayment(firstPayment + secondPayment); response.setSecondPayment(0.0); response.setSecondPaymentDate(""); } // end setting // Minstay calculation block if (PartyIds.PARTY_INTERHOME_ID.equals(product.getSupplierid()) || PartyIds.PARTY_RENTALS_UNITED_ID.equals(product.getSupplierid())) { MinStay minstayAction = new MinStay(product.getSupplierid(), product.getId(), fromDate, toDate, 0); minstayAction = sqlSession.getMapper(PropertyMinStayMapper.class).readbyexample(minstayAction); if (minstayAction != null && minstayAction.getValue() != null && minstayAction.getValue() > 0) { response.setMinstay(minstayAction.getValue()); } } else { Price checkInPrice = null; Price action = new Price(); action.setPartyid(product.getSupplierid()); action.setEntitytype(NameId.Type.Product.name()); action.setEntityid(product.getId()); action.setDate(fromDate); action.setTodate(toDate); action.setCurrency(currency); if (product.getUseonepricerow() != null && product.getUseonepricerow()) { checkInPrice = sqlSession.getMapper(PriceMapper.class).readexactmatch(action); } else { checkInPrice = sqlSession.getMapper(PriceMapper.class).getpropertydetailcheckinprice(action); } if (checkInPrice != null && checkInPrice.getMinStay() != null && checkInPrice.getMinStay() > 0) { response.setMinstay(checkInPrice.getMinStay()); } } // End minstay reservation.setCollisions(ReservationService.getCollisions(sqlSession, reservation)); response.setPaymentSupported(PaymentHelper.isPaymentSupported(propertyManagerInfo)); boolean available = sqlSession.getMapper(ReservationMapper.class).available(reservation); response.setAvailable(available && reservation.noCollisions()); response.setImageUrl(ImageService.getProductDefaultImageURL(sqlSession, product.getId())); response.setPropertyName(product.getName()); if (!available) { throw new ServiceException(Error.product_not_available); } } catch (ParseException x) { response.setErrorMessage(x.getMessage() == null ? "Null message" : x.getMessage()); LOG.error(x.getMessage()); } catch (Throwable x) { response.setPrice(0.0); response.setQuote(0.0); response.setErrorMessage(x.getMessage() == null ? "Null message" : x.getMessage()); LOG.error(x.getMessage()); } finally { sqlSession.close(); } return response; }
From source file:com.quartz.AmazonQuartzJob.java
public void execute(JobExecutionContext context) throws JobExecutionException { String error = "No error"; SimpleDateFormat out = new SimpleDateFormat("hh:mm a"); System.out.println(":::>>>Amazon Job Time Check @ " + out.format(new Date())); settingsHM = TextFileReadWrite.readSettings(file); String onoff = settingsHM.get("onoff"), emails = settingsHM.get("emails"), lastUpdate = settingsHM.get("lastUpdate"); ArrayList<String> time = new ArrayList(Arrays.asList(settingsHM.get("time").split(";"))); if (emails == null) { emails = ";"; }/*w w w . j a va 2 s . c o m*/ Date lastDate; try { lastDate = out1.parse(lastUpdate); } catch (ParseException ex) { GregorianCalendar now = new GregorianCalendar(); now.set(Calendar.DAY_OF_YEAR, -1); lastDate = now.getTime(); } String[] emailArr = emails.replace(";;", ";").replace(";", " ").trim().split(" "); if (onoff.equalsIgnoreCase("checked")) { for (String e : time) { Date dScheduled, dNow; try { dScheduled = out.parse(e); dNow = out.parse(out.format(new Date())); if (dScheduled.getTime() == dNow.getTime()) { System.out.println("\t---> Amazon task launch"); XMLOrderConfirmationFeedBuilder.generateShipConfirmXML(); try { this.submitFeed(); } catch (IOException ex) { System.out.println("Error occured in submitFeed method"); error += "Cannot submit feed."; } try { if (emails != null && emails.length() > 0) { for (String recipient : emailArr) { InternetAddress.parse(recipient); if (recipient.indexOf("@") > 0 && recipient.indexOf(".") > 0) { String subject = "Auto notification from AMZ order update application server"; String msg = "Scheduled Amazon orders update executed.\nError/s: " + error + "\n\n Update contents:\n\n" + XML.toJSONObject(TextFileReadWrite .readFile(new File("AMZ_Orders_Tracking_Feed.xml"))[0]) .toString(3); Emailer.Send(AKC_Creds.ANH_EMAIL, AKC_Creds.ANH_EMAIL_PWD, recipient, subject, msg); } } } System.out.println("===[email notifications send]==="); writeUpdateTimestamp(); } catch (MessagingException ex) { System.out.println(ex.getMessage()); } } else { //System.out.println("\txxx> AMZ task time not match | Scheduled: " + out.format(dScheduled) + " Now: " + out.format(dNow)); } } catch (ParseException ex) { //System.out.println(ex.getMessage()); error += " Cannot create XML feed."; } } } }
From source file:org.egov.egf.web.actions.payment.DirectBankPaymentAction.java
@Validations(requiredFields = { @RequiredFieldValidator(fieldName = "fundId", message = "", key = REQUIRED), @RequiredFieldValidator(fieldName = "voucherNumber", message = "", key = REQUIRED), @RequiredFieldValidator(fieldName = "commonBean.bankId", message = "", key = REQUIRED), @RequiredFieldValidator(fieldName = "commonBean.accountNumberId", message = "", key = REQUIRED), @RequiredFieldValidator(fieldName = "commonBean.amount", message = "", key = REQUIRED), @RequiredFieldValidator(fieldName = "voucherDate", message = "", key = REQUIRED), @RequiredFieldValidator(fieldName = "commonBean.documentNumber", message = "", key = REQUIRED), @RequiredFieldValidator(fieldName = "commonBean.documentDate", message = "", key = REQUIRED), @RequiredFieldValidator(fieldName = "commonBean.paidTo", message = "", key = REQUIRED) }) @SkipValidation//from w ww. j a v a 2 s . co m @ValidationErrorPage(value = NEW) @Action(value = "/payment/directBankPayment-create") public String create() { CVoucherHeader billVhId = null; voucherHeader.setType(FinancialConstants.STANDARD_VOUCHER_TYPE_PAYMENT); loadAjaxedDropDowns(); removeEmptyRowsAccoutDetail(billDetailslist); removeEmptyRowsSubledger(subLedgerlist); final String voucherDate = formatter1.format(voucherHeader.getVoucherDate()); String cutOffDate1 = null; try { if (!validateDBPData(billDetailslist, subLedgerlist)) { if (commonBean.getModeOfPayment().equalsIgnoreCase(FinancialConstants.MODEOFPAYMENT_RTGS)) { if (LOGGER.isInfoEnabled()) LOGGER.info("calling Validate RTGS"); validateRTGS(); } if (showMode != null && showMode.equalsIgnoreCase("nonbillPayment")) if (voucherHeader.getId() != null) billVhId = persistenceService.getSession().load(CVoucherHeader.class, voucherHeader.getId()); voucherHeader.setId(null); populateWorkflowBean(); paymentheader = paymentActionHelper.createDirectBankPayment(paymentheader, voucherHeader, billVhId, commonBean, billDetailslist, subLedgerlist, workflowBean); showMode = "create"; if (!cutOffDate.isEmpty() && cutOffDate != null) try { date = sdf.parse(cutOffDate); cutOffDate1 = formatter1.format(date); } catch (final ParseException e) { } if (cutOffDate1 != null && voucherDate.compareTo(cutOffDate1) <= 0 && FinancialConstants.CREATEANDAPPROVE.equalsIgnoreCase(workflowBean.getWorkFlowAction())) { if (paymentheader.getVoucherheader().getVouchermis().getBudgetaryAppnumber() == null) addActionMessage(getText("directbankpayment.transaction.success") + paymentheader.getVoucherheader().getVoucherNumber()); else addActionMessage(getText("directbankpayment.transaction.success") + paymentheader.getVoucherheader().getVoucherNumber() + " and " + getText("budget.recheck.sucessful", new String[] { paymentheader .getVoucherheader().getVouchermis().getBudgetaryAppnumber() })); } else { if (paymentheader.getVoucherheader().getVouchermis().getBudgetaryAppnumber() == null) addActionMessage(getText("directbankpayment.transaction.success") + paymentheader.getVoucherheader().getVoucherNumber()); else addActionMessage(getText("directbankpayment.transaction.success") + paymentheader.getVoucherheader().getVoucherNumber() + " and " + getText("budget.recheck.sucessful", new String[] { paymentheader .getVoucherheader().getVouchermis().getBudgetaryAppnumber() })); addActionMessage(getText("payment.voucher.approved", new String[] { paymentService .getEmployeeNameForPositionId(paymentheader.getState().getOwnerPosition()) })); } } else throw new ValidationException( Arrays.asList(new ValidationError("engine.validation.failed", "Validation Faild"))); } catch (final ValidationException e) { LOGGER.error(e.getMessage(), e); final List<ValidationError> errors = new ArrayList<ValidationError>(); errors.add(new ValidationError("exp", e.getErrors().get(0).getMessage())); throw new ValidationException(errors); } catch (final NumberFormatException e) { LOGGER.error(e.getMessage(), e); throw e; } catch (final ApplicationRuntimeException e) { LOGGER.error(e.getMessage(), e); throw e; } finally { if (subLedgerlist.size() == 0) subLedgerlist.add(new VoucherDetails()); // loadApproverUser(FinancialConstants.STANDARD_VOUCHER_TYPE_PAYMENT); } return VIEW; }
From source file:au.org.theark.core.dao.DataExtractionDao.java
/** * /*from ww w. ja va 2 s . c o m*/ * Simple export to CSV as Biospecimen Data * */ public File createBiospecimenCSV(Search search, DataExtractionVO devo, List<BiospecimenField> bsfs, List<CustomFieldDisplay> cfds, FieldCategory fieldCategory) { final String tempDir = System.getProperty("java.io.tmpdir"); String filename = new String("BIOSPECIMEN.csv"); final java.io.File file = new File(tempDir, filename); if (filename == null || filename.isEmpty()) { filename = "exportBiospecimencsv.csv"; } OutputStream outputStream; HashMap<String, ExtractionVO> hashOfBiospecimensWithData = devo.getBiospecimenData(); HashMap<String, ExtractionVO> hashOfBiospecimenCustomData = devo.getBiospecimenCustomData(); Set<String> biospecimens = new HashSet<String>(); biospecimens.addAll(hashOfBiospecimensWithData.keySet()); biospecimens.addAll(hashOfBiospecimenCustomData.keySet()); try { outputStream = new FileOutputStream(file); CsvWriter csv = new CsvWriter(outputStream); // Header csv.write("SUBJECTUID"); csv.write("BIOSPECIMENUID"); for (BiospecimenField bsf : bsfs) { if (!bsf.getPublicFieldName().equalsIgnoreCase("biospecimenUid")) csv.write(bsf.getPublicFieldName()); } for (CustomFieldDisplay cfd : cfds) { csv.write(cfd.getCustomField().getName()); } csv.endLine(); for (String biospecimenUID : biospecimens) { ExtractionVO evo = hashOfBiospecimensWithData.get(biospecimenUID); if (evo != null && evo.getSubjectUid() != null) { csv.write(evo.getSubjectUid()); csv.write(biospecimenUID); for (BiospecimenField bsf : bsfs) { if (evo != null) { HashMap<String, String> keyValues = evo.getKeyValues(); if (!bsf.getPublicFieldName().equalsIgnoreCase("biospecimenUid")) { String valueResult = keyValues.get(bsf.getPublicFieldName()); if (bsf.getFieldType().getName().equalsIgnoreCase(Constants.FIELD_TYPE_DATE) && valueResult != null) { try { DateFormat dateFormat = new SimpleDateFormat( au.org.theark.core.Constants.DD_MM_YYYY); String[] dateFormats = { au.org.theark.core.Constants.DD_MM_YYYY, au.org.theark.core.Constants.yyyy_MM_dd_hh_mm_ss_S }; Date date = DateUtils.parseDate(valueResult, dateFormats); csv.write(dateFormat.format(date)); } catch (ParseException e) { csv.write(valueResult); } } else { csv.write(valueResult); } } } } } evo = new ExtractionVO(); evo = hashOfBiospecimenCustomData.get(biospecimenUID); if (evo != null) { HashMap<String, String> keyValues = evo.getKeyValues(); for (CustomFieldDisplay cfd : cfds) { String valueResult = keyValues.get(cfd.getCustomField().getName()); if (cfd.getCustomField().getFieldType().getName() .equalsIgnoreCase(Constants.FIELD_TYPE_DATE) && valueResult != null) { try { DateFormat dateFormat = new SimpleDateFormat( au.org.theark.core.Constants.DD_MM_YYYY); String[] dateFormats = { au.org.theark.core.Constants.DD_MM_YYYY, au.org.theark.core.Constants.yyyy_MM_dd_hh_mm_ss_S }; Date date = DateUtils.parseDate(valueResult, dateFormats); csv.write(dateFormat.format(date)); } catch (ParseException e) { csv.write(valueResult); } } else { csv.write(valueResult); } } } else { // Write out a line with no values (no data existed for subject in question for (CustomFieldDisplay cfd : cfds) { csv.write(""); } } csv.endLine(); } csv.close(); } catch (FileNotFoundException e) { log.error(e.getMessage()); } return file; }
From source file:davmail.exchange.ExchangeSession.java
protected Condition getRangeCondition(String timeRangeStart, String timeRangeEnd) throws IOException { try {//from www .ja va2s. c o m SimpleDateFormat parser = getZuluDateFormat(); ExchangeSession.MultiCondition andCondition = and(); if (timeRangeStart != null) { andCondition.add(gt("dtend", formatSearchDate(parser.parse(timeRangeStart)))); } if (timeRangeEnd != null) { andCondition.add(lt("dtstart", formatSearchDate(parser.parse(timeRangeEnd)))); } return andCondition; } catch (ParseException e) { throw new IOException(e + " " + e.getMessage()); } }