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

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

Introduction

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

Prototype

public AtomicReference() 

Source Link

Document

Creates a new AtomicReference with null initial value.

Usage

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

public static void syncPendingChanges(final Workspace workspace, final GetOperation[] getOperations,
        final String[] itemPropertyFilters) {
    // This method has two goals in its execution. The primary goal is to
    // replace the pending changes for the workspace with those that we just
    // downloaded from the server. The second goal is to make sure that
    // local version rows for uncommitted items are cleaned up if their
    // pending changes have disappeared. The server will have already done
    // this cleanup for us.

    // We can't remove a pending add from PC and its uncommitted local
    // version row from LV in a single transaction since they are in
    // different tables. And we would much rather have an orphaned PC row
    // than an orphaned LV row. So we will get rid of the local version row
    // first in this case. (If there are no rows to clean up from LV, we
    // will not open the table at all.)

    // To do the scan of the GetOperations to check for this condition, we
    // need to have the new pending changes in a tree structure. The
    // LocalPendingChangesTable would do this anyway when we give it the
    // pending changes -- so we'll cheat a little bit here on the
    // encapsulation and do the work for it ahead of time, so we can use the
    // SparseTree for our own check.

    final AtomicReference<GUID> outServerPendingChangeSignature = new AtomicReference<GUID>();

    final PendingChange[] pendingChanges = workspace.getClient().getWebServiceLayer()
            .queryServerPendingChanges(workspace, outServerPendingChangeSignature);

    final GUID serverPendingChangeSignature = outServerPendingChangeSignature.get();

    final SparseTree<LocalPendingChange> pendingChangesTarget = new SparseTree<LocalPendingChange>(
            ServerPath.PREFERRED_SEPARATOR_CHARACTER, String.CASE_INSENSITIVE_ORDER);

    for (final PendingChange pendingChange : pendingChanges) {
        final LocalPendingChange pcEntry = LocalPendingChange.fromPendingChange(pendingChange);
        pendingChangesTarget.set(pcEntry.getTargetServerItem(), pcEntry);
    }// www  .j a v  a2 s. co  m

    if (null != getOperations) {
        final List<KeyValuePair<String, Boolean>> localVersionsToRemove = new ArrayList<KeyValuePair<String, Boolean>>();
        final List<String> localVersionsToUpdate = new ArrayList<String>();

        for (final GetOperation getOp : getOperations) {
            // Make sure any adds still have pending changes. The server
            // will remove the local version row for a pending add when the
            // pending change is removed, and for a pending branch when we
            // are syncing an item on top of it.
            if (getOp.getChangeType().contains(ChangeType.ADD)
                    || (getOp.getChangeType().contains(ChangeType.BRANCH)
                            && null != getOp.getTargetLocalItem())) {
                final LocalPendingChange pcEntry = pendingChangesTarget.get(getOp.getTargetServerItem());
                if (pcEntry == null) {
                    localVersionsToRemove.add(new KeyValuePair<String, Boolean>(getOp.getSourceServerItem(),
                            getOp.getVersionLocal() != 0));
                }
            }

            // if the server pushed an edit to us, we need to update the
            // local version
            if (getOp.getVersionLocal() == -1) {
                localVersionsToUpdate.add(getOp.getSourceServerItem());
            }
        }

        if (localVersionsToRemove.size() > 0 || localVersionsToUpdate.size() > 0) {
            final LocalWorkspaceTransaction lvTrans = new LocalWorkspaceTransaction(workspace);
            try {
                lvTrans.execute(new LocalVersionTransaction() {
                    @Override
                    public void invoke(final WorkspaceVersionTable lv) {
                        for (final KeyValuePair<String, Boolean> item : localVersionsToRemove) {
                            lv.removeByServerItem(item.getKey(), item.getValue(), false);
                        }

                        for (final String serverItem : localVersionsToUpdate) {
                            final WorkspaceLocalItem item = lv.getByServerItem(serverItem, true);

                            if (item != null && item.getVersion() != -1) {
                                lv.removeByServerItem(item.getServerItem(), item.isCommitted(), false);
                                item.setVersion(-1);
                                lv.add(item);
                            }
                        }
                    }
                });
            } finally {
                try {
                    lvTrans.close();
                } catch (final IOException e) {
                    throw new VersionControlException(e);
                }
            }
        }
    }

    final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
    try {
        transaction.execute(new PendingChangesTransaction() {
            @Override
            public void invoke(final LocalPendingChangesTable pc) {
                // The method taking a SparseTree is a violation of
                // encapsulation, but having us build the SparseTree gives
                // us a perf benefit since we need it earlier in the method.
                pc.replacePendingChanges(pendingChangesTarget);
                pc.setClientSignature(serverPendingChangeSignature);
            }
        });
    } finally {
        try {
            transaction.close();
        } catch (final IOException e) {
            throw new VersionControlException(e);
        }
    }
}

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

public static void snapBackToCheckinDate(final Workspace workspace, final GetRequest[] requests) {
    if (null == requests) {
        return;//from   ww  w .  ja va 2 s .c  o m
    }

    final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
    try {
        transaction.execute(new AllTablesTransaction() {
            @Override
            public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv,
                    final LocalPendingChangesTable pc) {
                for (final GetRequest getRequest : requests) {
                    if (null == getRequest) {
                        continue;
                    }

                    Iterable<WorkspaceLocalItem> lvEntrySource = null;

                    if (null == getRequest.getItemSpec()) {
                        // A null ItemSpec indicates that we should match
                        // every item in the workspace.
                        lvEntrySource = lv.queryByLocalItem(null, RecursionType.FULL, null);
                    } else {
                        final AtomicReference<Failure> dummy = new AtomicReference<Failure>();

                        final ParsedItemSpec parsedItemSpec = ParsedItemSpec.fromItemSpec(
                                getRequest.getItemSpec(), wp, lv, pc, ParsedItemSpecOptions.NONE, dummy);

                        if (null != parsedItemSpec) {
                            lvEntrySource = parsedItemSpec.expandFrom(lv, pc, dummy);
                        }
                    }

                    if (null == lvEntrySource) {
                        continue;
                    }

                    for (final WorkspaceLocalItem lvEntry : lvEntrySource) {
                        if (-1 != lvEntry.getCheckinDate()
                                && lvEntry.getCheckinDate() != lvEntry.getLastModifiedTime()) {
                            final LocalPendingChange pcEntry = pc.getByLocalVersion(lvEntry);

                            if ((null == pcEntry || !pcEntry.isEdit())
                                    && new File(lvEntry.getLocalItem()).exists()) {
                                try {
                                    /*
                                     * Potentially the item is read-only
                                     * (probably not, since this is a local
                                     * workspace.) Clear the read-only bit
                                     * in order to set the last-write time.
                                     */
                                    final FileSystemAttributes attrs = FileSystemUtils.getInstance()
                                            .getAttributes(lvEntry.getLocalItem());
                                    boolean restoreReadOnly = false;

                                    if (attrs != null && attrs.isReadOnly()) {
                                        attrs.setReadOnly(false);
                                        FileSystemUtils.getInstance().setAttributes(lvEntry.getLocalItem(),
                                                attrs);
                                        restoreReadOnly = true;
                                    }

                                    // Set the last modified time of the
                                    // item to the check-in date.
                                    new File(lvEntry.getLocalItem()).setLastModified(
                                            DotNETDate.fromWindowsFileTimeUTC(lvEntry.getCheckinDate())
                                                    .getTimeInMillis());

                                    // Put the read-only bit back if we took
                                    // it off.
                                    if (restoreReadOnly) {
                                        attrs.setReadOnly(true);
                                        FileSystemUtils.getInstance().setAttributes(lvEntry.getLocalItem(),
                                                attrs);
                                    }

                                    // Write out that the last mod time is
                                    // now the checkin date.
                                    lvEntry.setLastModifiedTime(lvEntry.getCheckinDate());
                                    lv.setDirty(true);
                                } catch (final Exception ex) {
                                    log.warn("Error snapping back to checkin date", ex); //$NON-NLS-1$
                                }
                            }
                        }
                    }
                }
            }
        });
    } finally {
        try {
            transaction.close();
        } catch (final IOException e) {
            throw new VersionControlException(e);
        }
    }

}

From source file:com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace.java

/**
 * Pend these changes for this workspace on the server.
 *
 * @param requests/*from   w w w .  j  a v  a2  s.c  o  m*/
 *        the requested changes to pend (must not be <code>null</code>)
 * @param getOptions
 *        options that affect how files on disk are treated during
 *        processing (must not be <code>null</code>)
 * @param pendOptions
 *        options that affect how items are pended (must not be
 *        <code>null</code>)
 * @param itemPropertyFilters
 *        a list of versioned item properties to return with each get
 *        operation (may be <code>null</code>)
 * @return the number of changes that were successfully processed by the
 *         server.
 */
private int pendChanges(final ChangeRequest[] requests, final GetOptions getOptions,
        final PendChangesOptions pendOptions, String[] itemPropertyFilters) {
    Check.notNull(requests, "requests"); //$NON-NLS-1$
    Check.notNull(getOptions, "getOptions"); //$NON-NLS-1$
    Check.notNull(pendOptions, "pendOptions"); //$NON-NLS-1$

    // Using web service directly so merge filters configured on client
    itemPropertyFilters = client.mergeWithDefaultItemPropertyFilters(itemPropertyFilters);

    client.getEventEngine()
            .fireOperationStarted(new PendOperationStartedEvent(EventSource.newFromHere(), this, requests));

    if (getClient().getServiceLevel().getValue() < WebServiceLevel.TFS_2012.getValue()) {
        if (hasPropertyChange(requests)) {
            client.getEventEngine().fireNonFatalError(new NonFatalErrorEvent(EventSource.newFromHere(), this,
                    new VersionControlException(Messages.getString("Workspace.PropertyNotSupportedText")))); //$NON-NLS-1$
        }
    }

    int ret = 0;
    try {
        SupportedFeatures features = SupportedFeatures.ALL;

        /*
         * If the get operation "Force Checkout Local Version" is set, we do
         * not advertise to the server that we support get latest on
         * checkout. Presumably, there may be a state where the server
         * wishes to update us to the local version and this explicitly
         * stops that.
         */
        if (pendOptions.contains(PendChangesOptions.FORCE_CHECK_OUT_LOCAL_VERSION)) {
            features = features.remove(SupportedFeatures.GET_LATEST_ON_CHECKOUT);
        }

        final AtomicReference<Failure[]> failures = new AtomicReference<Failure[]>();
        final AtomicBoolean onlineOperation = new AtomicBoolean();
        final AtomicReference<ChangePendedFlags> changePendedFlags = new AtomicReference<ChangePendedFlags>();

        final GetOperation[] operations = client.getWebServiceLayer().pendChanges(getName(), getOwnerName(),
                requests, pendOptions, features, failures, itemPropertyFilters, null, true, onlineOperation,
                changePendedFlags);

        // Get any required files.
        if (operations.length > 0) {

            /*
             * The TFS server (as of TFS 2013 QU1) provides in the response
             * only properties saved in the server's database, i.e. already
             * checked in. Thus, to process the executable bit and symlinks
             * using properties mechanism correctly in the client file
             * system, we have to merge properties received in the response
             * with those submitted in the change request.
             *
             * Note that for the local workspaces it's already done in the
             * LocalDataAccessLayer class.
             */
            if (WorkspaceLocation.SERVER == this.getLocation()
                    && getClient().getServiceLevel().getValue() >= WebServiceLevel.TFS_2012.getValue()) {
                for (final ChangeRequest request : requests) {
                    final PropertyValue[] requestProperties = request.getProperties();
                    if (requestProperties != null) {
                        final GetOperation operation = findMatchingOperation(operations, request);

                        if (operation != null) {
                            final PropertyValue[] operationProperties = operation.getPropertyValues();

                            if (operationProperties != null) {
                                operation.setPropertyValues(PropertyUtils
                                        .mergePendingValues(operationProperties, requestProperties));
                            }
                        }
                    }
                }
            }

            final GetEngine getEngine = new GetEngine(client);

            getEngine.processGetOperations(this, ProcessType.PEND, requests[0].getRequestType(),
                    new GetOperation[][] { operations }, getOptions, false, onlineOperation.get(),
                    changePendedFlags.get());

            // Return the number of operations that were successful.
            ret = operations.length;
        }

        if (changePendedFlags.get().contains(ChangePendedFlags.WORKING_FOLDER_MAPPINGS_UPDATED)) {
            invalidateMappings();
        }

        /*
         * If it was requested by the caller, strip out any Failure objects
         * from the failure set which are of type ItemNotFoundException.
         */
        if (failures.get() != null && failures.get().length > 0
                && pendOptions.contains(PendChangesOptions.SUPPRESS_ITEM_NOT_FOUND_FAILURES)) {
            final List<Failure> otherFailures = new ArrayList<Failure>();

            for (final Failure f : failures.get()) {
                if (f.getCode() == null || !f.getCode().equals(FailureCodes.ITEM_EXISTS_EXCEPTION)) {
                    otherFailures.add(f);
                }
            }

            failures.set(otherFailures.toArray(new Failure[otherFailures.size()]));
        }

        client.reportFailures(this, failures.get());

    } finally {
        client.getEventEngine().fireOperationCompleted(
                new PendOperationCompletedEvent(EventSource.newFromHere(), this, requests));

        Workstation.getCurrent(getClient().getConnection().getPersistenceStoreProvider())
                .notifyForWorkspace(this, Notification.VERSION_CONTROL_PENDING_CHANGES_CHANGED);
    }

    return ret;
}

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

/**
 * Gets information about multiple items. An {@link ItemSet} is returned for
 * each query item./*www. ja  va2 s. c  o  m*/
 *
 * @param itemSpecs
 *        the items to get information about (must not be <code>null</code>
 *        or empty)
 * @param version
 *        the version of each of the items to get information about (not
 *        null)
 * @param deletedState
 *        the deleted state of items (must not be <code>null</code>)
 * @param itemType
 *        the types of matching items that should be returned (must not be
 *        <code>null</code>)
 * @param options
 *        flags that control the amount of information returned for the item
 * @param itemPropertyFilters
 *        a list of versioned item properties to return with each item (may
 *        be <code>null</code>)
 * @return an array of {@link ItemSet} instances, one for each given
 *         {@link ItemSpec} in the original order. May be empty but never
 *         null.
 */
public ItemSet[] getItems(final ItemSpec[] itemSpecs, final VersionSpec version,
        final DeletedState deletedState, final ItemType itemType, final GetItemsOptions options,
        String[] itemPropertyFilters) {
    Check.notNullOrEmpty(itemSpecs, "itemSpecs"); //$NON-NLS-1$

    itemPropertyFilters = mergeWithDefaultItemPropertyFilters(itemPropertyFilters);

    final AtomicReference<String> workspaceName = new AtomicReference<String>();
    final AtomicReference<String> workspaceOwner = new AtomicReference<String>();

    determineWorkspaceNameAndOwner(itemSpecs, workspaceName, workspaceOwner);

    final ItemSet[] sets = getWebServiceLayer().queryItems(workspaceName.get(), workspaceOwner.get(), itemSpecs,
            version, deletedState, itemType, options.contains(GetItemsOptions.DOWNLOAD), options,
            itemPropertyFilters, null);

    /*
     * If the server did not sort the set contents, sort them locally.
     */
    if (options.contains(GetItemsOptions.UNSORTED) == false) {
        for (int i = 0; i < sets.length; i++) {
            /*
             * Sort a temporary copy (using the Item sort logic) and set it
             * back on the object.
             */
            final Item[] items = sets[i].getItems();

            Arrays.sort(items);

            sets[i].setItems(items);
        }
    }

    return sets;
}

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

public static LocalVersion[][] queryLocalVersions(final Workspace workspace, final ItemSpec[] itemSpecs) {
    final LocalVersion[][] toReturn = new LocalVersion[itemSpecs.length][];

    final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
    try {/*from  w  w  w  . j  a v a  2s .c om*/
        transaction.execute(new WorkspacePropertiesLocalVersionTransaction() {
            @Override
            public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv) {
                for (int i = 0; i < itemSpecs.length; i++) {
                    final List<LocalVersion> localVersions = new ArrayList<LocalVersion>();
                    final AtomicReference<Failure> dummy = new AtomicReference<Failure>();

                    final ParsedItemSpec parsedItemSpec = ParsedItemSpec.fromLocalItemSpec(itemSpecs[i], wp, lv,
                            null, ParsedItemSpecOptions.NONE, dummy, false);

                    if (null != parsedItemSpec) {
                        for (final WorkspaceLocalItem lvEntry : parsedItemSpec.expandFrom(lv, null, dummy)) {
                            localVersions.add(new LocalVersion(lvEntry.getLocalItem(), lvEntry.getVersion()));
                        }
                    }

                    toReturn[i] = localVersions.toArray(new LocalVersion[localVersions.size()]);
                }
            }
        });
    } finally {
        try {
            transaction.close();
        } catch (final IOException e) {
            throw new VersionControlException(e);
        }
    }

    return toReturn;
}

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

/**
 * Creates ExtendedItems using locally stored data.
 *///from  w w  w.  j av a  2s . c o  m
public static ExtendedItem[][] queryItemsExtended(final Workspace workspace, final ItemSpec[] items,
        final DeletedState deletedState, final ItemType itemType, final GetItemsOptions options) {
    final ExtendedItem[][] toReturn = new ExtendedItem[items.length][];
    final AtomicReference<Failure> dummy = new AtomicReference<Failure>();

    final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
    try {
        transaction.execute(new AllTablesTransaction() {
            @Override
            public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv,
                    final LocalPendingChangesTable pc) {
                workspace.getWorkspaceWatcher().scan(wp, lv, pc);

                for (int i = 0; i < items.length; i++) {
                    final List<ExtendedItem> extendedItems = new ArrayList<ExtendedItem>();
                    final ParsedItemSpec parsedItemSpec = ParsedItemSpec.fromItemSpec(items[i], wp, lv, pc,
                            ParsedItemSpecOptions.INCLUDE_DELETED, dummy);

                    // If the item is deleted, the result is an empty list
                    if (null != parsedItemSpec && deletedState != DeletedState.DELETED) {
                        for (final WorkspaceLocalItem lvEntry : parsedItemSpec.expandFrom(lv, pc, dummy)) {
                            final LocalPendingChange pcEntry = pc.getByLocalVersion(lvEntry);

                            // We ignore deletedState here because all items
                            // we find would be treated as non-deleted
                            // anyway (an item with a pending change is
                            // non-deleted)
                            if (ParsedItemSpec.matchItemType(lvEntry, itemType)) {
                                extendedItems.add(new ExtendedItem(pc, lvEntry, pcEntry));
                            }
                        }
                    }

                    toReturn[i] = extendedItems.toArray(new ExtendedItem[extendedItems.size()]);
                }
            }
        });
    } finally {
        try {
            transaction.close();
        } catch (final IOException e) {
            throw new VersionControlException(e);
        }
    }

    return toReturn;
}

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

/**
 * Gets extended information about items, with full results control.
 *
 * @param workspaceName/*  w ww  .  j a v  a 2 s .  c o m*/
 *        the name of the workspace to get extended information for. If the
 *        paths in the itemSpecs are server paths, this parameter is ignored
 *        (may be null). If this parameter is null and the itemSpec paths
 *        are local, the correct local workspace is determined
 *        automatically.
 * @param workspaceOwner
 *        the owner of the workspace to get extended information for. If the
 *        paths in the itemSpecs are server paths, this parameter is ignored
 *        (may be null). If this parameter is null and the itemSpec paths
 *        are local, the correct local workspace is determined
 *        automatically.
 * @param itemSpecs
 *        instances of {@link ItemSpec} that describe the item sets you want
 *        returned. One {@link ItemSet} will be returned for each
 *        {@link ItemSpec} (must not be <code>null</code> or empty)
 * @param deletedState
 *        the deleted state of items you want to list (must not be
 *        <code>null</code>)
 * @param itemType
 *        the types of items you want to list (must not be <code>null</code>
 *        )
 * @param options
 *        the {@link GetItemsOptions} which control the returned results
 *        (must not be <code>null</code>)
 * @param itemPropertyFilters
 *        a list of versioned item properties to return with each extended
 *        item (may be <code>null</code>)
 * @return an array of {@link ExtendedItem} arrays, each outer array
 *         representing one given {@link ItemSpec}, and each inner array
 *         representing the matches found for those {@link ItemSpec}s
 *         (should be only one object in these inner arrays because
 *         recursion is not an option). Inner arrays may be empty but are
 *         never null.
 */
public ExtendedItem[][] getExtendedItems(String workspaceName, String workspaceOwner,
        final ItemSpec[] itemSpecs, final DeletedState deletedState, final ItemType itemType,
        final GetItemsOptions options, String[] itemPropertyFilters) {
    Check.notNullOrEmpty(itemSpecs, "itemSpecs"); //$NON-NLS-1$
    Check.notNull(deletedState, "deletedState"); //$NON-NLS-1$
    Check.notNull(itemType, "itemType"); //$NON-NLS-1$
    Check.notNull(options, "options"); //$NON-NLS-1$

    itemPropertyFilters = mergeWithDefaultItemPropertyFilters(itemPropertyFilters);

    if (options.contains(GetItemsOptions.UNSORTED) || options.contains(GetItemsOptions.DOWNLOAD)) {
        throw new VersionControlException(MessageFormat.format(
                Messages.getString("VersionControlClient.TheUnsortedAndDownloadOptionsAreNotAllowedFormat"), //$NON-NLS-1$
                GetItemsOptions.UNSORTED.toString(), GetItemsOptions.DOWNLOAD.toString()));
    }

    /*
     * Detect the correct local workspace if none was supplied. Only works
     * if the paths are local paths. For server paths, a null name and owner
     * is returned, and sending that to the server results in less
     * information returned (no version info, etc.).
     */
    if (workspaceName == null && workspaceOwner == null) {
        final AtomicReference<String> workspaceNameHolder = new AtomicReference<String>();
        final AtomicReference<String> workspaceOwnerHolder = new AtomicReference<String>();

        determineWorkspaceNameAndOwner(itemSpecs, workspaceNameHolder, workspaceOwnerHolder);

        workspaceName = workspaceNameHolder.get();
        workspaceOwner = workspaceOwnerHolder.get();
    }

    return getWebServiceLayer().queryItemsExtended(workspaceName, workspaceOwner, itemSpecs, deletedState,
            itemType, options, itemPropertyFilters);
}

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

/**
 * Queries the server for history about an item. History items are returned
 * as an array of changesets.//from  ww w . j ava 2s . c o m
 *
 * @param serverOrLocalPath
 *        the server or local path to the server item being queried for its
 *        history (must not be <code>null</code> or empty).
 * @param version
 *        the version of the item to query history for (history older than
 *        this version will be returned) (must not be <code>null</code>)
 * @param deletionID
 *        the deletion ID for the item, if it is a deleted item (pass 0 if
 *        the item is not deleted).
 * @param recursion
 *        whether to query recursively (must not be <code>null</code>)
 * @param user
 *        only include historical changes made by this user (pass null to
 *        retrieve changes made by all users).
 * @param versionFrom
 *        the beginning version to query historical changes from (pass null
 *        to start at the first version).
 * @param versionTo
 *        the ending version to query historical changes to (pass null to
 *        end at the most recent version).
 * @param maxCount
 *        the maximum number of changes to return (pass Integer.MAX_VALUE
 *        for all available values). Must be > 0.
 * @param includeFileDetails
 *        true to include individual file change details with the returned
 *        results, false to return only general changeset information.
 * @param slotMode
 *        if true, all items that have occupied the given serverPath (during
 *        different times) will have their changes returned. If false, only
 *        the item that matches that path at the given version will have its
 *        changes returned.
 * @param sortAscending
 *        when <code>true</code> gets the top maxCount changes in ascending
 *        order, when <code>false</code> gets them in descending order
 * @return the changesets that matched the history query, null if the server
 *         did not return a changeset array.
 */
public Changeset[] queryHistory(final String serverOrLocalPath, final VersionSpec version, final int deletionID,
        final RecursionType recursion, final String user, final VersionSpec versionFrom,
        final VersionSpec versionTo, int maxCount, final boolean includeFileDetails, final boolean slotMode,
        final boolean includeDownloadInfo, final boolean sortAscending) throws ServerPathFormatException {
    Check.notNullOrEmpty(serverOrLocalPath, "serverOrLocalPath"); //$NON-NLS-1$
    Check.notNull(version, "version"); //$NON-NLS-1$
    Check.notNull(recursion, "recursion"); //$NON-NLS-1$
    Check.isTrue(maxCount > 0, "maxCount must be greater than 0"); //$NON-NLS-1$

    final AtomicReference<String> workspaceName = new AtomicReference<String>();
    final AtomicReference<String> workspaceOwner = new AtomicReference<String>();

    determineWorkspaceNameAndOwner(serverOrLocalPath, workspaceName, workspaceOwner);

    /*
     * Local paths require valid workspace name and owner.
     */
    if ((workspaceName.get() == null || workspaceOwner.get() == null)
            && ServerPath.isServerPath(serverOrLocalPath) == false) {
        Check.isTrue(false, MessageFormat.format("Could not determine the workspace for local path {0}", //$NON-NLS-1$
                serverOrLocalPath));
    }

    final ItemSpec spec = new ItemSpec(serverOrLocalPath, recursion, deletionID);

    final VersionSpec fromSpec = (versionFrom != null) ? versionFrom : new ChangesetVersionSpec(1);

    VersionSpec endVersion = versionTo;

    final ArrayList<Changeset> foundChangeSets = new ArrayList<Changeset>();

    /*
     * Changesets come in newest first (reverse chronological order).
     *
     * Fetch the changesets in chunks of HISTORY_ITEMS_CHUNK_SIZE. If we've
     * hit maxCount, or we've hit the first changeset (number 1), or the
     * server sent us fewer changesets than we expected (including 0), we
     * quit and return the results to the user.
     *
     * We decrement maxCount as our counter. chunk is kept just for tracing.
     */
    int chunk = 1;
    while (maxCount > 0) {
        if (log.isDebugEnabled()) {
            log.debug(MessageFormat.format("chunk {0}, maxCount {1}", //$NON-NLS-1$
                    Integer.toString(chunk++), Integer.toString(maxCount)));
        }

        // NOTE chunk is just for tracing, it only gets incremented when
        // debug is enabled.

        final int requestedCount = Math.min(maxCount, HISTORY_ITEMS_CHUNK_SIZE);

        if (log.isDebugEnabled()) {
            log.debug(MessageFormat.format("requestedCount {0}", Integer.toString(requestedCount))); //$NON-NLS-1$
        }

        if (log.isDebugEnabled()) {
            log.debug(
                    MessageFormat.format("requesting from {0} to {1}", ((fromSpec != null) ? fromSpec.toString() //$NON-NLS-1$
                            : "null"), ((endVersion != null) ? endVersion.toString() : "null"))); //$NON-NLS-1$ //$NON-NLS-2$
        }

        final Changeset[] sets = getWebServiceLayer().queryHistory(workspaceName.get(), workspaceOwner.get(),
                spec, version, user, fromSpec, endVersion, requestedCount, includeFileDetails,
                includeDownloadInfo, slotMode, sortAscending);

        if (sets == null) {
            log.debug("got null history sets"); //$NON-NLS-1$
            return null;
        }

        if (sets.length == 0) {
            log.debug("got empty history sets"); //$NON-NLS-1$
            break;
        }

        // if the user asked for the changes, sort them
        if (includeFileDetails) {
            for (final Changeset set : sets) {
                set.sortChanges();
            }
        }

        // Add all to the list
        foundChangeSets.addAll(Arrays.asList(sets));

        if (log.isDebugEnabled()) {
            log.debug(MessageFormat.format("got {0} history sets", sets.length)); //$NON-NLS-1$
        }

        /*
         * If the server sent us fewer than we had hoped, we should break,
         * because we're done.
         */
        if (sets.length < requestedCount) {
            log.debug("got less than a full chunk so exiting"); //$NON-NLS-1$
            break;
        }

        /*
         * Save the change set number of the last item in the list (which is
         * the oldest, chronologically), so we can create the end version
         * spec for the next time through the loop.
         */
        final int lastChangesetID = sets[sets.length - 1].getChangesetID();

        /*
         * This check saves us from asking for any more changesets when we
         * know we're done.
         */
        if (lastChangesetID == 1) {
            break;
        }

        /*
         * Decrement the counter by the number we just got, and set up the
         * end version for the next query.
         */
        maxCount -= sets.length;
        endVersion = new ChangesetVersionSpec(lastChangesetID - 1);
    }

    return foundChangeSets.toArray(new Changeset[foundChangeSets.size()]);
}

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

/**
 * Queries the server for history about an item. Results are returned as an
 * {@link Iterator} of {@link Changeset}s.
 *
 * @param serverOrLocalPath//  w ww  . j a v a2 s.c om
 *        the server or local path to the server item being queried for its
 *        history (must not be <code>null</code> or empty).
 * @param version
 *        the version of the item to query history for (history older than
 *        this version will be returned) (must not be <code>null</code>)
 * @param deletionID
 *        the deletion ID for the item, if it is a deleted item (pass 0 if
 *        the item is not deleted).
 * @param recursion
 *        whether to query recursively (must not be <code>null</code>)
 * @param user
 *        only include historical changes made by this user (pass null to
 *        retrieve changes made by all users).
 * @param versionFrom
 *        the beginning version to query historical changes from (pass null
 *        to start at the first version).
 * @param versionTo
 *        the ending version to query historical changes to (pass null to
 *        end at the most recent version).
 * @param maxCount
 *        the maximum number of changes to return (pass Integer.MAX_VALUE
 *        for all available values). Must be > 0.
 * @param includeFileDetails
 *        true to include individual file change details with the returned
 *        results, false to return only general changeset information.
 * @param slotMode
 *        if true, all items that have occupied the given serverPath (during
 *        different times) will have their changes returned. If false, only
 *        the item that matches that path at the given version will have its
 *        changes returned.
 * @param sortAscending
 *        when <code>true</code> gets the top maxCount changes in ascending
 *        order, when <code>false</code> gets them in descending order
 * @return the changesets that matched the history query, null if the server
 *         did not return a changeset array.
 */
public Iterator<Changeset> queryHistoryIterator(final String serverOrLocalPath, final VersionSpec version,
        final int deletionID, final RecursionType recursion, final String user, final VersionSpec versionFrom,
        final VersionSpec versionTo, final int maxCount, final boolean includeFileDetails,
        final boolean slotMode, final boolean includeDownloadInfo, final boolean sortAscending)
        throws ServerPathFormatException {
    Check.notNullOrEmpty(serverOrLocalPath, "serverOrLocalPath"); //$NON-NLS-1$
    Check.notNull(version, "version"); //$NON-NLS-1$
    Check.notNull(recursion, "recursion"); //$NON-NLS-1$
    Check.isTrue(maxCount > 0, "maxCount must be greater than 0"); //$NON-NLS-1$

    final AtomicReference<String> workspaceName = new AtomicReference<String>();
    final AtomicReference<String> workspaceOwner = new AtomicReference<String>();

    determineWorkspaceNameAndOwner(serverOrLocalPath, workspaceName, workspaceOwner);

    /*
     * Local paths require valid workspace name and owner.
     */
    if ((workspaceName.get() == null || workspaceOwner.get() == null)
            && ServerPath.isServerPath(serverOrLocalPath) == false) {
        Check.isTrue(false, MessageFormat.format("Could not determine the workspace for local path {0}", //$NON-NLS-1$
                serverOrLocalPath));
    }

    final ItemSpec itemSpec = new ItemSpec(serverOrLocalPath, recursion, deletionID);

    final HistoryIterator iterator = new HistoryIterator(getWebServiceLayer(), workspaceName.get(),
            workspaceOwner.get(), itemSpec, version, user, versionFrom, versionTo, maxCount, includeFileDetails,
            includeDownloadInfo, slotMode, sortAscending);

    iterator.prime();

    return iterator;
}

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

public static void processConversionBaselineRequests(final Workspace workspace,
        final Iterable<BaselineRequest> requests) throws CoreCancelException {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$
    Check.notNull(requests, "requests"); //$NON-NLS-1$

    final AtomicReference<BaselineFolderCollection> baselineFolderCollection = new AtomicReference<BaselineFolderCollection>();

    LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
    try {// w w  w .  j  a  va  2s.co m
        transaction.execute(new WorkspacePropertiesTransaction() {
            @Override
            public void invoke(final LocalWorkspaceProperties wp) {
                baselineFolderCollection.set(new BaselineFolderCollection(workspace, wp.getBaselineFolders()));
            }
        });
    } finally {
        try {
            transaction.close();
        } catch (final IOException e) {
            throw new VersionControlException(e);
        }
    }

    final AtomicReference<Iterable<BaselineRequest>> failedLocal = new AtomicReference<Iterable<BaselineRequest>>();

    baselineFolderCollection.get().processBaselineRequests(workspace, requests, true /* throwIfCanceled */,
            failedLocal);

    boolean hasAnyFailed = false;
    if (failedLocal.get() != null) {
        for (final BaselineRequest r : failedLocal.get()) {
            if (r != null) {
                hasAnyFailed = true;
                break;
            }
        }
    }

    if (hasAnyFailed) {
        /*
         * The set of BaselineRequests which had a populated LocalItem,
         * indicating that the content on the local disk is the committed
         * content. However, we hashed the content while gzipping it, and
         * found that the hash value did not match. (The length matched, or
         * we would not have put a local item on the BaselineRequest.) As a
         * result, we fell back to the download URL to fetch this content.
         *
         * We need to go back through this list and mark the corresponding
         * local version entries with a LastModifiedTime of -1 so that when
         * the scanner runs, these items are hashed again and discovered as
         * pending edits.
         */

        transaction = new LocalWorkspaceTransaction(workspace);
        try {
            transaction.execute(new LocalVersionTransaction() {

                @Override
                public void invoke(final WorkspaceVersionTable lv) {
                    for (final BaselineRequest request : failedLocal.get()) {
                        final WorkspaceLocalItem lvEntry = lv.getByLocalItem(request.getSourceLocalItem());

                        if (null != lvEntry) {
                            lv.removeByLocalItem(request.getSourceLocalItem(), false);
                            lvEntry.setLastModifiedTime(-1);
                            lv.add(lvEntry);
                        }
                    }
                }
            });
        } finally {
            try {
                transaction.close();
            } catch (final IOException e) {
                throw new VersionControlException(e);
            }
        }
    }
}