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

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

Introduction

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

Prototype

public final V get() 

Source Link

Document

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

Usage

From source file:com.microsoft.tfs.client.clc.commands.Command.java

/**
 * Displays a merge event.//from   www.jav a 2s .co m
 *
 * @param e
 *        the event to display
 */
private void displayMergingEvent(final MergingEvent e) {
    final AtomicReference<String> errorHolder = new AtomicReference<String>();
    final String message = e.getMessage(errorHolder);

    // Display the merge info.
    if (e.getStatus() == OperationStatus.CONFLICT) {
        getDisplay().printErrorLine(message);
        setExitCode(ExitCode.PARTIAL_SUCCESS);
    } else {
        getDisplay().printLine(message);
    }

    if (e.getStatus() == OperationStatus.GETTING || e.getStatus() == OperationStatus.REPLACING
            || e.getStatus() == OperationStatus.DELETING || e.getStatus() == OperationStatus.CONFLICT) {
        // Nothing to do
    } else if (e.getStatus() == OperationStatus.SOURCE_DIRECTORY_NOT_EMPTY
            || e.getStatus() == OperationStatus.SOURCE_WRITABLE
            || e.getStatus() == OperationStatus.TARGET_IS_DIRECTORY
            || e.getStatus() == OperationStatus.TARGET_LOCAL_PENDING
            || e.getStatus() == OperationStatus.TARGET_WRITABLE) {
        getDisplay().printErrorLine(errorHolder.get());
        setExitCode(ExitCode.PARTIAL_SUCCESS);
    }
}

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

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

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

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

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

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

    final GUID serverPendingChangeSignature = outServerPendingChangeSignature.get();

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

    for (final PendingChange pendingChange : pendingChanges) {
        final LocalPendingChange pcEntry = LocalPendingChange.fromPendingChange(pendingChange);
        pendingChangesTarget.set(pcEntry.getTargetServerItem(), pcEntry);
    }// w w  w.  jav  a  2  s. co  m

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

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

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

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

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

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

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

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

/**
 * It verifies that asyncRead timesout if it doesn't receive response from bk-client in configured timeout
 * //from ww w. j  ava2 s .  com
 * @throws Exception
 */
@Test
public void testManagedLedgerWithReadEntryTimeOut() throws Exception {
    ManagedLedgerConfig config = new ManagedLedgerConfig().setReadEntryTimeoutSeconds(1);
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("timeout_ledger_test", config);

    BookKeeper bk = mock(BookKeeper.class);
    doNothing().when(bk).asyncCreateLedger(anyInt(), anyInt(), anyInt(), any(), any(), any(), any(), any());
    AtomicReference<ManagedLedgerException> responseException1 = new AtomicReference<>();
    CountDownLatch latch1 = new CountDownLatch(1);

    CompletableFuture<LedgerEntries> entriesFuture = new CompletableFuture<>();
    ReadHandle ledgerHandle = mock(ReadHandle.class);
    doReturn(entriesFuture).when(ledgerHandle).readAsync(PositionImpl.earliest.getLedgerId(),
            PositionImpl.earliest.getEntryId());

    // (1) test read-timeout for: ManagedLedger.asyncReadEntry(..)
    ledger.asyncReadEntry(ledgerHandle, PositionImpl.earliest, new ReadEntryCallback() {
        @Override
        public void readEntryComplete(Entry entry, Object ctx) {
            responseException1.set(null);
            latch1.countDown();
        }

        @Override
        public void readEntryFailed(ManagedLedgerException exception, Object ctx) {
            responseException1.set(exception);
            latch1.countDown();
        }
    }, null);
    ledger.asyncCreateLedger(bk, config, null, new CreateCallback() {
        @Override
        public void createComplete(int rc, LedgerHandle lh, Object ctx) {

        }
    }, Collections.emptyMap());
    latch1.await(config.getReadEntryTimeoutSeconds() + 2, TimeUnit.SECONDS);
    assertNotNull(responseException1.get());
    assertEquals(responseException1.get().getMessage(),
            BKException.getMessage(BKException.Code.TimeoutException));

    // (2) test read-timeout for: ManagedLedger.asyncReadEntry(..)
    CountDownLatch latch2 = new CountDownLatch(1);
    AtomicReference<ManagedLedgerException> responseException2 = new AtomicReference<>();
    PositionImpl readPositionRef = PositionImpl.earliest;
    ManagedCursorImpl cursor = new ManagedCursorImpl(bk, config, ledger, "cursor1");
    OpReadEntry opReadEntry = OpReadEntry.create(cursor, readPositionRef, 1, new ReadEntriesCallback() {

        @Override
        public void readEntriesComplete(List<Entry> entries, Object ctx) {
            latch2.countDown();
        }

        @Override
        public void readEntriesFailed(ManagedLedgerException exception, Object ctx) {
            responseException2.set(exception);
            latch2.countDown();
        }

    }, null);
    ledger.asyncReadEntry(ledgerHandle, PositionImpl.earliest.getEntryId(), PositionImpl.earliest.getEntryId(),
            false, opReadEntry, null);
    latch2.await(config.getReadEntryTimeoutSeconds() + 2, TimeUnit.SECONDS);
    assertNotNull(responseException2.get());
    assertEquals(responseException2.get().getMessage(),
            BKException.getMessage(BKException.Code.TimeoutException));

    ledger.close();
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

private void doUploadMessage(final RoutingContext ctx, final String tenant, final String deviceId,
        final Buffer payload, final String contentType, final Future<MessageSender> senderTracker,
        final String endpointName) {

    if (!isPayloadOfIndicatedType(payload, contentType)) {
        HttpUtils.badRequest(ctx,/*w  ww.ja  v  a2 s .  c om*/
                String.format("Content-Type %s does not match with the payload", contentType));
    } else {
        final Integer qosHeader = getQoSLevel(ctx.request().getHeader(Constants.HEADER_QOS_LEVEL));
        if (contentType == null) {
            HttpUtils.badRequest(ctx, String.format("%s header is missing", HttpHeaders.CONTENT_TYPE));
        } else if (qosHeader != null && qosHeader == HEADER_QOS_INVALID) {
            HttpUtils.badRequest(ctx, "Bad QoS Header Value");
        } else {

            final Device authenticatedDevice = getAuthenticatedDevice(ctx);
            final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId,
                    authenticatedDevice);
            final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant);

            // AtomicBoolean to control if the downstream message was sent successfully
            final AtomicBoolean downstreamMessageSent = new AtomicBoolean(false);
            // AtomicReference to a Handler to be called to close an open command receiver link.
            final AtomicReference<Handler<Void>> closeLinkAndTimerHandlerRef = new AtomicReference<>();

            // Handler to be called with a received command. If the timer expired, null is provided as command.
            final Handler<Message> commandReceivedHandler = commandMessage -> {
                // reset the closeHandler reference, since it is not valid anymore at this time.
                closeLinkAndTimerHandlerRef.set(null);
                if (downstreamMessageSent.get()) {
                    // finish the request, since the response is now complete (command was added)
                    if (!ctx.response().closed()) {
                        ctx.response().end();
                    }
                }
            };

            CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> {

                if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) {
                    final MessageSender sender = senderTracker.result();
                    final Message downstreamMessage = newMessage(
                            ResourceIdentifier.from(endpointName, tenant, deviceId),
                            sender.isRegistrationAssertionRequired(), ctx.request().uri(), contentType, payload,
                            tokenTracker.result(), HttpUtils.getTimeTilDisconnect(ctx));
                    customizeDownstreamMessage(downstreamMessage, ctx);

                    // first open the command receiver link (if needed)
                    return openCommandReceiverLink(ctx, tenant, deviceId, commandReceivedHandler)
                            .compose(closeLinkAndTimerHandler -> {
                                closeLinkAndTimerHandlerRef.set(closeLinkAndTimerHandler);

                                if (qosHeader == null) {
                                    return sender.send(downstreamMessage);
                                } else {
                                    return sender.sendAndWaitForOutcome(downstreamMessage);
                                }
                            });
                } else {
                    // this adapter is not enabled for the tenant
                    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
                }
            }).compose(delivery -> {
                LOG.trace(
                        "successfully processed message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName);
                metrics.incrementProcessedHttpMessages(endpointName, tenant);
                ctx.response().setStatusCode(HttpURLConnection.HTTP_ACCEPTED);
                downstreamMessageSent.set(true);

                // if no command timer was created, the request now can be responded
                if (closeLinkAndTimerHandlerRef.get() == null) {
                    ctx.response().end();
                }

                return Future.succeededFuture();

            }).recover(t -> {

                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName, t);

                cancelResponseTimer(closeLinkAndTimerHandlerRef);

                if (ClientErrorException.class.isInstance(t)) {
                    final ClientErrorException e = (ClientErrorException) t;
                    ctx.fail(e.getErrorCode());
                } else {
                    metrics.incrementUndeliverableHttpMessages(endpointName, tenant);
                    HttpUtils.serviceUnavailable(ctx, 2);
                }
                return Future.failedFuture(t);
            });
        }
    }
}

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 w w . ja v a 2 s. co  m
     * 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:com.clxcommunications.xms.ApiConnectionIT.java

@Test
public void canHandle500WhenFetchingBatch() throws Exception {
    String spid = TestUtils.freshServicePlanId();
    BatchId batchId = TestUtils.freshBatchId();

    String path = "/v1/" + spid + "/batches/" + batchId;

    wm.stubFor(get(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  a  v  a  2 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<MtBatchSmsResult> testCallback = new TestCallback<MtBatchSmsResult>() {

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

                latch.countDown();
            }

        };

        Future<MtBatchSmsResult> future = conn.fetchBatchAsync(batchId, 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();
    }

    verifyGetRequest(path);
}

From source file:io.cloudslang.lang.tools.build.SlangBuilderTest.java

@Test
public void testProcessRunTestsMixed() {
    final Map<String, SlangTestCase> testCases = new LinkedHashMap<>();
    final SlangTestCase testCase1 = new SlangTestCase("test1", "testFlowPath", "desc", asList("abc", "new"),
            "mock", null, null, false, "SUCCESS");
    final SlangTestCase testCase2 = new SlangTestCase("test2", "testFlowPath", "desc", asList("efg", "new"),
            "mock", null, null, false, "SUCCESS");
    final SlangTestCase testCase3 = new SlangTestCase("test3", "testFlowPath", "desc", asList("new", "new2"),
            "mock", null, null, false, "SUCCESS");
    final SlangTestCase testCase4 = new SlangTestCase("test4", "testFlowPath", "desc", asList("new", "new2"),
            "mock", null, null, false, "SUCCESS");

    testCases.put("test1", testCase1);
    testCases.put("test2", testCase2);
    testCases.put("test3", testCase3);
    testCases.put("test4", testCase4);

    final List<String> testSuites = newArrayList("new");
    final Map<String, CompilationArtifact> compiledFlows = new HashMap<>();
    final String projectPath = "aaa";

    final AtomicReference<ThreadSafeRunTestResults> theCapturedArgument = new AtomicReference<>();
    final AtomicReference<Map<String, SlangTestCase>> capturedTestsSeq = new AtomicReference<>();
    final AtomicReference<Map<String, SlangTestCase>> capturedTestsPar = new AtomicReference<>();

    doCallRealMethod().when(slangTestRunner).isTestCaseInActiveSuite(any(SlangTestCase.class), anyList());
    doReturn(SlangBuildMain.TestCaseRunMode.SEQUENTIAL).doReturn(SlangBuildMain.TestCaseRunMode.PARALLEL)
            .doReturn(SlangBuildMain.TestCaseRunMode.PARALLEL)
            .doReturn(SlangBuildMain.TestCaseRunMode.SEQUENTIAL).when(testRunInfoService)
            .getRunModeForTestCase(any(SlangTestCase.class), any(ConflictResolutionStrategy.class),
                    any(DefaultResolutionStrategy.class));

    doAnswer(new Answer() {
        @Override//from w  ww.ja v  a  2s  .c  o m
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Object[] arguments = invocationOnMock.getArguments();
            Object argument = arguments[arguments.length - 2];
            theCapturedArgument.set((ThreadSafeRunTestResults) argument);

            return invocationOnMock.callRealMethod();
        }
    }).when(slangTestRunner).splitTestCasesByRunState(any(BulkRunMode.class), anyMap(), anyList(),
            any(IRunTestResults.class), eq(buildModeConfig));

    doAnswer(new Answer() {
        @Override
        @SuppressWarnings("unchecked")
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Object[] arguments = invocationOnMock.getArguments();
            capturedTestsSeq.set((Map<String, SlangTestCase>) arguments[1]);

            return null;
        }
    }).when(slangTestRunner).runTestsSequential(anyString(), anyMap(), anyMap(), any(IRunTestResults.class));
    doAnswer(new Answer() {
        @Override
        @SuppressWarnings("unchecked")
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Object[] arguments = invocationOnMock.getArguments();
            capturedTestsPar.set((Map<String, SlangTestCase>) arguments[1]);

            return null;
        }
    }).when(slangTestRunner).runTestsParallel(anyString(), anyMap(), anyMap(),
            any(ThreadSafeRunTestResults.class));

    // Tested call
    slangBuilder.processRunTests(projectPath, testSuites, POSSIBLY_MIXED, compiledFlows, testCases,
            buildModeConfig);

    InOrder inOrder = inOrder(slangTestRunner);
    inOrder.verify(slangTestRunner).splitTestCasesByRunState(eq(POSSIBLY_MIXED), eq(testCases), eq(testSuites),
            isA(ThreadSafeRunTestResults.class), eq(buildModeConfig));
    inOrder.verify(slangTestRunner).runTestsSequential(eq(projectPath), anyMap(), eq(compiledFlows),
            eq(theCapturedArgument.get()));
    inOrder.verify(slangTestRunner).runTestsParallel(eq(projectPath), anyMap(), eq(compiledFlows),
            eq(theCapturedArgument.get()));

    final List<SlangTestCase> listSeq = newArrayList(capturedTestsSeq.get().values());
    final List<SlangTestCase> listPar = newArrayList(capturedTestsPar.get().values());
    assertEquals(0, ListUtils.intersection(listSeq, listPar).size()); // assures that a test is run only once
    assertEquals(newHashSet(testCases.values()), newHashSet(ListUtils.union(listSeq, listPar)));
}

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

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

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

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

    return result.get();
}

From source file:com.quartercode.eventbridge.test.def.extra.extension.DefaultReturnEventExtensionReturnerTest.java

@SuppressWarnings("unchecked")
@Test//w w  w  .  ja  v a2  s.c  om
public void testReturnEventSenders() throws BridgeConnectorException {

    ToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE);

    final BridgeConnector source1 = null;
    final BridgeConnector source2 = context.mock(BridgeConnector.class, "source2");
    final BridgeConnector source3 = context.mock(BridgeConnector.class, "source3");

    final EmptyEvent1 returnEvent1 = new EmptyEvent1();
    final EmptyEvent2 returnEvent2 = new EmptyEvent2();
    final EmptyEvent3 returnEvent3 = new EmptyEvent3();
    final ReturnEventExtensionWrapper returnEvent1Wrapper = new ReturnEventExtensionWrapper(returnEvent1, 0,
            false);
    final ReturnEventExtensionWrapper returnEvent2Wrapper = new ReturnEventExtensionWrapper(returnEvent2, 1,
            false);
    final ReturnEventExtensionWrapper returnEvent3Wrapper = new ReturnEventExtensionWrapper(returnEvent3, 2,
            false);

    final RequestHandleInterceptor interceptor = context.mock(RequestHandleInterceptor.class);
    extension.getRequestHandleChannel().addInterceptor(new DummyRequestHandleInterceptor(interceptor), 1);

    final RequestEventHandler<Event> handler = context.mock(RequestEventHandler.class, "handler");
    final EventPredicate<Event> predicate = context.mock(EventPredicate.class, "predicate");
    final EventPredicate<?> wrapperPredicate = new ReturnEventExtensionWrapperPredicate(predicate);

    final AtomicReference<LowLevelHandler> lowLevelHandler = new AtomicReference<>();
    final AtomicReference<ReturnEventSender> returnEventSender1FromInterceptor = new AtomicReference<>();
    final AtomicReference<ReturnEventSender> returnEventSender2FromInterceptor = new AtomicReference<>();
    final AtomicReference<ReturnEventSender> returnEventSender3FromInterceptor = new AtomicReference<>();
    final AtomicReference<ReturnEventSender> returnEventSender1FromHandler = new AtomicReference<>();
    final AtomicReference<ReturnEventSender> returnEventSender2FromHandler = new AtomicReference<>();
    final AtomicReference<ReturnEventSender> returnEventSender3FromHandler = new AtomicReference<>();

    // @formatter:off
    context.checking(new Expectations() {
        {

            oneOf(lowLevelHandlerModule).addHandler(with(aLowLevelHandlerWithThePredicate(wrapperPredicate)));
            will(storeArgument(0).in(lowLevelHandler));

            final Sequence interceptorCalls = context.sequence("interceptorCalls");
            oneOf(interceptor).handleRequest(with(any(ChannelInvocation.class)), with(any(EmptyEvent1.class)),
                    with(source1), with(handler), with(any(ReturnEventSender.class)));
            inSequence(interceptorCalls);
            will(storeArgument(4).in(returnEventSender1FromInterceptor));
            oneOf(interceptor).handleRequest(with(any(ChannelInvocation.class)), with(any(EmptyEvent2.class)),
                    with(source2), with(handler), with(any(ReturnEventSender.class)));
            inSequence(interceptorCalls);
            will(storeArgument(4).in(returnEventSender2FromInterceptor));
            oneOf(interceptor).handleRequest(with(any(ChannelInvocation.class)), with(any(EmptyEvent3.class)),
                    with(source3), with(handler), with(any(ReturnEventSender.class)));
            inSequence(interceptorCalls);
            will(storeArgument(4).in(returnEventSender3FromInterceptor));

            final Sequence handlerCalls = context.sequence("handlerCalls");
            oneOf(handler).handle(with(any(EmptyEvent1.class)), with(any(ReturnEventSender.class)));
            inSequence(handlerCalls);
            will(storeArgument(1).in(returnEventSender1FromHandler));
            oneOf(handler).handle(with(any(EmptyEvent2.class)), with(any(ReturnEventSender.class)));
            inSequence(handlerCalls);
            will(storeArgument(1).in(returnEventSender2FromHandler));
            oneOf(handler).handle(with(any(EmptyEvent3.class)), with(any(ReturnEventSender.class)));
            inSequence(handlerCalls);
            will(storeArgument(1).in(returnEventSender3FromHandler));

            final Sequence returnSenderCalls = context.sequence("returnSenderCalls");
            oneOf(bridge).handle(returnEvent1Wrapper, source1);
            inSequence(returnSenderCalls);
            oneOf(source2).send(returnEvent2Wrapper);
            inSequence(handlerCalls);
            // Test exception suppression
            oneOf(source3).send(returnEvent3Wrapper);
            inSequence(handlerCalls);
            will(throwException(new BridgeConnectorException(source3)));

        }
    });
    // @formatter:on

    extension.addRequestHandler(handler, predicate);

    lowLevelHandler.get().handle(new ReturnEventExtensionWrapper(new EmptyEvent1(), 0, true), source1);
    lowLevelHandler.get().handle(new ReturnEventExtensionWrapper(new EmptyEvent2(), 1, true), source2);
    lowLevelHandler.get().handle(new ReturnEventExtensionWrapper(new EmptyEvent3(), 2, true), source3);

    assertTrue("Return event sender changes over time",
            returnEventSender1FromInterceptor.get() == returnEventSender1FromHandler.get());
    assertTrue("Return event sender changes over time",
            returnEventSender2FromInterceptor.get() == returnEventSender2FromHandler.get());
    assertTrue("Return event sender changes over time",
            returnEventSender3FromInterceptor.get() == returnEventSender3FromHandler.get());

    returnEventSender1FromInterceptor.get().send(returnEvent1);
    returnEventSender2FromInterceptor.get().send(returnEvent2);
    returnEventSender3FromInterceptor.get().send(returnEvent3);
}

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

/**
 * Process all the GetOperations the server returned to us as a result of
 * its get() method. This is generally not called directly from users of
 * this library. Instead, call the get methods in the {@link Workspace}
 * class.//from ww  w. j a  v a 2  s. c o m
 * <p>
 * <!-- 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 the
 *        workspace to process operations in (must not be <code>null</code>)
 * @param type
 *        the type of process to perform on the get operations (must not be
 *        <code>null</code>)
 * @param requestType
 *        the type of request for the operations (must not be
 *        <code>null</code>)
 * @param results
 *        the array of arrays of operations the server returned. Null items
 *        in the arrays will be skipped. Null arrays are not allowed.
 * @param options
 *        options for the get operation (must not be <code>null</code>)
 * @param deleteUndoneAdds
 *        if <code>true</code> adds which are undone can be deleted
 * @param onlineOperation
 *        true if this is for a server workspace
 * @param flags
 *        flags returned by the server when pending changes (must not be
 *        <code>null</code>; pass ChangePendedFlags.UNKNOWN if no server
 *        value available in your operation)
 * @return the status of the operation. Failure information for each item is
 *         available inside this object.
 * @throws CanceledException
 *         if the user canceled the processing through the default
 *         {@link TaskMonitor}
 */
public GetStatus processGetOperations(final Workspace workspace, final ProcessType type,
        final RequestType requestType, final GetOperation[][] results, final GetOptions options,
        final boolean deleteUndoneAdds, final boolean onlineOperation, final ChangePendedFlags flags)
        throws CanceledException {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$
    Check.notNull(type, "type"); //$NON-NLS-1$
    Check.notNull(requestType, "requestType"); //$NON-NLS-1$
    Check.notNull(results, "results"); //$NON-NLS-1$
    Check.notNull(options, "options"); //$NON-NLS-1$
    Check.notNull(flags, "flags"); //$NON-NLS-1$

    log.debug("Set all get operations type to: " + type.toString()); //$NON-NLS-1$
    int getOpsCount = 0;
    for (final GetOperation[] getOperations : results) {
        for (final GetOperation getOp : getOperations) {
            getOp.setProcessType(type);
            getOpsCount++;
        }
    }
    log.debug("Get operations count: " + String.valueOf(getOpsCount)); //$NON-NLS-1$

    final UpdateLocalVersionQueueOptions localUpdateOptions = calculateUpdateLocalVersionOptions(workspace,
            type, requestType, onlineOperation);

    log.debug("localUpdateOptions: " + localUpdateOptions.toString()); //$NON-NLS-1$
    log.debug("options: " + options.toString()); //$NON-NLS-1$

    final List<ClientLocalVersionUpdate> remapUpdates = new ArrayList<ClientLocalVersionUpdate>();

    if (WorkspaceLocation.LOCAL == workspace.getLocation() && options.contains(GetOptions.REMAP)) {
        final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
        try {
            log.debug("Trying to remap versions in the local workspace"); //$NON-NLS-1$
            transaction.execute(new LocalVersionTransaction() {
                @Override
                public void invoke(final WorkspaceVersionTable lv) {
                    // In a server workspace, when Remap is specified, the
                    // local version table is updated for you when an item
                    // is remapped. In a local workspace, the local version
                    // table is not updated, and a GetOperation is returned
                    // with VersionLocal set equal to VersionServer and
                    // SourceLocalItem equal to TargetLocalItem.
                    // VersionLocal is not actually set to that value yet.
                    // We must update the local version table (both local
                    // and server) in response to these GetOperations.

                    final boolean setLastFileTimeToCheckin = workspace.getOptions()
                            .contains(WorkspaceOptions.SET_FILE_TO_CHECKIN);

                    for (final GetOperation[] getOperations : results) {
                        for (final GetOperation getOp : getOperations) {
                            if (null != getOp.getTargetLocalItem()
                                    && LocalPath.equals(getOp.getSourceLocalItem(), getOp.getTargetLocalItem())
                                    &&
                            // Here the server is lying and telling us
                            // VersionLocal is equal to VersionServer
                            // even though it does not (yet). It is a
                            // signal that this is a remap operation.
                            getOp.getVersionLocal() == getOp.getVersionServer()) {
                                getOp.setIgnore(true);

                                final WorkspaceLocalItem lvExisting = lv
                                        .getByLocalItem(getOp.getTargetLocalItem());

                                if (null != lvExisting) {
                                    // If necessary, update the
                                    // last-modified time of the item on
                                    // disk to match the new check-in date
                                    // of the item that now occupies that
                                    // local path.
                                    if (setLastFileTimeToCheckin
                                            && !DotNETDate.MIN_CALENDAR.equals(getOp.getVersionServerDate())
                                            && VersionControlConstants.ENCODING_FOLDER != getOp.getEncoding()
                                            && new File(getOp.getTargetLocalItem()).exists()) {
                                        try {
                                            final File targetLocalFile = new File(getOp.getTargetLocalItem());
                                            final FileSystemAttributes attrs = FileSystemUtils.getInstance()
                                                    .getAttributes(targetLocalFile);
                                            boolean restoreReadOnly = false;

                                            if (attrs.isReadOnly()) {
                                                attrs.setReadOnly(false);
                                                FileSystemUtils.getInstance().setAttributes(targetLocalFile,
                                                        attrs);
                                                restoreReadOnly = true;
                                            }

                                            targetLocalFile.setLastModified(
                                                    getOp.getVersionServerDate().getTimeInMillis());

                                            if (restoreReadOnly) {
                                                attrs.setReadOnly(true);
                                                FileSystemUtils.getInstance().setAttributes(targetLocalFile,
                                                        attrs);
                                            }
                                        } catch (final Exception ex) {
                                            log.warn("Error setting file time for get with remap", ex); //$NON-NLS-1$
                                        }
                                    }

                                    remapUpdates.add(new ClientLocalVersionUpdate(getOp.getSourceServerItem(),
                                            getOp.getItemID(), getOp.getTargetLocalItem(),
                                            getOp.getVersionServer(), getOp.getVersionServerDate(),
                                            getOp.getEncoding(), lvExisting.getHashValue(),
                                            lvExisting.getLength(), lvExisting.getBaselineFileGUID(),
                                            null /* pendingChangeTargetServerItem */,
                                            getOp.getPropertyValues()));
                                }
                            }
                        }
                    }

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

        log.debug("The remapUpdates list has been prepared"); //$NON-NLS-1$
    }

    final WorkspaceLock wLock = workspace.lock();

    try {
        /*
         * Create a BaselineFolderCollection object to speed up read
         * operations on the baseline folders (so that each simple operation
         * like creating a new baseline file, deleting a baseline file, etc.
         * does not require us to open/close the WP table). Then attach that
         * BaselineFolderCollection to the WorkspaceLock which protects this
         * ProcessGetOperations().
         */
        final AtomicReference<BaselineFolderCollection> baselineFolders = new AtomicReference<BaselineFolderCollection>();

        if (workspace.getLocation() == WorkspaceLocation.LOCAL) {
            final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
            try {
                transaction.execute(new WorkspacePropertiesTransaction() {
                    @Override
                    public void invoke(final LocalWorkspaceProperties wp) {
                        baselineFolders.set(new BaselineFolderCollection(workspace, wp.getBaselineFolders()));
                    }
                });
            } finally {
                try {
                    transaction.close();
                } catch (final IOException e) {
                    throw new VersionControlException(e);
                }
            }

            wLock.setBaselineFolders(baselineFolders.get());
        }

        log.debug("remapUpdates.size(): " + remapUpdates.size()); //$NON-NLS-1$

        if (remapUpdates.size() > 0) {
            // If we have any remap update requests for the local version
            // table, execute them using a larger batch size than we
            // normally use. No file downloads are happening so these should
            // go through very quickly.
            Check.isTrue(localUpdateOptions.contains(UpdateLocalVersionQueueOptions.UPDATE_SERVER),
                    "localUpdateOptions.contains(UpdateLocalVersionQueueOptions.UPDATE_SERVER)"); //$NON-NLS-1$

            final UpdateLocalVersionQueue ulvq = new UpdateLocalVersionQueue(workspace, localUpdateOptions,
                    wLock, 5000 /* flushTriggerLevel */, 10000 /* maximumLevel */,
                    Integer.MAX_VALUE /* timeTriggerInMilliseconds */);

            try {
                for (final ClientLocalVersionUpdate remapUpdate : remapUpdates) {
                    ulvq.queueUpdate(remapUpdate);
                }
            } finally {
                ulvq.close();
            }

            log.debug("Local version updates have been successfully queued."); //$NON-NLS-1$
        }

        // Now, create an object to track the state for this get operation.
        final AsyncGetOperation asyncOp = new AsyncGetOperation(workspace, type, requestType, options,
                deleteUndoneAdds, wLock, localUpdateOptions, flags,
                new AccountingCompletionService<WorkerStatus>(client.getUploadDownloadWorkerExecutor()));

        log.debug("Preparing Get Operation actions"); //$NON-NLS-1$

        final GetOperation[] actions = prepareGetOperations(asyncOp, results);

        log.debug("Number of Get Operation actions prepared: " + actions.length); //$NON-NLS-1$

        processOperations(asyncOp, actions);

        log.debug("All Get Operation actions have been processed."); //$NON-NLS-1$

        return asyncOp.getStatus();
    } catch (final CoreCancelException e) {
        throw new CanceledException();
    } finally {
        if (wLock != null) {
            wLock.close();
        }
    }
}