List of usage examples for java.util TreeSet remove
public boolean remove(Object o)
From source file:org.cloudata.core.tabletserver.DiskSSTable.java
public ColumnValue findClosestMeta(Row.Key rowKey, String columnName, boolean great) throws IOException { lock.obtainReadLock();// w w w . ja v a 2 s . c o m try { if (columnMemoryCaches.containsKey(columnName)) { ColumnMemoryCache cache = columnMemoryCaches.get(columnName); return cache.findClosest(rowKey); } List<TabletMapFile> tabletMapFiles = mapFiles.get(columnName); if (tabletMapFiles == null || tabletMapFiles.isEmpty()) { return null; } MapFileReader[] readers = new MapFileReader[tabletMapFiles.size()]; TreeSet<MetaValue> metaValues = new TreeSet<MetaValue>(); TreeSet<ColumnValue> workPlace = new TreeSet<ColumnValue>(); try { //init CellFilter cellFilter = new CellFilter(columnName); int index = 0; for (TabletMapFile tabletMapFile : tabletMapFiles) { MapFileReader reader = tabletMapFile.getMapFileReader(rowKey, Row.Key.MAX_KEY, cellFilter); ColumnValue columnValue = null; while ((columnValue = reader.next()) != null) { if (great) { if (columnValue.getRowKey().compareTo(rowKey) < 0) { continue; } } else { if (columnValue.getRowKey().compareTo(rowKey) <= 0) { continue; } } break; } if (columnValue != null) { workPlace.add(columnValue); readers[index] = reader; } else { reader.close(); readers[index] = null; } index++; } //findClosestMeta while (true) { if (workPlace.isEmpty()) { return null; } ColumnValue winnerColumnValue = workPlace.first(); metaValues.add(new MetaValue(winnerColumnValue)); workPlace.remove(winnerColumnValue); Row.Key winnerRowKey = winnerColumnValue.getRowKey(); List<ColumnValue> tempWorkPlace = new ArrayList<ColumnValue>(); tempWorkPlace.addAll(workPlace); for (ColumnValue eachColumnValue : tempWorkPlace) { if (winnerRowKey.equals(eachColumnValue.getRowKey())) { metaValues.add(new MetaValue(eachColumnValue)); workPlace.remove(eachColumnValue); } } for (int i = 0; i < readers.length; i++) { if (readers[i] == null) { continue; } ColumnValue columnValue = null; while ((columnValue = readers[i].next()) != null) { if (winnerRowKey.equals(columnValue.getRowKey())) { metaValues.add(new MetaValue(columnValue)); } else { workPlace.add(columnValue); break; } } if (columnValue == null) { readers[i].close(); readers[i] = null; } } if (metaValues.size() > 0) { MetaValue firstValue = metaValues.first(); if (!firstValue.columnValue.isDeleted()) { return firstValue.columnValue; } else { metaValues.clear(); } } } } finally { for (int i = 0; i < readers.length; i++) { try { if (readers[i] != null) { readers[i].close(); } } catch (Exception e) { LOG.warn("Can't close MapFileReader:" + e.getMessage()); } } } } finally { lock.releaseReadLock(); } }
From source file:net.morimekta.providence.maven.plugin.BaseGenerateSourcesMojo.java
boolean executeInternal(File outputDir, IncludeExcludeFileSelector files, String defaultInputIncludes, boolean testCompile) throws MojoExecutionException, MojoFailureException { Set<File> inputs = ProvidenceInput.getInputFiles(project, files, defaultInputIncludes); if (inputs.isEmpty()) { return false; }/*www . jav a 2s .c om*/ if (!outputDir.exists()) { if (!outputDir.mkdirs()) { throw new MojoExecutionException("Unable to create target directory " + outputDir); } } TreeSet<File> includes = new TreeSet<>(); File workingDir = new File(buildDir, testCompile ? "providence-test" : "providence"); File[] deleteFiles = workingDir.listFiles(); if (!workingDir.exists()) { if (!workingDir.mkdirs()) { throw new MojoExecutionException("Unable to create working directory " + workingDir); } } else if (deleteFiles != null) { StreamSupport.<File>stream( Spliterators.spliterator(deleteFiles, Spliterator.DISTINCT | Spliterator.IMMUTABLE), false) .forEach(File::delete); } Set<Artifact> resolvedArtifacts = new HashSet<>(); for (Dependency dep : dependencies) { dep.setType(ProvidenceAssemblyMojo.TYPE); if (dep.getClassifier() == null || dep.getClassifier().isEmpty()) { dep.setClassifier(ProvidenceAssemblyMojo.CLASSIFIER); } Artifact artifact = repositorySystem.createDependencyArtifact(dep); // Avoid resolving stuff we already have resolved. if (resolvedArtifacts.contains(artifact)) { continue; } ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setLocalRepository(localRepository); request.setRemoteRepositories(remoteRepositories); request.setResolveTransitively(false); request.setArtifact(artifact); ArtifactResolutionResult result = artifactResolver.resolve(request); boolean found = false; for (Artifact resolved : result.getArtifacts()) { if (artifact.equals(resolved)) { resolvedArtifacts.add(resolved); addDependencyInclude(workingDir, includes, resolved); found = true; break; } } if (!found) { throw new MojoFailureException("Unable to resolve providence dependency: " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() + ":" + artifact.getClassifier()); } } if (includeDirs != null) { DirectoryScanner includeScanner = new DirectoryScanner(); includeScanner.setIncludes(includeDirs.getIncludes()); if (includeDirs.getExcludes() != null) { includeScanner.setExcludes(includeDirs.getExcludes()); } includeScanner.setBasedir(project.getBasedir()); includeScanner.scan(); for (String dir : includeScanner.getIncludedDirectories()) { includes.add(new File(project.getBasedir(), dir)); } for (String dir : includeScanner.getExcludedDirectories()) { includes.remove(new File(project.getBasedir(), dir)); } } inputs.stream().map(File::getParentFile).forEach(includes::add); FileManager fileManager = new FileManager(outputDir); DocumentParser parser = new ThriftDocumentParser(); TypeLoader loader = new TypeLoader(includes, parser); LinkedList<CDocument> documents = new LinkedList<>(); for (File in : inputs) { try { documents.add(loader.load(in)); } catch (IOException e) { throw new MojoExecutionException("Failed to read thrift file: " + in.getName(), e); } catch (ParseException e) { getLog().warn(e.getMessage()); getLog().warn(".---------------------."); throw new MojoFailureException("Failed to parse thrift file: " + in.getName(), e); } } try { Generator generator; if (tiny) { TinyOptions options = new TinyOptions(); options.jackson = jackson; if (android) { throw new MojoExecutionException("Android option not compatible with 'tiny_java' variant."); } generator = new TinyGenerator(fileManager, loader.getRegistry(), options); } else { JOptions options = new JOptions(); options.android = android; if (jackson) { throw new MojoExecutionException("Jackson option not compatible with 'java' variant."); } generator = new JGenerator(fileManager, loader.getRegistry(), options); } for (CDocument doc : documents) { try { generator.generate(doc); } catch (IOException e) { throw new MojoExecutionException("Failed to write document: " + doc.getPackageName(), e); } catch (GeneratorException e) { getLog().warn(e.getMessage()); throw new MojoFailureException("Failed to generate document: " + doc.getPackageName(), e); } } } catch (GeneratorException e) { getLog().warn(e.getMessage()); throw new MojoFailureException("Failed to generate file: " + e.getMessage(), e); } return compileOutput; }
From source file:org.prom5.analysis.performance.PerformanceAnalysisGUI.java
/** * Initializes the waiting time levels. If no manual peformance settings are * filled in by the user, standard settings are calculated and used. * Standard settings: approximately 33% low, 33% high, 33% medium level * note that a set is used instead of a list however, so if a time occurs * multiple times (this can happen easily with a waiting time of 0.0s for * instance) of such places only one is used, so the 33-33-33 estimation can * be quite wrong, though this is not considered to be a problem. *///from w ww . j av a2 s. c o m public void initializeWaitingTimeLevels() { if (!manualSettings) { //no manual settings are present TreeSet waitingTimes = new TreeSet(); ListIterator it = extendedPetriNet.getPlaces().listIterator(); while (it.hasNext()) { //place the mean waiting time of each place in the tree set ExtendedPlace p = (ExtendedPlace) it.next(); p.calculateMetrics(extendedLog.getLogTraceIDs(), advancedSettings[1], failedInstances); if (p.getMeanWaitingTime() >= 0) { //only add correct times double waitTime = p.getMeanWaitingTime() / timeDivider; waitingTimes.add(Double.valueOf(waitTime)); } } int num = waitingTimes.size() / 3; //remove the first 'num' measurements and the last 'num' measurements //from waitingTimes for (int i = 0; i < num; i++) { //there should be at least one waiting time measurement remaining if (!(waitingTimes.size() < 2)) { waitingTimes.remove(waitingTimes.first()); waitingTimes.remove(waitingTimes.last()); } } //give new values to the bounds and the colors if (waitingTimes.size() != 0) { Double bnd = (Double) waitingTimes.first(); bounds.set(0, bnd); bnd = (Double) waitingTimes.last(); bounds.set(1, bnd); } else { //in case there are no valid waiting times waitingTimes.add(Double.valueOf(0)); Double bnd = (Double) waitingTimes.first(); bounds.set(0, bnd); bounds.set(1, bnd); } levelColors.set(0, Color.BLUE); levelColors.set(1, Color.YELLOW); levelColors.set(2, Color.MAGENTA); } extendedPetriNet.setAdvancedSettings(advancedSettings); extendedPetriNet.setBounds(bounds); extendedPetriNet.setLevelColors(levelColors); extendedPetriNet.setTimeDivider(timeDivider); extendedPetriNet.setFailedInstances(failedInstances); }
From source file:org.processmining.analysis.performance.PerformanceAnalysisGUI.java
/** * Initializes the waiting time levels. If no manual peformance settings are * filled in by the user, standard settings are calculated and used. * Standard settings: approximately 33% low, 33% high, 33% medium level note * that a set is used instead of a list however, so if a time occurs * multiple times (this can happen easily with a waiting time of 0.0s for * instance) of such places only one is used, so the 33-33-33 estimation can * be quite wrong, though this is not considered to be a problem. *///from w ww . j a v a 2 s . c o m public void initializeWaitingTimeLevels() { if (!manualSettings) { // no manual settings are present TreeSet waitingTimes = new TreeSet(); ListIterator it = extendedPetriNet.getPlaces().listIterator(); while (it.hasNext()) { // place the mean waiting time of each place in the tree set ExtendedPlace p = (ExtendedPlace) it.next(); p.calculateMetrics(extendedLog.getLogTraceIDs(), advancedSettings[1], failedInstances); if (p.getMeanWaitingTime() >= 0) { // only add correct times double waitTime = p.getMeanWaitingTime() / timeDivider; waitingTimes.add(Double.valueOf(waitTime)); } } int num = waitingTimes.size() / 3; // remove the first 'num' measurements and the last 'num' // measurements // from waitingTimes for (int i = 0; i < num; i++) { // there should be at least one waiting time measurement // remaining if (!(waitingTimes.size() < 2)) { waitingTimes.remove(waitingTimes.first()); waitingTimes.remove(waitingTimes.last()); } } // give new values to the bounds and the colors if (waitingTimes.size() != 0) { Double bnd = (Double) waitingTimes.first(); bounds.set(0, bnd); bnd = (Double) waitingTimes.last(); bounds.set(1, bnd); } else { // in case there are no valid waiting times waitingTimes.add(Double.valueOf(0)); Double bnd = (Double) waitingTimes.first(); bounds.set(0, bnd); bounds.set(1, bnd); } levelColors.set(0, Color.BLUE); levelColors.set(1, Color.YELLOW); levelColors.set(2, Color.MAGENTA); } extendedPetriNet.setAdvancedSettings(advancedSettings); extendedPetriNet.setBounds(bounds); extendedPetriNet.setLevelColors(levelColors); extendedPetriNet.setTimeDivider(timeDivider); extendedPetriNet.setFailedInstances(failedInstances); }
From source file:com.hichinaschool.flashcards.anki.DeckPicker.java
private void updateDecksList(TreeSet<Object[]> decks, int eta, int count) { if (decks == null) { Log.e(AnkiDroidApp.TAG, "updateDecksList: empty decks list"); return;/* www . j a va 2s .c o m*/ } ArrayList<String> deckTitles = new ArrayList<String>(); String currentName = null; Object[] defaultDeck = null; for (Object[] d : decks) { currentName = readableDeckName(((String[]) d[0])); if (!currentName.equals("Default")) deckTitles.add(currentName); else defaultDeck = d; } decks.remove(defaultDeck); if (!deckTitles.contains("HSK 1 Vocabulary")) { String[] strings = { "HSK 1 Vocabulary" }; decks.add(new Object[] { strings, Long.valueOf(-10), 0, 0, 0, false, "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+1+Vocabulary.apkg" }); } if (!deckTitles.contains("HSK 2 Vocabulary")) { String[] strings = { "HSK 2 Vocabulary" }; decks.add(new Object[] { strings, Long.valueOf(-20), 0, 0, 0, false, "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+2+Vocabulary.apkg" }); } if (!deckTitles.contains("HSK 3 Vocabulary")) { String[] strings = { "HSK 3 Vocabulary" }; decks.add(new Object[] { strings, Long.valueOf(-30), 0, 0, 0, false, "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+3+Vocabulary.apkg" }); } if (!deckTitles.contains("HSK 4 Vocabulary")) { String[] strings = { "HSK 4 Vocabulary" }; decks.add(new Object[] { strings, Long.valueOf(-40), 0, 0, 0, false, "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+4+Vocabulary.apkg" }); } if (!deckTitles.contains("HSK 5 Vocabulary")) { String[] strings = { "HSK 5 Vocabulary" }; decks.add(new Object[] { strings, Long.valueOf(-50), 0, 0, 0, false, "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+5+Vocabulary.apkg" }); } mDeckList.clear(); int due = 0; for (Object[] d : decks) { HashMap<String, String> m = new HashMap<String, String>(); String[] name = ((String[]) d[0]); m.put("name", readableDeckName(name)); m.put("did", ((Long) d[1]).toString()); m.put("new", ((Integer) d[2]).toString()); m.put("lrn", ((Integer) d[3]).toString()); m.put("rev", ((Integer) d[4]).toString()); m.put("dyn", ((Boolean) d[5]) ? "d1" : "d0"); if (d.length > 6) m.put("url", ((String) d[6].toString())); // m.put("complMat", ((Float)d[5]).toString()); // m.put("complAll", ((Float)d[6]).toString()); if (name.length == 1) { due += Integer.parseInt(m.get("new")) + Integer.parseInt(m.get("lrn")) + Integer.parseInt(m.get("rev")); // top position m.put("sep", "top"); // correct previous deck if (mDeckList.size() > 0) { HashMap<String, String> map = mDeckList.get(mDeckList.size() - 1); if (map.get("sep").equals("top")) { map.put("sep", "ful"); } else { map.put("sep", "bot"); } } } else { // center position m.put("sep", "cen"); } if (mDeckList.size() > 0 && mDeckList.size() == decks.size() - 1) { // bottom position if (name.length == 1) { m.put("sep", "ful"); } else { m.put("sep", "bot"); } } mDeckList.add(m); } mDeckListAdapter.notifyDataSetChanged(); // set title Resources res = getResources(); // if (count != -1) { // String time = "-"; // if (eta != -1) { // time = res.getQuantityString(R.plurals.deckpicker_title_minutes, eta, eta); // } // AnkiDroidApp.getCompat().setSubtitle(this, res.getQuantityString(R.plurals.deckpicker_title, due, due, count, time)); // } setTitle(res.getString(R.string.app_name)); // update widget WidgetStatus.update(this, decks); }
From source file:ch.admin.suis.msghandler.checker.StatusCheckerSessionImpl.java
/** * Looks into the internal DB and selects the IDs of the messages that * have the status SENT or FORWARDED. Then this method checks the receipts directory * of the Sedex adapter to see, for which message there is already a receipt. * The list of the found receipt is then returned. If there are no receipts, this * method returns an empty collection./* w ww.ja va 2s. c om*/ * * @see ch.admin.suis.msghandler.checker.StatusCheckerSession#getMessagesIds() */ @Override public Collection<Receipt> getMessagesIds() throws LogServiceException { ArrayList<Receipt> receipts = new ArrayList<>(); // the internal DB final LogService logService = context.getLogService(); // the Sedex adapter's receipt directory File receiptsDir = new File( context.getClientConfiguration().getSedexAdapterConfiguration().getReceiptDir()); // get the messages that have either FORWARDED or SENT as their status TreeSet<String> sentIds = new TreeSet<>(logService.getSentMessages()); // loop over the files in the receipts directory // check for the files over there DirectoryStream<Path> files = FileUtils.listFiles(receiptsDir, FileFilters.XML_FILTER_PATH); if (files == null) { LOG.error("an I/O error occured while reading the receipts from the Sedex adapter; " + "check the message handler configuration to see whether the specified 'receipts' directory " + "for the Sedex Adapter actually exists"); return Collections.emptyList(); } // ArrayList<String> toBeRemoved = new ArrayList<>(); // for each receipt found for (Path path : files) { try (InputStream reader = Files.newInputStream(path)) { Receipt receipt = Receipt.createFrom(reader); if (!sentIds.contains(receipt.getMessageId())) { continue; } // get the sent date for this receipt (it is not unfortunately in the receipt XML) receipt.setSentDate(ISO8601Utils.format(logService.getSentDate(receipt.getMessageId()))); receipt.setReceiptFile(path.toFile()); receipts.add(receipt);// add it now LOG.info(MessageFormat.format("message ID {0}: receipt found", receipt.getMessageId())); // set to remove the id from the tree toBeRemoved.add(receipt.getMessageId()); } catch (FileNotFoundException e) { LOG.error("cannot find the file " + path.toString() + "; is it already removed?", e); } catch (IOException e) { LOG.error("cannot read the file " + path.toString(), e); } catch (JAXBException e) { LOG.error("cannot parse the file " + path.toString(), e); } catch (LogServiceException e) { closeStream(files); throw e; // In order to keep the current exception flow } } closeStream(files); // remove from the list sentIds.removeAll(toBeRemoved); // now, lets look at what has remained to find out, whether the Sedex adapter has just sent the files // but not received the receipt (look only at forwarded messages that are not "transparent") final File outputDir = new File( context.getClientConfiguration().getSedexAdapterConfiguration().getOutputDir()); for (final String messageId : logService.getMessages(LogStatus.FORWARDED)) { // Skips execution if not all of the conditions below match if (sentIds.contains(messageId) && !logService.isTransparent(messageId) && !new File(outputDir, FileUtils.getDataFilename(messageId)).exists()) { // the envelope that we have created final Message message = getSentMessage(messageId); if (message == null) { // the file is send by the adapter but there is no receipt yet LOG.warn(MessageFormat.format( "message ID {0}: message sent by the Sedex adapter, but there is no envelope in the Sedex sent directory", messageId)); continue; } // For each recipient, we generate a receipt for (String recipientId : message.getRecipientIds()) { receipts.add(generateReceipt(message, recipientId, messageId)); } LOG.info("message has been sent by the Sedex adapter: " + messageId); // remove the id from the tree sentIds.remove(messageId); } } /* TODO sort out the receipts so that we can reliably process the situation where there is more than one receipt pro message*/ return receipts; }
From source file:com.offbynull.voip.kademlia.FindSubcoroutine.java
@Override public List<Node> run(Continuation cnt) throws Exception { Context ctx = (Context) cnt.getContext(); ctx.addOutgoingMessage(subAddress, logAddress, info("Finding {}", findId)); // Set up subcoroutine router Address routerAddress = subAddress.appendSuffix("finderreq" + idGenerator.generate()); SubcoroutineRouter msgRouter = new SubcoroutineRouter(routerAddress, ctx); Controller msgRouterController = msgRouter.getController(); // Get initial set of nodes to query from routing table List<Node> startNodes = router.find(findId, maxResults, false); // do not include stale nodes, we only want to contact alive nodes ctx.addOutgoingMessage(subAddress, logAddress, info("Route table entries closest to {}: {}", findId, startNodes)); // Create sorted set of nodes to contact IdXorMetricComparator idClosenessComparator = new IdXorMetricComparator(findId); TreeSet<Node> contactSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId())); contactSet.addAll(startNodes);/*from w w w . ja va2 s . c o m*/ // Create a sorted set of nodes to retain closest nodes in TreeSet<Node> closestSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId())); // Execute requests Map<Subcoroutine<?>, Node> requestSubcoroutineToNodes = new HashMap<>(); // executing requests Set<Id> queriedSet = new HashSet<>(); // ids that have already been queried while (true) { // If there's room left to query more contacts that are closer to findId, do so... while (msgRouterController.size() < maxConcurrentRequests && !contactSet.isEmpty()) { // Get next farthest away node to contact Node contactNode = contactSet.pollLast(); // Add it to set of set of ids that have already been queried.. if it's already there, it means that it's already been // queried by this find, so skip it... boolean added = queriedSet.add(contactNode.getId()); if (!added) { continue; } // Add it to the set of closest nodes (will be removed if node fails to respond) closestSet.add(contactNode); // If we already have maxResult closer nodes to findId, skip this node if (closestSet.size() > maxResults) { Node removedNode = closestSet.pollLast(); if (removedNode == contactNode) { continue; } } // Initialize query Address destinationAddress = addressTransformer.toAddress(contactNode.getLink()) .appendSuffix(ROUTER_EXT_HANDLER_RELATIVE_ADDRESS); RequestSubcoroutine<FindResponse> reqSubcoroutine = new RequestSubcoroutine.Builder<FindResponse>() .sourceAddress(routerAddress, idGenerator).destinationAddress(destinationAddress) .timerAddress(timerAddress) .request(new FindRequest(advertiseSelf ? baseId : null, findId, maxResults)) .addExpectedResponseType(FindResponse.class).attemptInterval(Duration.ofSeconds(2L)) .maxAttempts(5).throwExceptionIfNoResponse(false).build(); ctx.addOutgoingMessage(subAddress, logAddress, info("Querying node {}", contactNode)); // Add query to router msgRouterController.add(reqSubcoroutine, AddBehaviour.ADD_PRIME_NO_FINISH); requestSubcoroutineToNodes.put(reqSubcoroutine, contactNode); } // If there are no more requests running, it means we're finished if (msgRouterController.size() == 0) { ctx.addOutgoingMessage(subAddress, logAddress, info("Find complete: {}", closestSet)); return new ArrayList<>(closestSet); } // Wait for next messange forward to the router cnt.suspend(); ForwardResult fr = msgRouter.forward(); // If a request completed from the forwarded message if (fr.isForwarded() && fr.isCompleted()) { // calling isCompleted by itself may throw an exception, check isForwarded first // Get response FindResponse findResponse = (FindResponse) fr.getResult(); if (findResponse == null) { // If failure, then mark as stale and remove from closest // DONT BOTHER WITH TRYING TO CALCULATE LOCKING/UNLOCKING LOGIC. THE LOGIC WILL BECOME EXTREMELY CONVOLUTED. THE QUERY // DID 5 REQUEST. IF NO ANSWER WAS GIVEN IN THE ALLOTED TIME, THEN MARK AS STALE! Node contactedNode = requestSubcoroutineToNodes.remove(fr.getSubcoroutine()); try { // not allowed to mark self as stale -- we may want to find self, but if we do and it's not responsive dont try to // mark it as stale if (!contactedNode.getId().equals(baseId)) { router.stale(contactedNode); } } catch (NodeNotFoundException nnfe) { // may have been removed (already marked as stale) / may not be in routing tree // Do nothing } closestSet.remove(contactedNode); } else { // If success, then add returned nodes to contacts Node[] nodes = findResponse.getNodes(); contactSet.addAll(Arrays.asList(nodes)); // If we don't want to find our own ID / query ourselves... remove any reference to our own ID in the contactSet // TODO: optimize this by removing before it's added to contactSet if (ignoreSelf) { contactSet.removeIf(x -> x.getId().equals(baseId)); } } } } }
From source file:org.lockss.subscription.SubscriptionManager.java
/** * Populates the list of weighted repositories, to be used in a round-robin * fashion for the subsequent AU configurations. * /*ww w . ja va 2s . c om*/ * @param repositoryMap * A Map<String, PlatformUtil.DF> with the map of all distinct * repositories available. * @return a List<String> with the list of weighted repositories. */ List<String> populateRepositories(Map<String, PlatformUtil.DF> repositoryMap) { final String DEBUG_HEADER = "populateRepositories(): "; if (log.isDebug2()) log.debug2(DEBUG_HEADER + "repositoryMap.size() = " + repositoryMap.size()); // Initialize the list of available repositories. List<String> repos = new ArrayList<String>(); // Handle an empty repository map. if (repositoryMap.size() < 1) { if (log.isDebug2()) log.debug2(DEBUG_HEADER + "repos = " + repos); return repos; } // Get the available repositories sorted by their available space. TreeSet<Entry<String, PlatformUtil.DF>> sortedRepos = new TreeSet<Entry<String, PlatformUtil.DF>>( DF_BY_AVAIL_COMPARATOR); sortedRepos.addAll(repositoryMap.entrySet()); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "sortedRepos.size() = " + sortedRepos.size()); // Handle the case of a single repository. if (sortedRepos.size() == 1) { repos.add(sortedRepos.first().getKey()); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "Added " + sortedRepos.first().getKey()); if (log.isDebug2()) log.debug2(DEBUG_HEADER + "repos = " + repos); return repos; } // Get the repository available space threshold from the configuration. int repoThreshold = ConfigManager.getCurrentConfig().getInt(PARAM_REPOSITORY_AVAIL_SPACE_THRESHOLD, DEFAULT_REPOSITORY_AVAIL_SPACE_THRESHOLD); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "repoThreshold = " + repoThreshold); // Get the available space of the repository with the least amount of // available space. long minAvail = sortedRepos.first().getValue().getAvail(); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "minAvail = " + minAvail); // Remove repositories that don't have a minimum of space, except the last // one. while (minAvail < repoThreshold) { sortedRepos.remove(sortedRepos.first()); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "sortedRepos.size() = " + sortedRepos.size()); // If there is only one repository left, use it. if (sortedRepos.size() == 1) { repos.add(sortedRepos.first().getKey()); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "Added " + sortedRepos.first().getKey()); if (log.isDebug2()) log.debug2(DEBUG_HEADER + "repos = " + repos); return repos; } // Get the available space of the repository with the least amount of // available space. minAvail = sortedRepos.first().getValue().getAvail(); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "minAvail = " + minAvail); } // Count the remaining repositories. int repoCount = sortedRepos.size(); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "repoCount = " + repoCount); // Initialize the array of repositories and the total available space. long totalAvailable = 0l; int i = 0; Entry<String, PlatformUtil.DF>[] repoArray = new Entry[repoCount]; for (Entry<String, PlatformUtil.DF> df : sortedRepos) { totalAvailable += df.getValue().getAvail(); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "totalAvailable = " + totalAvailable); repoArray[i++] = df; } // For each repository, compute the target fraction and initialize the count // of appearances in the final list. i = 0; double[] repoTargetFraction = new double[repoCount]; int[] repoAppearances = new int[repoCount]; for (Entry<String, PlatformUtil.DF> df : repoArray) { repoTargetFraction[i] = df.getValue().getAvail() / (double) totalAvailable; if (log.isDebug3()) log.debug3(DEBUG_HEADER + "i = " + i + ", repoTargetFraction[i] = " + repoTargetFraction[i]); repoAppearances[i++] = 0; } // The first repository in the list is the one with the largest amount of // available space. repos.add(repoArray[repoCount - 1].getKey()); repoAppearances[repoCount - 1]++; // An indication of whether the created list matches the target fractions of // all the repositories. boolean done = false; while (!done) { // If no differences between the target fractions and the fractions of // appearances are found in the process below, the list is complete. done = true; double difference = 0; double maxDifference = 0; int nextRepo = -1; // Loop through all the repositories. for (int j = 0; j < repoCount; j++) { if (log.isDebug3()) log.debug3(DEBUG_HEADER + "j = " + j + ", repoAppearances[j]/(double)repos.size() = " + repoAppearances[j] / (double) repos.size() + ", repoTargetFraction[j] = " + repoTargetFraction[j]); // Find the difference between the target fraction and the fraction of // appearances. difference = repoTargetFraction[j] - repoAppearances[j] / (double) repos.size(); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "difference = " + difference); // Update the largest difference, if necessary. if (maxDifference < difference) { maxDifference = difference; nextRepo = j; } } // Check whether a repository with the largest difference was found. if (nextRepo != -1) { // Yes: Add it to the list. repos.add(repoArray[nextRepo].getKey()); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "Added " + repoArray[nextRepo].getKey()); // Increment its appearance count. repoAppearances[nextRepo]++; // Check whether not all the target fractions have been achieved. for (int k = 0; k < repoCount; k++) { difference = repoAppearances[k] / (double) repos.size() - repoTargetFraction[k]; if (log.isDebug3()) log.debug3(DEBUG_HEADER + "k = " + k + ", difference = " + difference); // Within one per cent is a match. if (Math.abs(difference) > 0.01) { done = false; break; } } } } if (log.isDebug2()) log.debug2(DEBUG_HEADER + "repos = " + repos); return repos; }
From source file:org.ofbiz.order.order.OrderServices.java
public static Map<String, Object> createAlsoBoughtProductAssocsForOrder(DispatchContext dctx, Map<String, ? extends Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); String orderId = (String) context.get("orderId"); OrderReadHelper orh = new OrderReadHelper(delegator, orderId); List<GenericValue> orderItems = orh.getOrderItems(); // In order to improve efficiency a little bit, we will always create the ProductAssoc records // with productId < productIdTo when the two are compared. This way when checking for an existing // record we don't have to check both possible combinations of productIds TreeSet<String> productIdSet = new TreeSet<String>(); if (orderItems != null) { for (GenericValue orderItem : orderItems) { String productId = orderItem.getString("productId"); if (productId != null) { GenericValue parentProduct = ProductWorker.getParentProduct(productId, delegator); if (parentProduct != null) productId = parentProduct.getString("productId"); productIdSet.add(productId); }/* w ww. j a va2 s. c o m*/ } } TreeSet<String> productIdToSet = new TreeSet<String>(productIdSet); for (String productId : productIdSet) { productIdToSet.remove(productId); for (String productIdTo : productIdToSet) { EntityCondition cond = EntityCondition .makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productId", productId), EntityCondition.makeCondition("productIdTo", productIdTo), EntityCondition.makeCondition("productAssocTypeId", "ALSO_BOUGHT"), EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()), EntityCondition.makeCondition("thruDate", null))); GenericValue existingProductAssoc = null; try { // No point in using the cache because of the filterByDateExpr existingProductAssoc = EntityUtil.getFirst(delegator.findList("ProductAssoc", cond, null, UtilMisc.toList("fromDate DESC"), null, false)); } catch (GenericEntityException e) { Debug.logError(e, module); } try { if (existingProductAssoc != null) { BigDecimal newQuantity = existingProductAssoc.getBigDecimal("quantity"); if (newQuantity == null || newQuantity.compareTo(BigDecimal.ZERO) < 0) { newQuantity = BigDecimal.ZERO; } newQuantity = newQuantity.add(BigDecimal.ONE); ModelService updateProductAssoc = dctx.getModelService("updateProductAssoc"); Map<String, Object> updateCtx = updateProductAssoc.makeValid(context, ModelService.IN_PARAM, true, null); updateCtx.putAll(updateProductAssoc.makeValid(existingProductAssoc, ModelService.IN_PARAM)); updateCtx.put("quantity", newQuantity); dispatcher.runSync("updateProductAssoc", updateCtx); } else { Map<String, Object> createCtx = FastMap.newInstance(); createCtx.put("userLogin", context.get("userLogin")); createCtx.put("productId", productId); createCtx.put("productIdTo", productIdTo); createCtx.put("productAssocTypeId", "ALSO_BOUGHT"); createCtx.put("fromDate", UtilDateTime.nowTimestamp()); createCtx.put("quantity", BigDecimal.ONE); dispatcher.runSync("createProductAssoc", createCtx); } } catch (GenericServiceException e) { Debug.logError(e, module); } } } return ServiceUtil.returnSuccess(); }