Example usage for java.util.concurrent.atomic AtomicReference set

List of usage examples for java.util.concurrent.atomic AtomicReference set

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference set.

Prototype

public final void set(V newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java

@Test
public void testPair() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    URI uri = new URI("ws://localhost:" + port + "/composite");
    WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    stompClient.connect(new StompMessageHandler() {

        private StompSession stompSession;

        @Override//from w w  w  . j av a2 s  . c o m
        public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) {

            this.stompSession = stompSession;
            this.stompSession.subscribe("/user/queue/device", null);

            try {
                PairMessage pair = new PairMessage();
                Device d = new Device();
                d.setUuid(UUID.randomUUID());
                pair.setDevice(d);
                pair.setType(PairMessage.Types.exit);
                pair.setGeo(new float[] { lat, lon });
                pair.setPoint(new int[] { 0, 0 });
                pair.setVector(new float[] { 1, 1 });

                stompSession.send("/app/pair", pair);
            } catch (Throwable t) {
                failure.set(t);
                latch.countDown();
            }
        }

        @Override
        public void handleMessage(Message<byte[]> message) {
            try {
                String json = parseMessageJson(message);
                new JsonPathExpectationsHelper("devices").exists(json);
                new JsonPathExpectationsHelper("devices").assertValueIsArray(json);
                new JsonPathExpectationsHelper("type").assertValue(json, "pair");
            } catch (Throwable t) {
                failure.set(t);
            } finally {
                this.stompSession.disconnect();
                latch.countDown();
            }
        }

        @Override
        public void handleError(Message<byte[]> message) {
            StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
            String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload());
            logger.error(error);
            failure.set(new Exception(error));
        }

        @Override
        public void handleReceipt(String receiptId) {
        }

        @Override
        public void afterDisconnected() {
        }
    });

    if (!latch.await(10, TimeUnit.SECONDS)) {
        fail("Pair response not received");
    } else if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }

}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

private boolean verifySignature(Element element, PublicKey validatingKey,
        AtomicReference<String> OutReadableErrorMessage) {
    if (OutReadableErrorMessage == null) {
        OutReadableErrorMessage = new AtomicReference<String>();
    }//from   w  ww .  j a v  a2 s.com
    XMLSignatureFactory fac = initXMLSigFactory();
    NodeList nl = element.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Cannot find Signature element");
    }
    DOMValidateContext valContext = new DOMValidateContext(validatingKey, nl.item(0));
    try {
        valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        boolean coreValidity = signature.validate(valContext);
        // Check core validation status.
        if (coreValidity == false) {
            logger.warn("Signature failed core validation");
            boolean sv = signature.getSignatureValue().validate(valContext);
            logger.debug("signature validation status: " + sv);
            OutReadableErrorMessage
                    .set("signature validation failed: " + sv + "." + OutReadableErrorMessage.get());
            // Check the validation status of each Reference.
            @SuppressWarnings("unchecked")
            Iterator<Reference> i = signature.getSignedInfo().getReferences().iterator();
            //System.out.println("---------------------------------------------");
            for (int j = 0; i.hasNext(); j++) {
                Reference ref = (Reference) i.next();
                boolean refValid = ref.validate(valContext);
                logger.debug(j);
                logger.debug("ref[" + j + "] validity status: " + refValid);
                if (!refValid) {
                    OutReadableErrorMessage
                            .set("signature reference " + j + " invalid. " + OutReadableErrorMessage.get());
                }
                logger.debug("Ref type: " + ref.getType() + ", URI: " + ref.getURI());
                for (Object xform : ref.getTransforms()) {
                    logger.debug("Transform: " + xform);
                }
                String calcDigValStr = digestToString(ref.getCalculatedDigestValue());
                String expectedDigValStr = digestToString(ref.getDigestValue());
                logger.warn("    Calc Digest: " + calcDigValStr);
                logger.warn("Expected Digest: " + expectedDigValStr);
                if (!calcDigValStr.equalsIgnoreCase(expectedDigValStr)) {
                    OutReadableErrorMessage.set(
                            "digest mismatch for signature ref " + j + "." + OutReadableErrorMessage.get());
                }
            }
        } else {
            logger.info("Signature passed core validation");
        }
        return coreValidity;
    } catch (Exception e) {
        OutReadableErrorMessage
                .set("signature validation failed: " + e.getMessage() + OutReadableErrorMessage.get());
        logger.fatal(e);
        return false;
    }
}

From source file:org.apache.jackrabbit.oak.segment.CompactionAndCleanupIT.java

/**
 * Regression test for OAK-2192 testing for mixed segments. This test does not
 * cover OAK-3348. I.e. it does not assert the segment graph is free of cross
 * gc generation references.//from   ww w . j  a  v a  2 s. c  om
 */
@Test
public void testMixedSegments() throws Exception {
    FileStore store = fileStoreBuilder(getFileStoreFolder()).withMaxFileSize(2).withMemoryMapping(true)
            .withGCOptions(defaultGCOptions().setForceAfterFail(true)).build();
    final SegmentNodeStore nodeStore = SegmentNodeStoreBuilders.builder(store).build();
    final AtomicBoolean compactionSuccess = new AtomicBoolean(true);

    NodeBuilder root = nodeStore.getRoot().builder();
    createNodes(root.setChildNode("test"), 10, 3);
    nodeStore.merge(root, EmptyHook.INSTANCE, CommitInfo.EMPTY);

    final Set<UUID> beforeSegments = new HashSet<UUID>();
    collectSegments(store.getReader(), store.getRevisions(), beforeSegments);

    final AtomicReference<Boolean> run = new AtomicReference<Boolean>(true);
    final List<String> failedCommits = newArrayList();
    Thread[] threads = new Thread[10];
    for (int k = 0; k < threads.length; k++) {
        final int threadId = k;
        threads[k] = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; run.get(); j++) {
                    String nodeName = "b-" + threadId + "," + j;
                    try {
                        NodeBuilder root = nodeStore.getRoot().builder();
                        root.setChildNode(nodeName);
                        nodeStore.merge(root, EmptyHook.INSTANCE, CommitInfo.EMPTY);
                        Thread.sleep(5);
                    } catch (CommitFailedException e) {
                        failedCommits.add(nodeName);
                    } catch (InterruptedException e) {
                        Thread.interrupted();
                        break;
                    }
                }
            }
        });
        threads[k].start();
    }
    store.compact();
    run.set(false);
    for (Thread t : threads) {
        t.join();
    }
    store.flush();

    assumeTrue("Failed to acquire compaction lock", compactionSuccess.get());
    assertTrue("Failed commits: " + failedCommits, failedCommits.isEmpty());

    Set<UUID> afterSegments = new HashSet<UUID>();
    collectSegments(store.getReader(), store.getRevisions(), afterSegments);
    try {
        for (UUID u : beforeSegments) {
            assertFalse("Mixed segments found: " + u, afterSegments.contains(u));
        }
    } finally {
        store.close();
    }
}

From source file:github.daneren2005.dsub.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    // Strip out sensitive information from log
    Log.i(TAG, "Using URL " + url.substring(0, url.indexOf("?u=") + 1) + url.substring(url.indexOf("&v=") + 1));

    SharedPreferences prefs = Util.getPreferences(context);
    int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
    HttpParams newParams = httpClient.getParams();
    HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
    httpClient.setParams(newParams);/*from  ww  w  .  j av  a  2  s  .  c o  m*/

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                cancelled.set(true);
                                request.abort();
                            } catch (Exception e) {
                                Log.e(TAG, "Failed to stop http task");
                            }
                        }
                    }).start();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:org.commonjava.maven.galley.cache.infinispan.FastLocalCacheProvider.java

@Override
public boolean isReadLocked(ConcreteResource resource) {
    try {/*from   w  w w .  j  av  a2 s. co m*/
        //To avoid deadlock, here use a lock with timeout, if timeout happened, will throw exception
        AtomicReference<IOException> taskException = new AtomicReference<>();
        final Boolean result = tryLockAnd(resource, DEFAULT_WAIT_FOR_TRANSFER_LOCK_SECONDS, TimeUnit.SECONDS,
                r -> {
                    try {
                        final String cacheKey = getKeyForResource(resource);
                        final boolean isFileReadLocked = plCacheProvider.isReadLocked(resource);
                        final boolean isISPNLocked = nfsOwnerCache.isLocked(cacheKey);
                        logger.trace(
                                "The read lock status: resource locked: {}, ISPN locked: {}, lockKey: {}, Resource: {}",
                                isFileReadLocked, isISPNLocked, cacheKey, resource);
                        return isFileReadLocked || isISPNLocked;
                    } catch (IOException e) {
                        taskException.set(e);
                        return false;
                    }
                });
        propagateException(taskException.get());

        return result == null ? false : result;
    } catch (IOException e) {
        final String errorMsg = String.format(
                "[galley] When get NFS cache key for resource: %s, got I/O error.", resource.toString());
        logger.error(errorMsg, e);
        throw new IllegalStateException(errorMsg, e);
    }
}

From source file:org.apache.nifi.processors.standard.SplitText.java

/**
 * Will split the incoming stream releasing all splits as FlowFile at once.
 *//*from w w w.  j av a 2 s  .  c  o  m*/
@Override
public void onTrigger(ProcessContext context, ProcessSession processSession) throws ProcessException {
    FlowFile sourceFlowFile = processSession.get();
    if (sourceFlowFile == null) {
        return;
    }
    AtomicBoolean error = new AtomicBoolean();
    List<SplitInfo> computedSplitsInfo = new ArrayList<>();
    AtomicReference<SplitInfo> headerSplitInfoRef = new AtomicReference<>();
    processSession.read(sourceFlowFile, new InputStreamCallback() {
        @Override
        public void process(InputStream in) throws IOException {
            TextLineDemarcator demarcator = new TextLineDemarcator(in);
            SplitInfo splitInfo = null;
            long startOffset = 0;

            // Compute fragment representing the header (if available)
            long start = System.nanoTime();
            try {
                if (SplitText.this.headerLineCount > 0) {
                    splitInfo = SplitText.this.computeHeader(demarcator, startOffset,
                            SplitText.this.headerLineCount, null, null);
                    if ((splitInfo != null) && (splitInfo.lineCount < SplitText.this.headerLineCount)) {
                        error.set(true);
                        getLogger().error("Unable to split " + sourceFlowFile
                                + " due to insufficient amount of header lines. Required "
                                + SplitText.this.headerLineCount + " but was " + splitInfo.lineCount
                                + ". Routing to failure.");
                    }
                } else if (SplitText.this.headerMarker != null) {
                    splitInfo = SplitText.this.computeHeader(demarcator, startOffset, Long.MAX_VALUE,
                            SplitText.this.headerMarker.getBytes(StandardCharsets.UTF_8), null);
                }
                headerSplitInfoRef.set(splitInfo);
            } catch (IllegalStateException e) {
                error.set(true);
                getLogger().error(e.getMessage() + " Routing to failure.", e);
            }

            // Compute and collect fragments representing the individual splits
            if (!error.get()) {
                if (headerSplitInfoRef.get() != null) {
                    startOffset = headerSplitInfoRef.get().length;
                }
                long preAccumulatedLength = startOffset;
                while ((splitInfo = SplitText.this.nextSplit(demarcator, startOffset, SplitText.this.lineCount,
                        splitInfo, preAccumulatedLength)) != null) {
                    computedSplitsInfo.add(splitInfo);
                    startOffset += splitInfo.length;
                }
                long stop = System.nanoTime();
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Computed splits in " + (stop - start) + " milliseconds.");
                }
            }
        }
    });

    if (error.get()) {
        processSession.transfer(sourceFlowFile, REL_FAILURE);
    } else {
        final String fragmentId = UUID.randomUUID().toString();
        List<FlowFile> splitFlowFiles = this.generateSplitFlowFiles(fragmentId, sourceFlowFile,
                headerSplitInfoRef.get(), computedSplitsInfo, processSession);
        final FlowFile originalFlowFile = FragmentAttributes.copyAttributesToOriginal(processSession,
                sourceFlowFile, fragmentId, splitFlowFiles.size());
        processSession.transfer(originalFlowFile, REL_ORIGINAL);
        if (!splitFlowFiles.isEmpty()) {
            processSession.transfer(splitFlowFiles, REL_SPLITS);
        }
    }
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.WebServiceLayerLocalWorkspaces.java

@Override
public GetOperation[] pendChanges(final String workspaceName, final String ownerName,
        final ChangeRequest[] changes, final PendChangesOptions pendChangesOptions,
        final SupportedFeatures supportedFeatures, final AtomicReference<Failure[]> failures,
        final String[] itemPropertyFilters, final String[] itemAttributeFilters, final boolean updateDisk,
        final AtomicBoolean onlineOperation, final AtomicReference<ChangePendedFlags> changePendedFlags) {
    onlineOperation.set(false);//from ww w. j  av a2 s  .c  o  m

    // set this to none for local workspaces, if the call reaches the server
    // the flag will get overwritten
    changePendedFlags.set(ChangePendedFlags.NONE);
    int unlockCount = 0;

    final Workspace localWorkspace = getLocalWorkspace(workspaceName, ownerName);
    if (localWorkspace != null) {
        boolean attributeChange = false;
        boolean nonExecuteSymlinkBitPropertyChange = false;

        if (null != itemAttributeFilters && itemAttributeFilters.length > 0) {
            attributeChange = true;
        }

        // If the property filters are only for the executable bit, we can
        // handle that locally, otherwise we must go to the server.
        if (null != itemPropertyFilters && itemPropertyFilters.length > 0) {
            for (final String filter : itemPropertyFilters) {
                /*
                 * Not using wildcard matching here: just because a wildcard
                 * _does_ match the executable key _doesn't_ mean it
                 * wouldn't match others on the server. So only consider a
                 * direct match against the executable key to keep
                 * processing locally.
                 */
                if (PropertyValue.comparePropertyNames(PropertyConstants.EXECUTABLE_KEY, filter) != 0
                        && PropertyValue.comparePropertyNames(PropertyConstants.SYMBOLIC_KEY, filter) != 0) {
                    nonExecuteSymlinkBitPropertyChange = true;
                    break;
                }
            }
        }

        RequestType requestType = RequestType.NONE;
        boolean requestingLock = false;

        for (final ChangeRequest changeRequest : changes) {
            if (RequestType.NONE == requestType) {
                requestType = changeRequest.getRequestType();
            } else if (requestType != changeRequest.getRequestType()) {
                // TODO: Move string from server assembly
                throw new VersionControlException("Not all changes had the same request type"); //$NON-NLS-1$
            }

            // If the caller is requesting a lock, then the call is a server
            // call, unless the user is performing an add and the LockLevel
            // is None.

            // Is it possible to have different locklevels on different
            // ChangeRequest objects?

            if (changeRequest.getLockLevel() != LockLevel.UNCHANGED
                    && !(changeRequest.getLockLevel() == LockLevel.NONE
                            && changeRequest.getRequestType() == RequestType.ADD)) {
                requestingLock = true;
            }

            if (changeRequest.getLockLevel() == LockLevel.NONE
                    && changeRequest.getRequestType().equals(RequestType.LOCK)) {
                unlockCount++;
            }
        }

        final boolean silent = pendChangesOptions.contains(PendChangesOptions.SILENT);

        if (!requestingLock && !attributeChange && !nonExecuteSymlinkBitPropertyChange) {
            if (requestType == RequestType.ADD || requestType == RequestType.EDIT
                    || requestType == RequestType.DELETE || requestType == RequestType.RENAME
                    || requestType == RequestType.PROPERTY) {
                final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(localWorkspace);
                try {
                    final AtomicReference<Failure[]> delegateFailures = new AtomicReference<Failure[]>();
                    final AtomicReference<GetOperation[]> toReturn = new AtomicReference<GetOperation[]>();

                    final RequestType transactionRequestType = requestType;

                    transaction.execute(new AllTablesTransaction() {
                        @Override
                        public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv,
                                final LocalPendingChangesTable pc) {
                            if (transactionRequestType == RequestType.ADD) {
                                toReturn.set(LocalDataAccessLayer.pendAdd(localWorkspace, wp, lv, pc, changes,
                                        silent, delegateFailures, itemPropertyFilters));
                            } else if (transactionRequestType == RequestType.EDIT) {
                                toReturn.set(LocalDataAccessLayer.pendEdit(localWorkspace, wp, lv, pc, changes,
                                        silent, delegateFailures, itemPropertyFilters));
                            } else if (transactionRequestType == RequestType.DELETE) {
                                toReturn.set(LocalDataAccessLayer.pendDelete(localWorkspace, wp, lv, pc,
                                        changes, silent, delegateFailures, itemPropertyFilters));
                            } else if (transactionRequestType == RequestType.RENAME) {
                                final AtomicBoolean onlineOperationRequired = new AtomicBoolean(false);

                                toReturn.set(LocalDataAccessLayer.pendRename(localWorkspace, wp, lv, pc,
                                        changes, silent, delegateFailures, onlineOperationRequired,
                                        itemPropertyFilters));

                                if (onlineOperationRequired.get()) {
                                    toReturn.set(null);
                                    transaction.abort();
                                } else if (updateDisk) {
                                    // we don't want to file a conflict
                                    // while offline, so we check up front.
                                    for (final GetOperation getOp : toReturn.get()) {
                                        if (getOp.getTargetLocalItem() != null
                                                && !LocalPath.equals(getOp.getSourceLocalItem(),
                                                        getOp.getTargetLocalItem())
                                                && new File(getOp.getTargetLocalItem()).exists()) {
                                            throw new VersionControlException(MessageFormat.format(
                                                    //@formatter:off
                                                    Messages.getString(
                                                            "WebServiceLayerLocalWorkspaces.FileExistsFormat"), //$NON-NLS-1$
                                                    //@formatter:on
                                                    getOp.getTargetLocalItem()));
                                        }
                                    }
                                }
                            }

                            if (transactionRequestType == RequestType.PROPERTY) {
                                final AtomicBoolean onlineOperationRequired = new AtomicBoolean(false);

                                toReturn.set(LocalDataAccessLayer.pendPropertyChange(localWorkspace, wp, lv, pc,
                                        changes, silent, delegateFailures, onlineOperationRequired,
                                        itemPropertyFilters));

                                if (onlineOperationRequired.get()) {
                                    toReturn.set(null);
                                    transaction.abort();
                                }
                            }
                        }
                    });

                    if (toReturn.get() != null) {
                        // Offline operation successfully completed.
                        failures.set(delegateFailures.get());
                        return toReturn.get();
                    }
                } finally {
                    try {
                        transaction.close();
                    } catch (final IOException e) {
                        throw new VersionControlException(e);
                    }
                }
            } else if (requestType == RequestType.BRANCH || requestType == RequestType.UNDELETE
                    || requestType == RequestType.LOCK) {
                // Forward to server
            } else {
                // TODO: Remove this when all RequestTypes are supported
                // here.
                throw new VersionControlException("Not currently implemented for local workspaces"); //$NON-NLS-1$
            }
        }
    }

    if (null != localWorkspace) {
        // if we only have requests for unlocking, move on if the reconcile
        // fails this is needed for unlock other
        final Workspace w = reconcileIfLocal(workspaceName, ownerName, false, false,
                unlockCount == changes.length, null);

        // Lock the workspace which will receive the pending changes
        final WorkspaceLock lock = lockIfLocal(w);

        try {

            final GetOperation[] toReturn;
            try {
                if (getServiceLevel().getValue() >= WebServiceLevel.TFS_2012_QU1.getValue()) {
                    final _Repository5Soap_PendChangesInLocalWorkspaceResponse response = getRepository5()
                            .pendChangesInLocalWorkspace(workspaceName, ownerName,
                                    (_ChangeRequest[]) WrapperUtils.unwrap(_ChangeRequest.class, changes),
                                    pendChangesOptions.toIntFlags(), supportedFeatures.toIntFlags(),
                                    itemPropertyFilters, itemAttributeFilters,
                                    VersionControlConstants.MAX_SERVER_PATH_SIZE);
                    toReturn = (GetOperation[]) WrapperUtils.wrap(GetOperation.class,
                            response.getPendChangesInLocalWorkspaceResult());

                    failures.set((Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures()));
                    changePendedFlags.set(new ChangePendedFlags(response.getChangePendedFlags()));
                } else {
                    final _Repository4Soap_PendChangesInLocalWorkspaceResponse response = getRepository4()
                            .pendChangesInLocalWorkspace(workspaceName, ownerName,
                                    (_ChangeRequest[]) WrapperUtils.unwrap(_ChangeRequest.class, changes),
                                    pendChangesOptions.toIntFlags(), supportedFeatures.toIntFlags(),
                                    itemPropertyFilters, itemAttributeFilters);
                    toReturn = (GetOperation[]) WrapperUtils.wrap(GetOperation.class,
                            response.getPendChangesInLocalWorkspaceResult());

                    failures.set((Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures()));
                    changePendedFlags.set(new ChangePendedFlags(response.getChangePendedFlags()));
                }
            } catch (final ProxyException e) {
                throw VersionControlExceptionMapper.map(e);
            }

            syncWorkingFoldersIfNecessary(w, changePendedFlags.get());
            syncPendingChangesIfLocal(w, toReturn, itemPropertyFilters);

            if (RequestType.ADD == changes[0].getRequestType()) {
                // The client does not process the getops returned from a
                // PendAdd call. Because the server has created local
                // version rows for us, we need to update the local version
                // table to contain these rows too.
                LocalDataAccessLayer.afterAdd(localWorkspace, toReturn);

                // When a pending add is created, the item on disk is not
                // touched; so we need to inform the scanner that the item
                // is invalidated so it is re-scanned. Rather than go
                // through the local paths on which adds were pended, we'll
                // invalidate the workspace. This is not a common code path.
                localWorkspace.getWorkspaceWatcher().markPathChanged(""); //$NON-NLS-1$
            }

            onlineOperation.set(true);
            return toReturn;
        } finally {
            if (lock != null) {
                lock.close();
            }
        }
    } else {
        return super.pendChanges(workspaceName, ownerName, changes, pendChangesOptions, supportedFeatures,
                failures, itemPropertyFilters, itemAttributeFilters, updateDisk, onlineOperation,
                changePendedFlags);
    }
}

From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java

@Test
public void testDevices() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<>();

    URI uri = new URI("ws://localhost:" + port + "/composite");
    WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    stompClient.connect(new StompMessageHandler() {

        private StompSession stompSession;

        @Override//from  w  w  w. j  a  v  a  2s.com
        public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) {
            this.stompSession = stompSession;
            String topicUuid = simulateJoinEvent();

            // Call again to get a second device in the session
            simulateJoinEvent();

            this.stompSession.subscribe("/user/queue/device", null);
            this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null);

            try {
                // send a message to the devices endpoint
                HashMap<String, Object> devices = new HashMap<String, Object>();
                devices.put("type", "devices");
                this.stompSession.send(String.format("/app/%s", topicUuid), devices);
            } catch (Throwable t) {
                failure.set(t);
                latch.countDown();
            }
        }

        @Override
        public void handleMessage(Message<byte[]> message) {
            try {
                String json = parseMessageJson(message);
                new JsonPathExpectationsHelper("devices").exists(json);
                new JsonPathExpectationsHelper("type").exists(json);
                new JsonPathExpectationsHelper("type").assertValue(json, "devices");
                new JsonPathExpectationsHelper("serverTime").exists(json);
            } catch (Throwable t) {
                failure.set(t);
            } finally {
                this.stompSession.disconnect();
                latch.countDown();
            }
        }

        @Override
        public void handleError(Message<byte[]> message) {
            StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
            String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload());
            logger.error(error);
            failure.set(new Exception(error));
        }

        @Override
        public void handleReceipt(String receiptId) {
        }

        @Override
        public void afterDisconnected() {
        }
    });

    if (!latch.await(10, TimeUnit.SECONDS)) {
        fail("Devices response not received");
    } else if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }
}

From source file:org.commonjava.maven.galley.cache.infinispan.FastLocalCacheProvider.java

@Override
public boolean isWriteLocked(ConcreteResource resource) {
    try {/* w  w  w.  j  a v a 2s  . c  om*/
        //To avoid deadlock, here use a lock with timeout, if timeout happened, will throw exception
        AtomicReference<IOException> taskException = new AtomicReference<>();
        final Boolean result = tryLockAnd(resource, DEFAULT_WAIT_FOR_TRANSFER_LOCK_SECONDS, TimeUnit.SECONDS,
                r -> {
                    try {
                        final String cacheKey = getKeyForResource(resource);
                        final boolean isFileWriteLocked = plCacheProvider.isWriteLocked(resource);
                        final boolean isISPNLocked = nfsOwnerCache.isLocked(getKeyForResource(resource));
                        logger.trace(
                                "The write lock status: resource locked: {}, ISPN locked: {}, lock key: {}, Resource: {}",
                                isFileWriteLocked, isISPNLocked, cacheKey, resource);
                        return isFileWriteLocked || isISPNLocked;
                    } catch (IOException e) {
                        taskException.set(e);
                        return false;
                    }
                });
        propagateException(taskException.get());

        return result == null ? false : result;
    } catch (IOException e) {
        final String errorMsg = String.format(
                "[galley] When get NFS cache key for resource: %s, got I/O error.", resource.toString());
        logger.error(errorMsg, e);
        throw new IllegalStateException(errorMsg, e);
    }
}

From source file:interactivespaces.util.web.WebSocketTest.java

@Test
public void testWebSocketCommunication() throws Exception {
    final String dataKey = "message";

    final CountDownLatch clientOpenning = new CountDownLatch(1);
    final CountDownLatch clientClosing = new CountDownLatch(1);

    final AtomicBoolean onConnectCalledServer = new AtomicBoolean(false);
    final AtomicBoolean onCloseCalledServer = new AtomicBoolean(false);

    final AtomicReference<WebServerWebSocketHandler> serverHandler = new AtomicReference<WebServerWebSocketHandler>();

    int port = 8082;
    String webSocketUriPrefix = "websockettest";

    URI uri = new URI(String.format("ws://127.0.0.1:%d/%s", port, webSocketUriPrefix));

    final List<Integer> serverReceivedList = Lists.newArrayList();
    final List<Integer> clientReceivedList = Lists.newArrayList();
    List<Integer> serverSentList = Lists.newArrayList();
    List<Integer> clientSentList = Lists.newArrayList();
    Random random = new Random(System.currentTimeMillis());

    for (int i = 0; i < 100; i++) {
        clientSentList.add(random.nextInt());
        serverSentList.add(random.nextInt());
    }// www.java  2 s.c o  m

    NettyWebServer server = new NettyWebServer(threadPool, log);
    server.setServerName("test-server");
    server.setPort(port);
    server.setWebSocketHandlerFactory(webSocketUriPrefix, new WebServerWebSocketHandlerFactory() {

        @Override
        public WebServerWebSocketHandler newWebSocketHandler(WebSocketConnection connection) {
            WebServerWebSocketHandler handler = new WebServerWebSocketHandlerSupport(connection) {

                @Override
                public void onReceive(Object data) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> d = (Map<String, Object>) data;

                    serverReceivedList.add((Integer) d.get(dataKey));
                }

                @Override
                public void onConnect() {
                    onConnectCalledServer.set(true);
                }

                @Override
                public void onClose() {
                    onCloseCalledServer.set(true);
                }
            };

            serverHandler.set(handler);

            return handler;
        }
    });
    server.startup();

    Thread.sleep(2000);

    WebSocketHandler clientHandler = new WebSocketHandler() {

        @Override
        public void onConnect() {
            clientOpenning.countDown();
        }

        @Override
        public void onClose() {
            clientClosing.countDown();
        }

        @Override
        public void onReceive(Object data) {
            @SuppressWarnings("unchecked")
            Map<String, Object> d = (Map<String, Object>) data;

            clientReceivedList.add((Integer) d.get(dataKey));
        }
    };

    NettyWebSocketClient client = new NettyWebSocketClient(uri, clientHandler, threadPool, log);
    client.startup();

    Assert.assertTrue(clientOpenning.await(10, TimeUnit.SECONDS));

    Assert.assertTrue(client.isOpen());

    Map<String, Object> data = Maps.newHashMap();
    for (Integer i : clientSentList) {
        data.put("message", i);
        client.writeDataAsJson(data);
    }

    for (Integer i : serverSentList) {
        data.put("message", i);
        serverHandler.get().sendJson(data);
    }

    client.ping();

    client.shutdown();

    Assert.assertTrue(clientClosing.await(10, TimeUnit.SECONDS));

    server.shutdown();

    Assert.assertEquals(clientSentList, serverReceivedList);
    Assert.assertEquals(serverSentList, clientReceivedList);
    Assert.assertTrue(onConnectCalledServer.get());
    Assert.assertTrue(onCloseCalledServer.get());
}