List of usage examples for java.util.concurrent.atomic AtomicInteger get
public final int get()
From source file:com.cronutils.model.time.TimeNode.java
/** * We return same reference value if matches or next one if does not match. * Then we start applying shifts./*from w w w.j av a 2 s . c om*/ * This way we ensure same value is returned if no shift is requested. * @param reference - reference value * @param shiftsToApply - shifts to apply * @return NearestValue instance, never null. Holds information on nearest (forward) value and shifts performed. */ @VisibleForTesting NearestValue getNearestForwardValue(int reference, int shiftsToApply) { List<Integer> values = new ArrayList<Integer>(this.values); int index = 0; boolean foundGreater = false; AtomicInteger shift = new AtomicInteger(0); if (!values.contains(reference)) { for (Integer value : values) { if (value > reference) { index = values.indexOf(value); shiftsToApply--;//we just moved a position! foundGreater = true; break; } } if (!foundGreater) { shift.incrementAndGet(); } } else { index = values.indexOf(reference); } int value = values.get(index); for (int j = 0; j < shiftsToApply; j++) { value = getValueFromList(values, index + 1, shift); index = values.indexOf(value); } return new NearestValue(value, shift.get()); }
From source file:com.asakusafw.lang.compiler.cli.BatchCompilerCliTest.java
/** * minimal args./* w w w. j a va2s. c om*/ * @throws Exception if failed */ @Test public void execute_minimal() throws Exception { File output = deployer.newFolder(); String[] args = strings( new Object[] { "--explore", files(ResourceUtil.findLibraryByClass(DummyBatch.class)), "--output", output, "--classAnalyzer", classes(DummyClassAnalyzer.class), "--batchCompiler", classes(DelegateBatchCompiler.class), "--include", classes(DummyBatch.class), "--externalPortProcessors", classes(DummyExternalPortProcessor.class), }); AtomicInteger count = new AtomicInteger(); int status = execute(args, (context, batch) -> { count.incrementAndGet(); assertThat(batch.getBatchId(), is("DummyBatch")); assertThat(batch.getDescriptionClass(), is(classOf(DummyBatch.class))); assertThat(context.getOutput().getBasePath(), is(new File(output, batch.getBatchId()))); }); assertThat(status, is(0)); assertThat(count.get(), is(1)); }
From source file:com.cronutils.model.time.TimeNode.java
/** * We return same reference value if matches or previous one if does not match. * Then we start applying shifts.//from w ww. j ava2s. co m * This way we ensure same value is returned if no shift is requested. * @param reference - reference value * @param shiftsToApply - shifts to apply * @return NearestValue instance, never null. Holds information on nearest (backward) value and shifts performed. */ @VisibleForTesting NearestValue getNearestBackwardValue(int reference, int shiftsToApply) { List<Integer> values = new ArrayList<Integer>(this.values); Collections.reverse(values); int index = 0; boolean foundSmaller = false; AtomicInteger shift = new AtomicInteger(0); if (!values.contains(reference)) { for (Integer value : values) { if (value < reference) { index = values.indexOf(value); shiftsToApply--;//we just moved a position! foundSmaller = true; break; } } if (!foundSmaller) { shift.incrementAndGet(); } } else { index = values.indexOf(reference); } int value = values.get(index); for (int j = 0; j < shiftsToApply; j++) { value = getValueFromList(values, index + 1, shift); index = values.indexOf(value); } return new NearestValue(value, shift.get()); }
From source file:org.mahasen.util.PutUtil.java
/** * @param file/*ww w .ja v a2 s. c o m*/ * @throws InterruptedException * @throws RegistryException * @throws PastException * @throws IOException */ public void secureUpload(File file, Id resourceId) throws InterruptedException, RegistryException, PastException, IOException, MahasenConfigurationException, MahasenException { // get the IP addresses pool to upload files. Vector<String> nodeIpsToPut = getNodeIpsToPut(); MahasenFileSplitter mahasenFileSplitter = new MahasenFileSplitter(); mahasenFileSplitter.split(file); HashMap<String, String> fileParts = mahasenFileSplitter.getPartNames(); mahasenResource.addPartNames(fileParts.keySet().toArray(new String[fileParts.size()])); Random random = new Random(); for (String currentPartName : fileParts.keySet()) { File splittedFilePart = new File(fileParts.get(currentPartName)); int randomNumber = random.nextInt(nodeIpsToPut.size()); String nodeIp = nodeIpsToPut.get(randomNumber); try { setTrustStore(); URI uri = null; ArrayList<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("splittedfilename", splittedFilePart.getName())); uri = URIUtils.createURI("https", nodeIp + ":" + MahasenConstants.SERVER_PORT, -1, "/mahasen/upload_request_ajaxprocessor.jsp", URLEncodedUtils.format(qparams, "UTF-8"), null); MahasenUploadWorker uploadWorker = new MahasenUploadWorker(uri, currentPartName, splittedFilePart, mahasenResource, nodeIp); uploadThread = new Thread(uploadWorker); uploadWorker.setJobId(jobId); //keep track of uploading parts AtomicInteger noOfParts = new AtomicInteger(0); storedNoOfParts.put(jobId, noOfParts); uploadThread.start(); } catch (Exception e) { e.printStackTrace(); } } final BlockFlag blockFlag = new BlockFlag(true, 6000); while (true) { AtomicInteger noOfParts = storedNoOfParts.get(jobId); if (noOfParts.get() == fileParts.size()) { storedNoOfParts.remove(uploadThread.getId()); System.out.println("uploaded no of parts " + noOfParts + "out of " + fileParts.size() + "going out " + "#####Thread id:" + uploadThread.getId()); blockFlag.unblock(); break; } if (blockFlag.isBlocked()) { mahasenManager.getNode().getEnvironment().getTimeSource().sleep(10); } else { throw new MahasenException("Time out in uploading " + file.getName()); } } mahasenManager.insertIntoDHT(resourceId, mahasenResource, false); mahasenManager.insertTreeMapIntoDHT(resourceId, mahasenResource, false); ReplicateRequestStarter replicateStarter = new ReplicateRequestStarter(mahasenResource); Thread replicateThread = new Thread(replicateStarter); replicateThread.start(); }
From source file:com.logsniffer.reader.log4j.Log4jTextReaderTest.java
@Test(timeout = 200 * 1000) public void testPerformanceAndMultiThreading() throws IOException, ParseException { final Log4jTextReader reader = new Log4jTextReader("%d{ABSOLUTE} %-5p [%c] %m%n", "UTF-8"); final byte[] logLine = "00:27:29,456 DEBUG [com.logsniffer.parser.log4j.Log4jParser] Prepared parsing pattern\n" .getBytes();/*w w w . j a va2 s . c om*/ final ByteLogAccess mockAccess = Mockito.mock(ByteLogAccess.class); Mockito.when(mockAccess.createRelative(Mockito.any(LogPointer.class), Mockito.anyLong())) .thenAnswer(new Answer<LogPointer>() { @Override public LogPointer answer(final InvocationOnMock invocation) throws Throwable { final DefaultPointer from = (DefaultPointer) invocation.getArguments()[0]; final long offset = (long) invocation.getArguments()[1]; return new DefaultPointer(from == null ? offset : from.getOffset() + offset, Long.MAX_VALUE); } }); Mockito.when(mockAccess.getInputStream(null)).thenReturn(new ByteLogInputStream() { int i = 0; @Override public LogPointer getPointer() throws IOException { return new DefaultPointer(i, Long.MAX_VALUE); } @Override public int read() throws IOException { return logLine[i++ % logLine.length]; } }); final int linesToRead = 100000; final long start = System.currentTimeMillis(); final AtomicInteger count = new AtomicInteger(0); reader.readEntries(Mockito.mock(Log.class), mockAccess, null, new LogEntryConsumer() { @Override public boolean consume(final Log log, final LogPointerFactory pointerFactory, final LogEntry entry) throws IOException { try { Thread.sleep(1); } catch (final InterruptedException e) { e.printStackTrace(); } return count.incrementAndGet() < linesToRead; } }); final long size = logLine.length * (count.get() - 1); final long time = System.currentTimeMillis() - start; logger.info("Read {} lines {} total bytes in {}ms: {} bytes/s", count.get() - 1, size, time, size / time * 1000); Assert.assertEquals(linesToRead, count.get()); }
From source file:com.xiaomi.linden.file.TestFileChangeWatcher.java
@Test public void testFileChangeWatcher() throws IOException, InterruptedException { final AtomicInteger events = new AtomicInteger(0); final Function<String, Object> callback = new Function<String, Object>() { @Override/*from w w w . jav a 2s.c om*/ public String apply(String absolutePath) { events.incrementAndGet(); return null; } }; File dir = new File("tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File("tmp/test.txt"); file.createNewFile(); fileChangeWatcher = new FileChangeWatcher(file.getAbsolutePath(), callback, 10); fileChangeWatcher.start(); directoryChangeWatcher = new DirectoryChangeWatcher(dir.getAbsolutePath(), callback, 10); directoryChangeWatcher.start(); Files.write("Hello", file, Charsets.UTF_8); Thread.sleep(10 * 1000); Assert.assertEquals(2, events.get()); FileUtils.deleteQuietly(file); FileUtils.deleteDirectory(dir); }
From source file:org.apache.activemq.web.RestTest.java
@Test(timeout = 15 * 1000) public void testProperties() throws Exception { int port = getPort(); HttpClient httpClient = new HttpClient(); httpClient.start();/* w ww . j a va2s. c om*/ final CountDownLatch latch = new CountDownLatch(1); final StringBuffer buf = new StringBuffer(); final AtomicInteger status = new AtomicInteger(); httpClient.newRequest("http://localhost:" + port + "/message/testPost?type=queue&property=value") .method(HttpMethod.POST).send(new BufferingResponseListener() { @Override public void onComplete(Result result) { status.getAndSet(result.getResponse().getStatus()); buf.append(getContentAsString()); latch.countDown(); } }); latch.await(); assertTrue("success status", HttpStatus.isSuccess(status.get())); final CountDownLatch latch2 = new CountDownLatch(1); final StringBuffer buf2 = new StringBuffer(); final AtomicInteger status2 = new AtomicInteger(); final HttpFields responseFields = new HttpFields(); httpClient.newRequest("http://localhost:" + port + "/message/testPost?readTimeout=1000&type=Queue") .method(HttpMethod.GET).send(new BufferingResponseListener() { @Override public void onComplete(Result result) { responseFields.add(result.getResponse().getHeaders()); status2.getAndSet(result.getResponse().getStatus()); buf2.append(getContentAsString()); latch2.countDown(); } }); latch2.await(); assertTrue("success status", HttpStatus.isSuccess(status2.get())); HttpFields fields = responseFields; assertNotNull("Headers Exist", fields); assertEquals("header value", "value", fields.getStringField("property")); }
From source file:org.alfresco.repo.model.filefolder.FileFolderLoader.java
private int createFiles(final NodeRef folderNodeRef, final int fileCount, final int filesPerTxn, final long minFileSize, final long maxFileSize, final long maxUniqueDocuments, final boolean forceBinaryStorage, final int descriptionCount, final long descriptionSize) { final String nameBase = UUID.randomUUID().toString(); final AtomicInteger count = new AtomicInteger(0); RetryingTransactionCallback<Void> createFilesWork = new RetryingTransactionCallback<Void>() { @Override/*from w ww . j a v a 2s . c o m*/ public Void execute() throws Throwable { // Disable timestamp propagation to the parent by disabling cm:auditable policyBehaviourFilter.disableBehaviour(folderNodeRef, ContentModel.ASPECT_AUDITABLE); for (int i = 0; i < filesPerTxn; i++) { // Only create files while we need; we may need to do fewer in the last txn if (count.get() >= fileCount) { break; } // Each load has it's own base name String name = String.format("%s-%6d.txt", nameBase, count.get()); // Create a file FileInfo fileInfo = fileFolderService.create(folderNodeRef, name, ContentModel.TYPE_CONTENT, ContentModel.ASSOC_CONTAINS); NodeRef fileNodeRef = fileInfo.getNodeRef(); // Spoofed document Locale locale = Locale.ENGLISH; long seed = (long) (Math.random() * maxUniqueDocuments); long size = normalDistribution.getValue(minFileSize, maxFileSize); String contentUrl = SpoofedTextContentReader.createContentUrl(locale, seed, size); SpoofedTextContentReader reader = new SpoofedTextContentReader(contentUrl); if (forceBinaryStorage) { // Stream the text into the real storage ContentWriter writer = contentService.getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true); writer.setEncoding("UTF-8"); writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); writer.putContent(reader); } else { // Just use the URL ContentData contentData = reader.getContentData(); nodeService.setProperty(fileNodeRef, ContentModel.PROP_CONTENT, contentData); } // Store the description, if required if (descriptionCount > 0) { // Add the cm:description additional properties boolean wasMLAware = MLPropertyInterceptor.setMLAware(true); try { MLText descriptions = new MLText(); String[] languages = Locale.getISOLanguages(); String defaultLanguage = Locale.getDefault().getLanguage(); // Create cm:description translations for (int descriptionNum = -1; descriptionNum < (descriptionCount - 1); descriptionNum++) { String language = null; // Use the default language for the first description if (descriptionNum == -1) { language = defaultLanguage; } else if (languages[descriptionNum].equals(defaultLanguage)) { // Skip the default language, if we hit it continue; } else { language = languages[descriptionNum]; } Locale languageLocale = new Locale(language); // For the cm:description, create new reader with a seed that changes each time String descriptionUrl = SpoofedTextContentReader.createContentUrl(locale, seed + descriptionNum, descriptionSize); SpoofedTextContentReader readerDescription = new SpoofedTextContentReader( descriptionUrl); String description = readerDescription.getContentString(); descriptions.put(languageLocale, description); } nodeService.setProperty(fileNodeRef, ContentModel.PROP_DESCRIPTION, descriptions); } finally { MLPropertyInterceptor.setMLAware(wasMLAware); } } // Success count.incrementAndGet(); } return null; } }; // Batches RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper(); int txnCount = (int) Math.ceil((double) fileCount / (double) filesPerTxn); for (int i = 0; i < txnCount; i++) { txnHelper.doInTransaction(createFilesWork, false, true); } // Done return count.get(); }
From source file:org.jtheque.file.FileServiceTest.java
@Test public void importers() { final AtomicInteger counter = new AtomicInteger(0); fileService.registerImporter("no-module", new Importer() { @Override// ww w . ja v a2 s . c o m public boolean canImportFrom(String fileType) { return "xml".equals(fileType); } @Override public void importFrom(String path) throws FileException { assertEquals("path", path); counter.incrementAndGet(); } }); try { fileService.importDatas("no-module", "xml", "path"); } catch (FileException e) { fail("Exception during the export"); } assertEquals(1, counter.get()); }
From source file:io.realm.Realm.java
/** * Delete the Realm file specified by the given {@link RealmConfiguration} from the filesystem. * The Realm must be unused and closed before calling this method. * * @param configuration A {@link RealmConfiguration} * @return false if a file could not be deleted. The failing file will be logged. * * @throws java.lang.IllegalStateException if trying to delete a Realm that is already open. *//*ww w.j a v a 2s .c om*/ public static synchronized boolean deleteRealm(RealmConfiguration configuration) { boolean result = true; String id = configuration.getPath(); AtomicInteger counter = globalOpenInstanceCounter.get(id); if (counter != null && counter.get() > 0) { throw new IllegalStateException("It's not allowed to delete the file associated with an open Realm. " + "Remember to close() all the instances of the Realm before deleting its file."); } File realmFolder = configuration.getRealmFolder(); String realmFileName = configuration.getRealmFileName(); List<File> filesToDelete = Arrays.asList(new File(configuration.getPath()), new File(realmFolder, realmFileName + ".lock"), new File(realmFolder, realmFileName + ".lock_a"), new File(realmFolder, realmFileName + ".lock_b"), new File(realmFolder, realmFileName + ".log")); for (File fileToDelete : filesToDelete) { if (fileToDelete.exists()) { boolean deleteResult = fileToDelete.delete(); if (!deleteResult) { result = false; RealmLog.w("Could not delete the file " + fileToDelete); } } } return result; }