Java Code Examples for java.util.Collection

The following are top voted examples for showing how to use java.util.Collection. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dubbocloud   File: ConfigTest.java   View source code 6 votes vote down vote up
@Test
public void testGenericServiceConfig() throws Exception {
    ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
    service.setApplication(new ApplicationConfig("test"));
    service.setRegistry(new RegistryConfig("mock://localhost"));
    service.setInterface(DemoService.class.getName());
    service.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN);
    service.setRef(new GenericService(){

        public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
            return null;
        }
    });
    try {
        service.export();
        Collection<Registry> collection = MockRegistryFactory.getCachedRegistry();
        MockRegistry registry = (MockRegistry)collection.iterator().next();
        URL url = registry.getRegistered().get(0);
        Assert.assertEquals(Constants.GENERIC_SERIALIZATION_BEAN, url.getParameter(Constants.GENERIC_KEY));
    } finally {
        MockRegistryFactory.cleanCachedRegistry();
        service.unexport();
    }
}
 
Example 2
Project: smart-testing   File: DeleteAndRenameTestSelectionStrategyFunctionalTest.java   View source code 6 votes vote down vote up
@Test
public void should_run_renamed_test_as_changed_and_ignore_deleted_one() throws Exception {
    // given
    final Project project = testBed.getProject();
    project.configureSmartTesting().executionOrder(CHANGED).inMode(SELECTING).enable();

    final Collection<TestResult> expectedTestResults =
        project.applyAsCommits("Deletes one test", "Renames unit test");

    // when
    final TestResults actualTestResults =
        project.build("junit/core").options().withSystemProperties("scm.range.head", "HEAD", "scm.range.tail", "HEAD~~").configure().run();

    // then
    assertThat(actualTestResults.accumulatedPerTestClass()).containsAll(expectedTestResults)
        .hasSameSizeAs(expectedTestResults);
}
 
Example 3
Project: hdfs-shell   File: XScriptCommands.java   View source code 6 votes vote down vote up
/**
 * Opens the given script for reading
 *
 * @param script the script to read (required)
 * @return a non-<code>null</code> input stream
 */
private InputStream openScript(final File script) {
	try {
		return new BufferedInputStream(new FileInputStream(script));
	} catch (final FileNotFoundException fnfe) {
		// Try to find the script via the classloader
		final Collection<URL> urls = findResources(script.getName());

		// Handle search failure
		Assert.notNull(urls, "Unexpected error looking for '" + script.getName() + "'");

		// Handle the search being OK but the file simply not being present
		Assert.notEmpty(urls, "Script '" + script + "' not found on disk or in classpath");
		Assert.isTrue(urls.size() == 1, "More than one '" + script + "' was found in the classpath; unable to continue");
		try {
			return urls.iterator().next().openStream();
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}
}
 
Example 4
Project: JavaTools   File: ThreadPoolImpl.java   View source code 6 votes vote down vote up
@Override
public <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks, 
        long timeout, TimeUnit timeoutUnit) {
    if (null == tasks) {
        //todo throw exception
        return null;
    }
    if (timeout < 0) {
        //todo throw exception
        return null;
    }

    try {
        return executorService.invokeAll(tasks, timeout, timeoutUnit);
    } catch (InterruptedException e) {
        logger.info("invoke task list occurs error",e);
    }
    return null;
}
 
Example 5
Project: apache-tomcat-7.0.73-with-comment   File: Snake.java   View source code 6 votes vote down vote up
public synchronized void update(Collection<Snake> snakes) {
    Location nextLocation = head.getAdjacentLocation(direction);
    if (nextLocation.x >= SnakeWebSocketServlet.PLAYFIELD_WIDTH) {
        nextLocation.x = 0;
    }
    if (nextLocation.y >= SnakeWebSocketServlet.PLAYFIELD_HEIGHT) {
        nextLocation.y = 0;
    }
    if (nextLocation.x < 0) {
        nextLocation.x = SnakeWebSocketServlet.PLAYFIELD_WIDTH;
    }
    if (nextLocation.y < 0) {
        nextLocation.y = SnakeWebSocketServlet.PLAYFIELD_HEIGHT;
    }
    if (direction != Direction.NONE) {
        tail.addFirst(head);
        if (tail.size() > length) {
            tail.removeLast();
        }
        head = nextLocation;
    }

    handleCollisions(snakes);
}
 
Example 6
Project: garlicts   File: CollectionUtil.java   View source code 6 votes vote down vote up
/**
 * 检查指定的集合/数组/枚举为空
 * <p>
 * 此方法可以处理如下对象:
 * <ul>
 * <li>Collection
 * <li>Map
 * <li>Array
 * <li>Enumeration
 * </ul>
 * <p>
 *
 * @param object
 * @return true
 * @throws IllegalArgumentException
 * @since 1.0
 */
public static boolean isEmpty(final Object object) {
	if (object == null) {
		return true;
	} else if (object instanceof Collection<?>) {
		return ((Collection<?>) object).isEmpty();
	} else if (object instanceof Map<?, ?>) {
		return ((Map<?, ?>) object).isEmpty();
	} else if (object instanceof Object[]) {
		return ((Object[]) object).length == 0;
	} else if (object instanceof Iterator<?>) {
		return ((Iterator<?>) object).hasNext() == false;
	} else if (object instanceof Enumeration<?>) {
		return ((Enumeration<?>) object).hasMoreElements() == false;
	} else {
		try {
			return Array.getLength(object) == 0;
		} catch (final IllegalArgumentException ex) {
			throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
		}
	}
}
 
Example 7
Project: googles-monorepo-demo   File: AbstractMapBasedMultimap.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>The returned collection is immutable.
 */
@Override
public Collection<V> removeAll(@Nullable Object key) {
  Collection<V> collection = map.remove(key);

  if (collection == null) {
    return createUnmodifiableEmptyCollection();
  }

  Collection<V> output = createCollection();
  output.addAll(collection);
  totalSize -= collection.size();
  collection.clear();

  return unmodifiableCollectionSubclass(output);
}
 
Example 8
Project: scanning   File: LevelRunner.java   View source code 6 votes vote down vote up
/**
 * Get the scannables, ordered by level, lowest first
 * @param position
 * @return
 * @throws ScanningException
 */
protected Map<Integer, List<L>> getLevelOrderedDevices() throws ScanningException {
	if (sortedObjects!=null && sortedObjects.get()!=null) return sortedObjects.get();

	final Collection<L> devices = getDevices();

	if (devices == null) return Collections.emptyMap();

	final Map<Integer, List<L>> devicesByLevel = new TreeMap<>();
	for (L object : devices) {
		final int level = object.getLevel();

		if (!devicesByLevel.containsKey(level)) devicesByLevel.put(level, new ArrayList<L>(7));
		devicesByLevel.get(level).add(object);
	}
	if (isLevelCachingAllowed()) sortedObjects = new SoftReference<Map>(devicesByLevel);

	return devicesByLevel;
}
 
Example 9
Project: alevin-svn2   File: GraphMetrics.java   View source code 6 votes vote down vote up
/**
 * Test whether a graph is connected.
 * 
 * @param graph to test.
 * @return true if graph is connected, false otherwise.
 */
public static boolean connected(Graph<IVertex, IEdge> graph) {
	DijkstraShortestPath<IVertex, IEdge> sp = new DijkstraShortestPath<>(graph);
	Collection<IVertex> verts = graph.getVertices();

	// forall vertA, vertB in graph exists connecting path <=> graph is connected
	for (IVertex vertA : verts) {
		for (IVertex vertB : verts) {
			if (sp.getDistance(vertA, vertB) == null) {
				return false;
			}
		}
	}

	return true;
}
 
Example 10
Project: hashsdn-controller   File: ConfigurationImplTest.java   View source code 6 votes vote down vote up
@Test
public void testRemoveMemberReplicaForShard() {
    configuration.removeMemberReplicaForShard("default", MEMBER_2);
    String shardName = configuration.getShardNameForModule("default");
    assertEquals("ModuleShardName", "default", shardName);
    ShardStrategy shardStrategy = configuration.getStrategyForModule("default");
    assertNull("ModuleStrategy", shardStrategy);
    Collection<MemberName> members = configuration.getMembersFromShardName("default");
    assertEquals("Members", ImmutableSortedSet.of(MEMBER_1, MEMBER_3),
        ImmutableSortedSet.copyOf(members));

    configuration.removeMemberReplicaForShard("non-existent", MEMBER_2);
    Set<String> shardNames = configuration.getAllShardNames();
    assertEquals("ShardNames", ImmutableSortedSet.of("people-1", "cars-1", "test-1", "default"),
        ImmutableSortedSet.copyOf(shardNames));
}
 
Example 11
Project: Equella   File: InitialiserServiceImpl.java   View source code 6 votes vote down vote up
private Object processCollection(Object parent, Property property, Collection<?> col,
	IdentityHashMap<Object, Object> map, Map<Object, Object> evictees, InitialiserCallback callback,
	List<PropertySet> propsToSet)
{
	Collection<Object> newList = getSupportedCollection(col);

	for( Object colObj : col )
	{
		if( colObj != null )
		{
			Object newObj = processObject(parent, property, colObj, null, map, evictees, callback, propsToSet);
			newList.add(newObj);
		}
	}

	map.put(col, newList);
	return newList;
}
 
Example 12
Project: letv   File: LinkedBlockingDeque.java   View source code 6 votes vote down vote up
public LinkedBlockingDeque(Collection<? extends E> c) {
    this(Integer.MAX_VALUE);
    ReentrantLock lock = this.lock;
    lock.lock();
    try {
        for (E e : c) {
            if (e == null) {
                throw new NullPointerException();
            } else if (!linkLast(new Node(e))) {
                throw new IllegalStateException("Deque full");
            }
        }
    } finally {
        lock.unlock();
    }
}
 
Example 13
Project: incubator-netbeans   File: ImageNavigatorPanel.java   View source code 6 votes vote down vote up
@Override
public void panelActivated(Lookup context) {
    // lookup context and listen to result to get notified about context changes
    currentContext = context.lookup(MY_DATA);
    currentContext.addLookupListener(getContextListener());
    // get actual data and recompute content
    Collection data = currentContext.allInstances();
    currentDataObject = getDataObject(data);
    if (currentDataObject == null) {
        return;
    }
    if (fileChangeListener == null) {
        fileChangeListener = new ImageFileChangeAdapter();
    }
    currentDataObject.getPrimaryFile().addFileChangeListener(fileChangeListener);
    setNewContent(currentDataObject);
}
 
Example 14
Project: traccar-service   File: ReportResource.java   View source code 5 votes vote down vote up
@Path("events")
@GET
public Collection<Event> getEvents(
        @QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds,
        @QueryParam("type") final List<String> types,
        @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException {
    return Events.getObjects(getUserId(), deviceIds, groupIds, types,
            DateUtil.parseDate(from), DateUtil.parseDate(to));
}
 
Example 15
Project: HTAPBench   File: JSONArray.java   View source code 5 votes vote down vote up
/**
 * Construct a JSONArray from a collection of beans.
 * The collection should have Java Beans.
 */

public JSONArray(Collection<?> collection, boolean includeSuperClass) {
    this.myArrayList = new ArrayList<Object>();
    if(collection != null) {
        for (Iterator<?> iter = collection.iterator(); iter.hasNext();) {
            this.myArrayList.add(new JSONObject(iter.next(),includeSuperClass));    
        }
    }
}
 
Example 16
Project: incubator-netbeans   File: SemanticHighlighter.java   View source code 5 votes vote down vote up
public void setHighlights(final Document doc, final Collection<int[]> highlights) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            OffsetsBag bag = new OffsetsBag(doc);
            Coloring unused = ColoringAttributes.add(ColoringAttributes.empty(), ColoringAttributes.UNUSED);
            for (int[] highlight : highlights) {
                bag.addHighlight(highlight[0], highlight[1], ColoringManager.getColoringImpl(unused));
            }
            getImportHighlightsBag(doc).setHighlights(bag);
        }
    });
}
 
Example 17
Project: scanning   File: ScannableViewer.java   View source code 5 votes vote down vote up
public void refresh() throws Exception {
	final Collection<DeviceInformation<?>> scannables = cservice.getDeviceInformation();
	ScannableContentProvider prov = (ScannableContentProvider)viewer.getContentProvider();
       for (DeviceInformation<?> info : scannables) {
		if (info.isActivated()) prov.add(info.getName());
	}
       viewer.refresh();
}
 
Example 18
Project: rapidminer   File: SeriesChartPlotter.java   View source code 5 votes vote down vote up
@Override
public Collection<String> resolveXAxis(int axisIndex) {
	if (axis[INDEX] != -1) {
		return Collections.singletonList(dataTable.getColumnName(axis[INDEX]));
	} else {
		return Collections.singletonList(SERIESINDEX_LABEL);
	}
}
 
Example 19
Project: n4js   File: ModifierUtils.java   View source code 5 votes vote down vote up
/**
 * Converts an {@link N4Modifier} from the AST to a {@link TypeAccessModifier} in the types model.
 */
public static final TypeAccessModifier convertToTypeAccessModifier(Collection<? extends N4Modifier> modifiers,
		List<Annotation> annotations) {
	if (modifiers.contains(N4Modifier.PRIVATE)) {
		return TypeAccessModifier.PRIVATE;
	} else if (modifiers.contains(N4Modifier.PROJECT)) {
		return TypeAccessModifier.PROJECT;
	} else if (modifiers.contains(N4Modifier.PUBLIC)) {
		return annotations.stream().anyMatch(a -> ANN_INTERNAL.equals(a.getName()))
				? TypeAccessModifier.PUBLIC_INTERNAL
				: TypeAccessModifier.PUBLIC;
	} else {
		return TypeAccessModifier.UNDEFINED;
	}
}
 
Example 20
Project: lams   File: IdentitySet.java   View source code 5 votes vote down vote up
public boolean addAll(Collection c) {
	Iterator it = c.iterator();
	boolean changed = false;
	while ( it.hasNext() ) {
		if ( this.add( it.next() ) ) {
			changed = true;
		}
	}
	return changed;
}
 
Example 21
Project: ditb   File: ReplicationAdmin.java   View source code 5 votes vote down vote up
/**
 * Remove some table-cfs from config of the specified peer
 * @param id a short name that identifies the cluster
 * @param tableCfs A map from tableName to column family names
 * @throws ReplicationException
 */
public void removePeerTableCFs(String id, Map<TableName, ? extends Collection<String>> tableCfs)
    throws ReplicationException {
  if (tableCfs == null) {
    throw new ReplicationException("tableCfs is null");
  }

  Map<TableName, List<String>> preTableCfs = parseTableCFsFromConfig(getPeerTableCFs(id));
  if (preTableCfs == null) {
    throw new ReplicationException("Table-Cfs for peer" + id + " is null");
  }
  for (Map.Entry<TableName, ? extends Collection<String>> entry: tableCfs.entrySet()) {
    TableName table = entry.getKey();
    Collection<String> removeCfs = entry.getValue();
    if (preTableCfs.containsKey(table)) {
      List<String> cfs = preTableCfs.get(table);
      if (cfs == null && removeCfs == null) {
        preTableCfs.remove(table);
      } else if (cfs != null && removeCfs != null) {
        Set<String> cfSet = new HashSet<String>(cfs);
        cfSet.removeAll(removeCfs);
        if (cfSet.isEmpty()) {
          preTableCfs.remove(table);
        } else {
          preTableCfs.put(table, Lists.newArrayList(cfSet));
        }
      } else if (cfs == null && removeCfs != null) {
        throw new ReplicationException("Cannot remove cf of table: " + table
            + " which doesn't specify cfs from table-cfs config in peer: " + id);
      } else if (cfs != null && removeCfs == null) {
        throw new ReplicationException("Cannot remove table: " + table
            + " which has specified cfs from table-cfs config in peer: " + id);
      }
    } else {
      throw new ReplicationException("No table: " + table + " in table-cfs config of peer: " + id);
    }
  }
  setPeerTableCFs(id, preTableCfs);
}
 
Example 22
Project: kafka-0.11.0.0-src-with-comment   File: RecordHeaders.java   View source code 5 votes vote down vote up
public RecordHeaders(Iterable<Header> headers) {
    //Use efficient copy constructor if possible, fallback to iteration otherwise
    if (headers == null) {
        this.headers = new ArrayList<>();
    } else if (headers instanceof RecordHeaders) {
        this.headers = new ArrayList<>(((RecordHeaders) headers).headers);
    } else if (headers instanceof Collection) {
        this.headers = new ArrayList<>((Collection<Header>) headers);
    } else {
        this.headers = new ArrayList<>();
        for (Header header : headers)
            this.headers.add(header);
    }
}
 
Example 23
Project: gate-core   File: ControllerPersistence.java   View source code 5 votes vote down vote up
/**
 * Creates a new object from the data contained. This new object is supposed
 * to be a copy for the original object used as source for data extraction.
 */
@SuppressWarnings("unchecked")
@Override
public Object createObject()throws PersistenceException,
                                   ResourceInstantiationException{
  Controller controller = (Controller)super.createObject();
  if(controller.getPRs().isEmpty()){
    prList = PersistenceManager.getTransientRepresentation(
            prList,resourceName,initParamOverrides);
    controller.setPRs((Collection<ProcessingResource>)prList);
  }
  return controller;
}
 
Example 24
Project: ralasafe   File: UserRoleAction.java   View source code 5 votes vote down vote up
protected void doGet( HttpServletRequest req, HttpServletResponse resp )
			throws ServletException, IOException {
		String strUserId=req.getParameter( "userId" );
		Object userId=WebUtil.convertUserId( req, strUserId );
		
		UserManager userManager=WebUtil.getUserManager( req );
		User user=new User();
		user.setId( userId );
		user=userManager.selectById( user );
		
		UserRoleManager userRoleManager=WebUtil.getUserRoleManager( req );
		Collection assignedRoles=userRoleManager.getRoles( userId );
		
		Set assignedRoleIds=new HashSet();
		for( Iterator iter=assignedRoles.iterator(); iter.hasNext(); ) {
			Role role=(Role) iter.next();
			assignedRoleIds.add( new Integer(role.getId()) );
		}
		
		// search key
		String searchName=req.getParameter( "name" );
/*		if(searchName!=null){
			searchName=new String(searchName.getBytes("ISO-8859-1"),"UTF-8");		        
		}*/
		
		RoleManager roleMng=WebUtil.getRoleManager( req );
		Collection roles=null;
		if( StringUtil.isEmpty( searchName ) ) {
			roles=roleMng.getAllRoles();
		} else {
			roles=roleMng.getLikelyRoles( searchName );
		}
		
		req.setAttribute( "roles", roles );
		req.setAttribute( "assignedRoleIds", assignedRoleIds );
		req.setAttribute( "user", user );
		
		WebUtil.forward( req, resp, "/ralasafe/user/userRoles.jsp" );
	}
 
Example 25
Project: incubator-netbeans   File: M2ConfigProvider.java   View source code 5 votes vote down vote up
private synchronized Collection<M2Configuration> getConfigurations(boolean skipProfiles) {
    if (profiles == null && !skipProfiles) {
        profiles = createProfilesList();
    }
    if (shared == null) {
        //read from auxconf
        shared = readConfigurations(aux, project.getProjectDirectory(), true);
    }
    if (nonshared == null) {
        //read from auxconf
        nonshared = readConfigurations(aux, project.getProjectDirectory(), false);
    }
    Collection<M2Configuration> toRet = new TreeSet<M2Configuration>();
    toRet.add(DEFAULT);
    toRet.addAll(shared);
    toRet.addAll(nonshared);
    if (!skipProfiles) {
        //prevent duplicates in the list
        Iterator<M2Configuration> it = profiles.iterator();
        while (it.hasNext()) {
            M2Configuration c = it.next();
            if (!toRet.contains(c)) {
                toRet.add(c);
            } else {
                it.remove();
            }
        }
    }
    return toRet;
    
}
 
Example 26
Project: fresco_floodlight   File: IterableUtils.java   View source code 5 votes vote down vote up
/**
 * Convert an Iterable to a Collection (ArrayList under the hood). All items in the
 * Iterable will be retained.
 * @param i
 * @return
 */
public static <T> Collection<T> toCollection(Iterable<T> i) {
	if (i == null) {
		throw new IllegalArgumentException("Iterable 'i' cannot be null");
	}
	Collection<T> c = new ArrayList<T>();
	for (T t : i) {
		c.add(t);
	}
	return c;
}
 
Example 27
Project: atbash-octopus   File: SimpleAuthorizationInfo.java   View source code 5 votes vote down vote up
/**
 * Adds (assigns) multiple permissions to those associated directly with the account.  If the account doesn't yet
 * have any string-based permissions, a  new permissions collection (a Set&lt;String&gt;) will be created automatically.
 *
 * @param permissions the permissions to add to those associated directly with the account.
 */
public void addStringPermissions(Collection<String> permissions) {
    if (stringPermissions == null) {
        stringPermissions = new HashSet<>();
    }
    stringPermissions.addAll(permissions);
}
 
Example 28
Project: alevin-svn2   File: Utils.java   View source code 5 votes vote down vote up
public static <T extends NetworkEntity<?>> boolean equals(Collection<T> ts,
		Collection<T> us) {
	if (ts.size() != us.size()) {
		return false;
	}
	for (T t : ts) {
		if (!contains(t, us)) {
			return false;
		}
	}
	return true;
}
 
Example 29
Project: openjdk-jdk10   File: OptionParser.java   View source code 5 votes vote down vote up
public OptionSpecBuilder acceptsAll( Collection<String> options, String description ) {
    if ( options.isEmpty() )
        throw new IllegalArgumentException( "need at least one option" );

    ensureLegalOptions( options );

    return new OptionSpecBuilder( this, options, description );
}
 
Example 30
Project: Spigot-Attribute-Remover   File: SerialVersionUIDAdder.java   View source code 5 votes vote down vote up
/**
 * Sorts the items in the collection and writes it to the data output stream
 * 
 * @param itemCollection
 *            collection of items
 * @param dos
 *            a <code>DataOutputStream</code> value
 * @param dotted
 *            a <code>boolean</code> value
 * @exception IOException
 *                if an error occurs
 */
private static void writeItems(final Collection<Item> itemCollection,
        final DataOutput dos, final boolean dotted) throws IOException {
    int size = itemCollection.size();
    Item[] items = itemCollection.toArray(new Item[size]);
    Arrays.sort(items);
    for (int i = 0; i < size; i++) {
        dos.writeUTF(items[i].name);
        dos.writeInt(items[i].access);
        dos.writeUTF(dotted ? items[i].desc.replace('/', '.')
                : items[i].desc);
    }
}
 
Example 31
Project: alfresco-data-model   File: FolderTypeDefintionWrapper.java   View source code 5 votes vote down vote up
@Override
public Collection<PropertyDefinitionWrapper> getProperties(boolean update)
{
    if (update)
    {
        return getProperties();
    }
    else
    {
        return propertiesById.values();
    }
}
 
Example 32
Project: HCFCore   File: AbstractMapBag.java   View source code 5 votes vote down vote up
/**
 * Remove any members of the bag that are not in the given bag, respecting
 * cardinality.
 *
 * @param coll the collection to retain
 * @return true if this call changed the collection
 */
@Override
public boolean retainAll(final Collection<?> coll) {
    if (coll instanceof Bag) {
        return retainAll((Bag<?>) coll);
    }
    return retainAll(new HashBag<Object>(coll));
}
 
Example 33
Project: s-store   File: AbstractPartitioner.java   View source code 5 votes vote down vote up
/**
 * Creates the list of Statement catalog keys that we want to let
 * through our filter
 * 
 * @param tables
 * @throws Exception
 */
protected void addProcedures(Collection<Procedure> procedures) throws Exception {
    // Iterate through all of the procedures/queries and figure out
    // which
    // ones we'll actually want to look at
    for (Procedure catalog_proc : procedures) {
        for (Statement catalog_stmt : catalog_proc.getStatements()) {
            this.stmt_cache.add(CatalogKey.createKey(catalog_stmt));
        } // FOR
    } // FOR
    return;
}
 
Example 34
Project: smarti   File: StopwordlistConfiguration.java   View source code 5 votes vote down vote up
private Map<String,Collection<String>> parseStopwords(String location, Locale lang) {
    if(location == null) return null;
    Resource resource = rLoader.getResource(location);
    if(resource == null){
        log.warn("unable to load resource from location '{}' as configured for language '{}'", location, lang);
        return null;
    }
    Locale locale = lang == null ? Locale.ROOT : lang;
    Map<String,Collection<String>> stopwords = new HashMap<>();
    try (InputStream in = resource.getInputStream()){
        IOUtils.lineIterator(in, UTF8).forEachRemaining(line -> {
            if(StringUtils.isNoneBlank(line)){
                line = line.trim();
                if(line.charAt(0) != '#') {
                    String key = line.toLowerCase(locale);
                    Collection<String> values = stopwords.computeIfAbsent(key, (k) -> new LinkedHashSet<String>());
                    values.add(line);
                } //else comment
            }
        });
    } catch (IOException e) {
        log.warn("Unable to parsed stopwords for language '{}' from resource '{}' ({} - {})",
                lang, location, e.getClass().getSimpleName(), e.getMessage());
        log.debug("STACKTRACE", e);
    }
    return stopwords;
}
 
Example 35
Project: ttc2017smartGrids   File: ProcedureImpl.java   View source code 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
	switch (featureID) {
		case InfAssetsPackage.PROCEDURE__KIND:
			setKind((ProcedureKind)newValue);
			return;
		case InfAssetsPackage.PROCEDURE__SEQUENCE_NUMBER:
			setSequenceNumber((String)newValue);
			return;
		case InfAssetsPackage.PROCEDURE__LIMITS:
			getLimits().clear();
			getLimits().addAll((Collection<? extends Limit>)newValue);
			return;
		case InfAssetsPackage.PROCEDURE__COMPATIBLE_UNITS:
			getCompatibleUnits().clear();
			getCompatibleUnits().addAll((Collection<? extends CompatibleUnit>)newValue);
			return;
		case InfAssetsPackage.PROCEDURE__PROCEDURE_DATA_SETS:
			getProcedureDataSets().clear();
			getProcedureDataSets().addAll((Collection<? extends ProcedureDataSet>)newValue);
			return;
		case InfAssetsPackage.PROCEDURE__PROCEDURE_VALUES:
			getProcedureValues().clear();
			getProcedureValues().addAll((Collection<? extends UserAttribute>)newValue);
			return;
		case InfAssetsPackage.PROCEDURE__CORPORATE_CODE:
			setCorporateCode((String)newValue);
			return;
		case InfAssetsPackage.PROCEDURE__INSTRUCTION:
			setInstruction((String)newValue);
			return;
	}
	super.eSet(featureID, newValue);
}
 
Example 36
Project: s-store   File: CatalogKeyOldVersion.java   View source code 5 votes vote down vote up
public static Collection<String> createKeys(Iterable<? extends CatalogType> map) {
    Collection<String> keys = new ArrayList<String>();
    for (CatalogType catalog_item : map) {
        keys.add(createKey(catalog_item));
    } // FOR
    return (keys);
}
 
Example 37
Project: incubator-netbeans   File: QueriesProperlyDefined.java   View source code 5 votes vote down vote up
private static AnnotationMirror getFirstAnnotationFromGivenSet(TypeElement subject,
        Collection<String> annotationClasses) {

    for (String annClass : annotationClasses) {
        AnnotationMirror foundAnn = Utilities.findAnnotation(subject, annClass);

        if (foundAnn != null) {
            return foundAnn;
        }
    }

    return null;
}
 
Example 38
Project: amanda   File: Criterion.java   View source code 5 votes vote down vote up
@Override
public Predicate toPredicate(Criterion c, Root<?> r, CriteriaBuilder b) {
    Object o = c.getCompareTo();
    if(o == null)
        return r.get(c.getPropertyName()).in();
    if(o instanceof Collection)
        return r.get(c.getPropertyName()).in((Collection) o);
    throw new IllegalArgumentException(c.getPropertyName());
}
 
Example 39
Project: alfresco-remote-api   File: ResourceLocatorTests.java   View source code 5 votes vote down vote up
@Test(expected=org.alfresco.rest.framework.core.exceptions.NotFoundException.class)
public void testLocateRelationResource()
{
    Collection<String> relKeys = Arrays.asList("blacksheep","baaahh");
    Map<String,ResourceWithMetadata> embeds = locator.locateRelationResource(api,"sheep", relKeys, HttpMethod.GET);
    assertNotNull(embeds);
    
    relKeys = Arrays.asList("nonsense");
    embeds = locator.locateRelationResource(api,"sheep", relKeys, HttpMethod.GET);
    assertNotNull(embeds);
    
}
 
Example 40
Project: ttc2017smartGrids   File: ErpPersonnelImpl.java   View source code 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
	switch (featureID) {
		case InfERPSupportPackage.ERP_PERSONNEL__STATUS:
			setStatus((Status)newValue);
			return;
		case InfERPSupportPackage.ERP_PERSONNEL__ERP_PERSONS:
			getErpPersons().clear();
			getErpPersons().addAll((Collection<? extends ErpPerson>)newValue);
			return;
	}
	super.eSet(featureID, newValue);
}