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:io.cloudslang.lang.tools.build.SlangBuilderTest.java

private Answer getAnswer(final AtomicReference<IRunTestResults> theCapturedArgument) {
    return new Answer() {
        @Override/*from w  w  w  .  ja va  2  s. c  o m*/
        public Map<TestCaseRunState, Map<String, SlangTestCase>> answer(InvocationOnMock invocationOnMock)
                throws Throwable {
            Object[] arguments = invocationOnMock.getArguments();
            Object argument = arguments[arguments.length - 2];
            if (argument instanceof ThreadSafeRunTestResults) {
                theCapturedArgument.set((ThreadSafeRunTestResults) argument);
            } else if (argument instanceof RunTestsResults) {
                theCapturedArgument.set((RunTestsResults) argument);
            }

            return new LinkedHashMap<>();
        }
    };
}

From source file:io.hummer.util.ws.WebServiceClient.java

private InvocationResult doInvokeGET(String parameters, Map<String, String> httpHeaders, int retries,
        long connectTimeoutMS, long readTimeoutMS, boolean doUseCache) throws Exception {
    if (retries < 0)
        throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(parameters));

    String host = new URL(endpointURL).getHost();
    if (!lastRequestedHosts.containsKey(host)) {
        lastRequestedHosts.put(host, new AtomicLong());
    }//from ww  w  . ja v  a2 s  . co  m
    Object lockForTargetHost = lastRequestedHosts.get(host);

    parameters = parameters.trim();
    String urlString = endpointURL;
    if (!strUtil.isEmpty(parameters)) {
        String separator = endpointURL.contains("?") ? "&" : "?";
        urlString = endpointURL + separator + parameters;
    }

    if (doUseCache) {
        /** retrieve result from document cache */
        CacheEntry existing = cache.get(urlString);
        if (existing != null && !strUtil.isEmpty(existing.value)) {
            String valueShort = (String) existing.value;
            if (valueShort.length() > 200)
                valueShort = valueShort.substring(0, 200) + "...";
            AtomicReference<Element> eRef = new AtomicReference<Element>();
            Parallelization.warnIfNoResultAfter(eRef, "! Client could not convert element ("
                    + existing.value.length() + " bytes) within 15 seconds: " + valueShort, 15 * 1000);
            Parallelization.warnIfNoResultAfter(eRef, "! Client could not convert element ("
                    + existing.value.length() + " bytes) within 40 seconds: " + valueShort, 40 * 1000);
            Element e = xmlUtil.toElement((String) existing.value);
            eRef.set(e);
            logger.info("Result exists in cache for URL " + urlString + " - " + e + " - "
                    + this.xmlUtil.toString().length());
            return new InvocationResult(e);
        }
    }

    pauseToAvoidSpamming();

    URL url = new URL(urlString);
    URLConnection c = url.openConnection();
    c.setConnectTimeout((int) connectTimeoutMS);
    c.setReadTimeout((int) readTimeoutMS);
    logger.info("Retrieving data from service using GET: " + url);

    String tmpID = PerformanceInterceptor.event(EventType.START_HTTP_GET);
    for (String key : httpHeaders.keySet()) {
        c.setRequestProperty(key, httpHeaders.get(key));
    }
    StringBuilder b = new StringBuilder();
    synchronized (lockForTargetHost) {
        try {
            BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String temp;
            while ((temp = r.readLine()) != null) {
                b.append(temp);
                b.append("\n");
            }
        } catch (Exception e) {
            logger.info("Could not GET page with regular URLConnection, trying HtmlUnit..: " + e);
            b = getPageUsingHtmlUnit(urlString, httpHeaders, readTimeoutMS, null);
        }
    }

    PerformanceInterceptor.event(EventType.FINISH_HTTP_GET, tmpID);

    String tmpID1 = PerformanceInterceptor.event(EventType.START_RESPONSE_TO_XML);
    String result = b.toString().trim();
    if (!result.startsWith("<") || !result.endsWith(">")) { // wrap non-xml results (e.g., CSV files)
        StringBuilder sb = new StringBuilder("<doc><![CDATA[");
        sb.append(result);
        sb.append("]]></doc>");
        result = sb.toString();
    }

    String tmpID2 = PerformanceInterceptor.event(EventType.START_STRING_TO_XML);
    Element resultElement = xmlUtil.toElement(result);
    PerformanceInterceptor.event(EventType.FINISH_STRING_TO_XML, tmpID2);

    if (doUseCache) {
        /** put result element to document cache */
        cache.putWithoutWaiting(urlString, xmlUtil.toString(resultElement, true));
    }

    InvocationResult invResult = new InvocationResult(resultElement);
    PerformanceInterceptor.event(EventType.FINISH_RESPONSE_TO_XML, tmpID1);

    return invResult;
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

/**
 * Verifies the signature on an enveloped digital signature on a UDDI
 * entity, such as a business, service, tmodel or binding template.
 * <br><Br>/*from ww  w.j  a  v  a  2 s . c  o  m*/
 * It is expected that either the public key of the signing certificate
 * is included within the signature keyinfo section OR that sufficient
 * information is provided in the signature to reference a public key
 * located within the Trust Store provided<br><Br> Optionally, this
 * function also validate the signing certificate using the options
 * provided to the configuration map.
 *
 * @param obj an enveloped signed JAXB object
 * @param OutErrorMessage a human readable error message explaining the
 * reason for failure
 * @return true if the validation passes the signature validation test,
 * and optionally any certificate validation or trust chain validation
 * @throws IllegalArgumentException for null input
 */
public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage)
        throws IllegalArgumentException {
    if (OutErrorMessage == null) {
        OutErrorMessage = new AtomicReference<String>();
        OutErrorMessage.set("");
    }
    if (obj == null) {
        throw new IllegalArgumentException("obj");
    }
    try {
        DOMResult domResult = new DOMResult();
        JAXB.marshal(obj, domResult);

        Document doc = ((Document) domResult.getNode());
        Element docElement = doc.getDocumentElement(); //this is our signed node

        X509Certificate signingcert = getSigningCertificatePublicKey(docElement);

        if (signingcert != null) {
            logger.info(
                    "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString());
            if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) {
                signingcert.checkValidity();
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) {
                logger.info("verifying revocation status via OSCP for X509 public key "
                        + signingcert.getSubjectDN().toString());
                X500Principal issuerX500Principal = signingcert.getIssuerX500Principal();
                logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by "
                        + issuerX500Principal.getName() + ", attempting to retrieve certificate");
                Security.setProperty("ocsp.enable", "false");
                X509Certificate issuer = FindCertByDN(issuerX500Principal);
                if (issuer == null) {
                    OutErrorMessage.set(
                            "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. "
                                    + OutErrorMessage.get());
                    //throw new CertificateException("unable to locate the issuers certificate in the trust store");
                } else {
                    RevocationStatus check = OCSP.check(signingcert, issuer);
                    logger.info("certificate " + signingcert.getSubjectDN().toString()
                            + " revocation status is " + check.getCertStatus().toString() + " reason "
                            + check.getRevocationReason().toString());
                    if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) {
                        OutErrorMessage
                                .set("Certificate status is " + check.getCertStatus().toString() + " reason "
                                        + check.getRevocationReason().toString() + "." + OutErrorMessage.get());

                        //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString());
                    }
                }
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_CRL)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) {
                logger.info("verifying revokation status via CRL for X509 public key "
                        + signingcert.getSubjectDN().toString());

                Security.setProperty("ocsp.enable", "false");
                System.setProperty("com.sun.security.enableCRLDP", "true");

                X509CertSelector targetConstraints = new X509CertSelector();
                targetConstraints.setCertificate(signingcert);
                PKIXParameters params = new PKIXParameters(GetTrustStore());
                params.setRevocationEnabled(true);
                CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                CertPathValidator certPathValidator = CertPathValidator
                        .getInstance(CertPathValidator.getDefaultType());
                CertPathValidatorResult result = certPathValidator.validate(certPath, params);
                try {
                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
                    logger.info("revokation status via CRL PASSED for X509 public key "
                            + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            if (map.containsKey(CHECK_TRUST_CHAIN)
                    && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) {
                logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString());
                try {
                    PKIXParameters params = new PKIXParameters(GetTrustStore());
                    params.setRevocationEnabled(false);
                    CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                    CertPathValidator certPathValidator = CertPathValidator
                            .getInstance(CertPathValidator.getDefaultType());
                    CertPathValidatorResult result = certPathValidator.validate(certPath, params);

                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;

                    TrustAnchor ta = pkixResult.getTrustAnchor();
                    X509Certificate cert = ta.getTrustedCert();

                    logger.info(
                            "trust chain validated X509 public key " + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage);
            if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) {
                //no error message and its cryptographically valid
                return true;
            }
            return false;
        }

        //last chance validation
        logger.info(
                "signature did not have an embedded X509 public key. reverting to user specified certificate");
        //cert wasn't included in the signature, revert to some other means
        KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE));
        URL url = Thread.currentThread().getContextClassLoader()
                .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
        if (url == null) {
            try {
                url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL();
            } catch (Exception x) {
            }
        }
        if (url == null) {
            try {
                url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
            } catch (Exception x) {
            }
        }
        if (url == null) {
            logger.error("");
            OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and"
                    + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get());
            return false;
        }
        KeyStore.PrivateKeyEntry keyEntry = null;

        ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray());

        if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()));
        } else {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray()));
        }

        Certificate origCert = keyEntry.getCertificate();
        if (map.containsKey(CHECK_TIMESTAMPS)) {
            if (origCert.getPublicKey() instanceof X509Certificate) {
                X509Certificate x = (X509Certificate) origCert.getPublicKey();
                x.checkValidity();
            }
        }
        PublicKey validatingKey = origCert.getPublicKey();
        return verifySignature(docElement, validatingKey, OutErrorMessage);
    } catch (Exception e) {
        //throw new RuntimeException(e);
        logger.error("Error caught validating signature", e);
        OutErrorMessage.set(e.getMessage());
        return false;
    }
}

From source file:org.cerberus.launchcampaign.checkcampaign.CheckCampaignStatus.java

/**
 * Check all 5 seconds the status of campaign's execution. 
 * @param checkCampaign call method checkCampaign() all 5 seconds with parameter {@link ResultCIDto}.  
 *                   {@link ResultCIDto} contains all information of execution of campaing at the instant t
 * @param result call method result() when campaign execution is finish.
 *             {@link ResultCIDto} contains all information of execution at finish time
 * @throws Exception //from   w  ww  .jav a2 s.com
 */
public void execute(final CheckCampaignEvent checkCampaign, final ResultEvent result, final LogEvent logEvent)
        throws Exception {
    final ScheduledThreadPoolExecutor sch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

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

    sch.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            try {
                URL resultURL = new URL(urlCerberus + "/" + Constantes.URL_RESULT_CI + "?tag=" + tagCerberus);
                ResultCIDto resultDto = new ObjectMapper().readValue(resultURL, ResultCIDto.class);

                // condition to finish task
                if (!"PE".equals(resultDto.getResult())) {
                    result.result(resultDto);
                    sch.shutdown(); // when campaign is finish, we shutdown the schedule thread
                }

                if (!checkCampaign.checkCampaign(resultDto)) {
                    sch.shutdown();
                }
            } catch (SocketException e) {
                // do nothing during network problem. Wait the timeout to shutdown, and notify the error to logEvent
                logEvent.log("", e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
            } catch (Exception e) {
                exceptionOnThread.set(e);
                sch.shutdown();
            }
        }
    }, 0, this.timeToRefreshCampaignStatus, TimeUnit.SECONDS);

    sch.awaitTermination(this.timeoutForCampaignExecution, TimeUnit.SECONDS);

    // pass exeption of thread to called method
    if (exceptionOnThread.get() != null) {
        throw exceptionOnThread.get();
    }
}

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

/**
 * @return 'true' wenn alles fehlerfrei lief
 *//*w  w w.j a  v a 2s.com*/
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.apache.tinkerpop.gremlin.structure.TransactionTest.java

@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
@FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = Graph.Features.GraphFeatures.FEATURE_TRANSACTIONS)
@FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = Graph.Features.GraphFeatures.FEATURE_PERSISTENCE)
public void shouldCommitOnCloseWhenConfigured() throws Exception {
    final AtomicReference<Object> oid = new AtomicReference<>();
    final Thread t = new Thread(() -> {
        final Vertex v1 = graph.addVertex("name", "marko");
        g.tx().onClose(Transaction.CLOSE_BEHAVIOR.COMMIT);
        oid.set(v1.id());
        graph.tx().close();//from   www . j  a  v  a  2s  . c o m
    });
    t.start();
    t.join();

    final Vertex v2 = graph.vertices(oid.get()).next();
    assertEquals("marko", v2.<String>value("name"));
}

From source file:eu.eubrazilcc.lvl.storage.oauth2.dao.ResourceOwnerDAO.java

private boolean isValidUsingEmail(final String email, final String password,
        final @Nullable AtomicReference<String> scopeRef, final @Nullable AtomicReference<String> ownerIdRef) {
    checkArgument(isNotBlank(email), "Uninitialized or invalid email address");
    checkArgument(isNotBlank(password), "Uninitialized or invalid password");
    final ResourceOwner resourceOwner = findByEmail(email);
    final boolean isValid = (resourceOwner != null && resourceOwner.getUser() != null
            && email.equals(resourceOwner.getUser().getEmail())
            && hashAndSaltPassword(password, resourceOwner.getUser().getSalt())
                    .equals(resourceOwner.getUser().getPassword()));
    if (isValid) {
        if (scopeRef != null) {
            scopeRef.set(oauthScope(resourceOwner, false));
        }//from   ww  w . j  a  v a  2 s .  c o m
        if (ownerIdRef != null) {
            ownerIdRef.set(resourceOwner.getOwnerId());
        }
    }
    return isValid;
}

From source file:org.jasig.ssp.service.impl.EvaluatedSuccessIndicatorServiceImpl.java

private void getForPersonInTransaction(UUID personId, ObjectStatus status,
        AtomicReference<List<EvaluatedSuccessIndicatorTO>> rsltHolder) throws ObjectNotFoundException {

    final Person person = findPersonOrFail(personId);

    final PagingWrapper<SuccessIndicator> successIndicators = successIndicatorService.getAll(allActive());

    if (successIndicators.getResults() <= 0L) {
        rsltHolder.set(Lists.<EvaluatedSuccessIndicatorTO>newArrayListWithCapacity(0));
        return;/*from w w  w  .j  a  va  2  s. com*/
    }

    final ArrayList<EvaluatedSuccessIndicatorTO> evaluations = Lists
            .newArrayListWithExpectedSize((int) successIndicators.getResults());
    evaluationResourceCache.set(Maps.<String, Object>newLinkedHashMap());
    try {
        for (SuccessIndicator successIndicator : successIndicators) {
            try {
                final EvaluatedSuccessIndicatorTO evaluation = evaluate(successIndicator, person);
                if (evaluation != null) {
                    evaluations.add(evaluation);
                }
            } catch (Exception e) {
                // This rarely happens b/c evaluate() should be catching nearly all problems since the goal
                // is to aways return an evaluation TO with as much possible info for all active indicators, even
                // if the eval fails. If we tried to do that here, we wouldn't be able to output metric values in
                // the TO, for example. So while this is a handled exception, it does indicate a more serious
                // problem (probably a bad indicator code) than elsewhere in this class, so logging at a higher
                // level.
                LOGGER.error("System failure evaluating success indicator [{}] for person [{}]",
                        new Object[] { successIndicatorLoggingId(successIndicator), person.getId(), e });
            }
        }
    } finally {
        evaluationResourceCache.set(null);
    }
    rsltHolder.set(evaluations);
}

From source file:org.apache.servicemix.http.ProviderEndpointTest.java

public void testSoap() throws Exception {
    final AtomicReference<String> soapAction = new AtomicReference<String>();

    EchoComponent echo = new EchoComponent();
    echo.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "EchoService"));
    echo.setEndpoint("service");
    container.activateComponent(echo, "echo");

    HttpComponent http = new HttpComponent();

    HttpConsumerEndpoint ep0 = new HttpConsumerEndpoint();
    ep0.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService"));
    ep0.setEndpoint("consumer");
    ep0.setTargetService(new QName("http://servicemix.apache.org/samples/wsdl-first", "EchoService"));
    ep0.setTargetEndpoint("service");
    ep0.setLocationURI("http://localhost:8192/PersonService/");
    ep0.setMarshaler(new DefaultHttpConsumerMarshaler() {
        public MessageExchange createExchange(HttpServletRequest request, ComponentContext context)
                throws Exception {
            soapAction.set(request.getHeader("SOAPAction"));
            return super.createExchange(request, context); //To change body of overridden methods use File | Settings | File Templates.
        }/*from w w w  .  j a  v  a 2  s  .c om*/
    });

    HttpSoapProviderEndpoint ep1 = new HttpSoapProviderEndpoint();
    ep1.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService"));
    ep1.setEndpoint("soap");
    ep1.setWsdl(new ClassPathResource("person.wsdl"));
    ep1.setValidateWsdl(false); // TODO: Soap 1.2 not handled yet
    ep1.setUseJbiWrapper(true);

    http.setEndpoints(new HttpEndpointType[] { ep0, ep1 });
    container.activateComponent(http, "http");

    container.start();

    ServiceMixClient client = new DefaultServiceMixClient(container);
    InOut me = client.createInOutExchange();
    me.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService"));
    me.setOperation(new QName("http://servicemix.apache.org/samples/wsdl-first", "GetPerson"));
    me.getInMessage().setContent(
            new StringSource("<jbi:message xmlns:jbi=\"http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper\""
                    + "             xmlns:msg=\"http://servicemix.apache.org/samples/wsdl-first/types\" "
                    + "             name=\"Hello\" " + "             type=\"msg:HelloRequest\" "
                    + "             version=\"1.0\">" + "  <jbi:part>"
                    + "    <msg:GetPerson><msg:personId>id</msg:personId></msg:GetPerson>" + "  </jbi:part>"
                    + "</jbi:message>"));
    client.sendSync(me);
    client.done(me);
    assertEquals("\"urn:myaction\"", soapAction.get());
}

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  . j a va 2s. 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());
}