/** Adds a random obstacle to the ArrayList of obstacles. */ public void addRandomObstacle() { if (new Random().nextBoolean()) { obstacles.add(new BadObstacle(paintGreen)); } else { obstacles.add(new GoodObstacle(paintBlue)); } }
public ParseMessage(String msg) { FMValue = msg.substring(3, 5); // first one is starting index,last one is end+1 ToValue = msg.substring(9, 11); // NPVal = Character.getNumericValue(msg.charAt(15)); HCVal = Character.getNumericValue(msg.charAt(20)); msgNumber = Integer.parseInt(msg.substring(25, 28)); int i = msg.indexOf("DATA"); int j = msg.indexOf("VL"); if (i != (j + 4)) { VLNode = msg.substring(j + 3, i); } else VLNode = ""; DATA_Val = msg.substring(i + 5); if (NPVal == 2) { int k = msg.indexOf("registered as"); RegisteredName = "" + msg.charAt(k + 14) + msg.charAt(k + 15); } if (NPVal == 6) { String str = new String(DATA_Val); arr = new CopyOnWriteArrayList<>(); int m = 0; do { int k = str.indexOf(","); arr.add(new Node(str.substring(m, k))); str = str.substring(k + 1); } while (str.indexOf(",") != -1); arr.add(new Node(str)); } }
static { // Create list of customers cList.add( new Customer.CustomerBuilder() .id() .firstName("George") .lastName("Washington") .email("*****@*****.**") .city("Mt Vernon") .state("VA") .birthday("1732-02-23") .build()); cList.add( new Customer.CustomerBuilder() .id() .firstName("John") .lastName("Adams") .email("*****@*****.**") .city("Braintree") .state("MA") .birthday("1735-10-30") .build()); cList.add( new Customer.CustomerBuilder() .id() .firstName("Thomas") .lastName("Jefferson") .email("*****@*****.**") .city("CharlottesVille") .state("VA") .birthday("1743-04-13") .build()); cList.add( new Customer.CustomerBuilder() .id() .firstName("James") .lastName("Madison") .email("*****@*****.**") .city("Orange") .state("VA") .birthday("1751-03-16") .build()); cList.add( new Customer.CustomerBuilder() .id() .firstName("James") .lastName("Monroe") .email("*****@*****.**") .city("New York") .state("NY") .birthday("1758-04-28") .build()); }
public static void testWrite() { CopyOnWriteArrayList list = new CopyOnWriteArrayList(); list.add("k1:v1"); list.add("k2:v2"); Object obj0 = list.get(0); list.add("k3:v3"); list.set(0, "k1:vvvvvvv"); System.out.println(list.get(0).hashCode() + "@" + list.get(0)); System.out.println(obj0.hashCode() + "@" + obj0); }
@Override public void agentCreated() { hs = new HelloService(getExternalAccess()); ps = new SendPositionService(getExternalAccess()); addDirectService(hs); addDirectService(ps); String host = (String) getArgument("host"); Integer port = (Integer) getArgument("port"); Integer robotIdx = (Integer) getArgument("robId"); Integer devIdx = (Integer) getArgument("devIndex"); Boolean hasLaser = (Boolean) getArgument("laser"); Boolean hasLocalize = (Boolean) getArgument("localize"); /** Device list */ CopyOnWriteArrayList<Device> devList = new CopyOnWriteArrayList<Device>(); devList.add(new Device(IDevice.DEVICE_POSITION2D_CODE, host, port, devIdx)); devList.add(new Device(IDevice.DEVICE_RANGER_CODE, host, port, devIdx)); devList.add(new Device(IDevice.DEVICE_SONAR_CODE, host, port, devIdx)); devList.add(new Device(IDevice.DEVICE_SIMULATION_CODE, host, port, -1)); if (hasLocalize == true) { devList.add(new Device(IDevice.DEVICE_PLANNER_CODE, host, port + 1, devIdx)); devList.add(new Device(IDevice.DEVICE_LOCALIZE_CODE, host, port + 1, devIdx)); } /** Optional laser ranger */ if (hasLaser == true) devList.add(new Device(IDevice.DEVICE_RANGER_CODE, host, port, devIdx + 1)); /** Host list */ CopyOnWriteArrayList<Host> hostList = new CopyOnWriteArrayList<Host>(); hostList.add(new Host(host, port)); /** Optional planner device */ if (hasLocalize == true) hostList.add(new Host(host, port + 1)); /** Get the device node */ setDeviceNode( new DeviceNode( hostList.toArray(new Host[hostList.size()]), devList.toArray(new Device[devList.size()]))); getDeviceNode().runThreaded(); setRobot(new Pioneer(getDeviceNode().getDeviceListArray())); getRobot().setRobotId("r" + robotIdx); /** Check if a particular position is set */ Position setPose = new Position( (Double) getArgument("X"), (Double) getArgument("Y"), (Double) getArgument("Angle")); if (setPose.equals(new Position(0, 0, 0)) == false) getRobot().setPosition(setPose); sendHello(); }
// private ArrayList<RegistryEntry> readFromRegister(String key, Session session) { private String readFromRegister(String key, Session session) { // TODO Auto-generated method stub // Map<String, String> resultMap = new HashMap<String, String>(); String CLID = null, STATUS = null; String cqlStr = "SELECT * from consistify.registry WHERE key='" + key + "'"; Statement statement = new SimpleStatement(cqlStr); ResultSet results = session.execute(statement); CopyOnWriteArrayList<RegistryEntry> rList = new CopyOnWriteArrayList<RegistryEntry>(); RegistryEntry r = null; Scheduler scheduler = new Scheduler(); for (Row aRow : results) { // if (!resultMap.containsKey(aRow.getKey())) { if (aRow.getString("CREATETIME") != null && aRow.getString("key").equalsIgnoreCase(key)) { r = new RegistryEntry(); r.setKey(aRow.getString("key")); // System.out.println("**222*CLID:=="+aRow.getString("CLID")); r.setCLID(aRow.getString("CLID")); r.setDEADLINE(aRow.getString("DEADLINE")); r.setINDEX(aRow.getString("INDIC")); r.setLATENCYDEP(aRow.getString("LATENCYDEP")); r.setWAITINGTIME(aRow.getString("WAITINGTIME")); r.setSTATUS(aRow.getString("STATUS")); r.setCREATETIME(aRow.getString("CREATETIME")); rList.add(r); } // resultMap.put(aRow.getKey(), ++rowCnt); // System.out.println(aRow.getKey() + ":" + rowCnt); // } } // CLID = scheduler.schedule(rList).split(":")[0]; CLID = scheduler.schedule(rList); // System.out.println("****CLID:="+CLID); return CLID; }
/** * Connect provider to this pipe. Doesn't allow to connect one provider twice. Does register event * listeners if instance of IPipeConnectionListener is given. * * @param provider Provider * @param paramMap Parameters passed with connection, used in concrete pipe implementations * @return <code>true</code> if provider was added, <code>false</code> otherwise */ public boolean subscribe(IProvider provider, Map<String, Object> paramMap) { // register event listener if given if (provider instanceof IPipeConnectionListener) { listeners.add((IPipeConnectionListener) provider); } return providers.addIfAbsent(provider); }
public void add(E e) { for (int i = 0; i < replicas; ++i) { Long hash = Long.valueOf(func.hash(e.toString() + i)); circle.put(hash, e); } values.add(e); }
/** This method register a FermatTyrusPacketProcessor object with this server */ public void registerFermatPacketProcessor(FermatTyrusPacketProcessor fermatPacketProcessor) { // Validate if a previous list created if (packetProcessorsRegister.containsKey(fermatPacketProcessor.getFermatPacketType())) { /* * Add to the existing list */ packetProcessorsRegister .get(fermatPacketProcessor.getFermatPacketType()) .add(fermatPacketProcessor); } else { /* * Create a new list and add the fermatPacketProcessor */ CopyOnWriteArrayList<FermatTyrusPacketProcessor> fermatPacketProcessorList = new CopyOnWriteArrayList<>(); fermatPacketProcessorList.add(fermatPacketProcessor); /* * Add to the packetProcessorsRegister */ packetProcessorsRegister.put( fermatPacketProcessor.getFermatPacketType(), fermatPacketProcessorList); } }
/** * 第一步:通过subscriptionsByEventType得到该事件类型所有订阅者信息队列,根据优先级将当前订阅者信息插入到订阅者队列subscriptionsByEventType中; * 第二步:在typesBySubscriber中得到当前订阅者订阅的所有事件队列,将此事件保存到队列typesBySubscriber中,用于后续取消订阅; 第三步:检查这个事件是否是 * Sticky 事件,如果是则从stickyEvents事件保存队列中取出该事件类型最后一个事件发送给当前订阅者。 * * @param subscriber * @param subscriberMethod * @param sticky * @param priority */ private void subscribe( Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) { Class<?> eventType = subscriberMethod.eventType; CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); // 通过subscriptionsByEventType得到该事件类型所有订阅者信息队列 Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority); // 根据当前的eventType,在subscriptionsByEventType生成对应的key-value(没有则加入,有则跳过次处理) if (subscriptions == null) { subscriptions = new CopyOnWriteArrayList<Subscription>(); subscriptionsByEventType.put(eventType, subscriptions); } else { if (subscriptions.contains(newSubscription)) { throw new EventBusException( "Subscriber " + subscriber.getClass() + " already registered to event " + eventType); } } // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations // again) // subscriberMethod.method.setAccessible(true); // 根据优先级将当前订阅者信息插入到订阅者队列subscriptionsByEventType中; int size = subscriptions.size(); for (int i = 0; i <= size; i++) { if (i == size || newSubscription.priority > subscriptions.get(i).priority) { subscriptions.add(i, newSubscription); break; } } // 在typesBySubscriber中得到当前订阅者订阅的所有事件队列,将此事件保存到队列typesBySubscriber中,用于后续取消订阅; List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<Class<?>>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); // 检查这个事件是否是 Sticky 事件,如果是,则从stickyEvents事件保存队列中取出该事件类型最后一个事件发送给当前订阅者。 if (sticky) { if (eventInheritance) { // Existing sticky events of all subclasses of eventType have to be considered. // Note: Iterating over all events may be inefficient with lots of sticky events, // thus data structure should be changed to allow a more efficient lookup // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>). Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet(); for (Map.Entry<Class<?>, Object> entry : entries) { Class<?> candidateEventType = entry.getKey(); if (eventType.isAssignableFrom( candidateEventType)) { // 是用来判断一个类Class1和另一个类Class2是否相同或是另一个类的超类或接口 Object stickyEvent = entry.getValue(); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } } else { Object stickyEvent = stickyEvents.get(eventType); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } }
// Support POST operation. public static void add(String words) { int localId = id.incrementAndGet(); Adage adage = new Adage(); adage.setWords(words); adage.setId(localId); adages.add(adage); }
/* * Add or replace connection from CommunicationServlet static variable connections */ private void addOrReplaceConnection(String username) { // Check if exists any connection if (CommunicationWebsocketServlet.connections.get(this.username) != null) { // Get connection list and add new one CopyOnWriteArrayList<CommunicationWebsocketBusiness> connectionList = CommunicationWebsocketServlet.connections.get(this.username); connectionList.add(this); CommunicationWebsocketServlet.connections.remove(this.username); CommunicationWebsocketServlet.connections.put(this.username, connectionList); } else { // Create new connection CopyOnWriteArrayList<CommunicationWebsocketBusiness> connectionList = new CopyOnWriteArrayList<CommunicationWebsocketBusiness>(); connectionList.add(this); CommunicationWebsocketServlet.connections.put(this.username, connectionList); } }
/** @param channelTopics the channelTopics to set */ public void setChannelTopics(List<String> channelTopics) { m_channelTopics.clear(); for (String topic : channelTopics) { m_channelTopics.add(topic); } }
public void addPluginUpdateListener(PluginUpdateListener listener) { pluginUpdateListeners.add(listener); if (updates != null) { listener.pluginUpdateCheckComplete(updates, updatesForced); } else if (!updateChecker.updateChecksGloballyDisabled()) { checkForUpdates(false); } }
/** * Registers a display transaction listener to provide the client a chance to update its surfaces * within the same transaction as any display layout updates. * * @param listener The listener to register. */ public void registerDisplayTransactionListener(DisplayTransactionListener listener) { if (listener == null) { throw new IllegalArgumentException("listener must not be null"); } // List is self-synchronized copy-on-write. mDisplayTransactionListeners.add(listener); }
/** * Add listener using the specified frequency. Must be de-regsitered again using removeListener * * @param listener * @param frequency the frequency to call this listener. One of FREQUENCY_HIGH, FREQUENCY_MEDIUM, * FREQUENCY_LOW */ public void addListener(HeartListener listen, int frequency) { if (!highFrequencyListeners.contains(listen) && !mediumFrequencyListeners.contains(listen) && !lowFrequencyListeners.contains(listen)) { switch (frequency) { case FREQUENCY_HIGH: highFrequencyListeners.add(listen); break; case FREQUENCY_MEDIUM: mediumFrequencyListeners.add(listen); break; case FREQUENCY_LOW: lowFrequencyListeners.add(listen); break; } } }
/** * Add a new object to the bag for others to borrow. * * @param bagEntry an object to add to the bag */ public void add(final T bagEntry) { if (closed) { LOGGER.info("ConcurrentBag has been closed, ignoring add()"); throw new IllegalStateException("ConcurrentBag has been closed, ignoring add()"); } sharedList.add(bagEntry); synchronizer.signal(); }
/** Rest Api handlers. */ public static void createRESTHandler() { get( "/api/elevators", (req, res) -> { CopyOnWriteArrayList<ElevatorModel> models = new CopyOnWriteArrayList<ElevatorModel>(); for (Elevator e : ElevatorController.getInstance().getElevatorList()) { models.add(e.getElevatorModel()); } return models; }, new JsonTransformer()); get( "/api/floors", (req, res) -> { return Floor.getInstance(); }, new JsonTransformer()); get( "/api/requestElevator/:floor", (req, res) -> { String floor = req.params(":floor"); ElevatorControllerInterface.requestElevator(Integer.valueOf(floor)); return "Elevator request submitted"; }); post( "/api/addPeopleOnFloor", (req, res) -> { Map<String, String> keyValueMap = keyValues(req.body()); String floorNumber = keyValueMap.get("floorNumber"); String peopleCount = keyValueMap.get("peopleCount"); String destinationFloor = keyValueMap.get("destinationFloor"); if (floorNumber == null || peopleCount == null || destinationFloor == null) { return "Invalid request format, POST [url] body:floorNumber=1&peopleCount=10&destinationFloor=5"; } Floor.getInstance() .addPersonOnFloor( Integer.valueOf(floorNumber), Integer.valueOf(peopleCount), Integer.valueOf(destinationFloor)); return Floor.getInstance().getCountOfPeopleWaitingOnFloor(Integer.valueOf(floorNumber)); }, new JsonTransformer()); get( "/api/events", (req, res) -> { return ElevatorRecorder.getAll(); }, new JsonTransformer()); }
public WebApp(ServletContext context) { this.context = context; // TODO: allow classloader to be given? facets.addAll( Facet.discoverExtensions( Facet.class, Thread.currentThread().getContextClassLoader(), getClass().getClassLoader())); responseRenderers.add(new HttpResponseRenderer.Default()); }
/** * Producer method for partition collection * * @return Returns collection of partitions using copy on write list */ @PartitionType(implementation = COPY_ON_WRITE_LIST) @Produces public Collection<Partition> createPartitionCollection() { final CopyOnWriteArrayList<Partition> collection = new CopyOnWriteArrayList<>(); for (int i = 0; i < DEFAULT_MAX_PART; i++) { final String partitionName = "Partition-" + i; collection.add(new CoWPartitionImpl(DEFAULT_MAX_SESSIONS_PER_PARTITION, partitionName)); } return collection; }
public void verify( String repository, String verificationToken, final ActionListener<VerifyResponse> listener) { final DiscoveryNodes discoNodes = clusterService.state().nodes(); final DiscoveryNode localNode = discoNodes.localNode(); final ObjectContainer<DiscoveryNode> masterAndDataNodes = discoNodes.masterAndDataNodes().values(); final List<DiscoveryNode> nodes = newArrayList(); for (ObjectCursor<DiscoveryNode> cursor : masterAndDataNodes) { DiscoveryNode node = cursor.value; Version version = node.getVersion(); // Verification wasn't supported before v1.4.0 - no reason to send verification request to // these nodes if (version != null && version.onOrAfter(Version.V_1_4_0)) { nodes.add(node); } } final CopyOnWriteArrayList<VerificationFailure> errors = new CopyOnWriteArrayList<>(); final AtomicInteger counter = new AtomicInteger(nodes.size()); for (final DiscoveryNode node : nodes) { if (node.equals(localNode)) { try { doVerify(repository, verificationToken); } catch (Throwable t) { logger.warn("[{}] failed to verify repository", t, repository); errors.add(new VerificationFailure(node.id(), ExceptionsHelper.detailedMessage(t))); } if (counter.decrementAndGet() == 0) { finishVerification(listener, nodes, errors); } } else { transportService.sendRequest( node, ACTION_NAME, new VerifyNodeRepositoryRequest(repository, verificationToken), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleResponse(TransportResponse.Empty response) { if (counter.decrementAndGet() == 0) { finishVerification(listener, nodes, errors); } } @Override public void handleException(TransportException exp) { errors.add( new VerificationFailure(node.id(), ExceptionsHelper.detailedMessage(exp))); if (counter.decrementAndGet() == 0) { finishVerification(listener, nodes, errors); } } }); } } }
public FinalDungeon(int size) { dungeon = new ArrayList<Room>(); mobs = new CopyOnWriteArrayList<Monster>(); dID = 600; dungeon.add(new Room(600, "", "icons" + File.separator + "default.png")); dungeon.add(new Room(601, "", "icons" + File.separator + "default.png")); dungeon.add(new Room(602, "", "icons" + File.separator + "default.png")); dungeon.add(new Room(603, "", "icons" + File.separator + "default.png")); dungeon.add(new Room(604, "", "icons" + File.separator + "default.png")); dungeon.add(new Room(605, "", "icons" + File.separator + "default.png")); dungeon.add(new Room(606, "", "icons" + File.separator + "default.png")); entrance = dungeon.get(0); dungeon.get(0).setSouth(dungeon.get(5)); dungeon.get(0).setNorth(dungeon.get(6)); dungeon.get(0).setWest(dungeon.get(1)); dungeon.get(0).setEast(dungeon.get(2)); dungeon.get(0).setUp(dungeon.get(3)); dungeon.get(0).setDown(dungeon.get(4)); dungeon.get(1).setEast(dungeon.get(0)); dungeon.get(2).setWest(dungeon.get(0)); dungeon.get(3).setDown(dungeon.get(0)); dungeon.get(4).setUp(dungeon.get(0)); dungeon.get(5).setNorth(dungeon.get(0)); dungeon.get(6).setSouth(dungeon.get(0)); mobs.add(new Andariel()); mobs.add(new Astarte()); mobs.add(new Ayperos()); mobs.add(new Caliadne()); mobs.add(new Eligos()); mobs.add(new Orobas()); mobs.get(0).setRoom(dungeon.get(6)); mobs.get(1).setRoom(dungeon.get(5)); mobs.get(2).setRoom(dungeon.get(3)); mobs.get(3).setRoom(dungeon.get(1)); mobs.get(4).setRoom(dungeon.get(2)); mobs.get(5).setRoom(dungeon.get(4)); }
public boolean addEntity(Entity e, boolean initial) { for (Entity entity : entities) { if (e.getBump(true).intersects(entity.getBump(true))) return false; } entities.add(e); e.onSpawn(initial); render(); return true; }
public static void scheduleNewBlockChange(int dimID, ScheduledBlockChange change) { CopyOnWriteArrayList<ScheduledBlockChange> changeList = TickHandlerServer.scheduledBlockChanges.get(dimID); if (changeList == null) { changeList = new CopyOnWriteArrayList<ScheduledBlockChange>(); } changeList.add(change); TickHandlerServer.scheduledBlockChanges.put(dimID, changeList); }
private void addToHistory( final List<? extends PsiElement> elements, final FindUsagesOptions findUsagesOptions) { SearchData data = createSearchData(elements, findUsagesOptions); myFindUsagesHistory.remove(data); myFindUsagesHistory.add(data); // todo configure history depth limit if (myFindUsagesHistory.size() > 15) { myFindUsagesHistory.remove(0); } }
@Override public synchronized void add(int index, Layer layer) { if (mLayerList.contains(layer)) throw new IllegalArgumentException("layer added twice"); if (layer instanceof UpdateListener) mMap.events.bind((UpdateListener) layer); if (layer instanceof InputListener) mMap.input.bind((InputListener) layer); mLayerList.add(index, layer); mDirtyLayers = true; }
private void addNewExecutorIfNecessary() { Set<Integer> availableNumbers = new HashSet<Integer>(); for (int i = 0; i < numExecutors; i++) availableNumbers.add(i); for (Executor executor : executors) availableNumbers.remove(executor.getNumber()); for (Integer number : availableNumbers) { Executor e = new Executor(this, number); e.start(); executors.add(e); } }
private long testingCopyOnWriteArrayList() { CopyOnWriteArrayList<Object> array = new CopyOnWriteArrayList<Object>(); long start = System.currentTimeMillis(); for (int i = 0; i < getMax(); i++) { array.add(i); } long end = System.currentTimeMillis(); long time = (end - start); refreshTotalTime(time); return time; }
/** {@inheritDoc} */ public void addItem(IPlayItem item, int index) { IPlayItem prev = items.get(index); if (prev != null && prev instanceof SimplePlayItem) { // since it replaces the item in the current spot, reset the items time so the sort will work ((SimplePlayItem) item).setCreated(((SimplePlayItem) prev).getCreated() - 1); } items.add(index, item); if (index <= currentItemIndex) { // item was added before the currently playing currentItemIndex++; } }
/** Handles the events CompleteRequestListComponentRegisteredNotificationEvent */ public void handleCompleteComponentConnectionRequestNotificationEvent( final PlatformComponentProfile remoteComponentProfile) { /* * Tell the manager to handler the new connection established */ communicationNetworkServiceConnectionManager.handleEstablishedRequestedNetworkServiceConnection( remoteComponentProfile); if (remoteNetworkServicesRegisteredList != null && !remoteNetworkServicesRegisteredList.isEmpty()) remoteNetworkServicesRegisteredList.add(remoteComponentProfile); }