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.soapextensions.Workspace.java

/**
 * Checkin pending changes in this workspace.
 * <p>/*from www  . ja  v a 2  s  .  co  m*/
 * <!-- Event Origination Info -->
 * <p>
 * This method is an <b>core event origination point</b>. The
 * {@link EventSource} object that accompanies each event fired by this
 * method describes the execution context (current thread, etc.) when and
 * where this method was invoked.
 *
 * @param changes
 *        the changes to checkin (may be <code>null</code> to have the
 *        server check in all changes in this workspace)
 * @param committer
 *        if not <code>null</code>, the committer of this change. if
 *        <code>null</code>, the committer will be the authenticated user.
 * @param author
 *        if not <code>null</code>, the author of this change. if
 *        <code>null</code>, the author will be the authenticated user.
 * @param comment
 *        a text comment that will be associated with this checkin (can be
 *        <code>null</code>).
 * @param checkinNote
 *        {@link CheckinNote} object containing array of
 *        ACheckinNoteFieldValue objects. If <code>null</code>, no checkin
 *        notes are added to changeset. For a list of checkin note field
 *        names applicable to the items use the
 *        queryCheckinNoteFieldDefinitionsForServerPaths on the
 *        VersionControlClient.
 * @param associatedWorkItems
 *        work items to associate with the checkin. if <code>null</code>, no
 *        work items are associated with this checkin
 * @param policyOverrideInfo
 *        Optional information describing why checkin policies were
 *        overridden for this checkin. Pass null for a normal check-in
 *        (policies were not overridden).
 * @param flags
 *        {@link CheckinFlags} which control the checkin (must not be
 *        <code>null</code>)
 * @return the changeset number the server chooses for this changeset.
 * @throws CheckinException
 *         if conflicts caused the checkin to fail or if other errors
 *         occurred.
 * @throws ActionDeniedBySubscriberException
 *         if the check-in was denied by the server (because of a gated
 *         build definition, etc.).
 *
 * @see VersionControlClient#queryCheckinNoteFieldDefinitionsForServerPaths(String[])
 */
public int checkIn(PendingChange[] changes, final String committer, final String committerDisplayName,
        String author, String authorDisplayName, final String comment, final CheckinNote checkinNote,
        WorkItemCheckinInfo[] associatedWorkItems, final PolicyOverrideInfo policyOverrideInfo,
        final CheckinFlags flags) throws CheckinException {
    Check.isTrue(changes == null || changes.length > 0,
            "changes must be null for server-side change selection or non-empty"); //$NON-NLS-1$
    Check.notNull(flags, "flags"); //$NON-NLS-1$

    /**
     * TFS 2010 behaves strangely with gated check-ins if we send null for
     * associated work items (a non-standard subcode comes back in the
     * ActionDeniedBySubscriberException. Always send at least an empty
     * list.
     */
    if (associatedWorkItems == null) {
        associatedWorkItems = new WorkItemCheckinInfo[0];
    }

    final TaskMonitor monitor = TaskMonitorService.getTaskMonitor();

    /*
     * The total work for our progress monitor is set to 100, and subtasks
     * are allocated as percentages. For example, checkin for conflicts is
     * quick, so it takes only 2 percent. Uploading files usually takes
     * longer, so it's 80 percent. Make sure all the work done in this
     * method adds to 100.
     */
    monitor.begin("", 100); //$NON-NLS-1$

    /*
     * We sort the changes by server path so they appear in the correct
     * order when giving status information to the user.
     */
    String[] serverItems = null;
    if (changes != null) {
        changes = changes.clone();
        Arrays.sort(changes, new PendingChangeComparator(PendingChangeComparatorType.SERVER_ITEM));
        serverItems = PendingChange.toServerItems(changes);
    }

    // Lets us detect all abnormal exits (Throwable, Exception, Gated
    // checkin exception) for saved checkin reset
    boolean success = false;

    try {
        TaskMonitorService.pushTaskMonitor(monitor.newSubTaskMonitor(75));
        try {
            // Upload contents
            if (changes != null) {
                final CheckinEngine ci = new CheckinEngine(client, this);

                final long start = System.currentTimeMillis();
                ci.uploadChanges(changes, false, getLocation() == WorkspaceLocation.LOCAL);
                log.debug(MessageFormat.format("total time for upload of {0} was {1} ms", //$NON-NLS-1$
                        changes.length, (System.currentTimeMillis() - start)));
            } else {
                log.debug("null changes (server side change selection), skipped upload"); //$NON-NLS-1$
            }
        } finally {
            TaskMonitorService.popTaskMonitor(true);
        }

        if (author == null) {
            author = VersionControlConstants.AUTHENTICATED_USER;
        }
        if (authorDisplayName == null) {
            authorDisplayName = UserNameUtil.getCurrentUserName();
            final String domainName = UserNameUtil.getCurrentUserDomain();
            if (!StringUtil.isNullOrEmpty(domainName)) {
                authorDisplayName = UserNameUtil.format(authorDisplayName, domainName);
            }
        }

        /*
         * Finally, create a Changeset and send it to the server to be
         * committed. It's important to pass "null" for the date so TFS 2010
         * and later do not require CheckinOther permissions (required to
         * set a specific date on a new changeset).
         */
        final Changeset changeset = new Changeset(null, comment, checkinNote, policyOverrideInfo, committer,
                committerDisplayName, null, -1, author, authorDisplayName, null);

        /*
         * Test one final time before the change set is fully committed.
         */
        if (monitor.isCanceled()) {
            // Caught in this method below.
            throw new CoreCancelException();
        }

        monitor.setCurrentWorkDescription(Messages.getString("Workspace.CheckinInNewChangeset")); //$NON-NLS-1$

        final AtomicReference<Failure[]> failures = new AtomicReference<Failure[]>();
        final AtomicReference<Failure[]> conflicts = new AtomicReference<Failure[]>();
        final boolean noAutoResolve = flags.contains(CheckinFlags.NO_AUTO_RESOLVE);

        final CheckinResult result;
        try {
            /*
             * If changes was null when this method was called, serverItems
             * will be null here, which causes the server to check in all
             * workspace changes.
             */
            result = getClient().getWebServiceLayer().checkIn(getName(), getOwnerName(), serverItems, changeset,
                    makeCheckinNotificationInfo(associatedWorkItems), flags, null, conflicts, failures, false,
                    0, client.mergeWithDefaultItemPropertyFilters(null));
        } catch (final ActionDeniedBySubscriberException e) {
            if (e.getSubscriberType().equals(BUILD_CHECKIN_SUBSCRIBER) && e.getStatusCode() == 1) {
                /*
                 * For ease of use, convert the
                 * ActionDeniedBySubscriberException into a stronger type,
                 * GatedCheckinException. This exception has helper
                 * properties and is typed in a way that customers expect.
                 * It is still an ActionDeniedBySubscriberException.
                 */
                throw new GatedCheckinException(e);
            } else {
                /*
                 * Some other subscriber has denied the decision point.
                 * Throw the ActionDeniedBySubscriberException verbatim.
                 */
                throw e;
            }
        }

        monitor.worked(10);

        changeset.setChangesetID(result.getChangeset());

        // Report any failures.
        reportCheckinConflictsAndThrow(result, conflicts.get(), failures.get(), noAutoResolve);

        /*
         * When the SetFileTimeToCheckin workspace option is set, then the
         * full checkin manifest is returned to the client in the form of
         * GetOperations, even in a server workspace. (In a server
         * workspace, the local version updates are still performed by the
         * server at the end of the CheckIn call.) We use this manifest to
         * set the check-in date on each item in the changeset, even
         * implicitly included missing parents and affected items of
         * recursive changes.
         */
        final TaskMonitor setFileTimeMonitor = monitor.newSubTaskMonitor(5);
        try {
            if (getOptions().contains(WorkspaceOptions.SET_FILE_TO_CHECKIN)) {
                final GetOperation[] updates = result.getLocalVersionUpdates();

                if (updates != null && updates.length > 0) {
                    setFileTimeMonitor.begin(Messages.getString("Workspace.SettingFileTime"), updates.length); //$NON-NLS-1$

                    for (final GetOperation getOp : updates) {
                        if (ItemType.FILE == getOp.getItemType() && null != getOp.getTargetLocalItem()
                                && new File(getOp.getTargetLocalItem()).exists()) {
                            setFileTimeMonitor.setCurrentWorkDescription(getOp.getTargetLocalItem());

                            try {
                                final FileSystemAttributes attributes = FileSystemUtils.getInstance()
                                        .getAttributes(getOp.getTargetLocalItem());
                                boolean restoreReadOnly = false;

                                /*
                                 * Temporarily remove the read-only flag so
                                 * we can modify the time (Windows requires
                                 * this).
                                 */
                                if (attributes.isReadOnly()) {
                                    attributes.setReadOnly(false);
                                    FileSystemUtils.getInstance().setAttributes(getOp.getTargetLocalItem(),
                                            attributes);
                                    restoreReadOnly = true;
                                }

                                new File(getOp.getTargetLocalItem())
                                        .setLastModified(result.getCreationDate().getTimeInMillis());

                                if (restoreReadOnly) {
                                    attributes.setReadOnly(true);
                                    FileSystemUtils.getInstance().setAttributes(getOp.getTargetLocalItem(),
                                            attributes);
                                }
                            } catch (final Exception e) {
                                client.getEventEngine().fireNonFatalError(
                                        new NonFatalErrorEvent(EventSource.newFromHere(), this, e));
                            }
                        }
                    }
                }
            }
        } finally {
            setFileTimeMonitor.done();
        }

        /*
         * If this is a server workspace, set files read-only.
         */
        final TaskMonitor makeReadOnlyMonitor = monitor.newSubTaskMonitor(5);
        try {
            if (changes != null && getLocation() == WorkspaceLocation.SERVER) {
                makeReadOnlyMonitor.begin(Messages.getString("Workspace.SettingReadOnly"), changes.length); //$NON-NLS-1$

                for (final PendingChange change : changes) {
                    if (change.getChangeType().contains(ChangeType.EDIT) && change.getLocalItem() != null
                            && new File(change.getLocalItem()).exists()) {
                        makeReadOnlyMonitor.setCurrentWorkDescription(change.getLocalItem());

                        try {
                            final FileSystemAttributes attributes = FileSystemUtils.getInstance()
                                    .getAttributes(change.getLocalItem());
                            if (!attributes.isSymbolicLink() && !attributes.isDirectory()) {
                                attributes.setReadOnly(true);
                                FileSystemUtils.getInstance().setAttributes(change.getLocalItem(), attributes);
                            }
                        } catch (final Exception e) {
                            client.getEventEngine().fireNonFatalError(
                                    new NonFatalErrorEvent(EventSource.newFromHere(), this, e));
                        }
                    } else {
                        // Skipping this one.
                        makeReadOnlyMonitor.setCurrentWorkDescription(""); //$NON-NLS-1$
                    }

                    makeReadOnlyMonitor.worked(1);
                }
            }
        } finally {
            makeReadOnlyMonitor.done();
        }

        monitor.setCurrentWorkDescription(Messages.getString("Workspace.NotifyingListeners")); //$NON-NLS-1$

        /*
         * Determine which pending changes were committed and which were
         * undone. Preserve the sorted order in the sublists.
         */

        PendingChange[] committedChangesArray = new PendingChange[0];
        PendingChange[] undoneChangesArray = new PendingChange[0];

        if (changes != null && changes.length > 0) {
            final Set<String> undoneServerItems = new TreeSet<String>(ServerPath.TOP_DOWN_COMPARATOR);

            for (final String undoneServerItem : result.getUndoneServerItems()) {
                undoneServerItems.add(undoneServerItem);
            }

            final List<PendingChange> undonePendingChanges = new ArrayList<PendingChange>(
                    undoneServerItems.size());
            final List<PendingChange> committedPendingChanges = new ArrayList<PendingChange>();

            for (final PendingChange change : changes) {
                if (undoneServerItems.contains(change.getServerItem())) {
                    undonePendingChanges.add(change);
                } else {
                    committedPendingChanges.add(change);
                }
            }

            committedChangesArray = committedPendingChanges
                    .toArray(new PendingChange[committedPendingChanges.size()]);
            undoneChangesArray = undonePendingChanges.toArray(new PendingChange[undonePendingChanges.size()]);
        }

        // Notify the user that the checkin iCheckinEvents complete.
        client.getEventEngine().fireCheckin(new CheckinEvent(EventSource.newFromHere(), this,
                result.getChangeset(), committedChangesArray, undoneChangesArray));

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

        monitor.worked(1);

        final int cset = changeset.getChangesetID();

        TaskMonitorService.pushTaskMonitor(monitor.newSubTaskMonitor(4));
        try {
            /*
             * Only update work items if we have a valid (non-0) changeset.
             * Changeset 0 indicates all the pending changes were undone on
             * the server.
             */
            if (cset != 0) {
                updateWorkItems(associatedWorkItems, cset, comment);
            }
        } finally {
            TaskMonitorService.popTaskMonitor(true);
        }

        // Remove any saved attempted checkin info.
        setLastSavedCheckin(buildEmptyLastSavedCheckin());

        success = true;
        return cset;
    } catch (final CanceledException e) {
        // Fire as non-fatal
        client.getEventEngine().fireNonFatalError(new NonFatalErrorEvent(EventSource.newFromHere(), this,
                new CoreCancelException(Messages.getString("Workspace.CheckinCancelled")))); //$NON-NLS-1$
        return 0;
    } catch (final CoreCancelException e) {
        // Convert to CanceledException and fire as non-fatal
        client.getEventEngine().fireNonFatalError(new NonFatalErrorEvent(EventSource.newFromHere(), this,
                new CanceledException(Messages.getString("Workspace.CheckinCancelled")))); //$NON-NLS-1$
        return 0;
    } finally {
        /*
         * If the checkin didn't succeed, save the info for the next
         * attempt. success will be false for expected things like gated
         * checkin and cancelation exceptions, and also for unexpected
         * exceptions.
         */
        if (!success) {
            updateLastSavedCheckin(comment, checkinNote, associatedWorkItems, policyOverrideInfo);
        }

        monitor.done();
    }
}

From source file:io.pravega.segmentstore.server.writer.SegmentAggregatorTests.java

/**
 * Tests the flush() method with Append and MergeTransactionOperations.
 *///from w  ww . j a v  a 2s .c  o m
@Test
public void testMergeWithStorageErrors() throws Exception {
    // Storage Errors
    final int appendCount = 100; // This is number of appends per Segment/Transaction - there will be a lot of appends here.
    final int failSyncEvery = 2;
    final int failAsyncEvery = 3;
    final WriterConfig config = WriterConfig.builder()
            .with(WriterConfig.FLUSH_THRESHOLD_BYTES, appendCount * 50) // Extra high length threshold.
            .with(WriterConfig.FLUSH_THRESHOLD_MILLIS, 1000L).with(WriterConfig.MAX_FLUSH_SIZE_BYTES, 10000)
            .with(WriterConfig.MIN_READ_TIMEOUT_MILLIS, 10L).build();

    @Cleanup
    TestContext context = new TestContext(config);

    // Create and initialize all segments.
    context.storage.create(context.segmentAggregator.getMetadata().getName(), TIMEOUT).join();
    context.segmentAggregator.initialize(TIMEOUT, executorService()).join();
    for (SegmentAggregator a : context.transactionAggregators) {
        context.storage.create(a.getMetadata().getName(), TIMEOUT).join();
        a.initialize(TIMEOUT, executorService()).join();
    }

    // Store written data by segment - so we can check it later.
    HashMap<Long, ByteArrayOutputStream> dataBySegment = new HashMap<>();

    // Add a few appends to each Transaction aggregator and to the parent aggregator and seal all Transactions.
    for (int i = 0; i < context.transactionAggregators.length; i++) {
        SegmentAggregator transactionAggregator = context.transactionAggregators[i];
        long transactionId = transactionAggregator.getMetadata().getId();
        ByteArrayOutputStream writtenData = new ByteArrayOutputStream();
        dataBySegment.put(transactionId, writtenData);

        for (int appendId = 0; appendId < appendCount; appendId++) {
            StorageOperation appendOp = generateAppendAndUpdateMetadata(appendId, transactionId, context);
            transactionAggregator.add(appendOp);
            getAppendData(appendOp, writtenData, context);
        }

        transactionAggregator.add(generateSealAndUpdateMetadata(transactionId, context));
    }

    // Merge all the Transactions in the parent Segment.
    @Cleanup
    ByteArrayOutputStream parentData = new ByteArrayOutputStream();
    for (int transIndex = 0; transIndex < context.transactionAggregators.length; transIndex++) {
        // Merge this Transaction into the parent & record its data in the final parent data array.
        long transactionId = context.transactionAggregators[transIndex].getMetadata().getId();
        context.segmentAggregator.add(generateMergeTransactionAndUpdateMetadata(transactionId, context));

        ByteArrayOutputStream transactionData = dataBySegment.get(transactionId);
        parentData.write(transactionData.toByteArray());
        transactionData.close();
    }

    // Have the writes fail every few attempts with a well known exception.
    AtomicReference<IntentionalException> setException = new AtomicReference<>();
    Supplier<Exception> exceptionSupplier = () -> {
        IntentionalException ex = new IntentionalException(Long.toString(context.timer.getElapsedMillis()));
        setException.set(ex);
        return ex;
    };
    context.storage.setConcatSyncErrorInjector(
            new ErrorInjector<>(count -> count % failSyncEvery == 0, exceptionSupplier));
    context.storage.setConcatAsyncErrorInjector(
            new ErrorInjector<>(count -> count % failAsyncEvery == 0, exceptionSupplier));

    // Flush all the Aggregators, while checking that the right errors get handled and can be recovered from.
    tryFlushAllSegments(context, () -> setException.set(null), setException::get);

    // Verify that all Transactions are now fully merged.
    for (SegmentAggregator transactionAggregator : context.transactionAggregators) {
        SegmentMetadata transactionMetadata = transactionAggregator.getMetadata();
        Assert.assertTrue("Merged Transaction was not marked as deleted in metadata.",
                transactionMetadata.isDeleted());
        Assert.assertFalse("Merged Transaction still exists in storage.",
                context.storage.exists(transactionMetadata.getName(), TIMEOUT).join());
    }

    // Verify that in the end, the contents of the parents is as expected.
    byte[] expectedData = parentData.toByteArray();
    byte[] actualData = new byte[expectedData.length];
    long storageLength = context.storage
            .getStreamSegmentInfo(context.segmentAggregator.getMetadata().getName(), TIMEOUT).join()
            .getLength();
    Assert.assertEquals("Unexpected number of bytes flushed/merged to Storage.", expectedData.length,
            storageLength);
    context.storage.read(readHandle(context.segmentAggregator.getMetadata().getName()), 0, actualData, 0,
            actualData.length, TIMEOUT).join();
    Assert.assertArrayEquals("Unexpected data written to storage.", expectedData, actualData);
}

From source file:io.pravega.segmentstore.server.writer.SegmentAggregatorTests.java

/**
 * Tests the ability of the SegmentAggregator to reconcile AppendOperations (Cached/NonCached).
 *///from ww  w.  j a  v  a  2 s  .  c  o m
@Test
public void testReconcileAppends() throws Exception {
    final WriterConfig config = DEFAULT_CONFIG;
    final int appendCount = 1000;
    final int failEvery = 3;

    @Cleanup
    TestContext context = new TestContext(config);
    context.storage.create(context.segmentAggregator.getMetadata().getName(), TIMEOUT).join();
    context.segmentAggregator.initialize(TIMEOUT, executorService()).join();

    // The writes always succeed, but every few times we return some random error, indicating that they didn't.
    AtomicInteger writeCount = new AtomicInteger();
    AtomicReference<Exception> setException = new AtomicReference<>();
    context.storage.setWriteInterceptor((segmentName, offset, data, length, storage) -> {
        if (writeCount.incrementAndGet() % failEvery == 0) {
            // Time to wreak some havoc.
            return storage.write(writeHandle(segmentName), offset, data, length, TIMEOUT).thenAccept(v -> {
                IntentionalException ex = new IntentionalException(
                        String.format("S=%s,O=%d,L=%d", segmentName, offset, length));
                setException.set(ex);
                throw ex;
            });
        } else {
            setException.set(null);
            return null;
        }
    });

    @Cleanup
    ByteArrayOutputStream writtenData = new ByteArrayOutputStream();

    for (int i = 0; i < appendCount; i++) {
        // Add another operation and record its length.
        StorageOperation appendOp = generateAppendAndUpdateMetadata(i, SEGMENT_ID, context);
        context.segmentAggregator.add(appendOp);
        getAppendData(appendOp, writtenData, context);
    }

    context.increaseTime(config.getFlushThresholdTime().toMillis() + 1); // Force a flush by incrementing the time by a lot.
    while (context.segmentAggregator.mustFlush()) {
        // Call flush() and inspect the result.
        FlushResult flushResult = null;

        try {
            flushResult = context.segmentAggregator.flush(TIMEOUT, executorService()).get(TIMEOUT.toMillis(),
                    TimeUnit.MILLISECONDS);
            Assert.assertNull("An exception was expected, but none was thrown.", setException.get());
            Assert.assertNotNull("No FlushResult provided.", flushResult);
        } catch (Exception ex) {
            if (setException.get() != null) {
                Assert.assertEquals("Unexpected exception thrown.", setException.get(),
                        ExceptionHelpers.getRealException(ex));
            } else {
                // Only expecting a BadOffsetException after our own injected exception.
                Throwable realEx = ExceptionHelpers.getRealException(ex);
                Assert.assertTrue("Unexpected exception thrown: " + realEx,
                        realEx instanceof BadOffsetException);
            }
        }

        // Check flush result.
        if (flushResult != null) {
            AssertExtensions.assertGreaterThan("Not enough bytes were flushed (time threshold).", 0,
                    flushResult.getFlushedBytes());
            Assert.assertEquals("Not expecting any merged bytes in this test.", 0,
                    flushResult.getMergedBytes());
        }

        context.increaseTime(config.getFlushThresholdTime().toMillis() + 1); // Force a flush by incrementing the time by a lot.
    }

    // Verify data.
    byte[] expectedData = writtenData.toByteArray();
    byte[] actualData = new byte[expectedData.length];
    long storageLength = context.storage
            .getStreamSegmentInfo(context.segmentAggregator.getMetadata().getName(), TIMEOUT).join()
            .getLength();
    Assert.assertEquals("Unexpected number of bytes flushed to Storage.", expectedData.length, storageLength);
    context.storage.read(readHandle(context.segmentAggregator.getMetadata().getName()), 0, actualData, 0,
            actualData.length, TIMEOUT).join();

    Assert.assertArrayEquals("Unexpected data written to storage.", expectedData, actualData);
}

From source file:de.hybris.platform.test.TransactionTest.java

@Test
public void testNestedTAError() throws Exception {

    final AtomicBoolean storeCalled = new AtomicBoolean();
    final AtomicBoolean commitCalled = new AtomicBoolean();
    final AtomicBoolean rollbackCalled = new AtomicBoolean();

    final Transaction transaction = new DefaultTransaction() {
        @Override//from  w ww . j  a v  a2  s . c o m
        public void rollback() throws TransactionException {
            rollbackCalled.set(true);
            super.rollback();
        }

        @Override
        public void commit() throws TransactionException {
            commitCalled.set(true);
            super.commit();
        }
    };
    transaction.enableDelayedStore(true);

    final EntityInstanceContext eCtx = new EntityInstanceContext() {

        @Override
        public ItemDeployment getItemDeployment() {
            return null;
        }

        @Override
        public PK getPK() {
            return PK.NULL_PK;
        }

        @Override
        public PersistencePool getPersistencePool() {
            return null;
        }

        @Override
        public void setPK(final PK pk) {
            // mock
        }
    };

    final EntityInstance mockEntity = new EntityInstance() {
        final EntityInstanceContext ctx = eCtx;

        @Override
        public PK ejbFindByPrimaryKey(final PK pkValue) throws YObjectNotFoundException {
            return null;
        }

        @Override
        public void ejbLoad() {
            // mock
        }

        @Override
        public void ejbRemove() {
            // mock
        }

        @Override
        public void ejbStore() {
            storeCalled.set(true);
            throw new IllegalArgumentException("let's rollback ;)");
        }

        @Override
        public EntityInstanceContext getEntityContext() {
            return ctx;
        }

        @Override
        public boolean needsStoring() {
            return true;
        }

        @Override
        public void setEntityContext(final EntityInstanceContext ctx) {
            // mock
        }

        @Override
        public void setNeedsStoring(final boolean needs) {
            // mock
        }

    };

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final PrintStream printstream = new PrintStream(bos);

    final PrintStream err = System.err;

    final AtomicReference<Title> itemRef = new AtomicReference<Title>();

    try {
        System.setErr(printstream);

        // outer TA
        transaction.execute(new TransactionBody() {
            @Override
            public Object execute() throws Exception {
                // inner TA
                transaction.execute(new TransactionBody() {
                    @Override
                    public Object execute() throws Exception {
                        itemRef.set(UserManager.getInstance().createTitle("T" + System.currentTimeMillis()));

                        // inject mock entity to call ejbStore upon -> throws exception
                        transaction.registerEntityInstance(mockEntity);

                        return null;
                    }

                });
                return null;
            }

        });
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException ex) {
        assertTrue(storeCalled.get());
        assertEquals("let's rollback ;)", ex.getMessage());

        assertFalse(transaction.isRunning());
        assertEquals(0, transaction.getOpenTransactionCount());
        assertNotNull(itemRef.get());
        assertFalse(itemRef.get().isAlive());

        final String errorLog = new String(bos.toByteArray());

        assertFalse(errorLog.contains("no transaction running"));
    } catch (final Exception e) {
        fail("unexpected error " + e.getMessage());
    } finally {
        System.setErr(err);
    }
}

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

/**
 * Return the distinct set of pending changes from the workspace specified
 * that match the provided itemspecs./*  w  w  w  .ja va 2  s.c  o  m*/
 *
 * @param workspace
 *        Workspace to query pending changes in
 * @param lv
 *        Local version table for the workspace
 * @param pc
 *        Pending changes table for the workspace
 * @param itemSpecs
 *        Itemspecs to match
 * @param failuresAccumulator
 *        Container for failures.
 * @param includeCandidates
 *        Whether to include candidate pending changes
 * @return The set of distinct matching pending changes
 */
private static Iterable<LocalPendingChange> queryPendingChanges(final Workspace workspace,
        final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv, final LocalPendingChangesTable pc,
        final ItemSpec[] itemSpecs, final List<Failure> failuresAccumulator, final boolean includeCandidates,
        final String[] itemPropertyFilters) {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$
    Check.notNull(itemSpecs, "itemspecs"); //$NON-NLS-1$

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

    final List<List<LocalPendingChange>> itemSpecResults = new ArrayList<List<LocalPendingChange>>();

    for (final ItemSpec itemSpec : itemSpecs) {
        if (null == itemSpec) {
            continue;
        }

        // The set of pending changes matching this itemspec.
        final List<LocalPendingChange> pendingChanges = new ArrayList<LocalPendingChange>();
        final ParsedItemSpecOptions flags = ParsedItemSpecOptions.INCLUDE_DELETED;

        if (ServerPath.isServerPath(itemSpec.getItem())) {
            // Canonicalize the input.
            itemSpec.setItem(ServerPath.canonicalize(itemSpec.getItem()));

            final AtomicReference<Failure> outDummy = new AtomicReference<Failure>();
            final ParsedItemSpec parsedItemSpec = ParsedItemSpec.fromServerItemSpec(itemSpec, wp, lv, pc, flags,
                    outDummy, includeCandidates);

            if (null != parsedItemSpec) {
                final LocalPendingChange[] pcEntries = pc.queryByTargetServerItem(
                        parsedItemSpec.getTargetItem(), parsedItemSpec.getRecursionType(),
                        parsedItemSpec.getPattern());

                for (final LocalPendingChange pcEntry : pcEntries) {
                    pendingChanges.add(pcEntry);
                }

                if (includeCandidates) {
                    final Iterable<LocalPendingChange> entries = pc.queryCandidatesByTargetServerItem(
                            parsedItemSpec.getTargetItem(), parsedItemSpec.getRecursionType(),
                            parsedItemSpec.getPattern());

                    for (final LocalPendingChange pcEntry : entries) {
                        pendingChanges.add(pcEntry);
                    }
                }
            }
        } else {
            // Canonicalize the input.
            itemSpec.setItem(LocalPath.canonicalize(itemSpec.getItem()));

            final AtomicReference<Failure> outDummy = new AtomicReference<Failure>();
            final ParsedItemSpec parsedItemSpec = ParsedItemSpec.fromLocalItemSpec(itemSpec, wp, lv, pc, flags,
                    outDummy, includeCandidates);

            if (null != parsedItemSpec) {
                if (RecursionType.NONE == parsedItemSpec.getRecursionType()) {
                    // Easy case -- one lookup in the pending changes table
                    final Iterator<WorkspaceLocalItem> items = parsedItemSpec.expandFrom(lv, pc, outDummy)
                            .iterator();
                    WorkspaceLocalItem lvEntry = items.hasNext() ? items.next() : null;
                    LocalPendingChange pcEntry = null;

                    if (null != lvEntry) {
                        pcEntry = pc.getByLocalVersion(lvEntry);
                    } else {
                        final String targetServerItem = WorkingFolder.getServerItemForLocalItem(
                                parsedItemSpec.getTargetItem(), wp.getWorkingFolders());

                        if (null != targetServerItem) {
                            pcEntry = pc.getByTargetServerItem(targetServerItem);

                            // if we have it in a different spot in our
                            // workspace, don't include it.
                            if (pcEntry != null) {
                                lvEntry = lv.getByPendingChange(pcEntry);

                                if (null != lvEntry && !lvEntry.isDeleted()) {
                                    pcEntry = null;
                                }
                            }
                        }
                    }

                    if (null != pcEntry) {
                        pendingChanges.add(pcEntry);
                    }
                } else {
                    // Query plan: Scan the entire pending changes table and
                    // look up each committed server item in the local
                    // version table to see if it matches the itemspec
                    // provided. The assumption is that the size of the
                    // pending changes table is much less than the size of
                    // the local version table, at least most of the time.
                    for (final LocalPendingChange pcEntry : pc.queryByTargetServerItem(ServerPath.ROOT,
                            RecursionType.FULL, null)) {
                        String targetLocalItem;
                        final WorkspaceLocalItem lvEntry = lv.getByPendingChange(pcEntry);

                        if (null != lvEntry && !lvEntry.isDeleted()) {
                            targetLocalItem = lvEntry.getLocalItem();
                        } else {
                            // There is no local version entry for this
                            // item.
                            // Calculate its target local item using the
                            // workspace mappings.
                            targetLocalItem = WorkingFolder.getLocalItemForServerItem(
                                    pcEntry.getTargetServerItem(), wp.getWorkingFolders());
                        }

                        if (null != targetLocalItem && parsedItemSpec.match(targetLocalItem)) {
                            pendingChanges.add(pcEntry);
                        }
                    }
                }

                if (includeCandidates) {
                    // The target server item and local item of a candidate
                    // pending change are always in sync with the workspace
                    // mappings, so we can perform a more efficient query
                    // plan here where we walk the candidates table by the
                    // mapped server item of the local item provided.
                    final String targetServerItem = WorkingFolder
                            .getServerItemForLocalItem(parsedItemSpec.getTargetItem(), wp.getWorkingFolders());

                    if (null != targetServerItem) {
                        final Iterable<LocalPendingChange> candidateEntries = pc
                                .queryCandidatesByTargetServerItem(targetServerItem,
                                        parsedItemSpec.getRecursionType(), parsedItemSpec.getPattern());

                        for (final LocalPendingChange candidateEntry : candidateEntries) {
                            pendingChanges.add(candidateEntry);
                        }
                    }
                }
            }
        }

        if (pendingChanges.size() > 0) {
            itemSpecResults.add(pendingChanges);
        } else {
            final String format = Messages
                    .getString("LocalDataAccessLayer.NoPendingChangesMatchingItemSpecFormat"); //$NON-NLS-1$
            failuresAccumulator.add(new Failure(MessageFormat.format(format, itemSpec.getItem()),
                    FailureCodes.ITEM_NOT_CHECKED_OUT_EXCEPTION, SeverityType.ERROR, itemSpec.getItem()));
        }
    }

    if (itemSpecResults.size() == 1) {
        return itemSpecResults.get(0);
    } else {
        final Set<LocalPendingChange> toReturn = new TreeSet<LocalPendingChange>(
                LocalPendingChange.SERVER_ITEM_COMPARATOR);

        for (final List<LocalPendingChange> pendingChanges : itemSpecResults) {
            for (final LocalPendingChange pendingChange : pendingChanges) {
                toReturn.add(pendingChange);
            }
        }

        return toReturn;
    }
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.MainForm.java

@Override
public HexLayer makeHexLayer(final String name, final String comment) {
    if (name == null) {
        throw new NullPointerException("Name must not be null");
    }/*from  ww  w  .j  a v a 2  s  .co m*/
    if (comment == null) {
        throw new NullPointerException("Comments must not be null");
    }

    final AtomicReference<HexLayer> result = new AtomicReference<HexLayer>();

    final Runnable run = new Runnable() {
        @Override
        public void run() {
            result.set(layers.addLayer(layers.makeNewLayerField(name, comment)));
        }
    };

    if (SwingUtilities.isEventDispatchThread()) {
        run.run();
    } else {
        try {
            SwingUtilities.invokeAndWait(run);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    return result.get();
}

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

@Override
public GetOperation[] undoPendingChanges(final String workspaceName, final String ownerName,
        final ItemSpec[] items, final AtomicReference<Failure[]> failures, final String[] itemAttributeFilters,
        final String[] itemPropertyFilters, final AtomicBoolean onlineOperation, final boolean deleteAdds,
        final AtomicReference<ChangePendedFlags> changePendedFlags) {
    onlineOperation.set(true);/*from   w  w  w  .  j a va  2s . c  o m*/

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

    final Workspace localWorkspace = getLocalWorkspace(workspaceName, ownerName);

    if (localWorkspace != null) {
        final AtomicReference<GetOperation[]> toReturn = new AtomicReference<GetOperation[]>();

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

            transaction.execute(new AllTablesTransaction() {
                @Override
                public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv,
                        final LocalPendingChangesTable pc) {
                    toReturn.set(LocalDataAccessLayer.undoPendingChanges(localWorkspace, wp, lv, pc, items,
                            delegateFailures, onlineOperationRequired, itemPropertyFilters));

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

                    /*
                     * we should check to see if we are going to cause an
                     * existing file conflict if we are abort the
                     * transaction - since we don't want to try and contact
                     * the server in an offline undo.
                     */
                    if (toReturn.get() != null) {
                        Map<String, GetOperation> localItemDictionary = null;

                        for (final GetOperation op : toReturn.get()) {
                            if (op.getItemType() == ItemType.FILE && op.getTargetLocalItem() != null
                                    && op.getTargetLocalItem().length() > 0
                                    && LocalPath.equals(op.getTargetLocalItem(),
                                            op.getCurrentLocalItem()) == false) {
                                final WorkspaceLocalItem item = lv.getByLocalItem(op.getTargetLocalItem());

                                if ((item == null || item.isDeleted())
                                        && new File(op.getTargetLocalItem()).exists()) {
                                    if (localItemDictionary == null) {
                                        localItemDictionary = new HashMap<String, GetOperation>();
                                        /*
                                         * we go through our list and keep
                                         * track of adds we are removing
                                         * this is for the shelve /move
                                         * case.
                                         */
                                        for (final GetOperation getOp : toReturn.get()) {
                                            if (getOp.getTargetLocalItem() != null
                                                    && getOp.getTargetLocalItem().length() > 0
                                                    && getOp.getItemType() == ItemType.FILE) {
                                                final GetOperation currentValue = localItemDictionary
                                                        .get(getOp.getTargetLocalItem());
                                                if (currentValue != null) {
                                                    // don't overwrite an
                                                    // add
                                                    if (currentValue.getChangeType().contains(ChangeType.ADD)) {
                                                        localItemDictionary.put(getOp.getTargetLocalItem(),
                                                                getOp);
                                                    }
                                                } else {
                                                    localItemDictionary.put(getOp.getTargetLocalItem(), getOp);
                                                }
                                            }
                                        }
                                    }

                                    final GetOperation existingItem = localItemDictionary
                                            .get(op.getTargetLocalItem());
                                    if (existingItem != null
                                            && existingItem.getChangeType().contains(ChangeType.ADD)) {
                                        /*
                                         * if we are going to be removing
                                         * this anyway don't worry
                                         */
                                        if (deleteAdds) {
                                            continue;
                                        }
                                    }

                                    if (existingItem == null
                                            || !tryMoveAddLocation(existingItem, localItemDictionary)) {
                                        throw new VersionControlException(MessageFormat.format(
                                                //@formatter:off
                                                Messages.getString(
                                                        "WebServiceLayerLocalWorkspaces.UndoItemExistsLocallyFormat"), //$NON-NLS-1$
                                                //@formatter:on
                                                (op.getCurrentLocalItem() != null
                                                        && op.getCurrentLocalItem().length() > 0)
                                                                ? op.getCurrentLocalItem()
                                                                : op.getTargetLocalItem(),
                                                op.getTargetLocalItem()));
                                    }
                                }
                            }
                        }
                    }
                }
            });

            if (null != toReturn.get()) {
                onlineOperation.set(false);
                failures.set(delegateFailures.get());
                return toReturn.get();
            }
        } finally {
            try {
                transaction.close();
            } catch (final IOException e) {
                throw new VersionControlException(e);
            }
        }

        final Workspace w = reconcileIfLocal(workspaceName, ownerName);

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

        try {
            try {
                if (getServiceLevel().getValue() >= WebServiceLevel.TFS_2012_QU1.getValue()) {
                    final _Repository5Soap_UndoPendingChangesInLocalWorkspaceResponse response = getRepository5()
                            .undoPendingChangesInLocalWorkspace(workspaceName, ownerName,
                                    (_ItemSpec[]) WrapperUtils.unwrap(_ItemSpec.class, items),
                                    itemPropertyFilters, itemAttributeFilters,
                                    VersionControlConstants.MAX_SERVER_PATH_SIZE);

                    failures.set((Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures()));
                    changePendedFlags.set(new ChangePendedFlags(response.getChangePendedFlags()));
                    toReturn.set((GetOperation[]) WrapperUtils.wrap(GetOperation.class,
                            response.getUndoPendingChangesInLocalWorkspaceResult()));
                } else {
                    final _Repository4Soap_UndoPendingChangesInLocalWorkspaceResponse response = getRepository4()
                            .undoPendingChangesInLocalWorkspace(workspaceName, ownerName,
                                    (_ItemSpec[]) WrapperUtils.unwrap(_ItemSpec.class, items),
                                    itemPropertyFilters, itemAttributeFilters);

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

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

            // When a pending add is undone, the item on disk is not
            // touched; so we need to inform the scanner that the item is
            // invalidated so it is re-scanned. We'll invalidate the scanner
            // if we detect that we went to the server to undo a pending
            // add.
            if (null != toReturn.get()) {
                for (final GetOperation op : toReturn.get()) {
                    if (op.getChangeType().contains(ChangeType.ADD)) {
                        localWorkspace.getWorkspaceWatcher().markPathChanged(""); //$NON-NLS-1$
                        break;
                    }
                }
            }

            return toReturn.get();
        } finally {
            if (lock != null) {
                lock.close();
            }
        }
    } else {
        return super.undoPendingChanges(workspaceName, ownerName, items, failures, itemAttributeFilters,
                itemPropertyFilters, onlineOperation, deleteAdds, changePendedFlags);
    }
}

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

private QueryTripsResult queryTripsBinary(final HttpUrl url, final Location from, final @Nullable Location via,
        final Location to, final int expectedBufferSize) throws IOException {
    /*//from  ww w.j a  v a 2  s.c o m
     * Many thanks to Malte Starostik and Robert, who helped a lot with analyzing this API!
     */

    final AtomicReference<QueryTripsResult> result = new AtomicReference<>();

    httpClient.getInputStream(new HttpClient.Callback() {
        @Override
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            final CustomBufferedInputStream bis = new CustomBufferedInputStream(
                    new GZIPInputStream(body.byteStream()));

            // initialize input stream
            final LittleEndianDataInputStream is = new LittleEndianDataInputStream(bis);
            is.mark(expectedBufferSize);

            // quick check of status
            final int version = is.readShortReverse();
            if (version != 6 && version != 5)
                throw new IllegalStateException("unknown version: " + version + ", first chars: " + bodyPeek);
            final ResultHeader header = new ResultHeader(network, SERVER_PRODUCT, Integer.toString(version),
                    null, 0, null);

            // quick seek for pointers
            is.reset();
            is.skipBytes(0x20);
            final int serviceDaysTablePtr = is.readIntReverse();
            final int stringTablePtr = is.readIntReverse();

            is.reset();
            is.skipBytes(0x36);
            final int stationTablePtr = is.readIntReverse();
            final int commentTablePtr = is.readIntReverse();

            is.reset();
            is.skipBytes(0x46);
            final int extensionHeaderPtr = is.readIntReverse();

            // read strings
            final StringTable strings = new StringTable(is, stringTablePtr,
                    serviceDaysTablePtr - stringTablePtr);

            is.reset();
            is.skipBytes(extensionHeaderPtr);

            // read extension header
            final int extensionHeaderLength = is.readIntReverse();
            if (extensionHeaderLength < 0x2c)
                throw new IllegalStateException("too short: " + extensionHeaderLength);

            is.skipBytes(12);
            final int errorCode = is.readShortReverse();

            if (errorCode == 0) {
                // string encoding
                is.skipBytes(14);
                final Charset stringEncoding = Charset.forName(strings.read(is));
                strings.setEncoding(stringEncoding);

                // read number of trips
                is.reset();
                is.skipBytes(30);

                final int numTrips = is.readShortReverse();
                if (numTrips == 0) {
                    result.set(new QueryTripsResult(header, url.toString(), from, via, to, null,
                            new LinkedList<Trip>()));
                    return;
                }

                // read rest of header
                is.reset();
                is.skipBytes(0x02);

                final Location resDeparture = location(is, strings);
                final Location resArrival = location(is, strings);

                is.skipBytes(10);

                final long resDate = date(is);
                /* final long resDate30 = */date(is);

                is.reset();
                is.skipBytes(extensionHeaderPtr + 0x8);

                final int seqNr = is.readShortReverse();
                if (seqNr == 0)
                    throw new SessionExpiredException();
                else if (seqNr < 0)
                    throw new IllegalStateException("illegal sequence number: " + seqNr);

                final String requestId = strings.read(is);

                final int tripDetailsPtr = is.readIntReverse();
                if (tripDetailsPtr == 0)
                    throw new IllegalStateException("no connection details");

                is.skipBytes(4);

                final int disruptionsPtr = is.readIntReverse();

                is.skipBytes(10);

                final String ld = strings.read(is);
                final int attrsOffset = is.readIntReverse();

                final int tripAttrsPtr;
                if (extensionHeaderLength >= 0x30) {
                    if (extensionHeaderLength < 0x32)
                        throw new IllegalArgumentException("too short: " + extensionHeaderLength);
                    is.reset();
                    is.skipBytes(extensionHeaderPtr + 0x2c);
                    tripAttrsPtr = is.readIntReverse();
                } else {
                    tripAttrsPtr = 0;
                }

                // determine stops offset
                is.reset();
                is.skipBytes(tripDetailsPtr);
                final int tripDetailsVersion = is.readShortReverse();
                if (tripDetailsVersion != 1)
                    throw new IllegalStateException("unknown trip details version: " + tripDetailsVersion);
                is.skipBytes(0x02);

                final int tripDetailsIndexOffset = is.readShortReverse();
                final int tripDetailsLegOffset = is.readShortReverse();
                final int tripDetailsLegSize = is.readShortReverse();
                final int stopsSize = is.readShortReverse();
                final int stopsOffset = is.readShortReverse();

                // read stations
                final StationTable stations = new StationTable(is, stationTablePtr,
                        commentTablePtr - stationTablePtr, strings);

                // read comments
                final CommentTable comments = new CommentTable(is, commentTablePtr,
                        tripDetailsPtr - commentTablePtr, strings);

                final List<Trip> trips = new ArrayList<>(numTrips);

                // read trips
                for (int iTrip = 0; iTrip < numTrips; iTrip++) {
                    is.reset();
                    is.skipBytes(0x4a + iTrip * 12);

                    final int serviceDaysTableOffset = is.readShortReverse();

                    final int legsOffset = is.readIntReverse();

                    final int numLegs = is.readShortReverse();

                    final int numChanges = is.readShortReverse();

                    /* final long duration = time(is, 0, 0); */is.readShortReverse();

                    is.reset();
                    is.skipBytes(serviceDaysTablePtr + serviceDaysTableOffset);

                    /* final String serviceDaysText = */strings.read(is);

                    final int serviceBitBase = is.readShortReverse();
                    final int serviceBitLength = is.readShortReverse();

                    int tripDayOffset = serviceBitBase * 8;
                    for (int i = 0; i < serviceBitLength; i++) {
                        int serviceBits = is.read();
                        if (serviceBits == 0) {
                            tripDayOffset += 8;
                            continue;
                        }
                        while ((serviceBits & 0x80) == 0) {
                            serviceBits = serviceBits << 1;
                            tripDayOffset++;
                        }
                        break;
                    }

                    is.reset();
                    is.skipBytes(tripDetailsPtr + tripDetailsIndexOffset + iTrip * 2);
                    final int tripDetailsOffset = is.readShortReverse();

                    is.reset();
                    is.skipBytes(tripDetailsPtr + tripDetailsOffset);
                    final int realtimeStatus = is.readShortReverse();

                    /* final short delay = */is.readShortReverse();

                    /* final int legIndex = */is.readShortReverse();

                    is.skipBytes(2); // 0xffff

                    /* final int legStatus = */is.readShortReverse();

                    is.skipBytes(2); // 0x0000

                    String connectionId = null;
                    if (tripAttrsPtr != 0) {
                        is.reset();
                        is.skipBytes(tripAttrsPtr + iTrip * 2);
                        final int tripAttrsIndex = is.readShortReverse();

                        is.reset();
                        is.skipBytes(attrsOffset + tripAttrsIndex * 4);
                        while (true) {
                            final String key = strings.read(is);
                            if (key == null)
                                break;
                            else if (key.equals("ConnectionId"))
                                connectionId = strings.read(is);
                            else
                                is.skipBytes(2);
                        }
                    }

                    final List<Trip.Leg> legs = new ArrayList<>(numLegs);

                    for (int iLegs = 0; iLegs < numLegs; iLegs++) {
                        is.reset();
                        is.skipBytes(0x4a + legsOffset + iLegs * 20);

                        final long plannedDepartureTime = time(is, resDate, tripDayOffset);
                        final Location departureLocation = stations.read(is);

                        final long plannedArrivalTime = time(is, resDate, tripDayOffset);
                        final Location arrivalLocation = stations.read(is);

                        final int type = is.readShortReverse();

                        final String lineName = strings.read(is);

                        final Position plannedDeparturePosition = normalizePosition(strings.read(is));
                        final Position plannedArrivalPosition = normalizePosition(strings.read(is));

                        final int legAttrIndex = is.readShortReverse();

                        final List<Line.Attr> lineAttrs = new ArrayList<>();
                        String lineComment = null;
                        boolean lineOnDemand = false;
                        for (final String comment : comments.read(is)) {
                            if (comment.startsWith("bf ")) {
                                lineAttrs.add(Line.Attr.WHEEL_CHAIR_ACCESS);
                            } else if (comment.startsWith("FA ") || comment.startsWith("FB ")
                                    || comment.startsWith("FR ")) {
                                lineAttrs.add(Line.Attr.BICYCLE_CARRIAGE);
                            } else if (comment.startsWith("$R ") || comment.startsWith("ga ")
                                    || comment.startsWith("ja ") || comment.startsWith("Vs ")
                                    || comment.startsWith("mu ") || comment.startsWith("mx ")) {
                                lineOnDemand = true;
                                lineComment = comment.substring(5);
                            }
                        }

                        is.reset();
                        is.skipBytes(attrsOffset + legAttrIndex * 4);
                        String directionStr = null;
                        int lineClass = 0;
                        String lineCategory = null;
                        String routingType = null;
                        String lineNetwork = null;
                        while (true) {
                            final String key = strings.read(is);
                            if (key == null)
                                break;
                            else if (key.equals("Direction"))
                                directionStr = strings.read(is);
                            else if (key.equals("Class"))
                                lineClass = Integer.parseInt(strings.read(is));
                            else if (key.equals("Category"))
                                lineCategory = strings.read(is);
                            // else if (key.equals("Operator"))
                            // lineOperator = strings.read(is);
                            else if (key.equals("GisRoutingType"))
                                routingType = strings.read(is);
                            else if (key.equals("AdminCode"))
                                lineNetwork = normalizeLineAdministration(strings.read(is));
                            else
                                is.skipBytes(2);
                        }

                        if (lineCategory == null && lineName != null)
                            lineCategory = categoryFromName(lineName);

                        is.reset();
                        is.skipBytes(tripDetailsPtr + tripDetailsOffset + tripDetailsLegOffset
                                + iLegs * tripDetailsLegSize);

                        if (tripDetailsLegSize != 16)
                            throw new IllegalStateException(
                                    "unhandled trip details leg size: " + tripDetailsLegSize);

                        final long predictedDepartureTime = time(is, resDate, tripDayOffset);
                        final long predictedArrivalTime = time(is, resDate, tripDayOffset);
                        final Position predictedDeparturePosition = normalizePosition(strings.read(is));
                        final Position predictedArrivalPosition = normalizePosition(strings.read(is));

                        final int bits = is.readShortReverse();
                        final boolean arrivalCancelled = (bits & 0x10) != 0;
                        final boolean departureCancelled = (bits & 0x20) != 0;

                        is.readShort();

                        final int firstStopIndex = is.readShortReverse();

                        final int numStops = is.readShortReverse();

                        is.reset();
                        is.skipBytes(disruptionsPtr);

                        String disruptionText = null;

                        if (is.readShortReverse() == 1) {
                            is.reset();
                            is.skipBytes(disruptionsPtr + 2 + iTrip * 2);

                            int disruptionsOffset = is.readShortReverse();
                            while (disruptionsOffset != 0) {
                                is.reset();
                                is.skipBytes(disruptionsPtr + disruptionsOffset);

                                strings.read(is); // "0"

                                final int disruptionLeg = is.readShortReverse();

                                is.skipBytes(2); // bitmaske

                                strings.read(is); // start of line
                                strings.read(is); // end of line

                                strings.read(is);
                                // id
                                /* final String disruptionTitle = */strings.read(is);
                                final String disruptionShortText = ParserUtils.formatHtml(strings.read(is));

                                disruptionsOffset = is.readShortReverse(); // next

                                if (iLegs == disruptionLeg) {
                                    final int disruptionAttrsIndex = is.readShortReverse();

                                    is.reset();
                                    is.skipBytes(attrsOffset + disruptionAttrsIndex * 4);

                                    while (true) {
                                        final String key = strings.read(is);
                                        if (key == null)
                                            break;
                                        else if (key.equals("Text"))
                                            disruptionText = ParserUtils.resolveEntities(strings.read(is));
                                        else
                                            is.skipBytes(2);
                                    }

                                    if (disruptionShortText != null)
                                        disruptionText = disruptionShortText;
                                }
                            }
                        }

                        List<Stop> intermediateStops = null;

                        if (numStops > 0) {
                            is.reset();
                            is.skipBytes(tripDetailsPtr + stopsOffset + firstStopIndex * stopsSize);

                            if (stopsSize != 26)
                                throw new IllegalStateException("unhandled stops size: " + stopsSize);

                            intermediateStops = new ArrayList<>(numStops);

                            for (int iStop = 0; iStop < numStops; iStop++) {
                                final long plannedStopDepartureTime = time(is, resDate, tripDayOffset);
                                final Date plannedStopDepartureDate = plannedStopDepartureTime != 0
                                        ? new Date(plannedStopDepartureTime)
                                        : null;
                                final long plannedStopArrivalTime = time(is, resDate, tripDayOffset);
                                final Date plannedStopArrivalDate = plannedStopArrivalTime != 0
                                        ? new Date(plannedStopArrivalTime)
                                        : null;
                                final Position plannedStopDeparturePosition = normalizePosition(
                                        strings.read(is));
                                final Position plannedStopArrivalPosition = normalizePosition(strings.read(is));

                                is.readInt();

                                final long predictedStopDepartureTime = time(is, resDate, tripDayOffset);
                                final Date predictedStopDepartureDate = predictedStopDepartureTime != 0
                                        ? new Date(predictedStopDepartureTime)
                                        : null;
                                final long predictedStopArrivalTime = time(is, resDate, tripDayOffset);
                                final Date predictedStopArrivalDate = predictedStopArrivalTime != 0
                                        ? new Date(predictedStopArrivalTime)
                                        : null;
                                final Position predictedStopDeparturePosition = normalizePosition(
                                        strings.read(is));
                                final Position predictedStopArrivalPosition = normalizePosition(
                                        strings.read(is));

                                final int stopBits = is.readShortReverse();
                                final boolean stopArrivalCancelled = (stopBits & 0x10) != 0;
                                final boolean stopDepartureCancelled = (stopBits & 0x20) != 0;

                                is.readShort();

                                final Location stopLocation = stations.read(is);

                                final boolean validPredictedDate = !dominantPlanStopTime
                                        || (plannedStopArrivalDate != null && plannedStopDepartureDate != null);

                                final Stop stop = new Stop(stopLocation, plannedStopArrivalDate,
                                        validPredictedDate ? predictedStopArrivalDate : null,
                                        plannedStopArrivalPosition, predictedStopArrivalPosition,
                                        stopArrivalCancelled, plannedStopDepartureDate,
                                        validPredictedDate ? predictedStopDepartureDate : null,
                                        plannedStopDeparturePosition, predictedStopDeparturePosition,
                                        stopDepartureCancelled);

                                intermediateStops.add(stop);
                            }
                        }

                        final Trip.Leg leg;
                        if (type == 1 /* Fussweg */ || type == 3 /* Uebergang */ || type == 4 /* Uebergang */) {
                            final Trip.Individual.Type individualType;
                            if (routingType == null)
                                individualType = type == 1 ? Trip.Individual.Type.WALK
                                        : Trip.Individual.Type.TRANSFER;
                            else if ("FOOT".equals(routingType))
                                individualType = Trip.Individual.Type.WALK;
                            else if ("BIKE".equals(routingType))
                                individualType = Trip.Individual.Type.BIKE;
                            else if ("CAR".equals(routingType) || "P+R".equals(routingType))
                                individualType = Trip.Individual.Type.CAR;
                            else
                                throw new IllegalStateException("unknown routingType: " + routingType);

                            final Date departureTime = new Date(
                                    predictedDepartureTime != 0 ? predictedDepartureTime
                                            : plannedDepartureTime);
                            final Date arrivalTime = new Date(
                                    predictedArrivalTime != 0 ? predictedArrivalTime : plannedArrivalTime);

                            final Trip.Leg lastLeg = legs.size() > 0 ? legs.get(legs.size() - 1) : null;
                            if (lastLeg != null && lastLeg instanceof Trip.Individual
                                    && ((Trip.Individual) lastLeg).type == individualType) {
                                final Trip.Individual lastIndividualLeg = (Trip.Individual) legs
                                        .remove(legs.size() - 1);
                                leg = new Trip.Individual(individualType, lastIndividualLeg.departure,
                                        lastIndividualLeg.departureTime, arrivalLocation, arrivalTime, null, 0);
                            } else {
                                leg = new Trip.Individual(individualType, departureLocation, departureTime,
                                        arrivalLocation, arrivalTime, null, 0);
                            }
                        } else if (type == 2) {
                            final Product lineProduct;
                            if (lineOnDemand)
                                lineProduct = Product.ON_DEMAND;
                            else if (lineClass != 0)
                                lineProduct = intToProduct(lineClass);
                            else
                                lineProduct = normalizeType(lineCategory);

                            final Line line = newLine(lineNetwork, lineProduct, normalizeLineName(lineName),
                                    lineComment, lineAttrs.toArray(new Line.Attr[0]));

                            final Location direction;
                            if (directionStr != null) {
                                final String[] directionPlaceAndName = splitStationName(directionStr);
                                direction = new Location(LocationType.ANY, null, directionPlaceAndName[0],
                                        directionPlaceAndName[1]);
                            } else {
                                direction = null;
                            }

                            final Stop departure = new Stop(departureLocation, true,
                                    plannedDepartureTime != 0 ? new Date(plannedDepartureTime) : null,
                                    predictedDepartureTime != 0 ? new Date(predictedDepartureTime) : null,
                                    plannedDeparturePosition, predictedDeparturePosition, departureCancelled);
                            final Stop arrival = new Stop(arrivalLocation, false,
                                    plannedArrivalTime != 0 ? new Date(plannedArrivalTime) : null,
                                    predictedArrivalTime != 0 ? new Date(predictedArrivalTime) : null,
                                    plannedArrivalPosition, predictedArrivalPosition, arrivalCancelled);

                            leg = new Trip.Public(line, direction, departure, arrival, intermediateStops, null,
                                    disruptionText);
                        } else {
                            throw new IllegalStateException("unhandled type: " + type);
                        }
                        legs.add(leg);
                    }

                    final Trip trip = new Trip(connectionId, resDeparture, resArrival, legs, null, null,
                            (int) numChanges);

                    if (realtimeStatus != 2) // Verbindung fllt aus
                        trips.add(trip);
                }

                // if result is only one single individual leg, don't query for more
                final boolean canQueryMore = trips.size() != 1 || trips.get(0).legs.size() != 1
                        || !(trips.get(0).legs.get(0) instanceof Trip.Individual);

                result.set(new QueryTripsResult(header, url.toString(), from, via, to,
                        new QueryTripsBinaryContext(requestId, seqNr, ld, bis.getCount(), canQueryMore),
                        trips));
            } else {
                log.debug("Hafas error: {}", errorCode);
                if (errorCode == 1) {
                    throw new SessionExpiredException();
                } else if (errorCode == 2) {
                    // F2: Your search results could not be stored internally.
                    throw new SessionExpiredException();
                } else if (errorCode == 8) {
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.AMBIGUOUS));
                    return;
                } else if (errorCode == 13) {
                    // IN13: Our booking system is currently being used by too many users at the same
                    // time.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN));
                    return;
                } else if (errorCode == 19) {
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN));
                    return;
                } else if (errorCode == 207) {
                    // H207: Unfortunately your connection request can currently not be processed.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN));
                    return;
                } else if (errorCode == 887) {
                    // H887: Your inquiry was too complex. Please try entering less intermediate stations.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 890) {
                    // H890: No connections have been found that correspond to your request. It is
                    // possible
                    // that the requested service does not operate from or to the places you stated on the
                    // requested date of travel.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 891) {
                    // H891: Unfortunately there was no route found. Missing timetable data could be the
                    // reason.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 892) {
                    // H892: Your inquiry was too complex. Please try entering less intermediate stations.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 899) {
                    // H899: there was an unsuccessful or incomplete search due to a timetable change.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 900) {
                    // Unsuccessful or incomplete search (timetable change)
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 9220) {
                    // H9220: Nearby to the given address stations could not be found.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.UNRESOLVABLE_ADDRESS));
                    return;
                } else if (errorCode == 9240) {
                    // H9240: Unfortunately there was no route found. Perhaps your start or destination is
                    // not
                    // served at all or with the selected means of transport on the required date/time.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.NO_TRIPS));
                    return;
                } else if (errorCode == 9260) {
                    // H9260: Unknown departure station
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.UNKNOWN_FROM));
                    return;
                } else if (errorCode == 9280) {
                    // H9280: Unknown intermediate station
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.UNKNOWN_VIA));
                    return;
                } else if (errorCode == 9300) {
                    // H9300: Unknown arrival station
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.UNKNOWN_TO));
                    return;
                } else if (errorCode == 9320) {
                    // The input is incorrect or incomplete
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.INVALID_DATE));
                    return;
                } else if (errorCode == 9360) {
                    // H9360: Unfortunately your connection request can currently not be processed.
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.INVALID_DATE));
                    return;
                } else if (errorCode == 9380) {
                    // H9380: Dep./Arr./Intermed. or equivalent station defined more than once
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.TOO_CLOSE));
                    return;
                } else if (errorCode == 895) {
                    // H895: Departure/Arrival are too near
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.TOO_CLOSE));
                    return;
                } else if (errorCode == 65535) {
                    result.set(new QueryTripsResult(header, QueryTripsResult.Status.SERVICE_DOWN));
                    return;
                } else {
                    throw new IllegalStateException("error " + errorCode + " on " + url);
                }
            }
        }
    }, url);

    return result.get();
}

From source file:com.clxcommunications.xms.ApiConnectionIT.java

@Test
public void canHandle500WhenDeletingGroup() throws Exception {
    String spid = TestUtils.freshServicePlanId();
    GroupId groupId = TestUtils.freshGroupId();

    String path = "/v1/" + spid + "/groups/" + groupId;

    wm.stubFor(delete(urlEqualTo(path)).willReturn(aResponse().withStatus(500)
            .withHeader("Content-Type", ContentType.TEXT_PLAIN.toString()).withBody("BAD")));

    ApiConnection conn = ApiConnection.builder().servicePlanId(spid).token("tok")
            .endpoint("http://localhost:" + wm.port()).start();

    /*//from w  ww.  j  ava2 s  .  c  om
     * The exception we'll receive in the callback. Need to store it to
     * verify that it is the same exception as received from #get().
     */
    final AtomicReference<Exception> failException = new AtomicReference<Exception>();

    try {
        /*
         * Used to make sure callback and test thread are agreeing about the
         * failException variable.
         */
        final CountDownLatch latch = new CountDownLatch(1);

        FutureCallback<Void> testCallback = new TestCallback<Void>() {

            @Override
            public void failed(Exception exception) {
                if (!failException.compareAndSet(null, exception)) {
                    fail("failed called multiple times");
                }

                latch.countDown();
            }

        };

        Future<Void> future = conn.deleteGroupAsync(groupId, testCallback);

        // Give plenty of time for the callback to be called.
        latch.await();

        future.get();
        fail("unexpected future get success");
    } catch (ExecutionException ee) {
        /*
         * The exception cause should be the same as we received in the
         * callback.
         */
        assertThat(failException.get(), is(theInstance(ee.getCause())));
        assertThat(ee.getCause(), is(instanceOf(UnexpectedResponseException.class)));

        UnexpectedResponseException ure = (UnexpectedResponseException) ee.getCause();

        HttpResponse response = ure.getResponse();
        assertThat(response, notNullValue());
        assertThat(response.getStatusLine().getStatusCode(), is(500));
        assertThat(response.getEntity().getContentType().getValue(), is(ContentType.TEXT_PLAIN.toString()));

        byte[] buf = new byte[100];
        int read;

        InputStream contentStream = null;
        try {
            contentStream = response.getEntity().getContent();
            read = contentStream.read(buf);
        } catch (IOException ioe) {
            throw new AssertionError("unexpected exception: " + ioe.getMessage(), ioe);
        } finally {
            if (contentStream != null) {
                try {
                    contentStream.close();
                } catch (IOException ioe) {
                    throw new AssertionError("unexpected exception: " + ioe.getMessage(), ioe);
                }
            }
        }

        assertThat(read, is(3));
        assertThat(Arrays.copyOf(buf, 3), is(new byte[] { 'B', 'A', 'D' }));
    } finally {
        conn.close();
    }

    verifyDeleteRequest(path);
}

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

private QueryDeparturesResult xsltDepartureMonitorRequest(final String stationId, final @Nullable Date time,
        final int maxDepartures, final boolean equivs) throws IOException {
    final HttpUrl.Builder url = departureMonitorEndpoint.newBuilder();
    appendXsltDepartureMonitorRequestParameters(url, stationId, time, maxDepartures, equivs);
    final AtomicReference<QueryDeparturesResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override/*from w  ww  .ja 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);

                final QueryDeparturesResult r = new QueryDeparturesResult(header);

                XmlPullUtil.enter(pp, "itdDepartureMonitorRequest");
                XmlPullUtil.optSkipMultiple(pp, "itdMessage");

                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 (findStationDepartures(r.stationDepartures, location.id) == null)
                                r.stationDepartures.add(new StationDepartures(location,
                                        new LinkedList<Departure>(), new LinkedList<LineDestination>()));
                    }
                });

                if ("notidentified".equals(nameState) || "list".equals(nameState)) {
                    result.set(new QueryDeparturesResult(header, QueryDeparturesResult.Status.INVALID_STATION));
                    return;
                }

                XmlPullUtil.optSkip(pp, "itdDateTime");

                XmlPullUtil.optSkip(pp, "itdDMDateTime");

                XmlPullUtil.optSkip(pp, "itdDateRange");

                XmlPullUtil.optSkip(pp, "itdTripOptions");

                XmlPullUtil.optSkip(pp, "itdMessage");

                if (XmlPullUtil.test(pp, "itdServingLines")) {
                    if (!pp.isEmptyElementTag()) {
                        XmlPullUtil.enter(pp, "itdServingLines");
                        while (XmlPullUtil.test(pp, "itdServingLine")) {
                            final String assignedStopId = XmlPullUtil.optAttr(pp, "assignedStopID", null);
                            final LineDestinationAndCancelled lineDestinationAndCancelled = processItdServingLine(
                                    pp);
                            final LineDestination lineDestination = new LineDestination(
                                    lineDestinationAndCancelled.line, lineDestinationAndCancelled.destination);

                            StationDepartures assignedStationDepartures;
                            if (assignedStopId == null)
                                assignedStationDepartures = r.stationDepartures.get(0);
                            else
                                assignedStationDepartures = findStationDepartures(r.stationDepartures,
                                        assignedStopId);

                            if (assignedStationDepartures == null)
                                assignedStationDepartures = new StationDepartures(
                                        new Location(LocationType.STATION, assignedStopId),
                                        new LinkedList<Departure>(), new LinkedList<LineDestination>());

                            final List<LineDestination> assignedStationDeparturesLines = checkNotNull(
                                    assignedStationDepartures.lines);
                            if (!assignedStationDeparturesLines.contains(lineDestination))
                                assignedStationDeparturesLines.add(lineDestination);
                        }
                        XmlPullUtil.skipExit(pp, "itdServingLines");
                    } else {
                        XmlPullUtil.next(pp);
                    }
                } else {
                    result.set(new QueryDeparturesResult(header, QueryDeparturesResult.Status.INVALID_STATION));
                    return;
                }

                XmlPullUtil.require(pp, "itdDepartureList");
                if (XmlPullUtil.optEnter(pp, "itdDepartureList")) {
                    final Calendar plannedDepartureTime = new GregorianCalendar(timeZone);
                    final Calendar predictedDepartureTime = new GregorianCalendar(timeZone);

                    while (XmlPullUtil.test(pp, "itdDeparture")) {
                        final String assignedStopId = XmlPullUtil.attr(pp, "stopID");

                        StationDepartures assignedStationDepartures = findStationDepartures(r.stationDepartures,
                                assignedStopId);
                        if (assignedStationDepartures == null) {
                            final Point coord = processCoordAttr(pp);

                            // final String name = normalizeLocationName(XmlPullUtil.attr(pp, "nameWO"));

                            assignedStationDepartures = new StationDepartures(
                                    new Location(LocationType.STATION, assignedStopId, coord),
                                    new LinkedList<Departure>(), new LinkedList<LineDestination>());
                        }

                        final Position position = parsePosition(XmlPullUtil.optAttr(pp, "platformName", null));

                        XmlPullUtil.enter(pp, "itdDeparture");

                        XmlPullUtil.require(pp, "itdDateTime");
                        plannedDepartureTime.clear();
                        processItdDateTime(pp, plannedDepartureTime);

                        predictedDepartureTime.clear();
                        if (XmlPullUtil.test(pp, "itdRTDateTime"))
                            processItdDateTime(pp, predictedDepartureTime);

                        XmlPullUtil.optSkip(pp, "itdFrequencyInfo");

                        XmlPullUtil.require(pp, "itdServingLine");
                        final boolean isRealtime = XmlPullUtil.attr(pp, "realtime").equals("1");
                        final LineDestinationAndCancelled lineDestinationAndCancelled = processItdServingLine(
                                pp);

                        if (isRealtime && !predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY))
                            predictedDepartureTime.setTimeInMillis(plannedDepartureTime.getTimeInMillis());

                        XmlPullUtil.skipExit(pp, "itdDeparture");

                        if (!lineDestinationAndCancelled.cancelled) {
                            final Departure departure = new Departure(plannedDepartureTime.getTime(),
                                    predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY)
                                            ? predictedDepartureTime.getTime()
                                            : null,
                                    lineDestinationAndCancelled.line, position,
                                    lineDestinationAndCancelled.destination, null, null);
                            assignedStationDepartures.departures.add(departure);
                        }
                    }

                    XmlPullUtil.skipExit(pp, "itdDepartureList");
                }

                result.set(r);
            } 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();
}