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.eclipse.gyrex.context.internal.registry.ContextRegistryImpl.java

public boolean hasRealContext(IPath contextPath) throws IllegalArgumentException {
    checkClosed();/*w w w  .j  a va  2s.co m*/
    contextPath = sanitize(contextPath);

    final Lock readLock = contextRegistryLock.readLock();
    readLock.lock();
    try {
        return contexts.containsKey(contextPath);
    } finally {
        readLock.unlock();
    }

}

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

@Override
public ObjectInFolderList getChildren(CallContext callContext, String repositoryId, String folderId,
        String filter, String orderBy, Boolean includeAllowableActions,
        IncludeRelationships includeRelationships, String renditionFilter, Boolean includePathSegments,
        BigInteger maxItems, BigInteger skipCount, ExtensionsData extension,
        Holder<ObjectData> parentObjectData) {

    exceptionService.invalidArgumentRequiredString("folderId", folderId);

    Lock parentLock = threadLockService.getReadLock(repositoryId, folderId);

    try {//  w  w w . j  a  v  a 2s.c  o  m
        parentLock.lock();

        // //////////////////
        // General Exception
        // //////////////////
        Folder folder = contentService.getFolder(repositoryId, folderId);
        exceptionService.invalidArgumentFolderId(folder, folderId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_GET_CHILDREN_FOLDER,
                folder);

        // //////////////////
        // Body of the method
        // //////////////////
        // Set ObjectData of parent folder for ObjectInfo
        ObjectData _parent = compileService.compileObjectData(callContext, repositoryId, folder, filter,
                includeAllowableActions, includeRelationships, renditionFilter, false);
        parentObjectData.setValue(_parent);

        return getChildrenInternal(callContext, repositoryId, folderId, filter, orderBy,
                includeAllowableActions, includeRelationships, renditionFilter, includePathSegments, maxItems,
                skipCount, false);
    } finally {
        parentLock.unlock();
    }
}

From source file:org.onosproject.drivers.bmv2.Bmv2FlowRuleProgrammable.java

@Override
public Collection<FlowEntry> getFlowEntries() {

    if (!init()) {
        return Collections.emptyList();
    }//from  ww w.j  a  v a2 s .  co  m

    DeviceId deviceId = handler().data().deviceId();

    Bmv2DeviceAgent deviceAgent;
    try {
        deviceAgent = controller.getAgent(deviceId);
    } catch (Bmv2RuntimeException e) {
        log.error("Failed to get BMv2 device agent: {}", e.explain());
        return Collections.emptyList();
    }

    Bmv2DeviceContext context = contextService.getContext(deviceId);
    if (context == null) {
        log.warn("Unable to get device context for {}", deviceId);
    }

    Bmv2Interpreter interpreter = context.interpreter();
    Bmv2Configuration configuration = context.configuration();

    List<FlowEntry> entryList = Lists.newArrayList();

    for (Bmv2TableModel table : configuration.tables()) {
        // For each table in the configuration AND exposed by the interpreter.
        if (!interpreter.tableIdMap().inverse().containsKey(table.name())) {
            continue; // next table
        }

        List<Bmv2ParsedTableEntry> installedEntries;
        try {
            installedEntries = deviceAgent.getTableEntries(table.name());
        } catch (Bmv2RuntimeException e) {
            log.warn("Failed to get table entries of table {} of {}: {}", table.name(), deviceId, e.explain());
            continue; // next table
        }

        for (Bmv2ParsedTableEntry parsedEntry : installedEntries) {
            Bmv2TableEntryReference entryRef = new Bmv2TableEntryReference(deviceId, table.name(),
                    parsedEntry.matchKey());

            Lock lock = ENTRY_LOCKS.computeIfAbsent(entryRef, key -> new ReentrantLock());
            lock.lock();

            try {
                Bmv2FlowRuleWrapper frWrapper = tableEntryService.lookup(entryRef);

                if (frWrapper == null) {
                    log.debug(
                            "Missing reference from table entry service. Deleting it. BUG? "
                                    + "deviceId={}, tableName={}, matchKey={}",
                            deviceId, table.name(), entryRef.matchKey());
                    try {
                        doRemove(deviceAgent, table.name(), parsedEntry.entryId(), parsedEntry.matchKey());
                    } catch (Bmv2RuntimeException e) {
                        log.warn("Unable to remove inconsistent flow rule: {}", e.explain());
                    }
                    continue; // next entry
                }

                long remoteEntryId = parsedEntry.entryId();
                long localEntryId = frWrapper.entryId();

                if (remoteEntryId != localEntryId) {
                    log.debug(
                            "getFlowEntries(): inconsistent entry id! BUG? Updating it... remote={}, local={}",
                            remoteEntryId, localEntryId);
                    frWrapper = new Bmv2FlowRuleWrapper(frWrapper.rule(), remoteEntryId,
                            frWrapper.installedOnMillis());
                    tableEntryService.bind(entryRef, frWrapper);
                }

                long bytes = 0L;
                long packets = 0L;

                if (table.hasCounters()) {
                    // Read counter values from device.
                    try {
                        Pair<Long, Long> counterValue = deviceAgent.readTableEntryCounter(table.name(),
                                remoteEntryId);
                        bytes = counterValue.getLeft();
                        packets = counterValue.getRight();
                    } catch (Bmv2RuntimeException e) {
                        log.warn("Unable to get counters for entry {}/{} of device {}: {}", table.name(),
                                remoteEntryId, deviceId, e.explain());
                    }
                }

                FlowEntry entry = new DefaultFlowEntry(frWrapper.rule(), ADDED, frWrapper.lifeInSeconds(),
                        packets, bytes);
                entryList.add(entry);

            } finally {
                lock.unlock();
            }
        }
    }

    return Collections.unmodifiableCollection(entryList);
}

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

@Override
public ObjectData getFolderParent(CallContext callContext, String repositoryId, String folderId,
        String filter) {//from   ww  w  .  java  2  s  .c  o m

    exceptionService.invalidArgumentRequiredString("folderId", folderId);

    Lock childLock = threadLockService.getReadLock(repositoryId, folderId);

    try {
        childLock.lock();

        // //////////////////
        // General Exception
        // //////////////////
        Folder folder = (Folder) contentService.getContent(repositoryId, folderId);
        exceptionService.objectNotFound(DomainType.OBJECT, folder, folderId);
        exceptionService.permissionDenied(callContext, repositoryId,
                PermissionMapping.CAN_GET_FOLDER_PARENT_OBJECT, folder);

        // //////////////////
        // Specific Exception
        // //////////////////
        Folder parent = contentService.getParent(repositoryId, folderId);

        Lock parentLock = threadLockService.getReadLock(repositoryId, parent.getId());
        try {
            parentLock.lock();

            exceptionService.objectNotFoundParentFolder(repositoryId, folderId, parent);
            exceptionService.invalidArgumentRootFolder(repositoryId, folder);

            // //////////////////
            // Body of the method
            // //////////////////
            return compileService.compileObjectData(callContext, repositoryId, parent, filter, true,
                    IncludeRelationships.NONE, null, true);

        } finally {
            parentLock.unlock();
        }
    } finally {
        childLock.unlock();
    }
}

From source file:org.eclipse.gyrex.context.internal.registry.ContextRegistryImpl.java

public void close() throws Exception {
    // set closed
    closed.set(true);//w w  w .j  a  v  a 2 s.co m

    // remove preference listener
    getContextFlushNode().removePreferenceChangeListener(flushListener);

    // dispose active contexts
    GyrexContextImpl[] activeContexts;
    final Lock lock = contextRegistryLock.writeLock();
    lock.lock();
    try {
        activeContexts = contexts.values().toArray(new GyrexContextImpl[contexts.size()]);
        contexts.clear();
    } finally {
        lock.unlock();
    }

    // dispose all the active contexts
    for (final GyrexContextImpl context : activeContexts) {
        context.dispose();
    }

    // clear handles
    handles.clear();
}

From source file:org.openhab.binding.neeo.internal.handler.NeeoBrainHandler.java

/**
 * Initializes the bridge by connecting to the configuration ip address and parsing the results. Properties will be
 * set and the thing will go online./*from   w w w.  ja  va2s  .c  o m*/
 */
private void initializeTask() {
    final Lock writerLock = stateLock.writeLock();
    writerLock.lock();
    try {
        NeeoUtil.checkInterrupt();

        final NeeoBrainConfig config = getBrainConfig();
        final String ipAddress = config.getIpAddress();
        if (ipAddress == null || StringUtils.isEmpty(ipAddress)) {
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                    "Brain IP Address must be specified");
            return;
        }
        final NeeoBrainApi api = new NeeoBrainApi(ipAddress);
        final NeeoBrain brain = api.getBrain();
        final String brainId = getNeeoBrainId();

        NeeoUtil.checkInterrupt();
        neeoBrainApi = api;

        final Map<String, String> properties = new HashMap<>();
        addProperty(properties, "Name", brain.getName());
        addProperty(properties, "Version", brain.getVersion());
        addProperty(properties, "Label", brain.getLabel());
        addProperty(properties, "Is Configured", String.valueOf(brain.isConfigured()));
        addProperty(properties, "Key", brain.getKey());
        addProperty(properties, "AirKey", brain.getAirkey());
        addProperty(properties, "Last Change", String.valueOf(brain.getLastChange()));
        updateProperties(properties);

        if (config.isEnableForwardActions()) {
            NeeoUtil.checkInterrupt();

            forwardActionServlet = new NeeoForwardActionsServlet(scheduler,
                    new NeeoForwardActionsServlet.Callback() {
                        @Override
                        public void post(String json) {
                            triggerChannel(NeeoConstants.CHANNEL_BRAIN_FOWARDACTIONS, json);

                            final NeeoAction action = gson.fromJson(json, NeeoAction.class);

                            for (final Thing child : getThing().getThings()) {
                                final ThingHandler th = child.getHandler();
                                if (th instanceof NeeoRoomHandler) {
                                    ((NeeoRoomHandler) th).processAction(action);
                                }
                            }
                        }

                    }, config.getForwardChain());

            NeeoUtil.checkInterrupt();
            try {
                servletPath = NeeoConstants.WEBAPP_FORWARDACTIONS.replace("{brainid}", brainId);

                httpService.registerServlet(servletPath, forwardActionServlet, new Hashtable<>(),
                        httpService.createDefaultHttpContext());

                final URL callbackURL = createCallbackUrl(brainId, config);
                if (callbackURL == null) {
                    logger.debug(
                            "Unable to create a callback URL because there is no primary address specified (please set the primary address in the configuration)");
                } else {
                    final URL url = new URL(callbackURL, servletPath);
                    api.registerForwardActions(url);
                }
            } catch (NamespaceException | ServletException e) {
                logger.debug("Error registering forward actions to {}: {}", servletPath, e.getMessage(), e);
            }
        }

        NeeoUtil.checkInterrupt();
        updateStatus(ThingStatus.ONLINE);
        NeeoUtil.checkInterrupt();
        if (config.getCheckStatusInterval() > 0) {
            NeeoUtil.cancel(checkStatus.getAndSet(scheduler.scheduleWithFixedDelay(() -> {
                try {
                    NeeoUtil.checkInterrupt();
                    checkStatus(ipAddress);
                } catch (InterruptedException e) {
                    // do nothing - we were interrupted and should stop
                }
            }, config.getCheckStatusInterval(), config.getCheckStatusInterval(), TimeUnit.SECONDS)));
        }
    } catch (IOException e) {
        logger.debug("Exception occurred connecting to brain: {}", e.getMessage(), e);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                "Exception occurred connecting to brain: " + e.getMessage());
    } catch (InterruptedException e) {
        logger.debug("Initializtion was interrupted", e);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR,
                "Initialization was interrupted");
    } finally {
        writerLock.unlock();
    }
}

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

@Override
public List<ObjectInFolderContainer> getDescendants(CallContext callContext, String repositoryId,
        String folderId, BigInteger depth, String filter, Boolean includeAllowableActions,
        IncludeRelationships includeRelationships, String renditionFilter, Boolean includePathSegment,
        boolean foldersOnly, ExtensionsData extension, Holder<ObjectData> anscestorObjectData) {

    exceptionService.invalidArgumentRequiredString("folderId", folderId);

    Lock parentLock = threadLockService.getReadLock(repositoryId, folderId);

    try {/*w  w  w. j av a  2 s.c om*/
        parentLock.lock();

        // //////////////////
        // General Exception
        // //////////////////
        Folder folder = contentService.getFolder(repositoryId, folderId);
        exceptionService.permissionDenied(callContext, repositoryId,
                PermissionMapping.CAN_GET_DESCENDENTS_FOLDER, folder);

        // //////////////////
        // Specific Exception
        // //////////////////
        exceptionService.invalidArgumentFolderId(folder, folderId);
        exceptionService.invalidArgumentDepth(depth);

        // //////////////////
        // Body of the method
        // //////////////////
        // check depth
        int d = (depth == null ? 2 : depth.intValue());

        // set defaults if values not set
        boolean iaa = (includeAllowableActions == null ? false : includeAllowableActions.booleanValue());
        boolean ips = (includePathSegment == null ? false : includePathSegment.booleanValue());

        // Set ObjectData of the starting folder for ObjectInfo
        ObjectData _folder = compileService.compileObjectData(callContext, repositoryId, folder, filter,
                includeAllowableActions, includeRelationships, renditionFilter, false);
        anscestorObjectData.setValue(_folder);

        // get the tree.
        return getDescendantsInternal(callContext, repositoryId, _folder, filter, iaa, false,
                includeRelationships, null, ips, 0, d, foldersOnly);

    } finally {
        parentLock.unlock();
    }
}

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

@Override
public List<ObjectParentData> getObjectParents(CallContext callContext, String repositoryId, String objectId,
        String filter, Boolean includeAllowableActions, IncludeRelationships includeRelationships,
        String renditionFilter, Boolean includeRelativePathSegment, ExtensionsData extension) {

    exceptionService.invalidArgumentRequired("objectId", objectId);

    Lock childLock = threadLockService.getReadLock(repositoryId, objectId);

    try {/*from   w  ww  . j  a v  a 2  s.c  o m*/
        childLock.lock();

        // //////////////////
        // General Exception
        // //////////////////
        Content content = contentService.getContent(repositoryId, objectId);
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_GET_PARENTS_FOLDER,
                content);

        //Get parent
        Folder parent = contentService.getParent(repositoryId, objectId);
        Lock parentLock = threadLockService.getReadLock(repositoryId, parent.getId());

        try {
            parentLock.lock();

            // //////////////////
            // Specific Exception
            // //////////////////
            exceptionService.objectNotFoundParentFolder(repositoryId, objectId, parent);
            exceptionService.invalidArgumentRootFolder(repositoryId, content);

            // //////////////////
            // Body of the method
            // //////////////////
            ObjectParentDataImpl result = new ObjectParentDataImpl();
            ObjectData o = compileService.compileObjectData(callContext, repositoryId, parent, filter,
                    includeAllowableActions, includeRelationships, null, true);
            result.setObject(o);
            boolean irps = (includeRelativePathSegment == null ? false
                    : includeRelativePathSegment.booleanValue());
            if (irps) {
                result.setRelativePathSegment(content.getName());
            }

            return Collections.singletonList((ObjectParentData) result);

        } finally {
            parentLock.unlock();
        }

    } finally {
        childLock.unlock();
    }
}

From source file:org.eclipse.gyrex.context.internal.registry.ContextRegistryImpl.java

void doFlushHierarchy(final IPath contextPath) {
    // log debug message
    if (ContextDebug.debug) {
        LOG.debug("Flushing context hierarchy {}...", contextPath);
    }/*from ww w  .  j ava2s .c om*/

    // remove all entries within that path
    final List<GyrexContextImpl> removedContexts = new ArrayList<GyrexContextImpl>();
    final Lock lock = contextRegistryLock.writeLock();
    lock.lock();
    try {
        checkClosed();
        final Entry[] entrySet = contexts.entrySet().toArray(new Entry[0]);
        for (final Entry entry : entrySet) {
            final IPath entryPath = (IPath) entry.getKey();
            if (contextPath.isPrefixOf(entryPath)) {
                final GyrexContextImpl contextImpl = contexts.remove(entryPath);
                if (null != contextImpl) {
                    removedContexts.add(contextImpl);
                }
            }
        }
    } finally {
        lock.unlock();
    }

    // dispose all removed contexts (outside of lock)
    for (final GyrexContextImpl contextImpl : removedContexts) {
        if (ContextDebug.debug) {
            LOG.debug("Disposing context {}...", contextImpl);
        }
        contextImpl.dispose();
    }

    // log info message
    LOG.info("Flushed context hierarchy {}.", contextPath);
}

From source file:jenkins.plugins.git.AbstractGitSCMSource.java

@NonNull
@Override//from   w  w w.ja v  a 2s.  com
protected void retrieve(@NonNull final SCMHeadObserver observer, @NonNull TaskListener listener)
        throws IOException, InterruptedException {
    String cacheEntry = getCacheEntry();
    Lock cacheLock = getCacheLock(cacheEntry);
    cacheLock.lock();
    try {
        File cacheDir = getCacheDir(cacheEntry);
        Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir);
        GitClient client = git.getClient();
        client.addDefaultCredentials(getCredentials());
        if (!client.hasGitRepo()) {
            listener.getLogger().println("Creating git repository in " + cacheDir);
            client.init();
        }
        String remoteName = getRemoteName();
        listener.getLogger().println("Setting " + remoteName + " to " + getRemote());
        client.setRemoteUrl(remoteName, getRemote());
        listener.getLogger().println("Fetching " + remoteName + "...");
        List<RefSpec> refSpecs = getRefSpecs();
        client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()]));
        listener.getLogger().println("Pruning stale remotes...");
        final Repository repository = client.getRepository();
        try {
            client.prune(new RemoteConfig(repository.getConfig(), remoteName));
        } catch (UnsupportedOperationException e) {
            e.printStackTrace(listener.error("Could not prune stale remotes"));
        } catch (URISyntaxException e) {
            e.printStackTrace(listener.error("Could not prune stale remotes"));
        }
        listener.getLogger().println("Getting remote branches...");
        SCMSourceCriteria branchCriteria = getCriteria();
        RevWalk walk = new RevWalk(repository);
        try {
            walk.setRetainBody(false);
            for (Branch b : client.getRemoteBranches()) {
                if (!b.getName().startsWith(remoteName + "/")) {
                    continue;
                }
                final String branchName = StringUtils.removeStart(b.getName(), remoteName + "/");
                listener.getLogger().println("Checking branch " + branchName);
                if (isExcluded(branchName)) {
                    continue;
                }
                if (branchCriteria != null) {
                    RevCommit commit = walk.parseCommit(b.getSHA1());
                    final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime());
                    final RevTree tree = commit.getTree();
                    SCMSourceCriteria.Probe probe = new SCMSourceCriteria.Probe() {
                        @Override
                        public String name() {
                            return branchName;
                        }

                        @Override
                        public long lastModified() {
                            return lastModified;
                        }

                        @Override
                        public boolean exists(@NonNull String path) throws IOException {
                            TreeWalk tw = TreeWalk.forPath(repository, path, tree);
                            try {
                                return tw != null;
                            } finally {
                                if (tw != null) {
                                    tw.release();
                                }
                            }
                        }
                    };
                    if (branchCriteria.isHead(probe, listener)) {
                        listener.getLogger().println("Met criteria");
                    } else {
                        listener.getLogger().println("Does not meet criteria");
                        continue;
                    }
                }
                SCMHead head = new SCMHead(branchName);
                SCMRevision hash = new SCMRevisionImpl(head, b.getSHA1String());
                observer.observe(head, hash);
                if (!observer.isObserving()) {
                    return;
                }
            }
        } finally {
            walk.dispose();
        }

        listener.getLogger().println("Done.");
    } finally {
        cacheLock.unlock();
    }
}