Java Code Examples for org.apache.commons.lang3.mutable.MutableInt#setValue()

The following examples show how to use org.apache.commons.lang3.mutable.MutableInt#setValue() . 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: JavaScriptJobManagerMinimalTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void addJob_multipleExecution_removeJob() throws Exception {
    final MutableInt id = new MutableInt();
    final MutableInt count = new MutableInt(0);
    final JavaScriptJob job = new BasicJavaScriptJob(50, Integer.valueOf(50)) {
        @Override
        public void run() {
            count.increment();
            if (count.intValue() >= 5) {
                manager_.removeJob(id.intValue());
            }
        }
    };
    id.setValue(manager_.addJob(job, page_));
    manager_.waitForJobs(1000);
    assertEquals(5, count.intValue());
}
 
Example 2
Source File: JavaScriptJobManagerMinimalTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void getJobCount() throws Exception {
    final MutableInt count = new MutableInt();
    final JavaScriptJob job = new BasicJavaScriptJob(50, null) {
        @Override
        public void run() {
            count.setValue(manager_.getJobCount());
        }
    };
    assertEquals(0, manager_.getJobCount());
    manager_.addJob(job, page_);
    manager_.waitForJobs(1000);
    assertEquals(1, count.intValue());
    assertEquals(0, manager_.getJobCount());
}
 
Example 3
Source File: TestDataInterface.java    From count-db with MIT License 6 votes vote down vote up
@Test
public void testIteratorWithFilter() {
    DataInterface<Long> dataInterface = createCountDataInterface("testIteratorWithFilter");
    int numOfItems = 100;
    for (int i = 0; i < 100; i++) {
        dataInterface.write(i, (long) i);
    }
    dataInterface.flush();
    //Try with stream
    MutableInt numOfValuesRead = new MutableInt();
    dataInterface.stream(new EvenKeysFilter()).forEach((v) -> numOfValuesRead.increment());
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
    //Try with iterator
    numOfValuesRead.setValue(0);
    CloseableIterator<KeyValue<Long>> closeableIterator = dataInterface.iterator(new EvenKeysFilter());
    while (closeableIterator.hasNext()) {
        closeableIterator.next();
        numOfValuesRead.increment();
    }
    closeableIterator.close();
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
}
 
Example 4
Source File: TestDataInterface.java    From count-db with MIT License 6 votes vote down vote up
@Test
public void testValuesIteratorWithFilter() {
    DataInterface<Long> dataInterface = createCountDataInterface("testValuesIteratorWithFilter");
    int numOfItems = 100;
    for (int i = 0; i < 100; i++) {
        dataInterface.write(i, (long) i);
    }
    dataInterface.flush();
    //Try with stream
    MutableInt numOfValuesRead = new MutableInt();
    dataInterface.streamValues(new EvenKeysFilter()).forEach((v) -> numOfValuesRead.increment());
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
    //Try with iterator
    numOfValuesRead.setValue(0);
    CloseableIterator<Long> closeableIterator = dataInterface.valueIterator(new EvenKeysFilter());
    while (closeableIterator.hasNext()) {
        closeableIterator.next();
        numOfValuesRead.increment();
    }
    closeableIterator.close();
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
}
 
Example 5
Source File: TestDataInterface.java    From count-db with MIT License 6 votes vote down vote up
@Test
public void testValuesIteratorWithRangeFilter() {
    DataInterface<Long> dataInterface = createCountDataInterface("testValuesIteratorWithRangeFilter");
    int numOfItems = 100;
    for (int i = 0; i < numOfItems; i++) {
        dataInterface.write(i, (long) i);
    }
    dataInterface.flush();
    //Try with stream
    MutableInt numOfValuesRead = new MutableInt();
    dataInterface.streamValues(new RangeKeyFilter(0, 50)).forEach((v) -> numOfValuesRead.increment());
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
    //Try with iterator
    numOfValuesRead.setValue(0);
    CloseableIterator<Long> closeableIterator = dataInterface.valueIterator(new RangeKeyFilter(0, 50));
    while (closeableIterator.hasNext()) {
        closeableIterator.next();
        numOfValuesRead.increment();
    }
    closeableIterator.close();
    Assert.assertEquals(numOfItems / 2, numOfValuesRead.intValue());
}
 
Example 6
Source File: ContentStoreCleanerScalabilityRunner.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void loadData(final int maxCount)
{
    final MutableInt doneCount = new MutableInt(0);
    // Batches of 1000 objects
    RetryingTransactionCallback<Integer> makeNodesCallback = new RetryingTransactionCallback<Integer>()
    {
        public Integer execute() throws Throwable
        {
            for (int i = 0; i < 1000; i++)
            {
                // We don't need to write anything
                String contentUrl = FileContentStore.createNewFileStoreUrl();
                ContentData contentData = new ContentData(contentUrl, MimetypeMap.MIMETYPE_TEXT_PLAIN, 10, "UTF-8");
                nodeHelper.makeNode(contentData);
                
                int count = doneCount.intValue();
                count++;
                doneCount.setValue(count);
                
                // Do some reporting
                if (count % 1000 == 0)
                {
                    System.out.println(String.format("   " + (new Date()) + "Total created: %6d", count));
                }
                
                // Double check for shutdown
                if (vmShutdownListener.isVmShuttingDown())
                {
                    break;
                }
            }
            return maxCount;
        }
    };
    int repetitions = (int) Math.floor((double)maxCount / 1000.0);
    for (int i = 0; i < repetitions; i++)
    {
        transactionService.getRetryingTransactionHelper().doInTransaction(makeNodesCallback);
    }
}
 
Example 7
Source File: ZkSplitLogWorkerCoordination.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Submit a log split task to executor service
 * @param curTask task to submit
 * @param curTaskZKVersion current version of task
 */
void submitTask(final String curTask, final int curTaskZKVersion, final int reportPeriod) {
  final MutableInt zkVersion = new MutableInt(curTaskZKVersion);

  CancelableProgressable reporter = new CancelableProgressable() {
    private long last_report_at = 0;

    @Override
    public boolean progress() {
      long t = EnvironmentEdgeManager.currentTime();
      if ((t - last_report_at) > reportPeriod) {
        last_report_at = t;
        int latestZKVersion =
            attemptToOwnTask(false, watcher, server.getServerName(), curTask,
              zkVersion.intValue());
        if (latestZKVersion < 0) {
          LOG.warn("Failed to heartbeat the task" + curTask);
          return false;
        }
        zkVersion.setValue(latestZKVersion);
      }
      return true;
    }
  };
  ZkSplitLogWorkerCoordination.ZkSplitTaskDetails splitTaskDetails =
      new ZkSplitLogWorkerCoordination.ZkSplitTaskDetails();
  splitTaskDetails.setTaskNode(curTask);
  splitTaskDetails.setCurTaskZKVersion(zkVersion);

  WALSplitterHandler hsh =
      new WALSplitterHandler(server, this, splitTaskDetails, reporter,
          this.tasksInProgress, splitTaskExecutor);
  server.getExecutorService().submit(hsh);
}
 
Example 8
Source File: ProcedureTree.java    From hbase with Apache License 2.0 5 votes vote down vote up
private void collectStackId(Entry entry, Map<Integer, List<Entry>> stackId2Proc,
  MutableInt maxStackId) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("Procedure {} stack ids={}", entry, entry.proc.getStackIdList());
  }
  for (int i = 0, n = entry.proc.getStackIdCount(); i < n; i++) {
    int stackId = entry.proc.getStackId(i);
    if (stackId > maxStackId.intValue()) {
      maxStackId.setValue(stackId);
    }
    stackId2Proc.computeIfAbsent(stackId, k -> new ArrayList<>()).add(entry);
  }
  entry.subProcs.forEach(e -> collectStackId(e, stackId2Proc, maxStackId));
}
 
Example 9
Source File: TreeGridGanttLayout.java    From gantt with Apache License 2.0 5 votes vote down vote up
/**
 * Add all child steps directed by the TreeGrid's hierarchical data source.
 */
private void addChildStepRecursively(TreeGrid<Step> grid, Step itemId, MutableInt index) {
    if (!dataProvider.hasChildren(itemId) || !grid.isExpanded(itemId)) {
        return;
    }
    if (index.getValue() == 0) {
        index.setValue(gantt.getSteps().indexOf(itemId) + 1);
    }
    for (Step child : dataProvider.getTreeData().getChildren(itemId)) {
        gantt.addStep(index.getValue(), child);
        index.increment();
        addChildStepRecursively(grid, child, index);
    }
}
 
Example 10
Source File: KinesisProxyTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetShardListRetry() throws Exception {
	Properties kinesisConsumerConfig = new Properties();
	kinesisConsumerConfig.setProperty(ConsumerConfigConstants.AWS_REGION, "us-east-1");

	Shard shard = new Shard();
	shard.setShardId("fake-shard-000000000000");
	final ListShardsResult expectedResult = new ListShardsResult();
	expectedResult.withShards(shard);

	MutableInt exceptionCount = new MutableInt();
	final Throwable[] retriableExceptions = new Throwable[]{
		new AmazonKinesisException("attempt1"),
		new AmazonKinesisException("attempt2"),
	};

	AmazonKinesisClient mockClient = mock(AmazonKinesisClient.class);
	Mockito.when(mockClient.listShards(any())).thenAnswer(new Answer<ListShardsResult>() {

		@Override
		public ListShardsResult answer(InvocationOnMock invocation) throws Throwable {
			if (exceptionCount.intValue() < retriableExceptions.length) {
				exceptionCount.increment();
				throw retriableExceptions[exceptionCount.intValue() - 1];
			}
			return expectedResult;
		}
	});

	KinesisProxy kinesisProxy = new KinesisProxy(kinesisConsumerConfig);
	Whitebox.getField(KinesisProxy.class, "kinesisClient").set(kinesisProxy, mockClient);

	HashMap<String, String> streamNames = new HashMap();
	streamNames.put("fake-stream", null);
	GetShardListResult result = kinesisProxy.getShardList(streamNames);
	assertEquals(retriableExceptions.length, exceptionCount.intValue());
	assertEquals(true, result.hasRetrievedShards());
	assertEquals(shard.getShardId(), result.getLastSeenShardOfStream("fake-stream").getShard().getShardId());

	// test max attempt count exceeded
	int maxRetries = 1;
	exceptionCount.setValue(0);
	kinesisConsumerConfig.setProperty(ConsumerConfigConstants.LIST_SHARDS_RETRIES, String.valueOf(maxRetries));
	kinesisProxy = new KinesisProxy(kinesisConsumerConfig);
	Whitebox.getField(KinesisProxy.class, "kinesisClient").set(kinesisProxy, mockClient);
	try {
		kinesisProxy.getShardList(streamNames);
		Assert.fail("exception expected");
	} catch (SdkClientException ex) {
		assertEquals(retriableExceptions[maxRetries], ex);
	}
	assertEquals(maxRetries + 1, exceptionCount.intValue());
}
 
Example 11
Source File: KinesisProxyTest.java    From flink with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetShardListRetry() throws Exception {
	Properties kinesisConsumerConfig = new Properties();
	kinesisConsumerConfig.setProperty(ConsumerConfigConstants.AWS_REGION, "us-east-1");

	Shard shard = new Shard();
	shard.setShardId("fake-shard-000000000000");
	final ListShardsResult expectedResult = new ListShardsResult();
	expectedResult.withShards(shard);

	MutableInt exceptionCount = new MutableInt();
	final Throwable[] retriableExceptions = new Throwable[]{
		new AmazonKinesisException("attempt1"),
		new AmazonKinesisException("attempt2"),
	};

	AmazonKinesisClient mockClient = mock(AmazonKinesisClient.class);
	Mockito.when(mockClient.listShards(any())).thenAnswer(new Answer<ListShardsResult>() {

		@Override
		public ListShardsResult answer(InvocationOnMock invocation) throws Throwable {
			if (exceptionCount.intValue() < retriableExceptions.length) {
				exceptionCount.increment();
				throw retriableExceptions[exceptionCount.intValue() - 1];
			}
			return expectedResult;
		}
	});

	KinesisProxy kinesisProxy = new KinesisProxy(kinesisConsumerConfig);
	Whitebox.getField(KinesisProxy.class, "kinesisClient").set(kinesisProxy, mockClient);

	HashMap<String, String> streamNames = new HashMap();
	streamNames.put("fake-stream", null);
	GetShardListResult result = kinesisProxy.getShardList(streamNames);
	assertEquals(retriableExceptions.length, exceptionCount.intValue());
	assertEquals(true, result.hasRetrievedShards());
	assertEquals(shard.getShardId(), result.getLastSeenShardOfStream("fake-stream").getShard().getShardId());

	// test max attempt count exceeded
	int maxRetries = 1;
	exceptionCount.setValue(0);
	kinesisConsumerConfig.setProperty(ConsumerConfigConstants.LIST_SHARDS_RETRIES, String.valueOf(maxRetries));
	kinesisProxy = new KinesisProxy(kinesisConsumerConfig);
	Whitebox.getField(KinesisProxy.class, "kinesisClient").set(kinesisProxy, mockClient);
	try {
		kinesisProxy.getShardList(streamNames);
		Assert.fail("exception expected");
	} catch (SdkClientException ex) {
		assertEquals(retriableExceptions[maxRetries], ex);
	}
	assertEquals(maxRetries + 1, exceptionCount.intValue());
}
 
Example 12
Source File: AttributeServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Checks that {@link AttributeService#getAttributes(AttributeQueryCallback, Serializable...) AttributeService.getAttributes}
 * works.  This includes coverage of <a href=https://issues.alfresco.com/jira/browse/MNT-9112>MNT-9112</a>.
 */
public void testGetAttributes() throws Exception
{
    attributeService.setAttribute(VALUE_AAA_STRING, KEY_AAA);
    attributeService.setAttribute(VALUE_AAB_STRING, KEY_AAB);
    attributeService.setAttribute(VALUE_AAC_STRING, KEY_AAC);

    final List<Serializable> results = new ArrayList<Serializable>();
    final MutableInt counter = new MutableInt();
    final MutableInt max = new MutableInt(3);
    AttributeQueryCallback callback = new AttributeQueryCallback()
    {
        @Override
        public boolean handleAttribute(Long id, Serializable value, Serializable[] keys)
        {
            counter.increment();
            results.add(value);
            if (counter.intValue() == max.intValue())
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    };
    
    counter.setValue(0);
    max.setValue(3);
    results.clear();
    attributeService.getAttributes(callback, KEY_A);
    assertEquals(3, results.size());
    assertEquals(3, (int)counter.getValue());
    
    counter.setValue(0);
    max.setValue(2);
    results.clear();
    attributeService.getAttributes(callback, KEY_A);
    assertEquals(2, results.size());
    assertEquals(2, (int)counter.getValue());
}
 
Example 13
Source File: UserCSVUploadPost.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void doAddUsers(final MutableInt totalUsers, final MutableInt addedUsers,
        final Map<String, String> results, final List<Map<QName,String>> users,
        final ResourceBundle rb, final boolean sendEmails)
{
    for (Map<QName,String> user : users)
    {
        totalUsers.setValue( totalUsers.intValue()+1 );
        
        // Grab the username, and do any MT magic on it
        String username = user.get(ContentModel.PROP_USERNAME);
        try
        {
            username = PersonServiceImpl.updateUsernameForTenancy(username, tenantService);
        }
        catch (TenantDomainMismatchException e)
        {
            throw new ResourceBundleWebScriptException(
                    Status.STATUS_OK, rb,
                    ERROR_GENERAL, e);
        }
        
        // Do they already exist?
        if (personService.personExists(username))
        {
            results.put(username, rb.getString(MSG_EXISTING));
            if (logger.isDebugEnabled())
            {
                logger.debug("Not creating user as already exists: " + username + " for " + user);
            }
        }
        else
        {
            String password = user.get(ContentModel.PROP_PASSWORD);
            user.remove(ContentModel.PROP_PASSWORD); // Not for the person service
            
            try
            {
                // Add the person
                personService.createPerson( (Map<QName,Serializable>)(Map)user );
                
                // Add the underlying user
                authenticationService.createAuthentication(username, password.toCharArray());
                
                // If required, notify the user
                if (sendEmails)
                {
                    personService.notifyPerson(username, password);
                }
                
                if (logger.isDebugEnabled())
                {
                    logger.debug("Creating user from upload: " + username + " for " + user);
                }
                
                // All done
                String msg = MessageFormat.format(
                        rb.getString(MSG_CREATED),
                        new Object[] { user.get(ContentModel.PROP_EMAIL) });
                results.put(username, msg);
                addedUsers.setValue( addedUsers.intValue()+1 );
            }
            catch (Throwable t)
            {
                throw new ResourceBundleWebScriptException(
                        Status.STATUS_OK, rb, ERROR_GENERAL, t);
            }
        }
    }
}
 
Example 14
Source File: Width.java    From ij-ridgedetection with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Bresenham.
 *
 * @param nx
 *            the nx
 * @param ny
 *            the ny
 * @param px
 *            the px
 * @param py
 *            the py
 * @param length
 *            the length
 * @param line
 *            the line
 * @param num_points
 *            the num points
 */
/*
 * Modified Bresenham algorithm. It returns in line all pixels that are
 * intersected by a half line less than length away from the point (px,py) aint
 * the direction (nx,ny). The point (px,py) must lie within the pixel of the
 * origin, i.e., fabs(px) <= 0.5 and fabs(py) <= 0.5.
 */
public void bresenham(double nx, double ny, double px, double py, double length, Offset[] line,
		MutableInt num_points) {
	int i, n, x, y, s1, s2, xchg, maxit;
	double e, dx, dy, t;

	x = 0;
	y = 0;
	dx = Math.abs(nx);
	dy = Math.abs(ny);
	s1 = (int) Math.signum(nx);
	s2 = (int) Math.signum(ny);
	px *= s1;
	py *= s2;
	if (dy > dx) {
		t = dx;
		dx = dy;
		dy = t;
		t = px;
		px = py;
		py = t;
		xchg = 1;
	} else {
		xchg = 0;
	}
	maxit = (int) Math.ceil(length * dx);
	e = (0.5 - px) * dy / dx - (0.5 - py);
	n = 0;
	for (i = 0; i <= maxit; i++) {
		line[n].x = x;
		line[n].y = y;
		n++;
		while (e >= -1e-8) {
			if (!(xchg == 0))
				x += s1;
			else
				y += s2;
			e--;
			if (e > -1) {
				line[n].x = x;
				line[n].y = y;
				n++;
			}
		}
		if (!(xchg == 0))
			y += s2;
		else
			x += s1;
		e += dy / dx;
	}
	num_points.setValue(n);
}
 
Example 15
Source File: KinesisProxyTest.java    From flink with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetShardListRetry() throws Exception {
	Properties kinesisConsumerConfig = new Properties();
	kinesisConsumerConfig.setProperty(ConsumerConfigConstants.AWS_REGION, "us-east-1");

	Shard shard = new Shard();
	shard.setShardId("fake-shard-000000000000");
	final ListShardsResult expectedResult = new ListShardsResult();
	expectedResult.withShards(shard);

	MutableInt exceptionCount = new MutableInt();
	final Throwable[] retriableExceptions = new Throwable[]{
		new AmazonKinesisException("attempt1"),
		new AmazonKinesisException("attempt2"),
	};

	AmazonKinesisClient mockClient = mock(AmazonKinesisClient.class);
	Mockito.when(mockClient.listShards(any())).thenAnswer(new Answer<ListShardsResult>() {

		@Override
		public ListShardsResult answer(InvocationOnMock invocation) throws Throwable {
			if (exceptionCount.intValue() < retriableExceptions.length) {
				exceptionCount.increment();
				throw retriableExceptions[exceptionCount.intValue() - 1];
			}
			return expectedResult;
		}
	});

	KinesisProxy kinesisProxy = new KinesisProxy(kinesisConsumerConfig);
	Whitebox.getField(KinesisProxy.class, "kinesisClient").set(kinesisProxy, mockClient);

	HashMap<String, String> streamNames = new HashMap();
	streamNames.put("fake-stream", null);
	GetShardListResult result = kinesisProxy.getShardList(streamNames);
	assertEquals(retriableExceptions.length, exceptionCount.intValue());
	assertEquals(true, result.hasRetrievedShards());
	assertEquals(shard.getShardId(), result.getLastSeenShardOfStream("fake-stream").getShard().getShardId());

	// test max attempt count exceeded
	int maxRetries = 1;
	exceptionCount.setValue(0);
	kinesisConsumerConfig.setProperty(ConsumerConfigConstants.LIST_SHARDS_RETRIES, String.valueOf(maxRetries));
	kinesisProxy = new KinesisProxy(kinesisConsumerConfig);
	Whitebox.getField(KinesisProxy.class, "kinesisClient").set(kinesisProxy, mockClient);
	try {
		kinesisProxy.getShardList(streamNames);
		Assert.fail("exception expected");
	} catch (SdkClientException ex) {
		assertEquals(retriableExceptions[maxRetries], ex);
	}
	assertEquals(maxRetries + 1, exceptionCount.intValue());
}
 
Example 16
Source File: Position.java    From ij-ridgedetection with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Solve the linear equation a*x+b=0 and return the result in t and the number
 * of solutions in num.
 *
 * @param a
 *            the a
 * @param b
 *            the b
 * @param t
 *            the t
 * @param num
 *            the num
 */
public void solve_linear(double a, double b, MutableDouble t, MutableInt num) {

	if (a == 0.0) { //
		num.setValue(0);
		return;
	} else {
		num.setValue(1);
		t.setValue(-b / a);
		return;
	}
}