List of usage examples for java.lang Integer shortValue
public short shortValue()
From source file:voldemort.client.rebalance.AbstractZonedRebalanceTest.java
@Test(timeout = 600000) public void testProxyPutDuringRebalancing() throws Exception { logger.info("Starting testProxyPutDuringRebalancing"); try {//from w w w. j a va 2 s. c o m Cluster currentCluster = ServerTestUtils.getLocalZonedCluster(6, 2, new int[] { 0, 0, 0, 1, 1, 1 }, new int[][] { { 0 }, { 1, 6 }, { 2 }, { 3 }, { 4, 7 }, { 5 } }); Cluster finalCluster = UpdateClusterUtils.createUpdatedCluster(currentCluster, 2, Lists.newArrayList(7)); finalCluster = UpdateClusterUtils.createUpdatedCluster(finalCluster, 5, Lists.newArrayList(6)); /** * Original partition map * * [s0 : p0] [s1 : p1, p6] [s2 : p2] * * [s3 : p3] [s4 : p4, p7] [s5 : p5] * * final server partition ownership * * [s0 : p0] [s1 : p1] [s2 : p2, p7] * * [s3 : p3] [s4 : p4] [s5 : p5, p6] * * Note that rwStoreDefFileWithReplication is a "2/1/1" store def. * * Original server n-ary partition ownership * * [s0 : p0, p3-7] [s1 : p0-p7] [s2 : p1-2] * * [s3 : p0-3, p6-7] [s4 : p0-p7] [s5 : p4-5] * * final server n-ary partition ownership * * [s0 : p0, p2-7] [s1 : p0-1] [s2 : p1-p7] * * [s3 : p0-3, p5-7] [s4 : p0-4, p7] [s5 : p4-6] */ List<Integer> serverList = Arrays.asList(0, 1, 2, 3, 4, 5); Map<String, String> configProps = new HashMap<String, String>(); configProps.put("admin.max.threads", "5"); final Cluster updatedCurrentCluster = startServers(currentCluster, rwStoreDefFileWithReplication, serverList, configProps); ExecutorService executors = Executors.newFixedThreadPool(2); final AtomicBoolean rebalancingComplete = new AtomicBoolean(false); final List<Exception> exceptions = Collections.synchronizedList(new ArrayList<Exception>()); // Its is imperative that we test in a single shot since multiple // batches would mean the proxy bridges being torn down and // established multiple times and we cannot test against the source // cluster topology then. getRebalanceKit uses batch size of // infinite, so this should be fine. String bootstrapUrl = getBootstrapUrl(updatedCurrentCluster, 0); int maxParallel = 2; final ClusterTestUtils.RebalanceKit rebalanceKit = ClusterTestUtils.getRebalanceKit(bootstrapUrl, maxParallel, finalCluster); populateData(currentCluster, rwStoreDefWithReplication); final AdminClient adminClient = rebalanceKit.controller.getAdminClient(); // the plan would cause these partitions to move: // Partition : Donor -> stealer // // p2 (Z-SEC) : s1 -> s0 // p3-6 (Z-PRI) : s1 -> s2 // p7 (Z-PRI) : s0 -> s2 // // p5 (Z-SEC): s4 -> s3 // p6 (Z-PRI): s4 -> s5 // // :. rebalancing will run on servers 0, 2, 3, & 5 final List<ByteArray> movingKeysList = sampleKeysFromPartition(adminClient, 1, rwStoreDefWithReplication.getName(), Arrays.asList(6), 20); assertTrue("Empty list of moving keys...", movingKeysList.size() > 0); final AtomicBoolean rebalancingStarted = new AtomicBoolean(false); final AtomicBoolean proxyWritesDone = new AtomicBoolean(false); final HashMap<String, String> baselineTuples = new HashMap<String, String>(testEntries); final HashMap<String, VectorClock> baselineVersions = new HashMap<String, VectorClock>(); for (String key : baselineTuples.keySet()) { baselineVersions.put(key, new VectorClock()); } final CountDownLatch latch = new CountDownLatch(2); // start get operation. executors.execute(new Runnable() { @Override public void run() { SocketStoreClientFactory factory = null; try { // wait for the rebalancing to begin List<VoldemortServer> serverList = Lists.newArrayList(serverMap.get(0), serverMap.get(2), serverMap.get(3), serverMap.get(5)); while (!rebalancingComplete.get()) { Iterator<VoldemortServer> serverIterator = serverList.iterator(); while (serverIterator.hasNext()) { VoldemortServer server = serverIterator.next(); if (ByteUtils .getString(server.getMetadataStore() .get(MetadataStore.SERVER_STATE_KEY, null).get(0).getValue(), "UTF-8") .compareTo(VoldemortState.REBALANCING_MASTER_SERVER.toString()) == 0) { logger.info("Server " + server.getIdentityNode().getId() + " transitioned into REBALANCING MODE"); serverIterator.remove(); } } if (serverList.size() == 0) { rebalancingStarted.set(true); break; } } if (rebalancingStarted.get()) { factory = new SocketStoreClientFactory( new ClientConfig().setBootstrapUrls(getBootstrapUrl(updatedCurrentCluster, 0)) .setEnableLazy(false).setSocketTimeout(120, TimeUnit.SECONDS) .setClientZoneId(1)); final StoreClient<String, String> storeClientRW = new DefaultStoreClient<String, String>( testStoreNameRW, null, factory, 3); // Now perform some writes and determine the end // state of the changed keys. Initially, all data // now with zero vector clock for (ByteArray movingKey : movingKeysList) { try { String keyStr = ByteUtils.getString(movingKey.get(), "UTF-8"); String valStr = "proxy_write"; storeClientRW.put(keyStr, valStr); baselineTuples.put(keyStr, valStr); // all these keys will have [5:1] vector // clock is node 5 is the new pseudo master baselineVersions.get(keyStr).incrementVersion(5, System.currentTimeMillis()); proxyWritesDone.set(true); if (rebalancingComplete.get()) { break; } } catch (InvalidMetadataException e) { // let this go logger.error("Encountered an invalid metadata exception.. ", e); } } } } catch (Exception e) { logger.error("Exception in proxy write thread..", e); exceptions.add(e); } finally { if (factory != null) factory.close(); latch.countDown(); } } }); executors.execute(new Runnable() { @Override public void run() { try { rebalanceKit.rebalance(); } catch (Exception e) { logger.error("Error in rebalancing... ", e); exceptions.add(e); } finally { rebalancingComplete.set(true); latch.countDown(); } } }); latch.await(); executors.shutdown(); executors.awaitTermination(300, TimeUnit.SECONDS); assertEquals("Client did not see all server transition into rebalancing state", rebalancingStarted.get(), true); assertEquals("Not enough time to begin proxy writing", proxyWritesDone.get(), true); checkEntriesPostRebalance(updatedCurrentCluster, finalCluster, Lists.newArrayList(rwStoreDefWithReplication), Arrays.asList(0, 1, 2, 3, 4, 5), baselineTuples, baselineVersions); checkConsistentMetadata(finalCluster, serverList); // check No Exception if (exceptions.size() > 0) { for (Exception e : exceptions) { e.printStackTrace(); } fail("Should not see any exceptions."); } // check that the proxy writes were made to the original donor, node // 1 List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverList.size()); for (Integer nodeid : serverList) clockEntries.add(new ClockEntry(nodeid.shortValue(), System.currentTimeMillis())); VectorClock clusterXmlClock = new VectorClock(clockEntries, System.currentTimeMillis()); for (Integer nodeid : serverList) adminClient.metadataMgmtOps.updateRemoteCluster(nodeid, currentCluster, clusterXmlClock); adminClient.setAdminClientCluster(currentCluster); checkForTupleEquivalence(adminClient, 1, testStoreNameRW, movingKeysList, baselineTuples, baselineVersions); // stop servers try { stopServer(serverList); } catch (Exception e) { throw new RuntimeException(e); } } catch (AssertionError ae) { logger.error("Assertion broken in testProxyPutDuringRebalancing ", ae); throw ae; } }
From source file:eu.smartenit.sdn.floodlight090.dtm.DTM.java
/** * Updates configuration./* w ww .j ava 2 s . c om*/ * * @param configData configuration */ public synchronized void setConfigData(ConfigData configData) throws IllegalArgumentException { logger.debug("setConfigData(ConfigData) begin"); logger.debug("Updating configuration..."); validateConfigData(configData); this.configData = configData; daRouterPorts = getAllDARouterPorts(configData); logger.debug("All DA Router ports: " + daRouterPorts.toString()); int i = 1; for (ConfigDataEntry configDataEntry : configData.getEntries()) { ArrayList<Short> ports = new ArrayList<Short>(); for (TunnelInfo tunnelInfo : configDataEntry.getTunnels()) { ports.add((short) tunnelInfo.getDaRouterOfPortNumber()); } dcNumberOfPortsMap.put(i, ports); dcNumberDCAddress.put(i, configDataEntry.getRemoteDcPrefix()); i++; } //init DA Router for (LocalDCOfSwitchPorts localDCOfSwitchPorts : configData.getLocalDCPortsConfig()) { for (Integer localDCOfSwitchPortNumber : localDCOfSwitchPorts.getLocalDCOfSwitchPortNumbers()) { for (ConfigDataEntry configDataEntry : configData.getEntries()) { for (TunnelInfo tunnelInfo : configDataEntry.getTunnels()) { Flows.init(sw, floodlightProvider, null, localDCOfSwitchPortNumber.shortValue(), (short) tunnelInfo.getDaRouterOfPortNumber()); } } } } logger.debug("setConfigData(ConfigData) end"); }
From source file:org.mifos.accounts.productdefinition.business.PrdOfferingBO.java
/** * minimal legal constructor (based on table schema) *//*from w w w .j a v a2 s . c om*/ public PrdOfferingBO(Integer userId, String globalProductId, String name, String shortName, ProductCategoryBO productCategory, PrdStatusEntity status, PrdApplicableMasterEntity applicableToEntity, DateTime startDate, MifosCurrency currency) { this.prdOfferingId = null; this.prdOfferingName = name; this.prdOfferingShortName = shortName; this.globalPrdOfferingNum = globalProductId; this.prdCategory = productCategory; this.prdType = productCategory.getProductType(); this.prdStatus = status; this.prdApplicableMaster = applicableToEntity; this.startDate = startDate.toDate(); this.createdBy = userId.shortValue(); this.createdDate = new DateTime().toDate(); this.currency = currency; }
From source file:voldemort.client.rebalance.AbstractNonZonedRebalanceTest.java
@Test(timeout = 600000) public void testProxyPutDuringRebalancing() throws Exception { logger.info("Starting testProxyPutDuringRebalancing"); try {//from w ww . ja va 2s. co m Cluster currentCluster = ServerTestUtils.getLocalCluster(3, new int[][] { { 0 }, { 1, 3 }, { 2 } }); Cluster finalCluster = UpdateClusterUtils.createUpdatedCluster(currentCluster, 2, Lists.newArrayList(3)); // start servers 0,1,2 only final List<Integer> serverList = Arrays.asList(0, 1, 2); Map<String, String> configProps = new HashMap<String, String>(); configProps.put("admin.max.threads", "5"); final Cluster updatedCurrentCluster = startServers(currentCluster, rwStoreDefFileWithReplication, serverList, configProps); ExecutorService executors = Executors.newFixedThreadPool(2); final AtomicBoolean rebalancingComplete = new AtomicBoolean(false); final List<Exception> exceptions = Collections.synchronizedList(new ArrayList<Exception>()); // Its is imperative that we test in a single shot since multiple // batches would mean the proxy bridges being torn down and // established multiple times and we cannot test against the source // cluster topology then. String bootstrapUrl = getBootstrapUrl(currentCluster, 0); int maxParallel = 2; final ClusterTestUtils.RebalanceKit rebalanceKit = ClusterTestUtils.getRebalanceKit(bootstrapUrl, maxParallel, finalCluster); populateData(updatedCurrentCluster, rwStoreDefWithReplication, rebalanceKit.controller.getAdminClient(), false); final AdminClient adminClient = rebalanceKit.controller.getAdminClient(); // the plan would cause these partitions to move // Partition : Donor -> Stealer // p2 (SEC) : s1 -> s0 // p3 (PRI) : s1 -> s2 final List<ByteArray> movingKeysList = sampleKeysFromPartition(adminClient, 1, rwStoreDefWithReplication.getName(), Arrays.asList(2, 3), 20); assertTrue("Empty list of moving keys...", movingKeysList.size() > 0); final AtomicBoolean rebalancingStarted = new AtomicBoolean(false); final AtomicBoolean proxyWritesDone = new AtomicBoolean(false); final HashMap<String, String> baselineTuples = new HashMap<String, String>(testEntries); final HashMap<String, VectorClock> baselineVersions = new HashMap<String, VectorClock>(); for (String key : baselineTuples.keySet()) { baselineVersions.put(key, new VectorClock()); } final CountDownLatch latch = new CountDownLatch(2); // start get operation. executors.execute(new Runnable() { @Override public void run() { SocketStoreClientFactory factory = null; try { // wait for the rebalancing to begin. List<VoldemortServer> serverList = Lists.newArrayList(serverMap.get(0), serverMap.get(2)); while (!rebalancingComplete.get()) { Iterator<VoldemortServer> serverIterator = serverList.iterator(); while (serverIterator.hasNext()) { VoldemortServer server = serverIterator.next(); if (ByteUtils .getString(server.getMetadataStore() .get(MetadataStore.SERVER_STATE_KEY, null).get(0).getValue(), "UTF-8") .compareTo(VoldemortState.REBALANCING_MASTER_SERVER.toString()) == 0) { logger.info("Server " + server.getIdentityNode().getId() + " transitioned into REBALANCING MODE"); serverIterator.remove(); } } if (serverList.size() == 0) { rebalancingStarted.set(true); break; } } if (!rebalancingComplete.get()) { factory = new SocketStoreClientFactory( new ClientConfig().setBootstrapUrls(getBootstrapUrl(updatedCurrentCluster, 0)) .setEnableLazy(false).setSocketTimeout(120, TimeUnit.SECONDS)); final StoreClient<String, String> storeClientRW = new DefaultStoreClient<String, String>( testStoreNameRW, null, factory, 3); // Now perform some writes and determine the end // state // of the changed keys. Initially, all data now with // zero vector clock for (ByteArray movingKey : movingKeysList) { try { if (rebalancingComplete.get()) { break; } String keyStr = ByteUtils.getString(movingKey.get(), "UTF-8"); String valStr = "proxy_write"; storeClientRW.put(keyStr, valStr); baselineTuples.put(keyStr, valStr); // all these keys will have [2:1] vector // clock // is node 2 is the pseudo master in both // moves baselineVersions.get(keyStr).incrementVersion(2, System.currentTimeMillis()); proxyWritesDone.set(true); } catch (InvalidMetadataException e) { // let this go logger.error("Encountered an invalid metadata exception.. ", e); } } } } catch (Exception e) { logger.error("Exception in proxy put thread", e); exceptions.add(e); } finally { if (factory != null) factory.close(); latch.countDown(); } } }); executors.execute(new Runnable() { @Override public void run() { try { rebalanceKit.rebalance(); } catch (Exception e) { logger.error("Error in rebalancing... ", e); exceptions.add(e); } finally { rebalancingComplete.set(true); latch.countDown(); } } }); latch.await(); executors.shutdown(); executors.awaitTermination(300, TimeUnit.SECONDS); assertEquals("Client did not see all server transition into rebalancing state", rebalancingStarted.get(), true); assertEquals("Not enough time to begin proxy writing", proxyWritesDone.get(), true); checkEntriesPostRebalance(updatedCurrentCluster, finalCluster, Lists.newArrayList(rwStoreDefWithReplication), Arrays.asList(0, 1, 2), baselineTuples, baselineVersions); checkConsistentMetadata(finalCluster, serverList); // check No Exception if (exceptions.size() > 0) { for (Exception e : exceptions) { e.printStackTrace(); } fail("Should not see any exceptions."); } // check that the proxy writes were made to the original donor, node // 1 List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverList.size()); for (Integer nodeid : serverList) clockEntries.add(new ClockEntry(nodeid.shortValue(), System.currentTimeMillis())); VectorClock clusterXmlClock = new VectorClock(clockEntries, System.currentTimeMillis()); for (Integer nodeid : serverList) adminClient.metadataMgmtOps.updateRemoteCluster(nodeid, currentCluster, clusterXmlClock); adminClient.setAdminClientCluster(currentCluster); checkForTupleEquivalence(adminClient, 1, testStoreNameRW, movingKeysList, baselineTuples, baselineVersions); // stop servers try { stopServer(serverList); } catch (Exception e) { throw new RuntimeException(e); } } catch (AssertionError ae) { logger.error("Assertion broken in testProxyPutDuringRebalancing ", ae); throw ae; } }
From source file:engine.resources.objects.Baseline.java
public IoBuffer createDelta(List<Integer> objectQueue, byte[] data) { byte[] objects = {}; int size = 2; for (Integer o : objectQueue) { byte[] object; if (hasBuilders && getDeltaBuilders().containsKey(o)) { object = getDeltaBuilders().get(o).build(this.object); } else if (data != null) { object = data;/* w w w.j a va 2 s .c o m*/ } else { object = toBytes(get(o)); } size += 2 + object.length; IoBuffer buffer = createBuffer(size); buffer.put(objects); buffer.putShort(o.shortValue()); buffer.put(object); buffer.flip(); objects = buffer.array(); } IoBuffer buffer = createBuffer(27 + size); buffer.putShort((short) 5); buffer.putInt(Opcodes.DeltasMessage); buffer.putLong(object.getObjectID()); try { buffer.put(reverse(getShortTemplate()).getBytes("US-ASCII")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } buffer.put(viewType); buffer.putInt(size); buffer.putShort((short) objectQueue.size()); buffer.put(objects); buffer.flip(); //StringUtilities.printBytes(buffer.array()); return buffer; }
From source file:com.linkedin.databus.core.TestDbusEventBufferMult.java
private void batchReading(Set<Integer> srcIds, final int expectEvents, final int batchFetchSize) throws IOException, ScnNotFoundException, DatabusException, OffsetNotFoundException { // for debug generate this line String inputSrcIds = Arrays.toString(srcIds.toArray()); LOG.info("Reading events from " + inputSrcIds); // create checkpoints CheckpointMult cpMult = new CheckpointMult(); for (PhysicalSourceStaticConfig pConf : _pConfigs) { PhysicalPartition pPart = pConf.getPhysicalPartition(); Checkpoint cp;/*from ww w . j av a 2s . c om*/ if (cpMult.getCheckpoint(pPart) == null) { // needs a new checkpoint cp = new Checkpoint(); cp.setFlexible(); cpMult.addCheckpoint(pPart, cp); } } DbusEventBufferBatchReadable read = _eventBufferMult.getDbusEventBufferBatchReadable(srcIds, cpMult, null); int totalRead = 0; int numEventsRead = Integer.MAX_VALUE; int numNonControlEventsRead = 0; int maxIterNum = 100, iterCount = 0; String prevEvent = ""; while (numEventsRead > 0) { if (iterCount++ > maxIterNum) { fail("Checkpoint doesn't work - it is a never-ending loop"); } ByteArrayOutputStream jsonOut = new ByteArrayOutputStream(); WritableByteChannel jsonOutChannel = Channels.newChannel(jsonOut); numEventsRead = read.streamEvents(false, batchFetchSize, jsonOutChannel, Encoding.JSON_PLAIN_VALUE, new SourceDbusFilter(srcIds)).getNumEventsStreamed(); totalRead += numEventsRead; LOG.info("read for " + inputSrcIds + ": " + numEventsRead + " events"); byte[] jsonBytes = jsonOut.toByteArray(); if (jsonBytes.length == 0) break; // nothing more to read String jsonString = new String(jsonBytes); String[] jsonStrings = jsonString.split("\n"); assertEquals(jsonStrings.length, numEventsRead); ObjectMapper mapper = new ObjectMapper(); for (int i = 0; i < jsonStrings.length; i++) { // verify what was written String evtStr = jsonStrings[i]; if (evtStr.equals(prevEvent)) { // It may so happen that we receive the same event twice, especially when the // offered buffer is small. This check gets around the issue. continue; } prevEvent = evtStr; Map<String, Object> jsonMap = mapper.readValue(evtStr, new TypeReference<Map<String, Object>>() { }); //assertEquals(jsonMap.size(), 10); Integer srcId = (Integer) jsonMap.get("srcId"); if (!DbusEventUtils.isControlSrcId(srcId)) { // not a control message numNonControlEventsRead++; Integer physicalPartitionId = (Integer) jsonMap.get("physicalPartitionId"); Integer logicalPartitionId = (Integer) jsonMap.get("logicalPartitionId"); PhysicalPartition pPartition = _eventBufferMult.getPhysicalPartition(srcId, new LogicalPartition(logicalPartitionId.shortValue())); LOG.info("EVENT: " + jsonMap.toString()); assertTrue(srcIds.contains(srcId), "src id " + srcId + " doesn't match to " + inputSrcIds); assertEquals(physicalPartitionId, pPartition.getId(), "physical partition id didn't match"); } else { LOG.info("Control event: " + jsonMap.toString()); } } } assertTrue(totalRead > numNonControlEventsRead); assertEquals(numNonControlEventsRead, expectEvents); }
From source file:org.mifos.application.servicefacade.SavingsServiceFacadeWebTier.java
@Override public String createSavingsAccount(OpeningBalanceSavingsAccount openingBalanceSavingsAccount) { MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); LocalDate createdDate = new LocalDate(); Integer createdById = user.getUserId(); PersonnelBO createdBy = this.personnelDao.findPersonnelById(createdById.shortValue()); CustomerBO customer = this.customerDao .findCustomerBySystemId(openingBalanceSavingsAccount.getCustomerGlobalId()); SavingsOfferingBO savingsProduct = this.savingsProductDao .findBySystemId(openingBalanceSavingsAccount.getProductGlobalId()); AccountState savingsAccountState = AccountState.fromShort(openingBalanceSavingsAccount.getAccountState()); Money recommendedOrMandatory = new Money(savingsProduct.getCurrency(), openingBalanceSavingsAccount.getRecommendedOrMandatoryAmount()); Money openingBalance = new Money(savingsProduct.getCurrency(), openingBalanceSavingsAccount.getOpeningBalance()); LocalDate activationDate = openingBalanceSavingsAccount.getActivationDate(); CalendarEvent calendarEvents = this.holidayDao.findCalendarEventsForThisYearAndNext(customer.getOfficeId()); SavingsAccountActivationDetail activationDetails = SavingsBO.determineAccountActivationDetails(customer, savingsProduct, recommendedOrMandatory, savingsAccountState, calendarEvents, activationDate); SavingsBO savingsAccount = SavingsBO.createOpeningBalanceIndividualSavingsAccount(customer, savingsProduct, recommendedOrMandatory, savingsAccountState, createdDate, createdById, activationDetails, createdBy, openingBalance);//from w ww . j a v a2 s. c o m try { this.transactionHelper.startTransaction(); this.savingsDao.save(savingsAccount); this.transactionHelper.flushSession(); savingsAccount.generateSystemId(createdBy.getOffice().getGlobalOfficeNum()); this.savingsDao.save(savingsAccount); this.transactionHelper.commitTransaction(); return savingsAccount.getGlobalAccountNum(); } catch (BusinessRuleException e) { this.transactionHelper.rollbackTransaction(); throw new BusinessRuleException(e.getMessageKey(), e); } catch (Exception e) { this.transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } finally { this.transactionHelper.closeSession(); } }
From source file:org.mifos.application.servicefacade.SavingsServiceFacadeWebTier.java
@Override public Long createSavingsAccount(SavingsAccountCreationDto savingsAccountCreation, List<QuestionGroupDetail> questionGroups) { MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); LocalDate createdDate = new LocalDate(); Integer createdById = user.getUserId(); PersonnelBO createdBy = this.personnelDao.findPersonnelById(createdById.shortValue()); CustomerBO customer = this.customerDao.findCustomerById(savingsAccountCreation.getCustomerId()); SavingsOfferingBO savingsProduct = this.savingsProductDao.findById(savingsAccountCreation.getProductId()); Money recommendedOrMandatory = new Money(savingsProduct.getCurrency(), savingsAccountCreation.getRecommendedOrMandatoryAmount()); AccountState savingsAccountState = AccountState.fromShort(savingsAccountCreation.getAccountState()); CalendarEvent calendarEvents = this.holidayDao.findCalendarEventsForThisYearAndNext(customer.getOfficeId()); SavingsAccountTypeInspector savingsAccountWrapper = new SavingsAccountTypeInspector(customer, savingsProduct.getRecommendedAmntUnit()); try {/*from w ww . j a va 2s . c o m*/ SavingsBO savingsAccount = null; if (savingsAccountWrapper.isIndividualSavingsAccount()) { savingsAccount = SavingsBO.createIndividalSavingsAccount(customer, savingsProduct, recommendedOrMandatory, savingsAccountState, createdDate, createdById, calendarEvents, createdBy); } else if (savingsAccountWrapper.isJointSavingsAccountWithClientTracking()) { List<CustomerBO> activeAndOnHoldClients = new CustomerPersistence().getActiveAndOnHoldChildren( customer.getSearchId(), customer.getOfficeId(), CustomerLevel.CLIENT); savingsAccount = SavingsBO.createJointSavingsAccount(customer, savingsProduct, recommendedOrMandatory, savingsAccountState, createdDate, createdById, calendarEvents, createdBy, activeAndOnHoldClients); } this.transactionHelper.startTransaction(); this.savingsDao.save(savingsAccount); this.transactionHelper.flushSession(); savingsAccount.generateSystemId(createdBy.getOffice().getGlobalOfficeNum()); this.savingsDao.save(savingsAccount); this.transactionHelper.flushSession(); // save question groups if (!questionGroups.isEmpty()) { Integer eventSourceId = questionnaireServiceFacade.getEventSourceId("Create", "Savings"); QuestionGroupDetails questionGroupDetails = new QuestionGroupDetails( Integer.valueOf(user.getUserId()).shortValue(), savingsAccount.getAccountId(), eventSourceId, questionGroups); questionnaireServiceFacade.saveResponses(questionGroupDetails); } this.transactionHelper.commitTransaction(); return savingsAccount.getAccountId().longValue(); } catch (BusinessRuleException e) { this.transactionHelper.rollbackTransaction(); throw new BusinessRuleException(e.getMessageKey(), e); } catch (Exception e) { this.transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } finally { this.transactionHelper.closeSession(); } }
From source file:org.mifos.application.servicefacade.AdminServiceFacadeWebTier.java
@Override public ReportCategoryDto retrieveReportCategory(Integer reportCategoryId) { ReportsCategoryBO reportsCategoryBO = new ReportsPersistence() .getReportCategoryByCategoryId(reportCategoryId.shortValue()); return reportsCategoryBO.toDto(); }
From source file:org.mifos.application.servicefacade.AdminServiceFacadeWebTier.java
@Override public void createOrUpdateProductMix(Integer productId, List<Integer> notAllowedProductIds) { try {//from ww w . j ava 2s .com PrdOfferingBO product = new PrdOfferingPersistence().getPrdOfferingByID(productId.shortValue()); StaticHibernateUtil.startTransaction(); product.setPrdMixFlag(YesNoFlag.YES.getValue()); applicationConfigurationDao.save(product); StaticHibernateUtil.flushSession(); List<PrdOfferingBO> newNotAllowedProducts = new ArrayList<PrdOfferingBO>(); for (Integer notAllowedProductId : notAllowedProductIds) { PrdOfferingBO notAllowedProduct = new PrdOfferingPersistence() .getPrdOfferingByID(notAllowedProductId.shortValue()); newNotAllowedProducts.add(notAllowedProduct); } for (ProductMixBO oldNotAllowedProduct : product.getCollectionProductMix()) { ProductMixBO productMix = legacyProductMixDao.getPrdOfferingMixByPrdOfferingID( productId.shortValue(), oldNotAllowedProduct.getPrdOfferingNotAllowedId().getPrdOfferingId()); if (null != productMix) { applicationConfigurationDao.delete(productMix); StaticHibernateUtil.flushSession(); } ProductMixBO alternateproductmix = legacyProductMixDao.getPrdOfferingMixByPrdOfferingID( oldNotAllowedProduct.getPrdOfferingNotAllowedId().getPrdOfferingId(), productId.shortValue()); if (null != alternateproductmix) { applicationConfigurationDao.delete(alternateproductmix); StaticHibernateUtil.flushSession(); } } for (PrdOfferingBO notAllowedProduct : newNotAllowedProducts) { ProductMixBO productMix = new ProductMixBO(product, notAllowedProduct); productMix.setUpdatedDate(new DateTime().toDate()); productMix.setUpdatedBy(Short.valueOf("1")); applicationConfigurationDao.save(productMix); StaticHibernateUtil.flushSession(); } StaticHibernateUtil.commitTransaction(); } catch (Exception e) { StaticHibernateUtil.rollbackTransaction(); throw new MifosRuntimeException(e); } finally { StaticHibernateUtil.closeSession(); } }