List of usage examples for java.util Set removeAll
boolean removeAll(Collection<?> c);
From source file:com.smartmarmot.dbforbix.config.Config.java
/** * compares config file hashes: previous and actual * @return true or false//from w w w . j a v a 2 s.co m */ public boolean checkConfigChanges() { Config newconfig = new Config(); Config oldconfig = this; newconfig.setBasedir(oldconfig.getBasedir()); newconfig.setConfigFile(oldconfig.getConfigFile()); try { newconfig.readFileConfig(); } catch (IOException e) { LOG.error("Error in config: " + e.getLocalizedMessage()); return false; } catch (NullPointerException e) { LOG.error("Failed to calculate hash for config file: " + e.getLocalizedMessage()); return false; } boolean configFileChanged = (0 == newconfig.getFileConfigHash().compareTo(oldconfig.getFileConfigHash())) ? false : true; LOG.debug("Is config changed: " + configFileChanged); if (configFileChanged) return true; /** * Update configuration from Zabbix Servers */ newconfig.getZabbixConfigurationItems(); Set<String> configurationUIDs = oldconfig.getSetOfConfigurationUIDs(); Set<String> newConfigurationUIDs = newconfig.getSetOfConfigurationUIDs(); /** * candidates for update: * i.e. zbxServerHost:zbxServerPort, proxy, host, db, item key * are the same */ Set<String> toUpdate = new HashSet<>(configurationUIDs); toUpdate.retainAll(newConfigurationUIDs); Set<String> toRemoveFromUpdate = new HashSet<>(); for (String configurationUID : toUpdate) { ZabbixServer zabbixServer = oldconfig.getZabbixServerByConfigurationUID(configurationUID); ZabbixServer newZabbixServer = newconfig.getZabbixServerByConfigurationUID(configurationUID); IConfigurationItem configurationItem = zabbixServer .getConfigurationItemByConfigurationUID(configurationUID); IConfigurationItem newConfigurationItem = newZabbixServer .getConfigurationItemByConfigurationUID(configurationUID); String hashParam = configurationItem.getHashParam(); String newHashParam = newConfigurationItem.getHashParam(); if (hashParam.equals(newHashParam)) toRemoveFromUpdate.add(configurationUID); } toUpdate.removeAll(toRemoveFromUpdate); Set<String> toDelete = new HashSet<String>(configurationUIDs); toDelete.removeAll(newConfigurationUIDs); Set<String> toAdd = new HashSet<String>(newConfigurationUIDs); toAdd.removeAll(configurationUIDs); if (!toUpdate.isEmpty() || !toAdd.isEmpty() || !toDelete.isEmpty()) { /** * stop schedulers that are to be deleted and updated */ stopSchedulers(toDelete); stopSchedulers(toUpdate); /** * Build new Items */ newconfig.buildConfigurationElementsAndSchedulers(); /** * delete items configs */ deleteItemConfigs(toDelete); /** * add item configs */ addConfigurationItems(newconfig, toAdd); /** * update item configs */ updateItemConfigs(newconfig, toUpdate); /** * Open new connections to new DBs and Launch schedulers */ startChecks(); } return false; }
From source file:edu.uci.ics.hyracks.algebricks.rewriter.rules.RemoveUnusedAssignAndAggregateRule.java
private void collectUnusedAssignedVars(AbstractLogicalOperator op, Set<LogicalVariable> toRemove, boolean first, IOptimizationContext context) throws AlgebricksException { if (!first) { context.addToDontApplySet(this, op); }/*from w w w .j a v a 2 s.c o m*/ for (Mutable<ILogicalOperator> c : op.getInputs()) { collectUnusedAssignedVars((AbstractLogicalOperator) c.getValue(), toRemove, false, context); } if (op.hasNestedPlans()) { AbstractOperatorWithNestedPlans opWithNested = (AbstractOperatorWithNestedPlans) op; for (ILogicalPlan plan : opWithNested.getNestedPlans()) { for (Mutable<ILogicalOperator> r : plan.getRoots()) { collectUnusedAssignedVars((AbstractLogicalOperator) r.getValue(), toRemove, false, context); } } } boolean removeUsedVars = true; switch (op.getOperatorTag()) { case ASSIGN: { AssignOperator assign = (AssignOperator) op; toRemove.addAll(assign.getVariables()); break; } case AGGREGATE: { AggregateOperator agg = (AggregateOperator) op; toRemove.addAll(agg.getVariables()); break; } case UNNEST: { UnnestOperator uOp = (UnnestOperator) op; LogicalVariable pVar = uOp.getPositionalVariable(); if (pVar != null) { toRemove.add(pVar); } break; } case UNIONALL: { UnionAllOperator unionOp = (UnionAllOperator) op; for (Triple<LogicalVariable, LogicalVariable, LogicalVariable> varMapping : unionOp .getVariableMappings()) { toRemove.add(varMapping.third); } removeUsedVars = false; break; } } if (removeUsedVars) { List<LogicalVariable> used = new LinkedList<LogicalVariable>(); VariableUtilities.getUsedVariables(op, used); toRemove.removeAll(used); } }
From source file:de.acosix.alfresco.mtsupport.repo.sync.TenantAwareChainingUserRegistrySynchronizer.java
protected Pair<Integer, Integer> processAuthorityDeletions(final String id, final String batchId, final UserRegistry userRegistry, final boolean isFullSync, final boolean splitTxns) { final String zoneId = asZoneId(id); final Set<String> groupsToDelete = new HashSet<>(); final Set<String> usersToDelete = new HashSet<>(); final Pair<Integer, Integer> counts = new Pair<>(Integer.valueOf(0), Integer.valueOf(0)); if (isFullSync) { final Set<String> allZoneGroups = new TreeSet<>(); final Set<String> allZoneUsers = this.personService.getUserNamesAreCaseSensitive() ? new TreeSet<>() : new TreeSet<>(String.CASE_INSENSITIVE_ORDER); this.inReadOnlyTransaction(() -> { allZoneGroups.addAll(this.authorityService.getAllAuthoritiesInZone(zoneId, AuthorityType.GROUP)); allZoneUsers.addAll(this.authorityService.getAllAuthoritiesInZone(zoneId, AuthorityType.USER)); return null; }, splitTxns);/* w w w . j a v a 2 s. c om*/ groupsToDelete.addAll(allZoneGroups); groupsToDelete.removeAll(userRegistry.getGroupNames()); usersToDelete.addAll(allZoneUsers); final String currentDomain = TenantUtil.getCurrentDomain(); for (final String userName : userRegistry.getPersonNames()) { final String domainUser; final String primaryDomain = this.tenantService.getPrimaryDomain(userName); if (!EqualsHelper.nullSafeEquals(primaryDomain, currentDomain)) { domainUser = this.tenantService.getDomainUser(userName, currentDomain); } else { domainUser = userName; } usersToDelete.remove(domainUser); } final Set<String> authoritiesToDelete = new TreeSet<>(); authoritiesToDelete.addAll(groupsToDelete); authoritiesToDelete.addAll(usersToDelete); if (!authoritiesToDelete.isEmpty() && (this.allowDeletions || this.syncDelete)) { @SuppressWarnings("deprecation") final BatchProcessor<String> deletionProcessor = new BatchProcessor<>( SyncProcess.AUTHORITY_DELETION.getTitle(batchId), this.transactionService.getRetryingTransactionHelper(), authoritiesToDelete, this.workerThreads, USER_REGISTRY_ENTITY_BATCH_SIZE, this.applicationEventPublisher, LogFactory.getLog(TenantAwareChainingUserRegistrySynchronizer.class), this.loggingInterval); final AuthorityDeleter deleter = new AuthorityDeleter(zoneId, groupsToDelete, usersToDelete, this.allowDeletions, this.createComponentLookupCallback()); deletionProcessor.process(deleter, splitTxns); counts.setFirst(Integer.valueOf(usersToDelete.size())); counts.setSecond(Integer.valueOf(groupsToDelete.size())); } } return counts; }
From source file:de.uni_potsdam.hpi.asg.logictool.mapping.SequenceBasedAndGateDecomposer.java
private void removeSubSequences(SortedSet<IOBehaviour> sequencesFront, SortedSet<IOBehaviour> sequencesBack, Set<IOBehaviour> newSequences, Set<IOBehaviour> rmSequences) { rmSequences.clear();//w w w . j a v a 2 s. co m sequencesFront.addAll(newSequences); Iterator<IOBehaviour> it = sequencesFront.iterator(); if (!it.hasNext()) { //TODO: why? return; } IOBehaviour curr = it.next(); while (it.hasNext()) { IOBehaviour next = it.next(); if (newSequences.contains(curr)) { if (curr.getStart().compareTo(next.getStart()) == 0) { int i = 0; while (true) { if (curr.getSequence().size() == i) { rmSequences.add(curr); break; } //System.out.println(curr.toString() + " vs " + next.toString()); int cmpT = curr.getSequence().get(i).compareTo(next.getSequence().get(i)); if (cmpT != 0) { break; } //gleich, check next trans i++; } } } curr = next; } newSequences.removeAll(rmSequences); sequencesBack.addAll(newSequences); it = sequencesBack.iterator(); curr = it.next(); while (it.hasNext()) { IOBehaviour next = it.next(); if (newSequences.contains(curr)) { if (curr.getEnd().compareTo(next.getEnd()) == 0) { int i = 0; while (true) { if (curr.getSequence().size() == i) { rmSequences.add(curr); break; } int cmpT = curr.getSequence().get(curr.getSequence().size() - i - 1) .compareTo(next.getSequence().get(next.getSequence().size() - i - 1)); if (cmpT != 0) { break; } //gleich, check next trans i++; } } } curr = next; } }
From source file:net.dv8tion.jda.core.managers.GuildController.java
/** * Modifies the {@link net.dv8tion.jda.core.entities.Role Roles} of the specified {@link net.dv8tion.jda.core.entities.Member Member} * by adding and removing a collection of roles. * <br>None of the provided roles may be the <u>Public Role</u> of the current Guild. * <br>If a role is both in {@code rolesToAdd} and {@code rolesToRemove} it will be removed. * * <p>None of the provided collections may be null * <br>To only add or remove roles use either {@link #removeRolesFromMember(Member, Collection)} or {@link #addRolesToMember(Member, Collection)} * * <h1>Warning</h1>/*www . jav a2 s . c om*/ * <b>This may <u>not</u> be used together with any other role add/remove/modify methods for the same Member * within one event listener cycle! The changes made by this require cache updates which are triggered by * lifecycle events which are received later. This may only be called again once the specific Member has been updated * by a {@link net.dv8tion.jda.core.events.guild.member.GenericGuildMemberEvent GenericGuildMemberEvent} targeting the same Member.</b> * * <p>Possible {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} caused by * the returned {@link net.dv8tion.jda.core.requests.RestAction RestAction} include the following: * <ul> * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS} * <br>The Members Roles could not be modified due to a permission discrepancy</li> * * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS} * <br>We were removed from the Guild before finishing the task</li> * * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_MEMBER UNKNOWN_MEMBER} * <br>The target Member was removed from the Guild before finishing the task</li> * </ul> * * @param member * The {@link net.dv8tion.jda.core.entities.Member Member} that should be modified * @param rolesToAdd * A {@link java.util.Collection Collection} of {@link net.dv8tion.jda.core.entities.Role Roles} * to add to the current Roles the specified {@link net.dv8tion.jda.core.entities.Member Member} already has * @param rolesToRemove * A {@link java.util.Collection Collection} of {@link net.dv8tion.jda.core.entities.Role Roles} * to remove from the current Roles the specified {@link net.dv8tion.jda.core.entities.Member Member} already has * * @throws net.dv8tion.jda.core.exceptions.GuildUnavailableException * If the guild is temporarily not {@link net.dv8tion.jda.core.entities.Guild#isAvailable() available} * @throws net.dv8tion.jda.core.exceptions.PermissionException * If the provided roles are higher in the Guild's hierarchy * and thus cannot be modified by the currently logged in account * @throws IllegalArgumentException * <ul> * <li>If any of the provided arguments is {@code null}</li> * <li>If any of the specified Roles is managed or is the {@code Public Role} of the Guild</li> * </ul> * * @return {@link net.dv8tion.jda.core.requests.restaction.AuditableRestAction AuditableRestAction} */ @CheckReturnValue public AuditableRestAction<Void> modifyMemberRoles(Member member, Collection<Role> rolesToAdd, Collection<Role> rolesToRemove) { checkAvailable(); Checks.notNull(member, "member"); Checks.notNull(rolesToAdd, "Collection containing roles to be added to the member"); Checks.notNull(rolesToRemove, "Collection containing roles to be removed from the member"); checkGuild(member.getGuild(), "member"); checkPermission(Permission.MANAGE_ROLES); rolesToAdd.forEach(role -> { Checks.notNull(role, "role in rolesToAdd"); checkGuild(role.getGuild(), "role: " + role.toString()); checkPosition(role); if (role.isManaged()) throw new IllegalArgumentException( "Cannot add a Managed role to a Member. Role: " + role.toString()); }); rolesToRemove.forEach(role -> { Checks.notNull(role, "role in rolesToRemove"); checkGuild(role.getGuild(), "role: " + role.toString()); checkPosition(role); if (role.isManaged()) throw new IllegalArgumentException( "Cannot remove a Managed role from a Member. Role: " + role.toString()); }); Set<Role> currentRoles = new HashSet<>(((MemberImpl) member).getRoleSet()); currentRoles.addAll(rolesToAdd); currentRoles.removeAll(rolesToRemove); if (currentRoles.contains(guild.getPublicRole())) throw new IllegalArgumentException( "Cannot add the PublicRole of a Guild to a Member. All members have this role by default!"); JSONObject body = new JSONObject().put("roles", currentRoles.stream().map(Role::getId).collect(Collectors.toList())); Route.CompiledRoute route = Route.Guilds.MODIFY_MEMBER.compile(guild.getId(), member.getUser().getId()); return new AuditableRestAction<Void>(guild.getJDA(), route, body) { @Override protected void handleResponse(Response response, Request<Void> request) { if (response.isOk()) request.onSuccess(null); else request.onFailure(response); } }; }
From source file:com.cyberway.issue.crawler.framework.CrawlController.java
protected void processBdbLogs(final File checkpointDir, final String lastBdbCheckpointLog) throws IOException { File bdbDir = CheckpointUtils.getBdbSubDirectory(checkpointDir); if (!bdbDir.exists()) { bdbDir.mkdir();// w w w . j a v a 2s .com } PrintWriter pw = new PrintWriter(new FileOutputStream(new File(checkpointDir, "bdbje-logs-manifest.txt"))); try { // Don't copy any beyond the last bdb log file (bdbje can keep // writing logs after checkpoint). boolean pastLastLogFile = false; Set<String> srcFilenames = null; final boolean copyFiles = getCheckpointCopyBdbjeLogs(); do { FilenameFilter filter = CheckpointUtils.getJeLogsFilter(); srcFilenames = new HashSet<String>(Arrays.asList(getStateDisk().list(filter))); List tgtFilenames = Arrays.asList(bdbDir.list(filter)); if (tgtFilenames != null && tgtFilenames.size() > 0) { srcFilenames.removeAll(tgtFilenames); } if (srcFilenames.size() > 0) { // Sort files. srcFilenames = new TreeSet<String>(srcFilenames); int count = 0; for (final Iterator i = srcFilenames.iterator(); i.hasNext() && !pastLastLogFile;) { String name = (String) i.next(); if (copyFiles) { FileUtils.copyFiles(new File(getStateDisk(), name), new File(bdbDir, name)); } pw.println(name); if (name.equals(lastBdbCheckpointLog)) { // We're done. pastLastLogFile = true; } count++; } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copied " + count); } } } while (!pastLastLogFile && srcFilenames != null && srcFilenames.size() > 0); } finally { pw.close(); } }
From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.EclipsePlugin.java
public final EclipseSourceDir[] buildDirectoryList(MavenProject project, File basedir, File buildOutputDirectory) throws MojoExecutionException { File projectBaseDir = project.getFile().getParentFile(); String mainOutput = IdeUtils.toRelativeAndFixSeparator(projectBaseDir, buildOutputDirectory, false); // If using the standard output location, don't mix the test output into it. String testOutput = null;/* w w w. ja va 2 s.c o m*/ boolean useStandardOutputDir = buildOutputDirectory .equals(new File(project.getBuild().getOutputDirectory())); if (useStandardOutputDir) { getLog().debug("testOutput toRelativeAndFixSeparator " + projectBaseDir + " , " + project.getBuild().getTestOutputDirectory()); testOutput = IdeUtils.toRelativeAndFixSeparator(projectBaseDir, new File(project.getBuild().getTestOutputDirectory()), false); getLog().debug("testOutput after toRelative : " + testOutput); } Set mainDirectories = new LinkedHashSet(); extractSourceDirs(mainDirectories, project.getCompileSourceRoots(), basedir, projectBaseDir, false, null); extractResourceDirs(mainDirectories, project.getBuild().getResources(), basedir, projectBaseDir, false, mainOutput); Set testDirectories = new LinkedHashSet(); extractSourceDirs(testDirectories, project.getTestCompileSourceRoots(), basedir, projectBaseDir, true, testOutput); extractResourceDirs(testDirectories, project.getBuild().getTestResources(), basedir, projectBaseDir, true, testOutput); // avoid duplicated entries Set directories = new LinkedHashSet(); // NOTE: Since MNG-3118, test classes come before main classes boolean testBeforeMain = isMavenVersion("[2.0.8,)"); // let users override this if needed, they need to simulate more than the test phase in eclipse if (testSourcesLast) { testBeforeMain = false; } if (testBeforeMain) { directories.addAll(testDirectories); directories.removeAll(mainDirectories); directories.addAll(mainDirectories); } else { directories.addAll(mainDirectories); directories.addAll(testDirectories); } if (ajdt) { extractAspectDirs(directories, project, basedir, projectBaseDir, testOutput); } return (EclipseSourceDir[]) directories.toArray(new EclipseSourceDir[directories.size()]); }
From source file:com.joliciel.jochre.graphics.ShapeImpl.java
@Override public Collection<BridgeCandidate> getBridgeCandidates(double maxBridgeWidth) { if (this.bridgeCandidates == null) { TreeSet<VerticalLineSegment> lines = this.getVerticalLineSegments(); // Now, detect "bridges" which could indicate that the shape should be split // First, detect which spaces are "enclosed" and which touch the outer walls // To do this, build up a set of all inverse (white) lines TreeSet<VerticalLineSegment> inverseLines = new TreeSet<VerticalLineSegment>(); int currentX = -1; VerticalLineSegment previousLine = null; for (VerticalLineSegment line : lines) { //LOG.debug("Checking line x = " + line.x + ", top = " + line.yTop + ", bottom = " + line.yBottom); if (line.x != currentX) { // new x-coordinate if (previousLine != null && previousLine.yBottom < this.getHeight() - 1) { VerticalLineSegment inverseLine = new VerticalLineSegment(previousLine.x, previousLine.yBottom + 1); inverseLine.yBottom = this.getHeight() - 1; inverseLines.add(inverseLine); //LOG.debug("Adding inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); }//from w w w. jav a2s .c o m if (line.yTop > 0) { VerticalLineSegment inverseLine = new VerticalLineSegment(line.x, line.yTop - 1); inverseLine.yTop = 0; inverseLines.add(inverseLine); //LOG.debug("Adding inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); } currentX = line.x; } else if (previousLine != null) { VerticalLineSegment inverseLine = new VerticalLineSegment(previousLine.x, previousLine.yBottom + 1); inverseLine.yBottom = line.yTop - 1; inverseLines.add(inverseLine); //LOG.debug("Adding inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); } previousLine = line; } if (previousLine != null && previousLine.yBottom < this.getHeight() - 1) { VerticalLineSegment inverseLine = new VerticalLineSegment(previousLine.x, previousLine.yBottom + 1); inverseLine.yBottom = this.getHeight() - 1; inverseLines.add(inverseLine); //LOG.debug("Adding inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); } LOG.debug("inverseLines size: " + inverseLines.size()); // Calculate neighbours for inverse lines for (VerticalLineSegment inverseLine : inverseLines) { for (VerticalLineSegment otherLine : inverseLines) { if (otherLine.x == inverseLine.x + 1) { if (inverseLine.yTop - 1 <= otherLine.yBottom && otherLine.yTop <= inverseLine.yBottom + 1) { inverseLine.rightSegments.add(otherLine); otherLine.leftSegments.add(inverseLine); } } if (otherLine.x == inverseLine.x - 1) { if (inverseLine.yTop - 1 <= otherLine.yBottom && otherLine.yTop <= inverseLine.yBottom + 1) { inverseLine.leftSegments.add(otherLine); otherLine.rightSegments.add(inverseLine); } } } } // Eliminate any white lines which somehow touch an edge Stack<VerticalLineSegment> lineStack = new Stack<VerticalLineSegment>(); Set<VerticalLineSegment> outerInverseLines = new HashSet<VerticalLineSegment>(); for (VerticalLineSegment inverseLine : inverseLines) { if (inverseLine.yTop == 0 || inverseLine.x == 0 || inverseLine.yBottom == this.getHeight() - 1 || inverseLine.x == this.getWidth() - 1) lineStack.push(inverseLine); } while (!lineStack.isEmpty()) { VerticalLineSegment inverseLine = lineStack.pop(); if (!inverseLine.touched) { inverseLine.touched = true; outerInverseLines.add(inverseLine); //LOG.debug("Outer inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); for (VerticalLineSegment rightLine : inverseLine.rightSegments) lineStack.push(rightLine); for (VerticalLineSegment leftLine : inverseLine.leftSegments) { lineStack.push(leftLine); } } } LOG.debug("outerInverseLines size: " + outerInverseLines.size()); Set<VerticalLineSegment> enclosedInverseLines = new HashSet<VerticalLineSegment>(inverseLines); enclosedInverseLines.removeAll(outerInverseLines); LOG.debug("enclosedInverseLines.size: " + enclosedInverseLines.size()); if (LOG.isDebugEnabled()) { for (VerticalLineSegment inverseLine : enclosedInverseLines) LOG.debug("Enclosed inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); } // Add bridge candidates // based on maximum line length and having exactly one neighbour on each side LOG.debug("Adding bridge candidates"); List<BridgeCandidate> candidateList = new ArrayList<BridgeCandidate>(); for (VerticalLineSegment line : lines) { if (line.rightSegments.size() == 1 && line.leftSegments.size() == 1 && line.length() <= maxBridgeWidth) { // also the bridge width should be considered where two vertical lines touch each other // rather than for the full length of the line BridgeCandidate candidate = null; VerticalLineSegment rightLine = line.rightSegments.iterator().next(); VerticalLineSegment leftLine = line.leftSegments.iterator().next(); int leftTopTouch = (leftLine.yTop > line.yTop ? leftLine.yTop : line.yTop); int leftBottomTouch = (leftLine.yBottom < line.yBottom ? leftLine.yBottom : line.yBottom); int rightTopTouch = (rightLine.yTop > line.yTop ? rightLine.yTop : line.yTop); int rightBottomTouch = (rightLine.yBottom < line.yBottom ? rightLine.yBottom : line.yBottom); int rightLength = rightTopTouch - rightBottomTouch; int leftLength = leftTopTouch - leftBottomTouch; if (line.length() <= maxBridgeWidth || rightLength <= maxBridgeWidth || leftLength <= maxBridgeWidth) { candidate = new BridgeCandidate(this, line); if (rightLength < leftLength && rightLength < line.length()) { candidate.topTouch = rightTopTouch; candidate.bottomTouch = rightBottomTouch; } else if (leftLength < line.length()) { candidate.topTouch = leftTopTouch; candidate.bottomTouch = leftBottomTouch; } LOG.debug("Adding bridge candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); candidateList.add(candidate); } } } LOG.debug("Bridge candidate size: " + candidateList.size()); LOG.debug("Eliminating candidates with shorter neighbor"); Set<BridgeCandidate> candidatesToEliminate = null; if (candidateList.size() > 0) { // eliminate any bridge candidates that touch a shorter bridge candidate candidatesToEliminate = new HashSet<BridgeCandidate>(); for (int i = 0; i < candidateList.size() - 1; i++) { BridgeCandidate candidate = candidateList.get(i); for (int j = i + 1; j < candidateList.size(); j++) { BridgeCandidate otherCandidate = candidateList.get(j); if (otherCandidate.x == candidate.x + 1 && candidate.rightSegments.contains(otherCandidate)) { if ((candidate.bridgeWidth()) <= (otherCandidate.bridgeWidth())) { LOG.debug("Eliminating candidate x = " + otherCandidate.x + ", top = " + otherCandidate.yTop + ", bottom = " + otherCandidate.yBottom); candidatesToEliminate.add(otherCandidate); } else { LOG.debug("Eliminating candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); candidatesToEliminate.add(candidate); } } } } candidateList.removeAll(candidatesToEliminate); LOG.debug("Bridge candidate size: " + candidateList.size()); // To be a bridge, three additional things have to be true: // (A) intersection between right & left shape = null // (B) weight of right shape & weight of left shape > a certain threshold // (C) little overlap right boundary of left shape, left boundary of right shape LOG.debug("Eliminating candidates touching enclosed space"); // (A) intersection between right & left shape = null // Intersection between right and left shape is non-null // if the line segment X touches an enclosed space immediately above or below candidatesToEliminate = new HashSet<BridgeCandidate>(); for (BridgeCandidate candidate : candidateList) { boolean nullIntersection = true; for (VerticalLineSegment inverseLine : enclosedInverseLines) { if (candidate.x == inverseLine.x) { if (inverseLine.yBottom == candidate.yTop - 1 || inverseLine.yTop == candidate.yBottom + 1) { nullIntersection = false; break; } } } if (!nullIntersection) { LOG.debug("Eliminating candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); candidatesToEliminate.add(candidate); } } candidateList.removeAll(candidatesToEliminate); LOG.debug("Remaining bridge candidate size: " + candidateList.size()); // another criterion for avoiding "false splits" is that on both side of the bridge // the shapes pretty rapidly expand in width both up and down LOG.debug("Eliminating candidates without vertical expansion on both sides"); candidatesToEliminate = new HashSet<BridgeCandidate>(); int expansionLimit = (int) Math.ceil(((double) this.getWidth()) / 6.0); for (BridgeCandidate candidate : candidateList) { // take into account the portion touching on the right or left boolean isCandidate = true; Stack<VerticalLineSegment> leftLines = new Stack<VerticalLineSegment>(); Stack<Integer> leftDepths = new Stack<Integer>(); leftLines.push(candidate); leftDepths.push(0); int leftTop = candidate.topTouch; int leftBottom = candidate.bottomTouch; while (!leftLines.isEmpty()) { VerticalLineSegment line = leftLines.pop(); int depth = leftDepths.pop(); if (line.yTop < leftTop) leftTop = line.yTop; if (line.yBottom > leftBottom) leftBottom = line.yBottom; if (depth <= expansionLimit) { for (VerticalLineSegment leftSegment : line.leftSegments) { leftLines.push(leftSegment); leftDepths.push(depth + 1); } } } if (leftTop == candidate.topTouch || leftBottom == candidate.bottomTouch) isCandidate = false; if (isCandidate) { Stack<VerticalLineSegment> rightLines = new Stack<VerticalLineSegment>(); Stack<Integer> rightDepths = new Stack<Integer>(); rightLines.push(candidate); rightDepths.push(0); int rightTop = candidate.topTouch; int rightBottom = candidate.bottomTouch; while (!rightLines.isEmpty()) { VerticalLineSegment line = rightLines.pop(); int depth = rightDepths.pop(); if (line.yTop < rightTop) rightTop = line.yTop; if (line.yBottom > rightBottom) rightBottom = line.yBottom; if (depth <= expansionLimit) { for (VerticalLineSegment rightSegment : line.rightSegments) { rightLines.push(rightSegment); rightDepths.push(depth + 1); } } } if (rightTop == candidate.topTouch || rightBottom == candidate.bottomTouch) isCandidate = false; } if (!isCandidate) { LOG.debug("Eliminating candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); candidatesToEliminate.add(candidate); } } candidateList.removeAll(candidatesToEliminate); LOG.debug("Remaining bridge candidate size: " + candidateList.size()); if (LOG.isDebugEnabled()) { for (VerticalLineSegment candidate : candidateList) { LOG.debug("Remaining candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); } } } if (candidateList.size() > 0) { // (B) weight of right shape & weight of left shape > a certain threshold // (C) little overlap right boundary of left shape, left boundary of right shape // // We can now divide the shape into n groups, each separated by a candidate // We recursively build a group until we reach a candidate // and indicate whether it's the right or left border of the candidate. // We then keep going from the candidate on to the next one // We keep tab of the size of each group and of its right & left boundaries // at the end we can easily determine the right and left boundaries of each, // as well as the right & left pixel weight List<VerticalLineGroup> groups = new ArrayList<VerticalLineGroup>(); VerticalLineSegment firstLine = lines.first(); lineStack = new Stack<VerticalLineSegment>(); Stack<BridgeCandidate> candidateStack = new Stack<BridgeCandidate>(); Stack<Boolean> fromLeftStack = new Stack<Boolean>(); Stack<Boolean> candidateFromLeftStack = new Stack<Boolean>(); lineStack.push(firstLine); fromLeftStack.push(true); VerticalLineGroup group = new VerticalLineGroup(this); List<BridgeCandidate> touchedCandidates = new ArrayList<BridgeCandidate>(); while (!lineStack.isEmpty()) { while (!lineStack.isEmpty()) { VerticalLineSegment line = lineStack.pop(); boolean fromLeft = fromLeftStack.pop(); if (line.touched) continue; line.touched = true; if (candidateList.contains(line)) { // a candidate! LOG.debug("Touching candidate x = " + line.x + ", top = " + line.yTop + ", bottom = " + line.yBottom); BridgeCandidate candidate = null; for (BridgeCandidate existingCandidate : candidateList) { if (existingCandidate.equals(line)) { candidate = existingCandidate; break; } } boolean foundCandidate = touchedCandidates.contains(candidate); if (!foundCandidate) { touchedCandidates.add(candidate); candidateStack.push(candidate); candidateFromLeftStack.push(fromLeft); if (fromLeft) { // coming from the left group.rightCandidates.add(candidate); candidate.leftGroup = group; } else { group.leftCandidates.add(candidate); candidate.rightGroup = group; } } } else { // not a candidate LOG.debug("Touching line length = " + line.length() + ", x = " + line.x + ", top = " + line.yTop + ", bottom = " + line.yBottom); group.pixelCount += line.length(); if (line.x < group.leftBoundary) group.leftBoundary = line.x; if (line.x > group.rightBoundary) group.rightBoundary = line.x; if (line.yTop < group.topBoundary) group.topBoundary = line.yTop; if (line.yBottom > group.bottomBoundary) group.bottomBoundary = line.yBottom; for (VerticalLineSegment leftLine : line.leftSegments) { lineStack.push(leftLine); fromLeftStack.push(false); } for (VerticalLineSegment rightLine : line.rightSegments) { lineStack.push(rightLine); fromLeftStack.push(true); } } } // no more lines in this group groups.add(group); if (!candidateStack.isEmpty()) { BridgeCandidate candidate = candidateStack.pop(); boolean fromLeft = candidateFromLeftStack.pop(); //lineStack.push(candidate.line); //fromLeftStack.push(fromLeft); LOG.debug("*** New Group ***"); LOG.debug("Next candidate: x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); group = new VerticalLineGroup(this); if (fromLeft) { group.leftCandidates.add(candidate); candidate.rightGroup = group; } else { group.rightCandidates.add(candidate); candidate.leftGroup = group; } // add this candidate's neighbours to the lineStack for (VerticalLineSegment leftLine : candidate.leftSegments) { lineStack.push(leftLine); fromLeftStack.push(false); } for (VerticalLineSegment rightLine : candidate.rightSegments) { lineStack.push(rightLine); fromLeftStack.push(true); } } // next candidate on candidate stack } // no more lines to process if (LOG.isDebugEnabled()) { LOG.debug("Found " + groups.size() + " groups"); int i = 1; for (VerticalLineGroup aGroup : groups) { LOG.debug("Group " + i++ + ", pixelCount: " + aGroup.pixelCount + ", leftBoundary: " + aGroup.leftBoundary + ", rightBoundary: " + aGroup.rightBoundary); LOG.debug("Candidates on left: "); for (BridgeCandidate candidate : aGroup.leftCandidates) LOG.debug("Candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); LOG.debug("Candidates on right: "); for (BridgeCandidate candidate : aGroup.rightCandidates) LOG.debug("Candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); } LOG.debug("Found " + candidateList.size() + " candidates"); for (BridgeCandidate candidate : candidateList) { LOG.debug("Candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); LOG.debug("- Left group = pixelCount: " + candidate.leftGroup.pixelCount + ", leftBoundary: " + candidate.leftGroup.leftBoundary + ", rightBoundary: " + candidate.leftGroup.rightBoundary); LOG.debug("- Right group = pixelCount: " + candidate.rightGroup.pixelCount + ", leftBoundary: " + candidate.rightGroup.leftBoundary + ", rightBoundary: " + candidate.rightGroup.rightBoundary); } } // should we log? // calculate each candidate's pixel totals and boundaries for (BridgeCandidate candidate : candidateList) { for (VerticalLineGroup lineGroup : groups) lineGroup.touched = false; Stack<VerticalLineGroup> groupStack = new Stack<VerticalLineGroup>(); groupStack.push(candidate.leftGroup); while (!groupStack.isEmpty()) { VerticalLineGroup lineGroup = groupStack.pop(); if (lineGroup.touched) continue; lineGroup.touched = true; candidate.leftPixels += lineGroup.pixelCount; if (lineGroup.leftBoundary < candidate.leftShapeLeftBoundary) candidate.leftShapeLeftBoundary = lineGroup.leftBoundary; if (lineGroup.rightBoundary > candidate.leftShapeRightBoundary) candidate.leftShapeRightBoundary = lineGroup.rightBoundary; for (BridgeCandidate leftCandidate : lineGroup.leftCandidates) { if (!candidate.equals(leftCandidate)) { candidate.leftPixels += leftCandidate.length(); groupStack.push(leftCandidate.leftGroup); } } for (BridgeCandidate rightCandidate : lineGroup.rightCandidates) { if (!candidate.equals(rightCandidate)) { candidate.leftPixels += rightCandidate.length(); groupStack.push(rightCandidate.rightGroup); } } } // next left group groupStack.push(candidate.rightGroup); while (!groupStack.isEmpty()) { VerticalLineGroup lineGroup = groupStack.pop(); if (lineGroup.touched) continue; lineGroup.touched = true; candidate.rightPixels += lineGroup.pixelCount; if (lineGroup.leftBoundary < candidate.rightShapeLeftBoundary) candidate.rightShapeLeftBoundary = lineGroup.leftBoundary; if (lineGroup.rightBoundary > candidate.rightShapeRightBoundary) candidate.rightShapeRightBoundary = lineGroup.rightBoundary; for (BridgeCandidate leftCandidate : lineGroup.leftCandidates) { if (!candidate.equals(leftCandidate)) { candidate.rightPixels += leftCandidate.length(); groupStack.push(leftCandidate.leftGroup); } } for (BridgeCandidate rightCandidate : lineGroup.rightCandidates) { if (!candidate.equals(rightCandidate)) { candidate.rightPixels += rightCandidate.length(); groupStack.push(rightCandidate.rightGroup); } } } // next right group } // next candidate } // do we have any candidates? this.bridgeCandidates = candidateList; } // lazy load return this.bridgeCandidates; }
From source file:com.aurel.track.fieldType.bulkSetters.CustomMultipleSelectBulkSetter.java
/** * Sets the workItemBean's attribute depending on the value and bulkRelation * @param workItemBean/*from w w w . ja v a 2 s . c om*/ * @param fieldID * @param parameterCode * @param bulkTranformContext * @param selectContext * @param value * @return ErrorData if an error is found */ @Override public ErrorData setWorkItemAttribute(TWorkItemBean workItemBean, Integer fieldID, Integer parameterCode, BulkTranformContext bulkTranformContext, SelectContext selectContext, Object value) { if (getRelation() == BulkRelations.SET_NULL || getRelation() == BulkRelations.SET_TO) { return super.setWorkItemAttribute(workItemBean, fieldID, parameterCode, bulkTranformContext, selectContext, value); } Object originalValue = workItemBean.getAttribute(fieldID, parameterCode); Object[] originalSelections = null; if (originalValue != null) { try { //multiple values are loaded in the workItem as Object[], not as Integer[] !!! originalSelections = (Object[]) originalValue; } catch (Exception e) { LOGGER.info( "Getting the original object array value for " + value + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } Set<Integer> originalSet = new HashSet<Integer>(); if (originalSelections != null && originalSelections.length > 0) { for (int i = 0; i < originalSelections.length; i++) { try { originalSet.add((Integer) originalSelections[i]); } catch (Exception e) { LOGGER.info("Transforming the original object value " + originalSelections[i] + " to Integer failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } } Integer[] newValue = null; SortedMap<Integer, Integer[]> valueMap = (SortedMap<Integer, Integer[]>) value; Map<Integer, Map<Integer, Map<Integer, Integer>>> fieldToProjectToIssueTypeToListMap = bulkTranformContext .getFieldToProjectToIssueTypeToListMap(); if (fieldToProjectToIssueTypeToListMap != null) { Map<Integer, Map<Integer, Integer>> projectToIssueTypeToListMap = fieldToProjectToIssueTypeToListMap .get(fieldID); if (projectToIssueTypeToListMap != null) { Integer projectID = workItemBean.getProjectID(); Map<Integer, Integer> issueTypeToListMap = projectToIssueTypeToListMap.get(projectID); if (issueTypeToListMap != null) { Integer issueTypeID = workItemBean.getListTypeID(); Integer listID = issueTypeToListMap.get(issueTypeID); if (listID != null) { newValue = valueMap.get(listID); } } } } Set<Integer> bulkSelectionsSet = GeneralUtils.createSetFromIntegerArr(newValue); switch (getRelation()) { case BulkRelations.ADD_ITEMS: originalSet.addAll(bulkSelectionsSet); workItemBean.setAttribute(fieldID, parameterCode, GeneralUtils.createIntegerArrFromCollection(originalSet)); break; case BulkRelations.REMOVE_ITEMS: originalSet.removeAll(bulkSelectionsSet); workItemBean.setAttribute(fieldID, parameterCode, GeneralUtils.createIntegerArrFromCollection(originalSet)); break; default: break; } return null; }
From source file:com.alibaba.jstorm.daemon.supervisor.SyncProcessEvent.java
/** * check all workers is failed or not/*from w w w. j ava 2s . c o m*/ */ @SuppressWarnings("unchecked") public void checkNeedUpdateTopologys(Map<String, StateHeartbeat> localWorkerStats, Map<Integer, LocalAssignment> localAssignments) throws Exception { Set<String> topologys = new HashSet<String>(); Map<String, Long> topologyAssignTimeStamps = new HashMap<String, Long>(); for (Entry<Integer, LocalAssignment> entry : localAssignments.entrySet()) { topologys.add(entry.getValue().getTopologyId()); topologyAssignTimeStamps.put(entry.getValue().getTopologyId(), entry.getValue().getTimeStamp()); } for (StateHeartbeat stateHb : localWorkerStats.values()) { State state = stateHb.getState(); if (!state.equals(State.notStarted)) { String topologyId = stateHb.getHeartbeat().getTopologyId(); topologys.remove(topologyId); } } long currTime = System.currentTimeMillis(); Set<String> needRemoveTopologys = new HashSet<String>(); for (String topologyId : topologys) { try { long newAssignTime = topologyAssignTimeStamps.get(topologyId); if ((currTime - newAssignTime) / 1000 < (JStormUtils.MIN_1 * 2)) { LOG.debug("less 2 minite ,so removed " + topologyId); needRemoveTopologys.add(topologyId); } } catch (Exception e) { LOG.error("Failed to get the time of file last modification for topology" + topologyId, e); needRemoveTopologys.add(topologyId); } } topologys.removeAll(needRemoveTopologys); if (topologys.size() > 0) { LOG.debug("Following topologys is going to re-download the jars, " + topologys); } needDownloadTopologys.set(topologys); }