Example usage for java.util.concurrent.atomic AtomicReference AtomicReference

List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference

Introduction

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

Prototype

public AtomicReference() 

Source Link

Document

Creates a new AtomicReference with null initial value.

Usage

From source file:com.jayway.restassured.module.mockmvc.ContentTypeTest.java

@Test
public void doesnt_add_default_charset_to_content_type_if_configured_not_to_do_so() {
    final AtomicReference<String> contentType = new AtomicReference<String>();

    given().config(RestAssuredMockMvcConfig.config()
            .encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)))
            .standaloneSetup(new GreetingController()).contentType(ContentType.JSON)
            .interceptor(new MockHttpServletRequestBuilderInterceptor() {
                public void intercept(MockHttpServletRequestBuilder requestBuilder) {
                    MultiValueMap<String, Object> headers = Whitebox.getInternalState(requestBuilder,
                            "headers");
                    contentType.set(String.valueOf(headers.getFirst("Content-Type")));
                }/*  ww  w.  j a va2 s  .co  m*/
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

    assertThat(contentType.get()).isEqualTo("application/json");
}

From source file:com.amazon.carbonado.spi.BelatedRepositoryCreator.java

@Override
protected Repository createReal() throws SupportException {
    // For first attempt, use the real root reference. For retries, it
    // should not be used because it will destroy the root which was
    // successfully built and is in use. Instead, pass a dummy ref.
    AtomicReference<Repository> rootRef = mRetry ? new AtomicReference<Repository>() : mRootRef;
    mRetry = true;//from   www .jav a 2s  .c  o m

    Exception error;
    try {
        return mBuilder.build(rootRef);
    } catch (SupportException e) {
        // Cannot recover from this.
        throw e;
    } catch (RepositoryException e) {
        Throwable cause = e.getCause();
        if (cause instanceof ClassNotFoundException) {
            // If a class cannot be loaded, then I don't expect this to be
            // a recoverable situation.
            throw new SupportException(cause);
        }
        error = e;
    } catch (Exception e) {
        error = e;
    }
    mLog.error("Error building Repository \"" + mBuilder.getName() + '"', error);
    return null;
}

From source file:com.joyent.manta.client.MantaSeekableByteChannel.java

/**
 * Creates a new instance of a read-only seekable byte channel.
 *
 * @param path path of the object on the Manta API
 * @param position starting position in bytes from the start of the file
 * @param connectionFactory connection factory instance used for building requests to Manta
 * @param httpHelper helper class providing useful HTTP functions
 *//* w  w w  .j  av a 2  s  . c o m*/
@Deprecated
public MantaSeekableByteChannel(final String path, final long position,
        final MantaConnectionFactory connectionFactory, final HttpHelper httpHelper) {
    this.path = path;
    this.position = new AtomicLong(position);
    this.httpHelper = httpHelper;
    this.requestRef = new AtomicReference<>();
    this.responseStream = new AtomicReference<>();
}

From source file:eu.eubrazilcc.lvl.storage.security.shiro.LinkedInRealm.java

@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
        throws AuthenticationException {
    // validate token
    if (token == null) {
        throw new CredentialsException("Uninitialized token");
    }/*ww w .  j av  a2s  . c o  m*/
    if (!(token instanceof AccessTokenToken)) {
        throw new UnsupportedTokenException("Unsuported token type: " + token.getClass().getCanonicalName());
    }
    // get access token
    final AccessTokenToken accessToken = (AccessTokenToken) token;
    final String secret = trimToNull(accessToken.getToken());
    if (isEmpty(secret)) {
        throw new AccountException("Empty tokens are not allowed in this realm");
    }
    // find token in the LVL OAuth2 database
    String ownerid = null;
    final AtomicReference<String> ownerIdRef = new AtomicReference<String>();
    if (TOKEN_DAO.isValid(secret, ownerIdRef)) {
        ownerid = ownerIdRef.get();
    }
    if (isEmpty(ownerid)) {
        throw new IncorrectCredentialsException("Incorrect credentials found");
    }
    // find resource owner in the LVL IdP database      
    final ResourceOwner owner = RESOURCE_OWNER_DAO.useGravatar(false).find(ownerid);
    if (owner == null || owner.getUser() == null) {
        throw new UnknownAccountException("No account found for user [" + ownerid + "]");
    }
    return new SimpleAuthenticationInfo(ownerid, secret, getName());
}

From source file:com.twitter.sdk.android.core.internal.scribe.ScribeFilesSender.java

public ScribeFilesSender(Context context, ScribeConfig scribeConfig, long ownerId, TwitterAuthConfig authConfig,
        List<SessionManager<? extends Session>> sessionManagers, SSLSocketFactory sslSocketFactory,
        ExecutorService executorService, IdManager idManager) {
    this.context = context;
    this.scribeConfig = scribeConfig;
    this.ownerId = ownerId;
    this.authConfig = authConfig;
    this.sessionManagers = sessionManagers;
    this.sslSocketFactory = sslSocketFactory;
    this.executorService = executorService;
    this.idManager = idManager;
    this.apiAdapter = new AtomicReference<>();
}

From source file:com.palantir.leader.proxy.AwaitingLeadershipProxy.java

private AwaitingLeadershipProxy(Supplier<?> delegateSupplier, LeaderElectionService leaderElectionService,
        Class<?> interfaceClass) {
    Validate.notNull(delegateSupplier);/*  ww  w .  j a  va  2  s .com*/
    this.delegateSupplier = delegateSupplier;
    this.leaderElectionService = leaderElectionService;
    this.executor = PTExecutors.newSingleThreadExecutor(PTExecutors.newNamedThreadFactory(true));
    this.leadershipTokenRef = new AtomicReference<LeadershipToken>();
    this.delegateRef = new AtomicReference<Object>();
    this.interfaceClass = interfaceClass;
    this.isClosed = false;
}

From source file:com.github.anba.test262.environment.Environments.java

/**
 * Creates a new Rhino environment/*from w w  w  . j a v  a 2 s .  c om*/
 */
public static <T extends GlobalObject> EnvironmentProvider<T> rhino(final Configuration configuration) {
    final int version = configuration.getInt("rhino.version", Context.VERSION_DEFAULT);
    final String compiler = configuration.getString("rhino.compiler.default");
    List<?> enabledFeatures = configuration.getList("rhino.features.enabled", emptyList());
    List<?> disabledFeatures = configuration.getList("rhino.features.disabled", emptyList());
    final Set<Integer> enabled = intoCollection(filterMap(enabledFeatures, notEmptyString, toInteger),
            new HashSet<Integer>());
    final Set<Integer> disabled = intoCollection(filterMap(disabledFeatures, notEmptyString, toInteger),
            new HashSet<Integer>());

    /**
     * Initializes the global {@link ContextFactory} according to the
     * supplied configuration
     * 
     * @see ContextFactory#initGlobal(ContextFactory)
     */
    final ContextFactory factory = new ContextFactory() {
        @Override
        protected boolean hasFeature(Context cx, int featureIndex) {
            if (enabled.contains(featureIndex)) {
                return true;
            } else if (disabled.contains(featureIndex)) {
                return false;
            }
            return super.hasFeature(cx, featureIndex);
        }

        @Override
        protected Context makeContext() {
            Context context = super.makeContext();
            context.setLanguageVersion(version);
            return context;
        }
    };

    EnvironmentProvider<RhinoGlobalObject> provider = new EnvironmentProvider<RhinoGlobalObject>() {
        @Override
        public RhinoEnv<RhinoGlobalObject> environment(final String testsuite, final String sourceName,
                final Test262Info info) {
            Configuration c = configuration.subset(testsuite);
            final boolean strictSupported = c.getBoolean("strict", false);
            final String encoding = c.getString("encoding", "UTF-8");
            final String libpath = c.getString("lib_path");

            final Context cx = factory.enterContext();
            final AtomicReference<RhinoGlobalObject> $global = new AtomicReference<>();

            final RhinoEnv<RhinoGlobalObject> environment = new RhinoEnv<RhinoGlobalObject>() {
                @Override
                public RhinoGlobalObject global() {
                    return $global.get();
                }

                @Override
                protected String getEvaluator() {
                    return compiler;
                }

                @Override
                protected String getCharsetName() {
                    return encoding;
                }

                @Override
                public void exit() {
                    Context.exit();
                }
            };

            @SuppressWarnings({ "serial" })
            final RhinoGlobalObject global = new RhinoGlobalObject() {
                {
                    cx.initStandardObjects(this, false);
                }

                @Override
                protected boolean isStrictSupported() {
                    return strictSupported;
                }

                @Override
                protected String getDescription() {
                    return info.getDescription();
                }

                @Override
                protected void failure(String message) {
                    failWith(message, sourceName);
                }

                @Override
                protected void include(Path path) throws IOException {
                    // resolve the input file against the library path
                    Path file = Paths.get(libpath).resolve(path);
                    InputStream source = Files.newInputStream(file);
                    environment.eval(file.getFileName().toString(), source);
                }
            };

            $global.set(global);

            return environment;
        }
    };

    @SuppressWarnings("unchecked")
    EnvironmentProvider<T> p = (EnvironmentProvider<T>) provider;

    return p;
}

From source file:guru.qas.martini.DefaultMixologist.java

@Autowired
protected DefaultMixologist(GherkinResourceLoader loader, Mixology mixology, Categories categories,
        @Value("${unimplemented.steps.fatal:#{false}}") boolean missingStepFatal) {
    this.loader = loader;
    this.mixology = mixology;
    this.categories = categories;
    this.unimplementedStepsFatal = missingStepFatal;
    this.martinisReference = new AtomicReference<>();
}

From source file:org.openmrs.module.drughistory.api.DrugEventServiceTest.java

/**
 * @verifies throw exception when sinceWhen is in the future
 * @see DrugEventService#generateDrugEventsFromTrigger(org.openmrs.module.drughistory.DrugEventTrigger, java.util.Date)
 */// w ww  .  ja v a  2s. c  o m
@Test
@ExpectedException(IllegalArgumentException.class)
public void generateDrugEventsFromTrigger_shouldThrowExceptionWhenSinceWhenIsInTheFuture() throws Exception {
    GregorianCalendar gc = new GregorianCalendar();
    gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
    AtomicReference<Date> sinceWhen = new AtomicReference<Date>();
    sinceWhen.set(gc.getTime());
    DrugEventTrigger trigger = new DrugEventTrigger();
    drugEventService.generateDrugEventsFromTrigger(trigger, sinceWhen.get());
}

From source file:com.nokia.dempsy.mpcluster.zookeeper.ZookeeperSession.java

protected ZookeeperSession(String connectString, int sessionTimeout) throws IOException {
    this.connectString = connectString;
    this.sessionTimeout = sessionTimeout;
    this.zkref = new AtomicReference<ZooKeeper>();
    ZooKeeper newZk = makeZookeeperInstance(connectString, sessionTimeout);
    if (newZk != null)
        setNewZookeeper(newZk);/* w  w w.  j  a v  a  2 s . c o m*/
}