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.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java

@Test
public void test2Clients() throws Exception {
    CuratorFramework client1 = null;//  www.  j  a v  a  2  s .c  o  m
    CuratorFramework client2 = null;
    try {
        client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client1.start();
        client2.start();

        final InterProcessLock mutexForClient1 = makeLock(client1);
        final InterProcessLock mutexForClient2 = makeLock(client2);

        final CountDownLatch latchForClient1 = new CountDownLatch(1);
        final CountDownLatch latchForClient2 = new CountDownLatch(1);
        final CountDownLatch acquiredLatchForClient1 = new CountDownLatch(1);
        final CountDownLatch acquiredLatchForClient2 = new CountDownLatch(1);

        final AtomicReference<Exception> exceptionRef = new AtomicReference<Exception>();

        ExecutorService service = Executors.newCachedThreadPool();
        Future<Object> future1 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    mutexForClient1.acquire(10, TimeUnit.SECONDS);
                    acquiredLatchForClient1.countDown();
                    latchForClient1.await(10, TimeUnit.SECONDS);
                    mutexForClient1.release();
                } catch (Exception e) {
                    exceptionRef.set(e);
                }
                return null;
            }
        });
        Future<Object> future2 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    mutexForClient2.acquire(10, TimeUnit.SECONDS);
                    acquiredLatchForClient2.countDown();
                    latchForClient2.await(10, TimeUnit.SECONDS);
                    mutexForClient2.release();
                } catch (Exception e) {
                    exceptionRef.set(e);
                }
                return null;
            }
        });

        while (!mutexForClient1.isAcquiredInThisProcess() && !mutexForClient2.isAcquiredInThisProcess()) {
            Thread.sleep(1000);
            Assert.assertFalse(future1.isDone() && future2.isDone());
        }

        Assert.assertTrue(
                mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess());
        Thread.sleep(1000);
        Assert.assertTrue(
                mutexForClient1.isAcquiredInThisProcess() || mutexForClient2.isAcquiredInThisProcess());
        Assert.assertTrue(
                mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess());

        Exception exception = exceptionRef.get();
        if (exception != null) {
            throw exception;
        }

        if (mutexForClient1.isAcquiredInThisProcess()) {
            latchForClient1.countDown();
            Assert.assertTrue(acquiredLatchForClient2.await(10, TimeUnit.SECONDS));
            Assert.assertTrue(mutexForClient2.isAcquiredInThisProcess());
        } else {
            latchForClient2.countDown();
            Assert.assertTrue(acquiredLatchForClient1.await(10, TimeUnit.SECONDS));
            Assert.assertTrue(mutexForClient1.isAcquiredInThisProcess());
        }
    } finally {
        IOUtils.closeQuietly(client1);
        IOUtils.closeQuietly(client2);
    }
}

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

private void packedDump(PrintWriter pw, GTSDecoderIterator iter, long now, long timespan, boolean dedup,
        boolean signed, AtomicReference<Metadata> lastMeta, AtomicLong lastCount, int maxDecoderLen,
        String classSuffix, long chunksize, boolean sortMeta) throws IOException {

    String name = null;//www  . j a v  a2s .c o  m
    Map<String, String> labels = null;

    StringBuilder sb = new StringBuilder();

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

    List<GTSEncoder> encoders = new ArrayList<GTSEncoder>();

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

        if (dedup) {
            decoder = decoder.dedup();
        }

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

        GTSEncoder encoder = decoder.getEncoder(true);

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

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

        //
        // Compute the name
        //

        name = decoder.getName();
        labels = lbls;
        sb.setLength(0);
        GTSHelper.encodeName(sb, name + classSuffix);
        sb.append("{");
        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) {
                sb.append(",");
            }
            GTSHelper.encodeName(sb, entry.getKey());
            sb.append("=");
            GTSHelper.encodeName(sb, entry.getValue());
            first = false;
        }
        sb.append("}");

        // We treat the case where encoder.getCount() is 0 in a special way
        // as this may be because the encoder was generated from a partly
        // consumed decoder and thus its count was reset to 0
        if (0 == encoder.getCount() || encoder.getCount() > toDecodeCount) {
            // We have too much data, shrink the encoder
            GTSEncoder enc = new GTSEncoder();
            enc.safeSetMetadata(decoder.getMetadata());
            while (decoder.next() && toDecodeCount > 0) {
                enc.addValue(decoder.getTimestamp(), decoder.getLocation(), decoder.getElevation(),
                        decoder.getValue());
                toDecodeCount--;
            }
            encoder = enc;
        }

        if (timespan < 0) {
            currentCount += encoder.getCount();
        }

        encoders.clear();

        //
        // Add encoders per chunk
        //

        GTSDecoder chunkdec = encoder.getDecoder(true);

        GTSEncoder chunkenc = null;

        Long lastchunk = null;

        if (Long.MAX_VALUE == chunksize) {
            encoders.add(encoder);
        } else {
            while (chunkdec.next()) {
                long ts = chunkdec.getTimestamp();
                long chunk = ts >= 0 ? ts / chunksize : ((ts + 1) / chunksize) - 1;

                //
                // If it is the first chunk or we changed chunk, create a new encoder
                //

                if (null == chunkenc || (null != lastchunk && chunk != lastchunk)) {
                    chunkenc = new GTSEncoder(0L);
                    chunkenc.setMetadata(encoder.getMetadata());
                    encoders.add(chunkenc);
                }

                lastchunk = chunk;

                chunkenc.addValue(ts, chunkdec.getLocation(), chunkdec.getElevation(), chunkdec.getValue());
            }
        }

        while (!encoders.isEmpty()) {
            encoder = encoders.remove(0);

            if (encoder.size() > 0) {
                //
                // Determine most recent timestamp
                //

                GTSDecoder dec = encoder.getDecoder(true);

                dec.next();

                long timestamp = dec.getTimestamp();

                //
                // Build GTSWrapper
                //

                encoder.setMetadata(new Metadata());
                // Clear labels
                encoder.setName("");
                encoder.setLabels(new HashMap<String, String>());
                encoder.getMetadata().setAttributes(new HashMap<String, String>());

                GTSWrapper wrapper = GTSWrapperHelper.fromGTSEncoderToGTSWrapper(encoder, true);

                TSerializer ser = new TSerializer(new TCompactProtocol.Factory());
                byte[] serialized;

                try {
                    serialized = ser.serialize(wrapper);
                } catch (TException te) {
                    throw new IOException(te);
                }

                //
                // Check the size of the generatd wrapper. If it is over 75% of maxDecoderLen,
                // split the original encoder in two
                //

                if (serialized.length >= Math.floor(0.75D * maxDecoderLen) && encoder.getCount() > 2) {
                    GTSEncoder split = new GTSEncoder(0L);
                    split.setMetadata(encoder.getMetadata());

                    List<GTSEncoder> splits = new ArrayList<GTSEncoder>();

                    splits.add(split);

                    int threshold = encoder.size() / 2;

                    GTSDecoder deco = encoder.getDecoder(true);

                    while (deco.next()) {
                        split.addValue(deco.getTimestamp(), deco.getLocation(), deco.getElevation(),
                                deco.getValue());
                        if (split.size() > threshold) {
                            split = new GTSEncoder(0L);
                            splits.add(split);
                        }
                    }

                    //
                    // Now insert the splits at the beginning of 'encoders'
                    //

                    for (int i = splits.size() - 1; i >= 0; i--) {
                        encoders.add(0, splits.get(i));
                    }
                    continue;
                }

                if (serialized.length > Math.ceil(0.75D * maxDecoderLen)) {
                    throw new IOException(
                            "Encountered a value whose length is above the configured threshold of "
                                    + maxDecoderLen);
                }

                pw.print(timestamp);
                pw.print("//");
                pw.print(encoder.getCount());
                pw.print(" ");
                pw.print(sb.toString());
                pw.print(" '");

                OrderPreservingBase64.encodeToWriter(serialized, pw);

                pw.print("'");
                pw.write('\r');
                pw.write('\n');
            }
        }
    }

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

From source file:cl.gisred.android.RepartoActivity.java

public void enviarDatos() {
    final AtomicReference<String> resp = new AtomicReference<>("");

    for (RepartoClass rep : arrayDatos) {

        final RepartoClass repActual = rep;
        Map<String, Object> objectMap = new HashMap<>();

        objectMap.put("nis", rep.getNis());
        objectMap.put("valor_captura", rep.getCodigo());
        objectMap.put("empresa", empresa);
        objectMap.put("modulo", modulo);

        Point oUbicacion = new Point(rep.getX(), rep.getY());

        Graphic newFeatureGraphic = new Graphic(oUbicacion, null, objectMap);
        Graphic[] adds = { newFeatureGraphic };
        LyReparto.applyEdits(adds, null, null, new CallbackListener<FeatureEditResult[][]>() {
            @Override//  ww  w.  j  a  va2s .  c  om
            public void onCallback(FeatureEditResult[][] featureEditResults) {
                if (featureEditResults[0] != null) {
                    if (featureEditResults[0][0] != null && featureEditResults[0][0].isSuccess()) {

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                deleteData(repActual.getId());
                            }
                        });
                    }
                }
            }

            @Override
            public void onError(Throwable throwable) {
                resp.set("Error al ingresar: " + throwable.getLocalizedMessage());

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(RepartoActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}

From source file:net.ben.subsonic.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.i(TAG, "Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;//from  ww w . java  2s.com
        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);
            }
        }

        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:com.sysunite.weaver.nifi.GetXMLNodes.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {

    final FlowFile flowFileIn = session.get();

    if (flowFileIn == null) {
        return;/*  w w w  . j a  va2 s .  c  o m*/
    }

    //System.out.println("i am here!!!");

    final AtomicReference<InputStream> savedNodes = new AtomicReference<>();

    //inlezen van flowFileIn
    session.read(flowFileIn, new InputStreamCallback() {

        @Override
        public void process(InputStream isIn) throws IOException {

            try {

                String contents = IOUtils.toString(isIn);

                XML xml = new XMLDocument(contents); //"<error>\n<fout a=\"poo\">\n<tiger>Bla</tiger>\n</fout>\n</error>");

                String aPath = context.getProperty(PROP_XPATH).getValue();

                //System.out.println(aPath);

                StringBuffer buffer = new StringBuffer();
                buffer.append("<root>");

                int counter = 0;

                for (XML ibr : xml.nodes(aPath)) {

                    //              if(counter == 3){
                    //               break;
                    //              }

                    buffer.append(ibr.toString());
                    //System.out.println(ibr.toString());

                    //
                    //              FlowFile flowfileOut = session.create();
                    //
                    //        InputStream data = new ByteArrayInputStream(ibr.toString().getBytes());
                    //        flowfileOut = session.importFrom(data, flowfileOut);
                    //
                    //
                    //       session.transfer(flowfileOut, MY_RELATIONSHIP);
                    //      session.commit();

                    //counter++;

                }

                buffer.append("</root>");

                InputStream is = new ByteArrayInputStream(buffer.toString().getBytes()); // geen extra parameters, want dit zorgt voor 'too much output too process'

                savedNodes.set(is);

            } catch (Exception e) {

                System.out.println("??????");
                //System.out.println(e.getMessage());
            }

        }

    });

    session.remove(flowFileIn);

    try {

        String contents = IOUtils.toString(savedNodes.get());

        XML xml = new XMLDocument(contents);

        String aPath = context.getProperty(PROP_XPATH).getValue();
        String parts[] = aPath.split("/");

        int size = parts.length;
        String lastNode = parts[size - 1]; //FunctionalPhysicalObject"

        for (XML node : xml.nodes("root/" + lastNode)) {

            //System.out.println(node.toString());

            FlowFile flowfileOut = session.create();

            InputStream data = new ByteArrayInputStream(node.toString().getBytes());
            flowfileOut = session.importFrom(data, flowfileOut);

            session.transfer(flowfileOut, MY_RELATIONSHIP);
            session.commit();

        }

    } catch (IOException e) {
        System.out.println("w00t");// + e.getMessage());
    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage());
    } catch (FlowFileHandlingException e) {
        System.out.println(e.getMessage());
    }

    //---------------

    //            for (XML ibr : xml.nodes("//fout")) {
    //
    //              System.out.println(ibr.toString());
    //            }

    //            List<XML> nodes = xml.nodes(aPath);
    //
    //            if(nodes.size() == 0){
    //              System.out.println("geen nodes gevonden!!");
    //            }else{
    //
    //
    //              System.out.println("more nodes!!!");
    //
    ////              ListSaver ls = new ListSaver();
    ////
    //              StringBuffer buffer = new StringBuffer();
    //
    //              int counter = 0;
    //              for(;counter<nodes.size();counter++){
    //                XML node = nodes.get(counter);
    ////                ls.add(""+counter, node);
    //                buffer.append(node.node().toString());
    //             }
    //
    //              InputStream isOut = new ByteArrayInputStream(buffer.toString().getBytes());
    //
    //              xpath_nodes.set(isOut);
    //            }

    //      savedNodes.get().
    //      //System.out.println(ibr.toString());
    //      //remove flowFileIn from session otherwise fail to transfer new flowfile
    //      session.remove(flowFileIn);
    //
    //      FlowFile flowfileOut = session.create();
    //////
    //      InputStream data = new ByteArrayInputStream(ibr.toString().getBytes());
    //      flowfileOut = session.importFrom(data, flowfileOut);
    //      session.transfer(flowfileOut, MY_RELATIONSHIP);
    //session.transfer(flowFileIn, MY_RELATIONSHIP);

    //      System.out.println("going to make individual nodes");
    //
    //      //create flow files from every node in xpath_nodes

    //System.out.println(xpath_nodes.toString());
    //
    //      for(XML aNodeXML : nodes.xmlList){
    ////
    //       System.out.println(aNodeXML.toString());
    ////
    ////        //XMLDocument doc = new XMLDocument(aNodeXML.node());
    ////
    ////        //System.out.println(doc.node());
    ////
    ////        //FlowFile flowfileOut = session.create();
    ////
    ////        //InputStream data = new ByteArrayInputStream(doc.node().toString().getBytes());
    ////        //flowfileOut = session.importFrom(data, flowfileOut);
    ////
    ////        //session.transfer(flowfileOut, MY_RELATIONSHIP);
    ////
    //      }

    //session.transfer(flowFileIn, MY_RELATIONSHIP);

}

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

/**
 * Get an access token from the token service. A Result of TokenResponse will be returned if the invocation is successfully.
 * Otherwise, a Result of Status will be returned.
 *
 * @param tokenRequest token request constructed from the client.yml token section.
 * @param envTag the environment tag from the server.yml for service lookup.
 * @return Result of TokenResponse or error Status.
 *///from   w ww.  j  ava  2s .  com
public static Result<TokenResponse> getTokenResult(TokenRequest tokenRequest, 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 (tokenRequest.getServerUrl() != null) {
            connection = client.connect(new URI(tokenRequest.getServerUrl()), Http2Client.WORKER,
                    Http2Client.SSL, Http2Client.BUFFER_POOL,
                    tokenRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                            : OptionMap.EMPTY)
                    .get();
        } else if (tokenRequest.getServiceId() != null) {
            Cluster cluster = SingletonServiceFactory.getBean(Cluster.class);
            String url = cluster.serviceToUrl("https", tokenRequest.getServiceId(), envTag, null);
            connection = client
                    .connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL,
                            tokenRequest.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 "
                    + tokenRequest.getClass());
            throw new ClientException("both server_url and serviceId are not configured in client.yml for "
                    + tokenRequest.getClass());
        }
    } catch (Exception e) {
        logger.error("cannot establish connection:", e);
        return Failure.of(new Status(ESTABLISH_CONNECTION_ERROR,
                tokenRequest.getServerUrl() != null ? tokenRequest.getServerUrl()
                        : tokenRequest.getServiceId()));
    }

    try {
        IClientRequestComposable requestComposer = ClientRequestComposerProvider.getInstance().getComposer(
                ClientRequestComposerProvider.ClientRequestComposers.CLIENT_CREDENTIAL_REQUEST_COMPOSER);

        connection.getIoThread()
                .execute(new TokenRequestAction(tokenRequest, requestComposer, connection, reference, latch));

        latch.await(4, TimeUnit.SECONDS);
    } 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.microsoft.tfs.core.clients.versioncontrol.internal.WebServiceLayerLocalWorkspaces.java

/**
 * If the workspace name and owner provided correspond to a local workspace
 * on this computer, that local workspace will be reconciled.
 *//*from w  w w.ja  v a2  s .com*/
protected Workspace reconcileIfLocal(final String workspaceName, final String ownerName,
        final boolean unscannedReconcile, final boolean reconcileMissingLocalItems,
        final boolean skipIfAccessDenied, final AtomicBoolean reconciled) {
    if (reconciled != null) {
        reconciled.set(false);
    }

    if (workspaceName == null || workspaceName.length() == 0 || ownerName == null || ownerName.length() == 0) {
        return null;
    }

    Workspace localWorkspace = null;

    if ((localWorkspace = getLocalWorkspace(workspaceName, ownerName)) != null) {
        final AtomicReference<Failure[]> failures = new AtomicReference<Failure[]>();
        final AtomicBoolean pendingChangesUpdatedByServer = new AtomicBoolean();

        try {
            final boolean wasReconciled = LocalDataAccessLayer.reconcileLocalWorkspace(localWorkspace, this,
                    unscannedReconcile, reconcileMissingLocalItems, failures, pendingChangesUpdatedByServer);

            if (wasReconciled) {
                localWorkspace.invalidateMappings();
                localWorkspace.refreshMappingsIfNeeded();
            }

            if (reconciled != null) {
                reconciled.set(wasReconciled);
            }
        } catch (final ResourceAccessException e) {
            if (!skipIfAccessDenied) {
                throw e;
            }

            return null;
        }

        getVersionControlClient().reportFailures(localWorkspace, failures.get());
    }

    return localWorkspace;
}

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

@Test
public void should_query_async_with_default_params() throws Exception {
    long partitionKey = RandomUtils.nextLong(0, Long.MAX_VALUE);
    final CountDownLatch latch1 = new CountDownLatch(1);
    AchillesFuture<List<ClusteredEntity>> futureEntities = asyncManager.sliceQuery(ClusteredEntity.class)
            .forSelect().withPartitionComponents(partitionKey).fromClusterings(1, "name2")
            .toClusterings(1, "name4").withAsyncListeners(countDownLatch(latch1)).get();

    latch1.await();// w  w w . j ava  2s  . c om

    List<ClusteredEntity> entities = futureEntities.get();
    assertThat(entities).isEmpty();

    final CountDownLatch latch2 = new CountDownLatch(1);
    final AtomicReference<Object> successSpy = new AtomicReference<>();

    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch2.countDown();
        }

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

    String clusteredValuePrefix = insertValues(partitionKey, 1, 5);

    futureEntities = asyncManager.sliceQuery(ClusteredEntity.class).forSelect()
            .withPartitionComponents(partitionKey).fromClusterings(1, "name2").toClusterings(1, "name4")
            .withAsyncListeners(successCallBack).get();

    latch2.await();

    entities = futureEntities.get();

    assertThat(entities).hasSize(3);

    assertThat(entities.get(0).getValue()).isEqualTo(clusteredValuePrefix + 2);
    assertThat(entities.get(0).getId().getId()).isEqualTo(partitionKey);
    assertThat(entities.get(0).getId().getCount()).isEqualTo(1);
    assertThat(entities.get(0).getId().getName()).isEqualTo("name2");
    assertThat(entities.get(1).getValue()).isEqualTo(clusteredValuePrefix + 3);
    assertThat(entities.get(1).getId().getId()).isEqualTo(partitionKey);
    assertThat(entities.get(1).getId().getCount()).isEqualTo(1);
    assertThat(entities.get(1).getId().getName()).isEqualTo("name3");
    assertThat(entities.get(2).getValue()).isEqualTo(clusteredValuePrefix + 4);
    assertThat(entities.get(2).getId().getId()).isEqualTo(partitionKey);
    assertThat(entities.get(2).getId().getCount()).isEqualTo(1);
    assertThat(entities.get(2).getId().getName()).isEqualTo("name4");

    assertThat(successSpy.get()).isNotNull().isInstanceOf(List.class);
    List<CompleteBean> raws = (List<CompleteBean>) successSpy.get();
    assertThat(raws).hasSize(3);
    assertThat(raws.get(0)).isNotInstanceOf(Factory.class);

}

From source file:com.sysunite.weaver.nifi.FilterXMLNodes.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFileIn = session.get();

    if (flowFileIn == null) {
        return;/*from  ww  w  .j a  va  2  s  .  co  m*/
    }

    final AtomicReference<InputStream> savedNode = new AtomicReference<>();

    //read the flow file
    session.read(flowFileIn, new InputStreamCallback() {

        @Override
        public void process(InputStream isIn) throws IOException {

            //System.out.println("contact!");

            try {

                String contents = IOUtils.toString(isIn);

                XML xmlNode = new XMLDocument(contents);

                System.out.println(xmlNode.toString());

                // works:  .xpath("/FunctionalPhysicalObject/@name")
                String attributeToSearchFor = context.getProperty(PROP_NODE_ATTRIBUTE).getValue(); // name
                attributeToSearchFor = "@" + attributeToSearchFor; //@name

                String nodeToSearchFor = context.getProperty(PROP_NODE).getValue(); //FunctionalPhysicalObject
                nodeToSearchFor = "/" + nodeToSearchFor + "/"; // /FunctionalPhysicalObject/

                String fullNodePathWithAttribute = nodeToSearchFor + attributeToSearchFor; // /FunctionalPhysicalObject/@name

                //System.out.println(fullNodePathWithAttribute);

                String valueOfAttribute = xmlNode.xpath(fullNodePathWithAttribute).get(0);
                //System.out.println("naam: " + valueOfAttribute);
                //"(.*)AB(.*)CT(.*)"
                String filter = context.getProperty(PROP_PREGMATCH).getValue();

                if (valueOfAttribute.matches(filter)) {

                    //System.out.println("match!!");
                    //dit is de node die we echt willen!

                    InputStream is = new ByteArrayInputStream(xmlNode.toString().getBytes());

                    savedNode.set(is);

                }

            } catch (IOException e) {
                System.out.println("w00t");// + e.getMessage());
            } catch (IllegalArgumentException e) {
                System.out.println("is xml niet geldig?");
            } catch (IndexOutOfBoundsException e) {
                System.out.println("bah! de node waar gezocht naar moet worden is niet gevonden!");
            }

        }
    });

    session.remove(flowFileIn);

    //process what we have read
    try {

        //check if there is something to process
        String contents = IOUtils.toString(savedNode.get());
        if (contents != null && contents.length() > 0) {

            FlowFile flowfileOut = session.create();

            XML xmlNode = new XMLDocument(contents);

            InputStream data = new ByteArrayInputStream(xmlNode.toString().getBytes());
            flowfileOut = session.importFrom(data, flowfileOut);

            session.transfer(flowfileOut, MY_RELATIONSHIP);
            session.commit();

        }

    } catch (IOException e) {
        System.out.println("w00t");// + e.getMessage());
    } catch (IllegalArgumentException e) {
        System.out.println("xml niet geldig?");
    } catch (NullPointerException e) {
        System.out.println("zonder gevonden node geen waarde om te initialiseren.");
    }

}

From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java

public String doGetWithResponseHandler(String url, Map<String, String> allRequestParams) {
    AtomicReference<String> result = new AtomicReference<>("");
    // CloseableHttpResponse response = null;
    CloseableHttpClient client = null;//from   ww w.j  a  v  a 2s .  c om
    try {
        HttpGet httpGet = new HttpGet(url);
        URIBuilder uriBuilder = new URIBuilder(httpGet.getURI());

        allRequestParams.entrySet().forEach((entry) -> {
            String key = entry.getKey();
            String value = entry.getValue();
            if (value != null) {
                uriBuilder.setParameter(key, value);
            }
        });

        httpGet.setURI(uriBuilder.build());

        RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout())
                .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout())
                .setSocketTimeout(hcp.getSockectTimeout()).build();

        client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= hcp.getLowerStatusLimit() && status <= hcp.getUpperStatusLimit()) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException(hcp.getUnexpectedStatus() + status);
            }
        };

        result.set(client.execute(httpGet, responseHandler));
        client.close();

    } catch (IOException | URISyntaxException ex) {
        // LoggerFactory.getLogger(CustomHttpClientUtil.class).error(ex.getMessage(),
        // ex);
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (client != null) {
                client.close();
            }

        } catch (IOException ex) {
            // LoggerFactory.getLogger(CustomHttpClientUtil.class).error(ex.getMessage(),
            // ex);
            result.set(hcp.getIoExceptionMessage());
            Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result.get();
}