Example usage for org.eclipse.jgit.internal.storage.file LockFile unlock

List of usage examples for org.eclipse.jgit.internal.storage.file LockFile unlock

Introduction

In this page you can find the example usage for org.eclipse.jgit.internal.storage.file LockFile unlock.

Prototype

public void unlock() 

Source Link

Document

Unlock this file and abort this change.

Usage

From source file:com.collabnet.gerrit.SecureStoreJasypt.java

License:Apache License

private static void saveSecure(final FileBasedConfig sec) throws IOException {
    if (FileUtil.modified(sec)) {
        final byte[] out = Constants.encode(sec.toText());
        final File path = sec.getFile();
        final LockFile lf = new LockFile(path, FS.DETECTED);
        if (!lf.lock()) {
            throw new IOException("Cannot lock " + path);
        }//from   w ww. j av a  2s  .  c  o  m
        try {
            FileUtil.chmod(0600, new File(path.getParentFile(), path.getName() + ".lock"));
            lf.write(out);
            if (!lf.commit()) {
                throw new IOException("Cannot commit write to " + path);
            }
        } finally {
            lf.unlock();
        }
    }
}

From source file:com.google.gerrit.pgm.init.api.InitUtil.java

License:Apache License

public static void copy(Path dst, byte[] buf) throws FileNotFoundException, IOException {
    // If the file already has the content we want to put there,
    // don't attempt to overwrite the file.
    ///*from ww  w . jav  a2 s .  c om*/
    try (InputStream in = Files.newInputStream(dst)) {
        if (Arrays.equals(buf, ByteStreams.toByteArray(in))) {
            return;
        }
    } catch (NoSuchFileException notFound) {
        // Fall through and write the file.
    }

    Files.createDirectories(dst.getParent());
    LockFile lf = new LockFile(dst.toFile(), FS.DETECTED);
    if (!lf.lock()) {
        throw new IOException("Cannot lock " + dst);
    }
    try {
        try (InputStream in = new ByteArrayInputStream(buf); OutputStream out = lf.getOutputStream()) {
            ByteStreams.copy(in, out);
        }
        if (!lf.commit()) {
            throw new IOException("Cannot commit " + dst);
        }
    } finally {
        lf.unlock();
    }
}

From source file:com.google.gerrit.pgm.init.InitContainer.java

License:Apache License

@Override
public void run() throws FileNotFoundException, IOException {
    ui.header("Container Process");

    container.string("Run as", "user", username());
    container.string("Java runtime", "javaHome", javaHome());

    Path myWar;//from  w w w .j  a va 2s  .c om
    try {
        myWar = GerritLauncher.getDistributionArchive().toPath();
    } catch (FileNotFoundException e) {
        System.err.println("warn: Cannot find distribution archive (e.g. gerrit.war)");
        myWar = null;
    }

    String path = container.get("war");
    if (path != null) {
        path = container.string("Gerrit runtime", "war",
                myWar != null ? myWar.toAbsolutePath().toString() : null);
        if (path == null || path.isEmpty()) {
            throw die("container.war is required");
        }

    } else if (myWar != null) {
        final boolean copy;
        final Path siteWar = site.gerrit_war;
        if (Files.exists(siteWar)) {
            copy = ui.yesno(true, "Upgrade %s", siteWar);
        } else {
            copy = ui.yesno(true, "Copy %s to %s", myWar.getFileName(), siteWar);
            if (copy) {
                container.unset("war");
            } else {
                container.set("war", myWar.toAbsolutePath().toString());
            }
        }
        if (copy) {
            if (!ui.isBatch()) {
                System.err.format("Copying %s to %s", myWar.getFileName(), siteWar);
                System.err.println();
            }

            try (InputStream in = Files.newInputStream(myWar)) {
                Files.createDirectories(siteWar.getParent());

                LockFile lf = new LockFile(siteWar.toFile(), FS.DETECTED);
                if (!lf.lock()) {
                    throw new IOException("Cannot lock " + siteWar);
                }
                try {
                    try (OutputStream out = lf.getOutputStream()) {
                        ByteStreams.copy(in, out);
                    }
                    if (!lf.commit()) {
                        throw new IOException("Cannot commit " + siteWar);
                    }
                } finally {
                    lf.unlock();
                }
            }
        }
    }
}

From source file:com.google.gerrit.pgm.ProtoGen.java

License:Apache License

@Override
public int run() throws Exception {
    LockFile lock = new LockFile(file.getAbsoluteFile(), FS.DETECTED);
    if (!lock.lock()) {
        throw die("Cannot lock " + file);
    }//from   w  w w.  jav  a2  s.c  o m
    try {
        JavaSchemaModel jsm = new JavaSchemaModel(ReviewDb.class);
        try (OutputStream o = lock.getOutputStream();
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(o, "UTF-8")))) {
            String header;
            try (InputStream in = getClass().getResourceAsStream("ProtoGenHeader.txt")) {
                ByteBuffer buf = IO.readWholeStream(in, 1024);
                int ptr = buf.arrayOffset() + buf.position();
                int len = buf.remaining();
                header = new String(buf.array(), ptr, len, "UTF-8");
            }

            String version = com.google.gerrit.common.Version.getVersion();
            out.write(header.replace("@@VERSION@@", version));
            jsm.generateProto(out);
            out.flush();
        }
        if (!lock.commit()) {
            throw die("Could not write to " + file);
        }
    } finally {
        lock.unlock();
    }
    System.out.println("Created " + file.getPath());
    return 0;
}

From source file:com.googlesource.gerrit.plugins.lfs.locks.LfsProjectLocks.java

License:Apache License

LfsLock createLock(CurrentUser user, LfsCreateLockInput input) throws LfsException {
    log.atFine().log("Create lock for %s in project %s", input.path, project);
    String lockId = toLockId.apply(input.path);
    LfsLock lock = locks.getIfPresent(lockId);
    if (lock != null) {
        throw new LfsLockExistsException(lock);
    }/* w w  w.  java 2  s  .c o m*/

    lock = new LfsLock(lockId, input.path, LfsDateTime.now(), new LfsLockOwner(user.getUserName().get()));
    LockFile fileLock = new LockFile(locksPath.resolve(lockId).toFile());
    try {
        if (!fileLock.lock()) {
            log.atWarning().log("Cannot lock path [%s] in project %s", input.path, project);
            throw new LfsLockExistsException(lock);
        }
    } catch (IOException e) {
        String error = String.format("Locking path [%s] in project %s failed with error %s", input.path,
                project, e.getMessage());
        log.atWarning().log(error);
        throw new LfsException(error);
    }

    try {
        try (OutputStreamWriter out = new OutputStreamWriter(fileLock.getOutputStream())) {
            gson.toJson(lock, out);
        } catch (IOException e) {
            String error = String.format("Locking path [%s] in project %s failed during write with error %s",
                    input.path, project, e.getMessage());
            log.atWarning().log(error);
            throw new LfsException(error);
        }
        if (!fileLock.commit()) {
            String error = String.format("Committing lock to path [%s] in project %s failed", input.path,
                    project);
            log.atWarning().log(error);
            throw new LfsException(error);
        }
        // put lock object to cache while file lock is being hold so that
        // there is no chance that other process performs lock operation
        // in the meantime (either cache returns with existing object or
        // LockFile.lock fails on locking attempt)
        locks.put(lockId, lock);
    } finally {
        fileLock.unlock();
    }

    return lock;
}

From source file:com.googlesource.gerrit.plugins.lfs.locks.LfsProjectLocks.java

License:Apache License

void deleteLock(LfsLock lock) throws LfsException {
    LockFile fileLock = new LockFile(locksPath.resolve(lock.id).toFile());
    try {// www . j a v a2  s . co m
        if (!fileLock.lock()) {
            String error = String.format("Deleting lock on path [%s] in project %s is not possible", lock.path,
                    project);
            log.atWarning().log(error);
            throw new LfsException(error);
        }
    } catch (IOException e) {
        String error = String.format("Getting lock on path [%s] in project %s failed with error %s", lock.path,
                project, e.getMessage());
        log.atWarning().log(error);
        throw new LfsException(error);
    }

    try {
        Files.deleteIfExists(locksPath.resolve(lock.id));
        locks.invalidate(lock.id);
    } catch (IOException e) {
        String error = String.format("Deleting lock on path [%s] in project %s failed with error %s", lock.path,
                project, e.getMessage());
        log.atWarning().log(error);
        throw new LfsException(error);
    } finally {
        fileLock.unlock();
    }
}

From source file:com.googlesource.gerrit.plugins.secureconfig.SecureConfigStore.java

License:Apache License

private void saveSecure(final FileBasedConfig sec) throws IOException {
    if (FileUtil.modified(sec)) {
        final byte[] out = Constants.encode(sec.toText());
        final File path = sec.getFile();
        final LockFile lf = new LockFile(path);
        if (!lf.lock()) {
            throw new IOException("Cannot lock " + path);
        }/* w ww . j  a  v  a  2  s  .co m*/
        try {
            FileUtil.chmod(0600, new File(path.getParentFile(), path.getName() + ".lock"));
            lf.write(out);
            if (!lf.commit()) {
                throw new IOException("Cannot commit write to " + path);
            }
        } finally {
            lf.unlock();
        }
    }
}

From source file:com.microsoft.gittf.core.tasks.FetchTask.java

License:Open Source License

private boolean writeFetchHead(final ObjectId commitID, final int changesetID) throws IOException {
    Ref fetchHeadRef = repository.getRef(Constants.FETCH_HEAD);
    boolean referencesEqual = fetchHeadRef == null ? false : fetchHeadRef.getObjectId().equals(commitID);

    if (referencesEqual) {
        return false;
    }/*  w w  w . ja  v  a2s  .c o  m*/

    final File refFile = new File(repository.getDirectory(), Constants.FETCH_HEAD);
    final LockFile lockFile = new LockFile(refFile, repository.getFS());

    if (lockFile.lock()) {
        try {
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(lockFile.getOutputStream(), Charset.forName("UTF-8"))); //$NON-NLS-1$

            try {
                writer.append(MessageFormat.format("{0}\t\t{1}", commitID.getName(), //$NON-NLS-1$
                        Messages.formatString("FetchTask.RefLogFormat", //$NON-NLS-1$
                                Integer.toString(changesetID))));
            } finally {
                writer.close();
            }

            lockFile.commit();
        } finally {
            lockFile.unlock();
        }
    }

    return true;
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.FetchCommandImpl.java

License:Apache License

private void unlockRef(Repository db, Ref ref) throws IOException, InterruptedException {
    File refFile = new File(db.getDirectory(), ref.getName());
    File refLockFile = new File(db.getDirectory(), ref.getName() + ".lock");
    LockFile lock = new LockFile(refFile, FS.DETECTED);
    try {//  w  w w .j a va  2  s  .  c  o m
        if (!lock.lock()) {
            LOG.warn("Cannot lock the ref " + ref.getName() + ", will wait and try again");
            Thread.sleep(5000);
            if (lock.lock()) {
                LOG.warn("Successfully lock the ref " + ref.getName());
            } else {
                if (FileUtil.delete(refLockFile)) {
                    LOG.warn("Remove ref lock " + refLockFile.getAbsolutePath());
                } else {
                    LOG.warn("Cannot remove ref lock " + refLockFile.getAbsolutePath()
                            + ", fetch will probably fail. Please remove lock manually.");
                }
            }
        }
    } finally {
        lock.unlock();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.GitVcsSupportTest.java

License:Apache License

public void collecting_changes_should_not_block_IDE_requests() throws Exception {
    String classpath = myConfigBuilder.build().getFetchClasspath() + File.pathSeparator
            + ClasspathUtil.composeClasspath(new Class[] { MockFetcher.class }, null, null);
    myConfigBuilder.setSeparateProcessForFetch(true).setFetchClasspath(classpath)
            .setFetcherClassName(MockFetcher.class.getName());

    final GitVcsSupport support = getSupport();

    final VcsRootImpl root = (VcsRootImpl) getRoot("master");
    final File customRootDir = new File(myTmpDir, "custom-dir");
    root.addProperty(Constants.PATH, customRootDir.getAbsolutePath());
    final String repositoryUrl = root.getProperty(Constants.FETCH_URL);

    final AtomicInteger succeedIDERequestCount = new AtomicInteger(0);
    final AtomicBoolean fetchBlocksIDERequests = new AtomicBoolean(false);
    final List<Exception> errors = Collections.synchronizedList(new ArrayList<Exception>());

    Runnable longFetch = new Runnable() {
        public void run() {
            try {
                support.collectChanges(root, VERSION_TEST_HEAD, MERGE_VERSION, new CheckoutRules(""));
                fetchBlocksIDERequests.set(succeedIDERequestCount.get() == 0);
            } catch (VcsException e) {
                errors.add(e);//from w ww  .ja va 2s.  c  o  m
            }
        }
    };

    Runnable requestsFromIDE = new Runnable() {
        public void run() {
            while (!new File(customRootDir, "mock.lock").exists()) {//wait for fetch to begin (MockFetcher holds a lock during fetch)
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            LockFile lock = new LockFile(new File(customRootDir.getAbsolutePath(), "mock"), FS.DETECTED);
            try {
                while (true) {//do mapFullPath while fetch is executed (we cannot acquire a lock while it is executed)
                    if (!lock.lock()) {
                        support.mapFullPath(new VcsRootEntry(root, new CheckoutRules("")),
                                GitUtils.versionRevision(VERSION_TEST_HEAD) + "|" + repositoryUrl
                                        + "|readme.txt");
                        succeedIDERequestCount.incrementAndGet();
                    } else {
                        lock.unlock();
                        break;
                    }
                }
            } catch (Exception e) {
                errors.add(e);
            }
        }
    };

    Thread fetch = new Thread(longFetch);
    Thread ideRequests = new Thread(requestsFromIDE);
    fetch.start();
    ideRequests.start();
    fetch.join();
    ideRequests.join();
    if (!errors.isEmpty()) {
        fail("Errors in readers thread", errors.get(0));
    }

    assertFalse(fetchBlocksIDERequests.get());
}