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

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

Introduction

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

Prototype

public final void set(V newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

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

protected QueryTripsResult queryTripsMobile(final Location from, final @Nullable Location via,
        final Location to, final Date date, final boolean dep, final @Nullable Collection<Product> products,
        final @Nullable Optimize optimize, final @Nullable WalkSpeed walkSpeed,
        final @Nullable Accessibility accessibility, final @Nullable Set<Option> options) throws IOException {
    final HttpUrl.Builder url = tripEndpoint.newBuilder();
    appendXsltTripRequestParameters(url, from, via, to, date, dep, products, optimize, walkSpeed, accessibility,
            options);//from w  ww  . j  a  va2  s  .c o m
    final AtomicReference<QueryTripsResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override
        public void onSuccessful(final CharSequence bodyPeek, final ResponseBody body) throws IOException {
            try {
                result.set(queryTripsMobile(url.build(), from, via, to, 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);
            }
        }
    };

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

    return result.get();
}

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

@Override
public QueryTripsResult queryTrips(final Location from, final @Nullable Location via, final Location to,
        final Date date, final boolean dep, final @Nullable Set<Product> products,
        final @Nullable Optimize optimize, final @Nullable WalkSpeed walkSpeed,
        final @Nullable Accessibility accessibility, final @Nullable Set<Option> options) throws IOException {
    final HttpUrl.Builder url = tripEndpoint.newBuilder();
    appendXsltTripRequestParameters(url, from, via, to, date, dep, products, optimize, walkSpeed, accessibility,
            options);//from   w w w.ja v a  2  s .c  o  m
    final AtomicReference<QueryTripsResult> result = new AtomicReference<>();

    final HttpClient.Callback callback = new HttpClient.Callback() {
        @Override
        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);
            }
        }
    };

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

    return result.get();
}

From source file:org.commonjava.indy.promote.data.PromotionManager.java

private PathsPromoteResult runPathPromotions(final PathsPromoteRequest request, final Set<String> pending,
        final Set<String> prevComplete, final Set<String> prevSkipped, final List<Transfer> contents,
        ValidationResult validation, final ValidationRequest validationRequest) throws IndyWorkflowException {
    if (pending == null || pending.isEmpty()) {
        return new PathsPromoteResult(request, pending, prevComplete, prevSkipped, validation);
    }/* w  w w  .  j  a v a  2  s.c  o m*/

    StoreKey targetKey = request.getTarget();

    final Set<String> complete = prevComplete == null ? new HashSet<>() : new HashSet<>(prevComplete);
    final Set<String> skipped = prevSkipped == null ? new HashSet<>() : new HashSet<>(prevSkipped);

    List<String> errors = new ArrayList<>();

    ArtifactStore sourceStore = null;
    try {
        sourceStore = storeManager.getArtifactStore(request.getSource());
    } catch (IndyDataException e) {
        String msg = String.format("Failed to retrieve artifact store: %s. Reason: %s", request.getSource(),
                e.getMessage());
        errors.add(msg);
        logger.error(msg, e);
    }

    ArtifactStore targetStore = null;
    try {
        targetStore = storeManager.getArtifactStore(request.getTarget());
    } catch (IndyDataException e) {
        String msg = String.format("Failed to retrieve artifact store: %s. Reason: %s", request.getTarget(),
                e.getMessage());
        errors.add(msg);
        logger.error(msg, e);
    }

    if (targetStore == null) {
        String msg = String.format("Failed to retrieve artifact store: %s", request.getTarget());
        errors.add(msg);
        logger.error(msg);
    }

    if (errors.isEmpty()) {
        ArtifactStore src = sourceStore;
        ArtifactStore tgt = targetStore;

        AtomicReference<IndyWorkflowException> wfError = new AtomicReference<>();

        Set<PathTransferResult> results = byPathTargetLocks.lockAnd(targetKey, config.getLockTimeoutSeconds(),
                k -> {
                    logger.info("Running promotions from: {} (key: {})\n  to: {} (key: {})", src,
                            request.getSource(), tgt, request.getTarget());

                    DrainingExecutorCompletionService<PathTransferResult> svc = new DrainingExecutorCompletionService<>(
                            transferService);

                    try {
                        detectOverloadVoid(() -> contents.forEach((transfer) -> svc
                                .submit(newPathsPromoteTransfer(transfer, src, tgt, request))));

                        Set<PathTransferResult> pathResults = new HashSet<>();
                        try {
                            svc.drain(ptr -> pathResults.add(ptr));
                        } catch (InterruptedException | ExecutionException e) {
                            Set<String> paths;
                            try {
                                paths = validationRequest.getSourcePaths();
                            } catch (PromotionValidationException e1) {
                                paths = contents.stream().map(txfr -> txfr.getPath())
                                        .collect(Collectors.toSet());
                            }

                            logger.error(
                                    String.format("Error waiting for promotion of: %s to: %s\nPaths:\n\n%s\n\n",
                                            request.getSource(), targetKey, paths),
                                    e);
                        }

                        try {
                            clearStoreNFC(validationRequest.getSourcePaths(), tgt);
                        } catch (IndyDataException | PromotionValidationException e) {
                            String msg = String.format("Failed to promote to: %s. Reason: %s", tgt,
                                    e.getMessage());
                            errors.add(msg);
                            logger.error(msg, e);
                        }
                        return pathResults;
                    } catch (IndyWorkflowException e) {
                        wfError.set(e);
                        return null;
                    }
                }, (k, lock) -> {
                    String error = String.format(
                            "Failed to acquire promotion lock on target: %s in %d seconds.", targetKey,
                            config.getLockTimeoutSeconds());

                    errors.add(error);
                    logger.warn(error);

                    return false;
                });

        if (wfError.get() != null) {
            throw wfError.get();
        }

        if (results != null) {
            results.forEach(pathResult -> {
                if (pathResult.traversed) {
                    pending.remove(pathResult.path);
                }

                if (pathResult.skipped) {
                    skipped.add(pathResult.path);
                }

                if (pathResult.completed) {
                    complete.add(pathResult.path);
                }

                if (pathResult.error != null) {
                    errors.add(pathResult.error);
                }
            });
        }
    }

    String error = null;

    if (!errors.isEmpty()) {
        error = StringUtils.join(errors, "\n");
    }

    PathsPromoteResult result = new PathsPromoteResult(request, pending, complete, skipped, error, validation);

    if (request.isFireEvents()) {
        PathsPromoteCompleteEvent evt = new PathsPromoteCompleteEvent(result);
        fireEvent(promoteCompleteEvent, evt);
    }
    return result;
}

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   w ww.  j av 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();
        }
    }
}

From source file:io.realm.RealmTests.java

@Test
public void executeTransaction_canceled() {
    final AtomicReference<RuntimeException> thrownException = new AtomicReference<>(null);

    assertEquals(0, realm.allObjects(Owner.class).size());
    try {/*  w w w  .  j a va 2s .com*/
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                Owner owner = realm.createObject(Owner.class);
                owner.setName("Owner");
                thrownException.set(new RuntimeException("Boom"));
                throw thrownException.get();
            }
        });
    } catch (RuntimeException e) {
        //noinspection ThrowableResultOfMethodCallIgnored
        assertTrue(e == thrownException.get());
    }
    assertEquals(0, realm.allObjects(Owner.class).size());
}

From source file:com.networknt.client.oauth.OauthHelper.java

/**
 * Get a signed JWT token from token service to ensure that nobody can modify the payload when the token
 * is passed from service to service. Unlike the access JWT token, this token is ensure the data integrity
 * with signature.//from w w  w. java2  s.  co m
 *
 * @param signRequest SignRequest that is constructed from the client.yml sign section
 * @param envTag environment tag that is used for service lookup if serviceId is used.
 * @return Result that contains TokenResponse or error status when failed.
 */
public static Result<TokenResponse> getSignResult(SignRequest signRequest, String envTag) {
    final AtomicReference<Result<TokenResponse>> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        if (signRequest.getServerUrl() != null) {
            connection = client.connect(new URI(signRequest.getServerUrl()), Http2Client.WORKER,
                    Http2Client.SSL, Http2Client.BUFFER_POOL,
                    signRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                            : OptionMap.EMPTY)
                    .get();
        } else if (signRequest.getServiceId() != null) {
            Cluster cluster = SingletonServiceFactory.getBean(Cluster.class);
            String url = cluster.serviceToUrl("https", signRequest.getServiceId(), envTag, null);
            connection = client
                    .connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL,
                            signRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                                    : OptionMap.EMPTY)
                    .get();
        } else {
            // both server_url and serviceId are empty in the config.
            logger.error("Error: both server_url and serviceId are not configured in client.yml for "
                    + signRequest.getClass());
            throw new ClientException("both server_url and serviceId are not configured in client.yml for "
                    + signRequest.getClass());
        }
    } catch (Exception e) {
        logger.error("cannot establish connection:", e);
        return Failure.of(new Status(ESTABLISH_CONNECTION_ERROR,
                signRequest.getServerUrl() != null ? signRequest.getServerUrl() : signRequest.getServiceId()));
    }

    try {
        Map<String, Object> map = new HashMap<>();
        map.put("expires", signRequest.getExpires());
        map.put("payload", signRequest.getPayload());
        String requestBody = Config.getInstance().getMapper().writeValueAsString(map);
        connection.getIoThread().execute(() -> {
            final ClientRequest request = new ClientRequest().setMethod(Methods.POST)
                    .setPath(signRequest.getUri());
            request.getRequestHeaders().put(Headers.HOST, "localhost");
            request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
            request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
            request.getRequestHeaders().put(Headers.AUTHORIZATION,
                    getBasicAuthHeader(signRequest.getClientId(), signRequest.getClientSecret()));
            connection.sendRequest(request, new ClientCallback<ClientExchange>() {
                @Override
                public void completed(ClientExchange result) {
                    new StringWriteChannelListener(requestBody).setup(result.getRequestChannel());
                    result.setResponseListener(new ClientCallback<ClientExchange>() {
                        @Override
                        public void completed(ClientExchange result) {
                            new StringReadChannelListener(Http2Client.BUFFER_POOL) {

                                @Override
                                protected void stringDone(String string) {

                                    logger.debug("getToken response = " + string);
                                    reference.set(handleResponse(getContentTypeFromExchange(result), string));
                                    latch.countDown();
                                }

                                @Override
                                protected void error(IOException e) {
                                    logger.error("IOException:", e);
                                    reference.set(Failure.of(new Status(FAIL_TO_SEND_REQUEST)));
                                    latch.countDown();
                                }
                            }.setup(result.getResponseChannel());
                        }

                        @Override
                        public void failed(IOException e) {
                            logger.error("IOException:", e);
                            reference.set(Failure.of(new Status(FAIL_TO_SEND_REQUEST)));
                            latch.countDown();
                        }
                    });
                }

                @Override
                public void failed(IOException e) {
                    logger.error("IOException:", e);
                    reference.set(Failure.of(new Status(FAIL_TO_SEND_REQUEST)));
                    latch.countDown();
                }
            });
        });

        latch.await(signRequest.getTimeout(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        return Failure.of(new Status(FAIL_TO_SEND_REQUEST));
    } finally {
        IoUtils.safeClose(connection);
    }

    //if reference.get() is null at this point, mostly likely couldn't get token within latch.await() timeout.
    return reference.get() == null ? Failure.of(new Status(GET_TOKEN_TIMEOUT)) : reference.get();
}

From source file:com.ryan.ryanreader.fragments.MainMenuFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    // TODO load menu position?

    final Context context;

    // //from   w w w . ja  v  a  2s  . c o  m
    if (container != null) {
        context = container.getContext(); // TODO just use the inflater's
        // context in every case?
    } else {
        context = inflater.getContext();
    }

    // 
    final RedditAccount user = RedditAccountManager.getInstance(context).getDefaultAccount();

    final LinearLayout outer = new LinearLayout(context);

    // 
    outer.setOrientation(LinearLayout.VERTICAL);

    notifications = new LinearLayout(context);
    notifications.setOrientation(LinearLayout.VERTICAL);

    loadingView = new LoadingView(context, R.string.download_waiting, true, true);

    final ListView lv = new ListView(context);
    lv.setDivider(null);

    // listview?
    lv.addFooterView(notifications);

    final int paddingPx = General.dpToPixels(context, 8);
    lv.setPadding(paddingPx, 0, paddingPx, 0);

    adapter = new MainMenuAdapter(context, user, this);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(final AdapterView<?> adapterView, final View view, final int position,
                final long id) {
            adapter.clickOn(position);
        }
    });

    final AtomicReference<APIResponseHandler.SubredditResponseHandler> accessibleSubredditResponseHandler = new AtomicReference<APIResponseHandler.SubredditResponseHandler>(
            null);

    final APIResponseHandler.SubredditResponseHandler responseHandler = new APIResponseHandler.SubredditResponseHandler(
            context) {

        @Override
        protected void onDownloadNecessary() {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    notifications.addView(loadingView);
                }
            });
        }

        @Override
        protected void onDownloadStarted() {
            loadingView.setIndeterminate(R.string.download_subreddits);
        }

        @Override
        protected void onSuccess(final List<RedditSubreddit> result, final long timestamp) {

            if (result.size() == 0) {
                // Just get the defaults instead
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        notifications.removeView(loadingView);
                        RedditAPI.getUserSubreddits(CacheManager.getInstance(context),
                                accessibleSubredditResponseHandler.get(), RedditAccountManager.getAnon(),
                                force ? CacheRequest.DownloadType.FORCE
                                        : CacheRequest.DownloadType.IF_NECESSARY,
                                force, context);
                    }
                });

            } else {

                adapter.setSubreddits(result);

                if (loadingView != null)
                    loadingView.setDone(R.string.download_done);
            }
        }

        @Override
        protected void onCallbackException(final Throwable t) {
            BugReportActivity.handleGlobalError(context, t);
        }

        @Override
        protected void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status,
                final String readableMessage) {

            if (loadingView != null)
                loadingView.setDone(R.string.download_failed);
            final RRError error = General.getGeneralErrorForFailure(context, type, t, status);

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    notifications.addView(new ErrorView(getSupportActivity(), error));
                }
            });
        }

        @Override
        protected void onFailure(final APIFailureType type) {

            if (loadingView != null)
                loadingView.setDone(R.string.download_failed);
            final RRError error = General.getGeneralErrorForFailure(context, type);

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    notifications.addView(new ErrorView(getSupportActivity(), error));
                }
            });
        }
    };

    accessibleSubredditResponseHandler.set(responseHandler);

    RedditAPI.getUserSubreddits(CacheManager.getInstance(context), responseHandler, user,
            force ? CacheRequest.DownloadType.FORCE : CacheRequest.DownloadType.IF_NECESSARY, force, context);

    outer.addView(lv);
    lv.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;

    return outer;
}

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

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

    if (flowFile == null) {
        return;
    }

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

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

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

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

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

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

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

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

                        try {

                            GeoUtil geo = GeoUtil.getInstance();

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

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

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

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

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

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

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

                XmlPullUtil.enter(pp, "itdDepartureMonitorRequest");

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

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

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

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

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

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

    return result.get();
}

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

/**
 *
 *
 *
 * @param workspace/* w  ww  .j a  v a 2s .c  o m*/
 * @param itemSpecs
 * @param failures
 * @param lastChange
 *        If not null or empty, only items > last change will be returned.
 * @param pageSize
 *        If not zero, only the page size number of pending changes will be
 *        returned.
 * @param includeCandidates
 *        Whether to return candidate changes in the PendingSet object if
 *        true, a pending set object will be returned if the workspace
 *        either has pending changes or candidates
 * @return
 */
public static PendingSet[] queryPendingChanges(final Workspace workspace, final ItemSpec[] itemSpecs,
        final AtomicReference<Failure[]> failures, final boolean includeCandidates, final String lastChange,
        final int pageSize, final String[] itemPropertyFilters) {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$

    final List<PendingChange> pendingChanges = new ArrayList<PendingChange>();
    final List<PendingChange> candidateChanges = new ArrayList<PendingChange>();
    failures.set(new Failure[0]);

    final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
    try {
        transaction.execute(new AllTablesTransaction() {
            @Override
            public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv,
                    final LocalPendingChangesTable pc) {
                for (final LocalPendingChange pcEntry : queryPendingChanges(workspace, wp, lv, pc, itemSpecs,
                        new ArrayList<Failure>(), includeCandidates, itemPropertyFilters)) {
                    String targetLocalItem;

                    if (lastChange != null && lastChange.length() != 0 && !pcEntry.isCandidate()
                            && ServerPath.compareTopDown(pcEntry.getTargetServerItem(), lastChange) <= 0) {
                        continue;
                    }

                    // if it's a candidate don't bother looking up the local
                    // version row.
                    final WorkspaceLocalItem lvEntry = pcEntry.isCandidate() ? null
                            : 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 (!pcEntry.isCandidate()) {
                        pendingChanges.add(pcEntry.toPendingChange(workspace.getClient(), targetLocalItem));

                        if (pageSize != 0 && pageSize == pendingChanges.size()) {
                            break;
                        }
                    } else {
                        candidateChanges.add(pcEntry.toPendingChange(workspace.getClient(), targetLocalItem));
                    }
                }
            }
        });
    } finally {
        try {
            transaction.close();
        } catch (final IOException e) {
            throw new VersionControlException(e);
        }
    }

    if (pendingChanges.size() == 0 && candidateChanges.size() == 0) {
        return new PendingSet[0];
    } else {
        return new PendingSet[] { new PendingSet(workspace.getName(), workspace.getOwnerName(),
                workspace.getOwnerDisplayName(), OwnershipState.OWNED_BY_AUTHORIZED_USER,
                workspace.getComputer(), PendingSetType.WORKSPACE,
                pendingChanges.toArray(new PendingChange[pendingChanges.size()]),
                candidateChanges.toArray(new PendingChange[candidateChanges.size()])) };
    }
}