List of usage examples for java.util Date toString
public String toString()
where:dow mon dd hh:mm:ss zzz yyyy
From source file:net.cbtltd.rest.interhome.A_Handler.java
/** * Read accommodation products./*from w w w. jav a 2s . c o m*/ */ public synchronized void readProducts() { Date version = new Date(); String message = "Interhome readProducts " + getAltpartyid(); LOG.debug(message); String codeinterhome = null; String fn = null; final SqlSession sqlSession = RazorServer.openSession(); try { RelationService.load(sqlSession, Downloaded.PRODUCT_DOWNLOAD_DATE, getAltpartyid(), version.toString()); JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.accommodation"); Unmarshaller um = jc.createUnmarshaller(); fn = "accommodation.xml"; Accommodations accommodations = (Accommodations) um.unmarshal(ftp(fn)); int i = 0; StringBuilder sb = new StringBuilder(); // boolean check = true; for (Accommodation accommodation : accommodations.getAccommodation()) { try { // if (accommodation.getCode().equalsIgnoreCase("DK1026.631.1")) {check = false;} // if (accommodation.getCountry().equalsIgnoreCase("FR")) {check = false;} // if (check) continue; // Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), accommodation.getCode()); Product product = getProduct(sqlSession, getAltpartyid(), accommodation.getCode()); // if (product == null) {continue;} ArrayList<String> attributes = new ArrayList<String>(); product.setBathroom( accommodation.getBathrooms() == null ? 2 : accommodation.getBathrooms().intValue()); product.setRoom( accommodation.getBedrooms() == null ? 2 : accommodation.getBedrooms().intValue()); net.cbtltd.shared.Country country = sqlSession.getMapper(CountryMapper.class) .read(accommodation.getCountry()); Geodata geodata = accommodation.getGeodata(); product.setLatitude(geodata == null ? null : geodata.getLat().doubleValue()); product.setLongitude(geodata == null ? null : geodata.getLng().doubleValue()); product.setAltitude(0.0); product.setPerson(accommodation.getPax() == null ? 2 : accommodation.getPax().intValue()); product.setRoom( accommodation.getBedrooms() == null ? 1 : accommodation.getBedrooms().intValue()); product.setToilet( accommodation.getToilets() == null ? 0 : accommodation.getToilets().intValue()); product.setChild(0); product.setSecuritydeposit(Product.DEFAULT_SECUIRTY_DEPOSIT); product.setCommission(20.0); product.setCleaningfee(Product.DEFAULT_CLEANING_FEE); product.setCurrency(country.getCurrency()); // product.setDiscount(20.0); product.setInfant(0); String floor = accommodation.getFloor(); Short space = accommodation.getSqm(); if (NumberUtils.isNumber(floor)) { product.setFloor(Integer.valueOf(floor)); } else { LOG.error("Invalid floor or space value for product id: " + product.getId() + ", altid: " + accommodation.getCode()); } product.setSpace((space == null ? "0" : space) + " sq.m"); product.setQuantity(1); product.setRank(getRank()); product.setRating(5); // product.setState(Product.CREATED); product.setType(Product.Type.Accommodation.name()); product.setUnit(Unit.DAY); product.setWebaddress(accommodation.getUrl()); product.setVersion(version); // Search location by specific Interhome Code. codeinterhome = accommodation.getCountry() + "." + accommodation.getPlace(); Location location = new Location(); try { location.setCodeinterhome(codeinterhome); location = sqlSession.getMapper(LocationMapper.class).interhomeSearch(location); //location = getLocation(sqlSession, codeinterhome); } catch (Throwable x) { LOG.error("Location error for Accommodation: " + accommodation.getCode() + ", country: " + accommodation.getCountry() + ", region: " + accommodation.getRegion() + ", code: " + accommodation.getPlace() + ". Error: " + x.getMessage()); } if (location == null) { sb.append("\n") .append("Accommodation: " + accommodation.getCode() + " country: " + accommodation.getCountry() + " region: " + accommodation.getRegion() + " code: " + accommodation.getPlace()); product.setState(Product.SUSPENDED); } else { product.setLocationid(location.getId()); } String name = accommodation.getName(); product.setName(name == null || name.trim().isEmpty() ? getPropType(accommodation.getType()) + " " + (location == null ? "" : location.getName()) : getPropType(accommodation.getType()) + " " + name.trim()); sqlSession.getMapper(ProductMapper.class).update(product); if (accommodation.getBrand() != null) { product.setValue(Product.Value.Brand.name(), accommodation.getBrand()); } if (accommodation.getRegion() != null) { product.setValue(Product.Value.Region.name(), accommodation.getRegion()); } if (accommodation.getMaxrentalprice() != null) { product.setDoubleValue(Product.Value.Maxrentalprice.name(), accommodation.getMaxrentalprice().doubleValue()); } if (accommodation.getMinrentalprice() != null) { product.setDoubleValue(Product.Value.Minrentalprice.name(), accommodation.getMinrentalprice().doubleValue()); } if (accommodation.getSqm() != null) { product.setIntegerValue(Product.Value.SquareMetre.name(), accommodation.getSqm().intValue()); } if (accommodation.getFloor() != null) { product.setValue(Product.Value.Floor.name(), accommodation.getFloor()); } addType(attributes, accommodation.getType()); if (accommodation.getAttributes() != null && accommodation.getAttributes().getAttribute() != null) { for (String attribute : accommodation.getAttributes().getAttribute()) { addAttribute(attributes, attribute); } } if (accommodation.getDetails() != null) { addDetail(attributes, accommodation.getDetails()); } addQuality(attributes, String.valueOf(accommodation.getQuality())); if (accommodation.getThemes() != null && accommodation.getThemes().getTheme() != null) { for (String theme : accommodation.getThemes().getTheme()) { addTheme(attributes, theme); } } RelationService.replace(sqlSession, Relation.PRODUCT_VALUE, product.getId(), product.getValues()); RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(), attributes); RelationService.removeDeprecatedData(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(), attributes); /* StringBuilder description = new StringBuilder(); Distances distances = accommodation.getDistances(); if (distances != null && distances.getDistance() != null) { description.append("Distances to:"); for (Distance distance : distances.getDistance()) { description.append(" ") .append(getDistance(distance.getType())) .append(" ") .append(distance.getValue()) .append("m "); } description.append("\n"); } Text action = new Text(product.getPublicId(), Language.Code.en.name()); Text text = sqlSession.getMapper(TextMapper.class).readbyexample(action); if (text == null) {text = new Text(product.getPublicId(), product.getPublicLabel(), Text.Type.HTML, new Date(), "", Language.Code.en.name());} text.setState(Text.State.Created.name()); text.setNotes(description.toString()); product.setPublicText(text); TextService.update(sqlSession, product.getTexts());*/ if (HasUrls.LIVE && accommodation.getPictures() != null && accommodation.getPictures().getPicture() != null) { ArrayList<NameId> images = new ArrayList<NameId>(); List<Picture> pictures = accommodation.getPictures().getPicture(); int k = 0; for (Picture picture : pictures) { if (picture.getType().equalsIgnoreCase("M")) { String imageid = getImage(picture.getType()) + " " + getImage(picture.getSeason()); images.add(new NameId(imageid, picture.getUrl().replace("partner-medium", "partner-xlarge"))); pictures.remove(k); break; } k++; } k = 0; while (k < pictures.size()) { Picture picture = pictures.get(k); if (picture.getType().equalsIgnoreCase("I")) { String imageid = getImage(picture.getType()) + " " + getImage(picture.getSeason()); images.add(new NameId(imageid, picture.getUrl().replace("partner-medium", "partner-xlarge"))); pictures.remove(k); } else k++; } for (Picture picture : pictures) { try { String imageid = getImage(picture.getType()) + " " + getImage(picture.getSeason()); images.add(new NameId(imageid, picture.getUrl().replace("partner-medium", "partner-xlarge"))); } catch (Throwable x) { LOG.error("\nURL error " + picture.getUrl()); } } UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(), Language.EN, images); } sqlSession.commit(); LOG.debug(i++ + " " + accommodation.getCode() + " = " + product.getId()); // wait(getProductwait()); } catch (Throwable x) { LOG.error(accommodation + " error " + x.getMessage()); } // TODO: CJM if (i > 10) break; } Product action = new Product(); action.setAltpartyid(getAltpartyid()); action.setState(Product.CREATED); action.setVersion(version); sqlSession.getMapper(ProductMapper.class).cancelversion(action); sqlSession.commit(); LOG.debug("Missing Places" + sb.toString()); /* Language.Code language = Language.Code.en; readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language, "House/Residence", false); readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "Interior", false); language = Language.Code.de; readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language, "Haus/Residenz", true); readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "Innenbereich", false); language = Language.Code.fr; readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language, "La maison/la rsidence de vacances", true); readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "L'intrieur du logement", false); language = Language.Code.es; readDescriptions(sqlSession, "outsidedescription_" + language.name() + ".xml", language, "Haus/Residenz", true); readDescriptions(sqlSession, "insidedescription_" + language.name() + ".xml", language, "Innenbereich", false); */ } catch (Throwable x) { sqlSession.rollback(); LOG.error(x.getMessage()); } finally { sqlSession.close(); delete(fn); } //MonitorService.monitor(message, timestamp); }
From source file:org.ofbiz.tenant.tenant.TenantServices.java
/** * Create tenant backup/*from w ww . j av a 2 s.c om*/ * @param ctx * @param context * @return */ public static Map<String, Object> createTenantBackup(DispatchContext ctx, Map<String, Object> context) { Delegator delegator = ctx.getDelegator(); LocalDispatcher dispatcher = ctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); String tenantId = (String) context.get("tenantId"); try { Date nowDate = UtilDateTime.nowDate(); String suffix = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(nowDate); GenericValue sysUserLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", "system"), false); String outpath = EntityUtilProperties.getPropertyValue("tenant", "backup.outpath", delegator); File tempDir = new File(outpath, "tmp_" + tenantId + "_" + suffix); tempDir.mkdir(); Map<String, Object> exportTenantAllEntitiesInMap = FastMap.newInstance(); exportTenantAllEntitiesInMap.put("tenantId", tenantId); exportTenantAllEntitiesInMap.put("outpath", tempDir.getAbsolutePath()); exportTenantAllEntitiesInMap.put("userLogin", sysUserLogin); Map<String, Object> exportTenantAllEntitiesResults = dispatcher.runSync("exportTenantAllEntities", exportTenantAllEntitiesInMap); List<String> results = UtilGenerics.cast(exportTenantAllEntitiesResults.get("results")); String firstResult = results.get(0); if (firstResult.startsWith("[")) { // create zip file File outFile = new File(outpath + "/" + tenantId + "_" + suffix + ".zip"); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outFile)); String[] fileList = tempDir.list(); byte[] readBuffer = new byte[2156]; int bytesIn = 0; for (int i = 0; i < fileList.length; i++) { File file = new File(tempDir, fileList[i]); FileInputStream fis = new FileInputStream(file); ZipEntry entry = new ZipEntry(file.getName()); zout.putNextEntry(entry); while ((bytesIn = fis.read(readBuffer)) != -1) { zout.write(readBuffer, 0, bytesIn); } fis.close(); } zout.close(); FileUtils.deleteDirectory(tempDir); // create party content String partyId = null; String contentName = null; GenericValue tenantUserLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", tenantId), false); if (UtilValidate.isEmpty(tenantUserLogin)) { // create person Map<String, Object> createPersonInMap = FastMap.newInstance(); createPersonInMap.put("firstName", "Tenant Owner"); createPersonInMap.put("lastName", "Of " + tenantId); createPersonInMap.put("userLogin", sysUserLogin); Map<String, Object> createPersonResults = dispatcher.runSync("createPerson", createPersonInMap); partyId = UtilGenerics.cast(createPersonResults.get("partyId")); // create user login tenantUserLogin = delegator.makeValue("UserLogin"); tenantUserLogin.setString("userLoginId", tenantId); tenantUserLogin.setString("partyId", partyId); tenantUserLogin.setString("currentPassword", "{SHA}47ca69ebb4bdc9ae0adec130880165d2cc05db1a"); delegator.create(tenantUserLogin); } else { partyId = tenantUserLogin.getString("partyId"); } contentName = "Data of " + tenantId + " at " + nowDate.toString(); String dataResourceName = contentName.replace(" ", "_").replace(":", "_") + ".zip"; Map<String, Object> createDataResourceInMap = FastMap.newInstance(); createDataResourceInMap.put("dataResourceName", dataResourceName); createDataResourceInMap.put("dataResourceTypeId", "URL_RESOURCE"); createDataResourceInMap.put("isPublic", "Y"); createDataResourceInMap.put("mimeTypeId", "application/zip"); createDataResourceInMap.put("objectInfo", "file://" + outFile.getAbsolutePath()); createDataResourceInMap.put("userLogin", sysUserLogin); Map<String, Object> createDataResourceResults = dispatcher.runSync("createDataResource", createDataResourceInMap); String dataResourceId = UtilGenerics.cast(createDataResourceResults.get("dataResourceId")); Map<String, Object> createContentInMap = FastMap.newInstance(); createContentInMap.put("contentName", contentName); createContentInMap.put("dataResourceId", dataResourceId); createContentInMap.put("userLogin", sysUserLogin); Map<String, Object> createContentResults = dispatcher.runSync("createContent", createContentInMap); String contentId = UtilGenerics.cast(createContentResults.get("contentId")); Map<String, Object> createPartyContentInMap = FastMap.newInstance(); createPartyContentInMap.put("partyId", partyId); createPartyContentInMap.put("contentId", contentId); createPartyContentInMap.put("partyContentTypeId", "TENANT_BACKUP"); createPartyContentInMap.put("userLogin", sysUserLogin); dispatcher.runSync("createPartyContent", createPartyContentInMap); return ServiceUtil.returnSuccess(contentName + " has already been backed up."); } else { return ServiceUtil.returnError(firstResult); } } catch (Exception e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } }
From source file:TimeFormatter.java
/** * Format the given date as a string, according to the given * format string.//from w w w . ja v a 2 s .c o m * The format string is of the form used by the strftime(3) UNIX * call. * @param date The date to format * @param format The formatting string * @return the String with the formatted date. */ public static String format(Date date, String format) { StringBuffer buf = new StringBuffer(50); char ch; for (int i = 0; i < format.length(); i++) { ch = format.charAt(i); if (ch == '%') { ++i; if (i == format.length()) break; ch = format.charAt(i); if (ch == 'E') { // Alternate Era ++i; } else if (ch == 'Q') { // Alternate numeric symbols ++i; } if (i == format.length()) break; ch = format.charAt(i); switch (ch) { case 'A': buf.append(fullWeekDays[date.getDay()]); break; case 'a': buf.append(abrWeekDays[date.getDay()]); break; case 'B': buf.append(fullMonths[date.getMonth()]); break; case 'b': case 'h': buf.append(abrMonths[date.getMonth()]); break; case 'C': appendPadded(buf, (date.getYear() + 1900) / 100, 2); break; case 'c': buf.append(date.toLocaleString()); break; case 'D': buf.append(TimeFormatter.format(date, "%m/%d/%y")); break; case 'd': appendPadded(buf, date.getDate(), 2); break; case 'e': appendPadded(buf, date.getMonth() + 1, 2, ' '); break; case 'H': appendPadded(buf, date.getHours(), 2); break; case 'I': case 'l': int a = date.getHours() % 12; if (a == 0) a = 12; appendPadded(buf, a, 2, ch == 'I' ? '0' : ' '); break; case 'j': buf.append("[?]"); // No simple way to get this as of now break; case 'k': appendPadded(buf, date.getHours(), 2, ' '); break; case 'M': appendPadded(buf, date.getMinutes(), 2); break; case 'm': appendPadded(buf, date.getMonth() + 1, 2); break; case 'n': buf.append('\n'); break; case 'p': buf.append(date.getHours() < 12 ? "am" : "pm"); break; case 'R': buf.append(TimeFormatter.format(date, "%H:%M")); break; case 'r': buf.append(TimeFormatter.format(date, "%l:%M%p")); break; case 'S': appendPadded(buf, date.getSeconds(), 2); break; case 'T': buf.append(TimeFormatter.format(date, "%H:%M:%S")); break; case 't': buf.append('\t'); break; case 'U': case 'u': case 'V': case 'W': buf.append("[?]"); // Weekdays are a pain, especially // without day of year (0-365) ; break; case 'w': buf.append(date.getDay()); break; case 'X': buf.append(TimeFormatter.format(date, "%H:%M:%S")); break; case 'x': buf.append(TimeFormatter.format(date, "%B %e, %Y")); break; case 'y': appendPadded(buf, (date.getYear() + 1900) % 100, 2); break; case 'Y': appendPadded(buf, (date.getYear() + 1900), 4); break; case 'Z': String strdate = date.toString(); buf.append(strdate.substring(20, 23)); // (!) // There should be a better way // to do this... break; case '%': buf.append('%'); break; } } else { buf.append(ch); } } return buf.toString(); }
From source file:com.ut.healthelink.service.impl.transactionInManagerImpl.java
@Override public Date convertLongDate(String dateValue) { Date date = null; //this checks convert long date such February 2, 2014 try {/* w w w.j a v a2 s . c om*/ date = java.text.DateFormat.getDateInstance().parse(dateValue); /** this method converts February 29 to March 1, * we need to run through check two to make sure it is valid * **/ if (!recheckLongDate(dateValue, date.toString())) { return null; } } catch (Exception e) { } return date; }
From source file:org.nuclos.server.genericobject.ejb3.GenericObjectFacadeBean.java
/** * gets generic object with dependants vo for a given generic object id (historical, readonly view) * @param iGenericObjectId id of generic object to show historical information for * @param dateHistorical date to show historical information for * @return generic object with dependants vo at the given point in time * @throws CommonFinderException if the given object didn't exist at the given point in time. * @precondition dateHistorical != null//from w w w .j av a 2 s . com * @postcondition result != null * @nucleus.permission mayRead(module) */ @RolesAllowed("Login") public GenericObjectWithDependantsVO getHistorical(int iGenericObjectId, Date dateHistorical, String customUsage) throws CommonFinderException, CommonPermissionException { debug("Entering getHistorical(Integer iGenericObjectId, Date dateHistorical)"); if (dateHistorical == null) { throw new NullArgumentException("dateHistorical"); } final RuleObjectContainerCVO loccvo = this.getRuleObjectContainerCVO(Event.UNDEFINED, iGenericObjectId, customUsage); final GenericObjectVO govoResult = loccvo.getGenericObject(); final DependantMasterDataMap mpDependantsResult = loccvo.getDependants(); final Calendar calendar = new GregorianCalendar(); calendar.setTime(dateHistorical); // If dateHistorical has no time components, we can assume that the user wants to see the state of the object at the end of that day. if (calendar.get(Calendar.HOUR_OF_DAY) + calendar.get(Calendar.MINUTE) + calendar.get(Calendar.SECOND) == 0) { calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 0); } dateHistorical = calendar.getTime(); // Check if the object existed at the historical date: final Date dateCreatedAt = govoResult.getCreatedAt(); if (dateHistorical.before(dateCreatedAt)) { throw new CommonFinderException("genericobject.facade.exception.1");//"Das Objekt existierte zum angegebenen Zeitpunkt nicht."); } debug("Historical Date we want to see : " + dateHistorical.toString()); debug("Date of creation of record : " + dateCreatedAt.toString()); govoResult.setAttributes(GenericObjectFacadeHelper .getHistoricalAttributes(govoResult, dateHistorical, mpDependantsResult).values()); this.debug("Leaving getHistorical(Integer iGenericObjectId, Date dateHistorical)"); assert govoResult != null; return new GenericObjectWithDependantsVO(govoResult, mpDependantsResult); }
From source file:org.openbravo.erpCommon.obps.ActivationKey.java
private synchronized boolean refreshLicense(int minutesToRefresh) { Date timeToRefresh = null; if (lastRefreshTime != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(lastRefreshTime); calendar.add(Calendar.MINUTE, minutesToRefresh); timeToRefresh = calendar.getTime(); }//from w w w .java 2s. c o m if (timeToRefresh == null || new Date().after(timeToRefresh)) { log4j.debug("Trying to refresh license, last refresh " + (lastRefreshTime == null ? "never" : lastRefreshTime.toString())); Map<String, Object> params = new HashMap<String, Object>(); params.put("publicKey", strPublicKey); params.put("purpose", getProperty("purpose")); params.put("instanceNo", getProperty("instanceno")); params.put("activate", true); ProcessBundle pb = new ProcessBundle(null, new VariablesSecureApp("0", "0", "0")); pb.setParams(params); boolean refreshed = false; OBContext.setAdminMode(); try { new ActiveInstanceProcess().execute(pb); OBError msg = (OBError) pb.getResult(); refreshed = msg.getType().equals("Success"); if (refreshed) { OBDal.getInstance().flush(); log4j.debug("Instance refreshed"); } else { log4j.info("Problem refreshing instance " + msg.getMessage()); } } catch (Exception e) { log4j.error("Error refreshing instance", e); refreshed = false; } finally { OBContext.restorePreviousMode(); } if (!refreshed) { // Even license couldn't be refreshed, set lastRefreshTime not to try to refresh in the // following period of time lastRefreshTime = new Date(); } return refreshed; } else { log4j.debug("Not refreshing, last refresh was " + lastRefreshTime.toString() + ". Next time to refresh " + timeToRefresh.toString()); return false; } }
From source file:org.apache.slider.providers.agent.AgentProviderService.java
/** Publish component instance specific data if the component demands it */ protected void processAndPublishComponentSpecificExports(Map<String, String> ports, String containerId, String hostFqdn, String compName) { String portVarFormat = "${site.%s}"; String hostNamePattern = "${" + compName + "_HOST}"; List<ExportGroup> appExportGroups = getMetainfo().getApplication().getExportGroups(); Component component = getMetainfo().getApplicationComponent(compName); if (component != null && SliderUtils.isSet(component.getCompExports()) && appExportGroups != null && appExportGroups.size() > 0) { Set<String> compExports = new HashSet(); String compExportsStr = component.getCompExports(); for (String compExport : compExportsStr.split(",")) { if (compExport.trim().length() > 0) { compExports.add(compExport.trim()); }/* w w w .ja va 2 s . c o m*/ } Date now = new Date(); Set<String> modifiedGroups = new HashSet<String>(); for (ExportGroup exportGroup : appExportGroups) { List<Export> exports = exportGroup.getExports(); if (exports != null && !exports.isEmpty()) { String exportGroupName = exportGroup.getName(); ConcurrentHashMap<String, List<ExportEntry>> map = (ConcurrentHashMap<String, List<ExportEntry>>) getCurrentExports( exportGroupName); for (Export export : exports) { if (canBeExported(exportGroupName, export.getName(), compExports)) { log.info("Attempting to publish {} of group {} for component type {}", export.getName(), exportGroupName, compName); String templateToExport = export.getValue(); for (String portName : ports.keySet()) { boolean publishData = false; String portValPattern = String.format(portVarFormat, portName); if (templateToExport.contains(portValPattern)) { templateToExport = templateToExport.replace(portValPattern, ports.get(portName)); publishData = true; } if (templateToExport.contains(hostNamePattern)) { templateToExport = templateToExport.replace(hostNamePattern, hostFqdn); publishData = true; } if (publishData) { ExportEntry entryToAdd = new ExportEntry(); entryToAdd.setLevel(COMPONENT_TAG); entryToAdd.setValue(templateToExport); entryToAdd.setUpdatedTime(now.toString()); entryToAdd.setContainerId(containerId); entryToAdd.setTag(tags.getTag(compName, containerId)); List<ExportEntry> existingList = map.putIfAbsent(export.getName(), new CopyOnWriteArrayList(Arrays.asList(entryToAdd))); // in-place edit, no lock needed if (existingList != null) { boolean updatedInPlace = false; for (ExportEntry entry : existingList) { if (containerId.equalsIgnoreCase(entry.getContainerId())) { entryToAdd.setValue(templateToExport); entryToAdd.setUpdatedTime(now.toString()); updatedInPlace = true; } } if (!updatedInPlace) { existingList.add(entryToAdd); } } log.info("Publishing {} for name {} and container {}", templateToExport, export.getName(), containerId); modifiedGroups.add(exportGroupName); synchronized (containerExportsMap) { if (!containerExportsMap.containsKey(containerId)) { containerExportsMap.put(containerId, new HashSet<String>()); } Set<String> containerExportMaps = containerExportsMap.get(containerId); containerExportMaps .add(String.format("%s:%s", exportGroupName, export.getName())); } } } } } } } publishModifiedExportGroups(modifiedGroups); } }
From source file:net.cbtltd.rest.streamline.A_Handler.java
@SuppressWarnings("unchecked") @Override/*from w ww . ja v a 2 s. c o m*/ public void readPrices() { Date version = new Date(); Date toDateForExtraPrices = Time.addDuration(version, FEES_PRICES_FOR_NUMBER_DAYS_IN_FUTURE, Time.DAY); Date minimumToDateForExtraPricesUpdate = Time.addDuration(version, FEES_PRICES_UPDATE_DAYS, Time.DAY); String message = "readPrices Streamline (Altpartyid:" + this.getAltpartyid() + ")"; LOG.debug(message + version.toString()); final SqlSession sqlSession = RazorServer.openSession(); try { long functionStart = System.currentTimeMillis(); String responseReservationsAndPrices = getXmlFeedConnection(sqlSession, this.getAltpartyid()); SAXBuilder builder = new SAXBuilder(); Document document = (Document) builder.build(new StringReader(responseReservationsAndPrices)); Element rootNode = document.getRootElement(); List<Element> properties = rootNode.getChildren("property"); long gettingApiDataEnd = System.currentTimeMillis(); LOG.debug("Reading API data takes: " + (gettingApiDataEnd - functionStart) + "ms"); for (Element property : properties) { long onePropertyStart = System.currentTimeMillis(); String altId = property.getChildText("propertyId"); try { Product product = PartnerService.getProduct(sqlSession, getAltpartyid(), altId, false); if (product == null) { // LOG.error("ERROR product not exsit:" + altId); continue; } String productId = product.getId(); //Rates ArrayList<Price> pricesFromApi = new ArrayList<Price>(); ArrayList<Yield> discountYieldFromApi = new ArrayList<Yield>(); // ArrayList<Adjustment> adjustmentsFromApi = new ArrayList<Adjustment>(); List<Element> ratePeriodsList = property.getChild("ratePeriods").getChildren("ratePeriod"); for (Element ratePeriodEl : ratePeriodsList) { String fromDateStr = ratePeriodEl.getChild("dateRange").getChildText("beginDate"); String toDateStr = ratePeriodEl.getChild("dateRange").getChildText("endDate"); Date fromDate = responseDF.parse(fromDateStr); Date toDate = responseDF.parse(toDateStr); int minimumStay = Integer.parseInt(ratePeriodEl.getChildText("minimumStay")); List<Element> ratesList = ratePeriodEl.getChild("rates").getChildren("rate"); String dailyCurrency = product.getCurrency(); String weekendCurrency = product.getCurrency(); String weeklyCurrency = product.getCurrency(); String monthlyCurrency = product.getCurrency(); Double dailyRateValue = null; Double weekendRateValue = null; Double weeklyRateValue = null; Double monthlyRateValue = null; for (Element rateEl : ratesList) { String rateAmountStr = rateEl.getChildText("amount"); String currency = rateEl.getChild("amount").getAttributeValue("currency"); Double rateValue = null; try { rateValue = Double.valueOf(rateAmountStr); } catch (Exception parseExc) { } if (rateEl.getAttributeValue("rateType").equals("NIGHTLY_WEEKDAY")) { dailyCurrency = currency; dailyRateValue = rateValue; Double minumumValue = rateValue * minimumStay; this.addPrice(pricesFromApi, product, dailyCurrency, Unit.DAY, fromDate, toDate, rateValue, minumumValue, minimumStay); } else if (rateEl.getAttributeValue("rateType").equals("NIGHTLY_WEEKEND")) { weekendRateValue = rateValue; weekendCurrency = currency; } else if (rateEl.getAttributeValue("rateType").equals("WEEKLY")) { weeklyRateValue = rateValue; weeklyCurrency = currency; } else if (rateEl.getAttributeValue("rateType").equals("MONTHLY")) { monthlyRateValue = rateValue; monthlyCurrency = currency; } } if (weekendRateValue != null && dailyRateValue != null && (weekendRateValue - dailyRateValue != 0.0)) { if (!weekendCurrency.equalsIgnoreCase(dailyCurrency)) { Double currencyRate = WebService.getRate(sqlSession, weekendCurrency, dailyCurrency, new Date()); weekendRateValue = PaymentHelper .getAmountWithTwoDecimals(weekendRateValue * currencyRate); } Yield weekendRateYield = YieldService.createWeekendRate(productId, dailyRateValue, weekendRateValue, fromDate, toDate); if (weekendRateYield != null) { weekendRateYield.setParam(Yield.DAYS_OF_WEEKEND_FRI_SAT); discountYieldFromApi.add(weekendRateYield); } // Double extraAdjustmentPrice = weekendRateValue - dailyRateValue; // Adjustment adjustmentPrice = new Adjustment(); // adjustmentPrice.setCurrency(dailyCurrency); // adjustmentPrice.setPartyID(getAltpartyid()); // adjustmentPrice.setProductID(product.getId()); // adjustmentPrice.setFromDate(fromDate); // adjustmentPrice.setToDate(toDate); // adjustmentPrice.setMaxStay(999); // adjustmentPrice.setMinStay(minimumStay); // adjustmentPrice.setExtra(extraAdjustmentPrice); // adjustmentPrice.setServicedays(Adjustment.WEEKEND); // // adjustmentsFromApi.add(adjustmentPrice); } if (weeklyRateValue != null && dailyRateValue != null) { if (!weeklyCurrency.equalsIgnoreCase(dailyCurrency)) { Double currencyRate = WebService.getRate(sqlSession, weeklyCurrency, dailyCurrency, new Date()); weeklyRateValue = PaymentHelper .getAmountWithTwoDecimals(weeklyRateValue * currencyRate); } Yield weeklyDiscount = YieldService.createLengthOfStayDiscount(productId, dailyRateValue, weeklyRateValue, 7, fromDate, toDate); if (weeklyDiscount != null) { discountYieldFromApi.add(weeklyDiscount); } } if (monthlyRateValue != null && dailyRateValue != null) { if (!monthlyCurrency.equalsIgnoreCase(dailyCurrency)) { Double currencyRate = WebService.getRate(sqlSession, monthlyCurrency, dailyCurrency, new Date()); monthlyRateValue = PaymentHelper .getAmountWithTwoDecimals(monthlyRateValue * currencyRate); } //TODO set number of days in month //This is now set on 30, but in case of Streamline //min days for month price can be 27,28 Yield monthlyDiscount = YieldService.createLengthOfStayDiscount(productId, dailyRateValue, monthlyRateValue, 30, fromDate, toDate); if (monthlyDiscount != null) { discountYieldFromApi.add(monthlyDiscount); } } } // long handlingPropertyRatesDataEnd = System.currentTimeMillis(); // LOG.debug("Handling property rates data takes: "+ (handlingPropertyRatesDataEnd-onePropertyStart) + "ms"); PartnerService.updateProductPrices(sqlSession, product, NameId.Type.Product.name(), pricesFromApi, version, false, null); // long updateProductPricesEnd = System.currentTimeMillis(); // LOG.debug("PartnerService.updateProductPrices takes: "+ (updateProductPricesEnd-handlingPropertyRatesDataEnd) + "ms"); // PartnerService.updateProductAdjustments(sqlSession, product, adjustmentsFromApi, version); PartnerService.updateProductRateYields(sqlSession, product, discountYieldFromApi, version); // long updateProductRateYieldsEnd = System.currentTimeMillis(); // LOG.debug("PartnerService.updateProductRateYields takes: "+ (updateProductRateYieldsEnd-updateProductPricesEnd) + "ms"); ArrayList<Fee> feeFromApi = new ArrayList<Fee>(); ArrayList<Tax> taxListFromApi = new ArrayList<Tax>(); ArrayList<Tax> taxSpecialListForSomeFee = new ArrayList<Tax>(); //it is important to first process fees and than taxes //because in there 'fees' we will have some tax which are only for some fees.. //Fees List<Element> feesList = property.getChild("fees").getChildren("fee"); for (Element feeElement : feesList) { this.processFeeFromApi(feeFromApi, taxListFromApi, taxSpecialListForSomeFee, feeElement, product, toDateForExtraPrices); } //taxes List<Element> taxesElementList = property.getChild("taxes").getChildren("tax"); for (Element taxElement : taxesElementList) { this.processFeeFromApi(feeFromApi, taxListFromApi, taxSpecialListForSomeFee, taxElement, product, toDateForExtraPrices); } // long handlingPropertyFeesAndTaxesDataEnd = System.currentTimeMillis(); // LOG.debug("Handling property fees and taxes data takes: "+ (handlingPropertyFeesAndTaxesDataEnd-updateProductRateYieldsEnd) + "ms"); PartnerService.updateProductTaxes(sqlSession, product, taxListFromApi, version); // long updateProductTaxesEnd = System.currentTimeMillis(); // LOG.debug("PartnerService.updateProductTaxes takes: "+ (updateProductTaxesEnd-handlingPropertyFeesAndTaxesDataEnd) + "ms"); FeeService.updateProductFees(sqlSession, product, feeFromApi, version, true, minimumToDateForExtraPricesUpdate); // long updateProductFeesEnd = System.currentTimeMillis(); // LOG.debug("FeeService.updateProductFees takes: "+ (updateProductFeesEnd-updateProductTaxesEnd) + "ms"); sqlSession.commit(); LOG.debug("TOTAL one property (altID=" + altId + ") takes: " + (System.currentTimeMillis() - onePropertyStart) + "ms"); } catch (Throwable x) { LOG.error(Error.product_data.name() + altId); x.printStackTrace(); } } } catch (Throwable x) { sqlSession.rollback(); LOG.error(x.getMessage()); } finally { sqlSession.close(); } MonitorService.monitor(message, version); }
From source file:com.eucalyptus.objectstorage.WalrusManager.java
public GetObjectExtendedResponseType getObjectExtended(GetObjectExtendedType request) throws EucalyptusCloudException { GetObjectExtendedResponseType reply = (GetObjectExtendedResponseType) request.getReply(); Date ifModifiedSince = request.getIfModifiedSince(); Date ifUnmodifiedSince = request.getIfUnmodifiedSince(); String ifMatch = request.getIfMatch(); String ifNoneMatch = request.getIfNoneMatch(); boolean returnCompleteObjectOnFailure = request.getReturnCompleteObjectOnConditionFailure(); String bucketName = request.getBucket(); String objectKey = request.getKey(); Context ctx = Contexts.lookup(); Account account = ctx.getAccount();/*from w w w.j av a2 s. c o m*/ Status status = new Status(); Boolean getData = request.getGetData(); if (getData == null) { getData = false; } EntityWrapper<BucketInfo> db = EntityWrapper.get(BucketInfo.class); BucketInfo bucketInfo = new BucketInfo(bucketName); List<BucketInfo> bucketList = db.queryEscape(bucketInfo); if (bucketList.size() > 0) { BucketInfo bucket = bucketList.get(0); BucketLogData logData = bucket.getLoggingEnabled() ? request.getLogData() : null; boolean versioning = false; if (bucket.isVersioningEnabled()) { versioning = true; } EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class); ObjectInfo searchObjectInfo = new ObjectInfo(bucketName, objectKey); List<ObjectInfo> objectInfos = dbObject.queryEscape(searchObjectInfo); if (objectInfos.size() > 0) { ObjectInfo objectInfo = objectInfos.get(0); if (ctx.hasAdministrativePrivileges() || (objectInfo.canRead(account.getAccountNumber()) && (objectInfo.isGlobalRead() || Lookups.checkPrivilege(PolicySpec.S3_GETOBJECT, PolicySpec.VENDOR_S3, PolicySpec.S3_RESOURCE_OBJECT, PolicySpec.objectFullName(bucketName, objectKey), null)))) { String etag = objectInfo.getEtag(); String objectName = objectInfo.getObjectName(); Long byteRangeStart = request.getByteRangeStart(); Long byteRangeEnd = request.getByteRangeEnd(); DefaultHttpResponse httpResponse = null; if (byteRangeStart != null || byteRangeEnd != null) { httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.PARTIAL_CONTENT); } else { httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } if (byteRangeStart == null) { byteRangeStart = 0L; } if (byteRangeEnd == null) { byteRangeEnd = -1L; } if (byteRangeEnd == -1 || (byteRangeEnd + 1) > objectInfo.getSize()) { byteRangeEnd = objectInfo.getSize() - 1; } if ((byteRangeStart > objectInfo.getSize()) || (byteRangeStart > byteRangeEnd) || (byteRangeStart < 0 || byteRangeEnd < 0)) { db.rollback(); throw new InvalidRangeException("Range: " + byteRangeStart + "-" + byteRangeEnd + "object: " + bucketName + "/" + objectKey); } if (ifMatch != null) { if (!ifMatch.equals(etag) && !returnCompleteObjectOnFailure) { db.rollback(); throw new PreconditionFailedException(objectKey + " etag: " + etag); } } if (ifNoneMatch != null) { if (ifNoneMatch.equals(etag) && !returnCompleteObjectOnFailure) { db.rollback(); throw new NotModifiedException(objectKey + " ETag: " + etag); } } Date lastModified = objectInfo.getLastModified(); if (ifModifiedSince != null) { if ((ifModifiedSince.getTime() >= lastModified.getTime()) && !returnCompleteObjectOnFailure) { db.rollback(); throw new NotModifiedException(objectKey + " LastModified: " + lastModified.toString()); } } if (ifUnmodifiedSince != null) { if ((ifUnmodifiedSince.getTime() < lastModified.getTime()) && !returnCompleteObjectOnFailure) { db.rollback(); throw new PreconditionFailedException( objectKey + " lastModified: " + lastModified.toString()); } } if (request.getGetMetaData()) { List<MetaDataInfo> metaDataInfos = objectInfo.getMetaData(); for (MetaDataInfo metaDataInfo : metaDataInfos) { httpResponse.addHeader(WalrusProperties.AMZ_META_HEADER_PREFIX + metaDataInfo.getName(), metaDataInfo.getValue()); } } Long size = objectInfo.getSize(); String contentType = objectInfo.getContentType(); String contentDisposition = objectInfo.getContentDisposition(); db.commit(); if (logData != null) { updateLogData(bucket, logData); logData.setObjectSize(size); } String versionId = null; if (versioning) { versionId = objectInfo.getVersionId() != null ? objectInfo.getVersionId() : WalrusProperties.NULL_VERSION_ID; } if (request.getGetData()) { storageManager.sendObject(request, httpResponse, bucketName, objectName, byteRangeStart, byteRangeEnd + 1, size, etag, DateUtils.format(lastModified.getTime(), DateUtils.RFC822_DATETIME_PATTERN), contentType, contentDisposition, request.getIsCompressed(), versionId, logData); // fireUsageEvent For Get Object (we need the size in // regards // to byteRangeStart : byteRangeEnd +1 do math return null; } else { storageManager.sendHeaders(request, httpResponse, size, etag, DateUtils.format(lastModified.getTime(), DateUtils.RFC822_DATETIME_PATTERN), contentType, contentDisposition, versionId, logData); return null; } } else { db.rollback(); // Fix for EUCA-2782. Different exceptions are thrown based // on the request type so that the downstream logic can // differentiate if (getData) { throw new AccessDeniedException("Key", objectKey, logData); } else { throw new HeadAccessDeniedException("Key", objectKey, logData); } } } else { db.rollback(); // Fix for EUCA-2782. Different exceptions are thrown based on // the request type so that the downstream logic can // differentiate if (getData) { throw new NoSuchEntityException(objectKey); } else { throw new HeadNoSuchEntityException(objectKey); } } } else { db.rollback(); // Fix for EUCA-2782. Different exceptions are thrown based on the // request type so that the downstream logic can differentiate if (getData) { throw new NoSuchBucketException(bucketName); } else { throw new HeadNoSuchBucketException(bucketName); } } }