Java Code Examples for java.util.Collections

The following are top voted examples for showing how to use java.util.Collections. 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 product more good examples.

Example 1
Project: lettuce   File: ReadFromImpl.java View source code Vote up 7 votes
@Override
public List<RedisNodeDescription> select(Nodes nodes) {
    for (RedisNodeDescription node : nodes) {
        if (node.getRole() == RedisInstance.Role.MASTER) {
            return Lists.newArrayList(node);
        }
    }
    return Collections.emptyList();
}
 
Example 2
Project: sphereMiners   File: SphereMiners2015.java View source code Vote up 7 votes
/**
 * Returns the enemies surrounding the given (owned!) sphere in a certain distance.
 *
 * @param sphere The sphere you want to find the surrounding enemies for
 * @return the sourrounding enemies of the given sphere
 */
protected final Set<Sphere> getSurroundingEnemies(Sphere sphere) {
    if (!ownSpheres.contains(sphere)) {
        return Collections.emptySet();
    }

    return allSpheres.stream()
                     .filter(s -> s.getOwner() != ownAI
                                  && s.getPosition().dist(sphere.getPosition())
                                          <= 
                                      constants.getSightDistance() + sphere.getRadius())
                     .collect(Collectors.toSet());
}
 
Example 3
Project: lettuce   File: ClusterSlotsParser.java View source code Vote up 6 votes
/**
 * Parse the output of the redis CLUSTER SLOTS command and convert it to a list of
 * [email protected] com.lambdaworks.redis.cluster.models.slots.ClusterSlotRange}
 * 
 * @param clusterSlotsOutput output of CLUSTER SLOTS command
 * @return List&gt;ClusterSlotRange&gt;
 */
public static List<ClusterSlotRange> parse(List<?> clusterSlotsOutput) {
    List<ClusterSlotRange> result = Lists.newArrayList();

    for (Object o : clusterSlotsOutput) {

        if (!(o instanceof List)) {
            continue;
        }

        List<?> range = (List<?>) o;
        if (range.size() < 2) {
            continue;
        }

        ClusterSlotRange clusterSlotRange = parseRange(range);
        result.add(clusterSlotRange);
    }

    Collections.sort(result, new Comparator<ClusterSlotRange>() {
        @Override
        public int compare(ClusterSlotRange o1, ClusterSlotRange o2) {
            return o1.getFrom() - o2.getFrom();
        }
    });

    return Collections.unmodifiableList(result);
}
 
Example 4
Project: SAPManagerPack   File: ModCntManPack.java View source code Vote up 6 votes
public ModCntManPack() {
    super(new ModMetadata());
    ModMetadata meta = super.getMetadata();
    meta.modId = ManPackLoadingPlugin.MOD_ID;
    meta.name = "SanAndreasPs Manager Pack CORE edition";
    meta.version = ManPackLoadingPlugin.MOD_VERSION;
    meta.authorList = Collections.singletonList("SanAndreasP");
    meta.description = "A helper coremod which is needed for all my mods.";
    meta.url = "http://www.minecraftforge.net/forum/index.php/topic,2828.0.html";
    meta.screenshots = new String[0];
    meta.logoFile = "";
}
 
Example 5
Project: virgo.kernel   File: AbstractArtifact.java View source code Vote up 6 votes
/**
 * [email protected]}
 */
public final Set<Artifact> getDependents() {
    Set<Artifact> dependents = new HashSet<Artifact>();

    Object[] dependencyDeterminers = this.dependencyDeterminerTracker.getServices();
    if (dependencyDeterminers != null) {
        for (Object dependencyDeterminer : dependencyDeterminers) {
            dependents.addAll(((DependencyDeterminer) dependencyDeterminer).getDependents(this));
        }
    }

    return Collections.unmodifiableSet(dependents);
}
 
Example 6
Project: jboss-dmr   File: ObjectModelValue.java View source code Vote up 6 votes
@Override
ModelValue protect() {
    final Map<String, ModelNode> map = this.map;
    for (final ModelNode node : map.values()) {
        node.protect();
    }
    return map.getClass() == LinkedHashMap.class ? new ObjectModelValue(Collections.unmodifiableMap(map)) : this;
}
 
Example 7
Project: jentrata-msh   File: FileSystem.java View source code Vote up 6 votes
/**
 * Retrieves a collection of File objects from a specified directory.
 * 
 * @param c the collection into which the result will be stored.
 * @param rootDir the directory to be searched.
 * @param isRecursive true if the search should be recursive.
 * @param type the file type to be searched.
 * @param pattern the filename's pattern for filtering the result. null if
 *            no filtering should be applied.
 * @return a collection of File objects resulted from the search.
 */
private Collection getFiles(Collection c, File rootDir,
        boolean isRecursive, int type, String pattern) {
    File[] subfiles = rootDir.listFiles();
    if (subfiles == null || subfiles.length == 0) {
        return Collections.EMPTY_LIST;
    }
    else {
        if (c == null) {
            c = new ArrayList();
        }
        for (int i = 0; i < subfiles.length; i++) {
            if (subfiles[i].isDirectory()) {
                if ((TYPE_DIR & type) == TYPE_DIR) {
                    if (accept(subfiles[i], pattern)) {
                        c.add(subfiles[i]);
                    }
                }
                if (isRecursive) {
                    getFiles(c, subfiles[i], isRecursive, type, pattern);
                }
            }
            else {
                if ((TYPE_FILE & type) == TYPE_FILE) {
                    if (accept(subfiles[i], pattern)) {
                        c.add(subfiles[i]);
                    }
                }
            }
        }
        return c;
    }
}
 
Example 8
Project: aws-toolkit-eclipse   File: AwsPluginAccountManager.java View source code Vote up 6 votes
/**
 * Returns a map of the names of all the accounts configured in the toolkit.
 */
public Map<String, String> getAllAccountNames() {
    Map<String, AccountInfo> allAccountInfo = getAllAccountInfo();
    if (allAccountInfo == null) {
        return Collections.<String, String>emptyMap();
    }

    Map<String, String> allAccountNames = new LinkedHashMap<String, String>();
    for (Entry<String, AccountInfo> entry : allAccountInfo.entrySet()) {
        allAccountNames.put(
                entry.getKey(),
                entry.getValue().getAccountName());
    }
    return allAccountNames;
}
 
Example 9
Project: jbosgi   File: JNDIServiceListener.java View source code Vote up 6 votes
@SuppressWarnings("unchecked")
private static Collection<String> getStringPlusProperty(Object property) {
    if (property instanceof Collection) {
        return (Collection<String>) property;
    } else if (property instanceof String[]) {
        return Arrays.asList((String[]) property);
    } else if (property instanceof String) {
        return Collections.singleton((String) property);
    }
    return Collections.emptyList();
}
 
Example 10
Project: richfaces   File: BaseExtendedVisitContext.java View source code Vote up 6 votes
@Override
public Collection<String> getSubtreeIdsToVisit(UIComponent component) {

    // Make sure component is a NamingContainer
    if (!(component instanceof NamingContainer)) {
        throw new IllegalArgumentException("Component is not a NamingContainer: " + component);
    }

    if (hasImplicitSubtreeIdsToVisit(component)) {
        return VisitContext.ALL_IDS;
    }

    String clientId = buildExtendedClientId(component);

    Collection<String> result;

    Set<String> ids = subtreeIds.get(clientId);
    if (!ids.isEmpty()) {
        result = Collections.unmodifiableCollection(ids);
    } else {
        // returned collection should be non-modifiable
        result = Collections.emptySet();
    }

    return result;
}
 
Example 11
Project: BioWiki   File: ArrayAdapter.java View source code Vote up 6 votes
/**
 * Removes all elements at the specified locations in the [email protected] List} .
 *
 * @param locations the collection of indexes to remove.
 * @return a collection containing the removed objects.
 */
public Collection<T> removePositions(final Collection<Integer> locations) {
    ArrayList<T> removedItems = new ArrayList<T>();

    ArrayList<Integer> locationsList = new ArrayList<Integer>(locations);
    Collections.sort(locationsList);
    Collections.reverse(locationsList);
    for (int location : locationsList) {
        removedItems.add(mItems.remove(location));
    }
    notifyDataSetChanged();
    return removedItems;
}
 
Example 12
Project: tapestry-model   File: DefaultExclusionsBMModifierTest.java View source code Vote up 6 votes
@Test
void exclude()
{

	BeanModel model = mockBeanModel();
	DescriptorService descriptorService = newMock(DescriptorService.class);

	TynamoClassDescriptorImpl classDescriptor = new TynamoClassDescriptorImpl(Foo.class);
	IdentifierDescriptor idProp = new IdentifierDescriptorImpl(Foo.class, "id", String.class);
	TynamoPropertyDescriptor multiWordProp =
			new TynamoPropertyDescriptorImpl(Foo.class, "multiWordProperty", String.class);

	CollectionDescriptor bazzesDescriptor = new CollectionDescriptor(Foo.class, "bazzes", Set.class);
	bazzesDescriptor.setElementType(Baz.class);

	Collections.addAll(classDescriptor.getPropertyDescriptors(), idProp, multiWordProp, bazzesDescriptor);

	expect(model.exclude("id", "bazzes")).andReturn(model);
	expect(model.getBeanType()).andReturn(Foo.class);
	expect(descriptorService.getClassDescriptor(Foo.class)).andReturn(classDescriptor);

	replay();

	DefaultExclusionsBMModifier modifier = new DefaultExclusionsBMModifier(descriptorService);
	modifier.modify(model, PageType.LIST.getContextKey());

	verify();

}
 
Example 13
Project: apache-james-mime4j-groundhog   File: Entity.java View source code Vote up 6 votes
/**
 * Sets the specified multipart as body of this entity. Also sets the
 * content type accordingly and creates a message boundary string. A
 * <code>Header</code> is created if this entity does not already have
 * one.
 * 
 * @param multipart
 *            the multipart to set as body.
 */
public void setMultipart(Multipart multipart) {
    String mimeType = "multipart/" + multipart.getSubType();
    Map<String, String> parameters = Collections.singletonMap("boundary",
            MimeUtil.createUniqueBoundary());

    setBody(multipart, mimeType, parameters);
}
 
Example 14
Project: aipo   File: CreateProjectData.java View source code Vote up 6 votes
private static boolean setInsertUpdate(EipTProjectTask task,
    EipTProject project) {
  List<Integer> trackers = Arrays.asList(1, 2, 3);
  Collections.shuffle(trackers);
  String taskName = "???" + new Date().getTime();
  String desc = "?????" + new Date().getTime();
  List<Integer> status = Arrays.asList(1, 2, 3, 4, 5, 6);
  Collections.shuffle(status);
  List<Integer> priority = Arrays.asList(1, 2, 3);
  Collections.shuffle(priority);

  // ??????ID
  task.setEipTProject(project);
  // ??
  task.setTracker(String.valueOf(trackers.get(0)));
  // ????
  task.setTaskName(taskName);
  // ??
  task.setExplanation(desc);
  // ?????
  task.setStatus(String.valueOf(status.get(0)));
  // ???
  task.setPriority(String.valueOf(priority.get(0)));

  if (true) {
    // ???????????????

    // ?????
    task.setStartPlanDate(new Date());
    // ?????
    task.setEndPlanDate(new Date());
    // ?????
    task.setStartDate(ProjectUtils.getEmptyDate());
    // ?????
    task.setEndDate(ProjectUtils.getEmptyDate());
    // ????
    task.setPlanWorkload(new BigDecimal(4.0));
    // ???
    task.setProgressRate(0);
  }
  // ???
  task.setUpdateUserId(MASTER_USER_ID);
  // ???
  task.setUpdateDate(Calendar.getInstance().getTime());

  return true;
}
 
Example 15
Project: apache-james-mime4j-groundhog   File: StringArrayMap.java View source code Vote up 6 votes
/**
 * <p>Converts the given object into a string enumeration. The object may be either of:
 * <ul>
 *   <li>a string, which is returned as an enumeration with one element</li>
 *   <li>a list of strings, which is being converted into a string enumeration</li>
 *   <li>an array of strings, which is being converted into a string enumeration</li>
 * </ul>
 */
public static Enumeration<String> asStringEnum(final Object pValue) {
    if (pValue == null) {
        return null;
    }
    if (pValue instanceof String) {
        return new Enumeration<String>(){
            private Object value = pValue;
            public boolean hasMoreElements() {
                return value != null;
            }
            public String nextElement() {
                if (value == null) {
                    throw new NoSuchElementException();
                }
                final String s = (String) value;
                value = null;
                return s;
            }
        };
    }
    if (pValue instanceof String[]) {
        final String[] values = (String[]) pValue;
        return new Enumeration<String>() {
            private int offset;
            public boolean hasMoreElements() {
                return offset < values.length;
            }
            public String nextElement() {
                if (offset >= values.length) {
                    throw new NoSuchElementException();
                }
                return values[offset++];
            }
        };
    }
    if (pValue instanceof List) {
        @SuppressWarnings("unchecked")
        final List<String> stringList = (List<String>) pValue; 
        return Collections.enumeration(stringList);
    }
    throw new IllegalStateException("Invalid parameter class: " + pValue.getClass().getName());
}
 
Example 16
Project: JAME   File: Builder.java View source code Vote up 6 votes
public int stringToShape(String name, boolean colonsAllowed, Token location) {
	checkName(name, colonsAllowed, location);
	if (currentNameSpace.length() == 0) {
		return cfdg.encodeShapeName(name);
	}
	int index = Collections.binarySearch(globals, name);
	String n = currentNameSpace + name;
	if (index != -1 && cfdg.tryEncodeShapeName(n) == -1) {
		return cfdg.encodeShapeName(name);
	} else {
		return cfdg.encodeShapeName(n);
	}
}
 
Example 17
Project: wso2-synapse   File: JmxSecretAuthenticator.java View source code Vote up 6 votes
public Subject authenticate(Object credentials) {

        if (credentials == null) {
            throw new SecurityException("Credentials required");
        }

        if (!(credentials instanceof String[])) {
            throw new SecurityException("Credentials should be String[]");
        }

        // Only expect username/password, therefore the credentials should have two entries
        final String[] aCredentials = (String[]) credentials;
        if (aCredentials.length < 2) {
            throw new SecurityException("Credentials should have the username and password");
        }

        String username = aCredentials[0];
        String password = (aCredentials[1] != null ? aCredentials[1] : "");

        // perform authentication
        if (secretInformation.getUser().equals(username) &&
                password.equals(secretInformation.getResolvedSecret())) {
            return new Subject(true,
                Collections.singleton(new JMXPrincipal(username)),
                Collections.EMPTY_SET,
                Collections.EMPTY_SET);
        } else {
            throw new SecurityException("Username and/or password are incorrect, " +
                "or you do not have the necessary access rights.");
        }
    }
 
Example 18
Project: richfaces   File: MockTestBase.java View source code Vote up 6 votes
protected void recordMocks() {
    UIViewRoot viewRoot = facesEnvironment.createMock(UIViewRoot.class);
    expect(viewRoot.getLocale()).andStubReturn(Locale.ENGLISH);
    expect(facesEnvironment.getFacesContext().getViewRoot()).andStubReturn(viewRoot);
    expect(input.getAttributes()).andStubReturn(Collections.EMPTY_MAP);
    expect(input.getClientId(facesEnvironment.getFacesContext())).andStubReturn(TEST_COMPONENT_ID);
}
 
Example 19
Project: windtalk   File: JmDNSImpl.java View source code Vote up 6 votes
/**
 * Create an instance of JmDNS and bind it to a specific network interface given its IP-address.
 *
 * @param address
 *            IP address to bind to.
 * @param name
 *            name of the newly created JmDNS
 * @throws IOException
 */
public JmDNSImpl(InetAddress address, String name) throws IOException {
    super();
    if (logger.isLoggable(Level.FINER)) {
        logger.finer("JmDNS instance created");
    }
    _cache = new DNSCache(100);

    _listeners = Collections.synchronizedList(new ArrayList<DNSListener>());
    _serviceListeners = new ConcurrentHashMap<String, List<ServiceListenerStatus>>();
    _typeListeners = Collections.synchronizedSet(new HashSet<ServiceTypeListenerStatus>());
    _serviceCollectors = new ConcurrentHashMap<String, ServiceCollector>();

    _services = new ConcurrentHashMap<String, ServiceInfo>(20);
    _serviceTypes = new ConcurrentHashMap<String, ServiceTypeEntry>(20);

    _localHost = HostInfo.newHostInfo(address, this, name);
    _name = (name != null ? name : _localHost.getName());

    _timer = new Timer("JmDNS(" + _name + ").Timer", true);
    _stateTimer = new Timer("JmDNS(" + _name + ").State.Timer", false);
    // _cancelerTimer = new Timer("JmDNS.cancelerTimer");

    // (ldeck 2.1.1) preventing shutdown blocking thread
    // -------------------------------------------------
    // _shutdown = new Thread(new Shutdown(), "JmDNS.Shutdown");
    // Runtime.getRuntime().addShutdownHook(_shutdown);

    // -------------------------------------------------

    // Bind to multicast socket
    this.openMulticastSocket(this.getLocalHost());
    this.start(this.getServices().values());

    new RecordReaper(this).start(_timer);
}
 
Example 20
Project: jentrata-msh   File: Module.java View source code Vote up 6 votes
/**
 * Creates a new instance of Module.
 * 
 * @param descriptorLocation the module descriptor.
 * @param loader the class loader for this module.
 * @param shouldInitialize true if the module should be initialized.
 * @throws ModuleException if errors encountered when loading the module
 *             descriptor.
 */
public Module(String descriptorLocation, ClassLoader loader,
        boolean shouldInitialize) {
    if (descriptorLocation == null) {
        throw new ModuleException("No module descriptor specified");
    }

    if (loader == null) {
        loader = getClass().getClassLoader();
    }

    URL resrc = getResource(descriptorLocation, loader);
    if (resrc == null) {
        throw new ModuleException("Module descriptor not found: "
                + descriptorLocation);
    }

    try {
        this.classLoader = loader;
        this.components = Collections.synchronizedMap(new LinkedHashMap());
        this.descriptor = new PropertyTree(resrc);
        
        super.setModule(this);
        super.setId(getString("[email protected]"));
        super.setName(getString("[email protected]"));
        super.setParameters(descriptor.createProperties("/module/parameters/parameter"));            
        
        createComponents();
        if (shouldInitialize) {
            init();
        }
    }
    catch (Exception e) {
        throw new ModuleException("Unable to initialize module '"+getName()+"'", e);
    }
}
 
Example 21
Project: p1keyboard   File: ButtonConfiguration.java View source code Vote up 6 votes
private void updateDisplay() {
	for(Preference p : Collections.list(m_list_lookup.keys())) {
		ListPreference lp = (ListPreference)p;
		int code = m_prefs.getKeyMapping(m_list_lookup.get(p), m_controllerIndex);
		String keycode = m_name_lookup.containsKey(code) ? m_name_lookup.get(code) : "UNKNOWN - 0x" + Integer.toHexString(code); 
		int metacode = m_prefs.getMetaKeyMapping(m_list_lookup.get(p), m_controllerIndex);
		
		for(Integer i : m_meta_name_lookup.keySet()) {
			if ((metacode & i) != 0)
				keycode = m_meta_name_lookup.get(i) + " + " + keycode;
		}

		lp.setSummary(keycode);	
		lp.setValue(Integer.toString(code));
	}
	
	CharSequence[] profileEntries = new CharSequence[Preferences.PROFILE_KEYS.length];
	CharSequence[] profileEntryValues = new CharSequence[Preferences.PROFILE_KEYS.length];
	for(int i = 0; i < profileEntries.length; i++) {
		profileEntryValues[i] = Preferences.PROFILE_KEYS[i];
		profileEntries[i] = m_prefs.getProfileDisplayName(Preferences.PROFILE_KEYS[i]);
	}
	
	m_presets.setEntries(profileEntries);
	m_presets.setEntryValues(profileEntryValues);
	
	String currentProfile = m_prefs.getCurrentProfile();
	if (currentProfile.endsWith(":"))
			currentProfile = currentProfile.substring(0, currentProfile.length() - 1);
	m_presets.setValue(currentProfile);
	
	String display = m_prefs.getProfileDisplayName();
	m_presets.setTitle(display);
	m_presetName.setText(display);
}
 
Example 22
Project: jentrata-msh   File: ModuleGroup.java View source code Vote up 6 votes
/**
 * Creates a new instance of ModuleGroup.
 * 
 * @param descriptorLocation the descriptor location.
 * @param loader the class loader for loading the modules.
 */
public ModuleGroup(String descriptorLocation, ClassLoader loader) {
    if (descriptorLocation == null) {
        throw new ModuleException("No module group descriptor specified");
    }

    if (loader == null) {
        loader = getClass().getClassLoader();
    }

    URL resrc = Module.getResource(descriptorLocation, loader);
    if (resrc == null) {
        throw new ModuleException("Module group descriptor not found: " 
                    + descriptorLocation);
    }
        
    try {
        this.loader = loader;
        this.allModules = Collections.synchronizedMap(new LinkedHashMap());
        this.normalModules = new Vector();
        this.systemModules = new Vector();
        this.activeModules = new Vector();
        this.children = Collections.synchronizedSet(new HashSet());
        this.descriptor = new PropertyTree(resrc);
        this.name = descriptor.getProperty("[email protected]");
        
        loadModules();
    }
    catch (Exception e) {
        throw new ModuleException("Unable to initialize module group '"+getName()+"'", e);
    }
}
 
Example 23
Project: ISAvalidator-ISAconverter-BIImanager   File: PipelineWrapperNode.java View source code Vote up 6 votes
/**
 * Returns the left processings of this node, unless the node is the starting node of a sample file or
 * of an assay file. In the latter case, omits the processings not belonging to the current assay for which
 * the export is being generated.
 */
public SortedSet<Node> getInputs() {
	if (inputs == null) {
		inputs = new TreeSet<Node>();
		WrapperNodesFactory nodeFactory = WrapperNodesFactory.getInstance();

		if (nodeType == NodeType.REGULAR || nodeType == NodeType.END) {
			for (Processing inproc : (Collection<Processing>) node.getDownstreamProcessings()) {
				inputs.add(nodeFactory.getNode(inproc));
			}
		}
	}
	return Collections.unmodifiableSortedSet(inputs);
}
 
Example 24
Project: netlib   File: ConditionalNetLayer.java View source code Vote up 6 votes
/**
   * @return the lowest status of all lower NetLayers.
   * 
   * @see NetLayer#getStatus()
   */
  public NetLayerStatus getStatus() {
  	// get status of all possible lower net layers
  	Collection<NetLayerStatus> statuses = new ArrayList<NetLayerStatus>();
for (NetLayer lowerNetLayer : getAllLowerNetLayers()) {
	statuses.add(lowerNetLayer.getStatus());
}

  	// take the lowest status
return Collections.max(statuses);
  }
 
Example 25
Project: SyncthingAndroid   File: RecyclerListAdapter.java View source code Vote up 6 votes
public boolean swap(int pos1, int pos2) {
    try {
        Collections.swap(items, pos1, pos2);
        notifyItemMoved(pos1, pos2);
        notifyItemMoved(pos2, pos1);
        return true;
    } catch (IndexOutOfBoundsException e) {
        return false;
    }
}
 
Example 26
Project: Dempsy   File: Router.java View source code Vote up 6 votes
@Override
public void registerOutbound(RoutingStrategy.Outbound outbound, Collection<Class<?>> classes)
{
   synchronized(outbound)
   {
      unregisterOutbound(outbound);
      
      ClusterId clusterId = outbound.getClusterId();
      if (classes != null && classes.size() > 0)
      {
         // find the appropriate ClusterDefinition
         ClusterDefinition curClusterDef = applicationDefinition.getClusterDefinition(clusterId);
         
         if (curClusterDef != null)
         {
            // create a corresponding ClusterRouter
            @SuppressWarnings("unchecked")
            ClusterRouter clusterRouter = new ClusterRouter((Serializer<Object>)curClusterDef.getSerializer(),outbound);
         
            for (Class<?> clazz : classes)
            {
               Set<ClusterRouter> cur = Collections.newSetFromMap(new ConcurrentHashMap<ClusterRouter, Boolean>()); // potential
               Set<ClusterRouter> tmp = routerMap.putIfAbsent(clazz, cur);
               if (tmp != null)
                  cur = tmp;
               cur.add(clusterRouter);
            }
         }
         else
         {
            logger.error("Couldn't find the ClusterDefinition for " + clusterId + " while registering the Outbound " + 
                  SafeString.objectDescription(outbound) + " given the ApplicationDefinition " + applicationDefinition);
         }
      }
   }
}
 
Example 27
Project: airlift   File: TimedStat.java View source code Vote up 6 votes
@Managed
public double getMin()
{
    List<Long> values = sample.values();
    if (!values.isEmpty()) {
        return Collections.min(values);
    }

    return Double.NaN;
}
 
Example 28
Project: molindo-webtools   File: CounterMap.java View source code Vote up 6 votes
public SortedMap<Integer, T> toSortedMap() {
	SortedMap<Integer, T> map = new TreeMap<Integer, T>(Collections.reverseOrder());

	for (Entry<T, Integer> e : _counters.entrySet()) {
		map.put(e.getValue(), e.getKey());
	}

	return map;
}
 
Example 29
Project: newFunf   File: IJsonObject.java View source code Vote up 6 votes
public IJsonObject(JsonObject jsonObject) {
	if (jsonObject == null) {
		throw new IllegalStateException("Cannot create null IJsonObject");
	}
	SortedMap<String, JsonElement> map = new TreeMap<String, JsonElement>();
	for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
		map.put(entry.getKey(), JsonUtils.immutable(entry.getValue()));
	}
	members = Collections.unmodifiableSortedMap(map);
}
 
Example 30
Project: gcloud-java   File: DatastoreHelperTest.java View source code Vote up 6 votes
@Test
public void testGet() throws Exception {
  Datastore datastore = createStrictMock(Datastore.class);
  IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build();
  Key key1 = Key.builder(pKey1, 1).build();
  Entity entity1 = Entity.builder(key1).build();
  Key key2 = Key.builder(pKey1, 2).build();
  expect(datastore.get(new Key[]{key1}))
      .andReturn(Collections.singletonList(entity1).iterator());
  expect(datastore.get(new Key[]{key2}))
      .andReturn(Collections.<Entity>emptyIterator());
  replay(datastore);
  assertEquals(entity1, DatastoreHelper.get(datastore, key1));
  assertNull(DatastoreHelper.get(datastore, key2));
  verify(datastore);
}
 
Example 31
Project: fiware-rss   File: ServiceDeploymentDaoImpl.java View source code Vote up 6 votes
/**
 * listServiceDeploymentQuery to get all data from ServiceDeployment query.
 * 
 * @param hql
 *            the query to get ServiceDeployment id with the service, ob and country
 * @return a list with the results from the ServiceDeployment query
 */
private List<BmServiceDeployment> listServiceDeploymentQuery(final String hql) {
    ServiceDeploymentDaoImpl.LOGGER.debug(hql);
    // @SuppressWarnings("rawtypes")
    List list = this.getSession().createQuery(hql).list();
    // entityManager.createQuery(hql).getResultList();
    // @SuppressWarnings("unchecked")
    List<BmServiceDeployment> resultList = Collections.checkedList(list, BmServiceDeployment.class);
    return resultList;
}
 
Example 32
Project: java-util   File: TestDeepEquals.java View source code Vote up 6 votes
@Test
public void testEquivalentMaps()
{
    Map map1 = new LinkedHashMap();
    fillMap(map1);
    Map map2 = new HashMap();
    fillMap(map2);
    assertTrue(DeepEquals.deepEquals(map1, map2));
    assertEquals(DeepEquals.deepHashCode(map1), DeepEquals.deepHashCode(map2));

    map1 = new TreeMap();
    fillMap(map1);
    map2 = new TreeMap();
    map2 = Collections.synchronizedSortedMap((SortedMap) map2);
    fillMap(map2);
    assertTrue(DeepEquals.deepEquals(map1, map2));
    assertEquals(DeepEquals.deepHashCode(map1), DeepEquals.deepHashCode(map2));
}
 
Example 33
Project: UFMGame   File: XMLTag.java View source code Vote up 6 votes
/**
 * get an element of the xml tag
 * 
 * @param element
 *            is the index of the element to get
 * @return the element
 * @throws NoSuchElementException
 *             is thrown if the element is not found
 */
public XMLTag getElement(String element) throws NoSuchElementException {
	if (element.equals(name)) {
		return this;
	}
	// Get the string of the following elements (+ 1 to also chop off
	// the '.')
	int splitpoint = element.indexOf(".") + 1;
	element = element.substring(splitpoint, element.length());
	String subelement = element.split("\\.")[0];
	if (Collections.frequency(elementnames, subelement) > 1)
		throw new ElementNotUniqueException(this.name
				+ " contains more than one element called '" + subelement
				+ "'");
	if (elementnames.contains(subelement))
		return elements.get(elementnames.indexOf(subelement)).getElement(
				element);
	throw new NoSuchElementException(this.name + " does not have element '"
			+ element + "'");
}
 
Example 34
Project: UFMGame   File: Competition.java View source code Vote up 6 votes
/**
 * add all matches of this competition to random playrounds
 */
public void definePlayrounds() {
	playrounds = new ArrayList<Playround>();

	int i = 0;
	int j = 0;
	int k = 0;
	int p = 0;
	int round = 0;
	ArrayList<User> usersindelen = users;
	Collections.shuffle(usersindelen);
	User user = usersindelen.get(0);
	usersindelen.remove(0);
	usersindelen.add(user);

	for (i = 0; i < (users.size() * (users.size() - 1) / (users.size() / 2)); i++) {
		Playround newplayround = new Playround();
		if (i % 2 == 0) {
			round = p + 1;
		} else if (i % 2 != 0) {
			round = (users.size() * (users.size() - 1) / (users.size() / 2)) - (p);
			p = p + 1;
		}
		newplayround.setPlayroundnr(round);
		for (j = 0; j < (users.size() / 2); j++) {
			if (k == users.size()) {
				usersindelen.remove(user);
				Collections.rotate(usersindelen, 1);
				usersindelen.add(user);
				k = 0;
			}
			Match newmatch = new Match(usersindelen.get(k).getTeam(), usersindelen.get(users.size() - 1 - k).getTeam());
			newmatch.setPlayround(round);
			newplayround.addmatch(newmatch);
			k = k + 1;

		}
		playrounds.add(newplayround);
	}
}
 
Example 35
Project: jeboorker   File: MultiListPropertyEditor.java View source code Vote up 6 votes
@SuppressWarnings({ "rawtypes", "unchecked" })
public void setValue(Object value) {
	List viewList = new ArrayList(Arrays.asList(new Object[((List) value).size()]));
	Collections.copy(viewList, ((List) value));
	
	//the first one is the value which is stored to all selected ebooks.
	Object selectedValue = viewList.remove(0);
	viewList = ListUtils.distinct(viewList, UtilConstants.COMPARE_TEXT);
	viewList.remove(EMPTY);
	viewList.remove(null);
	viewList = new CompoundList(Arrays.asList(new Object[] {noChanges, clear}), viewList);
	Object[] values = viewList.toArray(new Object[viewList.size()]);
	this.setAvailableValues(values);
	if(selectedValue == null) {
		((JComboBox) editor).setSelectedIndex(0);
	} else if(StringUtil.toString(selectedValue).isEmpty()) {
		((JComboBox) editor).setSelectedIndex(1);
	} else {
		((JComboBox) editor).setSelectedItem(selectedValue);
	}
}
 
Example 36
Project: java-util   File: TestDeepEquals.java View source code Vote up 6 votes
@Test
public void testEquivalentCollections()
{
    // ordered Collection
    Collection col1 = new ArrayList();
    fillCollection(col1);
    Collection col2 = new LinkedList();
    fillCollection(col2);
    assertTrue(DeepEquals.deepEquals(col1, col2));
    assertEquals(DeepEquals.deepHashCode(col1), DeepEquals.deepHashCode(col2));

    // unordered Collections (Set)
    col1 = new LinkedHashSet();
    fillCollection(col1);
    col2 = new HashSet();
    fillCollection(col2);
    assertTrue(DeepEquals.deepEquals(col1, col2));
    assertEquals(DeepEquals.deepHashCode(col1), DeepEquals.deepHashCode(col2));

    col1 = new TreeSet();
    fillCollection(col1);
    col2 = new TreeSet();
    Collections.synchronizedSortedSet((SortedSet) col2);
    fillCollection(col2);
    assertTrue(DeepEquals.deepEquals(col1, col2));
    assertEquals(DeepEquals.deepHashCode(col1), DeepEquals.deepHashCode(col2));
}
 
Example 37
Project: android_platform_libcore   File: OldCollectionsTest.java View source code Vote up 6 votes
public void test_checkedSetSerializationCompatibility() throws Exception {
    String s = "aced0005737200206a6176612e7574696c2e436f6c6c656374696f6e73244368"
            + "65636b656453657441249ba27ad9ffab020000787200276a6176612e7574696c2"
            + "e436f6c6c656374696f6e7324436865636b6564436f6c6c656374696f6e15e96d"
            + "fd18e6cc6f0200034c0001637400164c6a6176612f7574696c2f436f6c6c65637"
            + "4696f6e3b4c0004747970657400114c6a6176612f6c616e672f436c6173733b5b"
            + "00167a65726f4c656e677468456c656d656e7441727261797400135b4c6a61766"
            + "12f6c616e672f4f626a6563743b7870737200116a6176612e7574696c2e486173"
            + "68536574ba44859596b8b7340300007870770c000000103f40000000000000787"
            + "67200106a6176612e6c616e672e537472696e67a0f0a4387a3bb3420200007870"
            + "70";
    assertSerialized(Collections.checkedSet(new HashSet<String>(), String.class), s, true);
}
 
Example 38
Project: levelup-java-examples   File: ReturnEmptyEnumeration.java View source code Vote up 6 votes
@Test
public void return_empty_enumeration_java () {

	Enumeration<String> strings = Collections.emptyEnumeration();
	
	assertFalse(strings.hasMoreElements());
}
 
Example 39
Project: google-web-toolkit-svnmirror   File: CollectionsTest.java View source code Vote up 6 votes
public void testFill() {
  List<String> a = createSortedList();
  Collections.fill(a, null);
  assertEquals(new Object[a.size()], a);

  List<Integer> b = createRandomList();
  Collections.fill(b, null);
  assertEquals(new Object[b.size()], b);
}
 
Example 40
Project: libreplan   File: TreeNodeOnList.java View source code Vote up 6 votes
@Override
public void replace(T previousChild, T newChild) {
    setParentIfRequired(newChild);
    Collections.replaceAll(children, previousChild, newChild);
    onChildAdded(newChild);
    onChildRemoved(previousChild);
}
 
Example 41
Project: acteur   File: HelpPage.java View source code Vote up 6 votes
@SuppressWarnings("unchecked")
private StringBuilder writeOut(String key, Object object, StringBuilder sb, String parentKey) {
    boolean code = ("PathRegex".equals(parentKey) || "Path".equals(parentKey) || "Methods".equals(parentKey))
            && "value".equals(key);
    String codeOpen = code ? "<code>" : "";
    String codeClose = code ? "</code>" : "";
    String humanized = deBicapitalize(key);
    if (key == null || object instanceof Map<?,?>) {
        Map<String, Object> m = Collections.checkedMap((Map<String,Object>) object, String.class, Object.class);
        if (key != null) {
            sb.append("\n<tr><th valign=\"left\" bgcolor='#FFEECC'>").append(humanized).append("</th><td>");
        }
        sb.append("<table>\n");
        List<String> sortedKeys = new LinkedList<>(m.keySet());
        Collections.sort(sortedKeys);
        for (String k : sortedKeys) {
            Object val = m.get(k);
            sb.append(codeOpen);;
            writeOut(k, val, sb, key);
            sb.append(codeClose);
            if (key == null) {
                sb.append("\n<tr><td colspan=2><hr/></td></tr>\n");
            }
        }
        sb.append("\n</table>\n");
        if (key != null) {
            sb.append("\n</td></tr>\n");
        }
    } else if (object instanceof CharSequence || object instanceof Boolean || object instanceof Number || object instanceof Enum) {
        sb.append("\n<tr><th bgcolor='#DDDDDD'>").append(humanized).append("</th><td>")
                .append(codeOpen)
                .append(object)
                .append(codeClose)
                .append("</td></tr>\n");
    } else if (object != null && object.getClass().isArray()) {
        String s = toString(object);;
        sb.append("\n<tr><th bgcolor='#DDDDDD'>").append(humanized).append("</th><td>")
                .append(codeOpen)
                .append(s)
                .append(codeClose)
                .append("</td></tr>\n");
    } else {
        sb.append("\n<tr><th bgcolor='#DDDDDD'>").append(humanized).append("</th><td>")
                .append(codeOpen)
                .append(object)
                .append(codeClose)
                .append("</td></tr>\n");
    }
    return sb;
}
 
Example 42
Project: RinLog   File: GotoClosestRoutePlanner.java View source code Vote up 6 votes
@Override
protected final void doUpdate(Collection<Parcel> onMap, long time) {
  @SuppressWarnings({ "unchecked", "rawtypes" })
  final Collection<Parcel> inCargo = Collections.checkedCollection(
    (Collection) pdpModel.get().getContents(vehicle.get()),
    Parcel.class);
  parcels.clear();
  parcels.addAll(onMap);
  parcels.addAll(onMap);
  parcels.addAll(inCargo);
  updateCurrent();
}
 
Example 43
Project: android_platform_libcore   File: OldCollectionsTest.java View source code Vote up 6 votes
public void test_checkedSortedSetSerializationCompatibility() throws Exception {
    String s = "aced0005737200266a6176612e7574696c2e436f6c6c656374696f6e73244368"
            + "65636b6564536f72746564536574163406ba7362eb0f0200014c0002737374001"
            + "54c6a6176612f7574696c2f536f727465645365743b787200206a6176612e7574"
            + "696c2e436f6c6c656374696f6e7324436865636b656453657441249ba27ad9ffa"
            + "b020000787200276a6176612e7574696c2e436f6c6c656374696f6e7324436865"
            + "636b6564436f6c6c656374696f6e15e96dfd18e6cc6f0200034c0001637400164"
            + "c6a6176612f7574696c2f436f6c6c656374696f6e3b4c0004747970657400114c"
            + "6a6176612f6c616e672f436c6173733b5b00167a65726f4c656e677468456c656"
            + "d656e7441727261797400135b4c6a6176612f6c616e672f4f626a6563743b7870"
            + "737200116a6176612e7574696c2e54726565536574dd98509395ed875b0300007"
            + "8707077040000000078767200106a6176612e6c616e672e537472696e67a0f0a4"
            + "387a3bb34202000078707071007e0009";
    assertSerialized(Collections.checkedSortedSet(new TreeSet<String>(), String.class), s, true);
}
 
Example 44
Project: spikes   File: EasyCustomTabsIntentBuilderTest.java View source code Vote up 6 votes
@Before
public void setUp() {
    initMocks(this);

    easyCustomTabsIntentBuilder = new EasyCustomTabsIntentBuilder(mockEasyCustomTabsConnection, mockComposers);
    when(mockComposers.iterator()).thenReturn(Collections.<Composer>emptyListIterator());
}
 
Example 45
Project: android_platform_libcore   File: OldCollectionsTest.java View source code Vote up 6 votes
public void test_checkedSortedMapSerializationCompatibility() throws Exception {
    String s = "aced0005737200266a6176612e7574696c2e436f6c6c656374696f6e73244368"
            + "65636b6564536f727465644d617016332c973afe036e0200014c0002736d74001"
            + "54c6a6176612f7574696c2f536f727465644d61703b787200206a6176612e7574"
            + "696c2e436f6c6c656374696f6e7324436865636b65644d61704fb2bcdf0d18636"
            + "80200054c00076b6579547970657400114c6a6176612f6c616e672f436c617373"
            + "3b4c00016d74000f4c6a6176612f7574696c2f4d61703b4c000976616c7565547"
            + "9706571007e00035b00127a65726f4c656e6774684b657941727261797400135b"
            + "4c6a6176612f6c616e672f4f626a6563743b5b00147a65726f4c656e677468566"
            + "16c7565417272617971007e00057870767200106a6176612e6c616e672e537472"
            + "696e67a0f0a4387a3bb3420200007870737200116a6176612e7574696c2e54726"
            + "5654d61700cc1f63e2d256ae60300014c000a636f6d70617261746f727400164c"
            + "6a6176612f7574696c2f436f6d70617261746f723b78707077040000000078710"
            + "07e0008707071007e000b";
    assertSerialized(Collections.checkedSortedMap(
            new TreeMap<String, String>(), String.class, String.class), s);
}
 
Example 46
Project: fiji   File: CustomVolumeBehavior2.java View source code Vote up 5 votes
/**
     * Given the graph (really a forest of trees) created by the AnalyzeSkeleton
     * plugin, a List and a Map are constructed. See above for a description of
     * these two structures.
     *
     * @param graph
     */
    private void createBlobLists(AnalyzedGraph graph) {
        Graph[] forest;
        Blob v1Blob = new Blob();
        Blob v2Blob = new Blob();
        Blob slabBlob;
        nSliceBlobs = new ArrayList(Collections.nCopies(imageDepth, null));
        forest = graph.getSkeletonResult().getGraph();
//        System.out.println("Trees in the forest: "+forest.length);
        int treecount = 0;
        for (Graph tree : forest) {
            // Skip those trees with no (zero) edges
            if (tree.getEdges().size() < 1) {
//                if (tree.getVertices().size() > 0) {
//                    for (Vertex v : tree.getVertices()) {
//                        for (Point p : v.getPoints()) {
//                            Blob pBlob = getBlobAtPoint(p, false);  // Called for the side effect
//                        }
//                    }
//                }
                continue;   // Skip this tree
            }
            treecount++;
//            System.out.println("T#: "+treecount+" Edges: "+tree.getEdges().size());
            int edgecount = 0;
            for (Edge edge : tree.getEdges()) {
                if (edge.getType() == -1) continue;
//                System.out.println("     E#: "+(++edgecount));
                for (Point v1Point : edge.getV1().getPoints()) {
                    v1Blob = getBlobAtPoint(v1Point, false);
                    if (v1Blob != null) {
                        v1Blob.edges.add(edge);
                        putBlobAtEdge(v1Blob, edge, false);
                    }
                }
                for (Point v2Point : edge.getV2().getPoints()) {
                    v2Blob = getBlobAtPoint(v2Point, false);
                    if (v2Blob != null) {
                        v2Blob.edges.add(edge);
                        putBlobAtEdge(v2Blob, edge, false);
                    }
                }

                for (Point slabPoint : edge.getSlabs()) {
                    slabBlob = getBlobAtPoint(slabPoint, false);
                    if (slabBlob != null) {
                        slabBlob.edges.add(edge);
                        putBlobAtEdge(slabBlob, edge, false);
                    }
                }
            }
        }
//        System.out.println("Trees used: "+treecount);
    }
 
Example 47
Project: HDP-2.2-Patched   File: TestFairScheduler.java View source code Vote up 5 votes
@Test (timeout = 5000)
/**
 * Make sure containers are chosen to be preempted in the correct order. Right
 * now this means decreasing order of priority.
 */
public void testChoiceOfPreemptedContainers() throws Exception {
  Configuration conf = createConfiguration();
  
  conf.setLong(FairSchedulerConfiguration.PREEMPTION_INTERVAL, 5000);
  conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10000); 
  
  conf.set(FairSchedulerConfiguration.ALLOCATION_FILE + ".allocation.file", ALLOC_FILE);
  scheduler.reinitialize(conf, resourceManager.getRMContext());
  
  MockClock clock = new MockClock();
  scheduler.setClock(clock);
  
  PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
  out.println("<?xml version=\"1.0\"?>");
  out.println("<allocations>");
  out.println("<queue name=\"queueA\">");
  out.println("<weight>.25</weight>");
  out.println("</queue>");
  out.println("<queue name=\"queueB\">");
  out.println("<weight>.25</weight>");
  out.println("</queue>");
  out.println("<queue name=\"queueC\">");
  out.println("<weight>.25</weight>");
  out.println("</queue>");
  out.println("<queue name=\"queueD\">");
  out.println("<weight>.25</weight>");
  out.println("</queue>");
  out.println("</allocations>");
  out.close();

  QueueManager queueManager = scheduler.getQueueManager();
  queueManager.initialize();

  // Create four nodes
  RMNode node1 =
      MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 1,
          "127.0.0.1");
  NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
  scheduler.handle(nodeEvent1);

  RMNode node2 =
      MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 2,
          "127.0.0.2");
  NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
  scheduler.handle(nodeEvent2);

  RMNode node3 =
      MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 3,
          "127.0.0.3");
  NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
  scheduler.handle(nodeEvent3);


  // Queue A and B each request three containers
  ApplicationAttemptId app1 =
      createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1);
  ApplicationAttemptId app2 =
      createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 2);
  ApplicationAttemptId app3 =
      createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 3);

  ApplicationAttemptId app4 =
      createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 1);
  ApplicationAttemptId app5 =
      createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 2);
  ApplicationAttemptId app6 =
      createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 3);

  scheduler.update();

  // Sufficient node check-ins to fully schedule containers
  for (int i = 0; i < 2; i++) {
    NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
    scheduler.handle(nodeUpdate1);

    NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
    scheduler.handle(nodeUpdate2);

    NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
    scheduler.handle(nodeUpdate3);
  }

  assertEquals(1, scheduler.applications.get(app1).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app2).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app3).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app4).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app5).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app6).getLiveContainers().size());

  // Now new requests arrive from queues C and D
  ApplicationAttemptId app7 =
      createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1);
  ApplicationAttemptId app8 =
      createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2);
  ApplicationAttemptId app9 =
      createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3);

  ApplicationAttemptId app10 =
      createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 1);
  ApplicationAttemptId app11 =
      createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 2);
  ApplicationAttemptId app12 =
      createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 3);

  scheduler.update();

  // We should be able to claw back one container from A and B each.
  // Make sure it is lowest priority container.
  scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
      Resources.createResource(2 * 1024));
  assertEquals(1, scheduler.applications.get(app1).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app2).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app4).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app5).getLiveContainers().size());
  
  // First verify we are adding containers to preemption list for the application
  assertTrue(!Collections.disjoint(scheduler.applications.get(app3).getLiveContainers(),
                                   scheduler.applications.get(app3).getPreemptionContainers()));
  assertTrue(!Collections.disjoint(scheduler.applications.get(app6).getLiveContainers(),
                                   scheduler.applications.get(app6).getPreemptionContainers()));

  // Pretend 15 seconds have passed
  clock.tick(15);

  // Trigger a kill by insisting we want containers back
  scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
      Resources.createResource(2 * 1024));

  // At this point the containers should have been killed (since we are not simulating AM)
  assertEquals(0, scheduler.applications.get(app6).getLiveContainers().size());
  assertEquals(0, scheduler.applications.get(app3).getLiveContainers().size());

  // Trigger a kill by insisting we want containers back
  scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
      Resources.createResource(2 * 1024));

  // Pretend 15 seconds have passed
  clock.tick(15);

  // We should be able to claw back another container from A and B each.
  // Make sure it is lowest priority container.
  scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
      Resources.createResource(2 * 1024));
  
  assertEquals(1, scheduler.applications.get(app1).getLiveContainers().size());
  assertEquals(0, scheduler.applications.get(app2).getLiveContainers().size());
  assertEquals(0, scheduler.applications.get(app3).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app4).getLiveContainers().size());
  assertEquals(0, scheduler.applications.get(app5).getLiveContainers().size());
  assertEquals(0, scheduler.applications.get(app6).getLiveContainers().size());

  // Now A and B are below fair share, so preemption shouldn't do anything
  scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
      Resources.createResource(2 * 1024));
  assertEquals(1, scheduler.applications.get(app1).getLiveContainers().size());
  assertEquals(0, scheduler.applications.get(app2).getLiveContainers().size());
  assertEquals(0, scheduler.applications.get(app3).getLiveContainers().size());
  assertEquals(1, scheduler.applications.get(app4).getLiveContainers().size());
  assertEquals(0, scheduler.applications.get(app5).getLiveContainers().size());
  assertEquals(0, scheduler.applications.get(app6).getLiveContainers().size());
}
 
Example 48
Project: cids-server   File: ObjectFactory.java View source code Vote up 5 votes
/**
 * DOCUMENT ME!
 *
 * @param   classId  DOCUMENT ME!
 *
 * @return  DOCUMENT ME!
 *
 * @throws  Exception  DOCUMENT ME!
 */
public Sirius.server.localserver.object.Object getInstance(final int classId) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getInstance(" + classId + ") called", new CurrentStackTrace()); // NOI18N
    }
    final Sirius.server.localserver._class.Class c = classCache.getClass(classId);

    final Sirius.server.localserver.object.Object o = new Sirius.server.localserver.object.DefaultObject(
            -1,
            classId);

    // nur ein Versuch:-)
    final Iterator iter = Collections.synchronizedCollection(c.getMemberAttributeInfos().values()).iterator();

    while (iter.hasNext()) {
        final MemberAttributeInfo mai = (MemberAttributeInfo)iter.next();

        ObjectAttribute oAttr;

        if (!mai.isForeignKey()) {
            oAttr = new ObjectAttribute(mai, -1, null, c.getAttributePolicy());
        } else if (!mai.isArray()) {
            oAttr = new ObjectAttribute(mai, -1, getInstance(mai.getForeignKeyClassId()), c.getAttributePolicy());
        } else // isArray
        {
            // construct artificial metaobject

            // classId des zwischenobjektes (join tabelle) zuweisen
            final int jtClassId = mai.getForeignKeyClassId();

            // Klasse der referenztabellen besorgen
            final Sirius.server.localserver._class.Class cl = classCache.getClass(jtClassId);

            // dummy erszeugen
            final Sirius.server.localserver.object.Object result =
                new Sirius.server.localserver.object.DefaultObject(-1,
                    cl.getID());

            // der dummy bekommt jetzt genau ein Attribut vom Typ der Klasse der Referenztabelle, als Muster

            // zwischenobjekt als arrayelement anlegen

            result.addAttribute(new ObjectAttribute(mai, -1, getInstance(jtClassId), cl.getAttributePolicy()));

            result.setDummy(true);

            // Objektattribut (array dummy) setzten
            oAttr = new ObjectAttribute(mai, -1, result, cl.getAttributePolicy());
            if (LOG.isDebugEnabled()) {
                LOG.debug("array oattr :" + oAttr.getName() + " class" + oAttr.getClassKey()); // NOI18N
            }
        }

        // not covered by the constructor
        oAttr.setVisible(mai.isVisible());
        oAttr.setSubstitute(mai.isSubstitute());
        oAttr.setReferencesObject(mai.isForeignKey());

        oAttr.setIsPrimaryKey(mai.getFieldName().equalsIgnoreCase(c.getPrimaryKey()));

        oAttr.setOptional(mai.isOptional());

        try {
            final String table = c.getTableName();

            final String pk = (mai.getFieldName() + "@" + table).toLowerCase(); // NOI18N

            if (primaryKeys.contains(pk)) {
                oAttr.setIsPrimaryKey(true); // bei gelegenheit raus da es im Konstruktor von MetaObject gesetzt
                // wird
            }
            oAttr.setClassKey(mai.getForeignKeyClassId() + "@" + classCache.getProperties().getServerName()); // NOI18N
        } catch (Exception e) {
            LOG.error("could not set primary key property", e);                                               // NOI18N
        }

        o.addAttribute(oAttr);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("result of getInstance()" + new DefaultMetaObject(o, "LOCAL")); // NOI18N
    }
    return o;
}