Example usage for org.apache.lucene.store Lock close

List of usage examples for org.apache.lucene.store Lock close

Introduction

In this page you can find the example usage for org.apache.lucene.store Lock close.

Prototype

public abstract void close() throws IOException;

Source Link

Document

Releases exclusive access.

Usage

From source file:com.github.lucene.store.database.DatabaseDirectoryITest.java

License:Apache License

@Test
public void obtainLock_whenLockFileNotFound_shouldReturnLock() throws IOException {
    final Lock lock = directory.obtainLock(IndexWriter.WRITE_LOCK_NAME);
    Assert.assertNotNull(lock);//  w ww  . j a v a2 s.  c  o m
    Assert.assertTrue(lock instanceof DatabaseReadWriteLockFactory.DatabaseReadWriteLock);
    lock.close();
}

From source file:com.github.lucene.store.database.DatabaseDirectoryITest.java

License:Apache License

@Test(expected = LockObtainFailedException.class)
public void obtainLock_whenLockFileFound_shouldThrowLockObtainFailedException() throws IOException {
    final Lock lock = directory.obtainLock(IndexWriter.WRITE_LOCK_NAME);
    try {/*  w  ww .j  a va 2s  .  c om*/
        directory.obtainLock(IndexWriter.WRITE_LOCK_NAME);
    } finally {
        lock.close();
    }
}

From source file:com.github.lucene.store.database.DatabaseDirectoryITest.java

License:Apache License

@Test
public void obtainLock_whenLockFileFoundButIsClosed_shouldReturnNewLock() throws IOException {
    final Lock lock1 = directory.obtainLock(IndexWriter.WRITE_LOCK_NAME);
    Assert.assertNotNull(lock1);/*ww w .ja v a2 s.  com*/
    lock1.close();

    final Lock lock2 = directory.obtainLock(IndexWriter.WRITE_LOCK_NAME);
    Assert.assertNotNull(lock2);
    lock2.close();
}

From source file:com.github.lucene.store.jdbc.JdbcDirectoryLockITest.java

License:Apache License

@Test
public void testLocks() throws Exception {
    try {/*from  w w w. java 2  s .  co  m*/
        final Connection con1 = DataSourceUtils.getConnection(dataSource);
        final Lock lock1 = dir1.obtainLock(IndexWriter.WRITE_LOCK_NAME);
        lock1.ensureValid();

        try {
            dir2.obtainLock(IndexWriter.WRITE_LOCK_NAME);
            Assert.fail("lock2 should not have valid lock");
        } catch (final IOException e) {
        }

        lock1.close();

        DataSourceUtils.commitConnectionIfPossible(con1);
        DataSourceUtils.releaseConnection(con1);

        final Connection con2 = DataSourceUtils.getConnection(dataSource);
        final Lock lock2 = dir2.obtainLock(IndexWriter.WRITE_LOCK_NAME);
        lock2.ensureValid();
        lock2.close();

        DataSourceUtils.commitConnectionIfPossible(con2);
        DataSourceUtils.releaseConnection(con2);

    } finally {
        dir1.delete();
    }
}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductImages.java

License:Open Source License

@Override
public void run(final Product product) {
    if (ImageIO.getUseCache())
        ImageIO.setUseCache(false);

    DrbNode node = null;/*from  w w w . j ava 2 s  . c o m*/
    URL url = product.getPath();

    // Prepare the DRb node to be processed
    try {
        // First : force loading the model before accessing items.
        @SuppressWarnings("unused")
        DrbCortexModel model = DrbCortexModel.getDefaultModel();
        node = ProcessingUtils.getNodeFromPath(url.getPath());

        if (node == null) {
            throw new IOException("Cannot Instantiate Drb with URI \"" + url.toExternalForm() + "\".");
        }

    } catch (Exception e) {
        logger.error("Exception raised while processing Quicklook", e);
        return;
    }

    if (!ImageFactory.isImage(node)) {
        logger.debug("No Image.");
        return;
    }

    RenderedImageList input_list = null;
    RenderedImage input_image = null;
    try {
        input_list = ImageFactory.createImage(node);
        input_image = RenderingFactory.createDefaultRendering(input_list);
    } catch (Exception e) {
        logger.debug("Cannot retrieve default rendering");
        if (logger.isDebugEnabled()) {
            logger.debug("Error occurs during rendered image reader", e);
        }

        if (input_list == null)
            return;
        input_image = input_list;
    }

    int quicklook_width = cfgManager.getProductConfiguration().getQuicklookConfiguration().getWidth();
    int quicklook_height = cfgManager.getProductConfiguration().getQuicklookConfiguration().getHeight();
    boolean quicklook_cutting = cfgManager.getProductConfiguration().getQuicklookConfiguration().isCutting();

    logger.info("Generating Quicklook " + quicklook_width + "x" + quicklook_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight());

    RenderedImage image = ProcessingUtils.ResizeImage(input_image, quicklook_width, quicklook_height, 10f,
            quicklook_cutting);

    String product_id = product.getIdentifier();
    if (product_id == null)
        product_id = "unknown";

    // Manages the quicklook output
    File image_directory = incomingManager.getNewIncomingPath();

    LockFactory lf = new NativeFSLockFactory(image_directory);
    Lock lock = lf.makeLock(".lock-writing");
    try {
        lock.obtain(900000);
    } catch (Exception e) {
        logger.warn("Cannot lock incoming directory - continuing without (" + e.getMessage() + ")");
    }
    File file = new File(image_directory, product_id + "-ql.jpg");
    try {
        ImageIO.write(image, "jpg", file);
        product.setQuicklookPath(file.getPath());
        product.setQuicklookSize(file.length());
    } catch (IOException e) {
        logger.error("Cannot save quicklook.", e);
    }

    // Thumbnail
    int thumbnail_width = cfgManager.getProductConfiguration().getThumbnailConfiguration().getWidth();
    int thumbnail_height = cfgManager.getProductConfiguration().getThumbnailConfiguration().getHeight();
    boolean thumbnail_cutting = cfgManager.getProductConfiguration().getThumbnailConfiguration().isCutting();

    logger.info("Generating Thumbnail " + thumbnail_width + "x" + thumbnail_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight() + " image.");

    image = ProcessingUtils.ResizeImage(input_image, thumbnail_width, thumbnail_height, 10f, thumbnail_cutting);

    // Manages the quicklook output
    file = new File(image_directory, product_id + "-th.jpg");
    try {
        ImageIO.write(image, "jpg", file);
        product.setThumbnailPath(file.getPath());
        product.setThumbnailSize(file.length());
    } catch (IOException e) {
        logger.error("Cannot save thumbnail.", e);
    }
    SdiImageFactory.close(input_list);
    try {
        lock.close();
    } catch (IOException e) {
    }
}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductPrepareDownload.java

License:Open Source License

@Override
public void run(Product product) {
    String product_id = product.getIdentifier();
    Map<String, String> checksums = null;
    String[] algorithms = cfgManager.getDownloadConfiguration().getChecksumAlgorithms().split(",");

    if (product_id == null)
        throw new NullPointerException("Product \"" + product.getPath() + "\" identifier not initialized.");

    String product_path = product.getPath().getPath();
    if (UnZip.supported(product_path)) {
        product.setDownloadablePath(product_path);
        product.setDownloadableSize(new File(product_path).length());
    }/*from   w ww  .j a v  a 2  s . co m*/

    File zip_file = null;

    String zip_file_string = product.getDownloadablePath();
    if ((zip_file_string == null) || (!(new File(zip_file_string).exists()))) {
        File incoming = incomingManager.getNewIncomingPath();
        LockFactory lf = new NativeFSLockFactory(incoming);
        Lock lock = lf.makeLock(".lock-writing");
        try {
            lock.obtain(900000);
        } catch (Exception e) {
            logger.warn("Cannot lock incoming directory - " + "continuing without (" + e.getMessage() + ")");
        }

        zip_file = new File(incoming, (product_id + ".zip"));

        logger.info(zip_file.getName() + ": Generating zip file and its checksum.");

        zip_file_string = zip_file.getPath();

        try {
            long start = System.currentTimeMillis();
            logger.info("Creation of downloadable archive into " + zip_file_string);
            checksums = processZip(product.getPath().getPath(), zip_file);
            long delay_ms = System.currentTimeMillis() - start;
            long size_read = new File(product.getPath().getPath()).length() / (1024 * 1024);
            long size_write = zip_file.length() / (1024 * 1024);

            String message = " in " + delay_ms + "ms. Read " + size_read + "MB, Write " + size_write + "MB at "
                    + (size_write / ((float) (delay_ms + 1) / 1000)) + "MB/s";
            logger.info("Downloadable archive saved (" + product.getPath().getFile() + ")" + message);
        } catch (IOException e) {
            logger.error("Cannot generate Zip archive for product \"" + product.getPath() + "\".", e);
        } finally {
            try {
                lock.close();
            } catch (IOException e) {
            }
        }

        product.setDownloadablePath(zip_file_string);
        product.setDownloadableSize(zip_file.length());
    } else {
        try {
            if ((checksums = findLocalChecksum(zip_file_string)) == null) {
                long start = System.currentTimeMillis();

                logger.info(new File(zip_file_string).getName() + ": Computing checksum only.");

                checksums = ProcessProductPrepareDownload.processChecksum(zip_file_string, algorithms);

                /* Compute the output message */
                long delay_ms = System.currentTimeMillis() - start;
                long size = new File(zip_file_string).length() / (1024 * 1024);

                String message = " in " + delay_ms + "ms. Read " + size + "MB at "
                        + (size / ((float) (delay_ms + 1) / 1000)) + "MB/s";

                logger.info("Checksum processed " + message);
            } else {
                logger.info(new File(zip_file_string).getName() + ": Checksum retrieved from transfert.");
            }
        } catch (Exception ioe) {
            logger.warn("cannot compute checksum.", ioe);
        }
    }

    if (checksums != null) {
        product.getDownload().getChecksums().clear();
        product.getDownload().getChecksums().putAll(checksums);
    }
}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductTransfer.java

License:Open Source License

@Override
public void run(Product product) {
    String url = product.getOrigin();
    if (url == null) {
        return;//from   ww w .  j  a  v a  2 s .  c  om
    }
    if (!product.getPath().toString().equals(url)) {
        return;
    }
    File dest = incomingManager.getNewProductIncomingPath();
    Boolean compute_checksum = null;
    try {
        compute_checksum = UnZip.supported((new URL(url)).getPath());
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    LockFactory lf = new NativeFSLockFactory(dest.getParentFile());
    Lock lock = lf.makeLock(".lock-writing");
    try {
        lock.obtain(900000);
    } catch (Exception e) {
        logger.warn("Cannot lock incoming directory - continuing without (" + e.getMessage() + ")");
    }
    try {
        User owner = productDao.getOwnerOfProduct(product);
        actionRecordWritterDao.uploadStart(dest.getPath(), owner.getUsername());
        URL u = new URL(url);
        String userInfos = u.getUserInfo();
        String username = null;
        String password = null;
        if (userInfos != null) {
            String[] infos = userInfos.split(":");
            username = infos[0];
            password = infos[1];
        }

        // Hooks to remove the partially transfered product
        Hook hook = new Hook(dest.getParentFile());
        Runtime.getRuntime().addShutdownHook(hook);
        upload(url, username, password, dest, compute_checksum);
        Runtime.getRuntime().removeShutdownHook(hook);

        String local_filename = ScannerFactory.getFileFromPath(url);
        File productFile = new File(dest, local_filename);
        product.setPath(productFile.toURI().toURL());
        productDao.update(product);
    } catch (Exception e) {
        FileUtils.deleteQuietly(dest);
        throw new DataStoreException("Cannot transfer product \"" + url + "\".", e);
    } finally {
        try {
            lock.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.apache.maven.index.context.DefaultIndexingContext.java

License:Apache License

private static void unlockForcibly(final TrackingLockFactory lockFactory, final Directory dir)
        throws IOException {
    //Warning: Not doable in lucene >= 5.3 consider to remove it as IndexWriter.unlock
    //was always strongly non recommended by Lucene.
    //For now try to do the best to simulate the IndexWriter.unlock at least on FSDirectory
    //using FSLockFactory, the RAMDirectory uses SingleInstanceLockFactory.
    //custom lock factory?
    if (lockFactory != null) {
        final Set<? extends Lock> emittedLocks = lockFactory.getEmittedLocks(IndexWriter.WRITE_LOCK_NAME);
        for (Lock emittedLock : emittedLocks) {
            emittedLock.close();
        }/*www  .  j a v  a  2 s . co m*/
    }
    if (dir instanceof FSDirectory) {
        final FSDirectory fsdir = (FSDirectory) dir;
        final Path dirPath = fsdir.getDirectory();
        if (Files.isDirectory(dirPath)) {
            Path lockPath = dirPath.resolve(IndexWriter.WRITE_LOCK_NAME);
            try {
                lockPath = lockPath.toRealPath();
            } catch (IOException ioe) {
                // Not locked
                return;
            }
            try (final FileChannel fc = FileChannel.open(lockPath, StandardOpenOption.CREATE,
                    StandardOpenOption.WRITE)) {
                final FileLock lck = fc.tryLock();
                if (lck == null) {
                    // Still active
                    throw new LockObtainFailedException("Lock held by another process: " + lockPath);
                } else {
                    // Not held fine to release
                    lck.close();
                }
            }
            Files.delete(lockPath);
        }
    }
}

From source file:org.apache.maven.index.context.TrackingLockFactoryTest.java

License:Apache License

@Test
public void testLockUnlock() throws IOException {
    final TrackingLockFactory lf = new TrackingLockFactory(new SingleInstanceLockFactory());
    final RAMDirectory ram = new RAMDirectory(lf);
    final Lock foo = ram.obtainLock("foo");
    final Lock bar = ram.obtainLock("bar");
    bar.close();
    foo.close();/* w w w. ja  v  a2s  .  co m*/
    ram.close();
}

From source file:org.apache.maven.index.context.TrackingLockFactoryTest.java

License:Apache License

@Test
public void testLockLocked() throws IOException {
    final TrackingLockFactory lf = new TrackingLockFactory(new SingleInstanceLockFactory());
    final RAMDirectory ram = new RAMDirectory(lf);
    final Lock foo = ram.obtainLock("foo");
    boolean thrownLOFE = false;
    try {//from w w w.  j ava2  s  .  com
        ram.obtainLock("foo");
    } catch (LockObtainFailedException e) {
        thrownLOFE = true;
    }
    assertTrue(thrownLOFE);
    foo.close();
    final Lock foo2 = ram.obtainLock("foo");
    foo2.close();
    ram.close();
}