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:net.sourceforge.kalimbaradio.androidapp.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    LOG.info("Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;/*from  w  w w .j av  a2 s.  c  o  m*/
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            LOG.debug("Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        ServerSettingsManager.ServerSettings server = Util.getActiveServer(context);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(server.getUsername(), server.getPassword()));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            LOG.warn("Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

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   www  . j ava2  s  .  co 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:no.barentswatch.fiskinfo.BaseActivity.java

/**
 * Sends a request to BarentsWatch for the given service, which returns a
 * JSONArray on success.//  w  w w .j  a  v  a2  s.co m
 * 
 * @param service
 *            The service to call in the API.
 * @return A JSONArray containing the response from BarentsWatch if the
 *         request succeeded, null otherwise.
 */
public JSONArray authenticatedGetRequestToBarentswatchAPIService(final String service) {
    if (!userIsAuthenticated) {
        Log.e("FiskInfo",
                "This should never happen. User must be logged in before we fetch the users geodata subs");
        return null;
    }

    final AtomicReference<String> responseAsString = new AtomicReference<String>();
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                CloseableHttpClient httpclient = HttpClients.createDefault();
                try {
                    String base_url = "https://www.barentswatch.no/api/v1/" + service;
                    List<NameValuePair> getParameters = new ArrayList<NameValuePair>(1);
                    getParameters
                            .add(new BasicNameValuePair("access_token", storedToken.getString("access_token")));
                    String paramsString = URLEncodedUtils.format(getParameters, "UTF-8");

                    HttpGet httpGet = new HttpGet(base_url + "?" + paramsString);
                    httpGet.addHeader(HTTP.CONTENT_TYPE, "application/json");

                    CloseableHttpResponse response = httpclient.execute(httpGet);
                    try {
                        responseAsString.set(EntityUtils.toString(response.getEntity()));
                    } finally {
                        response.close();
                    }

                } finally {
                    httpclient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    String barentswatchResponse = responseAsString.get();
    if (barentswatchResponse == null || barentswatchResponse.trim().length() == 0) {
        return null;
    }
    try {
        JSONArray barentswatchAPIJSONResponse = new JSONArray(barentswatchResponse);
        return barentswatchAPIJSONResponse;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.alibaba.wasp.master.FMaster.java

/**
 * @see com.alibaba.wasp.protobuf.generated.MasterAdminProtos.MasterAdminService.BlockingInterface#getEntityGroupWithScan(com.google.protobuf.RpcController,
 *      com.alibaba.wasp.protobuf.generated.MasterAdminProtos.GetEntityGroupWithScanRequest)
 *//*from  ww w. j  a  v a2  s.co m*/
@Override
public GetEntityGroupWithScanResponse getEntityGroupWithScan(RpcController controller,
        GetEntityGroupWithScanRequest request) throws ServiceException {
    byte[] tableNameOrEntityGroupName = request.getTableNameOrEntityGroupName().toByteArray();
    Pair<EntityGroupInfo, ServerName> pair;
    try {
        pair = FMetaReader.getEntityGroup(conf, tableNameOrEntityGroupName);
        if (pair == null) {
            final AtomicReference<Pair<EntityGroupInfo, ServerName>> result = new AtomicReference<Pair<EntityGroupInfo, ServerName>>(
                    null);
            final String encodedName = Bytes.toString(tableNameOrEntityGroupName);
            MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
                @Override
                public boolean processRow(org.apache.hadoop.hbase.client.Result data) throws IOException {
                    EntityGroupInfo info = EntityGroupInfo.getEntityGroupInfo(data);
                    if (info == null) {
                        LOG.warn("No serialized EntityGroupInfo in " + data);
                        return true;
                    }
                    if (!encodedName.equals(info.getEncodedName())) {
                        return true;
                    }
                    ServerName sn = EntityGroupInfo.getServerName(data);
                    result.set(new Pair<EntityGroupInfo, ServerName>(info, sn));
                    return false; // found the entityGroup, stop
                }
            };

            FMetaScanner.metaScan(conf, visitor);
            pair = result.get();
        }
        GetEntityGroupWithScanResponse.Builder builder = GetEntityGroupWithScanResponse.newBuilder();
        if (pair != null) {
            if (pair.getFirst() != null) {
                builder.setEgInfo(pair.getFirst().convert());
            }
            if (pair.getSecond() != null) {
                builder.setServerName(pair.getSecond().convert());
            }
        }
        return builder.build();
    } catch (Exception e) {
        LOG.error("Failed getEntityGroupWithScan.", e);
        throw new ServiceException(e);
    }
}

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

@Test
public void should_batch_several_entities_async() throws Exception {
    CompleteBean bean = CompleteBeanTestBuilder.builder().randomId().name("name").buid();
    Tweet tweet1 = TweetTestBuilder.tweet().randomId().content("tweet1").buid();
    Tweet tweet2 = TweetTestBuilder.tweet().randomId().content("tweet2").buid();

    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    final AtomicReference<Throwable> exceptionSpy = new AtomicReference<>();

    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override//from  w ww  .j  a v  a  2s .co  m
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

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

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

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

    // Start batch
    AsyncBatch batch = asyncManager.createBatch();
    batch.startBatch();

    batch.insert(bean);
    batch.insert(tweet1);
    batch.insert(tweet2);
    batch.insert(user);

    CompleteBean foundBean = asyncManager.find(CompleteBean.class, bean.getId()).getImmediately();
    Tweet foundTweet1 = asyncManager.find(Tweet.class, tweet1.getId()).getImmediately();
    Tweet foundTweet2 = asyncManager.find(Tweet.class, tweet2.getId()).getImmediately();
    User foundUser = asyncManager.find(User.class, user.getId()).getImmediately();

    assertThat(foundBean).isNull();
    assertThat(foundTweet1).isNull();
    assertThat(foundTweet2).isNull();
    assertThat(foundUser).isNull();

    // Flush
    batch.asyncEndBatch(successCallBack, errorCallBack);

    latch.await();

    final ResultSet resultSet = asyncManager.getNativeSession().execute(
            "SELECT id,favoriteTweets,followers,friends,age_in_years,name,welcomeTweet,label,preferences FROM CompleteBean WHERE id=:id",
            bean.getId());
    assertThat(resultSet.all()).hasSize(1);

    foundBean = asyncManager.find(CompleteBean.class, bean.getId()).getImmediately();
    foundTweet1 = asyncManager.find(Tweet.class, tweet1.getId()).getImmediately();
    foundTweet2 = asyncManager.find(Tweet.class, tweet2.getId()).getImmediately();
    foundUser = asyncManager.find(User.class, user.getId()).getImmediately();

    assertThat(foundBean.getName()).isEqualTo("name");
    assertThat(foundTweet1.getContent()).isEqualTo("tweet1");
    assertThat(foundTweet2.getContent()).isEqualTo("tweet2");
    assertThat(foundUser.getFirstname()).isEqualTo("fn");
    assertThat(foundUser.getLastname()).isEqualTo("ln");
    assertThatBatchContextHasBeenReset(batch);

    assertThat(successSpy.get()).isNotNull().isSameAs(Empty.INSTANCE);
    assertThat(exceptionSpy.get()).isNull();
}

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 av a 2  s  .co 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:io.pravega.segmentstore.server.writer.SegmentAggregatorTests.java

/**
 * Tests the behavior of flush() with appends and storage errors (on the write() method).
 *///  w ww .j  av a  2s .c  o  m
@Test
public void testFlushAppendWithStorageErrors() throws Exception {
    final WriterConfig config = DEFAULT_CONFIG;
    final int appendCount = config.getFlushThresholdBytes() * 10;
    final int failSyncEvery = 2;
    final int failAsyncEvery = 3;

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

    // 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.setWriteSyncErrorInjector(
            new ErrorInjector<>(count -> count % failSyncEvery == 0, exceptionSupplier));
    context.storage.setWriteAsyncErrorInjector(
            new ErrorInjector<>(count -> count % failAsyncEvery == 0, exceptionSupplier));

    @Cleanup
    ByteArrayOutputStream writtenData = new ByteArrayOutputStream();

    // Part 1: flush triggered by accumulated size.
    int exceptionCount = 0;
    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);

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

        try {
            flushResult = context.segmentAggregator.flush(TIMEOUT, executorService()).join();
            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));
                exceptionCount++;
            } else {
                // Not expecting any exception this time.
                throw ex;
            }
        }

        // 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());
        }
    }

    // Do one last flush at the end to make sure we clear out all the buffers, if there's anything else left.
    context.increaseTime(config.getFlushThresholdTime().toMillis() + 1); // Force a flush by incrementing the time by a lot.
    context.storage.setWriteSyncErrorInjector(null);
    context.storage.setWriteAsyncErrorInjector(null);
    context.segmentAggregator.flush(TIMEOUT, executorService()).join();

    // 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);
    AssertExtensions.assertGreaterThan("Not enough errors injected.", 0, exceptionCount);
}

From source file:github.madmarty.madsonic.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    SharedPreferences prefs = Util.getPreferences(context);
    int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
    HttpParams newParams = httpClient.getParams();
    HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
    httpClient.setParams(newParams);/*from w w  w .j a v a  2s . co  m*/

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:net.tac42.subtails.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;/*from  w w w. j a v  a  2s.co  m*/
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        SharedPreferences prefs = Util.getPreferences(context);
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}