List of usage examples for javax.ejb TransactionAttributeType REQUIRES_NEW
TransactionAttributeType REQUIRES_NEW
To view the source code for javax.ejb TransactionAttributeType REQUIRES_NEW.
Click Source Link
REQUIRES_NEW
with a new transaction context. From source file:org.rhq.enterprise.server.resource.ResourceFactoryManagerBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void completeCreateResource(CreateResourceResponse response) { log.debug("Received call to complete create resource: " + response); // Load the persisted history entry CreateResourceHistory history = entityManager.find(CreateResourceHistory.class, response.getRequestId()); // There is some inconsistency if we're completing a request that was not in the database if (history == null) { log.error("Attempting to complete a request that was not found in the database: " + response.getRequestId()); return;/*from w w w. j av a2s. c o m*/ } // Update the history entry history.setNewResourceKey(response.getResourceKey()); history.setErrorMessage(response.getErrorMessage()); history.setStatus(response.getStatus()); // The configuration may now have error messages in it, so merge with the persisted one if (response.getResourceConfiguration() != null) { entityManager.merge(response.getResourceConfiguration()); } // RHQ-666 - The resource name will likely come from the plugin. If both the user indicated a name at // creation time (which would be in the history item), use that to override what the plugin indicates String newResourceName = response.getResourceName(); if (history.getCreatedResourceName() != null) { newResourceName = history.getCreatedResourceName(); } // If the plugin reports it as successful, create the resource and mark it as committed // Currently commented out because of https://jira.jboss.org/jira/browse/JBNADM-3451 // basically: this prevented getting a version of the resource with correct pluginConfig // from autodiscovery back into the inventory // // if (response.getStatus() == CreateResourceStatus.SUCCESS) { // resourceFactoryManager.createInventoryResource(history.getParentResource().getId(), history // .getResourceType().getId(), newResourceName, response.getResourceKey()); // } }
From source file:gwap.rest.UserPicture.java
@PUT @Consumes(MediaType.APPLICATION_JSON)/*ww w. j a va 2 s . c o m*/ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @Transactional @Path("/userpicture/{id:[0-9][0-9]*}") public Response ratePicture(@PathParam("id") String idString, String payloadString) { persistPicturerating(idString, payloadString); return Response.ok().build(); }
From source file:org.rhq.enterprise.server.cloud.StatusManagerBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void updateByAlertDefinition(Subject subject, int alertDefinitionId) { log.debug("About to mark status by alert definition"); // alert templates and group alert definitions do not represent cache-ready entries if (alertDefinitionManager.isResourceAlertDefinition(alertDefinitionId) == false) { return;/* www .j a va2s .c o m*/ } /* * the old alert definition is needed to know which caches to remove stale entries from; the updated / new * alert definition is needed to know which caches need to be reloaded to get the new conditions; by the time * this method is called, we only have the updated alert definition, thus it's not possible to intelligently * know which of the two caches to reload; so, we need to reload them both to be sure the system is consistent */ markGlobalCache(); // use local references to execute in the same transaction Query updateAgentQuery = entityManager.createNamedQuery(Agent.QUERY_UPDATE_STATUS_BY_ALERT_DEFINITION); updateAgentQuery.setParameter("alertDefinitionId", alertDefinitionId); int agentsUpdated = updateAgentQuery.executeUpdate(); /* * this is informational debugging only - do NOT change the status bits here */ if (log.isDebugEnabled()) { AlertDefinition definition = entityManager.find(AlertDefinition.class, alertDefinitionId); Agent agent = agentManager.getAgentByResourceId(LookupUtil.getSubjectManager().getOverlord(), definition.getResource().getId()); log.debug("Marking status, agent[id=" + agent.getId() + ", status=" + agent.getStatus() + "] for alertDefinition[id=" + alertDefinitionId + "]"); log.debug("Agents updated: " + agentsUpdated); } }
From source file:gwap.rest.User.java
@PUT @Consumes(MediaType.APPLICATION_JSON)//from ww w.ja v a 2s. com @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @Transactional @Path("/{id:[A-Za-z0-9][A-Za-z0-9]*}") public Response updateUser(@PathParam("id") String deviceId, String payloadString) { log.info("updateUser(#0)", deviceId); JSONObject payload = parse(payloadString); Query query = entityManager.createNamedQuery("person.byDeviceId"); query.setParameter("deviceId", deviceId); Person person = (Person) query.getSingleResult(); if (payload.containsKey("username")) { // update user person.setExternalUsername(payload.get("username").toString()); } else { // create new gamesession+gameround query = entityManager.createNamedQuery("gameSession.byGameType"); query.setParameter("gameType", getGameType()); GameSession gameSession; try { gameSession = (GameSession) query.getSingleResult(); } catch (NoResultException e) { gameSession = new GameSession(); gameSession.setGameType(getGameType()); entityManager.persist(gameSession); } int score = Integer.parseInt(payload.get("score").toString()); int playedTime = Integer.parseInt(payload.get("playedTime").toString()); double coveredDistance = Double.parseDouble(payload.get("coveredDistance").toString()); boolean successful = Integer.parseInt(payload.get("gamesPlayed").toString()) == 1; GameRound gameRound = new GameRound(); entityManager.persist(gameRound); gameRound.setGameSession(gameSession); gameRound.setPerson(person); gameRound.setScore(score); Calendar cal = GregorianCalendar.getInstance(); gameRound.setEndDate(cal.getTime()); cal.add(Calendar.MILLISECOND, -1 * playedTime); gameRound.setStartDate(cal.getTime()); gameRound.setCoveredDistance(coveredDistance); gameRound.setSuccessful(successful); // Unlock new badges JSONArray newBadges = (JSONArray) payload.get("badges"); for (Object o : newBadges) { JSONObject badge = (JSONObject) o; long badgeId = Long.parseLong(badge.get("id").toString()); if (Boolean.parseBoolean(badge.get("unlocked").toString())) { Badge b = entityManager.find(Badge.class, badgeId); person.getBadges().add(b); } } } entityManager.flush(); log.info("Sucessfully updated user with deviceId #0", deviceId); return Response.ok().build(); }
From source file:dk.dma.msinm.service.MessageService.java
/** * Creates a new message as a draft message * * @param messageVo the template for the message to create * @return the new message//from w w w. jav a2s . co m */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public Message createMessage(MessageVo messageVo) throws Exception { Message message = messageVo.toEntity(); // Validate the message SeriesIdentifier id = message.getSeriesIdentifier(); if (message.getId() != null) { throw new Exception("Message already persisted"); } if (id.getMainType() == null) { throw new Exception("Message main type must be specified"); } if (message.getType() == null || message.getType().getSeriesIdType() != id.getMainType()) { throw new Exception("Missing or invalid Message type"); } if (message.getValidFrom() == null) { throw new Exception("Message validFrom must be specified"); } // Set default values if (StringUtils.isBlank(id.getAuthority())) { id.setAuthority(app.getOrganization()); } if (id.getYear() == null) { id.setYear(Calendar.getInstance().get(Calendar.YEAR)); } message.setStatus(Status.DRAFT); // Substitute the Area with a persisted one if (message.getArea() != null) { message.setArea(getByPrimaryKey(Area.class, message.getArea().getId())); } // Substitute the Categories with the persisted ones if (message.getCategories().size() > 0) { List<Category> categories = new ArrayList<>(); message.getCategories().forEach(cat -> categories.add(getByPrimaryKey(Category.class, cat.getId()))); message.setCategories(categories); } // Substitute the Charts with the persisted ones if (message.getCharts().size() > 0) { List<Chart> charts = new ArrayList<>(); message.getCharts().forEach(chart -> charts.add(getByPrimaryKey(Chart.class, chart.getId()))); message.setCharts(charts); } // Let publishers update the list of publications publishingService.createMessage(message); // Persist the message message = saveMessage(message); log.info("Saved message " + message); // Move the temporary repo folder to the final destination if (StringUtils.isNotBlank(messageVo.getRepoPath())) { String repoPath = repositoryService.getRepoPath(getMessageRepoFolder(message)); log.info("Moving repo from " + messageVo.getRepoPath() + " to " + repoPath); boolean repoMoved = repositoryService.moveRepoFolder(messageVo.getRepoPath(), repoPath); // Update the description with the new path boolean descUpdated = false; if (repoMoved) { for (MessageDesc desc : message.getDescs()) { if (StringUtils.isNotBlank(desc.getDescription()) && desc.getDescription().contains(messageVo.getRepoPath())) { desc.setDescription(desc.getDescription().replaceAll(messageVo.getRepoPath(), repoPath)); descUpdated = true; } } // Persist again if we have made any description changes if (descUpdated) { message = saveMessage(message); } } } em.flush(); return message; }
From source file:org.meveo.service.job.JobExecutionService.java
/** * Remove job execution history older then a given date * /* ww w . java2 s . c om*/ * @param jobName Job name to match * @param date Date to check * @param provider Provider * @return A number of records that were removed */ @SuppressWarnings("unchecked") @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public int deleteJobExecutionHistory(String jobName, Date date, Provider provider) { log.trace("Removing {} job execution history older then a {} date for provider {}", jobName, date, provider); List<JobInstance> jobInstances = null; if (jobName != null) { QueryBuilder qb = new QueryBuilder("select ji from JobInstance ji"); qb.addCriterion("ji.code", "=", jobName, false); jobInstances = qb.getQuery(getEntityManager()).getResultList(); if (jobInstances.isEmpty()) { log.info("Removed 0 job execution history which start date is older then a {} date for provider {}", date, provider); return 0; } } String sql = "delete from JobExecutionResultImpl t"; QueryBuilder qb = new QueryBuilder(sql); if (jobName != null) { qb.addSqlCriterion("t.jobInstance in :jis", "jis", jobInstances); } qb.addCriterionDateRangeToTruncatedToDay("t.startDate", date); qb.addCriterionEntity("t.provider", provider); int itemsDeleted = qb.getQuery(getEntityManager()).executeUpdate(); log.info("Removed {} job execution history which start date is older then a {} date for provider {}", itemsDeleted, date, provider); return itemsDeleted; }
From source file:org.rhq.enterprise.server.alert.AlertConditionManagerBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public InventoryStatus getResourceStatusByConditionId(int alertConditionId) { try {/*from w w w. j a va 2s .c o m*/ Query query = entityManager.createNamedQuery(AlertCondition.QUERY_FIND_RESOURCE_STATUS_BY_CONDITION_ID); query.setParameter("alertConditionId", alertConditionId); InventoryStatus status = (InventoryStatus) query.getSingleResult(); // a resource was marked for asynchronous uninventory, but not actually deleted yet return status; } catch (NoResultException nre) { // the resource was already deleted asynchronously, tell the caller as much return InventoryStatus.UNINVENTORIED; } }
From source file:gov.nih.nci.firebird.service.periodic.DailyJobServiceBean.java
@Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void initialize() { clearOldTimer(); createTimer(); }
From source file:org.meveo.service.catalog.impl.PricePlanMatrixService.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void importExcelLine(Row row, User user, Provider provider) throws BusinessException { EntityManager em = getEntityManager(); Object[] cellsObj = IteratorUtils.toArray(row.cellIterator()); int rowIndex = row.getRowNum(); int i = 0;/* w w w.ja va2 s .c o m*/ String pricePlanCode = getCellAsString((Cell) cellsObj[i++]); PricePlanMatrix pricePlan = null; QueryBuilder qb = new QueryBuilder(PricePlanMatrix.class, "p"); qb.addCriterion("code", "=", pricePlanCode, false); qb.addCriterionEntity("provider", provider); @SuppressWarnings("unchecked") List<PricePlanMatrix> pricePlans = qb.getQuery(em).getResultList(); if (pricePlans == null || pricePlans.size() == 0) { pricePlan = new PricePlanMatrix(); pricePlan.setProvider(provider); pricePlan.setAuditable(new Auditable()); pricePlan.getAuditable().setCreated(new Date()); pricePlan.getAuditable().setCreator(user); } else if (pricePlans.size() == 1) { pricePlan = pricePlans.get(0); } else { throw new BusinessException( "More than one priceplan in line=" + rowIndex + "with code=" + pricePlanCode); } String pricePlanDescription = getCellAsString((Cell) cellsObj[i++]); String eventCode = getCellAsString((Cell) cellsObj[i++]); String sellerCode = getCellAsString((Cell) cellsObj[i++]); String countryCode = getCellAsString((Cell) cellsObj[i++]); String currencyCode = getCellAsString((Cell) cellsObj[i++]); try { pricePlan.setStartSubscriptionDate(getCellAsDate((Cell) cellsObj[i++])); } catch (Exception e) { throw new BusinessException("Invalid startAppli in line=" + rowIndex + " expected format:" + param.getProperty("excelImport.dateFormat", "dd/MM/yyyy") + ", you may change the property excelImport.dateFormat."); } try { pricePlan.setEndSubscriptionDate(getCellAsDate((Cell) cellsObj[i++])); } catch (Exception e) { throw new BusinessException("Invalid endAppli in line=" + rowIndex + " expected format:" + param.getProperty("excelImport.dateFormat", "dd/MM/yyyy") + ", you may change the property excelImport.dateFormat."); } String offerCode = getCellAsString((Cell) cellsObj[i++]); String priority = getCellAsString((Cell) cellsObj[i++]); String amountWOTax = getCellAsString((Cell) cellsObj[i++]); String amountWithTax = getCellAsString((Cell) cellsObj[i++]); String amountWOTaxEL = getCellAsString((Cell) cellsObj[i++]); String amountWithTaxEL = getCellAsString((Cell) cellsObj[i++]); String minQuantity = getCellAsString((Cell) cellsObj[i++]); String maxQuantity = getCellAsString((Cell) cellsObj[i++]); String criteria1 = getCellAsString((Cell) cellsObj[i++]); String criteria2 = getCellAsString((Cell) cellsObj[i++]); String criteria3 = getCellAsString((Cell) cellsObj[i++]); String criteriaEL = getCellAsString((Cell) cellsObj[i++]); try { pricePlan.setStartRatingDate(getCellAsDate((Cell) cellsObj[i++])); } catch (Exception e) { throw new BusinessException("Invalid startRating in line=" + rowIndex + " expected format:" + param.getProperty("excelImport.dateFormat", "dd/MM/yyyy") + ", you may change the property excelImport.dateFormat."); } try { pricePlan.setEndRatingDate(getCellAsDate((Cell) cellsObj[i++])); } catch (Exception e) { throw new BusinessException("Invalid endRating in line=" + rowIndex + " expected format:" + param.getProperty("excelImport.dateFormat", "dd/MM/yyyy") + ", you may change the property excelImport.dateFormat."); } String minSubAge = getCellAsString((Cell) cellsObj[i++]); String maxSubAge = getCellAsString((Cell) cellsObj[i++]); String validityCalendarCode = getCellAsString((Cell) cellsObj[i++]); log.debug( "priceplanCode={}, priceplanDescription= {}, chargeCode={} sellerCode={}, countryCode={}, currencyCode={}," + " startSub={}, endSub={}, offerCode={}, priority={}, amountWOTax={}, amountWithTax={},amountWOTaxEL={}, amountWithTaxEL={}," + " minQuantity={}, maxQuantity={}, criteria1={}, criteria2={}, criteria3={}, criteriaEL={}," + " startRating={}, endRating={}, minSubAge={}, maxSubAge={}, validityCalendarCode={}", new Object[] { pricePlanCode, pricePlanDescription, eventCode, sellerCode, countryCode, currencyCode, pricePlan.getStartSubscriptionDate(), pricePlan.getEndSubscriptionDate(), offerCode, priority, amountWOTax, amountWithTax, amountWOTaxEL, amountWithTaxEL, minQuantity, maxQuantity, criteria1, criteria2, criteria3, criteriaEL, pricePlan.getStartRatingDate(), pricePlan.getEndRatingDate(), minSubAge, maxSubAge, validityCalendarCode }); if (!StringUtils.isBlank(eventCode)) { qb = new QueryBuilder(ChargeTemplate.class, "p"); qb.addCriterion("code", "=", eventCode, false); qb.addCriterionEntity("provider", provider); @SuppressWarnings("unchecked") List<Seller> charges = qb.getQuery(em).getResultList(); if (charges.size() == 0) { throw new BusinessException("cannot find charge in line=" + rowIndex + " with code=" + eventCode); } else if (charges.size() > 1) { throw new BusinessException("more than one charge in line=" + rowIndex + " with code=" + eventCode); } pricePlan.setEventCode(eventCode); } else { throw new BusinessException("Empty chargeCode in line=" + rowIndex + ", code=" + eventCode); } // Seller if (!StringUtils.isBlank(sellerCode)) { qb = new QueryBuilder(Seller.class, "p"); qb.addCriterion("code", "=", sellerCode, false); qb.addCriterionEntity("provider", provider); @SuppressWarnings("unchecked") List<Seller> sellers = qb.getQuery(em).getResultList(); Seller seller = null; if (sellers == null || sellers.size() == 0) { throw new BusinessException("Invalid seller in line=" + rowIndex + ", code=" + sellerCode); } seller = sellers.get(0); pricePlan.setSeller(seller); } else { pricePlan.setSeller(null); } // Country if (!StringUtils.isBlank(countryCode)) { qb = new QueryBuilder(TradingCountry.class, "p"); qb.addCriterion("p.country.countryCode", "=", countryCode, false); qb.addCriterionEntity("provider", provider); @SuppressWarnings("unchecked") List<TradingCountry> countries = qb.getQuery(em).getResultList(); TradingCountry tradingCountry = null; if (countries == null || countries.size() == 0) { throw new BusinessException("Invalid country in line=" + rowIndex + ", code=" + countryCode); } tradingCountry = countries.get(0); pricePlan.setTradingCountry(tradingCountry); } else { pricePlan.setTradingCountry(null); } // Currency if (!StringUtils.isBlank(currencyCode)) { qb = new QueryBuilder(TradingCurrency.class, "p"); qb.addCriterion("p.currency.currencyCode", "=", currencyCode, false); qb.addCriterionEntity("provider", provider); @SuppressWarnings("unchecked") List<TradingCurrency> currencies = qb.getQuery(em).getResultList(); TradingCurrency tradingCurrency = null; if (currencies == null || currencies.size() == 0) { throw new BusinessException("Invalid currency in line=" + rowIndex + ", code=" + countryCode); } tradingCurrency = currencies.get(0); pricePlan.setTradingCurrency(tradingCurrency); } else { pricePlan.setTradingCurrency(null); } if (!StringUtils.isBlank(pricePlanCode)) { pricePlan.setCode(pricePlanCode); } else { throw new BusinessException("Invalid priceplan code in line=" + rowIndex + ", code=" + offerCode); } if (!StringUtils.isBlank(pricePlanDescription)) { pricePlan.setDescription(pricePlanDescription); } else { pricePlan.setDescription(pricePlanCode); } // OfferCode if (!StringUtils.isBlank(offerCode)) { qb = new QueryBuilder(OfferTemplate.class, "p"); qb.addCriterion("code", "=", offerCode, false); qb.addCriterionEntity("provider", provider); @SuppressWarnings("unchecked") List<OfferTemplate> offers = qb.getQuery(em).getResultList(); OfferTemplate offer = null; if (offers == null || offers.size() == 0) { throw new BusinessException("Invalid offer code in line=" + rowIndex + ", code=" + offerCode); } offer = offers.get(0); pricePlan.setOfferTemplate(offer); } else { pricePlan.setOfferTemplate(null); } if (!StringUtils.isBlank(validityCalendarCode)) { qb = new QueryBuilder(Calendar.class, "p"); qb.addCriterion("code", "=", validityCalendarCode, false); qb.addCriterionEntity("provider", provider); @SuppressWarnings("unchecked") List<Calendar> calendars = qb.getQuery(em).getResultList(); Calendar calendar = null; if (calendars == null || calendars.size() == 0) { throw new BusinessException( "Invalid calendars code in line=" + rowIndex + ", code=" + validityCalendarCode); } calendar = calendars.get(0); pricePlan.setValidityCalendar(calendar); } else { pricePlan.setValidityCalendar(null); } // Priority if (!StringUtils.isBlank(priority)) { try { pricePlan.setPriority(Integer.parseInt(priority)); } catch (Exception e) { throw new BusinessException("Invalid priority in line=" + rowIndex + ", priority=" + priority); } } else { pricePlan.setPriority(1); } // AmountWOTax if (!StringUtils.isBlank(amountWOTax)) { try { pricePlan.setAmountWithoutTax(new BigDecimal(amountWOTax)); } catch (Exception e) { throw new BusinessException( "Invalid amount wo tax in line=" + rowIndex + ", amountWOTax=" + amountWOTax); } } else { throw new BusinessException("Amount wo tax in line=" + rowIndex + " should not be empty"); } // AmountWithTax if (!StringUtils.isBlank(amountWithTax)) { try { pricePlan.setAmountWithTax(new BigDecimal(amountWithTax)); } catch (Exception e) { throw new BusinessException( "Invalid amount wo tax in line=" + rowIndex + ", amountWithTax=" + amountWithTax); } } else { pricePlan.setAmountWithTax(null); } if (!StringUtils.isBlank(amountWOTaxEL)) { pricePlan.setAmountWithoutTaxEL(amountWOTaxEL); } else { pricePlan.setAmountWithoutTaxEL(null); } if (!StringUtils.isBlank(amountWithTaxEL)) { pricePlan.setAmountWithTaxEL(amountWithTaxEL); } else { pricePlan.setAmountWithTaxEL(null); } // minQuantity if (!StringUtils.isBlank(minQuantity)) { try { pricePlan.setMinQuantity(new BigDecimal(minQuantity)); } catch (Exception e) { throw new BusinessException( "Invalid minQuantity in line=" + rowIndex + ", minQuantity=" + minQuantity); } } else { pricePlan.setMinQuantity(null); } // maxQuantity if (!StringUtils.isBlank(maxQuantity)) { try { pricePlan.setMaxQuantity(new BigDecimal(maxSubAge)); } catch (Exception e) { throw new BusinessException( "Invalid maxQuantity in line=" + rowIndex + ", maxQuantity=" + maxQuantity); } } else { pricePlan.setMaxQuantity(null); } // Criteria1 if (!StringUtils.isBlank(criteria1)) { try { pricePlan.setCriteria1Value(criteria1); } catch (Exception e) { throw new BusinessException("Invalid criteria1 in line=" + rowIndex + ", criteria1=" + criteria1); } } else { pricePlan.setCriteria1Value(null); } // Criteria2 if (!StringUtils.isBlank(criteria2)) { try { pricePlan.setCriteria2Value(criteria2); } catch (Exception e) { throw new BusinessException("Invalid criteria2 in line=" + rowIndex + ", criteria2=" + criteria2); } } else { pricePlan.setCriteria2Value(null); } // Criteria3 if (!StringUtils.isBlank(criteria3)) { try { pricePlan.setCriteria3Value(criteria3); } catch (Exception e) { throw new BusinessException("Invalid criteria3 in line=" + rowIndex + ", criteria3=" + criteria3); } } else { pricePlan.setCriteria3Value(null); } // CriteriaEL if (!StringUtils.isBlank(criteriaEL)) { try { pricePlan.setCriteriaEL(criteriaEL); ; } catch (Exception e) { throw new BusinessException( "Invalid criteriaEL in line=" + rowIndex + ", criteriaEL=" + criteriaEL); } } else { pricePlan.setCriteriaEL(null); } // minSubAge if (!StringUtils.isBlank(minSubAge)) { try { pricePlan.setMinSubscriptionAgeInMonth(Long.parseLong(minSubAge)); } catch (Exception e) { throw new BusinessException("Invalid minSubAge in line=" + rowIndex + ", minSubAge=" + minSubAge); } } else { pricePlan.setMinSubscriptionAgeInMonth(0L); } // maxSubAge if (!StringUtils.isBlank(maxSubAge)) { try { pricePlan.setMaxSubscriptionAgeInMonth(Long.parseLong(maxSubAge)); } catch (Exception e) { throw new BusinessException("Invalid maxSubAge in line=" + rowIndex + ", maxSubAge=" + maxSubAge); } } else { pricePlan.setMaxSubscriptionAgeInMonth(9999L); } if (pricePlan.getId() == null) { create(pricePlan, user); } else { pricePlan.updateAudit(user); updateNoCheck(pricePlan); } }
From source file:com.unilever.audit.services2.SyncUp.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void saveVisit(JSONObject visitData) throws Exception { Map<String, Object> hm = new HashMap<String, Object>(); /***************Visit***********************/ Visit saveVisit = new Visit(); hm.put("id", visitData.get("visitId").toString()); if (visitFacadeREST.findOneByQuery("Visit.findById", hm) == null) { saveVisit.setId(visitData.get("visitId").toString()); Customers c = em.getReference(Customers.class, (Integer.parseInt(visitData.get("customerId").toString()))); saveVisit.setCustomerid(c);// ww w.j a va 2 s. co m Merchandisers m = em.getReference(Merchandisers.class, new BigDecimal(visitData.get("merchandiserId").toString())); saveVisit.setMerchandiserid(m); try { //Date date = new SimpleDateFormat("MM/dd/yyyy").parse(visitData.get("visitDate").toString()); Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") .parse(visitData.get("visitDate").toString()); saveVisit.setVisitdate(date); } catch (java.text.ParseException ex) { ex.printStackTrace(); } saveVisit.setSubmitteddate(new Date()); visitFacadeREST.create(saveVisit); /****************Product Result*********************/ JSONArray Productarray = (JSONArray) visitData.get("productResult"); for (Iterator<JSONObject> it1 = Productarray.iterator(); it1.hasNext();) { JSONObject ProductJson = it1.next(); ProductResult productResult = new ProductResult(); productResult.setQuantity(new BigInteger(ProductJson.get("quantity").toString())); productResult.setExsit(new BigInteger(ProductJson.get("exist").toString())); productResult.setVisitid(saveVisit); Productkpis ProductKPI = em.getReference(Productkpis.class, new BigDecimal(ProductJson.get("productKpiId").toString())); productResult.setProductid(ProductKPI); productResultFacadeREST.create(productResult); } /*********************Price Result*******************/ JSONArray Pricearray = (JSONArray) visitData.get("priceResult"); if (Pricearray.size() > 0) { for (Iterator<JSONObject> it2 = Pricearray.iterator(); it2.hasNext();) { JSONObject PriceJson = it2.next(); PriceResult priceResult = new PriceResult(); priceResult.setVisitid(saveVisit); priceResult.setPrice(new BigDecimal(PriceJson.get("pricevalue").toString())); priceResult.setPricetagexist(new BigInteger(PriceJson.get("pricetagcheck").toString())); Pricekpis PriceKPI = em.getReference(Pricekpis.class, new BigDecimal(PriceJson.get("priceKPIid").toString())); priceResult.setPriceid(PriceKPI); priceResultFacadeREST.create(priceResult); } } /*********************Question Result*****************/ JSONArray Questionarray = (JSONArray) visitData.get("questionResult"); for (Iterator<JSONObject> it3 = Questionarray.iterator(); it3.hasNext();) { JSONObject QuestionJson = it3.next(); QuestionResult questionResult = new QuestionResult(); questionResult.setVisitid(saveVisit); questionResult.setAnswertext(QuestionJson.get("answerText").toString()); Questionkpis questionKPI = em.getReference(Questionkpis.class, new BigDecimal(QuestionJson.get("questionId").toString())); questionResult.setQuestionid(questionKPI); questionResultFacadeREST.create(questionResult); } /*********************Promotion Result*********************/ JSONArray promotionarray = (JSONArray) visitData.get("promotionResult"); for (Iterator<JSONObject> it4 = promotionarray.iterator(); it4.hasNext();) { JSONObject PromotionJson = it4.next(); PromotionResult promotionResult = new PromotionResult(); promotionResult.setVisitid(saveVisit); promotionResult.setExist(new BigInteger(PromotionJson.get("exist").toString())); Promotionkpis promotionKPI = em.getReference(Promotionkpis.class, new BigDecimal(PromotionJson.get("promotionKPIid").toString())); promotionResult.setPromotionid(promotionKPI); promotionResultFacadeREST.create(promotionResult); } /***********************ShareOfFolder Result*********************/ JSONArray ShareOfFolderarray = (JSONArray) visitData.get("sofResult"); for (Iterator<JSONObject> it5 = ShareOfFolderarray.iterator(); it5.hasNext();) { JSONObject SofJson = it5.next(); ShareoffolderKpiResult SofResult = new ShareoffolderKpiResult(); SofResult.setVisitid(saveVisit); SofResult.setNoofpicture(new BigInteger(SofJson.get("noOfPicture").toString())); SofResult.setTotalofpicture(new BigInteger(SofJson.get("totalNoOfPicture").toString())); Shareoffolderkpis shareoffolderkpis = em.getReference(Shareoffolderkpis.class, new BigDecimal(SofJson.get("sofID").toString())); SofResult.setSofid(shareoffolderkpis); SofResult.setSofexist(new BigInteger(SofJson.get("sofExist").toString())); shareoffolderKpiResultFacadeREST.create(SofResult); } /***************************STOCK Result***********************/ JSONArray Stockarray = (JSONArray) visitData.get("stockResult"); for (Iterator<JSONObject> it8 = Stockarray.iterator(); it8.hasNext();) { JSONObject StockJson = it8.next(); StockResult stockResult = new StockResult(); stockResult.setQuantity(new BigInteger(StockJson.get("quantity").toString())); stockResult.setVisitid(saveVisit); stockResult.setStockquantity(new BigInteger(StockJson.get("stockQuantity").toString())); Stockkpis stockKPI = em.getReference(Stockkpis.class, new BigDecimal(StockJson.get("stockKpiId").toString())); stockResult.setStockid(stockKPI); stockResultFacadeREST.create(stockResult); } /********************NPD Result**************************/ JSONArray Npdarray = (JSONArray) visitData.get("npdResult"); for (Iterator<JSONObject> it6 = Npdarray.iterator(); it6.hasNext();) { JSONObject NpdJson = it6.next(); NpdResult npdResult = new NpdResult(); npdResult.setVisitid(saveVisit); npdResult.setExist(new BigInteger(NpdJson.get("exist").toString())); Npdkpis npdKPI = em.getReference(Npdkpis.class, new BigDecimal(NpdJson.get("npdid").toString())); npdResult.setNpdid(npdKPI); npdResultFacadeREST.create(npdResult); } /***********************share of shelf Result**********************/ JSONArray shareOfShelfarray = (JSONArray) visitData.get("shareOfShelfResult"); for (Iterator<JSONObject> it7 = shareOfShelfarray.iterator(); it7.hasNext();) { JSONObject ShareOfShelfJson = it7.next(); ShareofshelfKpiResult shareofshelfKpiResult = new ShareofshelfKpiResult(); shareofshelfKpiResult.setVisitid(saveVisit); shareofshelfKpiResult.setSosbrand(new BigInteger(ShareOfShelfJson.get("sosBrand").toString())); shareofshelfKpiResult.setSossegment(new BigInteger(ShareOfShelfJson.get("sosSegment").toString())); Shareofshelfkpi ShareOfShelfKPI = em.getReference(Shareofshelfkpi.class, new BigDecimal(ShareOfShelfJson.get("shareofShelfID").toString())); shareofshelfKpiResult.setShareofshelfid(ShareOfShelfKPI); shareofshelfKpiResultFacadeREST.create(shareofshelfKpiResult); } /***********************POS Result************************/ JSONArray Posarray = (JSONArray) visitData.get("posResult"); for (Iterator<JSONObject> it9 = Posarray.iterator(); it9.hasNext();) { JSONObject PosJson = it9.next(); PosmaterialResult posResult = new PosmaterialResult(); posResult.setVisitid(saveVisit); posResult.setExist(new BigInteger(PosJson.get("exist").toString())); Posmaterialkpi posmaterialKPI = em.getReference(Posmaterialkpi.class, new BigDecimal(PosJson.get("posid").toString())); posResult.setPosmaterialid(posmaterialKPI); posmaterialResultFacadeREST.create(posResult); } } }