List of usage examples for java.util ArrayDeque ArrayDeque
public ArrayDeque()
From source file:com.grepcurl.random.ObjectGenerator.java
public <T> T generate(Class<T> klass, SetterOverrides setterOverrides, String[] constructorArgTypes, Object... constructorArgs) { Validate.notNull(klass);/* w ww . ja va2 s. c o m*/ Validate.notNull(constructorArgs); if (verbose) { log(String.format("generating object of type: %s, with args: %s, of types: %s, with overrides: %s", klass, Arrays.toString(constructorArgs), Arrays.toString(constructorArgTypes), setterOverrides)); } try { Deque<Object> objectStack = new ArrayDeque<>(); Class[] constructorTypes = _toClasses(constructorArgTypes, constructorArgs); T t = klass.getConstructor(constructorTypes).newInstance(constructorArgs); objectStack.push(t); Method[] methods = klass.getMethods(); for (Method method : methods) { _processMethod(method, setterOverrides, t, objectStack); } objectStack.pop(); return t; } catch (Exception e) { throw new FailedRandomObjectGenerationException(e); } }
From source file:de.tiqsolutions.hdfs.HadoopFileSystemPath.java
Deque<Path> getPathSegments() { Deque<Path> paths = new ArrayDeque<>(); Path root = getRoot();/* w w w .j a v a 2 s . com*/ Path p = this; while (p != null && !p.equals(root)) { paths.push(p.getFileName()); p = p.getParent(); } return paths; }
From source file:logicProteinHypernetwork.analysis.reactions.ComplexMultigraph.java
public Set<Integer> bfs() { Set<Integer> visited = new HashSet<Integer>(); Deque<Integer> todo = new ArrayDeque<Integer>(); todo.add(0);/*from w ww . j a v a 2 s.c o m*/ while (!todo.isEmpty()) { int u = todo.remove(); visited.add(u); for (int v : getNeighbors(u)) { todo.add(v); } } return visited; }
From source file:com.google.gwt.emultest.java.util.ArrayDequeTest.java
public void testElement() { Object o1 = new Object(); Object o2 = new Object(); ArrayDeque<Object> deque = new ArrayDeque<>(); try {/* w w w.ja v a 2s. c o m*/ deque.element(); fail(); } catch (NoSuchElementException expected) { } deque.add(o1); assertEquals(o1, deque.element()); checkDequeSizeAndContent(deque, o1); deque.add(o2); assertEquals(o1, deque.element()); checkDequeSizeAndContent(deque, o1, o2); deque.clear(); assertTrue(deque.isEmpty()); try { deque.element(); fail(); } catch (NoSuchElementException expected) { } }
From source file:it.scoppelletti.mobilepower.app.FragmentLayoutController.java
/** * Ripristina lo stato dell’istanza. * /* w ww .j ava2s . com*/ * <P>L’attività ripristina lo stato dell’istanza * {@code FragmentLayoutController} all’interno del proprio metodo * {@code onRestoreInstanceState}.</P> * * @param savedInstanceState Stato dell’istanza. * @param fragmentCollector Collettore dei frammenti di dettaglio. */ public void onRestoreInstanceState(Bundle savedInstanceState, FragmentLayoutController.FragmentCollector fragmentCollector) { int n, oldPanelCount, tnId; String tag; ActivitySupport activitySupport; FragmentSupport fragment; FragmentManager fragmentMgr; FragmentLayoutController.BackStackChangedListener backStackListener; Queue<FragmentSupport> fragmentQueue; Queue<FragmentLayoutController.FragmentEntry> clonedQueue; if (savedInstanceState == null) { throw new NullPointerException("Argument savedInstanceState is null."); } if (fragmentCollector == null) { throw new NullPointerException("Argument fragmentCollector is null."); } if (!(myActivity instanceof ActivitySupport)) { myLogger.warn("Activity not implement interface ActivitySupport."); return; } oldPanelCount = savedInstanceState.getInt(FragmentLayoutController.STATE_PANELCOUNT, 0); if (oldPanelCount < 1) { myLogger.warn("Unexpected {}={} in saved instance state.", FragmentLayoutController.STATE_PANELCOUNT, oldPanelCount); return; } myLogger.debug("{}: current={}, saved instance state={}.", new Object[] { FragmentLayoutController.STATE_PANELCOUNT, myFrameCount, oldPanelCount }); if (oldPanelCount == myFrameCount) { // Il numero di pannelli non e' cambiato: // Il sistema ha gia' ripristinato correttamente i frammenti. return; } fragmentQueue = new ArrayDeque<FragmentSupport>(); fragmentCollector.collectFragments(fragmentQueue); // Ad ogni frammento associo il tag con il quale è stato // inserito clonedQueue = new ArrayDeque<FragmentLayoutController.FragmentEntry>(); while (!fragmentQueue.isEmpty()) { fragment = fragmentQueue.remove(); if (fragment == null) { myLogger.warn("Ignoring null."); continue; } tag = fragment.asFragment().getTag(); if (StringUtils.isBlank(tag)) { myLogger.warn("Ignoring fragment with empty tag."); continue; } clonedQueue.offer(new FragmentLayoutController.FragmentEntry(fragment.cloneFragment(), tag)); } fragmentQueue = null; // free memory activitySupport = (ActivitySupport) myActivity; fragmentMgr = activitySupport.getSupportFragmentManager(); // Ripristino la configurazione dei frammenti iniziale for (n = fragmentMgr.getBackStackEntryCount(); n > 0; n--) { fragmentMgr.popBackStack(); } if (myFrameCount > 1) { tnId = arrangeFragments(fragmentMgr, clonedQueue); } else { tnId = arrangePanel(fragmentMgr, clonedQueue); } if (Build.VERSION.SDK_INT < BuildCompat.VERSION_CODES.HONEYCOMB) { return; } // - Android 4.1.2 // La barra delle azioni non e' correttamente aggiornata forse perche' // si assume che non ce ne sia bisogno con transazioni schedulate // durante il ripristino dell'attivita' (o magari perche' non e' proprio // previsto che si schedulino transazioni durante il ripristino // dell'attivita'): // Visto che l'esecuzione delle transazioni e' asincrona, devo // utilizzare un gestore degli eventi di modifica del back stack che // gestisca l’ultima transazione che ho schedulato. backStackListener = new FragmentLayoutController.BackStackChangedListener(myActivity, fragmentMgr, tnId); fragmentMgr.addOnBackStackChangedListener(backStackListener); }
From source file:org.xwiki.xdomviz.Main.java
/** * <p>/*from w w w . j a va2s .c o m*/ * This method performs a normalization of the tree by removing all the multi-edges (due to a node having multiple * parents). This happens often with SpaceBlocks, which are reused all over the XDOM. The algorithm performs a * breadth first visit. For each visited node, it checks how many times a child occurs in its children list. If a * child occurs more than once, then we create new nodes, one for each occurrence. * </p> * <p> * The node tree corresponding to the XDOM of "this is a test" is: * </p> * <ul> * <li>XDOM -> P</li> * <li>P -> "This"</li> * <li>P -> S (3 edges, each one representing a space)</li> * <li>P -> "is"</li> * <li>P -> "a"</li> * <li>P -> "test"</li> * </ul> * <p> * The normalized tree will be: * </p> * <ul> * <li>XDOM -> P</li> * <li>P -> "This"</li> * <li>P -> S</li> * <li>P -> "is"</li> * <li>P -> S</li> * <li>P -> "a"</li> * <li>P -> S</li> * <li>P -> "test"</li> * </ul> * <p> * In a normalized tree, each node has one and only one parent. * </p> * * @param root The root node of the tree. * @return The root node of the normalized tree. */ private static Node normalize(Node root) { // Breadth first visit of the XDOM to assign simple ids to nodes. Queue<Node> nodesQueue = new ArrayDeque<Node>(); nodesQueue.add(root); while (!nodesQueue.isEmpty()) { Node node = nodesQueue.poll(); // This map contains, for the current node, where are the occurrences in the children list of each child. Map<Node, List<Integer>> nodeToIndexesMap = new HashMap<Node, List<Integer>>(); int i = 0; // For each child calculate store the its position in the indexes list. for (Node child : node.getChildren()) { List<Integer> indexes = nodeToIndexesMap.get(child); if (indexes == null) { indexes = new ArrayList<Integer>(); nodeToIndexesMap.put(child, indexes); } indexes.add(i); i++; } for (Node child : nodeToIndexesMap.keySet()) { List<Integer> indexes = nodeToIndexesMap.get(child); // If the indexes size is > 1 then a child occurs multiple times in a if (indexes.size() > 1) { for (Integer index : indexes) { Node newNode = new Node(child.getBlock()); newNode.getParents().add(node); newNode.getChildren().addAll(child.getChildren()); node.getChildren().set(index, newNode); } } } for (Node child : node.getChildren()) { nodesQueue.add(child); } } return root; }
From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java
@Before @SuppressWarnings("unchecked") public void setup() { responseBuffer = new Disruptor<ResponseEvent>(new EventFactory<ResponseEvent>() { @Override//from w ww .j av a 2s. c om public ResponseEvent newInstance() { return new ResponseEvent(); } }, 1024, Executors.newCachedThreadPool()); firedEvents = Collections.synchronizedList(new ArrayList<CouchbaseMessage>()); latch = new CountDownLatch(1); responseBuffer.handleEventsWith(new EventHandler<ResponseEvent>() { @Override public void onEvent(ResponseEvent event, long sequence, boolean endOfBatch) throws Exception { firedEvents.add(event.getMessage()); latch.countDown(); } }); responseRingBuffer = responseBuffer.start(); CoreEnvironment environment = mock(CoreEnvironment.class); when(environment.scheduler()).thenReturn(Schedulers.computation()); when(environment.queryEnabled()).thenReturn(Boolean.TRUE); when(environment.maxRequestLifetime()).thenReturn(10000L); when(environment.autoreleaseAfter()).thenReturn(2000L); endpoint = mock(AbstractEndpoint.class); when(endpoint.environment()).thenReturn(environment); when(environment.userAgent()).thenReturn("Couchbase Client Mock"); queue = new ArrayDeque<QueryRequest>(); handler = new QueryHandler(endpoint, responseRingBuffer, queue, false); channel = new EmbeddedChannel(handler); }
From source file:org.apache.asterix.om.typecomputer.impl.RecordRemoveFieldsTypeComputer.java
@Override public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env, IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException { AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expression; IAType type0 = (IAType) env.getType(funcExpr.getArguments().get(0).getValue()); List<List<String>> pathList = new ArrayList<>(); Set<String> fieldNameSet = new HashSet<>(); Deque<String> fieldPathStack = new ArrayDeque<>(); ARecordType inputRecordType = getRecordTypeFromType(type0, expression); if (inputRecordType == null) { return BuiltinType.ANY; }/*ww w. j a v a2s . co m*/ AbstractLogicalExpression arg1 = (AbstractLogicalExpression) funcExpr.getArguments().get(1).getValue(); IAType inputListType = (IAType) env.getType(arg1); AOrderedListType inputOrderedListType = TypeComputeUtils.extractOrderedListType(inputListType); if (inputOrderedListType == null) { throw new AlgebricksException( "The function 'remove-fields' expects an ordered list as the second argument, but got " + inputListType); } ATypeTag tt = inputOrderedListType.getItemType().getTypeTag(); if (tt == ATypeTag.STRING) { // If top-fieldlist if (setFieldNameSet(arg1, fieldNameSet)) { return buildOutputType(fieldPathStack, inputRecordType, fieldNameSet, pathList); } else { return DefaultOpenFieldType.NESTED_OPEN_RECORD_TYPE; } } else { // tt == ATypeTag.ANY, meaning the list is nested computeTypeFromNonConstantExpression(arg1, fieldNameSet, pathList); IAType resultType = buildOutputType(fieldPathStack, inputRecordType, fieldNameSet, pathList); return resultType; } }
From source file:org.talend.dataquality.semantic.statistics.SemanticQualityAnalyzer.java
/** * For the validation of a COMPOUND category, we only have to valid the leaves children categories. * This methods find the DICT children categories and the REGEX children categories. * /* w w w . j av a 2 s .c o m*/ * @param id, the category from we search the children * @return the DICT children categories and the REGEX children categories with a map. */ private Map<CategoryType, Set<DQCategory>> getChildrenCategories(String id) { Deque<String> catToSee = new ArrayDeque<>(); Set<String> catAlreadySeen = new HashSet<>(); Map<CategoryType, Set<DQCategory>> children = new HashMap<>(); children.put(CategoryType.REGEX, new HashSet<DQCategory>()); children.put(CategoryType.DICT, new HashSet<DQCategory>()); catToSee.add(id); String currentCategory; while (!catToSee.isEmpty()) { currentCategory = catToSee.pop(); DQCategory dqCategory = crm.getCategoryMetadataById(currentCategory); if (dqCategory != null) if (!CollectionUtils.isEmpty(dqCategory.getChildren())) { for (DQCategory child : dqCategory.getChildren()) { if (!catAlreadySeen.contains(child.getId())) { catAlreadySeen.add(child.getId()); catToSee.add(child.getId()); } } } else if (!currentCategory.equals(id)) { children.get(dqCategory.getType()).add(dqCategory); } } return children; }
From source file:com.grepcurl.random.ObjectGenerator.java
public <T, E> Collection<T> randomCollection(Type elementType, Class<E> collectionType, int count) { return randomCollection(elementType, collectionType, new SetterOverrides(), count, new ArrayDeque<>()); }