Java Code Examples for java.util.TreeSet

The following are top voted examples for showing how to use java.util.TreeSet. 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: iswc2012metadata   File: DataInstance.java View source code 6 votes vote down vote up
public TreeSet<String> getPropertyValueAsStringSet(Property prop){
	TreeSet<String> ret = new TreeSet<String>();
	NodeIterator iter = m_model.listObjectsOfProperty(m_subject, prop);
	while (iter.hasNext()){
		RDFNode node = iter.nextNode();
		ret.add(ToolJena.getNodeString(node));
	}
	return ret;
}
 
Example 2
Project: easyfpga-sdk-java   File: SerialPortList.java View source code 6 votes vote down vote up
/**
 * Get serial port names in Windows
 *
 * @since 2.3.0
 */
private static String[] getWindowsPortNames(Pattern pattern, Comparator<String> comparator) {
    String[] portNames = serialInterface.getSerialPortNames();
    if(portNames == null){
        return new String[]{};
    }
    TreeSet<String> ports = new TreeSet<String>(comparator);
    for(String portName : portNames){
        if(pattern.matcher(portName).find()){
            ports.add(portName);
        }
    }
    return ports.toArray(new String[ports.size()]);
}
 
Example 3
Project: StreamCruncher   File: HighestRowsWindowFTest.java View source code 6 votes vote down vote up
@Override
protected void verify(List<BatchResult> results) {
    TreeSet<Long> previousIds = new TreeSet<Long>();

    Long lastIdInBatch = null;

    System.out.println("--Results--");
    for (BatchResult result : results) {
        System.out.println("Batch created at: " + new Timestamp(result.getTimestamp())
                + ". Rows: " + result.getRows().size());

        List<Object[]> rows = result.getRows();

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

        System.out.println("  Batch results");
        for (Object[] objects : rows) {
            System.out.print("  ");
            for (Object object : objects) {
                System.out.print(object + " ");
            }
            System.out.println();

            /*
             * "event_id", "vehicle_id", "speed".
             */

            lastIdInBatch = ((Number) objects[0]).longValue();
        }

        Assert.assertFalse(previousIds.contains(lastIdInBatch),
                "Highest Id has already occurred in previous run, but appeared again");

        if (previousIds.isEmpty() == false) {
            Long prevCycId = previousIds.last();
            Assert.assertTrue((lastIdInBatch > prevCycId),
                    "Highest Id is not greater than previously seen Highest Ids");
        }

        previousIds.add(lastIdInBatch);
    }

    Assert.assertEquals(lastIdInBatch.longValue(), getMaxDataRows(),
            "Last Highest Id returned was not expected");
}
 
Example 4
Project: java-util   File: TestDeepEquals.java View source code 6 votes vote down vote up
@Test
public void testInequivalentCollections()
{
    Collection col1 = new TreeSet();
    fillCollection(col1);
    Collection col2 = new HashSet();
    fillCollection(col2);
    assertFalse(DeepEquals.deepEquals(col1, col2));
    assertEquals(DeepEquals.deepHashCode(col1), DeepEquals.deepHashCode(col2));

    col2 = new TreeSet();
    fillCollection(col2);
    col2.remove("lima");
    assertFalse(DeepEquals.deepEquals(col1, col2));
    assertNotEquals(DeepEquals.deepHashCode(col1), DeepEquals.deepHashCode(col2));

    assertFalse(DeepEquals.deepEquals(new HashMap(), new ArrayList()));
    assertFalse(DeepEquals.deepEquals(new ArrayList(), new HashMap()));
}
 
Example 5
Project: fiji   File: Graph_Test.java View source code 6 votes vote down vote up
private static void pickLeavesOfOneTrack(final TrackMateModel model) {
	DirectedNeighborIndex<Spot, DefaultWeightedEdge> cache = model.getTrackModel().getDirectedNeighborIndex();
	TreeSet<Spot> spots = new TreeSet<Spot>(Spot.frameComparator);
	spots.addAll(model.getTrackModel().vertexSet());
	Spot first = spots.first();
	DepthFirstIterator<Spot, DefaultWeightedEdge> iterator = model.getTrackModel().getDepthFirstIterator(first, true);

	while (iterator.hasNext()) {
		Spot spot = iterator.next();
		boolean isBranching = cache.successorsOf(spot).size() > 1;
		if (isBranching) {
			System.out.println(" - " + spot + " is branching to " + cache.successorsOf(spot).size() + " children.");
		} else {
			boolean isLeaf = cache.successorsOf(spot).size() == 0;
			if (isLeaf) {
				System.out.println(" - " + spot + " is a leaf.");
			} else {
				System.out.println(" - " + spot);
			}
		}
	}
}
 
Example 6
Project: teiid-designer   File: EObjectPropertiesOrderPreferences.java View source code 6 votes vote down vote up
public void replaceColumnsList( String eObject,
                                ArrayList list ) {
    Set propertiesSet = getOrderedPropertiesSet(eObject);
    if (propertiesSet == null) {
        propertiesSet = new TreeSet();
        this.eObjectMap.put(eObject, propertiesSet);
    } else {
        propertiesSet.clear();
    }
    propertiesSet.addAll(list);
}
 
Example 7
Project: fiji   File: SortedDepthFirstIterator.java View source code 6 votes vote down vote up
/**
  * This is where we add the multiple children in proper sorted order.
  */
 private void addUnseenChildrenOf(V vertex) {
 	
 	// Retrieve target vertices, and sort them in a TreeSet
 	TreeSet<V> sortedChildren = new TreeSet<V>(comparator);
 	// Keep a map of matching edges so that we can retrieve them in the same order
 	Map<V, E> localEdges = new HashMap<V, E>();
 	
     for (E edge : specifics.edgesOf(vertex)) {
     	V oppositeV = Graphs.getOppositeVertex(graph, edge, vertex);
     	if (!seen.containsKey(oppositeV)) {
     		sortedChildren.add(oppositeV);
     	}
     	localEdges.put(oppositeV, edge);
     }
     
     Iterator<V> it = sortedChildren.descendingIterator();
     while (it.hasNext()) {
V child = it.next();

         if (nListeners != 0) {
             fireEdgeTraversed(createEdgeTraversalEvent(localEdges.get(child)));
         }

         if (seen.containsKey(child)) {
             encounterVertexAgain(child, localEdges.get(child));
         } else {
             encounterVertex(child, localEdges.get(child));
         }
     }
 }
 
Example 8
Project: gpu-garbage-collection   File: HarnessOptionSet.java View source code 6 votes vote down vote up
private int[] parseIntSet(String str) {
  TreeSet<Integer> values = new TreeSet<Integer>();
  for (String element : str.split(",")) {
    values.add(Integer.valueOf(element));
  }
  int[] result = new int[values.size()];
  for (int i=0; i < result.length; i++) {
    result[i] = values.pollFirst();
  }
  return result;
}
 
Example 9
Project: SPINdle   File: TdlReasoningEngine2.java View source code 6 votes vote down vote up
@Override 
protected boolean isRecordExist(Literal literal,ConclusionType conclusionType){
	TreeSet<Temporal>consolidatedTemporals=getRecordTemporals(consolidatedTemporalRecords,conclusionType,literal,false);
	
	if (null==consolidatedTemporals){
		TreeSet<Temporal>temporals=getRecordTemporals(temporalRecords,conclusionType,literal,false);
		if (null==temporals)return false;
	
		consolidatedTemporals=new TreeSet<Temporal>(temporals);
		Temporal.consolidateTemporalSegments(consolidatedTemporals);
		
		Map<ConclusionType ,TreeSet<Temporal>> conclusionTypeSet=consolidatedTemporalRecords.get(literal);
		if (null==conclusionTypeSet){
			conclusionTypeSet=new TreeMap<ConclusionType,TreeSet<Temporal>>();
			consolidatedTemporalRecords.put(literal.cloneWithNoTemporal(),conclusionTypeSet);
		}
		conclusionTypeSet.put(conclusionType,consolidatedTemporals);
	}
	logMessage(Level.FINEST,4,"isRecordExist("+literal+","+conclusionType+")1="+consolidatedTemporals);
	Temporal literalTemporal=literal.getTemporal();
	if (null==literalTemporal)literalTemporal=PERSISTENT_TEMPORAL;
	
	
	SortedSet<Temporal>extractedTemporalSet=consolidatedTemporals.subSet(literalTemporal.getStartTimeAsInstance(),true,literalTemporal.getEndTimeAsInstance(),false);
	logMessage(Level.FINEST,4,"isRecordExist("+literal+","+conclusionType+")2:"+literalTemporal+":"+extractedTemporalSet);
	if (null!=extractedTemporalSet && extractedTemporalSet.size()>0){
		for (Temporal temporal:extractedTemporalSet){
			if (temporal.contains(literalTemporal))return true;
		}
	}
	Temporal extractedTemporal=consolidatedTemporals.floor(literalTemporal.getStartTimeAsInstance());
	logMessage(Level.FINEST,4,"isRecordExist("+literal+","+conclusionType+")3:"+literalTemporal+":"+extractedTemporal);
	if (null!=extractedTemporal){
		if (extractedTemporal.contains(literalTemporal))return true;
	}
	return false;
}
 
Example 10
Project: SpyGlass   File: HBaseSalter.java View source code 6 votes vote down vote up
private static byte[][] getAllKeysWithStartStop(byte[] originalKey, String prefixList, byte startPrefix, byte stopPrefix) {
    LOG.debug("".format("getAllKeysWithStartStop: OKEY (%s) PLIST (%s) PSRT (%s) PSTP (%s)",
            Bytes.toString(originalKey), prefixList, startPrefix, stopPrefix));

    char[] prefixArray = prefixList.toCharArray();
 TreeSet<Byte> prefixSet = new TreeSet<Byte>();
 
 for( char c : prefixArray ) {
  prefixSet.add((byte)c);
 }
 
 SortedSet<Byte> subSet = prefixSet.subSet(startPrefix, true, stopPrefix, true);

    LOG.debug("".format("Prefix subset (%s)", subSet));
 
 return getAllKeys(originalKey, subSet.toArray(new Byte[]{}));
}
 
Example 11
Project: airlift   File: ConfigAssertions.java View source code 6 votes vote down vote up
public static <T> void assertFullMapping(Map<String, String> properties, T expected)
{
    Assert.assertNotNull(properties, "properties");
    Assert.assertNotNull(expected, "expected");

    Class<T> configClass = (Class<T>) expected.getClass();
    ConfigurationMetadata<T> metadata = ConfigurationMetadata.getValidConfigurationMetadata(configClass);

    // verify all supplied properties are supported and not deprecated
    assertPropertiesSupported(metadata, properties.keySet(), false);

    // verify that every (non-deprecated) property is tested
    Set<String> nonDeprecatedProperties = new TreeSet<>();
    for (AttributeMetadata attribute : metadata.getAttributes().values()) {
        if (attribute.getInjectionPoint().getProperty() != null) {
            nonDeprecatedProperties.add(attribute.getInjectionPoint().getProperty());
        }
    }
    if (!properties.keySet().equals(nonDeprecatedProperties)) {
        TreeSet<String> untestedProperties = new TreeSet<>(nonDeprecatedProperties);
        untestedProperties.removeAll(properties.keySet());
        Assert.fail("Untested properties " + untestedProperties);
    }

    // verify that none of the values are the same as a default for the configuration
    T actual = newInstance(configClass, properties);
    T defaultInstance = newDefaultInstance(configClass);
    assertAttributesNotEqual(metadata, actual, defaultInstance);

    // verify that a configuration object created from the properties is equivalent to the expected object
    assertAttributesEqual(metadata, actual, expected);
}
 
Example 12
Project: picard-tools   File: PerTilePerCycleFileUtil.java View source code 6 votes vote down vote up
private Set<Integer> removeNonExistentCycles(final int[] cycles) {

        final TreeSet<Integer> inputCyclesSet = new TreeSet<Integer>();
        for (final Integer inputCycle : cycles) {
            inputCyclesSet.add(inputCycle);
        }

        inputCyclesSet.retainAll(detectedCycles);

        return inputCyclesSet;
    }
 
Example 13
Project: MapStoreMobile   File: OSMTagMapping.java View source code 6 votes vote down vote up
/**
 * @param histogram
 *            a histogram that represents the frequencies of tags
 */
public void optimizePoiOrdering(TShortIntHashMap histogram) {
	this.optimizedPoiIds.clear();
	final TreeSet<HistogramEntry> poiOrdering = new TreeSet<OSMTagMapping.HistogramEntry>();

	histogram.forEachEntry(new TShortIntProcedure() {
		@Override
		public boolean execute(short tag, int amount) {
			poiOrdering.add(new HistogramEntry(tag, amount));
			return true;
		}
	});

	short tmpPoiID = 0;

	OSMTag currentTag = null;
	for (HistogramEntry histogramEntry : poiOrdering.descendingSet()) {
		currentTag = this.idToPoiTag.get(Short.valueOf(histogramEntry.id));
		this.optimizedPoiIds.put(Short.valueOf(histogramEntry.id), Short.valueOf(tmpPoiID));
		LOGGER.finer("adding poi tag: " + currentTag.tagKey() + " id:" + tmpPoiID + " amount: "
				+ histogramEntry.amount);
		tmpPoiID++;
	}
}
 
Example 14
Project: webarchive-commons   File: TransformingPrefixStringFilter.java View source code 6 votes vote down vote up
public static TreeSet<String> makeTreeSet(Collection<String> blocks, 
		StringTransformer trans) {
	TreeSet<String> tmp = new TreeSet<String>();
	for(String filter : blocks) {
		if(trans != null) {
			filter = trans.transform(filter);
		}
		String possiblePrefix = tmp.floor(filter);
        if (possiblePrefix != null && filter.startsWith(possiblePrefix)) {
        	// don't add - a prefix is already in the set:
        } else {
        	// is this a prefix of the existing item?
        	String possibleLonger = tmp.ceiling(filter);
        	if(possibleLonger == null) {
        	} else if(possibleLonger.startsWith(filter)) {
        		tmp.remove(possibleLonger);
        	}
        	tmp.add(filter);
        }
	}
	return tmp;
}
 
Example 15
Project: iswc2012metadata   File: DataPVHMap.java View source code 6 votes vote down vote up
@Override
public String toString() {
	TreeSet<String> strdata = new TreeSet<String>();
	Iterator<Map.Entry<P, Set<V>>> iter = this.data.entrySet().iterator();
	while (iter.hasNext()){
		Map.Entry<P, Set<V>> entry = iter.next();
		strdata.add(entry.toString());
	}
	return strdata.toString();
}
 
Example 16
Project: gcs   File: ListRow.java View source code 6 votes vote down vote up
/**
 * @param categories The categories this data row belongs to.
 * @return Whether there was a change or not.
 */
public boolean setCategories(Collection<String> categories) {
	TreeSet<String> old = mCategories;
	mCategories = new TreeSet<>();
	for (String category : categories) {
		category = category.trim();
		if (category.length() > 0) {
			mCategories.add(category);
		}
	}
	if (!old.equals(mCategories)) {
		String id = getCategoryID();
		if (id != null) {
			notifySingle(id);
		}
		return true;
	}
	return false;
}
 
Example 17
Project: google-web-toolkit-svnmirror   File: TreeSetTest.java View source code 6 votes vote down vote up
/**
 * Test method for 'java.util.TreeSet.TreeSet(Comparator)'.
 * 
 * @see java.util.TreeSet#TreeSet(Comparator)
 */
public void testConstructor_comparator() {
  TreeSet<E> TreeSet = new TreeSet<E>(getComparator());
  _assertEmpty(TreeSet);
  if (isNaturalOrder()) {
    assertNull(TreeSet.comparator());
  } else {
    assertSame(getComparator(), TreeSet.comparator());
  }
}
 
Example 18
Project: WS171-frameworks-base   File: TreeSetTest.java View source code 6 votes vote down vote up
/**
 * 
 * Tests performance for the java.util.TreeSet method - clone()
 * 
 */

public void testTreeSetClone() {
    Object obj;
    TreeSet<Integer> set = sSet;
    for (int i = ITERATIONS - 1; i >= 0; i--) {
        obj = set.clone();
        obj = set.clone();
        obj = set.clone();
        obj = set.clone();
        obj = set.clone();
        obj = set.clone();
        obj = set.clone();
        obj = set.clone();
        obj = set.clone();
        obj = set.clone();
    }
}
 
Example 19
Project: WS171-frameworks-base   File: TreeSetTest.java View source code 6 votes vote down vote up
/**
 * 
 * Tests performance of tailSet(Integer arg0) - TreeSet
 * 
 */

public void testTreeSetTailSet() {
    Integer value = new Integer(900);
    SortedSet set;
    TreeSet<Integer> tSet = sSet;
    for (int i = ITERATIONS - 1; i >= 0; i--) {
        set = tSet.tailSet(value);
        set = tSet.tailSet(value);
        set = tSet.tailSet(value);
        set = tSet.tailSet(value);
        set = tSet.tailSet(value);
        set = tSet.tailSet(value);
        set = tSet.tailSet(value);
        set = tSet.tailSet(value);
        set = tSet.tailSet(value);
        set = tSet.tailSet(value);
    }
}
 
Example 20
Project: Magnolia   File: DefaultContentTest.java View source code 5 votes vote down vote up
@Test
public void testNameFilteringWorksForBothBinaryAndNonBinaryProperties() throws Exception {
    String contentProperties = StringUtils.join(Arrays.asList(
            "[email protected]=mgnl:content",
            "[email protected]=mgnl:contentNode",
            "[email protected]=mgnl:contentNode",
            "[email protected]=mgnl:contentNode",

            // 2 regular props
            "/somepage/mypage/paragraphs/0/attention=booyah",
            "/somepage/mypage/paragraphs/0/imaginary=date:2009-10-14T08:59:01.227-04:00",

            // 3 binaries
            "[email protected]=mgnl:resource",
            "/somepage/mypage/paragraphs/0/attachment1.fileName=hello",
            "/somepage/mypage/paragraphs/0/attachment1.extension=gif",
            // being a binary node, magnolia knows to store data as jcr:data w/o need to be explicitly told so
            "/somepage/mypage/paragraphs/0/attachment1=binary:X",
            "/somepage/mypage/paragraphs/0/attachment1.jcr\\:mimeType=image/gif",
            "/somepage/mypage/paragraphs/0/attachment1.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00",

            "[email protected]=mgnl:resource",
            "/somepage/mypage/paragraphs/0/attachment2.fileName=test",
            "/somepage/mypage/paragraphs/0/attachment2.extension=jpeg",
            "/somepage/mypage/paragraphs/0/attachment2=binary:X",
            "/somepage/mypage/paragraphs/0/attachment2.jcr\\:mimeType=image/jpeg",
            "/somepage/mypage/paragraphs/0/attachment2.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00",

            "[email protected]=mgnl:resource",
            "/somepage/mypage/paragraphs/0/image3.fileName=third",
            "/somepage/mypage/paragraphs/0/image3.extension=png",
            "/somepage/mypage/paragraphs/0/image3=binary:X",
            "/somepage/mypage/paragraphs/0/image3.jcr\\:mimeType=image/png",
            "/somepage/mypage/paragraphs/0/image3.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00",

            // and more which should not match
            "/somepage/mypage/paragraphs/0/foo=bar",
            "/somepage/mypage/paragraphs/0/mybool=boolean:true",
            "[email protected]=mgnl:resource",
            "/somepage/mypage/paragraphs/0/rand.fileName=randdddd",
            "/somepage/mypage/paragraphs/0/rand.extension=png",
            "/somepage/mypage/paragraphs/0/rand=binary:X",
            "/somepage/mypage/paragraphs/0/rand.jcr\\:mimeType=image/png",
            "/somepage/mypage/paragraphs/0/rand.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00"
    ), "\n");
    final HierarchyManager hm = MgnlContext.getHierarchyManager(RepositoryConstants.WEBSITE);
    new PropertiesImportExport().createContent(hm.getRoot(), IOUtils.toInputStream(contentProperties));
    hm.save();

    final Content content = hm.getContent("/somepage/mypage/paragraphs/0");
    final Collection<NodeData> props = content.getNodeDataCollection("att*|ima*");
    assertEquals(5, props.size());

    // sort by name
    final TreeSet<NodeData> sorted = new TreeSet<NodeData>(new Comparator<NodeData>() {
        @Override
        public int compare(NodeData o1, NodeData o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    sorted.addAll(props);
    // sanity check - just recheck we still have 5 elements
    assertEquals(5, sorted.size());
    final Iterator<NodeData> it = sorted.iterator();
    final NodeData a = it.next();
    final NodeData b = it.next();
    final NodeData c = it.next();
    final NodeData d = it.next();
    final NodeData e = it.next();
    assertEquals("attachment1", a.getName());
    assertEquals(PropertyType.BINARY, a.getType());
    assertEquals("attachment2", b.getName());
    assertEquals(PropertyType.BINARY, b.getType());
    assertEquals("image3", d.getName());
    assertEquals(PropertyType.BINARY, d.getType());
    assertEquals("image3", d.getName());
    assertEquals(PropertyType.BINARY, d.getType());

    assertEquals("attention", c.getName());
    assertEquals(PropertyType.STRING, c.getType());
    assertEquals("booyah", c.getString());
    assertEquals("imaginary", e.getName());
    assertEquals(PropertyType.DATE, e.getType());
    assertEquals(true, e.getDate().before(Calendar.getInstance()));
}
 
Example 21
Project: SimpleAlgebra_V2   File: GeometricAlgebraOrd.java View source code 5 votes vote down vote up
@Override
public boolean calcOrd(HashSet<BigInteger> ka, HashSet<BigInteger> kb, HashSet<BigInteger> el , U dim ) 
{
	boolean negate = false;
	
	final TreeSet<BigInteger> kaa = new TreeSet<BigInteger>( ka );
	final TreeSet<BigInteger> kbb = new TreeSet<BigInteger>( kb );
	
	
	final int sz = kaa.size() + kbb.size();
	
	
	final BigInteger[] arr = new BigInteger[ sz ];
	
	
	int cnt = 0;
	Iterator<BigInteger> it = kaa.iterator();
	while( it.hasNext() )
	{
		arr[ cnt ] = it.next();
		cnt++;
	}
	it = kbb.iterator();
	while( it.hasNext() )
	{
		arr[ cnt ] = it.next();
		cnt++;
	}
	
	
	
	boolean chg = true;
	while( chg )
	{
		chg = false;
		for( cnt = 0 ; cnt < ( sz - 1 ) ; cnt++ )
		{
			final BigInteger a0 = arr[ cnt ];
			final BigInteger a1 = arr[ cnt + 1 ];
			if( ( a0 == null ) && ( a1 != null ) )
			{
				arr[ cnt ] = a1;
				arr[ cnt + 1 ] = a0;
				chg = true;
			}
			else
			{
				if( ( a0 != null ) && ( a1 != null ) )
				{
					final int cmp = a0.compareTo( a1 );
					if( cmp == 0 )
					{
						arr[ cnt ] = null;
						arr[ cnt + 1 ] = null;
						chg = true;
					}
					else
					{
						if( cmp > 0 )
						{
							arr[ cnt ] = a1;
							arr[ cnt + 1 ] = a0;
							chg = true;
							negate = !negate;
						}
					}
				}
			}
		}
	}
	
	
	for( cnt = 0 ; cnt < sz ; cnt++ )
	{
		if( arr[ cnt ] != null )
		{
			el.add( arr[ cnt ] );
		}
	}
	
	
	
	
	return( negate );
}
 
Example 22
Project: aipo   File: VelocityPortletSetControl.java View source code 5 votes vote down vote up
/**
 * Populate a list of tabs that should be displayed by this control.
 * Each tab represents a child portlet.
 *
 * This method works best if the child of this control is a PortletSet
 * whose controller implements the PanedPortletController interface.
 * 
 * @param portlet the base portlet to explore for children
 * @
 */
private Collection getTabs(PortletSet portlets, RunData rundata, Context context)
{       
    TreeSet tabs = new TreeSet(new PortletTabComparator());
    PanedPortletController controller = null;

    // if portlet is a PortletSet, try to retrieve the Controller
    // we need a PanedPortletController to work properly.
    if (portlets.getController() instanceof PanedPortletController)
    {    
        controller = (PanedPortletController) portlets.getController();
    }

    int count = 0;
    for (Enumeration en = portlets.getPortlets(); en.hasMoreElements(); count++)
    {
        Portlet p = (Portlet) en.nextElement();
        PortalResource portalResource = new PortalResource(p);

        // Secure the tabs
        try
        {
            JetspeedLink jsLink = JetspeedLinkFactory.getInstance(rundata);
            portalResource.setOwner(jsLink.getUserName());
            JetspeedLinkFactory.putInstance(jsLink);
        }
        catch (Exception e)
        {
            logger.warn(e.toString(), e);
            portalResource.setOwner(null);
        }
        JetspeedRunData jdata = (JetspeedRunData) rundata;
        boolean hasView = JetspeedSecurity.checkPermission((JetspeedUser) jdata.getUser(),
                                                            portalResource, 
                                                            JetspeedSecurity.PERMISSION_VIEW);
        if (!hasView)
        {
            continue;
        }
        // skip any closed portlet
        if ((p instanceof PortletState) && (((PortletState) p).isClosed(rundata)))
        {
            continue;
        }            

        String mstate = p.getAttribute("_menustate", "open", rundata);
        if (mstate.equals("closed"))
        {
            continue;
        }

        PortletTab tab = new PortletTab();
        
        // Handle the portlet title
        String title = null;            
        PortletInstance pi = PersistenceManager.getInstance(p, rundata);
        if (pi != null)
        {
            title = pi.getTitle();
            if (title == null)
            {
                title = (p.getTitle() != null) ? p.getTitle() : p.getName();
            }
        }
        tab.setTitle(title);

        tab.setPosition(p.getPortletConfig().getPosition());
        if (tabs.contains(tab))
        {
            PortletTab lastTab = (PortletTab) tabs.last();
            int nextPos = lastTab.getPosition() + 1;
            tab.setPosition(nextPos);            
        }        
            
        if (controller != null)
        {
            tab.setSelected(controller.isSelected(p, rundata));
            tab.setLink(controller.getPortletURI(p, rundata).toString());                
        }
            
        tab.setActions(buildActionList(rundata, p));
        tabs.add(tab);
    }

    return tabs;
}
 
Example 23
Project: metrics   File: ParallelLeastShardAllocationStrategy.java View source code 5 votes vote down vote up
/**
 * [email protected]}
 */
@Override
public Set<String> rebalance(final Map<ActorRef, IndexedSeq<String>> currentShardAllocations, final Set<String> rebalanceInProgress) {
    // Only keep the rebalances that are in progress
    _pendingRebalances.keySet().retainAll(rebalanceInProgress);

    // Build a friendly set of current allocations
    // Sort the set by "effective shards after rebalance"
    final TreeSet<RegionShardAllocations> allocations =
            new TreeSet<>(Comparator.comparingInt(RegionShardAllocations::getEffectiveShardCount));

    for (final Map.Entry<ActorRef, IndexedSeq<String>> entry : currentShardAllocations.entrySet()) {
        allocations.add(
                new RegionShardAllocations(
                        entry.getKey(),
                        // Only count the shards that are not currently rebalancing
                        JavaConversions.setAsJavaSet(entry.getValue().<String>toSet())
                                .stream()
                                .filter(e -> !rebalanceInProgress.contains(e))
                                .collect(Collectors.toSet())));
    }

    final Set<String> toRebalance = Sets.newHashSet();

    for (int x = 0; x < _maxParallel - rebalanceInProgress.size(); x++) {
        // Note: the poll* functions remove the item from the set
        final RegionShardAllocations leastShards = allocations.pollFirst();
        final RegionShardAllocations mostShards = allocations.pollLast();


        // Make sure that we have more than 1 region
        if (mostShards == null) {
            LOGGER.debug()
                    .setMessage("Cannot rebalance shards, less than 2 shard regions found.")
                    .log();
            break;
        }

        // Make sure that the difference is enough to warrant a rebalance
        if (mostShards.getEffectiveShardCount() - leastShards.getEffectiveShardCount() < _rebalanceThreshold) {
            LOGGER.debug()
                    .setMessage("Not rebalancing any (more) shards, shard region with most shards already balanced with least")
                    .addData("most", mostShards.getEffectiveShardCount())
                    .addData("least", leastShards.getEffectiveShardCount())
                    .addData("rebalanceThreshold", _rebalanceThreshold)
                    .log();
            break;
        }

        final String rebalanceShard = Iterables.get(mostShards.getShards(), 0);

        // Now we take a shard from mostShards and give it to leastShards
        mostShards.removeShard(rebalanceShard);
        leastShards.incrementIncoming();
        toRebalance.add(rebalanceShard);
        _pendingRebalances.put(rebalanceShard, leastShards.getRegion());

        // Put them back in the list with their new counts
        allocations.add(mostShards);
        allocations.add(leastShards);
    }

    // Transform the currentShardAllocations to a Map<ActorRef, Set<String>> from the
    // Scala representation
    final Map<ActorRef, Set<String>> currentAllocations = Maps.transformValues(
            currentShardAllocations,
            e -> Sets.newHashSet(JavaConversions.seqAsJavaList(e)));

    final RebalanceNotification notification = new RebalanceNotification(
            currentAllocations,
            rebalanceInProgress,
            _pendingRebalances);
    LOGGER.debug()
            .setMessage("Broadcasting rebalance info")
            .addData("target", _notify)
            .addData("shardAllocations", notification)
            .log();
    if (_notify.isPresent()) {
        _notify.get().tell(notification, ActorRef.noSender());
    }
    return toRebalance;
}
 
Example 24
Project: fiji   File: NearestNeighborTracker.java View source code 5 votes vote down vote up
@Override
public boolean process() {
	long start = System.currentTimeMillis();

	reset();
	
	final double maxLinkingDistance = (Double) settings.get(KEY_LINKING_MAX_DISTANCE);
	final double maxDistSquare = maxLinkingDistance  * maxLinkingDistance;

	final TreeSet<Integer> frames = new TreeSet<Integer>(spots.keySet());
	Thread[] threads = new Thread[numThreads];

	// Prepare the thread array
	final AtomicInteger ai = new AtomicInteger(frames.first());
	final AtomicInteger progress = new AtomicInteger(0);
	for (int ithread = 0; ithread < threads.length; ithread++) {

		threads[ithread] = new Thread("TrackMate spot feature calculating thread "+(1+ithread)+"/"+threads.length) {  

			public void run() {

				for (int i = ai.getAndIncrement(); i < frames.last(); i = ai.getAndIncrement()) {

					// Build frame pair
					int sourceFrame = i;
					int targetFrame = frames.higher(i);
					List<Spot> sourceSpots = spots.get(sourceFrame);
					List<Spot> targetSpots = spots.get(targetFrame);
					
					List<RealPoint> targetCoords = new ArrayList<RealPoint>(targetSpots.size());
					List<FlagNode<Spot>> targetNodes = new ArrayList<FlagNode<Spot>>(targetSpots.size());
					for(Spot spot : targetSpots) {
						double[] coords = new double[3];
						TMUtils.localize(spot, coords);
						targetCoords.add(new RealPoint(coords));
						targetNodes.add(new FlagNode<Spot>(spot));
					}
					
					
					KDTree<FlagNode<Spot>> tree = new KDTree<FlagNode<Spot>>(targetNodes, targetCoords);
					NearestNeighborFlagSearchOnKDTree<Spot> search = new NearestNeighborFlagSearchOnKDTree<Spot>(tree);
					
					// For each spot in the source frame, find its nearest neighbor in the target frame
					for (Spot source : sourceSpots) {

						double[] coords = new double[3];
						TMUtils.localize(source, coords);
						RealPoint sourceCoords = new RealPoint(coords);
						search.search(sourceCoords);
						
						double squareDist = search.getSquareDistance();
						FlagNode<Spot> targetNode = search.getSampler().get();
						
						if (squareDist > maxDistSquare) {
							// The closest we could find is too far. We skip this source spot and do not create a link
							continue;								
						}

						// Everything is ok. This mode is free and below max dist. We create a link
						// and mark this node as assigned.

						targetNode.setVisited(true);
						synchronized (graph) {
							DefaultWeightedEdge edge = graph.addEdge(source, targetNode.getValue());
							graph.setEdgeWeight(edge, squareDist);
						}

					}
					logger.setProgress(progress.incrementAndGet() / (float)frames.size() );

				}
			}
		};

		
	}
	
	logger.setStatus("Tracking...");
	logger.setProgress(0);
	
	SimpleMultiThreading.startAndJoin(threads);
	
	logger.setProgress(1);
	logger.setStatus("");
	
	long end = System.currentTimeMillis();
	processingTime = end - start;
	return true;
}