List of usage examples for java.util List contains
boolean contains(Object o);
From source file:com.scvngr.levelup.core.test.JsonTestUtil.java
/** * <p>/*w ww . ja v a2 s. co m*/ * Checks that modifying individual fields in a model will result in its equals/hashCode methods * failing. Uses reflection on {@link JsonValueType} annotations on fields of a passed class to * figure out how to modify the JSON representation of the model in different ways, then parses * the JSON with a {@link AbstractJsonModelFactory} subclass before checking equals/hashcode on * both the original and a modified object. * </p> * <p> * This effectively checks that equals/hashcode works across any value changes from fields we * read from JSON, but also checks some other potential issues. We're implicitly checking that * the JSON typing declared in annotations for the fields matches what we actually use when * parsing our JSON (since if it doesn't, we'll get JSON errors when reading the data during the * clone/modify). We're also checking for fields that may have been added to the JSON keys and * the model without updating equals/hashcode to reflect them (as long as they're declared in * the JSONKeys class used here). * </p> * <p> * Note that this is only intended for test use and will turn all checked exceptions it might * throw into unchecked ones. * </p> * * @param jsonKeysClass Class of the underlying keys class to test all fields (except * blacklistFields) from. Must have visible fields to read from. * @param jsonFactory Factory object to construct model instances from out of the base and * generated-variant JSON objects before checking equals/hashcode. * @param baseJsonObject Fully-populated JSON object for the model to use for comparison with * modified copies. * @param blacklistFields Fields to exclude from variant testing (either because we need to test * them manually or because they don't reflect fields that are used for parsing into the * model). Note that this is the jsonKeysClass's field name as a string, not the JSON key * value (eg "ID", not "id"). */ public static void checkEqualsAndHashCodeOnJsonVariants(@NonNull final Class<?> jsonKeysClass, @NonNull final AbstractJsonModelFactory<?> jsonFactory, @NonNull final JSONObject baseJsonObject, @NonNull final String[] blacklistFields) { Object originalModel; Object differentModel; Object differentModelReparse; try { originalModel = jsonFactory.from(baseJsonObject); } catch (final JSONException e1) { throw new RuntimeException(e1); } MoreAsserts.checkEqualsAndHashCodeMethods(originalModel, null, false); final Field[] jsonKeyFields = jsonKeysClass.getFields(); final List<String> blacklisted = Arrays.asList(blacklistFields); final String key = null; MoreAsserts.assertNotEmpty("JSON keys class visible fields", Arrays.asList(jsonKeyFields)); for (final Field field : jsonKeyFields) { if (!blacklisted.contains(field.getName())) { JSONObject copiedDifferingObject; String fieldString; // Don't check exceptions, just let tests fail. try { fieldString = NullUtils.nonNullContract((String) field.get(key)); copiedDifferingObject = cloneObjectDifferingOnParam(baseJsonObject, fieldString, reflectJsonType(field)); differentModel = jsonFactory.from(copiedDifferingObject); differentModelReparse = jsonFactory.from(copiedDifferingObject); } catch (final IllegalArgumentException e) { throw new RuntimeException(e); } catch (final IllegalAccessException e) { throw new RuntimeException(e); } catch (final JSONException e) { throw new RuntimeException(e); } MoreAsserts.checkEqualsAndHashCodeMethods( String.format(Locale.US, "Modified %s and checked equals and hash", fieldString), originalModel, differentModel, false); MoreAsserts.checkEqualsAndHashCodeMethods( String.format(Locale.US, "Modified %s and checked equals and hash", fieldString), differentModel, differentModel, true); MoreAsserts.checkEqualsAndHashCodeMethods( String.format(Locale.US, "Modified %s and checked equals and hash", fieldString), differentModel, differentModelReparse, true); } } }
From source file:com.basetechnology.s0.agentserver.util.JsonUtils.java
public static void validateKeys(JSONObject objectJson, String objectName, List<String> validKeys) throws AgentServerException { String badKeys = ""; Map<String, Value> treeMap = new TreeMap<String, Value>(); for (Iterator<String> it = objectJson.keys(); it.hasNext();) treeMap.put(it.next(), null);//w w w. ja va2 s .c o m for (String key : treeMap.keySet()) if (!validKeys.contains(key)) badKeys += (badKeys.length() > 0 ? ", " : "") + key; if (badKeys.length() > 0) throw new AgentServerException(objectName + " JSON has invalid keys: " + badKeys); }
From source file:eu.edisonproject.training.execute.Main.java
private static void saveTerms2Avro(List<Term> terms, String out) { TermAvroSerializer ts = new TermAvroSerializer(out, Term.getClassSchema()); List<CharSequence> empty = new ArrayList<>(); empty.add(""); // Stemming stemer = new Stemming(); String stopWordsPath = System.getProperty("stop.words.file"); if (stopWordsPath == null) { stopWordsPath = prop.getProperty("stop.words.file", ".." + File.separator + "etc" + File.separator + "stopwords.csv"); }/*from www. ja v a 2 s . c o m*/ CharArraySet stopwordsCharArray = new CharArraySet(ConfigHelper.loadStopWords(stopWordsPath), true); StopWord tokenizer = new StopWord(stopwordsCharArray); StanfordLemmatizer lematizer = new StanfordLemmatizer(); for (Term t : terms) { List<CharSequence> nuid = t.getNuids(); if (nuid == null || nuid.isEmpty() || nuid.contains(null)) { t.setNuids(empty); } List<CharSequence> buids = t.getBuids(); if (buids == null || buids.isEmpty() || buids.contains(null)) { t.setBuids(empty); } List<CharSequence> alt = t.getAltLables(); if (alt == null || alt.isEmpty() || alt.contains(null)) { t.setAltLables(empty); } List<CharSequence> gl = t.getGlosses(); if (gl == null || gl.isEmpty() || gl.contains(null)) { ArrayList<CharSequence> lem = new ArrayList<>(); lem.add(t.lemma); t.setGlosses(lem); } else { StringBuilder glosses = new StringBuilder(); for (CharSequence n : gl) { glosses.append(n).append(" "); } glosses.append(t.lemma.toString().replaceAll("_", " ")); if (alt != null && !alt.isEmpty() && !alt.contains(null)) { for (CharSequence c : alt) { glosses.append(c.toString().replaceAll("_", " ")).append(" "); } } gl = new ArrayList<>(); tokenizer.setDescription(glosses.toString()); String cleanText = tokenizer.execute(); lematizer.setDescription(cleanText); String lematizedText = lematizer.execute(); gl.add(lematizedText); t.setGlosses(gl); } List<CharSequence> cat = t.getCategories(); if (cat == null || cat.contains(null)) { t.setCategories(empty); } ts.serialize(t); } ts.close(); }
From source file:forge.card.BoosterGenerator.java
public static void addCardsFromExtraSheet(List<PaperCard> dest, String printSheetKey) { PrintSheet extraSheet = getPrintSheet(printSheetKey); for (PaperCard card : extraSheet.toFlatList()) { if (!dest.contains(card)) { dest.add(card);//from www . j a v a 2s .c o m } } }
From source file:com.ckfinder.connector.utils.ImageUtils.java
/** * checks if file is image.//from w w w. j a v a2 s. co m * * @param file file to check * @return true if file is image. */ public static boolean isImage(final File file) { List<String> list = Arrays.asList(ALLOWED_EXT); String fileExt = null; if (file != null) { fileExt = FileUtils.getFileExtension(file.getName().toLowerCase()); return (fileExt != null) ? list.contains(fileExt) : false; } else { return false; } }
From source file:com.linkedin.databus.groupleader.impl.zkclient.LeaderElectUtils.java
public static List<Integer> parseLocalPorts(String hostPortList) { List<Integer> localPortsList = new ArrayList<Integer>(); String[] hostPortArray = hostPortList.split(","); for (String hostPortString : hostPortArray) { String[] hostAndPort = hostPortString.split(":"); if (hostAndPort[0].equals("localhost") || hostAndPort[0].equals("127.0.0.1")) { int port = Integer.parseInt(hostAndPort[1]); if (!localPortsList.contains(port)) { localPortsList.add(port); }/*from w w w .j av a 2 s. co m*/ } } return localPortsList; }
From source file:org.zht.framework.util.ZBeanUtil.java
private static void copy(Object source, Object target, Boolean ignorNull, Class<?> editable, String... ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); }//from w w w . java 2 s . co m actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null); for (PropertyDescriptor targetPd : targetPds) { Method writeMethod = targetPd.getWriteMethod(); if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null) { Method readMethod = sourcePd.getReadMethod(); if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if (ignorNull != null && ignorNull) { if (value != null && (!"[]".equals(value.toString()))) {// ? if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } else { if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } } } }
From source file:org.shept.util.BeanUtilsExtended.java
/** * Merge the property values of the given source bean into the given target bean. * <p>Note: Only not-null values are merged into the given target bean. * Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * @param source the source bean/*from w w w.j a va 2 s .c o m*/ * @param target the target bean * @param editable the class (or interface) to restrict property setting to * @param ignoreProperties array of property names to ignore * @throws BeansException if the copying failed * @see BeanWrapper */ private static void mergeProperties(Object source, Object target, Class<?> editable, String[] ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); } actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null; for (PropertyDescriptor targetPd : targetPds) { if (targetPd.getWriteMethod() != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null && sourcePd.getReadMethod() != null) { try { Method readMethod = sourcePd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if (value != null) { Method writeMethod = targetPd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } catch (Throwable ex) { throw new FatalBeanException("Could not copy properties from source to target", ex); } } } } }
From source file:com.nextep.designer.dbgm.ui.layout.DiagramLayoutService.java
/** * Layout the diagram//from w ww. j a va 2 s. c o m * @param diagram */ public static void autoLayout(IDiagram diagram) { int x = 1; int y = 1; // Getting diagram items List<IDiagramItem> items = new ArrayList<IDiagramItem>(diagram.getItems()); // Computing reverse dependencies map (one shot, multiple uses) final MultiValueMap invRefMap = CorePlugin.getService(IReferenceManager.class) .getReverseDependenciesMap(IElementType.getInstance(IBasicTable.TYPE_ID)); // Shuffling first, since our comparator is not deterministic, we mix our // items to provide multiple layout suggestions Collections.shuffle(items); // Sorting items Collections.sort(items, new TableDependencyComparator(invRefMap)); // Hashing diagram items Map<IReference, IDiagramItem> refMap = new HashMap<IReference, IDiagramItem>(); for (IDiagramItem i : items) { if (!(i.getItemModel() instanceof IBasicTable)) { continue; } refMap.put(((IBasicTable) i.getItemModel()).getReference(), i); } // Building tree DependencyTree<IDiagramItem> rootTree = new DependencyTree<IDiagramItem>(null); List<IDiagramItem> processed = new ArrayList<IDiagramItem>(); for (IDiagramItem i : items) { if (!processed.contains(i)) { rootTree.addChild(buildTree(i, items, processed, refMap, invRefMap)); } } // Sorting tree // DependencyTreeComparator comparator = new DependencyTreeComparator(rootTree); //// Collections.sort(rootTree.getChildren(),comparator); // DependencyTree next = comparator.getNextTreeToDisplay(); // while(next!=null) { // y = position(next,x,y) + V_SPACING; // next = comparator.getNextTreeToDisplay(); // } for (DependencyTree<IDiagramItem> treeItem : rootTree.getChildren()) { y = position(treeItem, x, y) + V_SPACING; } // // Parent tables referenced via foreign keys // for(IKeyConstraint k : table.getConstraints()) { // switch(k.getConstraintType()) { // case FOREIGN: // ForeignKeyConstraint fk = (ForeignKeyConstraint)k; // if(fk.getRemoteConstraint()!=null) { // IBasicTable t = fk.getRemoteConstraint().getConstrainedTable(); // if(t!=null) { // final IDiagramItem fkItem = createTableItem(fk.getRemoteConstraint().getConstrainedTable(),x,y); // parentItems.add(fkItem); // // Adjusting position variables // y+=fkItem.getHeight()+V_SPACING; // // MAnaging max height / width // if(y>maxHeight) maxHeight = y; // if(fkItem.getWidth()> maxWidth) { // maxWidth = fkItem.getWidth(); // } // // Registering item to diagrm // d.addItem(fkItem); // } // } // break; // } // } // leftHeight = maxHeight; // // Central table (current) // x+=maxWidth + H_SPACING; // y=1; // // IDiagramItem tabItem = new DiagramItem(VersionHelper.getVersionable(table),x,y); // tabItem.setHeight(40 + 21 * table.getColumns().size()); // d.addItem(tabItem); // // // Child tables // x+=tabItem.getWidth() + H_SPACING; // y=1; // // Collection<IReferencer> children = CorePlugin.getService(IReferenceManager.class).getReverseDependencies(table); // for(IReferencer r : children) { // if(r instanceof IBasicTable) { // final IDiagramItem i = createTableItem((IBasicTable)r,x,y); // childItems.add(i); // y+=i.getHeight()+V_SPACING; // if(y>maxHeight) maxHeight = y; // d.addItem(i); // } // } // // // Repositioning central table Y // tabItem.setYStart(maxHeight/2 - tabItem.getHeight()/2); // // // Repositioning minimum height elements // if(leftHeight<maxHeight) { // repositionItem(parentItems, leftHeight, maxHeight); // } else { // repositionItem(childItems, y, maxHeight); // } }
From source file:com.pureinfo.tgirls.servlet.GetPic.java
public static Photo getPic(String _type, List<String> _exincludeIds) { List<Photo> cacheList = GetPic.getPicList(_type); if (cacheList == null) { return null; }/* w ww . j a v a2 s . c o m*/ Photo p = null; for (int i = 0; i < cacheList.size(); i++) { p = cacheList.get(i); if (_exincludeIds.contains(String.valueOf(p.getId()))) { logger.debug("id[" + p.getId() + "] exists."); continue; } else { logger.debug("add id[" + p.getId() + "]"); _exincludeIds.add(String.valueOf(p.getId())); return p; } } int i = new Random().nextInt(cacheList.size()); logger.debug("all ids exists, get random one: " + i + "/" + cacheList.size()); return cacheList.get(i); }