Java Code Examples for com.google.common.collect.Lists#newCopyOnWriteArrayList()

The following examples show how to use com.google.common.collect.Lists#newCopyOnWriteArrayList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserRolesServiceImpl.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Override
public Page<UserRolesResponse> getAllUserRoles(String searchTerm, int page, int size) {
	Page<UserRoles> userRoles = userRolesRepository.findAllUserRolesDetails(searchTerm, PageRequest.of(page, size));
	List<UserRolesResponse> allUserRolesList = Lists.newCopyOnWriteArrayList();
	userRoles.getContent().forEach(userRoleDetail -> {
		UserRolesResponse userRolesResponse = new UserRolesResponse();
		if(userRoleDetail != null){
			userRolesResponse.setCreatedBy(userRoleDetail.getOwner());
			userRolesResponse.setCreatedDate(userRoleDetail.getCreatedDate());
			userRolesResponse.setModifiedDate(userRoleDetail.getModifiedDate());
			userRolesResponse.setRoleId(userRoleDetail.getRoleId());
			userRolesResponse.setDescription(userRoleDetail.getRoleDesc());
			userRolesResponse.setRoleName(userRoleDetail.getRoleName());
			userRolesResponse.setUsers(userRoleDetail.getUsers().parallelStream().map(user -> user != null ? user.getUserId() : StringUtils.EMPTY).collect(Collectors.toList()));
			allUserRolesList.add(userRolesResponse);
		} 
	 });
	Page<UserRolesResponse> allUserRoles = new PageImpl<UserRolesResponse>(allUserRolesList, PageRequest.of(page, size), userRoles.getTotalElements());
	return allUserRoles;
}
 
Example 2
Source File: RestService.java    From Juice with GNU General Public License v3.0 6 votes vote down vote up
public TaskKill kills(long taskId) {
    JuiceTask task = daoUtils.queryTask(taskId);

    if (null == task) {
        throw new RestException(CommonStatusCode.QUERY_RECORD_EMPTY.getStatus(), "task not exist to kill!");
    }

    if (task.getTaskStatus() > TaskResult.Result.RUNNING.getType()) {
        return new TaskKill(false, task.getTaskStatus(), task.getMessage());
    }

    TaskManagement taskManagement = new TaskManagement(Lists.newCopyOnWriteArrayList(), KILL);
    log.info("task id-> " + task.getTaskId() + "task name-> " +  task.getTaskName() + "retry-> " + task.getRetry() + "agent id-> " + task.getAgentId());
    TaskManagement.TaskAgentRel taskAgentRel = new TaskManagement.TaskAgentRel(task.getTaskId(), task.getTaskName(), task.getRetry(), task.getAgentId());
    taskManagement.getTaskAgentRels().add(taskAgentRel);
    log.info("push q start");
    cacheUtils.pushToQueue(cachesBizConfig.getManagementQueue(), gson.toJson(taskManagement));
    log.info("push q fin");
    return new TaskKill(true, task.getTaskStatus(), "juice accept kill task command");

}
 
Example 3
Source File: SoftwareProcessRebindNotRunningEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@BeforeMethod(alwaysRun=true)
@Override
public void setUp() throws Exception {
    super.setUp();

    latches = Lists.newCopyOnWriteArrayList();
    
    machineSpec = LocationSpec.create(SshMachineLocation.class)
            .configure("address", "1.2.3.4")
            .configure(SshMachineLocation.SSH_TOOL_CLASS, RecordingSshTool.class.getName());
    
    locationProvisioner = app().getManagementContext().getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
            .configure(FixedListMachineProvisioningLocation.MACHINE_SPECS, ImmutableList.<LocationSpec<? extends MachineLocation>>of(
                    machineSpec)));

    executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    
    RecordingSshTool.clear();
}
 
Example 4
Source File: CountDownLatchHelper.java    From Lottor with MIT License 5 votes vote down vote up
public CountDownLatchHelper() {
    executes = Lists.newCopyOnWriteArrayList();
    data = Lists.newCopyOnWriteArrayList();
    threadPool= new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors(),
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

}
 
Example 5
Source File: ServiceReplacerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    super.setUp();
    
    loc = app.newSimulatedLocation();
    events = Lists.newCopyOnWriteArrayList();
    eventListener = new SensorEventListener<Object>() {
        @Override public void onEvent(SensorEvent<Object> event) {
            events.add(event);
        }
    };
}
 
Example 6
Source File: RestService.java    From Juice with GNU General Public License v3.0 5 votes vote down vote up
public TaskReconcile reconciles(List<Long> taskIds) {
    List<JuiceTask> tasks = daoUtils.queryTasks(taskIds);
    Map<Long, TaskReconcile.Reconcile> reconcileMap = getTaskReconcile(taskIds);
    TaskManagement taskManagement = new TaskManagement(Lists.newCopyOnWriteArrayList(), RECONCILE);
    tasks.stream().parallel().forEach(t -> {
        String value = t.getAgentId();

        boolean isReconciled = false;
        String message = "";
        TaskReconcile.Reconcile reconcile = reconcileMap.get(t.getTaskId());
        if (null == reconcile) {
            String error = "taskId not matched with database record, taskId: " + t.getTaskId();
            log.warn(error);
            throw new RestException(ErrorCode.OBJECT_NOT_EQUAL_ERROR.getCode(), error);
        } else if (!t.getTaskStatus().equals(TaskResult.Result.RUNNING.getType())) {
            message = "not reconcile due to terminal task status : " + TaskResult.Result.getName(t.getTaskStatus());
        } else if (StringUtils.isBlank(value)) {
            reconcile.setReconciled(false);
            daoUtils.finishTaskWithSource(t.getTaskId(), TaskResult.Result.EXPIRED.getType(), "task expired", "");
            message = "not reconcile due to terminal task status : " + TaskResult.Result.EXPIRED.name();
        } else {
            TaskManagement.TaskAgentRel taskAgentRel = new TaskManagement.TaskAgentRel(t.getTaskId(), t.getTaskName(), t.getRetry(), value);
            taskManagement.getTaskAgentRels().add(taskAgentRel);
            isReconciled = true;
            message = "reconcile task";
        }

        reconcile.setTaskId(t.getTaskId());
        reconcile.setReconciled(isReconciled);
        reconcile.setMessage(message);
    });
    int reconcileCount = taskManagement.getTaskAgentRels().size();
    if (reconcileCount > 0) {
        cacheUtils.pushToQueue(cachesBizConfig.getManagementQueue(), gson.toJson(taskManagement));
    }
    return new TaskReconcile(taskIds.size(), reconcileCount, mapsToLists(reconcileMap));
}
 
Example 7
Source File: RestService.java    From Juice with GNU General Public License v3.0 5 votes vote down vote up
private List<TaskReconcile.Reconcile> mapsToLists(Map<Long, TaskReconcile.Reconcile> map) {
    final List<TaskReconcile.Reconcile> reconciles = Lists.newCopyOnWriteArrayList();
    map.entrySet().parallelStream().forEach(
            v -> {
                reconciles.add(v.getValue());
            }
    );
    return reconciles;
}
 
Example 8
Source File: ServiceRestarterTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    super.setUp();
    e1 = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    events = Lists.newCopyOnWriteArrayList();
    eventListener = new SensorEventListener<Object>() {
        @Override public void onEvent(SensorEvent<Object> event) {
            events.add(event);
        }
    };
}
 
Example 9
Source File: InOrderFlowObjectiveManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Test
public void forwardTimeout() {
    final AtomicInteger counter = new AtomicInteger(0);
    ForwardingObjective fwdTimeout = buildFwdObjective(S1, NID2).add(new ObjectiveContext() {
        @Override
        public void onError(Objective objective, ObjectiveError error) {
            if (Objects.equals(ObjectiveError.INSTALLATIONTIMEOUT, error)) {
                counter.incrementAndGet();
            }
        }
    });
    List<ForwardingObjective> expectFwdObjsTimeout = Lists.newCopyOnWriteArrayList(
            Lists.newArrayList(fwdTimeout, FWD1, FWD2));

    // Reduce timeout so the unit test doesn't have to wait many seconds
    internalSetup(TIMEOUT_THRESH);

    expect(mgr.flowObjectiveStore.getNextGroup(NID1)).andReturn(NGRP1).times(1);
    expect(mgr.flowObjectiveStore.getNextGroup(NID2)).andReturn(NGRP2).times(2);
    replay(mgr.flowObjectiveStore);

    // Force this objective to time out
    offset = mgr.objTimeoutMs * 3;

    expectFwdObjsTimeout.forEach(fwdObj -> mgr.forward(DEV1, fwdObj));

    // Wait for the pipeline operation to complete
    int expectedTime = (bound + offset) * 3;
    assertAfter(expectedTime, expectedTime * 5, () -> assertEquals(expectFwdObjsTimeout.size(), actualObjs.size()));

    assertAfter(expectedTime, expectedTime * 5, () -> assertTrue(counter.get() != 0));
    assertTrue(actualObjs.indexOf(fwdTimeout) < actualObjs.indexOf(FWD1));

    verify(mgr.flowObjectiveStore);
}
 
Example 10
Source File: BasicStartableTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesFilterToEntities() throws Exception {
    final List<Object> contexts = Lists.newCopyOnWriteArrayList();
    
    LocationsFilter filter = new LocationsFilter() {
        private static final long serialVersionUID = 7078046521812992013L;
        @Override public List<Location> filterForContext(List<Location> locations, Object context) {
            contexts.add(context);
            assertEquals(locations, ImmutableList.of(loc1, loc2));
            if (context instanceof Entity) {
                String entityName = ((Entity)context).getDisplayName();
                if ("1".equals(entityName)) {
                    return ImmutableList.<Location>of(loc1);
                } else if ("2".equals(entityName)) {
                    return ImmutableList.<Location>of(loc2);
                } else {
                    return ImmutableList.<Location>of();
                }
            } else {
                return ImmutableList.<Location>of();
            }
        }
    };
    BasicStartable startable = app.addChild(EntitySpec.create(BasicStartable.class)
            .configure(BasicStartable.LOCATIONS_FILTER, filter));
    TestEntity entity = startable.addChild(EntitySpec.create(TestEntity.class).displayName("1"));
    TestEntity entity2 = startable.addChild(EntitySpec.create(TestEntity.class).displayName("2"));
    app.start(ImmutableList.of(loc1, loc2));
    
    assertEqualsIgnoringOrder(entity.getLocations(), ImmutableSet.of(loc1));
    assertEqualsIgnoringOrder(entity2.getLocations(), ImmutableSet.of(loc2));
    assertEqualsIgnoringOrder(contexts, ImmutableList.of(entity, entity2));
}
 
Example 11
Source File: JcloudsRebindStubUnitTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    super.setUp();
    RecordingSshTool.clear();
    RecordingWinRmTool.clear();
    mgmts = Lists.newCopyOnWriteArrayList(ImmutableList.<ManagementContext>of(origManagementContext));
    machines = Multimaps.synchronizedMultimap(ArrayListMultimap.<ManagementContext, JcloudsSshMachineLocation>create());
}
 
Example 12
Source File: AbstractJcloudsLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    machines = Lists.newCopyOnWriteArrayList();
    managementContext = newManagementContext();
    
    // Don't let any defaults from brooklyn.properties (except credentials) interfere with test
    brooklynProperties = managementContext.getBrooklynProperties();
    stripBrooklynProperties(brooklynProperties);
}
 
Example 13
Source File: JcloudsRebindStubTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    super.setUp();
    mgmts = Lists.newCopyOnWriteArrayList(ImmutableList.<ManagementContext>of(origManagementContext));
    machines = Multimaps.synchronizedMultimap(ArrayListMultimap.<ManagementContext, JcloudsSshMachineLocation>create());
}
 
Example 14
Source File: ConnectionCacheEntity.java    From Thunder with Apache License 2.0 5 votes vote down vote up
private synchronized List<ConnectionEntity> retrieveConnectionEntityList(String interfaze) {
    List<ConnectionEntity> connectionEntityList = getConnectionEntityList(interfaze);
    if (connectionEntityList == null) {
        connectionEntityList = Lists.newCopyOnWriteArrayList();
        connectionEntityMap.put(interfaze, connectionEntityList);
    }

    return connectionEntityList;
}
 
Example 15
Source File: DockerJcloudsLocationLiveTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@BeforeMethod(alwaysRun = true)
@Override
public void setUp() throws Exception {
    super.setUp();
    machines = Lists.newCopyOnWriteArrayList();
}
 
Example 16
Source File: ReleaseMessageScanner.java    From apollo with Apache License 2.0 4 votes vote down vote up
public ReleaseMessageScanner() {
  listeners = Lists.newCopyOnWriteArrayList();
  executorService = Executors.newScheduledThreadPool(1, ApolloThreadFactory
      .create("ReleaseMessageScanner", true));
}
 
Example 17
Source File: AutoScalerPolicyMetricTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test(groups="Integration",invocationCount=20)
public void testWarnsWhenMaxCapReached() {
    final List<MaxPoolSizeReachedEvent> maxReachedEvents = Lists.newCopyOnWriteArrayList();
    tc.resize(1);
    
    BasicNotificationSensor<MaxPoolSizeReachedEvent> maxSizeReachedSensor = AutoScalerPolicy.DEFAULT_MAX_SIZE_REACHED_SENSOR;
    
    app.subscriptions().subscribe(tc, maxSizeReachedSensor, new SensorEventListener<MaxPoolSizeReachedEvent>() {
            @Override public void onEvent(SensorEvent<MaxPoolSizeReachedEvent> event) {
                maxReachedEvents.add(event.getValue());
            }});
    
    tc.policies().add(AutoScalerPolicy.builder()
            .metric(MY_ATTRIBUTE)
            .metricLowerBound(50)
            .metricUpperBound(100)
            .maxPoolSize(6)
            .maxSizeReachedSensor(maxSizeReachedSensor)
            .buildSpec());

    // workload can be handled by 6 servers, so no need to notify: 6 <= (100*6)/50
    tc.sensors().set(MY_ATTRIBUTE, 600);
    Asserts.succeedsEventually(currentSizeAsserter(tc, 6));
    assertTrue(maxReachedEvents.isEmpty());
    
    // Increases to above max capacity: would require (100000*6)/100 = 6000
    tc.sensors().set(MY_ATTRIBUTE, 100000);
    
    // Assert our listener gets notified (once)
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            assertEquals(maxReachedEvents.size(), 1);
            assertEquals(maxReachedEvents.get(0).getMaxAllowed(), 6);
            assertEquals(maxReachedEvents.get(0).getCurrentPoolSize(), 6);
            assertEquals(maxReachedEvents.get(0).getCurrentUnbounded(), 6000);
            assertEquals(maxReachedEvents.get(0).getMaxUnbounded(), 6000);
            assertEquals(maxReachedEvents.get(0).getTimeWindow(), 0);
        }});
    Asserts.succeedsContinually(new Runnable() {
            @Override public void run() {
                assertEquals(maxReachedEvents.size(), 1);
            }});
    currentSizeAsserter(tc, 6).run();
}
 
Example 18
Source File: MythTransaction.java    From myth with Apache License 2.0 4 votes vote down vote up
public MythTransaction() {
    this.transId = IdWorkerUtils.getInstance().createUUID();
    this.createTime = new Date();
    this.lastTime = new Date();
    mythParticipants = Lists.newCopyOnWriteArrayList();
}
 
Example 19
Source File: HmilyTransaction.java    From hmily with Apache License 2.0 4 votes vote down vote up
public HmilyTransaction(final String transId) {
    this.transId = transId;
    this.createTime = new Date();
    this.lastTime = new Date();
    hmilyParticipants = Lists.newCopyOnWriteArrayList();
}
 
Example 20
Source File: NMS.java    From TabooLib with MIT License 4 votes vote down vote up
public List<NBTAttribute> getAttribute(ItemStack item) {
    NBTCompound nbt = loadNBT(item);
    return !nbt.containsKey("AttributeModifiers") ? Lists.newCopyOnWriteArrayList() : nbt.get("AttributeModifiers").asList().stream().map(element -> NBTAttribute.fromNBT(element.asCompound())).collect(Collectors.toCollection(CopyOnWriteArrayList::new));
}