List of usage examples for java.util Queue add
boolean add(E e);
From source file:org.shaman.terrain.polygonal.PolygonalMapGenerator.java
private void createBiomes() { if (graph == null) { return;//w ww . ja v a2 s . co m } //assign temperatures for (Graph.Corner c : graph.corners) { c.temperature = c.elevation; c.temperature *= c.temperature; c.temperature = 1 - c.temperature; } assignCenterTemperature(); //create random rivers Random rand = new Random(seed * 3); for (Graph.Corner c : graph.corners) { c.river = 0; } float riverProb = 0.2f; float riverStartHeight = 0.7f; int riverCounter = 0; corner: for (Graph.Corner c : graph.corners) { if (c.water || c.elevation < riverStartHeight) { continue; } if (rand.nextFloat() > riverProb) { continue; } if (c.river > 0) continue; for (Graph.Corner c2 : c.adjacent) { if (c2.river > 0) { continue corner; } for (Graph.Corner c3 : c2.adjacent) { if (c3.river > 0) { continue corner; } } } //start new river from here Graph.Corner current = c; current.river = Math.max(current.river, 1); while (!current.ocean && !current.coast) { float minH = current.elevation; Graph.Corner minC = null; for (Graph.Corner c2 : current.adjacent) { if (c2.river > 0 && c2.elevation < current.elevation) { minC = c2; //force closing of rivers break; } if (c2.elevation < minH) { minC = c2; minH = c2.elevation; } } if (minC == null) { LOG.warning("river stuck in a local minima without reaching the ocean"); break; } minC.river = Math.max(minC.river, current.river + 1); current = minC; } riverCounter++; } LOG.info("count of created rivers: " + riverCounter); showRivers = true; //assign moisture Queue<Graph.Corner> queue = new ArrayDeque<>(); for (Graph.Corner q : graph.corners) { if ((q.water || q.river > 0) && !q.ocean) { q.moisture = q.river > 0 ? Math.min(3.0f, (0.4f * q.river)) : 1; queue.add(q); } else { q.moisture = 0; } } while (!queue.isEmpty()) { Graph.Corner q = queue.poll(); for (Graph.Corner r : q.adjacent) { float newMoisture = q.moisture * 0.8f; if (newMoisture > r.moisture) { r.moisture = newMoisture; queue.add(r); } } } for (Graph.Corner q : graph.corners) { if (q.ocean || q.coast) { q.moisture = 1; } } //redistribute moisture ArrayList<Graph.Corner> corners = new ArrayList<>(); for (Graph.Corner q : graph.corners) { if (!q.ocean && !q.coast) { corners.add(q); } } Collections.sort(corners, new Comparator<Graph.Corner>() { @Override public int compare(Graph.Corner o1, Graph.Corner o2) { return Float.compare(o1.moisture, o2.moisture); } }); for (int i = 0; i < corners.size(); i++) { corners.get(i).moisture = i / (float) (corners.size() - 1); } assignCenterMoisture(); assignBiomes(); //update mesh updateTemperatureGeometry(); updateMoistureGeometry(); updateBiomesGeometry(); }
From source file:tachyon.master.file.FileSystemMaster.java
/** * Gets absolute paths of all in memory files. Called by the web ui. * * @return absolute paths of all in memory files *//*from w w w . j a v a2 s .c o m*/ public List<TachyonURI> getInMemoryFiles() { List<TachyonURI> ret = new ArrayList<TachyonURI>(); Queue<Pair<InodeDirectory, TachyonURI>> nodesQueue = new LinkedList<Pair<InodeDirectory, TachyonURI>>(); synchronized (mInodeTree) { // TODO(yupeng): Verify we want to use absolute path. nodesQueue.add(new Pair<InodeDirectory, TachyonURI>(mInodeTree.getRoot(), new TachyonURI(TachyonURI.SEPARATOR))); while (!nodesQueue.isEmpty()) { Pair<InodeDirectory, TachyonURI> pair = nodesQueue.poll(); InodeDirectory directory = pair.getFirst(); TachyonURI curUri = pair.getSecond(); Set<Inode> children = directory.getChildren(); for (Inode inode : children) { TachyonURI newUri = curUri.join(inode.getName()); if (inode.isDirectory()) { nodesQueue.add(new Pair<InodeDirectory, TachyonURI>((InodeDirectory) inode, newUri)); } else if (isFullyInMemory((InodeFile) inode)) { ret.add(newUri); } } } } return ret; }
From source file:uk.ac.bbsrc.tgac.miso.spring.ajax.PoolControllerHelperService.java
public JSONObject printPoolBarcodes(HttpSession session, JSONObject json) { try {//w w w. j a v a 2 s. co m User user = securityManager .getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); JSONArray ss = JSONArray.fromObject(json.getString("pools")); String serviceName = null; if (json.has("serviceName")) { serviceName = json.getString("serviceName"); } MisoPrintService<File, Barcodable, PrintContext<File>> mps = null; if (serviceName == null) { Collection<MisoPrintService> services = printManager .listPrintServicesByBarcodeableClass(Pool.class); if (services.size() == 1) { mps = services.iterator().next(); } else { return JSONUtils.SimpleJSONError( "No serviceName specified, but more than one available service able to print this barcode type."); } } else { mps = printManager.getPrintService(serviceName); } Queue<File> thingsToPrint = new LinkedList<File>(); for (JSONObject p : (Iterable<JSONObject>) ss) { try { Long poolId = p.getLong("poolId"); Pool pool = requestManager.getPoolById(poolId); File f = mps.getLabelFor(pool); if (f != null) thingsToPrint.add(f); } catch (IOException e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Error printing pool barcode: " + e.getMessage()); } } PrintJob pj = printManager.print(thingsToPrint, mps.getName(), user); return JSONUtils.SimpleJSONResponse("Job " + pj.getJobId() + " : Barcodes printed."); } catch (MisoPrintException e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("No printer of that name available: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Cannot print barcodes: " + e.getMessage()); } }
From source file:org.shaman.terrain.polygonal.PolygonalMapGenerator.java
private void findOceans() { for (Graph.Center c : graph.centers) { c.ocean = false;/*from w w w .j ava 2 s . c o m*/ c.water = false; } for (Graph.Corner c : graph.corners) { c.ocean = false; } //set water parameter of centers float LAKE_THRESHOLD = 0.3f; Queue<Graph.Center> queue = new ArrayDeque<>(); for (Graph.Center p : graph.centers) { int numWater = 0; for (Graph.Corner c : p.corners) { if (c.border || c.ocean) { p.border = true; p.water = true; p.ocean = true; queue.add(p); break; } if (c.water) { numWater++; } } p.water = (p.ocean || numWater >= p.corners.size() * LAKE_THRESHOLD); } LOG.info("border cells: " + queue.size()); //float fill borders to distinguish between ocean and likes while (!queue.isEmpty()) { Graph.Center c = queue.poll(); for (Graph.Center r : c.neighbors) { if (r.water && !r.ocean) { r.ocean = true; queue.add(r); } } } //assign coast tag for (Graph.Corner q : graph.corners) { q.coast = false; } for (Graph.Center c : graph.centers) { if (c.ocean) { for (Graph.Corner q : c.corners) { if (!q.water) { q.coast = true; } else { q.ocean = true; } } } } //assign basic biomes int oceanCount = 0; int lakeCount = 0; int landCount = 0; for (Graph.Center c : graph.centers) { if (c.ocean) { c.biome = Biome.OCEAN; oceanCount++; } else if (c.water) { c.biome = Biome.LAKE; lakeCount++; } else { c.biome = Biome.BEACH; lakeCount++; } } LOG.log(Level.INFO, "ocean cells: {0}, lake cells: {1}, land cells: {2}", new Object[] { oceanCount, lakeCount, landCount }); }
From source file:org.kuali.rice.krad.uif.lifecycle.ViewLifecyclePhaseBase.java
/** * Initializes only the lifecycle successors referenced by paths within {@link #getRefreshPaths()}. * * @param successors the successor queue *///from www . j a v a 2 s .c o m protected void initializeRefreshPathSuccessors(Queue<ViewLifecyclePhase> successors) { LifecycleElement element = getElement(); String nestedPathPrefix; Component nestedParent; if (element instanceof Component) { nestedParent = (Component) element; nestedPathPrefix = ""; } else { nestedParent = getParent(); nestedPathPrefix = getParentPath() + "."; } List<String> nestedProperties = getNestedPropertiesForRefreshPath(); for (String nestedProperty : nestedProperties) { String nestedPath = nestedPathPrefix + nestedProperty; LifecycleElement nestedElement = ObjectPropertyUtils.getPropertyValue(element, nestedProperty); if (nestedElement != null) { ViewLifecyclePhase nestedPhase = initializeSuccessor(nestedElement, nestedPath, nestedParent); successors.add(nestedPhase); } } }
From source file:org.rhq.enterprise.server.cloud.StorageNodeManagerBean.java
private Map<Integer, Integer> findResourcesWithAlertsToStorageNodeMap(StorageNode storageNode) { Stopwatch stopwatch = stopwatchStart(); List<StorageNode> initialStorageNodes = getStorageNodes(); try {//from ww w .ja v a 2s .c o m if (storageNode == null) { initialStorageNodes = getStorageNodes(); } else { initialStorageNodes = Arrays.asList(storageNode.getResource() == null ? entityManager.find(StorageNode.class, storageNode.getId()) : storageNode); } Map<Integer, Integer> resourceIdsToStorageNodeMap = new HashMap<Integer, Integer>(); Queue<Resource> unvisitedResources = new LinkedList<Resource>(); // we are assuming here that the set of resources is disjunktive across different storage nodes for (StorageNode initialStorageNode : initialStorageNodes) { if (initialStorageNode.getResource() != null) { unvisitedResources.add(initialStorageNode.getResource()); while (!unvisitedResources.isEmpty()) { Resource resource = unvisitedResources.poll(); if (!resource.getAlertDefinitions().isEmpty()) { resourceIdsToStorageNodeMap.put(resource.getId(), initialStorageNode.getId()); } Set<Resource> childResources = resource.getChildResources(); if (childResources != null) { for (Resource child : childResources) { unvisitedResources.add(child); } } } } } return resourceIdsToStorageNodeMap; } finally { if (log.isDebugEnabled()) { stopwatchEnd(stopwatch, "Found storage node resources with alert defs in "); } } }
From source file:ome.services.graphs.GraphPathBean.java
/** * Process the Hibernate domain object model to initialize this class' instance fields. * No other method should write to them. * @param sessionFactory the Hibernate session factory *///from w w w . j a va 2s. c o m private void initialize(SessionFactoryImplementor sessionFactory) { /* note all the direct superclasses */ final Map<String, String> superclasses = new HashMap<String, String>(); final Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata(); for (final String className : classesMetadata.keySet()) { try { final Class<?> actualClass = Class.forName(className); if (IObject.class.isAssignableFrom(actualClass)) { classesBySimpleName.put(actualClass.getSimpleName(), actualClass.asSubclass(IObject.class)); final Set<String> subclassNames = sessionFactory.getEntityPersister(className) .getEntityMetamodel().getSubclassEntityNames(); for (final String subclassName : subclassNames) { if (!subclassName.equals(className)) { final Class<?> actualSubclass = Class.forName(subclassName); if (actualSubclass.getSuperclass() == actualClass) { superclasses.put(subclassName, className); } } } } else { log.warn("mapped class " + className + " is not a " + IObject.class.getName()); } } catch (ClassNotFoundException e) { log.error("could not instantiate class", e); } } /* note the indirect superclasses and subclasses */ for (final Entry<String, String> superclassRelationship : superclasses.entrySet()) { final String startClass = superclassRelationship.getKey(); String superclass = superclassRelationship.getValue(); while (superclass != null) { allSuperclasses.put(startClass, superclass); allSubclasses.put(superclass, startClass); superclass = superclasses.get(superclass); } } /* queue for processing all the properties of all the mapped entities: name, type, nullability */ final Queue<PropertyDetails> propertyQueue = new LinkedList<PropertyDetails>(); final Map<String, Set<String>> allPropertyNames = new HashMap<String, Set<String>>(); for (final Entry<String, ClassMetadata> classMetadata : classesMetadata.entrySet()) { final String className = classMetadata.getKey(); final ClassMetadata metadata = classMetadata.getValue(); /* note name of identifier property */ classIdProperties.put(metadata.getEntityName(), metadata.getIdentifierPropertyName()); /* queue other properties */ final String[] propertyNames = metadata.getPropertyNames(); final Type[] propertyTypes = metadata.getPropertyTypes(); final boolean[] propertyNullabilities = metadata.getPropertyNullability(); for (int i = 0; i < propertyNames.length; i++) { final List<String> propertyPath = Collections.singletonList(propertyNames[i]); propertyQueue.add( new PropertyDetails(className, propertyPath, propertyTypes[i], propertyNullabilities[i])); } final Set<String> propertyNamesSet = new HashSet<String>(propertyNames.length); propertyNamesSet.addAll(Arrays.asList(propertyNames)); allPropertyNames.put(className, propertyNamesSet); } /* process each property to note entity linkages */ while (!propertyQueue.isEmpty()) { final PropertyDetails property = propertyQueue.remove(); if (ignoreProperty(property.path.get(property.path.size() - 1))) { continue; } /* if the property has a component type, queue the parts for processing */ if (property.type instanceof ComponentType) { final ComponentType componentType = (ComponentType) property.type; final String[] componentPropertyNames = componentType.getPropertyNames(); final Type[] componentPropertyTypes = componentType.getSubtypes(); final boolean[] componentPropertyNullabilities = componentType.getPropertyNullability(); for (int i = 0; i < componentPropertyNames.length; i++) { final List<String> componentPropertyPath = new ArrayList<String>(property.path.size() + 1); componentPropertyPath.addAll(property.path); componentPropertyPath.add(componentPropertyNames[i]); propertyQueue.add(new PropertyDetails(property.holder, componentPropertyPath, componentPropertyTypes[i], componentPropertyNullabilities[i])); } } else { /* determine if another mapped entity class is linked by this property */ final boolean isAssociatedEntity; if (property.type instanceof CollectionType) { final CollectionType ct = (CollectionType) property.type; isAssociatedEntity = sessionFactory.getCollectionPersister(ct.getRole()).getElementType() .isEntityType(); } else { isAssociatedEntity = property.type instanceof AssociationType; } /* the property can link to entities, so process it further */ String propertyPath = Joiner.on('.').join(property.path); /* find if the property is accessible (e.g., not protected) */ boolean propertyIsAccessible = false; String classToInstantiateName = property.holder; Class<?> classToInstantiate = null; try { classToInstantiate = Class.forName(classToInstantiateName); while (Modifier.isAbstract(classToInstantiate.getModifiers())) { classToInstantiateName = allSubclasses.get(classToInstantiateName).iterator().next(); classToInstantiate = Class.forName(classToInstantiateName); } try { PropertyUtils.getNestedProperty(classToInstantiate.newInstance(), propertyPath); propertyIsAccessible = true; } catch (NoSuchMethodException e) { /* expected for collection properties */ } catch (NestedNullException e) { log.warn("guessing " + propertyPath + " of " + property.holder + " to be accessible"); propertyIsAccessible = true; } } catch (ReflectiveOperationException e) { log.error("could not probe property " + propertyPath + " of " + property.holder, e); continue; } /* build property report line for log */ final char arrowShaft = property.isNullable ? '-' : '='; final StringBuffer sb = new StringBuffer(); sb.append(property.holder); sb.append(' '); for (final String propertyName : property.path) { sb.append(arrowShaft); sb.append(arrowShaft); sb.append(propertyName); } sb.append(arrowShaft); sb.append(arrowShaft); sb.append("> "); final String valueClassName; if (isAssociatedEntity) { valueClassName = ((AssociationType) property.type).getAssociatedEntityName(sessionFactory); sb.append(valueClassName); } else { valueClassName = null; sb.append("value"); } if (property.type.isCollectionType()) { sb.append("[]"); } if (!propertyIsAccessible) { sb.append(" (inaccessible)"); } /* determine from which class the property is inherited, if at all */ String superclassWithProperty = null; String currentClass = property.holder; while (true) { currentClass = superclasses.get(currentClass); if (currentClass == null) { break; } else if (allPropertyNames.get(currentClass).contains(property.path.get(0))) { superclassWithProperty = currentClass; } } /* check if the property actually comes from an interface */ final String declaringClassName = superclassWithProperty == null ? property.holder : superclassWithProperty; final Class<? extends IObject> interfaceForProperty = getInterfaceForProperty(declaringClassName, property.path.get(0)); /* report where the property is declared */ if (superclassWithProperty != null) { sb.append(" from "); sb.append(superclassWithProperty); } else { if (interfaceForProperty != null) { sb.append(" see "); sb.append(interfaceForProperty.getName()); /* It would be nice to set PropertyDetails to have the interface as the holder, * but then properties would not be unique by declarer class and instance ID. */ } /* entity linkages by non-inherited properties are recorded */ if (valueClassName == null && property.path.size() > 1) { /* assume that the top-level property suffices for describing simple properties */ log.debug("recording " + propertyPath + " as " + property.path.get(0)); propertyPath = property.path.get(0); } final Entry<String, String> classPropertyName = Maps.immutableEntry(property.holder, propertyPath); if (valueClassName == null) { simpleProperties.put(property.holder, propertyPath); } else { linkedTo.put(property.holder, Maps.immutableEntry(valueClassName, propertyPath)); linkedBy.put(valueClassName, classPropertyName); } final PropertyKind propertyKind; if (property.type.isCollectionType()) { propertyKind = PropertyKind.COLLECTION; } else if (property.isNullable) { propertyKind = PropertyKind.OPTIONAL; } else { propertyKind = PropertyKind.REQUIRED; } propertyKinds.put(classPropertyName, propertyKind); if (propertyIsAccessible) { accessibleProperties.add(classPropertyName); } } if (log.isDebugEnabled()) { log.debug(sb.toString()); } } } log.info("initialized graph path bean with " + propertyKinds.size() + " properties"); }
From source file:OpenDaylightUtil.SwitchIdList.java
public Queue<String> getSwitchIdList() { Queue<String> switchIDlist = new LinkedList<String>(); URI controllerURI = UriBuilder.fromUri("http://" + controllerIp + ":8181/restconf").build(); String topoEntity;//ww w.j ava2s . c om try { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); client.addFilter(new HTTPBasicAuthFilter(adminAccount, adminPass)); ClientResponse TopoResponse = client.resource(controllerURI) .path("operational/network-topology:network-topology") .type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); int status = TopoResponse.getStatus(); if (status == 200) { topoEntity = TopoResponse.getEntity(String.class); JSONParser topoParser = new JSONParser(); JSONObject topoObject = (JSONObject) topoParser.parse(topoEntity); JSONArray topoList = (JSONArray) ((JSONObject) topoObject.get("network-topology")).get("topology"); for (Object topoList1 : topoList) { JSONArray allnodeList = (JSONArray) ((JSONObject) topoList1).get("node"); for (Object allnodeList1 : allnodeList) { String allNodeId = (String) ((JSONObject) allnodeList1).get("node-id"); // Just for String[] switchAndHost = allNodeId.split(":"); if (switchAndHost[0].equals("openflow")) { switchIDlist.add(allNodeId); } } } } } catch (Exception e) { System.out.println(e.getMessage()); } return switchIDlist; }
From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java
private void initializeRetryRunnable() { pushRetryRunnable = new Runnable() { public void run() { while (true) { AndroidUtilities.sleepDeep(TIME_BETWEEN_TRIES); if (failedPushes.isEmpty()) { synchronized (ActFmSyncService.this) { pushRetryThread = null; return; }/*from ww w. j av a2s. c o m*/ } if (failedPushes.size() > 0) { // Copy into a second queue so we don't end up infinitely retrying in the same loop Queue<FailedPush> toTry = new LinkedList<FailedPush>(); while (failedPushes.size() > 0) { toTry.add(failedPushes.remove(0)); } while (!toTry.isEmpty() && !actFmPreferenceService.isOngoing()) { FailedPush pushOp = toTry.remove(); switch (pushOp.pushType) { case PUSH_TYPE_TASK: pushTask(pushOp.itemId); break; case PUSH_TYPE_TAG: pushTag(pushOp.itemId); break; case PUSH_TYPE_UPDATE: pushUpdate(pushOp.itemId); break; } } } } } }; }
From source file:com.dbay.apns4j.impl.ApnsConnectionImpl.java
private void startErrorWorker() { Thread thread = new Thread(new Runnable() { @Override/*ww w . j ava 2s . co m*/ public void run() { Socket curSocket = socket; try { if (!isSocketAlive(curSocket)) { return; } InputStream socketIs = curSocket.getInputStream(); byte[] res = new byte[ERROR_RESPONSE_BYTES_LENGTH]; int size = 0; while (true) { try { size = socketIs.read(res); if (size > 0 || size == -1) { // break, when something was read or there is no // data any more break; } } catch (SocketTimeoutException e) { // There is no data. Keep reading. Thread.sleep(10); } } int command = res[0]; /** * EN: error-response,close the socket and resent * notifications CN: ??????? */ if (size == res.length && command == Command.ERROR) { int status = res[1]; int errorId = ApnsTools.parse4ByteInt(res[2], res[3], res[4], res[5]); String token = ErrorResponse.desc(status); // callback error token? if (null != errorProcessHandler) { errorProcessHandler.process(errorId, status, token); } if (logger.isInfoEnabled()) { logger.info(String.format( "%s, %s Received error response. status: %s, id: %s, error-desc: %s", serviceName, connName, status, errorId, token)); } Queue<PushNotification> resentQueue = new LinkedList<PushNotification>(); synchronized (lock) { boolean found = false; errorHappendedLastConn = true; while (!notificationCachedQueue.isEmpty()) { PushNotification pn = notificationCachedQueue.poll(); if (pn.getId() == errorId) { found = true; } else { /** * https://developer.apple.com/library/ios/ * documentation * /NetworkingInternet/Conceptual * /RemoteNotificationsPG * /Chapters/CommunicatingWIthAPS.html As * the document said, add the notifications * which need be resent to the queue. Igonre * the error one */ if (found) { resentQueue.add(pn); } } } if (!found) { logger.warn(connName + " Didn't find error-notification in the queue. Maybe it's time to adjust cache length. id: " + errorId); } } // resend notifications if (!resentQueue.isEmpty()) { ApnsResender.getInstance().resend(name, resentQueue); } } else { // ignore and continue reading logger.error( connName + " Unexpected command or size. commend: " + command + " , size: " + size); } } catch (Exception e) { // logger.error(connName + " " + e.getMessage(), e); logger.error(connName + " " + e.getMessage()); } finally { /** * EN: close the old socket although it may be closed once * before. CN: ??? */ closeSocket(curSocket); } } }); thread.start(); }