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: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 {//from  www.j a v  a2s.c om
        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);
            }
        }
    }
}

From source file:com.scb.edmhdpif.processors.RowIdDBSTest.java

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();// w  w  w .  j  a  v a 2 s . c  om

    if (flowFile == null) {
        return;
    }

    final StopWatch stopWatch = new StopWatch(true);
    final char inputDelimiter = replaceDelimiter(
            context.getProperty(INPUT_DELIMITER).evaluateAttributeExpressions().getValue());
    final String geofile = context.getProperty(GeoFile).evaluateAttributeExpressions(flowFile).getValue();
    final String dlon = context.getProperty(DLon).evaluateAttributeExpressions(flowFile).getValue();
    final String dlat = context.getProperty(DLat).evaluateAttributeExpressions(flowFile).getValue();
    final String plon = context.getProperty(PLon).evaluateAttributeExpressions(flowFile).getValue();
    final String plat = context.getProperty(PLat).evaluateAttributeExpressions(flowFile).getValue();
    GeoUtil.setFilePath(geofile);

    try {
        AtomicReference<Long> totalRowCount = new AtomicReference<>();
        AtomicReference<String> fromcellvalue = new AtomicReference<>();
        AtomicReference<String> tocellvalue = new AtomicReference<>();
        AtomicReference<String> rowidvalue = new AtomicReference<>();
        AtomicReference<ArrayList<String>> provEvents = new AtomicReference<>();

        flowFile = session.write(flowFile, new StreamCallback() {
            @Override
            public void process(final InputStream rawIn, final OutputStream rawOut) throws IOException {

                try (final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(rawOut));
                        final BufferedReader reader = new BufferedReader(new InputStreamReader(rawIn))) {
                    long rowcount = 0;
                    String fromcell = "";
                    String tocell = "";
                    String rowId = "";
                    String line = "";
                    ArrayList<String> rowIds = new ArrayList<>();

                    while ((line = reader.readLine()) != null) {
                        rowcount++;
                        rowId = Long.toString(rowcount) + "_"
                                + Long.toString(DateTime.now(DateTimeZone.UTC).getMillis()) + "_"
                                + UUID.randomUUID().toString();

                        //--------------------------------------------------
                        double pickup_latitude = 0;
                        double pickup_longitude = 0;
                        double dropoff_latitude = 0;
                        double dropoff_longitude = 0;

                        try {
                            pickup_longitude = Double.valueOf(plon);
                            pickup_latitude = Double.valueOf(plat);
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        }

                        try {
                            dropoff_longitude = Double.valueOf(dlon);
                            dropoff_latitude = Double.valueOf(dlat);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }

                        try {

                            GeoUtil geo = GeoUtil.getInstance();

                            if (geo.contain(pickup_longitude, pickup_latitude)) {
                                fromcell = geo.getCellId();
                            } else {
                                fromcell = "OutLiner";
                            }

                            if (geo.contain(dropoff_longitude, dropoff_latitude)) {
                                tocell = geo.getCellId();
                            } else {
                                tocell = "OutLiner";
                            }
                            //--------------------------------------------------
                        } catch (Exception j) {
                            j.printStackTrace();
                        }

                        writer.write(rowId + inputDelimiter + line + inputDelimiter + fromcell + inputDelimiter
                                + tocell);
                        writer.newLine();
                        rowIds.add(rowId);
                    }
                    provEvents.set(rowIds);
                    totalRowCount.set(rowcount);
                    fromcellvalue.set(fromcell);
                    tocellvalue.set(tocell);
                    rowidvalue.set(rowId);
                    writer.flush();
                }
            }
        });
        stopWatch.stop();
        flowFile = session.putAttribute(flowFile, TOTAL_ROW_COUNT, totalRowCount.get().toString());
        flowFile = session.putAttribute(flowFile, FROM_CELL, fromcellvalue.get().toString());
        flowFile = session.putAttribute(flowFile, TO_CELL, tocellvalue.get().toString());
        flowFile = session.putAttribute(flowFile, ROW_ID, rowidvalue.get().toString());
        flowFile = session.putAttribute(flowFile, ROW_ID_ADDED, "true");
        final String tableName = flowFile.getAttribute("tablename");
        for (final String rowId : provEvents.get()) {
            final String provEvent = rowId + "," + tableName;
            session.getProvenanceReporter().modifyContent(flowFile, provEvent);
        }
        session.getProvenanceReporter().modifyContent(flowFile, stopWatch.getDuration(TimeUnit.MILLISECONDS));
        session.transfer(flowFile, REL_SUCCESS);

    } catch (final ProcessException e) {
        session.transfer(flowFile, REL_FAILURE);
        throw e;
    }
}

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

/**
 * Sends the given updates to the server.
 *
 * @param updates//from  w w w.j  av a 2  s.co  m
 *        the updates to send (must not be <code>null</code>)
 */
private IPopulatableLocalVersionUpdate[] sendToServer(final ILocalVersionUpdate[] updates) {
    Check.notNull(updates, "updates"); //$NON-NLS-1$

    log.debug(MessageFormat.format("Sending {0} updates to the server (options={1})", //$NON-NLS-1$
            Integer.toString(updates.length), options));

    if (updates.length == 0) {
        return null;
    }

    final AtomicReference<IPopulatableLocalVersionUpdate[]> updatesMissingBaselines = new AtomicReference<IPopulatableLocalVersionUpdate[]>();

    if (workspace.getLocation() == WorkspaceLocation.LOCAL
            && options.contains(UpdateLocalVersionQueueOptions.UPDATE_LOCAL)) {
        /*
         * We cannot perform baseline folder maintenance with the LV or PC
         * tables open. The baseline folder maintenance could cause them to
         * move.
         */
        final LocalWorkspaceTransaction baselineMaintTransaction = new LocalWorkspaceTransaction(workspace,
                wLock);
        try {
            baselineMaintTransaction.execute(new WorkspacePropertiesTransaction() {
                @Override
                public void invoke(final LocalWorkspaceProperties wp) {
                    wp.doBaselineFolderMaintenance();
                }
            });
        } finally {
            try {
                baselineMaintTransaction.close();
            } catch (final IOException e) {
                throw new VersionControlException(e);
            }
        }

        /*
         * Must run while synchronized(this) because
         * persistedDisplacedBaselines is accessed.
         */
        synchronized (this) {
            final LocalWorkspaceTransaction updateTransaction = new LocalWorkspaceTransaction(workspace, wLock);
            try {
                updateTransaction.execute(new AllTablesTransaction() {
                    @Override
                    public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv,
                            final LocalPendingChangesTable pc) {
                        if (options.contains(UpdateLocalVersionQueueOptions.UPDATE_SERVER)) {
                            ILocalVersionUpdate[] acks;

                            synchronized (pendingAcks) {
                                acks = pendingAcks.toArray(new ILocalVersionUpdate[pendingAcks.size()]);
                                pendingAcks.clear();
                            }

                            if (acks.length > 0) {
                                LocalDataAccessLayer.acknowledgeUpdateLocalVersion(lv, acks);
                            }
                        }

                        LocalDataAccessLayer.updateLocalVersion(workspace, wp, lv, pc, updates,
                                persistedDisplacedBaselines, updatesMissingBaselines);
                    }
                });
            } finally {
                try {
                    updateTransaction.close();
                } catch (final IOException e) {
                    throw new VersionControlException(e);
                }
            }
        }
    }

    if (options.contains(UpdateLocalVersionQueueOptions.UPDATE_SERVER)) {
        workspace.getClient().getWebServiceLayer().updateLocalVersion(workspace.getName(),
                workspace.getOwnerName(), updates);

        if (options.contains(UpdateLocalVersionQueueOptions.UPDATE_LOCAL)
                && WorkspaceLocation.LOCAL == workspace.getLocation()) {
            synchronized (pendingAcks) {
                for (final ILocalVersionUpdate update : updates) {
                    pendingAcks.add(update);
                }
            }
        }
    }

    return updatesMissingBaselines.get();
}

From source file:de.hybris.platform.servicelayer.tx.ItemModelTransactionTest.java

@Test
public void testManualInvalidationInsideTxRollbacking() throws Exception {
    if (Config.isHSQLDBUsed()) {
        return; //should work, but doesn't at the moment. thomas has stacktrace from bamboo. it hangs inside hsqldb
    }//  ww w  . j  a  v a2  s . c  o m
    final MediaModel media = setupMedia("cat", "media", MIME_BEFORE);
    final Media jaloMedia = modelService.getSource(media);
    final PK mediaPK = media.getPk();
    assertEquals(mediaPK, jaloMedia.getPK());

    // check before
    assertEquals(MIME_BEFORE, media.getMime());
    assertEquals(MIME_BEFORE, jaloMedia.getMime());
    // read in other thread
    String[] outerMimes = getMimeFromOtherThread(mediaPK);
    assertEquals(MIME_BEFORE, outerMimes[0]);
    assertEquals(MIME_BEFORE, outerMimes[1]);
    // read direct
    assertEquals(MIME_BEFORE, readMimeViaJDBC(mediaPK));

    final Transaction tx = Transaction.current();
    final AtomicReference<Exception> rollbackExc = new AtomicReference<Exception>(null);
    try {
        tx.execute(//
                new TransactionBody() {

                    @Override
                    public Object execute() throws Exception {
                        // check before (again) inside tx
                        assertEquals(MIME_BEFORE, media.getMime());
                        assertEquals(MIME_BEFORE, jaloMedia.getMime());
                        // read direct inide tx
                        assertEquals(MIME_BEFORE, readMimeViaJDBC(mediaPK));

                        // update direct (not committed) -> caches stay untouched
                        changeMimeViaJDBC(mediaPK, MIME_AFTER);
                        // read direct again inside tx
                        assertEquals(MIME_AFTER, readMimeViaJDBC(mediaPK));
                        // read direct again outside tx
                        assertEquals(MIME_BEFORE, readMimeViaJDBC(mediaPK, false));

                        // must have the old values here
                        assertEquals(MIME_BEFORE, jaloMedia.getMime());
                        assertEquals(MIME_BEFORE, media.getMime());
                        modelService.refresh(media); // even after refreshing !
                        assertEquals(MIME_BEFORE, media.getMime());
                        // read in other thread
                        String[] outerMimes = getMimeFromOtherThread(mediaPK);
                        assertEquals(MIME_BEFORE, outerMimes[0]);
                        assertEquals(MIME_BEFORE, outerMimes[1]);

                        // now invalidate manually -> should be only effective inside this tx !!!
                        Utilities.invalidateCache(mediaPK);

                        // jalo must show new value immediately
                        assertEquals(MIME_AFTER, jaloMedia.getMime());
                        // model is still old but that's correct since it has not been refreshed yet
                        assertEquals(MIME_BEFORE, media.getMime());
                        modelService.refresh(media); // now refresh
                        assertEquals(MIME_AFTER, media.getMime());
                        // read in other thread-> both must show old value
                        outerMimes = getMimeFromOtherThread(mediaPK);
                        assertEquals(MIME_BEFORE, outerMimes[0]);
                        assertEquals(MIME_BEFORE, outerMimes[1]);

                        final RuntimeException ex = new RuntimeException("rollback please");
                        rollbackExc.set(ex);
                        throw ex;
                    }
                });
    } catch (final Exception e) {
        assertEquals(rollbackExc.get(), e);
    }
    // after commit all values must be correct
    assertEquals(MIME_BEFORE, readMimeViaJDBC(mediaPK));
    assertEquals(MIME_BEFORE, jaloMedia.getMime());
    // please note that media *is stale* after rollback !!!
    assertEquals(MIME_AFTER, media.getMime());
    modelService.refresh(media); // now refresh should correct it
    assertEquals(MIME_BEFORE, media.getMime());
    // read in other thread-> both must show old value
    outerMimes = getMimeFromOtherThread(mediaPK);
    assertEquals(MIME_BEFORE, outerMimes[0]);
    assertEquals(MIME_BEFORE, outerMimes[1]);
}

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

private NearbyLocationsResult nearbyStationsRequest(final String stationId, final int maxLocations)
        throws IOException {
    final HttpUrl.Builder url = departureMonitorEndpoint.newBuilder();
    appendCommonRequestParams(url, "XML");
    url.addEncodedQueryParameter("type_dm", "stop");
    url.addEncodedQueryParameter("name_dm",
            ParserUtils.urlEncode(normalizeStationId(stationId), requestUrlEncoding));
    url.addEncodedQueryParameter("itOptionsActive", "1");
    url.addEncodedQueryParameter("ptOptionsActive", "1");
    if (useProxFootSearch)
        url.addEncodedQueryParameter("useProxFootSearch", "1");
    url.addEncodedQueryParameter("mergeDep", "1");
    url.addEncodedQueryParameter("useAllStops", "1");
    url.addEncodedQueryParameter("mode", "direct");
    final AtomicReference<NearbyLocationsResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override//from  ww  w.j a va 2 s. co  m
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            try {
                final XmlPullParser pp = parserFactory.newPullParser();
                pp.setInput(body.byteStream(), null); // Read encoding from XML declaration
                final ResultHeader header = enterItdRequest(pp);

                XmlPullUtil.enter(pp, "itdDepartureMonitorRequest");

                final AtomicReference<Location> ownStation = new AtomicReference<>();
                final List<Location> stations = new ArrayList<>();

                final String nameState = processItdOdv(pp, "dm", new ProcessItdOdvCallback() {
                    @Override
                    public void location(final String nameState, final Location location,
                            final int matchQuality) {
                        if (location.type == LocationType.STATION) {
                            if ("identified".equals(nameState))
                                ownStation.set(location);
                            else if ("assigned".equals(nameState))
                                stations.add(location);
                        } else {
                            throw new IllegalStateException("cannot handle: " + location.type);
                        }
                    }
                });

                if ("notidentified".equals(nameState)) {
                    result.set(new NearbyLocationsResult(header, NearbyLocationsResult.Status.INVALID_ID));
                    return;
                }

                if (ownStation.get() != null && !stations.contains(ownStation))
                    stations.add(ownStation.get());

                if (maxLocations == 0 || maxLocations >= stations.size())
                    result.set(new NearbyLocationsResult(header, stations));
                else
                    result.set(new NearbyLocationsResult(header, stations.subList(0, maxLocations)));
            } catch (final XmlPullParserException x) {
                throw new ParserException("cannot parse xml: " + bodyPeek, x);
            }
        }
    };

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

    return result.get();
}

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

/**
 * Given a local workspace, returns all pending changes for that workspace
 * by calling QueryPendingSets on the server. Also returns the current
 * pending change signature from the server.
 *///from w w w .  j  a  v a2 s .  c  om
@Override
public PendingChange[] queryServerPendingChanges(final Workspace localWorkspace,
        final AtomicReference<GUID> outServerPendingChangeSignature) {
    Check.isTrue(WorkspaceLocation.LOCAL == localWorkspace.getLocation(),
            "WorkspaceLocation.LOCAL == localWorkspace.getLocation()"); //$NON-NLS-1$

    Failure[] failures;
    PendingSet[] pendingSets;

    final ItemSpec[] itemSpecs = new ItemSpec[] { new ItemSpec(ServerPath.ROOT, RecursionType.FULL) };

    try {
        if (getServiceLevel().getValue() >= WebServiceLevel.TFS_2012_QU1.getValue()) {
            final _Repository5Soap_QueryPendingSetsWithLocalWorkspacesResponse response = getRepository5()
                    .queryPendingSetsWithLocalWorkspaces(null, null, localWorkspace.getName(),
                            localWorkspace.getOwnerName(),
                            (_ItemSpec[]) WrapperUtils.unwrap(_ItemSpec.class, itemSpecs),
                            false /* generateDownloadUrls */, null,
                            VersionControlConstants.MAX_SERVER_PATH_SIZE);

            pendingSets = (PendingSet[]) WrapperUtils.wrap(PendingSet.class,
                    response.getQueryPendingSetsWithLocalWorkspacesResult());

            failures = (Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures());
        } else {
            final _Repository4Soap_QueryPendingSetsWithLocalWorkspacesResponse response = getRepository4()
                    .queryPendingSetsWithLocalWorkspaces(null, null, localWorkspace.getName(),
                            localWorkspace.getOwnerName(),
                            (_ItemSpec[]) WrapperUtils.unwrap(_ItemSpec.class, itemSpecs),
                            false /* generateDownloadUrls */, null);

            pendingSets = (PendingSet[]) WrapperUtils.wrap(PendingSet.class,
                    response.getQueryPendingSetsWithLocalWorkspacesResult());

            failures = (Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures());
        }
    } catch (final ProxyException e) {
        throw VersionControlExceptionMapper.map(e);
    }

    getVersionControlClient().reportFailures(localWorkspace, failures);

    if (pendingSets.length == 0) {
        outServerPendingChangeSignature
                .set(queryPendingChangeSignature(localWorkspace.getName(), localWorkspace.getOwnerName()));
        return new PendingChange[0];
    } else {
        outServerPendingChangeSignature.set(pendingSets[0].getPendingChangeSignature());

        // If the server does not have the change where
        // PendingChangeSignature comes down with PendingSet objects, then
        // we'll have to go fetch it ourselves. This change was made to the
        // server in the Dev11 CTP3 iteration.
        if (outServerPendingChangeSignature.get().equals(GUID.EMPTY)) {
            outServerPendingChangeSignature
                    .set(queryPendingChangeSignature(localWorkspace.getName(), localWorkspace.getOwnerName()));
        }

        return pendingSets[0].getPendingChanges();
    }
}

From source file:com.twitter.distributedlog.lock.TestZKSessionLock.java

private void testLockWhenSiblingUseDifferentLockId(long timeout, final boolean isUnlock) throws Exception {
    String lockPath = "/test-lock-when-sibling-use-different-lock-id-" + timeout + "-" + isUnlock + "-"
            + System.currentTimeMillis();
    String clientId0 = "client-id-0";
    String clientId1 = "client-id-1";

    createLockPath(zkc.get(), lockPath);

    final ZKSessionLock lock0_0 = new ZKSessionLock(zkc0, lockPath, clientId0, lockStateExecutor);
    final ZKSessionLock lock0_1 = new ZKSessionLock(zkc0, lockPath, clientId0, lockStateExecutor);
    final ZKSessionLock lock1 = new ZKSessionLock(zkc, lockPath, clientId1, lockStateExecutor);

    lock0_0.tryLock(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

    // lock1 wait for the lock ownership.
    final CountDownLatch lock1DoneLatch = new CountDownLatch(1);
    Thread lock1Thread = new Thread(new Runnable() {
        @Override/*w  ww.  j  a  va  2  s  .  c  o  m*/
        public void run() {
            try {
                lock1.tryLock(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
                lock1DoneLatch.countDown();
            } catch (LockingException e) {
                logger.error("Failed on locking lock1 : ", e);
            }
        }
    }, "lock1-thread");
    lock1Thread.start();

    // check lock1 is waiting for lock0_0
    List<String> children = awaitWaiters(2, zkc, lockPath);

    assertEquals(2, children.size());
    assertEquals(State.CLAIMED, lock0_0.getLockState());
    assertEquals(lock0_0.getLockId(), Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(0))));
    awaitState(State.WAITING, lock1);
    assertEquals(lock1.getLockId(), Await.result(asyncParseClientID(zkc.get(), lockPath, children.get(1))));

    final CountDownLatch lock0DoneLatch = new CountDownLatch(1);
    final AtomicReference<String> ownerFromLock0 = new AtomicReference<String>(null);
    Thread lock0Thread = null;
    if (timeout == 0) {
        try {
            lock0_1.tryLock(0, TimeUnit.MILLISECONDS);
            fail("Should fail on locking if sibling is using differnt lock id.");
        } catch (OwnershipAcquireFailedException oafe) {
            assertEquals(clientId0, oafe.getCurrentOwner());
        }
        assertEquals(State.CLOSED, lock0_1.getLockState());
        children = getLockWaiters(zkc, lockPath);
        assertEquals(2, children.size());
        assertEquals(State.CLAIMED, lock0_0.getLockState());
        assertEquals(lock0_0.getLockId(),
                Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(0))));
        assertEquals(State.WAITING, lock1.getLockState());
        assertEquals(lock1.getLockId(), Await.result(asyncParseClientID(zkc.get(), lockPath, children.get(1))));
    } else {
        lock0Thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock0_1.tryLock(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
                    if (isUnlock) {
                        lock0DoneLatch.countDown();
                    }
                } catch (OwnershipAcquireFailedException oafe) {
                    if (!isUnlock) {
                        ownerFromLock0.set(oafe.getCurrentOwner());
                        lock0DoneLatch.countDown();
                    }
                } catch (LockingException le) {
                    logger.error("Failed on locking lock0_1 : ", le);
                }
            }
        }, "lock0-thread");
        lock0Thread.start();

        // check lock1 is waiting for lock0_0
        children = awaitWaiters(3, zkc, lockPath);

        assertEquals(3, children.size());
        assertEquals(State.CLAIMED, lock0_0.getLockState());
        assertEquals(lock0_0.getLockId(),
                Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(0))));
        awaitState(State.WAITING, lock1);
        assertEquals(lock1.getLockId(), Await.result(asyncParseClientID(zkc.get(), lockPath, children.get(1))));
        awaitState(State.WAITING, lock0_1);
        assertEquals(lock0_1.getLockId(),
                Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(2))));
    }

    if (isUnlock) {
        lock0_0.unlock();
    } else {
        ZooKeeperClientUtils.expireSession(zkc0, zkServers, sessionTimeoutMs);
    }

    lock1DoneLatch.await();
    lock1Thread.join();

    // check the state of lock0_0
    if (isUnlock) {
        assertEquals(State.CLOSED, lock0_0.getLockState());
    } else {
        assertEquals(State.EXPIRED, lock0_0.getLockState());
    }

    if (timeout == 0) {
        children = getLockWaiters(zkc, lockPath);
        assertEquals(1, children.size());
        assertEquals(State.CLAIMED, lock1.getLockState());
        assertEquals(lock1.getLockId(), Await.result(asyncParseClientID(zkc.get(), lockPath, children.get(0))));
    } else {
        assertNotNull(lock0Thread);
        if (!isUnlock) {
            // both lock0_0 and lock0_1 would be expired
            lock0DoneLatch.await();
            lock0Thread.join();

            assertEquals(clientId0, ownerFromLock0.get());
            assertEquals(State.CLOSED, lock0_1.getLockState());

            children = getLockWaiters(zkc, lockPath);
            assertEquals(1, children.size());
            assertEquals(State.CLAIMED, lock1.getLockState());
            assertEquals(lock1.getLockId(),
                    Await.result(asyncParseClientID(zkc.get(), lockPath, children.get(0))));
        } else {
            children = getLockWaiters(zkc, lockPath);
            assertEquals(2, children.size());
            assertEquals(State.CLAIMED, lock1.getLockState());
            assertEquals(lock1.getLockId(),
                    Await.result(asyncParseClientID(zkc.get(), lockPath, children.get(0))));
            assertEquals(State.WAITING, lock0_1.getLockState());
            assertEquals(lock0_1.getLockId(),
                    Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(1))));
        }
    }

    lock1.unlock();

    if (timeout != 0 && isUnlock) {
        lock0DoneLatch.await();
        lock0Thread.join();

        children = getLockWaiters(zkc, lockPath);
        assertEquals(1, children.size());
        assertEquals(State.CLAIMED, lock0_1.getLockState());
        assertEquals(lock0_1.getLockId(),
                Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(0))));
    }
}

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

protected SuggestLocationsResult xmlStopfinderRequest(final Location constraint) throws IOException {
    final HttpUrl.Builder url = stopFinderEndpoint.newBuilder();
    appendStopfinderRequestParameters(url, constraint, "XML");
    final AtomicReference<SuggestLocationsResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override//from  w  w  w .  ja v  a2  s. c o  m
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            try {
                final XmlPullParser pp = parserFactory.newPullParser();
                pp.setInput(body.byteStream(), null); // Read encoding from XML declaration
                final ResultHeader header = enterItdRequest(pp);

                final List<SuggestedLocation> locations = new ArrayList<>();

                XmlPullUtil.enter(pp, "itdStopFinderRequest");

                processItdOdv(pp, "sf", new ProcessItdOdvCallback() {
                    @Override
                    public void location(final String nameState, final Location location,
                            final int matchQuality) {
                        locations.add(new SuggestedLocation(location, matchQuality));
                    }
                });

                XmlPullUtil.skipExit(pp, "itdStopFinderRequest");

                result.set(new SuggestLocationsResult(header, locations));
            } catch (final XmlPullParserException x) {
                throw new ParserException("cannot parse xml: " + bodyPeek, x);
            }
        }
    };

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

    return result.get();
}

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

private static boolean reconcileLocalWorkspaceHelper(final Workspace workspace,
        final WebServiceLayer webServiceLayer, final boolean unscannedReconcile,
        final boolean reconcileMissingFromDisk, final AtomicReference<Failure[]> failures,
        final AtomicBoolean pendingChangesUpdatedByServer) {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$
    pendingChangesUpdatedByServer.set(false);
    final List<PendingChange> convertedAdds = new ArrayList<PendingChange>();

    final boolean throwOnProjectRenamed;
    if (EnvironmentVariables.isDefined(EnvironmentVariables.DD_SUITES_PROJECT_RENAME_UNPATCHED_CLIENT)) {
        throwOnProjectRenamed = false;//from ww  w  .java  2  s  . c om
    } else {
        throwOnProjectRenamed = true;
    }

    final AtomicReference<GUID> serverPendingChangeSignature = new AtomicReference<GUID>(GUID.EMPTY);

    // No optimization away of reconciles when sending up MissingFromDisk
    // rows, since the bit in the header (lvHeader.PendingReconcile) may be
    // false when we actually have work to do (there are rows in the table
    // marked MissingFromDisk).
    if ((unscannedReconcile || !workspace.getWorkspaceWatcher().isScanNecessary())
            && !reconcileMissingFromDisk) {
        // Pre-reconcile
        final AtomicBoolean hasPendingLocalVersionRows = new AtomicBoolean(true);
        LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);

        try {
            transaction.execute(new LocalVersionHeaderTransaction() {
                @Override
                public void invoke(final WorkspaceVersionTableHeader lvh) {
                    hasPendingLocalVersionRows.set(lvh.getPendingReconcile());
                }
            });
        } finally {
            try {
                transaction.close();
            } catch (final IOException e) {
                throw new VersionControlException(e);
            }
        }

        final AtomicReference<GUID> clientPendingChangeSignature = new AtomicReference<GUID>(GUID.EMPTY);

        if (!hasPendingLocalVersionRows.get()) {
            transaction = new LocalWorkspaceTransaction(workspace);
            try {
                transaction.execute(new PendingChangesHeaderTransaction() {
                    @Override
                    public void invoke(final LocalPendingChangesTableHeader pch) {
                        clientPendingChangeSignature.set(pch.getClientSignature());

                    }
                });
            } finally {
                try {
                    transaction.close();
                } catch (final IOException e) {
                    throw new VersionControlException(e);
                }
            }

            final GUID lastServerPendingChangeGuid = workspace.getOfflineCacheData()
                    .getLastServerPendingChangeSignature();
            final Calendar lastReconcileTime = workspace.getOfflineCacheData().getLastReconcileTime();
            lastReconcileTime.add(Calendar.SECOND, 8);

            if (lastServerPendingChangeGuid != GUID.EMPTY
                    && clientPendingChangeSignature.get().equals(lastServerPendingChangeGuid)
                    && lastReconcileTime.after(Calendar.getInstance())) {
                // This reconcile was optimized away with no server call.

                failures.set(new Failure[0]);
                return false;
            }

            serverPendingChangeSignature.set(
                    webServiceLayer.queryPendingChangeSignature(workspace.getName(), workspace.getOwnerName()));

            if (serverPendingChangeSignature.get() != GUID.EMPTY
                    && clientPendingChangeSignature.get().equals(serverPendingChangeSignature)) {
                // This reconcile was optimized away.

                workspace.getOfflineCacheData()
                        .setLastServerPendingChangeSignature(serverPendingChangeSignature.get());
                workspace.getOfflineCacheData().setLastReconcileTime(Calendar.getInstance());

                failures.set(new Failure[0]);
                return false;
            }
        }
    }

    final AtomicBoolean toReturn = new AtomicBoolean(true);

    final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
    try {
        final AtomicReference<Failure[]> delegateFailures = new AtomicReference<Failure[]>(new Failure[0]);
        final AtomicBoolean delegatePCUpdated = new AtomicBoolean(false);

        transaction.execute(new AllTablesTransaction() {
            @Override
            public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv,
                    final LocalPendingChangesTable pc) {
                if (!unscannedReconcile) {
                    // The line below has been commented out because we
                    // decided not to force a full scan here, because it
                    // causes significant degradation in UI performance.
                    //
                    // workspace.getWorkspaceWatcher().markPathChanged(null);
                    //
                    // It was an attempt to fix the bug:
                    // Bug 6191: When using local workspaces, get latest
                    // does not get a file that has been deleted from disk.
                    //
                    // The customer has to explicitly invoke
                    // Pending Changes>Actions>Detect local changes
                    // in Team Explorer.
                    //
                    // Note that none of customers reported that as an
                    // issue.
                    // It was detected on our tests only.
                    workspace.getWorkspaceWatcher().scan(wp, lv, pc);
                }

                // Pre-reconcile
                if (!lv.getPendingReconcile() && !reconcileMissingFromDisk
                        && GUID.EMPTY == serverPendingChangeSignature.get()) {
                    serverPendingChangeSignature.set(webServiceLayer
                            .queryPendingChangeSignature(workspace.getName(), workspace.getOwnerName()));

                    if (serverPendingChangeSignature.get() != GUID.EMPTY
                            && pc.getClientSignature().equals(serverPendingChangeSignature.get())) {
                        // This reconcile was optimized away.
                        delegateFailures.set(new Failure[0]);

                        workspace.getOfflineCacheData()
                                .setLastServerPendingChangeSignature(serverPendingChangeSignature.get());
                        workspace.getOfflineCacheData().setLastReconcileTime(Calendar.getInstance());

                        toReturn.set(true);

                        return;
                    }
                }

                // Acknowledgment of team project renames, if any have been
                // completed
                if (wp.getNewProjectRevisionId() > 0) {
                    webServiceLayer.promotePendingWorkspaceMappings(workspace.getName(),
                            workspace.getOwnerName(), wp.getNewProjectRevisionId());

                    wp.setNewProjectRevisionId(0);
                }

                final LocalPendingChange[] pendingChanges = pc.queryByTargetServerItem(ServerPath.ROOT,
                        RecursionType.FULL, null);

                /*
                 * TEE-specific Code
                 *
                 * In order to support offline property changes, which
                 * cannot be reconciled with
                 * WebServiceLayer.reconcileLocalWorkspace (the property
                 * values can't be sent), we have to pull out the pended
                 * property changes and send them to the server before
                 * reconciling.
                 */
                final List<ChangeRequest> propertyRequests = new ArrayList<ChangeRequest>();

                for (final LocalPendingChange lpc : pendingChanges) {
                    if (lpc.getChangeType().contains(ChangeType.PROPERTY)) {
                        final PropertyValue[] pv = lpc.getPropertyValues();
                        final String serverItem = lpc.getTargetServerItem();

                        if (pv != null && pv.length > 0 && serverItem != null) {
                            final ChangeRequest request = new ChangeRequest(
                                    new ItemSpec(serverItem, RecursionType.NONE),
                                    new WorkspaceVersionSpec(workspace), RequestType.PROPERTY, ItemType.ANY,
                                    VersionControlConstants.ENCODING_UNCHANGED, LockLevel.UNCHANGED, 0, null,
                                    false);

                            request.setProperties(pv);

                            propertyRequests.add(request);
                        }
                    }
                }

                if (propertyRequests.size() > 0) {
                    ((WebServiceLayerLocalWorkspaces) webServiceLayer).pendChangesInLocalWorkspace(
                            workspace.getName(), workspace.getOwnerName(),
                            propertyRequests.toArray(new ChangeRequest[propertyRequests.size()]),
                            PendChangesOptions.NONE, SupportedFeatures.ALL, new AtomicReference<Failure[]>(),
                            null, null, new AtomicBoolean(), new AtomicReference<ChangePendedFlags>());

                    // TODO handle failures?
                }

                // Back to normal, non-TEE behavior

                final AtomicBoolean outClearLocalVersionTable = new AtomicBoolean();
                final ServerItemLocalVersionUpdate[] lvUpdates = lv.getUpdatesForReconcile(pendingChanges,
                        reconcileMissingFromDisk, outClearLocalVersionTable);

                ReconcileResult result = webServiceLayer.reconcileLocalWorkspace(workspace.getName(),
                        workspace.getOwnerName(), pc.getClientSignature(), pendingChanges, lvUpdates,
                        outClearLocalVersionTable.get(), throwOnProjectRenamed);

                // report any failures
                Failure[] reconcileFailures = result.getFailures();
                workspace.getClient().reportFailures(workspace, reconcileFailures);

                if (reconcileFailures.length > 0) {
                    throw new ReconcileFailedException(reconcileFailures);
                }

                GUID newSignature = new GUID(result.getNewSignature());
                PendingChange[] newPendingChanges = result.getNewPendingChanges();

                // If the local version rows for this local workspace have
                // been purged from the server, then the server will set
                // this flag on the result of the next reconcile.
                if (result.isReplayLocalVersionsRequired()) {
                    // Reconcile a second time. This time, set the
                    // clearLocalVersionTable flag. This way, we know
                    // we have cleared out any lingering local version rows
                    // for this workspace.
                    if (!outClearLocalVersionTable.get()) {
                        result = webServiceLayer.reconcileLocalWorkspace(workspace.getName(),
                                workspace.getOwnerName(), pc.getClientSignature(), pendingChanges, lvUpdates,
                                true /* clearLocalVersionTable */, throwOnProjectRenamed);

                        // Report any failures
                        reconcileFailures = result.getFailures();
                        workspace.getClient().reportFailures(workspace, reconcileFailures);

                        if (reconcileFailures.length > 0) {
                            throw new ReconcileFailedException(reconcileFailures);
                        }

                        // Grab the new signature and new pending changes
                        newSignature = new GUID(result.getNewSignature());
                        newPendingChanges = result.getNewPendingChanges();
                    }

                    // Now, go through the local version table and replay
                    // every row that we have.
                    final List<ServerItemLocalVersionUpdate> replayUpdates = new ArrayList<ServerItemLocalVersionUpdate>(
                            Math.min(lv.getLocalItemsCount(), 1000));

                    for (final WorkspaceLocalItem lvEntry : lv.queryByServerItem(ServerPath.ROOT,
                            RecursionType.FULL, null, true /* includeDeleted */)) {
                        final ServerItemLocalVersionUpdate replayUpdate = lvEntry
                                .getLocalVersionUpdate(reconcileMissingFromDisk, true /* force */);

                        if (replayUpdate != null) {
                            replayUpdates.add(replayUpdate);

                            // Batch these updates in groups of 1000 items.
                            if (replayUpdates.size() >= 1000) {
                                webServiceLayer.updateLocalVersion(workspace.getName(),
                                        workspace.getOwnerName(), replayUpdates.toArray(
                                                new ServerItemLocalVersionUpdate[replayUpdates.size()]));

                                replayUpdates.clear();
                            }
                        }
                    }

                    if (replayUpdates.size() > 0) {
                        webServiceLayer.updateLocalVersion(workspace.getName(), workspace.getOwnerName(),
                                replayUpdates.toArray(new ServerItemLocalVersionUpdate[replayUpdates.size()]));
                    }
                }

                if (result.isPendingChangesUpdated()) {
                    delegatePCUpdated.set(true);

                    final Map<String, ItemType> newPendingDeletes = new TreeMap<String, ItemType>(
                            String.CASE_INSENSITIVE_ORDER);

                    for (final PendingChange pendingChange : newPendingChanges) {
                        if (pendingChange.isAdd()) {
                            final LocalPendingChange oldPendingChange = pc
                                    .getByTargetServerItem(pendingChange.getServerItem());

                            if (null == oldPendingChange || !oldPendingChange.isAdd()) {
                                // Before calling ReconcileLocalWorkspace,
                                // we did not have a pending add at this
                                // target server item.
                                convertedAdds.add(pendingChange);
                            }
                        } else if (pendingChange.isDelete()) {
                            // If the server removed any of our presented
                            // pending deletes, we want to know about it so
                            // we can get rid of the local version rows that
                            // we have in the deleted state. The server will
                            // remove our pending deletes when the item has
                            // been destroyed on the server.
                            newPendingDeletes.put(
                                    pendingChange.getSourceServerItem() == null ? pendingChange.getServerItem()
                                            : pendingChange.getSourceServerItem(),
                                    pendingChange.getItemType());
                        }
                    }

                    for (final LocalPendingChange oldPendingChange : pc
                            .queryByCommittedServerItem(ServerPath.ROOT, RecursionType.FULL, null)) {
                        if (oldPendingChange.isDelete()
                                && !newPendingDeletes.containsKey(oldPendingChange.getCommittedServerItem())) {
                            // We presented this delete to the server for
                            // Reconcile, but the server removed it from the
                            // pending changes manifest. We need to get rid
                            // of the LV rows for
                            // oldPendingChange.CommittedServerItem since
                            // this item is now destroyed.
                            final List<ServerItemIsCommittedTuple> lvRowsToRemove = new ArrayList<ServerItemIsCommittedTuple>();

                            final RecursionType recursion = oldPendingChange.isRecursiveChange()
                                    ? RecursionType.FULL
                                    : RecursionType.NONE;

                            // Aggregate up the deleted local version
                            // entries at this committed server item
                            // (or below if it's a folder), and we'll remove
                            // them.
                            for (final WorkspaceLocalItem lvEntry : lv.queryByServerItem(
                                    oldPendingChange.getCommittedServerItem(), recursion, null,
                                    true /* includeDeleted */)) {
                                if (lvEntry.isDeleted()) {
                                    lvRowsToRemove.add(new ServerItemIsCommittedTuple(lvEntry.getServerItem(),
                                            lvEntry.isCommitted()));
                                }
                            }

                            for (final ServerItemIsCommittedTuple tuple : lvRowsToRemove) {
                                // We don't need to reconcile the removal of
                                // LV entries marked IsDeleted since they
                                // don't exist on the server anyway.
                                lv.removeByServerItem(tuple.getCommittedServerItem(), tuple.isCommitted(),
                                        false);
                            }
                        }
                    }

                    pc.replacePendingChanges(newPendingChanges);
                }

                // If all we're doing to LV is marking it reconciled, then
                // don't use TxF to commit
                // both tables atomically as this is slower
                if (!lv.isDirty()) {
                    transaction.setAllowTxF(false);
                }

                if (lvUpdates.length > 0) {
                    lv.markAsReconciled(wp, reconcileMissingFromDisk);

                    // If we removed all missing-from-disk items from the
                    // local version table, then we need to remove
                    // the corresponding candidate delete rows for those
                    // items as well.
                    if (reconcileMissingFromDisk) {
                        List<String> candidatesToRemove = null;

                        for (final LocalPendingChange candidateChange : pc
                                .queryCandidatesByTargetServerItem(ServerPath.ROOT, RecursionType.FULL, null)) {
                            if (candidateChange.isDelete()) {
                                if (null == candidatesToRemove) {
                                    candidatesToRemove = new ArrayList<String>();
                                }
                                candidatesToRemove.add(candidateChange.getTargetServerItem());
                            }
                        }

                        if (null != candidatesToRemove) {
                            for (final String candidateDeleteTargetServerItem : candidatesToRemove) {
                                pc.removeCandidateByTargetServerItem(candidateDeleteTargetServerItem);
                            }
                            // Set the candidates changed to true so that it
                            // refreshes the UI
                            LocalWorkspaceTransaction.getCurrent().setRaisePendingChangeCandidatesChanged(true);
                        }
                    }
                }

                newSignature = webServiceLayer.queryPendingChangeSignature(workspace.getName(),
                        workspace.getOwnerName());

                if (!newSignature.equals(pc.getClientSignature())) {
                    pc.setClientSignature(newSignature);
                    workspace.getOfflineCacheData().setLastServerPendingChangeSignature(newSignature);
                }

                if (!newSignature.equals(pc.getClientSignature())) {
                    pc.setClientSignature(newSignature);
                    workspace.getOfflineCacheData().setLastServerPendingChangeSignature(newSignature);
                }

                workspace.getOfflineCacheData().setLastReconcileTime(Calendar.getInstance());
            }
        });

        failures.set(delegateFailures.get());
        pendingChangesUpdatedByServer.set(delegatePCUpdated.get());
    } finally {
        try {
            transaction.close();
        } catch (final IOException e) {
            throw new VersionControlException(e);
        }
    }

    if (convertedAdds.size() > 0) {
        final UpdateLocalVersionQueueOptions options = UpdateLocalVersionQueueOptions.UPDATE_BOTH;
        final UpdateLocalVersionQueue ulvq = new UpdateLocalVersionQueue(workspace, options);

        try {
            for (final PendingChange pc : convertedAdds) {
                // Every item in this list has a ChangeType of Add. As a
                // result they are uncommitted items with no committed hash
                // value, no committed length, and no baseline file GUID.
                ulvq.queueUpdate(new ClientLocalVersionUpdate(pc.getServerItem(), pc.getItemID(),
                        pc.getLocalItem(), 0 /* localVersion */, DotNETDate.MIN_CALENDAR, pc.getEncoding(),
                        null /* committedHashValue */, 0 /* committedLength */, null /* baselineFileGuid */,
                        null /* pendingChangeTargetServerItem */, null /* properties */));
            }
        } finally {
            ulvq.close();
        }
    }

    return toReturn.get();
}