Example usage for java.util Queue isEmpty

List of usage examples for java.util Queue isEmpty

Introduction

In this page you can find the example usage for java.util Queue isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this collection contains no elements.

Usage

From source file:org.jbpm.services.task.jaxb.ComparePair.java

public void recursiveCompare() {
    Queue<ComparePair> compares = new LinkedList<ComparePair>();
    compares.add(this);
    while (!compares.isEmpty()) {
        compares.addAll(compares.poll().compare());
    }//from   w  ww  .  java  2s .c  o m
}

From source file:org.lunarray.model.descriptor.scanner.AnnotationScannerUtil.java

/**
 * Transitively tests for marker marks./* w  w  w  . ja  v  a  2s  .  c o m*/
 * 
 * @param marker
 *            The marker.
 * @param processed
 *            The processed annotations.
 * @param process
 *            The annotations to process.
 * @return True if and only if the marker marks any of the processed
 *         annotations.
 */
private boolean isMarkedTransiviteProcess(final Class<? extends Annotation> marker,
        final Set<Class<? extends Annotation>> processed, final Queue<Class<? extends Annotation>> process) {
    boolean marked = false;
    while (!process.isEmpty()) {
        final Class<? extends Annotation> poll = process.poll();
        processed.add(poll);
        if (poll.equals(marker)) {
            marked = true;
            process.clear();
        } else {
            for (final Annotation annotation : poll.getAnnotations()) {
                final Class<? extends Annotation> annotationType = annotation.annotationType();
                if (!processed.contains(annotationType)) {
                    process.add(annotationType);
                }
            }
        }
    }
    return marked;
}

From source file:org.apache.http2.impl.client.HttpAuthenticator.java

public boolean authenticate(final HttpHost host, final HttpResponse response,
        final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) {
    try {/*ww  w  .  j a  v  a  2s  .  c  o m*/
        if (this.log.isDebugEnabled()) {
            this.log.debug(host.toHostString() + " requested authentication");
        }
        Map<String, Header> challenges = authStrategy.getChallenges(host, response, context);
        if (challenges.isEmpty()) {
            this.log.debug("Response contains no authentication challenges");
            return false;
        }

        AuthScheme authScheme = authState.getAuthScheme();
        switch (authState.getState()) {
        case FAILURE:
            return false;
        case SUCCESS:
            authState.reset();
            break;
        case CHALLENGED:
        case HANDSHAKE:
            if (authScheme == null) {
                this.log.debug("Auth scheme is null");
                authStrategy.authFailed(host, null, context);
                authState.reset();
                authState.setState(AuthProtocolState.FAILURE);
                return false;
            }
        case UNCHALLENGED:
            if (authScheme != null) {
                String id = authScheme.getSchemeName();
                Header challenge = challenges.get(id.toLowerCase(Locale.US));
                if (challenge != null) {
                    this.log.debug("Authorization challenge processed");
                    authScheme.processChallenge(challenge);
                    if (authScheme.isComplete()) {
                        this.log.debug("Authentication failed");
                        authStrategy.authFailed(host, authState.getAuthScheme(), context);
                        authState.reset();
                        authState.setState(AuthProtocolState.FAILURE);
                        return false;
                    } else {
                        authState.setState(AuthProtocolState.HANDSHAKE);
                        return true;
                    }
                } else {
                    authState.reset();
                    // Retry authentication with a different scheme
                }
            }
        }
        Queue<AuthOption> authOptions = authStrategy.select(challenges, host, response, context);
        if (authOptions != null && !authOptions.isEmpty()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Selected authentication options: " + authOptions);
            }
            authState.setState(AuthProtocolState.CHALLENGED);
            authState.update(authOptions);
            return true;
        } else {
            return false;
        }
    } catch (MalformedChallengeException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn("Malformed challenge: " + ex.getMessage());
        }
        authState.reset();
        return false;
    }
}

From source file:com.ibm.amc.feedback.FeedbackHandler.java

public void handleRequest(final HttpServletRequest request, final HttpServletResponse response) {
    if (logger.isEntryEnabled())
        logger.entry("handleRequest", request, response);

    final String user = request.getRemoteUser();
    final Queue<ActionStatusResponse> statuses = getActionStatuses(user);
    if (statuses.isEmpty()) {
        // No updates pending - register listener
        final AsyncContext asyncContext = request.startAsync(request, response);
        asyncContext.setTimeout(900000000L);
        logger.debug("handleRequest", "Registering new listener for user " + user);
        synchronized (feedbackListeners) {
            Set<AsyncContext> contexts = feedbackListeners.get(user);
            if (contexts == null) {
                contexts = new HashSet<AsyncContext>();
                feedbackListeners.put(user, contexts);
            }//from w  w w  . j  a  v a2  s .co  m
            contexts.add(asyncContext);
        }

        // Timeout listener
        executor.schedule(new Runnable() {

            @Override
            public void run() {
                synchronized (feedbackListeners) {
                    final Set<AsyncContext> contexts = feedbackListeners.get(user);
                    if (contexts.remove(asyncContext)) {
                        if (logger.isDebugEnabled())
                            logger.debug("handleRequest$Runnable.run", "Timing out listener for user " + user);
                        writeResponse(asyncContext.getResponse(), new LinkedList<ActionStatusResponse>());
                        asyncContext.complete();
                        if (contexts.isEmpty())
                            feedbackListeners.remove(user);
                    }
                }
            }

        }, POLLING_TIMEOUT, TimeUnit.SECONDS);
    } else {
        // Update pending - send response immediately
        writeResponse(response, statuses);
    }

    if (logger.isEntryEnabled())
        logger.exit("handleRequest");
}

From source file:info.magnolia.test.mock.jcr.MockSession.java

@Override
public Node getNodeByIdentifier(String id) throws RepositoryException {
    Queue<Node> queue = new LinkedList<Node>();
    queue.add(rootNode);//from w  w w  .j  a va2  s.c om
    while (!queue.isEmpty()) {
        Node node = queue.remove();
        // null safe equals check
        if (StringUtils.equals(id, node.getIdentifier()))
            return node;
        // add children to stack
        NodeIterator iterator = node.getNodes();
        while (iterator.hasNext())
            queue.add(iterator.nextNode());

    }
    throw new ItemNotFoundException("No node found with identifier/uuid [" + id + "]");
}

From source file:com.tasktop.c2c.server.configuration.service.TemplateProcessingConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    File hudsonHomeDir = new File(targetBaseLocation,
            (perOrg ? configuration.getOrganizationIdentifier() : configuration.getProjectIdentifier()));

    if (hudsonHomeDir.exists()) {
        LOG.warn("Hudson home already apears to exist: " + hudsonHomeDir.getAbsolutePath());
    } else {//w ww. jav a2 s  .com
        // If we're here, the destination directory doesn't exist. Create it now.
        LOG.info("Creating new Hudson home: " + hudsonHomeDir.getAbsolutePath());
        hudsonHomeDir.mkdirs();
    }

    Queue<File> fileQueue = new LinkedList<File>();
    Map<String, String> props = new HashMap<String, String>(configuration.getProperties());

    fileQueue.add(new File(templateBaseLocation));
    while (!fileQueue.isEmpty()) {
        File currentFile = fileQueue.poll();
        if (currentFile.isDirectory()) {
            fileQueue.addAll(Arrays.asList(currentFile.listFiles()));
            createOrEnsureTargetDirectory(currentFile, configuration);
        } else {
            try {
                applyTemplateFileToTarget(props, currentFile, configuration);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.opendatakit.aggregate.format.structure.KmlGeoTraceNGeoShapeGenerator.java

@Override
String generatePlacemarkSubmission(Submission sub, List<FormElementModel> propertyNames, CallingContext cc)
        throws ODKDatastoreException {

    StringBuilder placemarks = new StringBuilder();

    // check if gps coordinate is in top element, else it's in a repeat
    if (geoParentRootSubmissionElement()) {
        placemarks.append(generatePlacemark(sub));
    } else {/*w w w  . j  a  v a2s . c  o  m*/
        Queue<SubmissionSet> submissionSetLevelsToExamine = new LinkedList<SubmissionSet>();
        submissionSetLevelsToExamine.add(sub);
        while (!submissionSetLevelsToExamine.isEmpty()) {
            SubmissionSet submissionSet = submissionSetLevelsToExamine.remove();
            recursiveElementSearchToFindRepeats(submissionSet, submissionSetLevelsToExamine, placemarks);
        }
    }

    return placemarks.toString();
}

From source file:org.rhq.plugins.modcluster.test.ModClusterPluginIntegrationTest.java

private Set<Resource> findResource(Resource parent) {
    Set<Resource> foundResources = new HashSet<Resource>();

    Queue<Resource> discoveryQueue = new LinkedList<Resource>();
    discoveryQueue.add(parent);//from  w  w w. ja v  a 2 s.  com

    while (!discoveryQueue.isEmpty()) {
        Resource currentResource = discoveryQueue.poll();

        log.info("Discovered resource of type: " + currentResource.getResourceType().getName());
        if (currentResource.getResourceType().getPlugin().equals(PLUGIN_NAME)) {
            foundResources.add(currentResource);
        }

        if (currentResource.getChildResources() != null) {
            for (Resource child : currentResource.getChildResources()) {
                discoveryQueue.add(child);
            }
        }
    }

    return foundResources;
}

From source file:edu.toronto.cs.phenotips.solr.HPOScriptService.java

/**
 * Get the HPO IDs of the specified phenotype and all its ancestors.
 * /*  w w w.  j  ava 2  s .c o  m*/
 * @param id the HPO identifier to search for, in the {@code HP:1234567} format
 * @return the full set of ancestors-or-self IDs, or an empty set if the requested ID was not found in the index
 */
public Set<String> getAllAncestorsAndSelfIDs(final String id) {
    Set<String> results = new HashSet<String>();
    Queue<SolrDocument> nodes = new LinkedList<SolrDocument>();
    SolrDocument crt = this.get(id);
    if (crt == null) {
        return results;
    }
    nodes.add(crt);
    while (!nodes.isEmpty()) {
        crt = nodes.poll();
        results.add(String.valueOf(crt.get(ID_FIELD_NAME)));
        @SuppressWarnings("unchecked")
        List<String> parents = (List<String>) crt.get("is_a");
        if (parents == null) {
            continue;
        }
        for (String pid : parents) {
            nodes.add(this.get(StringUtils.substringBefore(pid, " ")));
        }
    }
    return results;
}

From source file:org.polymap.core.runtime.event.AnnotatedEventListener.java

/**
 * //from w w  w. ja  v a2 s .  co m
 */
public AnnotatedEventListener(Object handler, Integer mapKey, EventFilter... filters) {
    assert handler != null;
    assert filters != null;
    this.handlerRef = new WeakReference(handler);
    this.handlerClass = handler.getClass();
    this.mapKey = mapKey;

    // find annotated methods
    Queue<Class> types = new ArrayDeque(16);
    types.add(handler.getClass());
    while (!types.isEmpty()) {
        Class type = types.remove();
        if (type.getSuperclass() != null) {
            types.add(type.getSuperclass());
        }
        types.addAll(Arrays.asList(type.getInterfaces()));

        for (Method m : type.getDeclaredMethods()) {
            EventHandler annotation = m.getAnnotation(EventHandler.class);
            if (annotation != null) {
                m.setAccessible(true);

                // annotated method
                AnnotatedMethod am = annotation.delay() > 0 ? new DeferredAnnotatedMethod(m, annotation)
                        : new AnnotatedMethod(m, annotation);

                EventListener listener = am;

                // display thread;
                if (annotation.display()) {
                    // if this is NOT the delegate of the DeferringListener then
                    // check DeferringListener#SessionUICallbackCounter
                    listener = new DisplayingListener(listener);
                }

                // deferred
                // XXX There is a race cond. between the UIThread and the event thread; if the UIThread
                // completes the current request before all display events are handled then the UI
                // is not updated until next user request; DeferringListener handles this by activating
                // UICallBack, improving behaviour - but not really solving in all cases; after 500ms we
                // are quite sure that no more events are pending and UI callback can turned off

                // currenty COMMENTED OUT! see EventManger#SessionEventDispatcher
                if (annotation.delay() > 0 /*|| annotation.display()*/) {
                    int delay = annotation.delay() > 0 ? annotation.delay() : 500;
                    listener = new TimerDeferringListener(listener, delay, 10000);
                }
                // filters
                listener = new FilteringListener(listener,
                        ObjectArrays.concat(am.filters, filters, EventFilter.class));

                // session context; first in chain so that all listener/filters
                // get the proper context
                SessionContext session = SessionContext.current();
                if (session != null) {
                    listener = new SessioningListener(listener, mapKey, session, handlerClass);
                }
                methods.add(listener);
            }
        }
    }
    if (methods.isEmpty()) {
        throw new IllegalArgumentException("No EventHandler annotation found in: " + handler.getClass());
    }
}