List of usage examples for java.util HashMap size
int size
To view the source code for java.util HashMap size.
Click Source Link
From source file:org.gephi.statistics.plugin.Renumbering.java
public void triangles(HierarchicalGraph hgraph) { int ProgressCount = 0; Progress.start(progress, 7 * hgraph.getNodeCount()); hgraph.readLock();/* ww w .ja v a2s .c o m*/ N = hgraph.getNodeCount(); nodeClustering = new double[N]; /** Create network for processing */ network = new ArrayWrapper[N]; /** */ HashMap<Node, Integer> indicies = new HashMap<Node, Integer>(); int index = 0; for (Node s : hgraph.getNodes()) { indicies.put(s, index); network[index] = new ArrayWrapper(); index++; Progress.progress(progress, ++ProgressCount); } index = 0; for (Node node : hgraph.getNodes()) { HashMap<Node, EdgeWrapper> neighborTable = new HashMap<Node, EdgeWrapper>(); if (!isDirected) { for (Edge edge : hgraph.getEdgesAndMetaEdges(node)) { Node neighbor = hgraph.getOpposite(node, edge); neighborTable.put(neighbor, new EdgeWrapper(1, network[indicies.get(neighbor)])); } } else { for (Edge in : ((HierarchicalDirectedGraph) hgraph).getInEdgesAndMetaInEdges(node)) { Node neighbor = in.getSource().getNodeData().getNode(hgraph.getView().getViewId()); neighborTable.put(neighbor, new EdgeWrapper(1, network[indicies.get(neighbor)])); } for (Edge out : ((HierarchicalDirectedGraph) hgraph).getOutEdgesAndMetaOutEdges(node)) { Node neighbor = out.getTarget().getNodeData().getNode(hgraph.getView().getViewId()); EdgeWrapper ew = neighborTable.get(neighbor); if (ew == null) { neighborTable.put(neighbor, new EdgeWrapper(1, network[indicies.get(neighbor)])); } else { ew.count++; } } } EdgeWrapper[] edges = new EdgeWrapper[neighborTable.size()]; int i = 0; for (EdgeWrapper e : neighborTable.values()) { edges[i] = e; i++; } network[index].node = node; network[index].setArray(edges); index++; Progress.progress(progress, ++ProgressCount); if (isCanceled) { hgraph.readUnlockAll(); return; } } Arrays.sort(network); for (int j = 0; j < N; j++) { network[j].setID(j); Progress.progress(progress, ++ProgressCount); } for (int j = 0; j < N; j++) { Arrays.sort(network[j].getArray(), new Renumbering()); Progress.progress(progress, ++ProgressCount); } triangles = new int[N]; K = (int) Math.sqrt(N); for (int v = 0; v < K && v < N; v++) { newVertex(v); Progress.progress(progress, ++ProgressCount); } /* remaining links */ for (int v = N - 1; (v >= 0) && (v >= K); v--) { for (int i = closest_in_array(v); i >= 0; i--) { int u = network[v].get(i); if (u >= K) { tr_link_nohigh(u, v, network[v].getCount(i)); } } Progress.progress(progress, ++ProgressCount); if (isCanceled) { hgraph.readUnlockAll(); return; } } //Results and average avgClusteringCoeff = 0; totalTriangles = 0; int numNodesDegreeGreaterThanOne = 0; for (int v = 0; v < N; v++) { if (network[v].length() > 1) { numNodesDegreeGreaterThanOne++; double cc = triangles[v]; totalTriangles += triangles[v]; cc /= (network[v].length() * (network[v].length() - 1)); if (!isDirected) { cc *= 2.0f; } nodeClustering[v] = cc; avgClusteringCoeff += cc; } Progress.progress(progress, ++ProgressCount); if (isCanceled) { hgraph.readUnlockAll(); return; } } totalTriangles /= 3; avgClusteringCoeff /= numNodesDegreeGreaterThanOne; hgraph.readUnlock(); }
From source file:org.openmeetings.axis.services.FileWebService.java
/** * //from ww w .ja v a 2s . c o m * Import file from external source * * to upload a file to a room-drive you specify: externalUserId, user if of * openmeetings user for which we upload the file room_id = openmeetings * room id isOwner = 0 parentFolderId = 0 * * to upload a file to a private-drive you specify: externalUserId, user if * of openmeetings user for which we upload the file room_id = openmeetings * room id isOwner = 1 parentFolderId = -2 * * @param SID The logged in session id with minimum webservice level * @param externalUserId * the external user id => If the file should goto a private * section of any user, this number needs to be set * @param externalFileId * the external file-type to identify the file later * @param externalType * the name of the external system * @param room_id * the room Id, if the file goes to the private folder of an * user, you can set a random number here * @param isOwner * specify a 1/true AND parentFolderId==-2 to make the file goto * the private section * @param path * http-path where we can grab the file from, the file has to be * accessible from the OpenMeetings server * @param parentFolderId * specify a parentFolderId==-2 AND isOwner == 1/true AND to make * the file goto the private section * @param fileSystemName * the filename => Important WITH file extension! * @return * @throws AxisFault */ public FileImportError[] importFile(String SID, String externalUserId, Long externalFileId, String externalType, Long room_id, boolean isOwner, String path, Long parentFolderId, String fileSystemName) throws AxisFault { try { Long users_id = sessionManagement.checkSession(SID); Long User_level = userManagement.getUserLevelByID(users_id); if (authLevelManagement.checkWebServiceLevel(User_level)) { String current_dir = getServletContext().getRealPath("/"); URL url = new URL(path); URLConnection uc = url.openConnection(); InputStream inputstream = new BufferedInputStream(uc.getInputStream()); Users externalUser = userManagement.getUserByExternalIdAndType(externalUserId, externalType); LinkedHashMap<String, Object> hs = new LinkedHashMap<String, Object>(); hs.put("user", externalUser); HashMap<String, HashMap<String, String>> returnError = fileProcessor.processFile( externalUser.getUser_id(), room_id, isOwner, inputstream, parentFolderId, fileSystemName, current_dir, hs, externalFileId, externalType); HashMap<String, String> returnAttributes = returnError.get("returnAttributes"); // Flash cannot read the response of an upload // httpServletResponse.getWriter().print(returnError); hs.put("message", "library"); hs.put("action", "newFile"); hs.put("fileExplorerItem", fileExplorerItemDao.getFileExplorerItemsById( Long.parseLong(returnAttributes.get("fileExplorerItemId").toString()))); hs.put("error", returnError); hs.put("fileName", returnAttributes.get("completeName")); FileImportError[] fileImportErrors = new FileImportError[returnError.size()]; int i = 0; // Axis need Objects or array of objects, Map won't work for (Iterator<String> iter = returnError.keySet().iterator(); iter.hasNext();) { HashMap<String, String> returnAttribute = returnError.get(iter.next()); fileImportErrors[i] = new FileImportError(); fileImportErrors[i].setCommand( (returnAttribute.get("command") != null) ? returnAttribute.get("command").toString() : ""); fileImportErrors[i].setError( (returnAttribute.get("error") != null) ? returnAttribute.get("error").toString() : ""); fileImportErrors[i].setExitValue((returnAttribute.get("exitValue") != null) ? Integer.valueOf(returnAttribute.get("exitValue").toString()).intValue() : 0); fileImportErrors[i].setProcess( (returnAttribute.get("process") != null) ? returnAttribute.get("process").toString() : ""); i++; } return fileImportErrors; } } catch (Exception err) { log.error("[importFile]", err); } return null; }
From source file:org.openmeetings.axis.services.FileWebService.java
/** * Import file from external source//w ww . j a va2 s . c om * * to upload a file to a room-drive you specify: internalUserId, user if of * openmeetings user for which we upload the file room_id = openmeetings * room id isOwner = 0 parentFolderId = 0 * * to upload a file to a private-drive you specify: internalUserId, user if * of openmeetings user for which we upload the file room_id = openmeetings * room id isOwner = 1 parentFolderId = -2 * * @param SID * The SID of the User. This SID must be marked as logged in * @param internalUserId * the openmeetings user id => If the file should goto a private * section of any user, this number needs to be se * @param externalFileId * the external file-type to identify the file later * @param externalType * the name of the external system * @param room_id * the room Id, if the file goes to the private folder of an * user, you can set a random number here * @param isOwner * specify a 1/true AND parentFolderId==-2 to make the file goto * the private section * @param path * http-path where we can grab the file from, the file has to be * accessible from the OpenMeetings server * @param parentFolderId * specify a parentFolderId==-2 AND isOwner == 1/true AND to make * the file goto the private section * @param fileSystemName * the filename => Important WITH file extension! * @return * @throws AxisFault */ public FileImportError[] importFileByInternalUserId(String SID, Long internalUserId, Long externalFileId, String externalType, Long room_id, boolean isOwner, String path, Long parentFolderId, String fileSystemName) throws AxisFault { try { Long users_id = sessionManagement.checkSession(SID); Long User_level = userManagement.getUserLevelByID(users_id); if (authLevelManagement.checkWebServiceLevel(User_level)) { String current_dir = getServletContext().getRealPath("/"); URL url = new URL(path); URLConnection uc = url.openConnection(); InputStream inputstream = new BufferedInputStream(uc.getInputStream()); Users internalUser = userManagement.getUserById(internalUserId); LinkedHashMap<String, Object> hs = new LinkedHashMap<String, Object>(); hs.put("user", internalUser); HashMap<String, HashMap<String, String>> returnError = fileProcessor.processFile( internalUser.getUser_id(), room_id, isOwner, inputstream, parentFolderId, fileSystemName, current_dir, hs, externalFileId, externalType); HashMap<String, String> returnAttributes = returnError.get("returnAttributes"); // Flash cannot read the response of an upload // httpServletResponse.getWriter().print(returnError); hs.put("message", "library"); hs.put("action", "newFile"); hs.put("fileExplorerItem", fileExplorerItemDao.getFileExplorerItemsById( Long.parseLong(returnAttributes.get("fileExplorerItemId").toString()))); hs.put("error", returnError); hs.put("fileName", returnAttributes.get("completeName")); FileImportError[] fileImportErrors = new FileImportError[returnError.size()]; int i = 0; // Axis need Objects or array of objects, Map won't work for (Iterator<String> iter = returnError.keySet().iterator(); iter.hasNext();) { HashMap<String, String> returnAttribute = returnError.get(iter.next()); fileImportErrors[i] = new FileImportError(); fileImportErrors[i].setCommand( (returnAttribute.get("command") != null) ? returnAttribute.get("command").toString() : ""); fileImportErrors[i].setError( (returnAttribute.get("error") != null) ? returnAttribute.get("error").toString() : ""); fileImportErrors[i].setExitValue((returnAttribute.get("exitValue") != null) ? Integer.valueOf(returnAttribute.get("exitValue").toString()).intValue() : 0); fileImportErrors[i].setProcess( (returnAttribute.get("process") != null) ? returnAttribute.get("process").toString() : ""); i++; } return fileImportErrors; } } catch (Exception err) { log.error("[importFile]", err); } return null; }
From source file:org.powertac.tariffmarket.CapacityControlServiceTest.java
/** * Up-regulation test/*from www . j a va2 s .c o m*/ */ @Test public void testExerciseBalancingControlUp() { TariffSubscription sub1 = tariffSubscriptionRepo.getSubscription(customer1, tariff); sub1.subscribe(100); TariffSubscription sub2 = tariffSubscriptionRepo.getSubscription(customer2, tariff); sub2.subscribe(200); sub1.usePower(200); sub2.usePower(300); BalancingOrder order = new BalancingOrder(broker, spec, 1.0, 0.1); RegulationCapacity cap = capacityControl.getRegulationCapacity(order); assertEquals("correct up-regulation", 0.4 * 500.0, cap.getUpRegulationCapacity(), 1e-6); assertEquals("correct down-regulation", 0.0, cap.getDownRegulationCapacity(), 1e-6); // exercise the control assertEquals("no messages yet", 0, msgs.size()); reset(mockAccounting); final HashMap<CustomerInfo, Object[]> answers = new HashMap<CustomerInfo, Object[]>(); when(mockAccounting.addTariffTransaction(any(TariffTransaction.Type.class), any(Tariff.class), any(CustomerInfo.class), anyInt(), anyDouble(), anyDouble())).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); CustomerInfo customer = (CustomerInfo) args[2]; answers.put(customer, args); return null; } }); capacityControl.exerciseBalancingControl(order, 100.0, 11.0); // check the outgoing message assertEquals("one message", 1, msgs.size()); assertTrue("correct type", msgs.get(0) instanceof BalancingControlEvent); BalancingControlEvent bce = (BalancingControlEvent) msgs.get(0); assertEquals("correct broker", broker, bce.getBroker()); assertEquals("correct tariff", spec.getId(), bce.getTariffId()); assertEquals("correct amount", 100.0, bce.getKwh(), 1e-6); assertEquals("correct payment", 11.0, bce.getPayment(), 1e-6); assertEquals("correct timeslot", 0, bce.getTimeslotIndex()); // Check regulation assertEquals("correct regulation sub1", 40.0 / 100.0, sub1.getRegulation(), 1e-6); assertEquals("correct regulation sub2", 60.0 / 200.0, sub2.getRegulation(), 1e-6); // check tariff transactions assertEquals("correct # of calls", 2, answers.size()); Object[] args = answers.get(customer1); assertNotNull("customer1 included", args); assertEquals("correct arg count", 6, args.length); assertEquals("correct type", TariffTransaction.Type.PRODUCE, (TariffTransaction.Type) args[0]); assertEquals("correct tariff", tariff, (Tariff) args[1]); assertEquals("correct kwh", 40.0, (Double) args[4], 1e-6); assertEquals("correct charge", -4.4, (Double) args[5], 1e-6); args = answers.get(customer2); assertNotNull("customer2 included", args); assertEquals("correct arg count", 6, args.length); assertEquals("correct type", TariffTransaction.Type.PRODUCE, (TariffTransaction.Type) args[0]); assertEquals("correct tariff", tariff, (Tariff) args[1]); assertEquals("correct kwh", 60.0, (Double) args[4], 1e-6); assertEquals("correct charge", -6.6, (Double) args[5], 1e-6); }
From source file:com.globalsight.machineTranslation.domt.DoMTProxy.java
/** * Send segments with tags to DOMT engine. *///from www .j ava 2 s .c om private String[] translateWithTags(Locale sourceLocale, Locale targetLocale, String[] segments) { String[] results = new String[segments.length]; boolean isXlf = MTHelper.isXlf(this.getMtParameterMap()); try { // Ensure the sequence will be unchanged after translation. HashMap<Integer, String> id2Segs = new HashMap<Integer, String>(); String[] heads = new String[segments.length]; for (int i = 0; i < segments.length; i++) { int index = segments[i].indexOf(">"); heads[i] = segments[i].substring(0, index + 1); boolean hasInternalText = (segments[i].indexOf(" internal=\"yes\"") > -1); GxmlElement gxmlRoot = MTHelper.getGxmlElement(segments[i]); List subFlowList = gxmlRoot.getDescendantElements(GxmlElement.SUB_TYPE); if ((subFlowList == null || subFlowList.size() == 0) && !hasInternalText) { String segmentWithId = segments[i]; if (!isXlf) { segmentWithId = segmentWithId.replace(" i=", " id="); } id2Segs.put(composeKey(i, 0), GxmlUtil.stripRootTag(segmentWithId)); } else { // If segment gxml HAS subs, send texts to MT then compose // back again. List items = MTHelper.getImmediateAndSubImmediateTextNodes(gxmlRoot); for (int subIndex = 0; subIndex < items.size(); subIndex++) { TextNode textNode = (TextNode) items.get(subIndex); id2Segs.put(composeKey(i, subIndex + 1), textNode.toGxml()); } } } if (id2Segs.size() > 0) { String srcXlf = getDoMtXliff(id2Segs, sourceLocale, targetLocale); if (MTHelper.isLogDetailedInfo(ENGINE_DOMT)) { logger.info("Segments in XLF sending to DoMT:" + srcXlf); } String translatedXlf = hitDoMt(sourceLocale, targetLocale, srcXlf); if (MTHelper.isLogDetailedInfo(ENGINE_DOMT)) { logger.info("Segments in XLF returned from DoMT:" + translatedXlf); } if (!isXlf && StringUtil.isNotEmpty(translatedXlf)) { translatedXlf = translatedXlf.replace(" id=", " i=").replace("trans-unit i=", "trans-unit id="); } // id :: translated targets HashMap<Integer, String> targets = extractDoMtReturning(translatedXlf); HashMap<Integer, HashMap<Integer, String>> targetGroups = getTargetGroups(targets); String translatedSegment = ""; for (int mainIndex = 0; mainIndex < segments.length; mainIndex++) { translatedSegment = ""; HashMap<Integer, String> subSet = targetGroups.get(mainIndex); if (subSet == null) { results[mainIndex] = heads[mainIndex] + "" + "</segment>"; continue; } boolean hasInternalText = (segments[mainIndex].indexOf(" internal=\"yes\"") > -1); GxmlElement gxmlRoot = MTHelper.getGxmlElement(segments[mainIndex]); List subFlowList = gxmlRoot.getDescendantElements(GxmlElement.SUB_TYPE); if ((subFlowList == null || subFlowList.size() == 0) && !hasInternalText) { translatedSegment = subSet.get(0); // if DoMT fails to translate this, it returns -1. if (translatedSegment == null || "-1".equals(translatedSegment)) { translatedSegment = ""; } } else { List items = MTHelper.getImmediateAndSubImmediateTextNodes(gxmlRoot); if (items != null && items.size() > 0 && items.size() == subSet.size()) { for (int subIndex = 0; subIndex < items.size(); subIndex++) { TextNode textNode = (TextNode) items.get(subIndex); String trans = subSet.get(subIndex + 1); if (trans == null || "-1".equals(trans)) { trans = ""; } textNode.setTextBuffer(new StringBuffer(trans)); } translatedSegment = GxmlUtil.stripRootTag(gxmlRoot.toGxml()); } } results[mainIndex] = heads[mainIndex] + translatedSegment + "</segment>"; } } } catch (MachineTranslationException e) { logger.error(e.getMessage()); } return results; }
From source file:fragment.web.RegistrationControllerTest.java
@SuppressWarnings("unchecked") @Test//from ww w . j av a2s .co m public void testGetLoginPageUIRelatedConfigs() { HashMap<String, Object> configs = (HashMap<String, Object>) controller.getLoginPageUIRelatedConfigs(); Assert.assertEquals(4, configs.size()); Assert.assertEquals("false", configs.get("isDirectoryServiceAuthenticationON")); Assert.assertEquals("N", configs.get("showSuffix")); Assert.assertEquals("true", configs.get("showSuffixDropBox")); List<String> suffixList = (List<String>) configs.get("suffixList"); Assert.assertEquals(0, suffixList.size()); Configuration configuration = configurationService .locateConfigurationByName(Names.com_citrix_cpbm_portal_directory_service_enabled); configuration.setValue("true"); configurationService.update(configuration); configuration = configurationService.locateConfigurationByName(Names.com_citrix_cpbm_directory_mode); configuration.setValue("pull"); configurationService.update(configuration); configs = (HashMap<String, Object>) controller.getLoginPageUIRelatedConfigs(); Assert.assertEquals(4, configs.size()); Assert.assertEquals("true", configs.get("isDirectoryServiceAuthenticationON")); Assert.assertEquals("N", configs.get("showSuffix")); Assert.assertEquals("true", configs.get("showSuffixDropBox")); suffixList = (List<String>) configs.get("suffixList"); Assert.assertEquals(0, suffixList.size()); configuration = configurationService .locateConfigurationByName(Names.com_citrix_cpbm_username_duplicate_allowed); configuration.setValue("Y"); configurationService.update(configuration); configs = (HashMap<String, Object>) controller.getLoginPageUIRelatedConfigs(); Assert.assertEquals(4, configs.size()); Assert.assertEquals("true", configs.get("isDirectoryServiceAuthenticationON")); Assert.assertEquals("Y", configs.get("showSuffix")); Assert.assertEquals("true", configs.get("showSuffixDropBox")); suffixList = (List<String>) configs.get("suffixList"); Assert.assertEquals(0, suffixList.size()); configuration = configurationService .locateConfigurationByName(Names.com_citrix_cpbm_login_screen_tenant_suffix_dropdown_enabled); configuration.setValue("false"); configurationService.update(configuration); configs = (HashMap<String, Object>) controller.getLoginPageUIRelatedConfigs(); Assert.assertEquals(4, configs.size()); Assert.assertEquals("true", configs.get("isDirectoryServiceAuthenticationON")); Assert.assertEquals("Y", configs.get("showSuffix")); Assert.assertEquals("false", configs.get("showSuffixDropBox")); suffixList = (List<String>) configs.get("suffixList"); Assert.assertEquals(0, suffixList.size()); }
From source file:edu.uci.ics.asterix.transaction.management.service.locking.LockManagerDeterministicUnitTest.java
@Override public void run() { Thread.currentThread().setName("Thread-0"); HashMap<String, Thread> threadMap = new HashMap<String, Thread>(); Thread t = null;// w ww . j a va 2s . co m LockRequest lockRequest = null; boolean isSuccess = true; try { readRequest(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } catch (ACIDException e) { e.printStackTrace(); System.exit(-1); } //initialize workerThread int size = requestList.size(); for (int i = 0; i < size; i++) { lockRequest = requestList.get(i); if (lockRequest.threadName.equals("Thread-0")) { //Thread-0 is controller thread. continue; } t = threadMap.get(lockRequest.threadName); if (t == null) { t = new Thread(new LockRequestWorker(txnProvider, workerReadyQueue, lockRequest.threadName), lockRequest.threadName); threadMap.put(lockRequest.threadName, t); t.start(); log("Created " + lockRequest.threadName); } } //wait for all workerThreads to be ready try { log("waiting for all workerThreads to complete initialization ..."); Thread.sleep(5); } catch (InterruptedException e1) { e1.printStackTrace(); } while (workerReadyQueue.size() != threadMap.size()) { try { log(" ."); Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } //make workerThread work while (requestList.size() != 0) { lockRequest = requestList.remove(0); log("Processing: " + lockRequest.prettyPrint()); try { if (!handleRequest(lockRequest)) { log("\n*** Test Failed ***"); isSuccess = false; break; } else { log("Processed: " + lockRequest.prettyPrint()); } } catch (ACIDException e) { e.printStackTrace(); break; } } if (isSuccess) { log("\n*** Test Passed ***"); } ((LogManager) txnProvider.getLogManager()).stop(false, null); }
From source file:com.bah.applefox.main.plugins.imageindex.ImageAccumuloSampler.java
/** * Overridden method to create the sample *///from w ww .j av a 2s . co m public void createSample() { try { // HashMap to write the sample table to HashMap<String, Integer> output = new HashMap<String, Integer>(); // Scan the data table Scanner scan = AccumuloUtils.connectRead(dataTable); Map<String, String> properties = new HashMap<String, String>(); IteratorSetting cfg2 = new IteratorSetting(11, SamplerCreator.class, properties); scan.addScanIterator(cfg2); for (Entry<Key, Value> entry : scan) { try { // Write the data from the table to the sample table String row = entry.getKey().getRow().toString(); int value = output.containsKey(row) ? output.get(row) : 0; value += 1; output.put(row, value); } catch (Exception e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } } } // get the total number of docs from the urls table Scanner scann = AccumuloUtils.connectRead(urlTable); IteratorSetting cfg3 = new IteratorSetting(11, TotalDocFinder.class, properties); scann.addScanIterator(cfg3); for (Entry<Key, Value> entry : scann) { try { output.put(entry.getKey().getRow().toString(), (Integer) IngestUtils.deserialize(entry.getValue().get())); } catch (Exception e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } } } // Create the sample table file System.out.println(output.size()); System.out.println("sample file: " + sampleFile); File f = new File(sampleFile); f.createNewFile(); // use buffering OutputStream file = new FileOutputStream(f); OutputStream buffer = new BufferedOutputStream(file); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(output); out.flush(); out.close(); } catch (AccumuloException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } } catch (AccumuloSecurityException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } } catch (TableNotFoundException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } } catch (IOException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } } }
From source file:org.powertac.tariffmarket.CapacityControlServiceTest.java
/** * Up-regulation test//from w w w .ja v a 2 s . c om */ @Test public void testExerciseBalancingControlDown() { TariffSpecification specRR1 = new TariffSpecification(broker, PowerType.THERMAL_STORAGE_CONSUMPTION) .addRate(new Rate().withValue(-0.11)) .addRate(new RegulationRate().withUpRegulationPayment(0.15).withDownRegulationPayment(-0.05)); Tariff tariffRR1 = new Tariff(specRR1); tariffRR1.init(); TariffSubscription sub1 = tariffSubscriptionRepo.getSubscription(customer1, tariffRR1); sub1.subscribe(100); sub1.setRegulationCapacity(new RegulationCapacity(sub1, 3.0, -1.5)); sub1.usePower(200); // avail down-regulation is -150 TariffSubscription sub2 = tariffSubscriptionRepo.getSubscription(customer2, tariffRR1); sub2.subscribe(200); sub2.setRegulationCapacity(new RegulationCapacity(sub2, 2.0, -1.1)); sub2.usePower(300); // avail down-regulation is -220 BalancingOrder order = new BalancingOrder(broker, specRR1, -1.0, -0.04); RegulationCapacity cap = capacityControl.getRegulationCapacity(order); assertEquals("correct up-regulation", 700.0, cap.getUpRegulationCapacity(), 1e-6); assertEquals("correct down-regulation", -370.0, cap.getDownRegulationCapacity(), 1e-6); // exercise the control assertEquals("no messages yet", 0, msgs.size()); reset(mockAccounting); final HashMap<CustomerInfo, Object[]> answers = new HashMap<CustomerInfo, Object[]>(); when(mockAccounting.addTariffTransaction(any(TariffTransaction.Type.class), any(Tariff.class), any(CustomerInfo.class), anyInt(), anyDouble(), anyDouble())).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); CustomerInfo customer = (CustomerInfo) args[2]; answers.put(customer, args); return null; } }); capacityControl.exerciseBalancingControl(order, -100.0, -6.0); // check the outgoing message assertEquals("one message", 1, msgs.size()); assertTrue("correct type", msgs.get(0) instanceof BalancingControlEvent); BalancingControlEvent bce = (BalancingControlEvent) msgs.get(0); assertEquals("correct broker", broker, bce.getBroker()); assertEquals("correct tariff", specRR1.getId(), bce.getTariffId()); assertEquals("correct amount", -100.0, bce.getKwh(), 1e-6); assertEquals("correct payment", -6.0, bce.getPayment(), 1e-6); assertEquals("correct timeslot", 0, bce.getTimeslotIndex()); // Check regulation assertEquals("correct regulation sub1", -15000.0 / 370.0 / 100.0, sub1.getRegulation(), 1e-6); assertEquals("correct regulation sub2", -22000.0 / 370.0 / 200.0, sub2.getRegulation(), 1e-6); // check tariff transactions assertEquals("correct # of calls", 2, answers.size()); Object[] args = answers.get(customer1); assertNotNull("customer1 included", args); assertEquals("correct arg count", 6, args.length); assertEquals("correct type", TariffTransaction.Type.CONSUME, (TariffTransaction.Type) args[0]); assertEquals("correct tariff", tariffRR1, (Tariff) args[1]); assertEquals("correct kwh", -15000.0 / 370.0, (Double) args[4], 1e-6); assertEquals("correct charge", 0.05 * 15000.0 / 370.0, (Double) args[5], 1e-6); args = answers.get(customer2); assertNotNull("customer2 included", args); assertEquals("correct arg count", 6, args.length); assertEquals("correct type", TariffTransaction.Type.CONSUME, (TariffTransaction.Type) args[0]); assertEquals("correct tariff", tariffRR1, (Tariff) args[1]); assertEquals("correct kwh", -22000.0 / 370.0, (Double) args[4], 1e-6); assertEquals("correct charge", 0.05 * 22000.0 / 370.0, (Double) args[5], 1e-6); }
From source file:com.acc.android.network.operator.base.BaseHttpOperator.java
private String encodeUrlParam(Object paramObject) throws UnsupportedEncodingException { if (paramObject == null) return HttpConstant.DEFAULTPARAM; StringBuilder sb = new StringBuilder(); if (paramObject instanceof Bundle) { Bundle bundle = (Bundle) paramObject; if (bundle.size() == 0) { return HttpConstant.DEFAULTPARAM; } else {//from w ww . ja v a 2 s .co m boolean isFirst = true; for (String key : bundle.keySet()) { if (isFirst) isFirst = false; else sb.append("&"); // Object object; sb.append(key + "=" + URLEncoder.encode(bundle.getString(key), HttpConstant.ENCODE)); // + paramBundle.getString(key)); } } } else if (paramObject instanceof Map) { HashMap<String, String> map = (HashMap<String, String>) paramObject; if (map.size() == 0) { return HttpConstant.DEFAULTPARAM; } else { boolean isFirst = true; for (Object key : map.keySet()) { if (isFirst) isFirst = false; else sb.append("&"); // Object object; sb.append(key + "=" + URLEncoder.encode(map.get(key).toString(), HttpConstant.ENCODE)); // + paramBundle.getString(key)); } } } else if (paramObject instanceof List && ((List) paramObject).get(0) instanceof NameValuePair) { // if (paramObject instanceof List) { // List list = (List) paramObject; // Object object = list.get(0); // if (object instanceof NameValuePair) { boolean isFirst = true; for (NameValuePair nameValuePair : (List<NameValuePair>) paramObject) { if (isFirst) isFirst = false; else sb.append("&"); // Object object; sb.append(nameValuePair.getName() + "=" + URLEncoder.encode(nameValuePair.getValue(), HttpConstant.ENCODE)); // + paramBundle.getString(key)); } } else { // sb.append("&"); // Object object; sb.append(HttpConstant.DEFAULT_KEY_REQUEST_PARAM + "=" + URLEncoder.encode(this.jsonManager.getJson(paramObject), HttpConstant.ENCODE)); } return sb.toString(); }