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

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

Introduction

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

Prototype

public AtomicReference() 

Source Link

Document

Creates a new AtomicReference with null initial value.

Usage

From source file:org.zodiark.subscriber.SubscriberTest.java

@Test(enabled = false)
public void sucessfulRequestForAction() throws IOException, InterruptedException {
    final CountDownLatch completed = new CountDownLatch(1);

    final ZodiarkClient wowzaClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch connected = new CountDownLatch(1);
    final AtomicReference<String> uuid = new AtomicReference<>();
    final AtomicReference<String> paths = new AtomicReference<>();

    // =============== Wowza

    paths.set("");
    wowzaClient.handler(new OnEnvelopHandler() {
        @Override/*  w  w  w  .j  a v  a2  s.co  m*/
        public boolean onEnvelop(Envelope e) throws IOException {

            Message m = e.getMessage();
            switch (m.getPath()) {
            case Paths.WOWZA_CONNECT:
                // Connected. Listen
                uuid.set(e.getUuid());
                break;
            case Paths.SERVER_VALIDATE_OK:
                Envelope publisherOk = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(paths.get()), e.getMessage().getData()));
                wowzaClient.send(publisherOk);
                break;
            case Paths.WOWZA_OBFUSCATE:
                WowzaMessage wm = mapper.readValue(m.getData(), WowzaMessage.class);
                Envelope ok = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.WOWZA_OBFUSCATE_OK), e.getMessage().getData()));
                System.out.println("Obfuscating Subscribers");
                wowzaClient.send(ok);
            case Paths.WOWZA_DEOBFUSCATE:
                wm = mapper.readValue(m.getData(), WowzaMessage.class);
                System.out.println("De-obfuscating Subscribers");
                ok = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.WOWZA_DEOBFUSCATE_OK), e.getMessage().getData()));
                wowzaClient.send(ok);
            default:
                // ERROR
            }

            connected.countDown();
            return false;
        }
    }).open();

    Envelope wowzaConnect = Envelope.newClientToServerRequest(new Message(new Path(Paths.WOWZA_CONNECT),
            mapper.writeValueAsString(new UserPassword("wowza", "bar"))));
    wowzaClient.send(wowzaConnect);
    connected.await();

    // ================ Publisher

    final AtomicReference<PublisherResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> publisherUUID = new AtomicReference<>();
    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            publisherUUID.set(e.getUuid());
            latch.countDown();
            return true;
        }
    }).open();

    // ================ Publisher create the session

    Envelope createSessionMessage = Envelope.newClientToServerRequest(
            new Message(new Path(""), mapper.writeValueAsString(new UserPassword("publisherex", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
    answer.set(null);

    final CountDownLatch tlatch = new CountDownLatch(1);
    final AtomicReference<String> finalMessage = new AtomicReference<>();

    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {

            switch (e.getMessage().getPath()) {
            case Paths.BEGIN_STREAMING_SESSION:
                answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
                tlatch.countDown();
                break;
            case Paths.PUBLISHER_ACTION_ACCEPT:
                Action a = mapper.readValue(e.getMessage().getData(), Action.class);
                Envelope publisherOk = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.ZODIARK_ACTION_ACCEPTED), e.getMessage().getData()));
                publisherClient.send(publisherOk);
                break;
            case Paths.ACTION_START:
                // Start action
                PublisherResults results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);
                System.out.println("==> Start Action " + results.getResults());

                publisherOk = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.ACTION_START_OK), e.getMessage().getData()));
                publisherClient.send(publisherOk);
                break;
            case Paths.ACTION_TIMER:
                Time t = mapper.readValue(e.getMessage().getData(), Time.class);
                System.out.println("Publisher ===>" + t);
                break;
            case Paths.ACTION_COMPLETED:
                results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);
                System.out.println("Publisher Action completed");
                completed.countDown();
                break;
            case Paths.PUBLISHER_ABOUT_READY:
                results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);

                finalMessage.set(results.getResults());
                break;
            }
            return false;
        }
    });

    // ================ Prepare for streaming, handshake with Wowza

    Envelope startStreamingSession = Envelope
            .newClientToServerRequest(new Message(new Path(Paths.VALIDATE_PUBLISHER_STREAMING_SESSION),
                    mapper.writeValueAsString(new WowzaUUID(uuid.get()))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(startStreamingSession);

    tlatch.await();

    assertEquals("OK", answer.get().getResults());

    // ================ Subscriber

    paths.set(Paths.JOIN_SUBSCRIBER_STREAMING_SESSION);
    final AtomicReference<SubscriberResults> sanswer = new AtomicReference<>();
    final ZodiarkClient subscriberClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch platch = new CountDownLatch(1);
    final AtomicReference<String> subscriberUUID = new AtomicReference<>();

    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            subscriberUUID.set(e.getUuid());
            platch.countDown();
            return true;
        }
    }).open();

    // ================ Subscriber create the session

    createSessionMessage = Envelope.newClientToServerRequest(subscriberUUID.get(),
            new Message(new Path(Paths.DB_POST_SUBSCRIBER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("123456", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.SUBSCRIBER));
    subscriberClient.send(createSessionMessage);
    platch.await();
    assertEquals("OK", sanswer.get().getResults());
    sanswer.set(null);

    final CountDownLatch elatch = new CountDownLatch(1);
    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            elatch.countDown();
            return true;
        }
    });

    // ================ Join the Publisher Session

    StreamingRequest request = new StreamingRequestImpl(publisherUUID.get(), uuid.get());
    startStreamingSession = Envelope.newClientToServerRequest(subscriberUUID.get(), new Message(
            new Path(Paths.VALIDATE_SUBSCRIBER_STREAMING_SESSION), mapper.writeValueAsString(request)));
    startStreamingSession.setFrom(new From(ActorValue.SUBSCRIBER));
    subscriberClient.send(startStreamingSession);

    elatch.await();

    assertEquals("OK", sanswer.get().getResults());

    // ================ Ask for an Action the Publisher Session

    Action action = new Action();
    action.setPath("/action/doSomething");
    action.setData("{ \"foo\":\"bar\"");
    Envelope e = Envelope.newClientToServerRequest(subscriberUUID.get(),
            new Message(new Path(Paths.SUBSCRIBER_ACTION), mapper.writeValueAsString(action)));
    e.setFrom(new From(ActorValue.SUBSCRIBER));
    final CountDownLatch actionLatch = new CountDownLatch(1);
    final AtomicReference<Envelope> response = new AtomicReference<>();
    final AtomicBoolean timerCalled = new AtomicBoolean();
    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            switch (e.getMessage().getPath()) {
            case Paths.MESSAGE_ACTION_VALIDATE:
                response.set(e);
                actionLatch.countDown();
                break;
            case Paths.ACTION_TIMER:
                Time t = mapper.readValue(e.getMessage().getData(), Time.class);
                System.out.println("Subscriber ===>" + t);
                timerCalled.set(true);
                break;
            case Paths.ACTION_COMPLETED:
                SubscriberResults results = mapper.readValue(e.getMessage().getData(), SubscriberResults.class);
                System.out.println("Action completed");
                break;
            }

            return false;
        }
    });
    subscriberClient.send(e);

    actionLatch.await();

    assertEquals(Paths.MESSAGE_ACTION_VALIDATE, response.get().getMessage().getPath());
    assertEquals("{\"results\":\"OK\",\"uuid\":null}", response.get().getMessage().getData());

    completed.await();

    assertTrue(timerCalled.get());
    assertEquals("READY", finalMessage.get());
}

From source file:org.appverse.web.framework.backend.frontfacade.websocket.IntegrationWebsocketTest.java

@Test
public void getPositions() throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<>();

    StompSessionHandler handler = new AbstractTestSessionHandler(failure) {

        @Override//from  w  ww .j  a va  2s . c  o  m
        public void afterConnected(final StompSession session, StompHeaders connectedHeaders) {
            session.subscribe("/app/positions", new StompFrameHandler() {
                @Override
                public Type getPayloadType(StompHeaders headers) {
                    return byte[].class;
                }

                @Override
                public void handleFrame(StompHeaders headers, Object payload) {
                    String json = new String((byte[]) payload);
                    logger.debug("Got " + json);
                    try {
                        new JsonPathExpectationsHelper("$[0].company").assertValue(json,
                                "Citrix Systems, Inc.");
                        new JsonPathExpectationsHelper("$[1].company").assertValue(json, "Dell Inc.");
                        new JsonPathExpectationsHelper("$[2].company").assertValue(json, "Microsoft");
                        new JsonPathExpectationsHelper("$[3].company").assertValue(json, "Oracle");
                    } catch (Throwable t) {
                        failure.set(t);
                    } finally {
                        session.disconnect();
                        latch.countDown();
                    }
                }
            });
        }
    };

    WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
    stompClient.connect("http://localhost:{port}/services/websocket", this.headers, handler, port);

    if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }

    if (!latch.await(5, TimeUnit.SECONDS)) {
        fail("Portfolio positions not received");
    }
}

From source file:com.microsoft.tfs.client.clc.Application.java

/**
 * Does almost all of the work of the command-line client. This method is
 * invoked from the static main() method, and also recursively when a
 * command file is encountered.//from w  w  w .j  av  a 2  s .c o  m
 *
 * @param args
 *        the command-line arguments as passed into the process by the Java
 *        virtual machine (or in that style, but parsed from a command
 *        file).
 * @param recursiveCall
 *        true if this method was called recursively from itself, false
 *        otherwise.
 * @return the status code to exit the process with.
 */
private int run(final String[] args, final boolean recursiveCall) {
    log.debug("Entering CLC application"); //$NON-NLS-1$
    log.debug("Command line: "); //$NON-NLS-1$
    for (int i = 0; i < args.length; i++) {
        final int p = args[i].toLowerCase().indexOf("login:"); //$NON-NLS-1$
        if (p < 0) {
            log.debug("     args[" + i + "]: " + args[i]); //$NON-NLS-1$ //$NON-NLS-2$
        } else {
            log.debug("     args[" + i + "]: " + args[i].substring(0, p + 6) + "*******"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }

    }
    /*
     * create and cache the options map and commands map we also set the
     * maps on the static Help class so the Help class always has access to
     * them
     */
    optionsMap = createOptionsMap();
    commandsMap = createCommandsMap();
    Help.init(commandsMap, optionsMap);

    Command c = null;
    int ret = ExitCode.UNKNOWN;
    boolean printExitCode = false;

    try {
        final String[] tokens = args.clone();

        log.debug("Parse and prepare arguments."); //$NON-NLS-1$
        /*
         * Check to see if the first argument is a file containing commands.
         * Don't allow this if we're being called recursively.
         */
        if (recursiveCall == false && tokens.length > 0 && tokens[0].startsWith("@")) //$NON-NLS-1$
        {
            /*
             * Search all the arguments for the "continue on error" and
             * output separator options.
             */
            boolean continueOnError = false;
            String outputSeparator = null;
            for (int i = 0; i < tokens.length; i++) {
                if (tokens[i] == null || tokens[i].length() == 0) {
                    continue;
                }

                try {
                    final Option o = optionsMap.findOption(tokens[i]);

                    if (o instanceof OptionContinueOnError) {
                        continueOnError = true;
                    } else if (o instanceof OptionOutputSeparator) {
                        outputSeparator = ((OptionOutputSeparator) o).getValue();
                    }
                } catch (final Exception e) {
                    // Ignore.
                }
            }

            try {
                ret = runCommandFile(tokens, continueOnError, outputSeparator);
            } catch (final FileNotFoundException e) {
                final String messageFormat = Messages.getString("Application.CommandFileCoundNotBeFoundFormat"); //$NON-NLS-1$
                final String message = MessageFormat.format(messageFormat, tokens[0].substring(1));
                display.printErrorLine(message);
            } catch (final IOException e) {
                final String messageFormat = Messages
                        .getString("Application.ErrorReadingFromCommandFileFormat"); //$NON-NLS-1$
                final String message = MessageFormat.format(messageFormat, tokens[0].substring(1),
                        e.getLocalizedMessage());
                log.warn(message, e);
                display.printErrorLine(message);
            }

            return ret;
        }

        final ArrayList<Option> options = new ArrayList<Option>();
        final ArrayList<String> freeArguments = new ArrayList<String>();

        /*
         * Parse all the args into a command, its options, and free
         * arguments.
         */

        final AtomicReference<Exception> outException = new AtomicReference<Exception>();
        c = parseTokens(args, options, freeArguments, outException);

        /*
         * Set the display on the command as soon as possible, so it can
         * write errors/messages.
         */
        if (c != null) {
            c.setInput(input);
            c.setDisplay(display);
        }

        /*
         * Search for the help option anywhere in the command line.
         * Microsoft's client does this for user convenience. Also look for
         * the exit code option while we're searching.
         */
        boolean foundHelpOption = false;
        for (int i = 0; i < options.size(); i++) {
            if (options.get(i) instanceof OptionHelp) {
                foundHelpOption = true;
            }

            if (options.get(i) instanceof OptionExitCode) {
                printExitCode = true;
            }
        }

        final boolean invalidCommandArguments = outException.get() != null;

        if (tokens.length == 0 || c == null || foundHelpOption || invalidCommandArguments) {
            if (invalidCommandArguments) {
                final String messageFormat = Messages.getString("Application.AnArgumentErrorOccurredFormat"); //$NON-NLS-1$
                final String message = MessageFormat.format(messageFormat,
                        outException.get().getLocalizedMessage());
                display.printErrorLine(message);
            }

            Help.show(c, display);

            return invalidCommandArguments ? ExitCode.FAILURE : ExitCode.SUCCESS;
        }

        c.setOptions(options.toArray(new Option[0]), commandsMap.getGlobalOptions());
        c.setFreeArguments(freeArguments.toArray(new String[0]));

        log.debug("Execute the command implementation."); //$NON-NLS-1$

        c.run();

        log.debug("Close the command: Flush any remaining notifications and remove the manager"); //$NON-NLS-1$
        c.close();

        ret = c.getExitCode();
    } catch (final CanceledException e) {
        getDisplay().printErrorLine(""); //$NON-NLS-1$
        getDisplay().printErrorLine(Messages.getString("Application.CommandCanceled")); //$NON-NLS-1$

        ret = ExitCode.FAILURE;
    } catch (final InputValidationException e) {
        final String messageFormat = Messages.getString("Application.AnInputValidationErrorOccurredFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage());
        display.printErrorLine(message);

        ret = ExitCode.FAILURE;
    } catch (final ArgumentException e) {
        /*
         * Argument exceptions happen when the user supplies an incorrect
         * command, misspelled options, the wrong option values, is missing
         * an option, or other similar error. We should show the help to the
         * user in this case.
         */
        final String messageFormat = Messages.getString("Application.AnArgumentErrorOccurredFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage());
        display.printErrorLine(message);

        Help.show(c, display);

        ret = ExitCode.FAILURE;
    } catch (final IllegalArgumentException e) {
        /*
         * Same as above but returned by some low level Core or Common
         * classes, e.g. HttpHost.
         */
        CLCTelemetryHelper.sendException(e);

        final String messageFormat = Messages.getString("Application.AnArgumentErrorOccurredFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage());
        display.printErrorLine(message);

        ret = ExitCode.FAILURE;
    } catch (final CLCException e) {
        /*
         * CLCExceptions have messages that are meaningful to users.
         */
        final String messageFormat = Messages.getString("Application.AClientErrorOccurredFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage());
        log.error(message, e);
        display.printErrorLine(message);

        ret = ExitCode.FAILURE;
    } catch (final MalformedURLException e) {
        final String messageFormat = Messages.getString("Application.StringCouldNotBeConvertedToURLFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage());
        log.info(message, e);
        display.printErrorLine(message);
        ret = ExitCode.FAILURE;
    } catch (final LicenseException e) {
        final String messageFormat = Messages.getString("Application.LicenseErrorFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage());
        log.error(message, e);
        display.printErrorLine(message);

        if (e.getType() == LicenseExceptionType.EULA) {
            display.printErrorLine(Messages.getString("Application.RunTfEulaToAccept")); //$NON-NLS-1$
        } else {
            display.printErrorLine(Messages.getString("Application.RunTfProductkeyToInstall")); //$NON-NLS-1$
        }

        ret = ExitCode.FAILURE;
    } catch (final AuthenticationSecurityException e) {
        /*
         * Thrown when using insecure credentials over an insecure channel.
         */
        log.error(e);
        display.printErrorLine(e.getLocalizedMessage());
        ret = ExitCode.FAILURE;
    } catch (final TFSFederatedAuthException e) {
        /*
         * FederatedAuthenticationException is thrown when
         * DefaultFederatedAuthenticationHandler decided not to try to auth,
         * which only happens because the username and/or password weren't
         * available.
         */
        final String message = Messages.getString("Command.FedAuthRequiresUsernamePassword"); //$NON-NLS-1$
        log.error(message, e);
        display.printErrorLine(message);
        ret = ExitCode.FAILURE;
    } catch (final ProxyException e) {
        final String message = MessageFormat.format(
                Messages.getString("Application.ProblemContactingServerFormat"), //$NON-NLS-1$
                e.getLocalizedMessage());
        log.error(message, e);
        display.printErrorLine(message);
        ret = ExitCode.FAILURE;
    } catch (final TECoreException e) {
        /*
         * The most basic core exception class. All lower level (SOAP)
         * exceptions are wrapped in these.
         */
        CLCTelemetryHelper.sendException(e);

        final String messageFormat = Messages.getString("Application.AnErrorOccurredFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, e.getLocalizedMessage());
        log.error(message, e);
        display.printErrorLine(message);
        ret = ExitCode.FAILURE;
    } catch (final Throwable e) {
        CLCTelemetryHelper.sendException(new Exception("Unexpected exception.", e)); //$NON-NLS-1$

        log.error("Unexpected exception: ", e); //$NON-NLS-1$
    }

    // If the exit code never got set, set it to 0.
    if (ret == ExitCode.UNKNOWN) {
        ret = ExitCode.SUCCESS;
    }

    if (printExitCode) {
        final String messageFormat = Messages.getString("Application.ExitCodeFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, Integer.toString(ret));
        display.printLine(message);
        display.printLine(""); //$NON-NLS-1$
    }

    CLCTelemetryHelper.sendCommandFinishedEvent(c, ret);
    log.debug("Leaving CLC application"); //$NON-NLS-1$

    return ret;
}

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

/**
 * Given a baseline file GUID, and the target local path where the item will
 * be placed in the workspace, returns the path (without file extension)
 * where the baseline file should be created on disk. This method is used to
 * place new baselines on disk.//from  w  w  w .  ja va  2  s  .  com
 *
 * Do not use this method to look up the location of a baseline that already
 * exists.
 *
 * @param workspace
 * @param baselineFolders
 * @param baselineFileGuid
 *        Baseline file GUID for the baseline
 * @param targetLocalItem
 *        The location on disk of the file
 * @return The filename on disk where the baseline should be placed (except
 *         for file extension)
 */
public static String getNewBaselineLocation(final Workspace workspace,
        final List<BaselineFolder> baselineFolders, final byte[] baselineFileGuid,
        final String targetLocalItem) {
    BaselineFolder.checkForValidBaselineFileGUID(baselineFileGuid);

    BaselineFolder baselineFolder = null;

    if (targetLocalItem != null && targetLocalItem.length() > 0) {
        baselineFolder = getBaselineFolderForPartition(baselineFolders,
                BaselineFolder.getPartitionForPath(targetLocalItem));
    }

    if (null == baselineFolder && baselineFolders.size() > 0) {
        baselineFolder = baselineFolders.get(0);
    }

    final AtomicReference<String> outIndividualBaselineFolder = new AtomicReference<String>();
    String toReturn;

    if (null == baselineFolder) {
        // There were no baseline folders available to host this baseline.
        // We will instead store it in our fallback location in the
        // ProgramData location.
        BaselineFolder.ensureLocalMetadataDirectoryExists(workspace);

        toReturn = BaselineFolder.getPathFromGUID(workspace.getLocalMetadataDirectory(), baselineFileGuid,
                outIndividualBaselineFolder);

        final File directory = new File(outIndividualBaselineFolder.get());
        if (!directory.exists()) {
            directory.mkdirs();
        }

        return toReturn;
    } else {
        BaselineFolder.ensureBaselineDirectoryExists(workspace, baselineFolder.getPath());

        toReturn = BaselineFolder.getPathFromGUID(baselineFolder.getPath(), baselineFileGuid,
                outIndividualBaselineFolder);

        final File directory = new File(outIndividualBaselineFolder.get());
        if (!directory.exists()) {
            directory.mkdirs();
        }

        return toReturn;
    }
}

From source file:com.networknt.openapi.ValidatorHandlerTest.java

@Test
public void testGetParam() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from w w w.j a v  a 2s .com
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v1/pets/111").setMethod(Methods.GET);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(body);
        Assert.assertEquals("getPetById", body);
    }
}

From source file:org.apache.solr.servlet.SolrDispatchFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain, boolean retry)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest))
        return;//from www. j  a v  a 2 s .c  o m
    try {

        if (cores == null || cores.isShutDown()) {
            log.error(
                    "Error processing the request. CoreContainer is either not initialized or shutting down.");
            throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE,
                    "Error processing the request. CoreContainer is either not initialized or shutting down.");
        }

        AtomicReference<ServletRequest> wrappedRequest = new AtomicReference<>();
        if (!authenticateRequest(request, response, wrappedRequest)) { // the response and status code have already been
                                                                       // sent
            return;
        }
        if (wrappedRequest.get() != null) {
            request = wrappedRequest.get();
        }

        request = closeShield(request, retry);
        response = closeShield(response, retry);

        if (cores.getAuthenticationPlugin() != null) {
            log.debug("User principal: {}", ((HttpServletRequest) request).getUserPrincipal());
        }

        // No need to even create the HttpSolrCall object if this path is excluded.
        if (excludePatterns != null) {
            String requestPath = ((HttpServletRequest) request).getServletPath();
            String extraPath = ((HttpServletRequest) request).getPathInfo();
            if (extraPath != null) { // In embedded mode, servlet path is empty - include all post-context path here for
                                     // testing
                requestPath += extraPath;
            }
            for (Pattern p : excludePatterns) {
                Matcher matcher = p.matcher(requestPath);
                if (matcher.lookingAt()) {
                    chain.doFilter(request, response);
                    return;
                }
            }
        }

        HttpSolrCall call = getHttpSolrCall((HttpServletRequest) request, (HttpServletResponse) response,
                retry);
        ExecutorUtil.setServerThreadFlag(Boolean.TRUE);
        try {
            Action result = call.call();
            switch (result) {
            case PASSTHROUGH:
                chain.doFilter(request, response);
                break;
            case RETRY:
                doFilter(request, response, chain, true);
                break;
            case FORWARD:
                request.getRequestDispatcher(call.getPath()).forward(request, response);
                break;
            }
        } finally {
            call.destroy();
            ExecutorUtil.setServerThreadFlag(null);
        }
    } finally {
        consumeInputFully((HttpServletRequest) request);
    }
}

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

@Test
public void should_reinit_batch_context_and_consistency_after_exception_async() throws Exception {
    Tweet tweet1 = TweetTestBuilder.tweet().randomId().content("simple_tweet1").buid();
    Tweet tweet2 = TweetTestBuilder.tweet().randomId().content("simple_tweet2").buid();

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override/*w  ww. j a  v  a  2  s .c  o m*/
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

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

    asyncManager.insert(tweet1);

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

    batch.startBatch(EACH_QUORUM);
    batch.insert(tweet2);

    batch.asyncEndBatch(successCallBack);

    latch.await();

    assertThatBatchContextHasBeenReset(batch);

    logAsserter.prepareLogLevelForDriverConnection();
    batch.startBatch();
    batch.insert(tweet2);
    batch.asyncEndBatch();
    logAsserter.assertConsistencyLevels(ONE);

    assertThat(successSpy.get()).isEqualTo(Empty.INSTANCE);
}

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

@Test
public void should_return_entities_for_typed_query_async() throws Exception {
    CompleteBean paul = builder().randomId().name("Paul").age(35L).addFriends("foo", "bar")
            .addFollowers("George", "Jack").addPreference(1, "FR").addPreference(2, "Paris")
            .addPreference(3, "75014").buid();

    CompleteBean john = builder().randomId().name("John").age(34L).addFriends("qux", "twix")
            .addFollowers("Isaac", "Lara").addPreference(1, "US").addPreference(2, "NewYork").buid();

    asyncManager.insert(paul).getImmediately();
    asyncManager.insert(john).getImmediately();

    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<Object> successSpy1 = new AtomicReference<>();
    final AtomicReference<Object> successSpy2 = new AtomicReference<>();

    FutureCallback<Object> successCallBack1 = new FutureCallback<Object>() {
        @Override//from  www .  java 2s.  c  o m
        public void onSuccess(Object result) {
            successSpy1.getAndSet(result);
            latch.countDown();
        }

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

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

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

    final RegularStatement selectStar = select().from("CompleteBean").where(eq("id", bindMarker("id")));
    final List<CompleteBean> list1 = asyncManager.typedQuery(CompleteBean.class, selectStar, paul.getId())
            .get(successCallBack1).get();
    final CompleteBean foundJohn = asyncManager.typedQuery(CompleteBean.class, selectStar, john.getId())
            .getFirst(successCallBack2).get();

    latch.await();

    assertThat(list1).hasSize(1);

    CompleteBean foundPaul = list1.get(0);

    Factory factory1 = (Factory) foundPaul;
    @SuppressWarnings("unchecked")
    ProxyInterceptor<CompleteBean> interceptor1 = (ProxyInterceptor<CompleteBean>) factory1.getCallback(0);

    CompleteBean realPaul = (CompleteBean) interceptor1.getTarget();

    assertThat(realPaul.getLabel()).isNull();
    assertThat(realPaul.getWelcomeTweet()).isNull();

    assertThat(realPaul.getName()).isEqualTo(paul.getName());
    assertThat(realPaul.getAge()).isEqualTo(paul.getAge());
    assertThat(realPaul.getFriends()).containsAll(paul.getFriends());
    assertThat(realPaul.getFollowers()).containsAll(paul.getFollowers());
    assertThat(realPaul.getPreferences().get(1)).isEqualTo("FR");
    assertThat(realPaul.getPreferences().get(2)).isEqualTo("Paris");
    assertThat(realPaul.getPreferences().get(3)).isEqualTo("75014");

    Factory factory2 = (Factory) foundJohn;
    @SuppressWarnings("unchecked")
    ProxyInterceptor<CompleteBean> interceptor2 = (ProxyInterceptor<CompleteBean>) factory2.getCallback(0);

    CompleteBean realJohn = (CompleteBean) interceptor2.getTarget();

    assertThat(realJohn.getLabel()).isNull();
    assertThat(realJohn.getWelcomeTweet()).isNull();

    assertThat(realJohn.getName()).isEqualTo(john.getName());
    assertThat(realJohn.getAge()).isEqualTo(john.getAge());
    assertThat(realJohn.getFriends()).containsAll(john.getFriends());
    assertThat(realJohn.getFollowers()).containsAll(john.getFollowers());
    assertThat(realJohn.getPreferences().get(1)).isEqualTo("US");
    assertThat(realJohn.getPreferences().get(2)).isEqualTo("NewYork");

    latch.await();
    Thread.sleep(100);
    assertThat(successSpy1.get()).isNotNull().isInstanceOf(List.class);
    assertThat(successSpy2.get()).isNotNull().isInstanceOf(CompleteBean.class).isNotInstanceOf(Factory.class);
}

From source file:com.jivesoftware.os.amza.deployable.Main.java

public void run(String[] args) throws Exception {

    String hostname = args[0];/*from  w  w  w .  j a  va  2  s .  c om*/
    String clusterName = (args.length > 1 ? args[1] : "unnamed");
    String hostPortPeers = (args.length > 2 ? args[2] : null);

    int port = Integer.parseInt(System.getProperty("amza.port", "1175"));
    String multicastGroup = System.getProperty("amza.discovery.group", "225.4.5.6");
    int multicastPort = Integer.parseInt(System.getProperty("amza.discovery.port", "1223"));

    String logicalName = System.getProperty("amza.logicalName", hostname + ":" + port);
    String datacenter = System.getProperty("host.datacenter", "unknownDatacenter");
    String rack = System.getProperty("host.rack", "unknownRack");

    RingMember ringMember = new RingMember(logicalName);
    RingHost ringHost = new RingHost(datacenter, rack, hostname, port);

    // todo need a better way to create writer id.
    int writerId = Integer.parseInt(System.getProperty("amza.id", String.valueOf(new Random().nextInt(512))));

    SnowflakeIdPacker idPacker = new SnowflakeIdPacker();
    JiveEpochTimestampProvider timestampProvider = new JiveEpochTimestampProvider();
    final TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl(
            new ConstantWriterIdProvider(writerId), idPacker, timestampProvider);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, false);

    final AmzaServiceConfig amzaServiceConfig = new AmzaServiceConfig();
    final AmzaStats amzaSystemStats = new AmzaStats();
    final AmzaStats amzaStats = new AmzaStats();
    final SickThreads sickThreads = new SickThreads();
    final SickPartitions sickPartitions = new SickPartitions();

    AtomicInteger systemRingSize = new AtomicInteger(-1);
    amzaServiceConfig.workingDirectories = System.getProperty("amza.working.dirs", "./data1,./data2,./data3")
            .split(",");
    amzaServiceConfig.systemRingSize = Integer.parseInt(System.getProperty("amza.system.ring.size", "-1"));
    if (amzaServiceConfig.systemRingSize > 0) {
        systemRingSize.set(amzaServiceConfig.systemRingSize);
    }

    AmzaInterner amzaInterner = new AmzaInterner();

    PartitionPropertyMarshaller partitionPropertyMarshaller = new PartitionPropertyMarshaller() {
        @Override
        public PartitionProperties fromBytes(byte[] bytes) {
            try {
                return mapper.readValue(bytes, PartitionProperties.class);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        @Override
        public byte[] toBytes(PartitionProperties partitionProperties) {
            try {
                return mapper.writeValueAsBytes(partitionProperties);
            } catch (JsonProcessingException ex) {
                throw new RuntimeException(ex);
            }
        }
    };

    //  hmmm
    LABPointerIndexConfig labConfig = BindInterfaceToConfiguration.bindDefault(LABPointerIndexConfig.class);
    labConfig.setLeapCacheMaxCapacity(
            Integer.parseInt(System.getProperty("amza.leap.cache.max.capacity", "1000000")));

    BinaryPrimaryRowMarshaller primaryRowMarshaller = new BinaryPrimaryRowMarshaller(); // hehe you cant change this :)
    BinaryHighwaterRowMarshaller highwaterRowMarshaller = new BinaryHighwaterRowMarshaller(amzaInterner);

    AtomicReference<Callable<RingTopology>> topologyProvider = new AtomicReference<>(); // bit of a hack

    InstanceDescriptor instanceDescriptor = new InstanceDescriptor(datacenter, rack, "", "", "", "", "", "", "",
            "", 0, "", "", "", 0L, true);
    ConnectionDescriptorsProvider connectionsProvider = (connectionDescriptorsRequest,
            expectedReleaseGroup) -> {
        try {
            RingTopology systemRing = topologyProvider.get().call();
            List<ConnectionDescriptor> descriptors = Lists.newArrayList(Iterables.transform(systemRing.entries,
                    input -> new ConnectionDescriptor(instanceDescriptor, false, false,
                            new HostPort(input.ringHost.getHost(), input.ringHost.getPort()),
                            Collections.emptyMap(), Collections.emptyMap())));
            return new ConnectionDescriptorsResponse(200, Collections.emptyList(), "", descriptors,
                    connectionDescriptorsRequest.getRequestUuid());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
    TenantsServiceConnectionDescriptorProvider<String> connectionPoolProvider = new TenantsServiceConnectionDescriptorProvider<>(
            Executors.newScheduledThreadPool(1), "", connectionsProvider, "", "", 10_000); // TODO config
    connectionPoolProvider.start();

    TenantAwareHttpClient<String> httpClient = new TenantRoutingHttpClientInitializer<String>(null)
            .builder(connectionPoolProvider, new HttpDeliveryClientHealthProvider("", null, "", 5000, 100))
            .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).maxConnections(1_000)
            .socketTimeoutInMillis(60_000).build(); //TODO expose to conf

    AvailableRowsTaker availableRowsTaker = new HttpAvailableRowsTaker(httpClient, amzaInterner, mapper); // TODO config
    AquariumStats aquariumStats = new AquariumStats();

    AmzaService amzaService = new AmzaServiceInitializer().initialize(amzaServiceConfig, amzaInterner,
            aquariumStats, amzaSystemStats, amzaStats,
            new HealthTimer(CountersAndTimers.getOrCreate("quorumLatency"), "quorumLatency",
                    new NoOpHealthChecker<>("quorumLatency")),
            () -> amzaServiceConfig.systemRingSize, sickThreads, sickPartitions, primaryRowMarshaller,
            highwaterRowMarshaller, ringMember, ringHost, Collections.emptySet(), orderIdProvider, idPacker,
            partitionPropertyMarshaller, (workingIndexDirectories, indexProviderRegistry,
                    ephemeralRowIOProvider, persistentRowIOProvider, partitionStripeFunction) -> {
                indexProviderRegistry
                        .register(
                                new BerkeleyDBWALIndexProvider(BerkeleyDBWALIndexProvider.INDEX_CLASS_NAME,
                                        partitionStripeFunction, workingIndexDirectories),
                                persistentRowIOProvider);

                indexProviderRegistry.register(new LABPointerIndexWALIndexProvider(amzaInterner, labConfig,
                        Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
                        LABPointerIndexWALIndexProvider.INDEX_CLASS_NAME, partitionStripeFunction,
                        workingIndexDirectories), persistentRowIOProvider);
            }, availableRowsTaker, () -> {
                return new HttpRowsTaker("system", amzaStats, httpClient, mapper, amzaInterner,
                        Executors.newSingleThreadExecutor(), Executors.newCachedThreadPool());
            }, () -> {
                return new HttpRowsTaker("striped", amzaStats, httpClient, mapper, amzaInterner,
                        Executors.newSingleThreadExecutor(), Executors.newCachedThreadPool());
            }, Optional.absent(), (changes) -> {
            }, (threadCount, name) -> {
                return Executors.newCachedThreadPool();
            });

    topologyProvider.set(() -> amzaService.getRingReader().getRing(AmzaRingReader.SYSTEM_RING, -1));

    TailAtScaleStrategy tailAtScaleStrategy = new TailAtScaleStrategy(
            BoundedExecutor.newBoundedExecutor(1024, "tas"), 100, // TODO config
            95, // TODO config
            1000 // TODO config
    );

    AmzaClientProvider<HttpClient, HttpClientException> clientProvider = new AmzaClientProvider<>(
            new HttpPartitionClientFactory(),
            new HttpPartitionHostsProvider(httpClient, tailAtScaleStrategy, mapper),
            new RingHostHttpClientProvider(httpClient), BoundedExecutor.newBoundedExecutor(1024, "amza-client"),
            10_000, //TODO expose to conf
            -1, -1);

    final JerseyEndpoints jerseyEndpoints = new JerseyEndpoints().addEndpoint(AmzaEndpoints.class)
            .addInjectable(AmzaService.class, amzaService).addEndpoint(AmzaReplicationRestEndpoints.class)
            .addInjectable(AmzaInstance.class, amzaService).addEndpoint(AmzaClientRestEndpoints.class)
            .addInjectable(AmzaInterner.class, amzaInterner).addInjectable(ObjectMapper.class, mapper)
            .addInjectable(AmzaClientService.class, new AmzaClientService(amzaService.getRingReader(),
                    amzaService.getRingWriter(), amzaService));

    new AmzaUIInitializer().initialize(clusterName, ringHost, amzaService, clientProvider, aquariumStats,
            amzaStats, timestampProvider, idPacker, amzaInterner, new AmzaUIInitializer.InjectionCallback() {
                @Override
                public void addEndpoint(Class clazz) {
                    System.out.println("Adding endpoint=" + clazz);
                    jerseyEndpoints.addEndpoint(clazz);
                }

                @Override
                public void addInjectable(Class clazz, Object instance) {
                    System.out.println("Injecting " + clazz + " " + instance);
                    jerseyEndpoints.addInjectable(clazz, instance);
                }

                @Override
                public void addSessionAuth(String... paths) throws Exception {
                    System.out.println("Ignoring session auth request for paths: " + Arrays.toString(paths));
                }
            });

    InitializeRestfulServer initializeRestfulServer = new InitializeRestfulServer(false, port, "AmzaNode",
            false, null, null, null, 128, 10000);
    initializeRestfulServer.addClasspathResource("/resources");
    initializeRestfulServer.addContextHandler("/", jerseyEndpoints);
    RestfulServer restfulServer = initializeRestfulServer.build();
    restfulServer.start();

    System.out.println("-----------------------------------------------------------------------");
    System.out.println("|      Jetty Service Online");
    System.out.println("-----------------------------------------------------------------------");

    amzaService.start(ringMember, ringHost);

    System.out.println("-----------------------------------------------------------------------");
    System.out.println("|      Amza Service Online");
    System.out.println("-----------------------------------------------------------------------");

    if (clusterName != null) {
        if (hostPortPeers != null) {
            System.out.println("-----------------------------------------------------------------------");
            System.out.println("|     Amza Service is in manual Discovery mode. Cluster Name:" + clusterName);
            String[] peers = hostPortPeers.split(",");
            for (String peer : peers) {
                String[] hostPort = peer.trim().split(":");
                if (hostPort.length != 2 && hostPort.length != 3) {
                    System.out.println("|     Malformed peer:" + peer
                            + " expected form: <host>:<port> or <logicalName>:<host>:<port>");
                } else {
                    String peerLogicalName = (hostPort.length == 2) ? hostPort[0] + ":" + hostPort[1]
                            : hostPort[0];
                    String peerHostname = (hostPort.length == 2) ? hostPort[0] : hostPort[1];
                    String peerPort = (hostPort.length == 2) ? hostPort[1] : hostPort[2];

                    RingMember peerRingMember = new RingMember(peerLogicalName);
                    RingHost peerRingHost = new RingHost("unknown", "unknown", peerHostname,
                            Integer.parseInt(peerPort));

                    System.out.println("|     Adding ringMember:" + peerRingMember + " on host:" + peerRingHost
                            + " to cluster: " + clusterName);
                    amzaService.getRingWriter().register(peerRingMember, peerRingHost, writerId, false);
                }
            }
            systemRingSize.set(1 + peers.length);
            System.out.println("-----------------------------------------------------------------------");
        } else {
            AmzaDiscovery amzaDiscovery = new AmzaDiscovery(amzaService.getRingReader(),
                    amzaService.getRingWriter(), clusterName, multicastGroup, multicastPort, systemRingSize);
            amzaDiscovery.start();
            System.out.println("-----------------------------------------------------------------------");
            System.out.println("|      Amza Service Discovery Online: Cluster Name:" + clusterName);
            System.out.println("-----------------------------------------------------------------------");
        }
    } else {
        System.out.println("-----------------------------------------------------------------------");
        System.out.println("|     Amza Service is in manual Discovery mode.  No cluster name was specified");
        System.out.println("-----------------------------------------------------------------------");
    }
}