List of usage examples for java.util Queue isEmpty
boolean isEmpty();
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.TestFSRMStateStore.java
private void verifyFilesUnreadablebyHDFS(MiniDFSCluster cluster, Path root) throws Exception { DistributedFileSystem fs = cluster.getFileSystem(); Queue<Path> paths = new LinkedList<>(); paths.add(root);/*from w ww . j a v a2s . c o m*/ while (!paths.isEmpty()) { Path p = paths.poll(); FileStatus stat = fs.getFileStatus(p); if (!stat.isDirectory()) { try { LOG.warn("\n\n ##Testing path [" + p + "]\n\n"); fs.open(p); Assert.fail("Super user should not be able to read [" + UserGroupInformation.getCurrentUser() + "] [" + p.getName() + "]"); } catch (AccessControlException e) { Assert.assertTrue( e.getMessage().contains("superuser is not allowed to perform this operation")); } catch (Exception e) { Assert.fail("Should get an AccessControlException here"); } } if (stat.isDirectory()) { FileStatus[] ls = fs.listStatus(p); for (FileStatus f : ls) { paths.add(f.getPath()); } } } }
From source file:hudson.plugins.plot.XMLSeries.java
/*** * This is a fallback strategy for nodesets that include non numeric content * enabling users to create lists by selecting them such that names and * values share a common parent. If a node has attributes and is empty that * node will be re-enqueued as a parent to its attributes. * //w ww . jav a 2s . c o m * @param buildNumber * the build number * * @returns a list of PlotPoints where the label is the last non numeric * text content and the value is the last numeric text content for * each set of nodes under a given parent. ***/ private List<PlotPoint> coalesceTextnodesAsLabelsStrategy(NodeList nodeList, int buildNumber) { Map<Node, List<Node>> parentNodeMap = new HashMap<Node, List<Node>>(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (!parentNodeMap.containsKey(node.getParentNode())) { parentNodeMap.put(node.getParentNode(), new ArrayList<Node>()); } parentNodeMap.get(node.getParentNode()).add(node); } List<PlotPoint> retval = new ArrayList<PlotPoint>(); Queue<Node> parents = new ArrayDeque<Node>(parentNodeMap.keySet()); while (!parents.isEmpty()) { Node parent = parents.poll(); Double value = null; String label = null; for (Node child : parentNodeMap.get(parent)) { if (null == child.getTextContent() || child.getTextContent().trim().isEmpty()) { NamedNodeMap attrmap = child.getAttributes(); List<Node> attrs = new ArrayList<Node>(); for (int i = 0; i < attrmap.getLength(); i++) { attrs.add(attrmap.item(i)); } parentNodeMap.put(child, attrs); parents.add(child); } else if (new Scanner(child.getTextContent().trim()).hasNextDouble()) { value = new Scanner(child.getTextContent().trim()).nextDouble(); } else { label = child.getTextContent().trim(); } } if ((label != null) && (value != null)) { addValueToList(retval, new String(label), String.valueOf(value), buildNumber); } } return retval; }
From source file:org.callimachusproject.client.HttpAuthenticator.java
private void generateAuthResponse(final HttpRequest request, final AuthState authState, final HttpContext context) throws HttpException, IOException { AuthScheme authScheme = authState.getAuthScheme(); Credentials creds = authState.getCredentials(); switch (authState.getState()) { case FAILURE: return;/*from ww w .ja v a 2 s . co m*/ case SUCCESS: ensureAuthScheme(authScheme); if (authScheme.isConnectionBased()) { return; } break; case CHALLENGED: final Queue<AuthOption> authOptions = authState.getAuthOptions(); if (authOptions != null) { while (!authOptions.isEmpty()) { final AuthOption authOption = authOptions.remove(); authScheme = authOption.getAuthScheme(); creds = authOption.getCredentials(); authState.update(authScheme, creds); if (this.log.isDebugEnabled()) { this.log.debug("Generating response to an authentication challenge using " + authScheme.getSchemeName() + " scheme"); } try { final Header header = doAuth(authScheme, creds, request, context); request.addHeader(header); break; } catch (final AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn(authScheme + " authentication error: " + ex.getMessage()); } } } return; } else { ensureAuthScheme(authScheme); } } if (authScheme != null) { try { final Header header = doAuth(authScheme, creds, request, context); request.addHeader(header); } catch (final AuthenticationException ex) { if (this.log.isErrorEnabled()) { this.log.error(authScheme + " authentication error: " + ex.getMessage()); } } } }
From source file:de.thomaskrille.dropwizard.environment_configuration.EnvironmentConfigurationFactory.java
private void replaceEnvironmentVariables(final JsonNode root) { Queue<JsonNode> q = Queues.newArrayDeque(); q.add(root);/*from w w w .j av a 2 s .c o m*/ while (!q.isEmpty()) { JsonNode currentNode = q.poll(); if (!currentNode.isContainerNode()) { continue; } if (currentNode.isObject()) { replaceEnvironmentVariablesForObject(q, (ObjectNode) currentNode); } else if (currentNode.isArray()) { replaceEnvironmentVariablesForArray(q, (ArrayNode) currentNode); } } }
From source file:org.aksw.simba.cetus.tools.ClassModelCreator.java
public static boolean inferSubClassRelations(Model classModel) { Set<Resource> subClasses = new HashSet<Resource>(); ResIterator resIterator = classModel.listSubjectsWithProperty(RDFS.subClassOf); while (resIterator.hasNext()) { subClasses.add(resIterator.next()); }//from w w w . j a va2s. c o m LOGGER.info("Found " + subClasses.size() + " sub classes."); Queue<Resource> queue = new LinkedList<Resource>(); int count = 0, count2 = 0; Resource resource, next; NodeIterator nodeIterator; Set<Resource> equalClasses = new HashSet<Resource>(); Set<Resource> alreadySeen = new HashSet<Resource>(); for (Resource subClass : subClasses) { equalClasses.clear(); equalClasses.add(subClass); nodeIterator = classModel.listObjectsOfProperty(subClass, OWL.equivalentClass); while (nodeIterator.hasNext()) { equalClasses.add(nodeIterator.next().asResource()); } resIterator = classModel.listSubjectsWithProperty(OWL.equivalentClass, subClass); while (resIterator.hasNext()) { equalClasses.add(resIterator.next()); } for (Resource equalClass : equalClasses) { nodeIterator = classModel.listObjectsOfProperty(equalClass, RDFS.subClassOf); while (nodeIterator.hasNext()) { queue.add(nodeIterator.next().asResource()); } } alreadySeen.clear(); while (!queue.isEmpty()) { resource = queue.poll(); // mark this resource as super class of the sub class classModel.add(subClass, RDFS.subClassOf, resource); ++count2; if (!classModel.contains(resource, RDF.type, RDFS.Class)) { classModel.add(resource, RDF.type, RDFS.Class); } nodeIterator = classModel.listObjectsOfProperty(resource, RDFS.subClassOf); while (nodeIterator.hasNext()) { next = nodeIterator.next().asResource(); if (!alreadySeen.contains(next)) { queue.add(next); alreadySeen.add(next); } } } ++count; if ((count % 100000) == 0) { LOGGER.info("processed " + count + " sub classes."); } } LOGGER.info("Added " + count2 + " properties."); return true; }
From source file:org.callimachusproject.client.HttpAuthenticator.java
private boolean handleAuthChallenge(final HttpHost host, final HttpResponse response, final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) { try {// ww w . java 2s . com if (this.log.isDebugEnabled()) { this.log.debug(host.toHostString() + " requested authentication"); } final Map<String, Header> challenges = authStrategy.getChallenges(host, response, context); if (challenges.isEmpty()) { this.log.debug("Response contains no authentication challenges"); return false; } final 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) { final String id = authScheme.getSchemeName(); final 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 } } } final 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 (final MalformedChallengeException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Malformed challenge: " + ex.getMessage()); } authState.reset(); return false; } }
From source file:com.datatorrent.stram.appdata.AppDataPushAgent.java
private JSONObject getPushData() { // assemble the json that contains the app stats and logical operator stats and counters JSONObject json = new JSONObject(); try {/*w w w . ja v a 2 s . c om*/ json.put("type", DATA); json.put("appId", dnmgr.getLogicalPlan().getValue(DAGContext.APPLICATION_ID)); json.put("appName", dnmgr.getLogicalPlan().getValue(DAGContext.APPLICATION_NAME)); json.put("appUser", appContext.getUser()); List<LogicalOperatorInfo> logicalOperatorInfoList = dnmgr.getLogicalOperatorInfoList(); JSONObject logicalOperators = new JSONObject(); for (LogicalOperatorInfo logicalOperator : logicalOperatorInfoList) { JSONObject logicalOperatorJson = extractFields(logicalOperator); JSONArray metricsList = new JSONArray(); Queue<Pair<Long, Map<String, Object>>> windowMetrics = dnmgr.getWindowMetrics(logicalOperator.name); if (windowMetrics != null) { while (!windowMetrics.isEmpty()) { Pair<Long, Map<String, Object>> metrics = windowMetrics.remove(); long windowId = metrics.first; // metric name, aggregated value Map<String, Object> aggregates = metrics.second; long now = System.currentTimeMillis(); if (!operatorsSchemaLastSentTime.containsKey(logicalOperator.name) || (metricsTransport.getSchemaResendInterval() > 0 && operatorsSchemaLastSentTime.get(logicalOperator.name) < now - metricsTransport.getSchemaResendInterval())) { try { pushMetricsSchema(dnmgr.getLogicalPlan().getOperatorMeta(logicalOperator.name), aggregates); operatorsSchemaLastSentTime.put(logicalOperator.name, now); } catch (IOException ex) { LOG.error("Cannot push metrics schema", ex); } } JSONObject metricsItem = new JSONObject(); metricsItem.put("_windowId", windowId); long windowToMillis = dnmgr.windowIdToMillis(windowId); LOG.debug("metric window {} time {}", windowId, windowToMillis); metricsItem.put("_time", windowToMillis); for (Map.Entry<String, Object> entry : aggregates.entrySet()) { String metricName = entry.getKey(); Object aggregateValue = entry.getValue(); metricsItem.put(metricName, aggregateValue); } metricsList.put(metricsItem); } } logicalOperatorJson.put("metrics", metricsList); logicalOperators.put(logicalOperator.name, logicalOperatorJson); } json.put("time", System.currentTimeMillis()); json.put("logicalOperators", logicalOperators); json.put("stats", extractFields(appContext.getStats())); } catch (JSONException ex) { throw new RuntimeException(ex); } return json; }
From source file:com.shollmann.igcparser.ui.activity.IGCFilesActivity.java
private List<IGCFile> getListIGCFiles(File parentDir) { List<IGCFile> inFiles = new ArrayList<>(); Queue<File> files = new LinkedList<>(); try {/*w w w . ja v a 2 s. c o m*/ files.addAll(Arrays.asList(parentDir.listFiles())); while (!files.isEmpty()) { File file = files.remove(); if (!Utilities.isUnlikelyIGCFolder(file)) { if (file != null && file.isDirectory()) { files.addAll(Arrays.asList(file.listFiles())); } else if (file != null && (file.getName().toLowerCase().endsWith(".igc"))) { inFiles.add(Parser.quickParse(Uri.parse(file.getAbsolutePath()))); } } } Collections.sort(inFiles, Comparators.compareByDate); } catch (Throwable t) { final String message = "Couldn't open files"; Crashlytics.log(message); Crashlytics.logException(t); Logger.logError(message); } return inFiles; }
From source file:org.apache.stratos.usage.agent.persist.UsageDataPersistenceTask.java
/** * this method create a Summarizer object for each tenant and call accumulate() method to * accumulate usage statistics//from w w w. j av a 2s .c om * * @param jobQueue usage data persistence jobs * @throws org.apache.stratos.usage.agent.exception.UsageException * */ public void persistUsage(Queue<BandwidthUsage> jobQueue) throws UsageException { // create a map to hold summarizer objects against tenant id HashMap<Integer, Summarizer> summarizerMap = new HashMap<Integer, Summarizer>(); // if the jobQueue is not empty for (int i = 0; i < configuration.getUsageTasksNumberOfRecordsPerExecution() && !jobQueue.isEmpty(); i++) { // get the first element from the queue, which is a BandwidthUsage object BandwidthUsage usage = jobQueue.poll(); // get the tenant id int tenantId = usage.getTenantId(); //get the Summarizer object corresponds to the tenant id Summarizer summarizer = summarizerMap.get(tenantId); // when tenant invoke service for the first time, no corresponding summarizer object in // the map if (summarizer == null) { //create a Summarizer object and put to the summarizerMap summarizer = new Summarizer(); summarizerMap.put(tenantId, summarizer); } // now accumulate usage summarizer.accumulate(usage); } //Finished accumulating. Now publish the events // get the collection view of values in summarizerMap Collection<Summarizer> summarizers = summarizerMap.values(); // for each summarizer object call the publish method for (Summarizer summarizer : summarizers) { summarizer.publish(); } }
From source file:org.primeframework.mvc.util.ClassClasspathResolver.java
private Collection<Class<U>> loadFromDirectory(File dir, Test<Class<U>> test, boolean recursive) throws IOException { Set<Class<U>> matches = new HashSet<Class<U>>(); // Loop over the files Queue<File> files = new LinkedList<File>(safeListFiles(dir, null)); while (!files.isEmpty()) { File file = files.poll(); if (file.isDirectory() && recursive) { files.addAll(safeListFiles(file, null)); } else if (file.isFile()) { // This file matches, test it Testable<Class<U>> testable = test.prepare(file); if (testable != null && testable.passes()) { matches.add(testable.result()); }/*from w w w . j a v a 2 s . c o m*/ } } return matches; }