Example usage for java.util.concurrent.atomic AtomicBoolean get

List of usage examples for java.util.concurrent.atomic AtomicBoolean get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean get.

Prototype

public final boolean get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.couchbase.client.dcp.state.SessionState.java

/**
 * Check if the current sequence numbers for all partitions are equal to the ones set as end.
 *
 * @return true if all are at the end, false otherwise.
 *///from   www. jav a  2s  . c  om
public boolean isAtEnd() {
    final AtomicBoolean atEnd = new AtomicBoolean(true);
    foreachPartition(new Action1<PartitionState>() {
        @Override
        public void call(PartitionState ps) {
            if (!ps.isAtEnd()) {
                atEnd.set(false);
            }
        }
    });
    return atEnd.get();
}

From source file:org.apache.camel.component.bean.BeanProcessor.java

public boolean process(Exchange exchange, AsyncCallback callback) {
    // do we have an explicit method name we always should invoke
    boolean isExplicitMethod = ObjectHelper.isNotEmpty(method);

    Object bean;/*  w ww .ja  v  a  2 s .  co  m*/
    BeanInfo beanInfo;
    try {
        bean = beanHolder.getBean();
        beanInfo = beanHolder.getBeanInfo();
    } catch (Throwable e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }

    // do we have a custom adapter for this POJO to a Processor
    // should not be invoked if an explicit method has been set
    Processor processor = getProcessor();
    if (!isExplicitMethod && processor != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using a custom adapter as bean invocation: " + processor);
        }
        try {
            processor.process(exchange);
        } catch (Throwable e) {
            exchange.setException(e);
        }
        callback.done(true);
        return true;
    }

    Message in = exchange.getIn();

    // Now it gets a bit complicated as ProxyHelper can proxy beans which we later
    // intend to invoke (for example to proxy and invoke using spring remoting).
    // and therefore the message body contains a BeanInvocation object.
    // However this can causes problem if we in a Camel route invokes another bean,
    // so we must test whether BeanHolder and BeanInvocation is the same bean or not
    BeanInvocation beanInvoke = in.getBody(BeanInvocation.class);
    if (beanInvoke != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Exchange IN body is a BeanInvocation instance: " + beanInvoke);
        }
        Class<?> clazz = beanInvoke.getMethod().getDeclaringClass();
        boolean sameBean = clazz.isInstance(bean);
        if (LOG.isTraceEnabled()) {
            LOG.debug("BeanHolder bean: " + bean.getClass() + " and beanInvocation bean: " + clazz
                    + " is same instance: " + sameBean);
        }
        if (sameBean) {
            beanInvoke.invoke(bean, exchange);
            // propagate headers
            exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
            callback.done(true);
            return true;
        }
    }

    // set temporary header which is a hint for the bean info that introspect the bean
    if (in.getHeader(Exchange.BEAN_MULTI_PARAMETER_ARRAY) == null) {
        in.setHeader(Exchange.BEAN_MULTI_PARAMETER_ARRAY, isMultiParameterArray());
    }

    String prevMethod = null;
    MethodInvocation invocation;
    if (methodObject != null) {
        invocation = beanInfo.createInvocation(methodObject, bean, exchange);
    } else {
        // we just override the bean's invocation method name here
        if (isExplicitMethod) {
            prevMethod = in.getHeader(Exchange.BEAN_METHOD_NAME, String.class);
            in.setHeader(Exchange.BEAN_METHOD_NAME, method);
        }
        try {
            invocation = beanInfo.createInvocation(bean, exchange);
        } catch (Throwable e) {
            exchange.setException(e);
            callback.done(true);
            return true;
        }
    }
    if (invocation == null) {
        throw new IllegalStateException(
                "No method invocation could be created, no matching method could be found on: " + bean);
    }

    // remove temporary header
    in.removeHeader(Exchange.BEAN_MULTI_PARAMETER_ARRAY);

    Object value = null;
    try {
        AtomicBoolean sync = new AtomicBoolean(true);
        value = invocation.proceed(callback, sync);
        if (!sync.get()) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: " + exchange.getExchangeId()
                        + " is continued being processed asynchronously");
            }
            // the remainder of the routing will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: " + exchange.getExchangeId()
                    + " is continued being processed synchronously");
        }
    } catch (InvocationTargetException e) {
        // lets unwrap the exception when its an invocation target exception
        exchange.setException(e.getCause());
        callback.done(true);
        return true;
    } catch (Throwable e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    } finally {
        if (isExplicitMethod) {
            in.setHeader(Exchange.BEAN_METHOD_NAME, prevMethod);
        }
    }

    // if the method returns something then set the value returned on the Exchange
    if (!invocation.getMethod().getReturnType().equals(Void.TYPE) && value != Void.TYPE) {
        if (exchange.getPattern().isOutCapable()) {
            // force out creating if not already created (as its lazy)
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting bean invocation result on the OUT message: " + value);
            }
            exchange.getOut().setBody(value);
            // propagate headers
            exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
        } else {
            // if not out then set it on the in
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting bean invocation result on the IN message: " + value);
            }
            exchange.getIn().setBody(value);
        }
    }

    callback.done(true);
    return true;
}

From source file:com.adaptris.core.lms.StreamWrapperCase.java

@Test
public void testOutputStream_Write() throws Exception {
    StreamWrapper wrapper = createWrapper(false);
    File file = TempFileUtils.createTrackedFile(wrapper);
    AtomicBoolean callback = new AtomicBoolean(false);
    OutputStream out = wrapper.openOutputStream(file, () -> {
        callback.set(true);/*from www.  j  ava2 s .  c  o  m*/
    });
    try (OutputStream closeable = out) {
        out.write(BYTES_TEXT[0]);
    }
    tryQuietly(() -> {
        out.close();
    });
    assertTrue(callback.get());
}

From source file:com.netflix.spinnaker.fiat.shared.FiatPermissionEvaluator.java

public UserPermission.View getPermission(String username) {
    UserPermission.View view = null;
    if (StringUtils.isEmpty(username)) {
        return null;
    }//from www .  j  av  a 2  s.c  o  m

    try {
        AtomicBoolean cacheHit = new AtomicBoolean(true);
        view = permissionsCache.get(username, () -> {
            cacheHit.set(false);
            return AuthenticatedRequest.propagate(() -> fiatService.getUserPermission(username)).call();
        });
        log.debug("Fiat permission cache hit: " + cacheHit.get());
    } catch (ExecutionException | UncheckedExecutionException ee) {
        String message = String.format("Cannot get whole user permission for user %s. Cause: %s", username,
                ee.getCause().getMessage());
        if (log.isDebugEnabled()) {
            log.debug(message, ee.getCause());
        } else {
            log.info(message);
        }
    }
    return view;
}

From source file:io.dyn.core.handler.AnnotationHandlerMethodResolver.java

@Override
public boolean supports(final Class<?> aClass) {
    boolean classLevelAnno = (null != AnnotationUtils.findAnnotation(aClass, Handler.class));
    final AtomicBoolean hasHandlerMethod = new AtomicBoolean(false);
    Class<?> clazz = aClass;
    while (null != clazz && clazz != Object.class) {
        ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
            @Override//from  w  w  w .  j  ava 2 s  . c  o m
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                if (!hasHandlerMethod.get()) {
                    hasHandlerMethod.set(true);
                }
            }
        }, Handlers.USER_METHODS);
        clazz = clazz.getSuperclass();
    }

    return (hasHandlerMethod.get() || classLevelAnno);
}

From source file:core.nipr.NiprClient.java

public void getNiprReports(Map<String, GregorianCalendar> aInDates,
        Map<String, LicenseInternal> aInOutLatestLicenses, Map<String, GregorianCalendar> aOutSuccessDates,
        StringBuilder aInOutErrors) {

    Map<String, LicenseInternal> lCurrentDayInfo = new HashMap<String, LicenseInternal>();

    for (GregorianCalendar lCal : aInDates.values()) {

        String lFormattedDate = CalenderUtils.getFormattedDate(lCal);
        System.out.println("NiprClient: Get data for " + lFormattedDate);

        AtomicBoolean lSpecificFailure = new AtomicBoolean(false);
        lCurrentDayInfo = getSpecificReport(lCal, lSpecificFailure, aInOutErrors);

        if (lSpecificFailure.get()) {
            System.out.println("Nipr Sync for date " + lFormattedDate + " failed");
            continue;
        }//from   w  w  w  . j a v  a2  s .c  om

        System.out.println("Nipr Sync for date " + lFormattedDate + " SUCCESS, generating CSV file");
        // Generate a CSV for it.
        generateAndSendCsvFile(lFormattedDate, lCurrentDayInfo);

        // Previous Day is higher
        mergeReports(lCurrentDayInfo, aInOutLatestLicenses);
        GregorianCalendar lCalCopy = (GregorianCalendar) lCal.clone();
        aOutSuccessDates.put(CalenderUtils.getFormattedDate(lCalCopy), lCalCopy);
    }
}

From source file:ir.rasen.charsoo.controller.image_loader.core.LoadAndDisplayImageTask.java

/** @return <b>true</b> - if task should be interrupted; <b>false</b> - otherwise */
private boolean waitIfPaused() {
    AtomicBoolean pause = engine.getPause();
    if (pause.get()) {
        synchronized (engine.getPauseLock()) {
            if (pause.get()) {
                L.d(LOG_WAITING_FOR_RESUME, memoryCacheKey);
                try {
                    engine.getPauseLock().wait();
                } catch (InterruptedException e) {
                    L.e(LOG_TASK_INTERRUPTED, memoryCacheKey);
                    return true;
                }//w w w  .  ja  v a 2s  .co  m
                L.d(LOG_RESUME_AFTER_PAUSE, memoryCacheKey);
            }
        }
    }
    return isTaskNotActual();
}

From source file:ch.cyberduck.core.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.j  ava  2s.  c o 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(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(), new DisabledTranscriptListener());
    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, t, new TransferOptions(), new TransferSpeedometer(t),
            new DisabledTransferPrompt() {
                @Override
                public TransferAction prompt(final TransferItem file) {
                    return TransferAction.overwrite;
                }
            }, new DisabledTransferErrorCallback(), new DisabledTransferItemCallback(),
            new DisabledProgressListener(), counter, new DisabledLoginCallback(), TransferItemCache.empty()) {

    }.run(session));
    local.delete();
    assertEquals(62768L, counter.getSent(), 0L);
    assertEquals(62768L, new DAVAttributesFeature(session).find(test).getSize());
    assertTrue(failed.get());
    new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:com.google.gdt.eclipse.designer.util.Utils.java

/**
 * @return <code>true</code> if given module inherits required, directly or indirectly.
 *///from   ww  w .j  av a2 s. c o m
public static boolean inheritsModule(ModuleDescription moduleDescription, final String requiredModule)
        throws Exception {
    final AtomicBoolean result = new AtomicBoolean();
    ModuleVisitor.accept(moduleDescription, new ModuleVisitor() {
        @Override
        public void endVisitModule(ModuleElement module) {
            if (requiredModule.equals(module.getId())) {
                result.set(true);
            }
        }
    });
    return result.get();
}

From source file:de.undercouch.gradle.tasks.download.InterceptorTest.java

/**
 * Tests if an interceptor can be used to manipulate a request before
 * it is sent/*from   w w  w  .j  a  v a 2 s  .  c o  m*/
 * @throws Exception if anything goes wrong
 */
@Test
public void interceptRequest() throws Exception {
    final AtomicBoolean interceptorCalled = new AtomicBoolean(false);

    Download t = makeProjectAndTask();
    t.src(makeSrc(INTERCEPTOR));
    File dst = folder.newFile();
    t.dest(dst);
    t.requestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            assertFalse(interceptorCalled.get());
            interceptorCalled.set(true);
            request.addHeader(ADDITIONAL_REQUEST_HEADER_KEY, ADDITIONAL_REQUEST_HEADER_VALUE);
        }
    });
    t.execute();

    assertTrue(interceptorCalled.get());

    String dstContents = FileUtils.readFileToString(dst);
    assertEquals(UNINTERCEPTED + ":" + ADDITIONAL_REQUEST_HEADER_VALUE, dstContents);
}