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:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java

public void createType(String namespace, String typeName, String typeSpec) throws IOException, SchemaException {
    Utilities.ensureNonNull("typeName", typeName);
    Utilities.ensureNonNull("typeSpec", typeSpec);
    final Lock lock = rwLock.writeLock();
    String type = null;//from   www .  j  av  a 2  s  . c o m
    try {
        lock.lock();
        checkStore();

        final SimpleFeatureType featureType = DataUtilities.createType(namespace, typeName, typeSpec);
        tileIndexStore.createSchema(featureType);
        type = featureType.getTypeName();
        if (typeName != null) {
            addTypeName(typeName, true);
        }
        extractBasicProperties(type);
    } finally {
        lock.unlock();
    }

}

From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java

public void createType(SimpleFeatureType featureType) throws IOException {
    Utilities.ensureNonNull("featureType", featureType);
    final Lock lock = rwLock.writeLock();
    String typeName = null;/*from  w  w w .  j a va  2  s.  c o m*/
    try {
        lock.lock();
        checkStore();

        tileIndexStore.createSchema(featureType);
        typeName = featureType.getTypeName();
        if (typeName != null) {
            addTypeName(typeName, true);
        }
        extractBasicProperties(typeName);
    } finally {
        lock.unlock();
    }

}

From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java

public void createType(String identification, String typeSpec) throws SchemaException, IOException {
    Utilities.ensureNonNull("typeSpec", typeSpec);
    Utilities.ensureNonNull("identification", identification);
    final Lock lock = rwLock.writeLock();
    String typeName = null;/*from  ww w.jav  a  2  s. c  o  m*/
    try {
        lock.lock();
        checkStore();
        final SimpleFeatureType featureType = DataUtilities.createType(identification, typeSpec);
        tileIndexStore.createSchema(featureType);
        typeName = featureType.getTypeName();
        if (typeName != null) {
            addTypeName(typeName, true);
        }
        extractBasicProperties(typeName);
    } finally {
        lock.unlock();
    }

}

From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java

@Override
public BoundingBox getBounds(final String typeName) {
    final Lock lock = rwLock.readLock();
    ReferencedEnvelope bound = null;/*from   w w  w . java2s. c om*/
    try {
        lock.lock();
        checkStore();
        if (bounds.containsKey(typeName)) {
            bound = bounds.get(typeName);
        } else {
            bound = this.tileIndexStore.getFeatureSource(typeName).getBounds();
            bounds.put(typeName, bound);
        }
    } catch (IOException e) {
        LOGGER.log(Level.FINER, e.getMessage(), e);
        bounds.remove(typeName);
    } finally {
        lock.unlock();
    }

    // return bounds;
    return bound;
}

From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java

@Override
public void getGranuleDescriptors(Query query, final GranuleCatalogVisitor visitor) throws IOException {
    Utilities.ensureNonNull("query", query);
    final Query q = mergeHints(query);
    String typeName = q.getTypeName();
    final Lock lock = rwLock.readLock();
    try {/*from  w  w  w  .j  a v  a2  s.c o  m*/
        lock.lock();
        checkStore();

        //
        // Load tiles informations, especially the bounds, which will be
        // reused
        //
        final SimpleFeatureSource featureSource = tileIndexStore.getFeatureSource(typeName);
        if (featureSource == null) {
            throw new NullPointerException(
                    "The provided SimpleFeatureSource is null, it's impossible to create an index!");
        }

        final SimpleFeatureCollection features = featureSource.getFeatures(q);
        if (features == null)
            throw new NullPointerException(
                    "The provided SimpleFeatureCollection is null, it's impossible to create an index!");

        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine("Index Loaded");

        // visiting the features from the underlying store
        final DefaultProgressListener listener = new DefaultProgressListener();
        features.accepts(new AbstractFeatureVisitor() {
            public void visit(Feature feature) {
                if (feature instanceof SimpleFeature) {
                    // get the feature
                    final SimpleFeature sf = (SimpleFeature) feature;
                    MultiLevelROI footprint = getGranuleFootprint(sf);
                    if (footprint == null || !footprint.isEmpty()) {
                        final GranuleDescriptor granule = new GranuleDescriptor(sf, suggestedRasterSPI,
                                pathType, locationAttribute, parentLocation, footprint, heterogeneous,
                                q.getHints());

                        visitor.visit(granule, null);
                    }

                    // check if something bad occurred
                    if (listener.isCanceled() || listener.hasExceptions()) {
                        if (listener.hasExceptions()) {
                            throw new RuntimeException(listener.getExceptions().peek());
                        } else {
                            throw new IllegalStateException(
                                    "Feature visitor for query " + q + " has been canceled");
                        }
                    }
                }
            }
        }, listener);

    } catch (Throwable e) {
        final IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    } finally {
        lock.unlock();

    }
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests a successful asynchronous request where the implementation of the 
 * {@link AsyncHandler#onSuccess(HttpResponse, Object)} callback throws an exception.</p> 
 *  //from   w ww. j  av a 2 s.  c om
 * @since 1.3.0
 */
@Test
public final void testAsyncSuccessCallbackError() throws InterruptedException {

    String subpath = "/successcallbackerror";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200)));

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncSuccessCallbackError(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String e) {

            try {

                throw new IllegalStateException();
            } finally {

                lock.lock();
                condition.signal();
                lock.unlock();
            }
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    successScenario(); //verify that the asynchronous request executor has survived the exception
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

public CacheEntry fetch(String key) {
    Lock lock = lockSource.getReadLock(key);
    lock.lock();
    try {//  w ww .j a  va 2s  . c o  m
        Connection connection = connect();
        if (connection == null)
            return null;

        try {
            String sql = "SELECT data, media_type, language, character_set, encoding, modification_date, tag, headers, expiration_date, document_modification_date FROM "
                    + cacheTableName + " WHERE key=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            try {
                statement.setString(1, key);
                ResultSet rs = statement.executeQuery();
                try {
                    if (rs.next()) {
                        byte[] data = rs.getBytes(1);
                        MediaType mediaType = MediaType.valueOf(rs.getString(2));
                        Language language = Language.valueOf(rs.getString(3));
                        CharacterSet characterSet = CharacterSet.valueOf(rs.getString(4));
                        Encoding encoding = Encoding.valueOf(rs.getString(5));
                        Timestamp modificationDate = rs.getTimestamp(6);
                        String tagValue = rs.getString(7);
                        Tag tag = tagValue != null ? Tag.parse(tagValue) : null;
                        String rawHeaders = rs.getString(8);
                        Series<Header> headers = (rawHeaders != null) && (rawHeaders.length() > 0)
                                ? deserializeHeaders(rawHeaders)
                                : null;
                        Timestamp expirationDate = rs.getTimestamp(9);
                        Timestamp documentModificationDate = rs.getTimestamp(10);

                        logger.fine("Fetched: " + key);

                        CacheEntry entry;
                        if (encoding != null)
                            entry = new CacheEntry(data, mediaType, language, characterSet, encoding, headers,
                                    modificationDate, tag, expirationDate, documentModificationDate);
                        else {
                            try {
                                entry = new CacheEntry(new String(data), mediaType, language, characterSet,
                                        null, headers, modificationDate, tag, expirationDate,
                                        documentModificationDate);
                            } catch (IOException x) {
                                throw new RuntimeException("Should never happen if data is not encoded!");
                            }
                        }

                        if (new java.util.Date().after(entry.getExpirationDate())) {
                            lock.unlock();
                            try {
                                logger.fine("Stale entry: " + key);
                                delete(connection, key);

                                // (Note that this also discarded our lock,
                                // but we kept it as a local variable)
                            } finally {
                                lock.lock();
                            }
                            return null;
                        }

                        return entry;
                    }
                } finally {
                    rs.close();
                }
            } finally {
                statement.close();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException x) {
        logger.log(Level.WARNING, "Could not fetch cache entry", x);
    } finally {
        lock.unlock();
    }

    logger.fine("Did not fetch: " + key);
    return null;
}

From source file:com.ibm.broker.analytics.r.RNode.java

/**
 * Parse and evaluate the specified script on the provided Rserve connection.
 * The script will be checked to see if has been updated before it is parsed and evaluated.
 * @param connection the established Rserve connection to use.
 * @param script the script to parse and evaluate.
 * @throws RNodeException if a problem occurs parsing or evaluating the specified script.
 * @throws MbException if a problem occurs during user trace processing.
 *//*from  w ww  .jav  a2  s. co  m*/
private void runScript(Connection connection, RNodeScript script) throws RNodeException, MbException {
    final String methodName = "runScript";
    RNodeLog.logUserTrace(this, methodName, 7826, "About to evaluate file using R runtime", getName(),
            script.getFileName());
    try {

        // Check to see if the script has been updated.
        script.update();

        // Check to see if we need to update the parsed script.
        // The file may have been updated since we last parsed it.
        String parsedScriptVariable = ".iib_r_parsed_script_" + script.getKey();
        Lock readLock = script.getReadLock();
        readLock.lock();
        try {
            if (connection.checkScriptVersion(script.getKey(), script.getVersion())) {

                // Assign the script contents to an R variable.
                String scriptVariable = ".iib_r_script_" + script.getKey();
                connection.assign(scriptVariable, script.getContent());

                // Parse the script contents on the Rserve server into an R language object.
                // We use try, as it also allows us to retrieve the error messages from the R runtime.
                REXP result = connection.parseAndEval(
                        "try(" + parsedScriptVariable + " <- parse(text=" + scriptVariable + "),silent=TRUE)");
                if (result.inherits("try-error")) {
                    throw new RNodeException(this, methodName, 7810, "R runtime failed to parse file contents",
                            getName(), script.getFileName(), result.asString());
                }

            }
        } finally {
            readLock.unlock();
        }

        // Evaluate the R script on the Rserve server.
        // We use try, as it also allows us to retrieve the error messages from the R runtime.
        REXP result = connection.parseAndEval("try(eval(" + parsedScriptVariable + "),silent=TRUE)");

        // Check to see if an error occurred - if so, throw an exception containing the error messages.
        if (result.inherits("try-error")) {
            throw new RNodeException(this, methodName, 7811, "R runtime failed to evaluate file contents",
                    getName(), script.getFileName(), result.asString());
        }
        RNodeLog.logUserTrace(this, methodName, 7827, "R runtime successfully evaluated file", getName(),
                script.getFileName());

    } catch (REngineException | REXPMismatchException e) {
        throw new RNodeException(this, methodName, 7811, "R runtime failed to evaluate file contents",
                getName(), script.getFileName(), e.getMessage());
    }
}

From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java

/**
 * Clears all caches for all locales./*from  w  w w. ja v  a  2  s .  c  o m*/
 */
protected void resetCache(IPentahoSession session) {
    final Lock writeLock = cacheLock.writeLock();
    try {
        writeLock.lock();
        final ICacheManager cacheMgr = PentahoSystem.getCacheManager(session);
        cacheMgr.clearRegionCache(CATALOG_CACHE_REGION);
    } finally {
        writeLock.unlock();
    }
}

From source file:org.soaplab.services.storage.FileStorage.java

/**************************************************************************
 *
 **************************************************************************/
public void removeJob(String jobId) throws SoaplabException {

    // precaution: it is related to how the JobManager creates job
    // IDs (it is here intentionally in the not-too-portable way)
    if (!jobId.startsWith("[")) {
        log.warn("Trying to remove strangely named job: " + jobId);
        return;//  w  w w  . j ava  2s. co m
    }

    File jobDir = getJobDir(jobId);
    Lock writeLock = getLock(jobId, false);
    writeLock.lock();
    try {
        FileUtils.deleteDirectory(jobDir);
    } catch (IOException e) {
        throw new SoaplabException(
                "Error while deleting the job directory " + "of job " + jobId + ": " + e.toString());
    } finally {
        writeLock.unlock();
    }
}