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:jp.aegif.nemaki.cmis.service.impl.PolicyServiceImpl.java

@Override
public void removePolicy(CallContext callContext, String repositoryId, String policyId, String objectId,
        ExtensionsData extension) {/* w w  w. ja v  a 2s. co m*/

    exceptionService.invalidArgumentRequiredString("objectId", objectId);
    exceptionService.invalidArgumentRequiredString("policyId", policyId);

    Lock objectLock = threadLockService.getWriteLock(repositoryId, objectId);
    Lock policyLock = threadLockService.getReadLock(repositoryId, policyId);
    try {
        objectLock.lock();
        policyLock.lock();

        // //////////////////
        // General Exception
        // //////////////////
        Content content = contentService.getContent(repositoryId, objectId);
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_REMOVE_POLICY_OBJECT,
                content);
        Policy policy = contentService.getPolicy(repositoryId, policyId);
        exceptionService.objectNotFound(DomainType.OBJECT, policy, policyId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_REMOVE_POLICY_POLICY,
                policy);

        // //////////////////
        // Body of the method
        // //////////////////
        contentService.removePolicy(callContext, repositoryId, policyId, objectId, extension);

        nemakiCachePool.get(repositoryId).removeCmisCache(objectId);

    } finally {
        objectLock.unlock();
        policyLock.unlock();
    }
}

From source file:org.pentaho.reporting.platform.plugin.cache.FileSystemCacheBackend.java

private List<Lock> lockForRead(List<String> key) {
    List<Lock> retval;
    if (!key.isEmpty()) {
        final List<String> parent = key.subList(0, key.size() - 1);
        retval = lockForRead(parent);// w ww.  jav a 2s  .c o m
    } else {
        retval = new ArrayList<>();
    }

    final Lock lock = getLock(key).readLock();
    lock.lock();
    retval.add(lock);
    return retval;
}

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

/**
 * Updates app data for the specified user and group with the new values.
 *
 * @param userId  The user// w w  w  .ja v a  2 s  .  co m
 * @param groupId The group
 * @param appId   The application ID
 * @param fields  The fields to update.  Empty set implies that all fields that should be persisted have been
 *                provided in the values map (completely replace current appData with new data).  A key in the
 *                fields set without a corresponding key in the values map implies a delete of that field.
 *                A key in the values map not present in the fields set is a bad request.
 * @param values  The values to set
 * @param token   The security token
 * @return an error if one occurs
 */
@Override
public Future<Void> updatePersonData(UserId userId, GroupId groupId, String appId, Set<String> fields,
        Map<String, Object> values, 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, create an empty object to store the data in that we'll save when we're done
        if (applicationData == null) {
            applicationData = new ApplicationDataImpl(null, personId, appId, new HashMap<String, Object>());
        }

        //if the fields parameter is empty, we can just use the values map directly since this is a full update
        if (fields == null || fields.size() == 0) {
            applicationData.setData(values);
        }
        //if there are keys in the values map that aren't in the fields set, its a bad request
        else if (!fields.containsAll(values.keySet())) {
            throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
                    "Fields parameter must either be empty or contain keys "
                            + "for all name value pairs sent in request.");
        }
        //we have a partial update - we know that the fields set contains keys for all the entries in the values
        //map (due to the check above), so we can just enumerate over it now to finish our work.  So we want to remove
        //any fields found in the fields set that are not found in the values map and update the rest.
        else {
            Map<String, Object> data = applicationData.getData();
            for (String field : fields) {
                //if this field is not in the values map, its a delete
                if (!values.containsKey(field)) {
                    data.remove(field);
                } else {
                    //its an update
                    data.put(field, values.get(field));
                }
            }
        }

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

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

@RequestMapping(value = "/records/{cid}/cancel", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public Collection cancelCollection(@PathVariable("cid") String cid) throws CollectionStateException {
    Lock lock = hazelcast.getLock(cid);
    try {//from   ww w  .j  a  v  a2s  . c  om
        lock.lock();
        Collection collection = collectionMap.get(cid);
        if (collection == null) {
            // collection not existing
            throw new ResourceNotFoundException(String.format("No collection with id '%s'", cid));
        }
        if (CollectionState.COLLECTING != collection.getState()) {
            // COLLECTING is the unique state that can be canceled
            throw new CollectionStateException(String.format("Cannot cancel collection '%s' in state '%s'",
                    collection.getId(), collection.getState().name()));
        }
        if (collection.isCancelable()) {
            // OK, can cancel
            collectionRecords.remove(cid);
            collectionMap.remove(cid);
            throw new NoContentException(String.format("Collection with id '%s' cancelled", cid));
        } else {
            // not cancelable so end the collection
            return markCollectionEnded(collection);
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.pentaho.reporting.platform.plugin.cache.FileSystemCacheBackend.java

/**
 * Acquires read locks for all sub-directories, and a final write lock for the current working directory. It acquires
 * the parent locks first, before trying to get more local locks.
 *
 * @param key/*from ww  w. j a  v a 2 s  .co m*/
 * @return
 */
private List<Lock> lockForWrite(final List<String> key) {
    final List<Lock> retval;
    if (CollectionUtils.isNotEmpty(key)) {
        final List<String> parent = key.subList(0, key.size() - 1);
        retval = lockForRead(parent);
    } else {
        retval = new ArrayList<>();
    }

    final Lock lock = getLock(key).writeLock();
    lock.lock();
    retval.add(lock);
    return retval;
}

From source file:jp.aegif.nemaki.cmis.service.impl.PolicyServiceImpl.java

@Override
public void applyPolicy(CallContext callContext, String repositoryId, String policyId, String objectId,
        ExtensionsData extension) {/*from   w w w. j av  a 2s.c o m*/
    exceptionService.invalidArgumentRequiredString("objectId", objectId);
    exceptionService.invalidArgumentRequiredString("policyId", policyId);

    Lock objectLock = threadLockService.getWriteLock(repositoryId, objectId);
    Lock policyLock = threadLockService.getReadLock(repositoryId, policyId);
    try {
        objectLock.lock();
        policyLock.lock();

        // //////////////////
        // General Exception
        // //////////////////
        Content content = contentService.getContent(repositoryId, objectId);
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_ADD_POLICY_OBJECT,
                content);
        Policy policy = contentService.getPolicy(repositoryId, policyId);
        exceptionService.objectNotFound(DomainType.OBJECT, policy, policyId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_ADD_POLICY_POLICY,
                policy);

        // //////////////////
        // Specific Exception
        // //////////////////
        TypeDefinition td = typeManager.getTypeDefinition(repositoryId, content);
        if (!td.isControllablePolicy())
            exceptionService.constraint(objectId,
                    "appyPolicy cannot be performed on the object whose controllablePolicy = false");

        // //////////////////
        // Body of the method
        // //////////////////
        contentService.applyPolicy(callContext, repositoryId, policyId, objectId, extension);

        nemakiCachePool.get(repositoryId).removeCmisCache(objectId);

    } finally {
        objectLock.unlock();
        policyLock.unlock();
    }
}

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

/**
 * Validates the object by checking that it exists at the object store and that
 * the state of the given object is consisten with the persisted state
 * /*from   ww w .  j  av a2 s . c o m*/
 * @param key the key of the object at the object store
 * @param obj 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 boolean validateObject(String key, OAuth2Adapter obj) {
    if (!this.getAdapterClass().isInstance(obj)) {
        throw new IllegalArgumentException("Invalid connector type");
    }

    OAuth2Adapter connector = (OAuth2Adapter) obj;

    Lock lock = this.getLock(key);
    lock.lock();
    try {
        if (!this.objectStore.contains(key)) {
            return false;
        }

        OAuthState state = this.retrieveOAuthState(key, true);

        if (connector.getAccessToken() == null) {
            return false;
        }

        if (!connector.getAccessToken().equals(state.getAccessToken())) {
            return false;
        }
        if (connector.getRefreshToken() == null && state.getRefreshToken() != null) {
            return false;
        }

        if (connector.getRefreshToken() != null
                && !connector.getRefreshToken().equals(state.getRefreshToken())) {
            return false;
        }
    } catch (ObjectStoreException e) {
        logger.warn("Could not validate object due to object store exception", e);
        return false;
    } finally {
        lock.unlock();
    }
    return true;
}

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

/**
 * This method creates an instance of// w  w w . java2  s .  c  o m
 * {@link org.mule.security.oauth.OAuth2Adapter} which concrete type depends on
 * the return of
 * {@link BaseOAuthClientFactory#getAdapterClass} The
 * adapter is fully initialized and interfaces such as
 * {@link Initialisable},
 * {@link MuleContextAware} and
 * {@link Startable} are respected by invoking the
 * corresponding methods in case the adapter implements them. Finally, the
 * {@link OAuth2Connector#postAuth()} method is invoked.
 * 
 * @param key the of the object at the object store
 */
@Override
public final OAuth2Adapter makeObject(String key) throws Exception {
    OAuthState state = null;
    Lock lock = this.getLock(key);
    lock.lock();

    try {
        if (!this.objectStore.contains(key)) {
            throw new NotAuthorizedException(String.format(
                    "There is no access token stored under the key %s . You need to call the <authorize> message processor. The key will be given to you via a flow variable after the OAuth dance is completed. You can extract it using flowVars['tokenId'].",
                    key));
        }

        state = this.retrieveOAuthState(key, true);
    } finally {
        lock.unlock();
    }

    OAuth2Adapter connector = this.getAdapterClass().getConstructor(OAuth2Manager.class)
            .newInstance(this.oauthManager);

    connector.setConsumerKey(oauthManager.getDefaultUnauthorizedConnector().getConsumerKey());
    connector.setConsumerSecret(oauthManager.getDefaultUnauthorizedConnector().getConsumerSecret());
    connector.setAccessToken(state.getAccessToken());
    connector.setAuthorizationUrl(state.getAuthorizationUrl());
    connector.setAccessTokenUrl(state.getAccessTokenUrl());
    connector.setRefreshToken(state.getRefreshToken());

    this.setCustomAdapterProperties(connector, state);

    if (connector instanceof MuleContextAware) {
        ((MuleContextAware) connector).setMuleContext(oauthManager.getMuleContext());
    }
    if (connector instanceof Initialisable) {
        ((Initialisable) connector).initialise();
    }
    if (connector instanceof Startable) {
        ((Startable) connector).start();
    }

    this.oauthManager.postAuth(connector, key);
    return connector;
}

From source file:org.apache.synapse.endpoints.algorithms.WeightedRoundRobin.java

public void changeWeight(int pos, int weight) {
    Lock writeLock = lock.writeLock();
    writeLock.lock();
    try {/*  ww w .  ja va2  s  .c o m*/
        EndpointState state = null;
        for (EndpointState s : endpointStates) {
            if (s.getEndpointPosition() == pos) {
                state = s;
            }
        }

        if (state == null) {
            throw new SynapseException("The specified endpoint position cannot be found");
        }

        state.weight = weight;

        calculate();

        reset(null);
    } finally {
        writeLock.unlock();
    }
}

From source file:org.ambraproject.wombat.service.AssetServiceImpl.java

/**
 * {@inheritDoc}//from   w  w w.  j av a2s. c o m
 */
@Override
public String getCompiledAssetLink(AssetType assetType, List<String> filenames, Site site) throws IOException {
    String sourceCacheKey = generateCacheKey(assetType, site, filenames);
    String compiledFilename = cache.get(sourceCacheKey);
    if (compiledFilename == null) {
        // Keep a lock on asset compilation. We do this because we've
        // had a problem when we bring up wombat, and all the requests
        // attempt to compile assets simultaneously, leading to high
        // load.
        Lock lock = lockStripes.get(sourceCacheKey);
        try {
            lock.lock();
            // Check again in case another thread built this while we were
            // waiting for the lock.
            compiledFilename = cache.get(sourceCacheKey);
            if (compiledFilename == null) {
                File concatenated = concatenateFiles(filenames, site, assetType.getExtension());
                CompiledAsset compiled = compileAsset(assetType, concatenated);
                concatenated.delete();
                compiledFilename = compiled.digest.getFile().getName();

                // We cache both the file name and the file contents (if it is small enough) in memcache.
                // In an ideal world, we would use the filename (including the hash of its contents) as
                // the only cache key.  However, it's potentially expensive to calculate that key since
                // you need the contents of the compiled file, which is why we do it this way.
                cache.put(sourceCacheKey, compiledFilename, CACHE_TTL);
                if (compiled.contents.length < MAX_ASSET_SIZE_TO_CACHE) {
                    String contentsCacheKey = compiled.digest.getCacheKey();
                    cache.put(contentsCacheKey, compiled.contents, CACHE_TTL);
                }
            }
        } finally {
            lock.unlock();
        }
    }
    return AssetUrls.COMPILED_PATH_PREFIX + compiledFilename;
}