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

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

Introduction

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

Prototype

public final V get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:de.schildbach.pte.AbstractEfaProvider.java

protected QueryTripsResult queryMoreTripsMobile(final QueryTripsContext contextObj, final boolean later)
        throws IOException {
    final Context context = (Context) contextObj;
    final HttpUrl commandUrl = HttpUrl.parse(context.context);
    final HttpUrl.Builder url = commandUrl.newBuilder();
    url.addEncodedQueryParameter("command", later ? "tripNext" : "tripPrev");
    final AtomicReference<QueryTripsResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override/*w ww. j av  a 2 s.  c o  m*/
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            try {
                result.set(queryTripsMobile(url.build(), null, null, null, body.byteStream()));
            } catch (final XmlPullParserException x) {
                throw new ParserException("cannot parse xml: " + bodyPeek, x);
            } catch (final RuntimeException x) {
                throw new RuntimeException("uncategorized problem while processing " + url, x);
            }
        }
    };

    httpClient.getInputStream(callback, url.build(), httpRefererTrip);

    return result.get();
}

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

/**
 *
 *
 *
 * @param workspace/*w  w  w  .ja v  a  2 s  .com*/
 * @param lv
 * @param pc
 * @param itemSpecs
 * @param failures
 * @param onlineOperationRequired
 * @param invalidateWorkspaceAfterServerCall
 * @return
 */
public static GetOperation[] undoPendingChanges(final Workspace workspace, final LocalWorkspaceProperties wp,
        final WorkspaceVersionTable lv, final LocalPendingChangesTable pc, final ItemSpec[] itemSpecs,
        final AtomicReference<Failure[]> failures, final AtomicBoolean onlineOperationRequired,
        final String[] itemPropertyFilters) {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$
    Check.notNullOrEmpty(itemSpecs, "itemSpecs"); //$NON-NLS-1$

    final List<Failure> failuresList = new ArrayList<Failure>();

    final GetOperation[] toReturn = undoPendingChanges(workspace, wp, lv, pc,
            queryPendingChanges(workspace, wp, lv, pc, itemSpecs, failuresList, false, itemPropertyFilters),
            ChangeType.ALL, failures, onlineOperationRequired);

    for (final Failure failure : failures.get()) {
        failuresList.add(failure);
    }

    failures.set(failuresList.toArray(new Failure[failuresList.size()]));
    return toReturn;
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerTest.java

@Test
public void testConcurrentOpenCursor() throws Exception {
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("testConcurrentOpenCursor");

    final AtomicReference<ManagedCursor> cursor1 = new AtomicReference<>(null);
    final AtomicReference<ManagedCursor> cursor2 = new AtomicReference<>(null);
    final CyclicBarrier barrier = new CyclicBarrier(2);
    final CountDownLatch latch = new CountDownLatch(2);

    cachedExecutor.execute(() -> {/*from  w  w w .  j  a v a  2 s . c  o m*/
        try {
            barrier.await();
        } catch (Exception e) {
        }
        ledger.asyncOpenCursor("c1", new OpenCursorCallback() {

            @Override
            public void openCursorFailed(ManagedLedgerException exception, Object ctx) {
                latch.countDown();
            }

            @Override
            public void openCursorComplete(ManagedCursor cursor, Object ctx) {
                cursor1.set(cursor);
                latch.countDown();
            }
        }, null);
    });

    cachedExecutor.execute(() -> {
        try {
            barrier.await();
        } catch (Exception e) {
        }
        ledger.asyncOpenCursor("c1", new OpenCursorCallback() {

            @Override
            public void openCursorFailed(ManagedLedgerException exception, Object ctx) {
                latch.countDown();
            }

            @Override
            public void openCursorComplete(ManagedCursor cursor, Object ctx) {
                cursor2.set(cursor);
                latch.countDown();
            }
        }, null);
    });

    latch.await();
    assertNotNull(cursor1.get());
    assertNotNull(cursor2.get());
    assertEquals(cursor1.get(), cursor2.get());

    ledger.close();
}

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

/**
 *
 *
 *
 * @param workspace/*from  w w  w.j  a  v a  2  s.  c o m*/
 * @param lv
 * @param pc
 * @param changeRequests
 * @param silent
 * @param failures
 * @param onlineOperationRequired
 * @param invalidateWorkspaceAfterServerCall
 * @return
 */
public static GetOperation[] pendRename(final Workspace workspace, final LocalWorkspaceProperties wp,
        final WorkspaceVersionTable lv, final LocalPendingChangesTable pc, final ChangeRequest[] changeRequests,
        final boolean silent, final AtomicReference<Failure[]> failures,
        final AtomicBoolean onlineOperationRequired, final String[] itemPropertyFilters) {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$
    Check.notNull(changeRequests, "changeRequests"); //$NON-NLS-1$

    workspace.getWorkspaceWatcher().scan(wp, lv, pc);

    final List<Failure> failureList = new ArrayList<Failure>();
    final List<GetOperation> getOps = new ArrayList<GetOperation>();

    failures.set(null);
    final WorkingFolder[] workspaceMappings = wp.getWorkingFolders();

    for (int i = 0; i < changeRequests.length; i++) {
        if (null == changeRequests[i]) {
            continue;
        }

        final ParsedItemSpec parsedItemSpec = ParsedItemSpec.fromItemSpec(changeRequests[i].getItemSpec(), wp,
                lv, pc, ParsedItemSpecOptions.NONE, failureList);

        if (null == parsedItemSpec) {
            continue;
        }

        final String sourceRoot = parsedItemSpec.getTargetItem();
        String targetRoot = changeRequests[i].getTargetItem();
        final String sourceServerRoot = tryGetServerItem(sourceRoot, wp, lv, pc);

        String targetServerRoot = null;
        boolean isCloaked = false;

        if (ServerPath.isServerPath(targetRoot)) {
            targetServerRoot = targetRoot;
        } else {
            final PathTranslation translation = WorkingFolder.translateLocalItemToServerItem(targetRoot,
                    workspaceMappings);

            if (translation != null) {
                targetServerRoot = translation.getTranslatedPath();
                isCloaked = translation.isCloaked();
            }
        }

        if (isCloaked) {
            failureList.add(createItemCloakedFailure(targetRoot));
            continue;
        } else if (targetServerRoot == null) {
            // Error is consistent with server workspaces when target path
            // is non-server and unmapped, but not cloaked
            failureList.add(createItemNotMappedFailure(targetRoot));
            continue;
        }

        final String targetLocalRoot = ServerPath.isServerPath(targetRoot)
                ? WorkingFolder.getLocalItemForServerItem(targetRoot, workspaceMappings)
                : targetRoot;

        final int maxServerPathLength = workspace.getClient().getMaxServerPathLength();
        // For consistency in error messages with server workspaces, check
        // the provided itemspec first, then the translated path.
        final AtomicReference<String> outTargetRoot = new AtomicReference<String>(targetRoot);
        ItemPath.checkItem(outTargetRoot, "changeRequest.ItemSpec.Item", //$NON-NLS-1$
                false, false, false, true, maxServerPathLength);
        targetRoot = outTargetRoot.get();

        if (ServerPath.isServerPath(targetRoot)) {
            if (targetLocalRoot != null && targetLocalRoot.length() > 0) {
                LocalPath.checkLocalItem(targetLocalRoot, "TargetItem", false, false, false, true); //$NON-NLS-1$
            }
        } else {
            final AtomicReference<String> outTargetServerRoot = new AtomicReference<String>(targetServerRoot);
            ServerPath.checkServerItem(outTargetServerRoot, "TargetItem", //$NON-NLS-1$
                    false, false, false, true, maxServerPathLength);
            targetServerRoot = outTargetServerRoot.get();
        }

        // server path minus all renames that exists on its parents
        final String targetUnrenamedServerRoot = pc.getCommittedServerItemForTargetServerItem(targetServerRoot);
        if (ItemPath.isWildcard(targetRoot)) {
            failureList.add(
                    new Failure(Messages.getString("LocalDataAccessLayer.WildcardNotAllowedForRenameTarget"), //$NON-NLS-1$
                            FailureCodes.WILDCARD_NOT_ALLOWED_EXCEPTION, SeverityType.ERROR, targetRoot));
            continue;
        }

        final ItemType targetItemType = changeRequests[i].getTargetItemType();
        final boolean isMove = isMove(targetUnrenamedServerRoot, targetItemType, lv);
        final boolean targetIsFolder = targetItemType == ItemType.ANY ? isDirectory(lv, pc, targetServerRoot)
                : targetItemType == ItemType.FOLDER;
        // if we move dir\*.cs, root (dir will not be included), if we move
        // dir, root is included
        final boolean rootIncludedInRename = parsedItemSpec.getPattern() == null;

        if (parsedItemSpec.getPattern() != null && ItemPath.isWildcard(parsedItemSpec.getPattern())
                && !isMove) {
            failureList.add(
                    new Failure(Messages.getString("LocalDataAccessLayer.WildcardNotAllowedForRenameSource"), //$NON-NLS-1$
                            FailureCodes.WILDCARD_NOT_ALLOWED_EXCEPTION, SeverityType.ERROR, sourceRoot));
            continue;
        }

        if (ServerPath.isRootFolder(targetServerRoot)) {
            failureList
                    .add(new Failure(Messages.getString("LocalDataAccessLayer.CanNotChangeRootFolderException"), //$NON-NLS-1$
                            FailureCodes.CANNOT_CHANGE_ROOT_FOLDER_EXCEPTION, SeverityType.ERROR,
                            parsedItemSpec.getTargetItem()));
            continue;
        }

        if (!targetIsFolder) {
            // we validate if target is a team project only if it doesn't
            // exist in local workspace - if it does, we will move files
            // under it
            final Failure teamProjectValidationFailure = TeamProject.validateChange(targetServerRoot,
                    ItemType.FOLDER);
            if (teamProjectValidationFailure != null) {
                failureList.add(teamProjectValidationFailure);
                continue;
            }
        }

        for (final WorkspaceLocalItem lvEntry : parsedItemSpec.expandFrom(lv, pc, failureList)) {
            final String sourceCommittedServerItem = lvEntry.getServerItem();
            String sourceCurrentServerItem = sourceCommittedServerItem;
            if (lvEntry.isCommitted()) {
                sourceCurrentServerItem = pc
                        .getTargetServerItemForCommittedServerItem(sourceCommittedServerItem);
            }
            final String targetServerItem = calculateTargetServerItem(sourceServerRoot, sourceCurrentServerItem,
                    targetServerRoot, targetIsFolder, rootIncludedInRename);
            // targetLocalItem may be null if we move file into not mapped
            // location
            final String targetLocalItem = WorkingFolder.getLocalItemForServerItem(targetServerItem,
                    wp.getWorkingFolders());

            final boolean caseOnlyRename = ServerPath.equals(sourceCurrentServerItem, targetServerItem)
                    && !ServerPath.equals(sourceCurrentServerItem, targetServerItem, false);
            if (ServerPath.isRootFolder(sourceCurrentServerItem)) {
                failureList.add(
                        new Failure(Messages.getString("LocalDataAccessLayer.CanNotChangeRootFolderException"), //$NON-NLS-1$
                                FailureCodes.CANNOT_CHANGE_ROOT_FOLDER_EXCEPTION, SeverityType.ERROR,
                                sourceCurrentServerItem));
                continue;
            }

            final Failure teamProjectValidationFailure = TeamProject.validateChange(sourceCommittedServerItem,
                    lvEntry.isDirectory() ? ItemType.FOLDER : ItemType.FILE);
            if (teamProjectValidationFailure != null) {
                failureList.add(teamProjectValidationFailure);
                continue;
            }

            if (targetServerItem.length() > VersionControlConstants.MAX_SERVER_PATH_SIZE) {
                failureList.add(createPathTooLongFailure(targetServerItem));
                continue;
            }

            // validate mappings
            boolean workspaceMappingFailure = false;
            for (final WorkingFolder mapping : workspaceMappings) {
                if (ServerPath.equals(mapping.getServerItem(), sourceCurrentServerItem)) {
                    final String format = Messages
                            .getString("LocalDataAccessLayer.RenameWorkingFolderExceptionFormat"); //$NON-NLS-1$
                    failureList.add(new Failure(MessageFormat.format(format, sourceCurrentServerItem),
                            FailureCodes.RENAME_WORKING_FOLDER_EXCEPTION, SeverityType.ERROR,
                            sourceCurrentServerItem));
                    workspaceMappingFailure = true;
                    break;
                }

                if (ServerPath.isChild(sourceCurrentServerItem, mapping.getServerItem())) {
                    return sendToServer(failures, onlineOperationRequired);
                }
            }
            if (workspaceMappingFailure) {
                continue;
            }

            if (!caseOnlyRename && pc.getByTargetServerItem(targetServerItem) != null) {
                final String format = Messages
                        .getString("LocalDataAccessLayer.ChangeAlreadyPendingExceptionFormat"); //$NON-NLS-1$
                failureList.add(new Failure(MessageFormat.format(format, targetServerItem),
                        FailureCodes.CHANGE_ALREADY_PENDING_EXCEPTION, SeverityType.ERROR,
                        sourceCurrentServerItem));
                continue;
            }

            if (pc.getRecursiveChangeTypeForTargetServerItem(targetServerItem).contains(ChangeType.DELETE)) {
                failureList.add(createPendingParentDeleteFailure(targetServerItem));
                continue;
            }

            LocalPendingChange mainPendingChange = pc.getByLocalVersion(lvEntry);
            if (null != mainPendingChange) {
                if (mainPendingChange.isLock()) {
                    // Cannot offline rename a pending lock.
                    return sendToServer(failures, onlineOperationRequired);
                }

                if (mainPendingChange.isDelete()) {
                    final String format = Messages
                            .getString("LocalDataAccessLayer.IncompatibleChangeExceptionFormat"); //$NON-NLS-1$
                    failureList.add(new Failure(MessageFormat.format(format, targetServerItem),
                            FailureCodes.INCOMPATIBLE_CHANGE_EXCEPTION, SeverityType.ERROR,
                            changeRequests[i].getItemSpec().getItem()));
                    continue;
                }
                // target server item minus all parent renames
                // if we have both parent renamed (folder->folder2) and item
                // renamed(a->b), renaming folder2\a to folder2\b
                // should undo rename on bar
                final String targetParent = ServerPath.getParent(targetServerItem);
                final String committedParent = pc.getCommittedServerItemForTargetServerItem(targetParent);
                String targetUnrenamedParent = null;
                if (committedParent != null && committedParent.length() > 0) {
                    targetUnrenamedParent = committedParent + targetServerItem.substring(targetParent.length());
                }

                if ((targetUnrenamedParent != null
                        && ServerPath.equals(targetUnrenamedParent, sourceCommittedServerItem, false))
                        || ServerPath.equals(sourceCommittedServerItem, targetServerItem, false)) {
                    // Selective undo
                    final AtomicReference<Failure[]> undoFailures = new AtomicReference<Failure[]>();
                    final List<LocalPendingChange> changes = new ArrayList<LocalPendingChange>();
                    changes.add(mainPendingChange);

                    final GetOperation[] undoOps = undoPendingChanges(workspace, wp, lv, pc, changes,
                            ChangeType.RENAME, undoFailures, onlineOperationRequired);

                    if (onlineOperationRequired.get()) {
                        return sendToServer(failures, onlineOperationRequired);
                    }

                    failureList.addAll(Arrays.asList(undoFailures.get()));
                    getOps.addAll(Arrays.asList(undoOps));
                    continue;
                }
            }
            WorkspaceLocalItem conflictingItem = (targetLocalItem == null || targetLocalItem.length() == 0)
                    ? null
                    : lv.getByLocalItem(targetLocalItem);
            if (conflictingItem != null && !caseOnlyRename) {
                final String format = Messages.getString("LocalDataAccessLayer.ItemExistsExceptionFormat"); //$NON-NLS-1$
                failureList.add(new Failure(MessageFormat.format(format, targetServerItem),
                        FailureCodes.ITEM_EXISTS_EXCEPTION, SeverityType.ERROR,
                        conflictingItem.getLocalItem()));
                continue;
            }
            final List<GetOperation> affectedItems = new ArrayList<GetOperation>();
            final Map<String, LocalPendingChange> affectedCommittedPendingChanges = new HashMap<String, LocalPendingChange>();
            final Map<String, LocalPendingChange> affectedNotCommittedPendingChanges = new HashMap<String, LocalPendingChange>();
            // we should not updated pending changes in the main loop, since
            // we use them to calculate target path for each item
            // we need to do that afterwards
            final List<KeyValuePair<String, LocalPendingChange>> updatedPendingChanges = new ArrayList<KeyValuePair<String, LocalPendingChange>>();

            // Create or update main pending change (on the item itself)
            if (mainPendingChange == null) {
                mainPendingChange = new LocalPendingChange(lvEntry, targetServerItem, ChangeType.RENAME);
                affectedCommittedPendingChanges.put(mainPendingChange.getCommittedServerItem(),
                        mainPendingChange);
            } else {
                if (mainPendingChange.isAdd() || mainPendingChange.isBranch()) {
                    affectedNotCommittedPendingChanges.put(mainPendingChange.getTargetServerItem(),
                            mainPendingChange);
                } else {
                    mainPendingChange
                            .setChangeType(mainPendingChange.getChangeType().combine(ChangeType.RENAME));
                    affectedCommittedPendingChanges.put(mainPendingChange.getCommittedServerItem(),
                            mainPendingChange);
                }
            }

            boolean abort = false;
            if (lvEntry.isDirectory()) {
                // build lookup of pending changes, so we can update them
                // and populate GetOps with the right change
                for (final LocalPendingChange lpEntry : pc.queryByTargetServerItem(sourceCurrentServerItem,
                        RecursionType.FULL, "*")) //$NON-NLS-1$
                {
                    if (lpEntry.isAdd() || lpEntry.isBranch()) {
                        affectedNotCommittedPendingChanges.put(lpEntry.getTargetServerItem(), lpEntry);
                    } else {
                        affectedCommittedPendingChanges.put(lpEntry.getCommittedServerItem(), lpEntry);
                    }
                }
            }

            for (final WorkspaceLocalItem childEntry : ParsedItemSpec.queryLocalVersionsByTargetServerItem(lv,
                    pc, sourceCurrentServerItem, RecursionType.FULL, null,
                    ParsedItemSpecOptions.INCLUDE_DELETED)) {
                String childTargetServerItem;
                GetOperation childGetOp;

                LocalPendingChange associatedPendingChange = null;
                if (childEntry.isCommitted()) {
                    associatedPendingChange = affectedCommittedPendingChanges.get(childEntry.getServerItem());
                } else if (!childEntry.isCommitted()) {
                    associatedPendingChange = affectedNotCommittedPendingChanges
                            .get(childEntry.getServerItem());
                }

                if (associatedPendingChange != null) {
                    if (associatedPendingChange.isLock()) {
                        // Cannot offline rename a pending lock.
                        return sendToServer(failures, onlineOperationRequired);
                    }

                    if (!ServerPath.equals(targetServerItem, associatedPendingChange.getTargetServerItem(),
                            false)) {
                        // do not update if this is new pending change we
                        // just created (mainPendingChange)
                        childTargetServerItem = calculateTargetServerItem(sourceServerRoot,
                                associatedPendingChange.getTargetServerItem(), targetServerRoot, targetIsFolder,
                                rootIncludedInRename);
                    } else {
                        childTargetServerItem = associatedPendingChange.getTargetServerItem();
                    }

                    updatedPendingChanges.add(new KeyValuePair<String, LocalPendingChange>(
                            childTargetServerItem, associatedPendingChange));
                    childGetOp = childEntry.toGetOperation(associatedPendingChange, itemPropertyFilters);
                    // SourceServerItem should be identical with
                    // TargetServerItem for not committed changes (add and
                    // branch)
                    childGetOp.setSourceServerItem(childEntry.isCommitted() ? childGetOp.getSourceServerItem()
                            : childTargetServerItem);
                    childGetOp.setTargetServerItem(childTargetServerItem);
                    childGetOp.setChangeType(childEntry.isCommitted()
                            ? associatedPendingChange.getChangeType().combine(ChangeType.RENAME)
                            : childGetOp.getChangeType());
                } else {
                    final String currentServerItem = childEntry.isCommitted()
                            ? pc.getTargetServerItemForCommittedServerItem(childEntry.getServerItem())
                            : childEntry.getServerItem();
                    childTargetServerItem = calculateTargetServerItem(sourceServerRoot, currentServerItem,
                            targetServerRoot, targetIsFolder, rootIncludedInRename);
                    childGetOp = childEntry.toGetOperation(itemPropertyFilters);
                    childGetOp.setTargetServerItem(childTargetServerItem);
                    childGetOp.setChangeType(ChangeType.RENAME);
                }

                // TODO we include deletes only to add entry to
                // updatedPendingChanges and update them later. We should
                // check how costly it is when we rename folder that
                // contains big deletes subfolder
                if (childEntry.isDeleted()) {
                    continue;
                }

                if (childTargetServerItem.length() > VersionControlConstants.MAX_SERVER_PATH_SIZE) {
                    abort = true;
                    failureList.add(createPathTooLongFailure(childTargetServerItem));
                    break;
                }

                final String childTargetLocalItem = WorkingFolder
                        .getLocalItemForServerItem(childTargetServerItem, wp.getWorkingFolders());

                conflictingItem = (childTargetLocalItem == null || childTargetLocalItem.length() == 0) ? null
                        : lv.getByLocalItem(childTargetLocalItem);

                if (conflictingItem != null
                        && !ServerPath.equals(conflictingItem.getServerItem(), childEntry.getServerItem())) {
                    abort = true;
                    final String format = Messages.getString("LocalDataAccessLayer.ItemExistsExceptionFormat"); //$NON-NLS-1$
                    failureList.add(new Failure(MessageFormat.format(format, targetServerItem),
                            FailureCodes.ITEM_EXISTS_EXCEPTION, SeverityType.ERROR,
                            conflictingItem.getLocalItem()));
                    break;
                }

                if ((childTargetLocalItem == null || childTargetLocalItem.length() == 0)
                        && childGetOp.getChangeType().contains(ChangeType.EDIT)) {
                    abort = true;
                    final String format = Messages
                            .getString("LocalDataAccessLayer.TargetCloakedExceptionFormat"); //$NON-NLS-1$
                    failureList.add(new Failure(MessageFormat.format(format, sourceCurrentServerItem),
                            FailureCodes.TARGET_CLOAKED_EXCEPTION, SeverityType.ERROR,
                            sourceCurrentServerItem));
                    break;
                }
                if (silent) {
                    // we generated all possible warnings, now bail since
                    // it's a silent operation
                    continue;
                }
                childGetOp.setTargetLocalItem(childTargetLocalItem);
                affectedItems.add(childGetOp);
            }
            if (abort) {
                continue;
            }

            // update pending changes
            for (final KeyValuePair<String, LocalPendingChange> updatedPendingChangeInfo : updatedPendingChanges) {
                final String updateServerPath = updatedPendingChangeInfo.getKey();
                final LocalPendingChange updatedPendingChange = updatedPendingChangeInfo.getValue();
                pc.remove(updatedPendingChange);
                updatedPendingChange.setTargetServerItem(updateServerPath);
                pc.pendChange(updatedPendingChange);
            }

            if (!silent) {
                // update local versions of not committed items (adds and
                // branches)
                for (final String originalServerItem : affectedNotCommittedPendingChanges.keySet()) {
                    final LocalPendingChange pendingChange = affectedNotCommittedPendingChanges
                            .get(originalServerItem);
                    final WorkspaceLocalItem addEntry = lv.getByServerItem(originalServerItem, false);
                    if (addEntry != null) {
                        lv.removeByServerItem(originalServerItem, false, true);
                        addEntry.setServerItem(pendingChange.getTargetServerItem());
                        // TODO what about renaming pending branch into not
                        // mapped location?
                        // TODO we already calculated this local path once,
                        // we should store it in
                        // affectedNotCommittedPendingChanges and reuse it
                        addEntry.setLocalItem(WorkingFolder.getLocalItemForServerItem(
                                pendingChange.getTargetServerItem(), wp.getWorkingFolders()));
                        lv.add(addEntry);
                    }
                }
            }
            getOps.addAll(affectedItems);
        }
    }

    for (final Failure failure : failureList) {
        failure.setRequestType(RequestType.RENAME);
    }

    onlineOperationRequired.set(false);
    failures.set(failureList.toArray(new Failure[failureList.size()]));
    return getOps.toArray(new GetOperation[getOps.size()]);
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncQueryIT.java

@Test
public void should_return_entities_for_typed_query_async() throws Exception {
    CompleteBean paul = builder().randomId().name("Paul").age(35L).addFriends("foo", "bar")
            .addFollowers("George", "Jack").addPreference(1, "FR").addPreference(2, "Paris")
            .addPreference(3, "75014").buid();

    CompleteBean john = builder().randomId().name("John").age(34L).addFriends("qux", "twix")
            .addFollowers("Isaac", "Lara").addPreference(1, "US").addPreference(2, "NewYork").buid();

    asyncManager.insert(paul).getImmediately();
    asyncManager.insert(john).getImmediately();

    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<Object> successSpy1 = new AtomicReference<>();
    final AtomicReference<Object> successSpy2 = new AtomicReference<>();

    FutureCallback<Object> successCallBack1 = new FutureCallback<Object>() {
        @Override//from ww  w.jav  a 2s.  c  o m
        public void onSuccess(Object result) {
            successSpy1.getAndSet(result);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    };

    FutureCallback<Object> successCallBack2 = new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            successSpy2.getAndSet(result);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    };

    final RegularStatement selectStar = select().from("CompleteBean").where(eq("id", bindMarker("id")));
    final List<CompleteBean> list1 = asyncManager.typedQuery(CompleteBean.class, selectStar, paul.getId())
            .get(successCallBack1).get();
    final CompleteBean foundJohn = asyncManager.typedQuery(CompleteBean.class, selectStar, john.getId())
            .getFirst(successCallBack2).get();

    latch.await();

    assertThat(list1).hasSize(1);

    CompleteBean foundPaul = list1.get(0);

    Factory factory1 = (Factory) foundPaul;
    @SuppressWarnings("unchecked")
    ProxyInterceptor<CompleteBean> interceptor1 = (ProxyInterceptor<CompleteBean>) factory1.getCallback(0);

    CompleteBean realPaul = (CompleteBean) interceptor1.getTarget();

    assertThat(realPaul.getLabel()).isNull();
    assertThat(realPaul.getWelcomeTweet()).isNull();

    assertThat(realPaul.getName()).isEqualTo(paul.getName());
    assertThat(realPaul.getAge()).isEqualTo(paul.getAge());
    assertThat(realPaul.getFriends()).containsAll(paul.getFriends());
    assertThat(realPaul.getFollowers()).containsAll(paul.getFollowers());
    assertThat(realPaul.getPreferences().get(1)).isEqualTo("FR");
    assertThat(realPaul.getPreferences().get(2)).isEqualTo("Paris");
    assertThat(realPaul.getPreferences().get(3)).isEqualTo("75014");

    Factory factory2 = (Factory) foundJohn;
    @SuppressWarnings("unchecked")
    ProxyInterceptor<CompleteBean> interceptor2 = (ProxyInterceptor<CompleteBean>) factory2.getCallback(0);

    CompleteBean realJohn = (CompleteBean) interceptor2.getTarget();

    assertThat(realJohn.getLabel()).isNull();
    assertThat(realJohn.getWelcomeTweet()).isNull();

    assertThat(realJohn.getName()).isEqualTo(john.getName());
    assertThat(realJohn.getAge()).isEqualTo(john.getAge());
    assertThat(realJohn.getFriends()).containsAll(john.getFriends());
    assertThat(realJohn.getFollowers()).containsAll(john.getFollowers());
    assertThat(realJohn.getPreferences().get(1)).isEqualTo("US");
    assertThat(realJohn.getPreferences().get(2)).isEqualTo("NewYork");

    latch.await();
    Thread.sleep(100);
    assertThat(successSpy1.get()).isNotNull().isInstanceOf(List.class);
    assertThat(successSpy2.get()).isNotNull().isInstanceOf(CompleteBean.class).isNotInstanceOf(Factory.class);
}

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

/**
 * Retrieves the authoritative copy of the working folders for a local
 * workspace.//from ww w. j  a v a 2  s  .  c o  m
 *
 *
 * @param workspace
 *        The local workspace whose working folders should be fetched
 * @return The working folders for the local workspace
 */
public static WorkingFolder[] queryWorkingFolders(final Workspace workspace) {
    final AtomicReference<WorkingFolder[]> toReturn = new AtomicReference<WorkingFolder[]>(null);

    final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
    try {
        transaction.execute(new WorkspacePropertiesTransaction() {
            @Override
            public void invoke(final LocalWorkspaceProperties wp) {
                // Make a deep copy to return to the caller.
                toReturn.set(WorkingFolder.clone(wp.getWorkingFolders()));
            }
        });
    } finally {
        try {
            transaction.close();
        } catch (final IOException e) {
            throw new VersionControlException(e);
        }
    }

    return toReturn.get();
}

From source file:de.schildbach.pte.AbstractEfaProvider.java

@Override
public QueryTripsResult queryTrips(final Location from, final @Nullable Location via, final Location to,
        final Date date, final boolean dep, final @Nullable Set<Product> products,
        final @Nullable Optimize optimize, final @Nullable WalkSpeed walkSpeed,
        final @Nullable Accessibility accessibility, final @Nullable Set<Option> options) throws IOException {
    final HttpUrl.Builder url = tripEndpoint.newBuilder();
    appendXsltTripRequestParameters(url, from, via, to, date, dep, products, optimize, walkSpeed, accessibility,
            options);/* ww  w .  j  av  a 2 s .  co  m*/
    final AtomicReference<QueryTripsResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            try {
                result.set(queryTrips(url.build(), body.byteStream()));
            } catch (final XmlPullParserException x) {
                throw new ParserException("cannot parse xml: " + bodyPeek, x);
            } catch (final RuntimeException x) {
                throw new RuntimeException("uncategorized problem while processing " + url, x);
            }
        }
    };

    if (httpPost)
        httpClient.getInputStream(callback, url.build(), url.build().encodedQuery(),
                "application/x-www-form-urlencoded", httpRefererTrip);
    else
        httpClient.getInputStream(callback, url.build(), httpRefererTrip);

    return result.get();
}

From source file:de.schildbach.pte.AbstractEfaProvider.java

protected QueryTripsResult queryTripsMobile(final Location from, final @Nullable Location via,
        final Location to, final Date date, final boolean dep, final @Nullable Collection<Product> products,
        final @Nullable Optimize optimize, final @Nullable WalkSpeed walkSpeed,
        final @Nullable Accessibility accessibility, final @Nullable Set<Option> options) throws IOException {
    final HttpUrl.Builder url = tripEndpoint.newBuilder();
    appendXsltTripRequestParameters(url, from, via, to, date, dep, products, optimize, walkSpeed, accessibility,
            options);/*from   ww  w.j a  v  a 2 s  . c  o m*/
    final AtomicReference<QueryTripsResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            try {
                result.set(queryTripsMobile(url.build(), from, via, to, body.byteStream()));
            } catch (final XmlPullParserException x) {
                throw new ParserException("cannot parse xml: " + bodyPeek, x);
            } catch (final RuntimeException x) {
                throw new RuntimeException("uncategorized problem while processing " + url, x);
            }
        }
    };

    if (httpPost)
        httpClient.getInputStream(callback, url.build(), url.build().encodedQuery(),
                "application/x-www-form-urlencoded", httpRefererTrip);
    else
        httpClient.getInputStream(callback, url.build(), httpRefererTrip);

    return result.get();
}

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   w w  w  . ja  va  2s .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: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);//  w  w  w .j  a va 2s. co 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);
        }
    }
}