Example usage for java.util.concurrent.locks Lock lock

List of usage examples for java.util.concurrent.locks Lock lock

Introduction

In this page you can find the example usage for java.util.concurrent.locks Lock lock.

Prototype

lock

Source Link

Usage

From source file:com.alibaba.shared.django.DjangoClient.java

public String accessToken() {
    Lock rl = lock.readLock();
    rl.lock(); // Waiting for refresh!
    try {/*from  www . j a v a  2s  .c  om*/
        if (accessToken != null) {
            return accessToken;
        }
    } finally {
        rl.unlock();
    }
    if (accessToken == null) {
        try {
            refreshToken();
        } catch (URISyntaxException e) {
            LOGGER.error("refreshTokenError", e);
        } catch (IOException e) {
            LOGGER.error("refreshTokenError", e);
        }
    }
    return accessToken;
}

From source file:net.gbmb.collector.RecordController.java

private Collection registerCollection(Application application, String cid, String mode)
        throws CollectionStateException {
    boolean isTest = TEST_KEY.equals(mode);
    Lock lock = hazelcast.getLock(cid);
    lock.lock();
    try {//from   w w  w  .  j  av  a  2  s.  c o m
        if (collectionRepository.findByCollectionId(cid) != null) {
            // collection already existing
            throw new CollectionStateException(String.format("Collection already existing: %s", cid));
        }
        Collection collection = new Collection(cid);
        collection.setCreationDate(new Date());
        collection.setState(CollectionState.COLLECTING);
        collection.setCancelable(application.getCancelableCollection());
        collection.setTestMode(isTest);
        if (collectionMap.putIfAbsent(cid, collection) == null) {
            // no previous record
            return collection;
        } else {
            // already existing
            throw new CollectionStateException("Already existising: " + cid);
        }
    } finally {
        lock.unlock();
    }
}

From source file:com.alibaba.shared.django.DjangoClient.java

protected void refreshToken() throws URISyntaxException, IOException {
    Lock wl = lock.writeLock();
    wl.lock();
    try {//from   w ww  .  jav a2 s . c  o  m
        final String timestamp = String.valueOf(new Date().getTime());
        DjangoMessage msg = executeRequest(new Supplier<HttpUriRequest>() {
            public HttpUriRequest get() {
                Map<String, String> params = Maps.newHashMap();
                params.put("appKey", appKey);
                params.put("timestamp", timestamp);
                params.put("signature", buildSignature(timestamp));
                return new HttpGet(buildURI(tokenUrl, params, false));
            }
        }, false);
        if (msg != null && msg.isSuccess()) {
            accessToken = msg.getString(ACCESS_TOKEN_KEY);
            LOGGER.info("Received accessToken {}", accessToken);
        }
    } finally {
        wl.unlock();
    }
}

From source file:org.apache.rave.opensocial.service.impl.DefaultAppDataService.java

/**
 * Deletes data for the specified user and group.
 *
 * @param userId  The user/*from w  ww  . j  ava  2  s  .  c om*/
 * @param groupId The group
 * @param appId   The application ID
 * @param fields  The fields to delete - empty set implies all fields
 * @param token   The security token
 * @return an error if one occurs
 */
@Override
public Future<Void> deletePersonData(UserId userId, GroupId groupId, String appId, Set<String> fields,
        SecurityToken token) throws ProtocolException {
    //make sure the request conforms to the OpenSocial visibility rules
    String personId = validateWriteRequest(userId, groupId, appId, token);

    //lock on this user and this application to avoid any potential concurrency issues
    Lock lock = getApplicationDataLock(personId, appId);
    try {
        lock.lock();

        //get the application data for this user and application
        ApplicationData applicationData = applicationDataRepository.getApplicationData(personId, appId);

        //if there is no data, there's nothing to delete, so we're done...
        if (applicationData == null || applicationData.getData() == null) {
            return Futures.immediateFuture(null);
        }

        //remove the fields specified -- empty field set implies remove all, otherwise remove just the fields specified
        Map<String, Object> data = applicationData.getData();
        if (fields == null || fields.size() == 0) {
            data.clear();
        } else {
            data.keySet().removeAll(fields);
        }

        //save our changes and return
        applicationDataRepository.save(applicationData);
    } finally {
        lock.unlock();
        lockService.returnLock(lock);
    }
    return Futures.immediateFuture(null);
}

From source file:org.mule.service.oauth.internal.AbstractOAuthDancer.java

/**
 * Updates the resource owner oauth context information
 *
 * @param resourceOwnerOAuthContext//  w  ww  .  j a va 2s .  c  om
 */
protected void updateResourceOwnerOAuthContext(DefaultResourceOwnerOAuthContext resourceOwnerOAuthContext) {
    final Lock resourceOwnerContextLock = resourceOwnerOAuthContext.getRefreshUserOAuthContextLock();
    resourceOwnerContextLock.lock();
    try {
        tokensStore.put(resourceOwnerIdTransformer.apply(resourceOwnerOAuthContext.getResourceOwnerId()),
                resourceOwnerOAuthContext);
    } finally {
        resourceOwnerContextLock.unlock();
    }
}

From source file:org.eclipse.gyrex.monitoring.metrics.BaseMetric.java

/**
 * Returns a map of attribute values contained in the metric.
 * <p>//from   w  w w.ja  va 2s. c o m
 * Although public this method must not be called by clients. The framework
 * uses this method to obtain further information about a metric for
 * processing purposes.
 * </p>
 * 
 * @return an unmodifiable map of metric attribute values
 * @noreference This method is not intended to be referenced by clients.
 */
public final Map<String, ?> getAttributeValues() {
    final Map<String, Object> attributeValues = new HashMap<String, Object>();
    final Lock lock = getReadLock();
    lock.lock();
    try {
        populateAttributeValues(attributeValues);
    } finally {
        lock.unlock();
    }
    return Collections.unmodifiableMap(attributeValues);
}

From source file:org.mule.service.oauth.internal.AbstractOAuthDancer.java

/**
 * Retrieves the oauth context for a particular user. If there's no state for that user a new state is retrieve so never returns
 * null.//from   ww  w .j  ava 2 s .c  o  m
 *
 * @param resourceOwnerId id of the user.
 * @return oauth state
 */
public ResourceOwnerOAuthContext getContextForResourceOwner(String resourceOwnerId) {
    if (resourceOwnerId == null) {
        resourceOwnerId = DEFAULT_RESOURCE_OWNER_ID;
    }

    final String transformedResourceOwnerId = resourceOwnerIdTransformer.apply(resourceOwnerId);

    DefaultResourceOwnerOAuthContext resourceOwnerOAuthContext = null;
    if (!tokensStore.containsKey(transformedResourceOwnerId)) {
        final Lock lock = lockProvider.createLock(toString() + "-config-oauth-context");
        lock.lock();
        try {
            if (!tokensStore.containsKey(transformedResourceOwnerId)) {
                resourceOwnerOAuthContext = new DefaultResourceOwnerOAuthContext(
                        createLockForResourceOwner(transformedResourceOwnerId), resourceOwnerId);
                tokensStore.put(transformedResourceOwnerId, resourceOwnerOAuthContext);
            }
        } finally {
            lock.unlock();
        }
    }
    if (resourceOwnerOAuthContext == null) {
        resourceOwnerOAuthContext = tokensStore.get(transformedResourceOwnerId);
        resourceOwnerOAuthContext
                .setRefreshUserOAuthContextLock(createLockForResourceOwner(transformedResourceOwnerId));
    }
    return resourceOwnerOAuthContext;
}

From source file:org.eclipse.gyrex.monitoring.metrics.BaseMetric.java

/**
 * Resets the metric statistics but not the metric values.
 *///from  ww w  .java  2s.  co  m
public final void resetStats() {
    final Lock writeLock = getWriteLock();
    writeLock.lock();
    try {
        statsSince = System.currentTimeMillis();
        doResetStats();
    } finally {
        writeLock.unlock();
    }
}

From source file:com.mg.framework.service.DatabaseAuditServiceImpl.java

public void stop() {
    Lock lock = entityAuditSetupLock.writeLock();
    lock.lock();
    try {//from  w  ww.j av a2 s  .  co  m
        entityAuditSetup.clear();
    } finally {
        lock.unlock();
    }
}

From source file:org.mule.security.oauth.BaseOAuthClientFactory.java

/**
 * Passivates the object by updating the state of the persisted object with the
 * one of the given one. If the object doesn't exist in the object store then it
 * is created//w  w  w  .j a  v  a  2s .  co m
 * 
 * @param key the key of the object at the object store
 * @param connector an instance of {@link org.mule.security.oauth.OAuth2Adapter}
 * @throws IllegalArgumentException if obj is not an instance of the type returned by {@link BaseOAuthClientFactory#getAdapterClass()}
 */
@Override
public final void passivateObject(String key, OAuth2Adapter connector) throws Exception {
    if (!this.getAdapterClass().isInstance(connector)) {
        throw new IllegalArgumentException("Invalid connector type");
    }

    OAuthState state;

    Lock lock = this.getLock(key);
    lock.lock();

    try {
        if (this.objectStore.contains(key)) {
            state = this.retrieveOAuthState(key, false);
            this.objectStore.remove(key);
        } else {
            state = new OAuthState();
        }

        state.setAccessToken(connector.getAccessToken());
        state.setAccessTokenUrl(connector.getAccessTokenUrl());
        state.setAuthorizationUrl(connector.getAuthorizationUrl());
        state.setRefreshToken(connector.getRefreshToken());

        this.setCustomStateProperties(connector, state);

        this.objectStore.store(key, state);
    } finally {
        lock.unlock();
    }
}