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.sybase365.mobiliser.custom.project.handlers.authentication.GtalkAuthenticationHandler.java

@Override
public void authenticate(final SubTransaction transaction, final String authToken, final boolean payer)
        throws AuthenticationException {

    lazyInit();/*from   w  w  w.j av a2 s .c o  m*/

    final Customer customer;
    final String otherName;
    if (payer) {
        customer = transaction.getTransaction().getPayer();
        otherName = transaction.getTransaction().getPayee().getDisplayName();
    } else {
        customer = transaction.getTransaction().getPayee();
        otherName = transaction.getTransaction().getPayer().getDisplayName();
    }

    final String email = this.notificationLogic.getCustomersEmail(customer, 0).get(0);

    final AtomicReference<String> userResponse = new AtomicReference<String>();

    final ChatManager chatmanager = this.connection.getChatManager();

    final MessageListener messageListener = new MessageListener() {

        @Override
        public void processMessage(Chat chat, Message message) {
            synchronized (userResponse) {
                LOG.info("got user response: " + message.getBody());
                userResponse.set(message.getBody());
                userResponse.notify();
            }
        }

    };

    final Chat newChat = chatmanager.createChat(email, messageListener);

    try {
        try {
            newChat.sendMessage("Please confirm payment to " + otherName + " by entering yes.");
        } catch (final XMPPException e) {
            LOG.info("can not send message to user " + email + ": " + e.getMessage(), e);

            throw new AuthenticationFailedPermanentlyException(StatusCodes.ERROR_IVR_NO_PICKUP);
        }

        synchronized (userResponse) {
            try {
                userResponse.wait(10000);
            } catch (final InterruptedException e) {
                LOG.info("Interrupted while waiting", e);
                Thread.currentThread().interrupt();
            }
        }

        if (userResponse.get() == null) {
            LOG.info("did not receive a response in time.");

            throw new AuthenticationFailedPermanentlyException("did not receive a response in time.",
                    StatusCodes.ERROR_IVR_NO_USER_INPUT, new HashMap<String, String>());
        }

        if ("yes".equalsIgnoreCase(userResponse.get())) {

            LOG.debug("received confirmation.");

            try {
                newChat.sendMessage("Thank You.");
            } catch (final XMPPException e1) {
                LOG.debug("Thank you Response was not sent. Ignored", e1);
            }

            return;
        }

        LOG.debug("received unknown response: " + userResponse.get());

        try {
            newChat.sendMessage("Transaction will be cancelled.");
        } catch (final XMPPException e2) {
            LOG.debug("Response was not sent. Ignored", e2);
        }

        throw new AuthenticationFailedPermanentlyException(StatusCodes.ERROR_IVR_HANGUP);

    } finally {
        newChat.removeMessageListener(messageListener);
    }

}

From source file:com.blacklocus.jres.request.index.JresUpdateDocumentScriptTest.java

@Test
public void testRetryOnConflict() throws InterruptedException {
    final String index = "JresUpdateDocumentScriptTest.testRetryOnConflict".toLowerCase();
    final String type = "test";
    final String id = "warzone";

    final AtomicInteger total = new AtomicInteger();
    final AtomicReference<String> error = new AtomicReference<String>();
    final Random random = new Random(System.currentTimeMillis());

    final int numThreads = 16, numIterations = 100;

    ExecutorService x = Executors.newFixedThreadPool(numThreads);
    for (int i = 0; i < numThreads; i++) {
        x.submit(new Runnable() {
            @Override/*from  w w  w  .  ja v  a2 s  .c  o m*/
            public void run() {
                try {
                    for (int j = 0; j < numIterations; j++) {
                        int increment = random.nextInt(5);
                        total.addAndGet(increment);
                        JresUpdateDocumentScript req = new JresUpdateDocumentScript(index, type, id,
                                "ctx._source.value += increment", ImmutableMap.of("increment", increment),
                                ImmutableMap.of("value", increment), null);
                        req.setRetryOnConflict(numIterations * 10);
                        jres.quest(req);
                    }
                } catch (Exception e) {
                    error.set(e.getMessage());
                }
            }
        });
    }
    x.shutdown();
    x.awaitTermination(1, TimeUnit.MINUTES);

    Assert.assertNull("With so many retries, all of these should have gotten through without conflict error",
            error.get());
    jres.quest(new JresRefresh(index));
    JresGetDocumentReply getReply = jres.quest(new JresGetDocument(index, type, id));
    Map<String, Integer> doc = getReply.getSourceAsType(new TypeReference<Map<String, Integer>>() {
    });
    Assert.assertEquals("All increments should have gotten committed", (Object) total.get(), doc.get("value"));
    Assert.assertEquals("Should have been numThreads * numIterations versions committed",
            (Object) (numThreads * numIterations), getReply.getVersion());
}

From source file:com.vmware.admiral.host.BaseManagementHostClusterIT.java

private <T extends ServiceDocument> T doGet(ServiceHost host, String selfLink, Class<T> type, String token) {
    AtomicReference<T> result = new AtomicReference<>();

    TestContext ctx = testContext();/*from  w w w  .jav  a 2s  .c o  m*/

    QueryTask q = QueryUtil.buildPropertyQuery(type, ServiceDocument.FIELD_NAME_SELF_LINK, selfLink);
    QueryUtil.addExpandOption(q);

    host.sendRequest(Operation
            .createGet(UriUtils.buildUri(host, ServiceUriPaths.CORE_DOCUMENT_INDEX,
                    "documentSelfLink=" + selfLink))
            .addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, token).setBody(q).setReferer(host.getUri())
            .setCompletion((o, e) -> {
                if (e != null) {
                    ctx.failIteration(e);
                } else {
                    result.set(o.getBody(type));
                    ctx.completeIteration();
                }
            }));

    ctx.await();

    return result.get();
}

From source file:com.igormaznitsa.zxpoly.MainForm.java

private void menuFileLoadSnapshotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuFileLoadSnapshotActionPerformed
    stepSemaphor.lock();/*  w w w  . j a v a 2s  . co  m*/
    try {
        this.board.forceResetCPUs();
        this.board.resetIODevices();

        final AtomicReference<FileFilter> theFilter = new AtomicReference<>();
        final File selected = chooseFileForOpen("Select snapshot", this.lastSnapshotFolder, theFilter,
                new FormatZXP(), new FormatZ80(), new FormatSNA());
        if (selected != null) {
            this.lastSnapshotFolder = selected.getParentFile();
            try {
                final Snapshot selectedFilter = (Snapshot) theFilter.get();
                log.info("Loading snapshot " + selectedFilter.getName());
                selectedFilter.loadFromArray(this.board, this.board.getVideoController(),
                        FileUtils.readFileToByteArray(selected));
            } catch (Exception ex) {
                log.log(Level.WARNING, "Can't read snapshot file [" + ex.getMessage() + ']', ex);
                JOptionPane.showMessageDialog(this, "Can't read snapshot file [" + ex.getMessage() + ']',
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    } finally {
        stepSemaphor.unlock();
    }
}

From source file:org.apache.nifi.processors.att.m2x.PutM2XStream.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;/*www  .  j a  v a  2s.  c o  m*/
    }

    final ProcessorLog logger = getLogger();
    final OkHttpClient httpClient = getHttpClient();
    final StateManager stateManager = context.getStateManager();
    final String apiKey = context.getProperty(M2X_API_KEY).getValue();
    final String apiUrl = context.getProperty(M2X_API_URL).getValue();
    final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue();
    final String streamName = context.getProperty(M2X_STREAM_NAME).getValue();
    final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue();
    final String streamUrl = new StringBuilder().append(apiUrl.replaceAll("/*$", "")).append("/devices/")
            .append(deviceId).append("/streams/").append(streamName).append("/value").toString();

    try {
        final AtomicReference<String> postBodyRef = new AtomicReference<>();
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream is) {
                try {
                    String timestamp = flowFile.getAttribute("m2x.stream.value.timestamp");
                    if (StringUtils.isEmpty(timestamp)) {
                        timestamp = ISODateTimeFormat.dateTime().print(flowFile.getEntryDate());
                    }
                    final String value = IOUtils.toString(is, StandardCharsets.UTF_8);

                    final M2XStreamValue m2xValue = new M2XStreamValue();
                    m2xValue.setValue(value);
                    m2xValue.setTimestamp(timestamp);

                    final ObjectMapper mapper = new ObjectMapper();
                    mapper.registerModule(new JodaModule());
                    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

                    final String postBody = mapper.writeValueAsString(m2xValue);
                    logger.warn("POST body is {}", new Object[] { postBody });
                    postBodyRef.set(postBody);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });

        final String postBody = postBodyRef.get();
        if (StringUtils.isEmpty(postBody)) {
            logger.error("FlowFile {} contents didn't produce a valid M2X stream value",
                    new Object[] { flowFile });
            session.transfer(flowFile, REL_FAILURE);
            return;
        }

        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey)
                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody)).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            session.penalize(flowFile);
            return;
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        session.penalize(flowFile);
        return;
    }

    session.transfer(flowFile, REL_SUCCESS);
}

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  www  .  ja v  a2s  .  c  om*/
    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.igormaznitsa.zxpoly.MainForm.java

private void loadDiskIntoDrive(final int drive) {
    this.stepSemaphor.lock();
    try {/*from   ww  w  . ja  va 2 s  . c om*/
        final char diskName;
        switch (drive) {
        case BetaDiscInterface.DRIVE_A:
            diskName = 'A';
            break;
        case BetaDiscInterface.DRIVE_B:
            diskName = 'B';
            break;
        case BetaDiscInterface.DRIVE_C:
            diskName = 'C';
            break;
        case BetaDiscInterface.DRIVE_D:
            diskName = 'D';
            break;
        default:
            throw new Error("Unexpected drive index");
        }
        final AtomicReference<FileFilter> filter = new AtomicReference<>();
        final File selectedFile = chooseFileForOpen("Select Disk " + diskName, this.lastFloppyFolder, filter,
                new SCLFileFilter(), new TRDFileFilter());
        if (selectedFile != null) {
            this.lastFloppyFolder = selectedFile.getParentFile();
            try {
                final TRDOSDisk floppy = new TRDOSDisk(
                        filter.get().getClass() == SCLFileFilter.class ? TRDOSDisk.Source.SCL
                                : TRDOSDisk.Source.TRD,
                        FileUtils.readFileToByteArray(selectedFile), false);
                this.board.getBetaDiskInterface().insertDiskIntoDrive(drive, floppy);
                log.info("Loaded drive " + diskName + " by floppy image file " + selectedFile);
            } catch (IOException ex) {
                log.log(Level.WARNING, "Can't read Floppy image file [" + selectedFile + ']', ex);
                JOptionPane.showMessageDialog(this, "Can't read Floppy image file", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    } finally {
        this.stepSemaphor.unlock();
    }
}

From source file:io.warp10.continuum.egress.EgressFetchHandler.java

/**
 * Output a tab separated version of fetched data. Deduplication is done on the fly so we don't decode twice.
 * /* www  .  ja v a2  s . co  m*/
 */
private static void tsvDump(PrintWriter pw, GTSDecoderIterator iter, long now, long timespan, boolean raw,
        boolean dedup, boolean signed, AtomicReference<Metadata> lastMeta, AtomicLong lastCount,
        boolean sortMeta) throws IOException {

    String name = null;
    Map<String, String> labels = null;

    StringBuilder classSB = new StringBuilder();
    StringBuilder labelsSB = new StringBuilder();
    StringBuilder attributesSB = new StringBuilder();
    StringBuilder valueSB = new StringBuilder();

    Metadata lastMetadata = lastMeta.get();
    long currentCount = lastCount.get();

    while (iter.hasNext()) {
        GTSDecoder decoder = iter.next();

        if (!decoder.next()) {
            continue;
        }

        long toDecodeCount = Long.MAX_VALUE;

        if (timespan < 0) {
            Metadata meta = decoder.getMetadata();
            if (!meta.equals(lastMetadata)) {
                lastMetadata = meta;
                currentCount = 0;
            }
            toDecodeCount = Math.max(0, -timespan - currentCount);
        }

        //
        // Only display the class + labels if they have changed since the previous GTS
        //

        Map<String, String> lbls = decoder.getLabels();

        //
        // Compute the new name
        //

        boolean displayName = false;

        if (null == name || (!name.equals(decoder.getName()) || !labels.equals(lbls))) {
            displayName = true;
            name = decoder.getName();
            labels = lbls;
            classSB.setLength(0);
            GTSHelper.encodeName(classSB, name);
            labelsSB.setLength(0);
            attributesSB.setLength(0);
            boolean first = true;

            if (sortMeta) {
                lbls = new TreeMap<String, String>(lbls);
            }
            for (Entry<String, String> entry : lbls.entrySet()) {
                //
                // Skip owner/producer labels and any other 'private' labels
                //
                if (!signed) {
                    if (Constants.PRODUCER_LABEL.equals(entry.getKey())) {
                        continue;
                    }
                    if (Constants.OWNER_LABEL.equals(entry.getKey())) {
                        continue;
                    }
                }

                if (!first) {
                    labelsSB.append(",");
                }
                GTSHelper.encodeName(labelsSB, entry.getKey());
                labelsSB.append("=");
                GTSHelper.encodeName(labelsSB, entry.getValue());
                first = false;
            }

            first = true;
            if (decoder.getMetadata().getAttributesSize() > 0) {

                if (sortMeta) {
                    decoder.getMetadata()
                            .setAttributes(new TreeMap<String, String>(decoder.getMetadata().getAttributes()));
                }

                for (Entry<String, String> entry : decoder.getMetadata().getAttributes().entrySet()) {
                    if (!first) {
                        attributesSB.append(",");
                    }
                    GTSHelper.encodeName(attributesSB, entry.getKey());
                    attributesSB.append("=");
                    GTSHelper.encodeName(attributesSB, entry.getValue());
                    first = false;
                }
            }

        }

        long timestamp = 0L;
        long location = GeoTimeSerie.NO_LOCATION;
        long elevation = GeoTimeSerie.NO_ELEVATION;
        Object value = null;

        boolean dup = true;

        long decoded = 0;

        do {

            if (toDecodeCount == decoded) {
                break;
            }

            //
            // Filter out any value not in the time range
            //

            long newTimestamp = decoder.getTimestamp();

            if (newTimestamp > now || (timespan >= 0 && newTimestamp <= (now - timespan))) {
                continue;
            }

            //
            // TODO(hbs): filter out values with no location or outside the selected geozone when a geozone was set
            //

            long newLocation = decoder.getLocation();
            long newElevation = decoder.getElevation();
            Object newValue = decoder.getValue();

            dup = true;

            if (dedup) {
                if (location != newLocation || elevation != newElevation) {
                    dup = false;
                } else {
                    if (null == newValue) {
                        // Consider nulls as duplicates (can't happen!)
                        dup = false;
                    } else if (newValue instanceof Number) {
                        if (!((Number) newValue).equals(value)) {
                            dup = false;
                        }
                    } else if (newValue instanceof String) {
                        if (!((String) newValue).equals(value)) {
                            dup = false;
                        }
                    } else if (newValue instanceof Boolean) {
                        if (!((Boolean) newValue).equals(value)) {
                            dup = false;
                        }
                    }
                }
            }

            decoded++;

            location = newLocation;
            elevation = newElevation;
            timestamp = newTimestamp;
            value = newValue;

            if (raw) {
                if (!dedup || !dup) {
                    pw.print(classSB);
                    pw.print('\t');
                    pw.print(labelsSB);
                    pw.print('\t');
                    pw.print(attributesSB);
                    pw.print('\t');

                    pw.print(timestamp);
                    pw.print('\t');

                    if (GeoTimeSerie.NO_LOCATION != location) {
                        double[] latlon = GeoXPLib.fromGeoXPPoint(location);
                        pw.print(latlon[0]);
                        pw.print('\t');
                        pw.print(latlon[1]);
                    } else {
                        pw.print('\t');
                    }

                    pw.print('\t');

                    if (GeoTimeSerie.NO_ELEVATION != elevation) {
                        pw.print(elevation);
                    }
                    pw.print('\t');

                    valueSB.setLength(0);
                    GTSHelper.encodeValue(valueSB, value);
                    pw.println(valueSB);
                }
            } else {
                // Display the name only if we have at least one value to display
                // We force 'dup' to be false when we must show the name
                if (displayName) {
                    pw.print("# ");
                    pw.print(classSB);
                    pw.print("{");
                    pw.print(labelsSB);
                    pw.print("}");
                    pw.print("{");
                    pw.print(attributesSB);
                    pw.println("}");
                    displayName = false;
                    dup = false;
                }

                if (!dedup || !dup) {
                    pw.print(timestamp);
                    pw.print('\t');
                    if (GeoTimeSerie.NO_LOCATION != location) {
                        double[] latlon = GeoXPLib.fromGeoXPPoint(location);
                        pw.print(latlon[0]);
                        pw.print('\t');
                        pw.print(latlon[1]);
                    } else {
                        pw.print('\t');
                    }

                    pw.print('\t');

                    if (GeoTimeSerie.NO_ELEVATION != elevation) {
                        pw.print(elevation);
                    }
                    pw.print('\t');

                    valueSB.setLength(0);
                    GTSHelper.encodeValue(valueSB, value);
                    pw.println(valueSB);
                }
            }
        } while (decoder.next());

        // Update currentcount
        if (timespan < 0) {
            currentCount += decoded;
        }

        // Print any remaining value
        if (dedup && dup) {
            if (raw) {
                pw.print(classSB);
                pw.print('\t');
                pw.print(labelsSB);
                pw.print('\t');
                pw.print(attributesSB);
                pw.print('\t');

                pw.print(timestamp);
                pw.print('\t');

                if (GeoTimeSerie.NO_LOCATION != location) {
                    double[] latlon = GeoXPLib.fromGeoXPPoint(location);
                    pw.print(latlon[0]);
                    pw.print('\t');
                    pw.print(latlon[1]);
                } else {
                    pw.print('\t');
                }

                pw.print('\t');

                if (GeoTimeSerie.NO_ELEVATION != elevation) {
                    pw.print(elevation);
                }
                pw.print('\t');

                valueSB.setLength(0);
                GTSHelper.encodeValue(valueSB, value);
                pw.println(valueSB);
            } else {
                pw.print(timestamp);
                pw.print('\t');
                if (GeoTimeSerie.NO_LOCATION != location) {
                    double[] latlon = GeoXPLib.fromGeoXPPoint(location);
                    pw.print(latlon[0]);
                    pw.print('\t');
                    pw.print(latlon[1]);
                } else {
                    pw.print('\t');
                }

                pw.print('\t');

                if (GeoTimeSerie.NO_ELEVATION != elevation) {
                    pw.print(elevation);
                }
                pw.print('\t');

                valueSB.setLength(0);
                GTSHelper.encodeValue(valueSB, value);
                pw.println(valueSB);
            }

        }

        //
        // If displayName is still true it means we should have displayed the name but no value matched,
        // so set name to null so we correctly display the name for the next decoder if it has values
        //

        if (displayName) {
            name = null;
        }
    }

    lastMeta.set(lastMetadata);
    lastCount.set(currentCount);
}

From source file:burlov.ultracipher.swing.SwingGuiApplication.java

/**
 * @return 'true' wenn alles fehlerfrei lief
 *///w  w w . ja  v a2 s.c om
private boolean downloadAndMergeData() {
    if (core.getSyncCredentials() == null) {
        // Nichts zu tun, aber kein Fehler
        return true;
    }
    if (core.getCurrentCryptor() == null) {
        /*
         * Beim Sync Passwort mit Bestaetigung abfragen, weil beim falsch
         * eingegebenem Passwort keine Fehlermeldung kommt sondern einfach
         * nur leere Daten
         */
        if (!createNewCryptor(true)) {
            // Vorgang abgebrochen
            return false;
        }
    }
    final AtomicReference<SyncResult> incomingChanges = new AtomicReference<SyncResult>(SyncResult.NoData);
    Callable<String> callable = new Callable<String>() {

        @Override
        public String call() throws Exception {
            // Mit neuesten Daten vom Sync-Account mergen
            System.out.println("Download data from " + core.getSyncCredentials().getEmailaddress());
            incomingChanges.set(core.syncDatabase(true));
            synced = true;
            return null;
        }
    };
    CallableTask<String> task = new CallableTask<String>(callable);
    WaitDialog dlg = new WaitDialog(getMainFrame(), "Download data", task, 0, 0);
    dlg.start();
    try {
        task.get();
        mainPanel.init();
        if (incomingChanges.get() == SyncResult.NoData) {
            showInfo("No sync data found on the server");
        } else if (!hasChanges && incomingChanges.get() == SyncResult.IncomingChanges) {
            setNeedSave(true);
            /*
             * Wenn lokale Aenderungen nur von gerade runtergeladenen Daten
             * kommen, dann die fusionierte Daten sofort lokal abspeichern
             */
            setNeedSave(!localSaveData());
            return !hasChanges;
        }
        if (incomingChanges.get() == SyncResult.OutgoingChanges) {
            /*
             * Es existieren lokale Daten die nicht auf dem sync-Server
             * bekannt sind. Speicher-Flag setzen damit das Upload nicht
             * vergessen wird
             */
            setNeedSave(true);
        }

        return true;
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
        showError("Sync failed", e.getCause());
    }
    return false;
}

From source file:org.elasticsearch.smoketest.SmokeTestWatcherTestSuiteIT.java

private ObjectPath getWatchHistoryEntry(String watchId) throws Exception {
    final AtomicReference<ObjectPath> objectPathReference = new AtomicReference<>();
    assertBusy(() -> {/*  w w  w.java 2s  .  c o  m*/
        client().performRequest("POST", ".watcher-history-*/_refresh");

        try (XContentBuilder builder = jsonBuilder()) {
            builder.startObject();
            builder.startObject("query").startObject("bool").startArray("must");
            builder.startObject().startObject("term").startObject("watch_id").field("value", watchId)
                    .endObject().endObject().endObject();
            builder.endArray().endObject().endObject();
            builder.startArray("sort").startObject().startObject("trigger_event.triggered_time")
                    .field("order", "desc").endObject().endObject().endArray();
            builder.endObject();

            StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON);
            Response response = client().performRequest("POST", ".watcher-history-*/_search", emptyMap(),
                    entity);
            ObjectPath objectPath = ObjectPath.createFromResponse(response);
            int totalHits = objectPath.evaluate("hits.total");
            assertThat(totalHits, is(greaterThanOrEqualTo(1)));
            String watchid = objectPath.evaluate("hits.hits.0._source.watch_id");
            assertThat(watchid, is(watchId));
            objectPathReference.set(objectPath);
        }
    });
    return objectPathReference.get();
}