List of usage examples for java.util.concurrent.atomic AtomicBoolean get
public final boolean get()
From source file:de.undercouch.gradle.tasks.download.InterceptorTest.java
/** * Tests if we can manipulate a response * @throws Exception if anything goes wrong *//*from w w w . j a v a 2 s .com*/ @Test public void interceptResponse() throws Exception { final AtomicBoolean interceptorCalled = new AtomicBoolean(false); Download t = makeProjectAndTask(); t.src(makeSrc(INTERCEPTOR)); File dst = folder.newFile(); t.dest(dst); t.responseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { assertFalse(interceptorCalled.get()); interceptorCalled.set(true); response.setEntity(new StringEntity(INTERCEPTED)); } }); t.execute(); assertTrue(interceptorCalled.get()); String dstContents = FileUtils.readFileToString(dst); assertEquals(INTERCEPTED, dstContents); }
From source file:org.apache.hadoop.mapreduce.server.tasktracker.Localizer.java
/** * Initialize the local directories for a particular user on this TT. This * involves creation and setting permissions of the following directories * <ul>/* w w w . j ava 2s. c o m*/ * <li>$mapred.local.dir/taskTracker/$user</li> * <li>$mapred.local.dir/taskTracker/$user/jobcache</li> * <li>$mapred.local.dir/taskTracker/$user/distcache</li> * </ul> * * @param user * @throws IOException */ public void initializeUserDirs(String user) throws IOException { if (user == null) { // This shouldn't happen in general throw new IOException("User is null. Cannot initialized user-directories."); } AtomicBoolean localizedUser; synchronized (localizedUsers) { if (!localizedUsers.containsKey(user)) { localizedUsers.put(user, new AtomicBoolean(false)); } localizedUser = localizedUsers.get(user); } synchronized (localizedUser) { if (localizedUser.get()) { // User-directories are already localized for this user. LOG.info("User-directories for the user " + user + " are already initialized on this TT. Not doing anything."); return; } LOG.info("Initializing user " + user + " on this TT."); boolean userDirStatus = false; boolean jobCacheDirStatus = false; boolean distributedCacheDirStatus = false; for (String localDir : localDirs) { Path userDir = new Path(localDir, TaskTracker.getUserDir(user)); // Set up the user-directory. if (fs.exists(userDir) || fs.mkdirs(userDir)) { // Set permissions on the user-directory FsPermission userOnly = new FsPermission((short) 0700); FileUtil.setPermission(new File(userDir.toUri().getPath()), userOnly); userDirStatus = true; // Set up the jobcache directory File jobCacheDir = new File(localDir, TaskTracker.getJobCacheSubdir(user)); if (jobCacheDir.exists() || jobCacheDir.mkdirs()) { // Set permissions on the jobcache-directory FileUtil.setPermission(jobCacheDir, userOnly); jobCacheDirStatus = true; } else { LOG.warn("Unable to create job cache directory : " + jobCacheDir); } // Set up the cache directory used for distributed cache files File distributedCacheDir = new File(localDir, TaskTracker.getPrivateDistributedCacheDir(user)); if (distributedCacheDir.exists() || distributedCacheDir.mkdirs()) { // Set permissions on the distcache-directory FileUtil.setPermission(distributedCacheDir, userOnly); distributedCacheDirStatus = true; } else { LOG.warn("Unable to create distributed-cache directory : " + distributedCacheDir); } } else { LOG.warn("Unable to create the user directory : " + userDir); } } if (!userDirStatus) { throw new IOException("Not able to initialize user directories " + "in any of the configured local directories for user " + user); } if (!jobCacheDirStatus) { throw new IOException("Not able to initialize job-cache directories " + "in any of the configured local directories for user " + user); } if (!distributedCacheDirStatus) { throw new IOException("Not able to initialize distributed-cache directories " + "in any of the configured local directories for user " + user); } // Localization of the user is done localizedUser.set(true); } }
From source file:ch.cyberduck.core.worker.SingleTransferWorkerTest.java
@Test public void testTransferredSizeRepeat() throws Exception { final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); final byte[] content = new byte[62768]; new Random().nextBytes(content); final OutputStream out = local.getOutputStream(false); IOUtils.write(content, out);//from w w w . jav a 2 s . co m out.close(); final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch", new Credentials(System.getProperties().getProperty("webdav.user"), System.getProperties().getProperty("webdav.password"))); host.setDefaultPath("/dav/basic"); final AtomicBoolean failed = new AtomicBoolean(); final DAVSession session = new DAVSession(host) { final DAVUploadFeature upload = new DAVUploadFeature(new DAVWriteFeature(this)) { @Override protected InputStream decorate(final InputStream in, final MessageDigest digest) throws IOException { if (failed.get()) { // Second attempt successful return in; } return new CountingInputStream(in) { @Override protected void beforeRead(final int n) throws IOException { super.beforeRead(n); if (this.getByteCount() >= 32768L) { failed.set(true); throw new SocketTimeoutException(); } } }; } }; @Override @SuppressWarnings("unchecked") public <T> T _getFeature(final Class<T> type) { if (type == Upload.class) { return (T) upload; } return super._getFeature(type); } }; session.open(new DisabledHostKeyCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final Transfer t = new UploadTransfer(new Host(new TestProtocol()), test, local); final BytecountStreamListener counter = new BytecountStreamListener(new DisabledStreamListener()); assertTrue(new SingleTransferWorker(session, session, t, new TransferOptions(), new TransferSpeedometer(t), new DisabledTransferPrompt() { @Override public TransferAction prompt(final TransferItem file) { return TransferAction.overwrite; } }, new DisabledTransferErrorCallback(), new DisabledProgressListener(), counter, new DisabledLoginCallback(), new DisabledPasswordCallback(), TransferItemCache.empty()) { }.run(session, session)); local.delete(); assertEquals(62768L, counter.getSent(), 0L); assertEquals(62768L, new DAVAttributesFinderFeature(session).find(test).getSize()); assertTrue(failed.get()); new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
From source file:com.github.thorbenlindhauer.math.MathUtil.java
public boolean isZeroMatrix() { final AtomicBoolean isZeroMatrix = new AtomicBoolean(true); // TODO: optimize to stop after first non-zero entry matrix.walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() { @Override/*ww w . j av a2 s . com*/ public void visit(int row, int column, double value) { if (value > DOUBLE_COMPARISON_OFFSET || value < -DOUBLE_COMPARISON_OFFSET) { isZeroMatrix.set(false); } } }); return isZeroMatrix.get(); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.BaselineFileDownloadOutput.java
/** * {@inheritDoc}//from www . j av a 2 s . c o m */ @Override public synchronized OutputStream getOutputStream() throws IOException { if (outputStream == null) { final String contentType = getActualContentType(); Check.notNull(contentType, "Cannot open output stream until actual content type is set"); //$NON-NLS-1$ String path = baselineFileNoSuffix.getAbsolutePath(); if (contentType.equals(DownloadContentTypes.APPLICATION_GZIP)) { path = path + BaselineFolder.getGzipExtension(); } else if (contentType.equals(DownloadContentTypes.APPLICATION_OCTET_STREAM)) { path = path + BaselineFolder.getRawExtension(); } else { throw new VersionControlException(MessageFormat.format( Messages.getString("VersionControlClient.UnsupportedContentTypeFormat"), //$NON-NLS-1$ contentType)); } final AtomicBoolean tempCreated = new AtomicBoolean(); final AtomicReference<String> pathReference = new AtomicReference<String>(path); outputStream = BaselineFolderCollection.createFile(pathReference, true, null /* ignored */, tempCreated); path = pathReference.get(); outputStreamFile = new File(path); tempFileCreatedInsteadOfBaseline = tempCreated.get(); } return outputStream; }
From source file:org.apache.nifi.processors.email.smtp.SmtpConsumer.java
@Override public void data(final InputStream data) throws RejectException, TooMuchDataException, IOException { final ProcessSession processSession = sessionFactory.createSession(); final StopWatch watch = new StopWatch(); watch.start();//www . j a v a 2 s . c o m try { FlowFile flowFile = processSession.create(); final AtomicBoolean limitExceeded = new AtomicBoolean(false); flowFile = processSession.write(flowFile, (OutputStream out) -> { final LimitingInputStream lis = new LimitingInputStream(data, maxMessageSize); IOUtils.copy(lis, out); if (lis.hasReachedLimit()) { limitExceeded.set(true); } }); if (limitExceeded.get()) { throw new TooMuchDataException( "Maximum message size limit reached - client must send smaller messages"); } flowFile = processSession.putAllAttributes(flowFile, extractMessageAttributes()); watch.stop(); processSession.getProvenanceReporter().receive(flowFile, "smtp://" + host + ":" + port + "/", watch.getDuration(TimeUnit.MILLISECONDS)); processSession.transfer(flowFile, ListenSMTP.REL_SUCCESS); processSession.commit(); } catch (FlowFileAccessException | IllegalStateException | RejectException | IOException ex) { log.error("Unable to fully process input due to " + ex.getMessage(), ex); throw ex; } finally { processSession.rollback(); //make sure this happens no matter what - is safe } }
From source file:fr.xebia.servlet.filter.SecuredRemoteAddressFilterTest.java
private void testRemoteAddr(String remoteAddr, boolean expected) throws ServletException, IOException { SecuredRemoteAddressFilter filter = new SecuredRemoteAddressFilter(); MockFilterConfig filterConfig = new MockFilterConfig(); filter.init(filterConfig);//w w w .jav a2 s. c o m final AtomicBoolean secured = new AtomicBoolean(); MockFilterChain filterChain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) { secured.set(request.isSecure()); } }; MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr(remoteAddr); filter.doFilter(request, new MockHttpServletResponse(), filterChain); assertEquals(expected, secured.get()); }
From source file:org.apache.bookkeeper.stream.storage.impl.sc.ZkStorageContainerManagerTest.java
@Test public void testStartContainerOnFailures() throws Exception { scManager.close();/*w w w . ja va 2 s .co m*/ long containerId = 11L; AtomicBoolean returnGoodContainer = new AtomicBoolean(false); CompletableFuture<StorageContainer> startFuture = new CompletableFuture<>(); StorageContainer goodSc = createStorageContainer(containerId, startFuture, FutureUtils.Void()); mockScFactory = (scId) -> { if (returnGoodContainer.get()) { return goodSc; } else { return createStorageContainer(scId, FutureUtils.exception(new Exception("Failed to start")), FutureUtils.Void()); } }; scRegistry = spy(new StorageContainerRegistryImpl(mockScFactory)); scManager = new ZkStorageContainerManager( myEndpoint, new StorageConfiguration(new CompositeConfiguration()) .setClusterControllerScheduleInterval(1, TimeUnit.SECONDS), clusterMetadataStore, scRegistry, NullStatsLogger.INSTANCE); // start the storage container manager scManager.start(); // update assignment map ClusterAssignmentData cad = ClusterAssignmentData.newBuilder() .putServers(NetUtils.endpointToString(myEndpoint), ServerAssignmentData.newBuilder().addContainers(containerId).build()) .build(); clusterMetadataStore.updateClusterAssignmentData(cad); // wait until container start is called and verify it is not started. verify(scRegistry, timeout(10000).atLeastOnce()).startStorageContainer(eq(containerId)); assertEquals(0, scManager.getLiveContainers().size()); // flip the flag to return a good container to simulate successful startup returnGoodContainer.set(true); FutureUtils.complete(startFuture, goodSc); // wait until container start is called again and the container is started MoreAsserts.assertUtil(ignored -> scManager.getLiveContainers().size() >= 1, () -> null); assertEquals(1, scManager.getLiveContainers().size()); assertTrue(scManager.getLiveContainers().containsKey(containerId)); }
From source file:com.spectralogic.ds3client.helpers.FileObjectGetter_Test.java
@Test public void testThatFileReportsAsRegularOnWindows() throws IOException, InterruptedException { Assume.assumeTrue(Platform.isWindows()); final String tempPathPrefix = null; final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix); final String A_FILE_NAME = "aFile.txt"; final AtomicBoolean caughtException = new AtomicBoolean(false); try {//from w w w. j av a2 s. c om Files.createFile(Paths.get(tempDirectory.toString(), A_FILE_NAME)); new FileObjectGetter(tempDirectory).buildChannel(A_FILE_NAME); } catch (final UnrecoverableIOException e) { assertTrue(e.getMessage().contains(A_FILE_NAME)); caughtException.set(true); } finally { FileUtils.deleteDirectory(tempDirectory.toFile()); } assertFalse(caughtException.get()); }
From source file:com.clxcommunications.xms.ApiConnectionTest.java
@Test public void leavesExternalHttpClientAlone() throws Exception { final AtomicBoolean clientClosed = new AtomicBoolean(); ApiConnection conn = ApiConnection.builder().token("token").servicePlanId("spid") .httpClient(new DummyClient() { @Override//from w ww .java2 s .co m public void close() throws IOException { clientClosed.set(true); } }).build(); conn.start(); conn.close(); assertThat(clientClosed.get(), is(false)); }