List of usage examples for java.util Set addAll
boolean addAll(Collection<? extends E> c);
From source file:com.ocs.dynamo.domain.model.util.EntityModelUtil.java
/** * Compares two entities based on the entity model and reports a list of the differences * // w w w .j a va 2 s . co m * @param oldEntity * the old entity * @param newEntity * the new entity * @param model * the entity model * @param entityModelFactory * @param messageService * the message service * @param ignore * the names of the fields to ignore */ public static List<String> compare(Object oldEntity, Object newEntity, EntityModel<?> model, EntityModelFactory entityModelFactory, MessageService messageService, String... ignore) { List<String> results = new ArrayList<>(); Set<String> toIgnore = new HashSet<>(); if (ignore != null) { toIgnore = Sets.newHashSet(ignore); } toIgnore.addAll(ALWAYS_IGNORE); String noValue = messageService.getMessage("ocs.no.value"); for (AttributeModel am : model.getAttributeModels()) { if ((AttributeType.BASIC.equals(am.getAttributeType()) || AttributeType.MASTER.equals(am.getAttributeType())) && !toIgnore.contains(am.getName())) { Object oldValue = ClassUtils.getFieldValue(oldEntity, am.getName()); Object newValue = ClassUtils.getFieldValue(newEntity, am.getName()); if (!ObjectUtils.equals(oldValue, newValue)) { String oldValueStr = TableUtils.formatPropertyValue(entityModelFactory, model, messageService, am.getName(), oldValue); String newValueStr = TableUtils.formatPropertyValue(entityModelFactory, model, messageService, am.getName(), newValue); results.add(messageService.getMessage("ocs.value.changed", am.getDisplayName(), oldValue == null ? noValue : oldValueStr, newValue == null ? noValue : newValueStr)); } } else if (AttributeType.DETAIL.equals(am.getAttributeType())) { Collection<?> ocol = (Collection<?>) ClassUtils.getFieldValue(oldEntity, am.getName()); Collection<?> ncol = (Collection<?>) ClassUtils.getFieldValue(newEntity, am.getName()); for (Object o : ncol) { if (!ocol.contains(o)) { results.add(messageService.getMessage("ocs.value.added", getDescription(o, am.getNestedEntityModel()), am.getDisplayName())); } } for (Object o : ocol) { if (!ncol.contains(o)) { results.add(messageService.getMessage("ocs.value.removed", getDescription(o, am.getNestedEntityModel()), am.getDisplayName())); } } for (Object o : ocol) { for (Object o2 : ncol) { if (o.equals(o2)) { List<String> nested = compare(o, o2, am.getNestedEntityModel(), entityModelFactory, messageService, ignore); results.addAll(nested); } } } } } return results; }
From source file:eu.itesla_project.modules.rules.CheckSecurityTool.java
private static void writeCsv2(Map<String, Map<SecurityIndexId, SecurityRuleCheckStatus>> checkStatusPerBaseCase, Path outputCsvFile) throws IOException { Objects.requireNonNull(outputCsvFile); Set<SecurityIndexId> securityIndexIds = new LinkedHashSet<>(); for (Map<SecurityIndexId, SecurityRuleCheckStatus> checkStatus : checkStatusPerBaseCase.values()) { securityIndexIds.addAll(checkStatus.keySet()); }//from w w w .j av a 2s. co m try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) { writer.write("Base case"); for (SecurityIndexId securityIndexId : securityIndexIds) { writer.write(CSV_SEPARATOR); writer.write(securityIndexId.toString()); } writer.newLine(); for (Map.Entry<String, Map<SecurityIndexId, SecurityRuleCheckStatus>> entry : checkStatusPerBaseCase .entrySet()) { String baseCaseName = entry.getKey(); writer.write(baseCaseName); Map<SecurityIndexId, SecurityRuleCheckStatus> checkStatus = entry.getValue(); for (SecurityIndexId securityIndexId : securityIndexIds) { writer.write(CSV_SEPARATOR); SecurityRuleCheckStatus status = checkStatus.get(securityIndexId); writer.write(status.name()); } writer.newLine(); } } }
From source file:net.shopxx.util.CompressUtils.java
public static void archive(File[] srcFiles, File destFile, String archiverName) { Assert.notNull(destFile);//from www . j a v a2 s. c o m Assert.state(!destFile.exists() || destFile.isFile()); Assert.hasText(archiverName); File parentFile = destFile.getParentFile(); if (parentFile != null) { parentFile.mkdirs(); } ArchiveOutputStream archiveOutputStream = null; try { archiveOutputStream = new ArchiveStreamFactory().createArchiveOutputStream(archiverName, new BufferedOutputStream(new FileOutputStream(destFile))); if (ArrayUtils.isNotEmpty(srcFiles)) { for (File srcFile : srcFiles) { if (srcFile == null || !srcFile.exists()) { continue; } Set<File> files = new HashSet<File>(); if (srcFile.isFile()) { files.add(srcFile); } if (srcFile.isDirectory()) { files.addAll(FileUtils.listFilesAndDirs(srcFile, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)); } String basePath = FilenameUtils.getFullPath(srcFile.getCanonicalPath()); for (File file : files) { try { String entryName = FilenameUtils.separatorsToUnix( StringUtils.substring(file.getCanonicalPath(), basePath.length())); ArchiveEntry archiveEntry = archiveOutputStream.createArchiveEntry(file, entryName); archiveOutputStream.putArchiveEntry(archiveEntry); if (file.isFile()) { InputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(inputStream, archiveOutputStream); } catch (FileNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { IOUtils.closeQuietly(inputStream); } } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { archiveOutputStream.closeArchiveEntry(); } } } } } catch (ArchiveException e) { throw new RuntimeException(e.getMessage(), e); } catch (FileNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { IOUtils.closeQuietly(archiveOutputStream); } }
From source file:com.dtolabs.rundeck.ec2.NodeGenerator.java
private static Set<Instance> performQuery(AWSCredentials credentials, final String endPoint, final ArrayList<String> filterParams) { AmazonEC2Client ec2 = new AmazonEC2Client(credentials); if (null != endPoint && !"".equals(endPoint) && !"-".equals(endPoint)) { ec2.setEndpoint(endPoint);//w ww .j ava 2s. com } //create "running" filter ArrayList<Filter> filters = new ArrayList<Filter>(); Filter filter = new Filter("instance-state-name").withValues(InstanceStateName.Running.toString()); filters.add(filter); if (null != filterParams) { for (final String filterParam : filterParams) { String[] x = filterParam.split("=", 2); if (!"".equals(x[0]) && !"".equals(x[1])) { filters.add(new Filter(x[0]).withValues(x[1])); } } } DescribeInstancesRequest request = new DescribeInstancesRequest().withFilters(filters); DescribeInstancesResult describeInstancesRequest = ec2.describeInstances(request); List<Reservation> reservations = describeInstancesRequest.getReservations(); Set<Instance> instances = new HashSet<Instance>(); for (final Reservation reservation : reservations) { instances.addAll(reservation.getInstances()); } return instances; }
From source file:com.github.s4ke.moar.json.MoarJSONSerializer.java
private static CodePointSet buildFnFromSetExpression(String setExpression) { RegexLexer lexer = new RegexLexer(new ANTLRInputStream(setExpression)); RegexParser parser = new RegexParser(new CommonTokenStream(lexer)); parser.setBuildParseTree(true);/*from w w w . ja v a2s .c o m*/ parser.getErrorListeners().clear(); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw e; } }); RegexParser.SetContext setContext = parser.set(); if (parser.getNumberOfSyntaxErrors() > 0) { throw new IllegalArgumentException("malformed set expression: " + setExpression); } Set<RangeRep> ranges = new HashSet<>(); boolean negative; if (setContext.negativeSet() != null) { ranges.addAll(Arrays.asList(RegexTreeListener.ranges(setContext.negativeSet().setItems()))); negative = true; } else if (setContext.positiveSet() != null) { ranges.addAll(Arrays.asList(RegexTreeListener.ranges(setContext.positiveSet().setItems()))); negative = false; } else { throw new AssertionError(); } CodePointSet ret = CharacterClassesUtils.positiveFn(ranges); if (negative) { ret = ret.negative(); } return ret; }
From source file:edu.ku.brc.af.core.UsageTracker.java
/** * Clears all usage statistics.//from w w w .j a v a2 s. co m */ protected synchronized static void clearUsageStats() { AppPreferences appPrefs = AppPreferences.getLocalPrefs(); Set<Object> prefNames = appPrefs.getProperties().keySet(); Set<Object> prefNamesCopy = new HashSet<Object>(); prefNamesCopy.addAll(prefNames); for (Object o : prefNamesCopy) { String prefName = (String) o; if (prefName.startsWith(USAGE_PREFIX)) //$NON-NLS-1$ { appPrefs.remove(prefName); } } if (usageProps != null) { usageProps.clear(); } }
From source file:com.edmunds.etm.management.util.DnsUtils.java
/** * Returns a set of all IP addresses for the given host names. * * @param hosts collection of host names or IP addresses * @param retryCount maximum number of times to retry DNS lookups * @return set of all IP addresses (may be empty if no addresses were found) *//* w w w.j a v a 2 s . c o m*/ public static Set<InetAddress> getAddressesByHost(Collection<String> hosts, int retryCount) { Set<InetAddress> allAddresses = new HashSet<InetAddress>(); for (String host : hosts) { if (StringUtils.isBlank(host)) { continue; } InetAddress[] hostAddresses = getAddressesByHost(host, retryCount); if (hostAddresses != null) { allAddresses.addAll(Arrays.asList(hostAddresses)); } } return allAddresses; }
From source file:com.cinchapi.concourse.shell.SyntaxTools.java
/** * Check {@code line} to see if it is a function call that is missing any * commas among arguments.//from w ww .j a v a 2 s .c om * * @param line * @param methods * @return the line with appropriate argument commas */ public static String handleMissingArgCommas(String line, List<String> methods) { int hashCode = methods.hashCode(); Set<String> hashedMethods = CACHED_METHODS.get(hashCode); if (hashedMethods == null) { hashedMethods = Sets.newHashSetWithExpectedSize(methods.size()); hashedMethods.addAll(methods); CACHED_METHODS.put(hashCode, hashedMethods); } char[] chars = line.toCharArray(); StringBuilder transformed = new StringBuilder(); StringBuilder gather = new StringBuilder(); boolean foundMethod = false; boolean inSingleQuotes = false; boolean inDoubleQuotes = false; int parenCount = 0; for (char c : chars) { if (Character.isWhitespace(c) && !foundMethod) { transformed.append(gather); transformed.append(c); foundMethod = hashedMethods.contains(gather.toString()); gather.setLength(0); } else if (Character.isWhitespace(c) && foundMethod) { if (transformed.charAt(transformed.length() - 1) != ',' && !inSingleQuotes && !inDoubleQuotes && c != '\n') { transformed.append(","); } transformed.append(c); } else if (c == '(' && !foundMethod) { parenCount++; transformed.append(gather); transformed.append(c); foundMethod = hashedMethods.contains(gather.toString()); gather.setLength(0); } else if (c == '(' && foundMethod) { parenCount++; transformed.append(c); } else if (c == ';') { transformed.append(c); foundMethod = false; parenCount = 0; } else if (c == ')') { parenCount--; transformed.append(c); foundMethod = parenCount == 0 ? false : foundMethod; } else if (c == '"') { transformed.append(c); inSingleQuotes = !inSingleQuotes; } else if (c == '\'') { transformed.append(c); inDoubleQuotes = !inDoubleQuotes; } else if (foundMethod) { transformed.append(c); } else { gather.append(c); } } transformed.append(gather); return transformed.toString(); }
From source file:br.com.autonomiccs.cloudTraces.main.GoogleTracesToCloudTracesParser.java
private static List<Integer> getAllTimesThatWeExecuteTask(List<VirtualMachine> virtualMachines) { Set<Integer> times = new HashSet<>(); for (VirtualMachine virtualMachine : virtualMachines) { times.addAll(virtualMachine.getGoogleJob().getMapTimeByTasks().keySet()); }/*w w w .j a va 2 s . c om*/ ArrayList<Integer> listOfTimes = new ArrayList<>(times); Collections.sort(listOfTimes); return listOfTimes; }
From source file:com.github.rvesse.airline.model.OptionMetadata.java
/** * Tries to merge the option metadata together such that the child metadata * takes precedence. Not all options can be successfully overridden and an * error may be thrown in cases where merging is not possible * <p>//w w w . j ava 2s . co m * The following pieces of metadata may be overridden: * </p> * <ul> * <li>Title</li> * <li>Description</li> * <li>Required</li> * <li>Hidden</li> * </ul> * * @param parent * Parent * @param child * Child * @return Merged metadata */ public static OptionMetadata override(Set<String> names, OptionMetadata parent, OptionMetadata child) { // Cannot change option type, arity or names if (parent.optionType != child.optionType) throw new IllegalArgumentException( String.format("Cannot change optionType when overriding option %s", names)); if (parent.arity != child.arity) throw new IllegalArgumentException( String.format("Cannot change arity when overriding option %s", names)); if (!parent.options.equals(child.options)) throw new IllegalArgumentException( String.format("Cannot change option names when overriding option %s", names)); // Also cannot change the type of the option unless the change is a // narrowing conversion Class<?> parentType = parent.getJavaType(); Class<?> childType = child.getJavaType(); if (!parentType.equals(childType)) { if (!parentType.isAssignableFrom(childType)) { if (childType.isAssignableFrom(parentType)) { // A widening conversion exists but this is illegal however // we can give a slightly more informative error in this // case throw new IllegalArgumentException(String.format( "Cannot change the Java type from %s to %s when overriding option %s as this is a widening type change - only narrowing type changes are permitted", parentType, childType, names)); } else { // No conversion exists throw new IllegalArgumentException(String.format( "Cannot change the Java type from %s to %s when overriding option %s - only narrowing type changes where a valid cast exists are permitted", parentType, childType, names)); } } } // Check for duplicates boolean isDuplicate = parent == child || parent.equals(child); // Parent must not state it is sealed UNLESS it is a duplicate which can // happen when using @Inject to inject options via delegates if (parent.sealed && !isDuplicate) throw new IllegalArgumentException( String.format("Cannot override option %s as parent option declares it to be sealed", names)); // Child must explicitly state that it overrides otherwise we cannot // override UNLESS it is the case that this is a duplicate which // can happen when using @Inject to inject options via delegates if (!child.overrides && !isDuplicate) throw new IllegalArgumentException( String.format("Cannot override option %s unless child option sets overrides to true", names)); OptionMetadata merged; //@formatter:off merged = new OptionMetadata(child.optionType, child.options, child.title != null ? child.title : parent.title, child.description != null ? child.description : parent.description, child.arity, child.hidden, child.overrides, child.sealed, child.restrictions.size() > 0 ? child.restrictions : parent.restrictions, null); //@formatter:on // Combine both child and parent accessors - this is necessary so the // parsed value propagates to all classes in the hierarchy Set<Accessor> accessors = new LinkedHashSet<>(child.accessors); accessors.addAll(parent.accessors); merged.accessors = AirlineUtils.unmodifiableSetCopy(accessors); return merged; }