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:io.termd.core.telnet.TelnetHandlerTest.java

@Test
public void testRejectEcho() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    EchoOptionHandler optionHandler = new EchoOptionHandler(false, false, false, false);
    testOptionValue(() -> new TelnetHandler() {
        @Override/*  w ww.  j ava  2s  .  c  o m*/
        protected void onOpen(TelnetConnection conn) {
            conn.writeWillOption(Option.ECHO);
        }

        @Override
        protected void onEcho(boolean echo) {
            serverValue.set(echo);
            testComplete();
        }
    }, optionHandler);
    assertEquals(false, serverValue.get());
    assertEquals(false, optionHandler.getAcceptRemote());
}

From source file:com.sysunite.nifi.StringSplit.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    //position 4//from w ww .  j ava  2 s  .  c  o  m

    FlowFile flowFile = session.get();

    if (flowFile == null) {
        return;
    }

    int totalDynamicRelations = this.getRelationships().size();

    System.out.println("rels= " + totalDynamicRelations);

    //-------reading
    final AtomicReference<String> flowFileContentStore = new AtomicReference<>();

    session.read(flowFile, new InputStreamCallback() {

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

            System.out.println("read");

            try {

                String flowFileContent = IOUtils.toString(inputStream);
                flowFileContentStore.set(flowFileContent);

            } catch (Exception e) {

            }

        }
    });

    //-------using en editing
    try {

        //get contents
        String flowFileContent = flowFileContentStore.get();

        //split contents by delimiter
        String regexForSplit = context.getProperty(SPLIT).getValue();
        String[] splittedFlowFileContents = flowFileContent.split(regexForSplit);

        //count splits
        int totalSplits = splittedFlowFileContents.length;

        System.out.println("split= " + totalSplits);

        //get list of dynamic props
        final Map<Relationship, PropertyValue> propMap = this.propertyMap;

        for (final Map.Entry<Relationship, PropertyValue> entry : propMap.entrySet()) {

            final PropertyValue value = entry.getValue();
            String oriValue = value.getValue();

            //use only splits not empty
            if (oriValue != null) {

                try {

                    int partFromSplittedFlowFileContents = Integer.parseInt(oriValue);

                    //parts only in range are allowed
                    if (partFromSplittedFlowFileContents < totalSplits) {

                        String splittedPart = splittedFlowFileContents[partFromSplittedFlowFileContents];

                        String relationName = entry.getKey().getName();

                        System.out.println("relationship (" + relationName + ") -> " + splittedPart);

                        //now we can tranfer splitted part to the relation

                        FlowFile fNew = session.clone(flowFile);
                        fNew = session.putAttribute(fNew, relationName, splittedPart);
                        session.transfer(fNew, entry.getKey());

                    }

                } catch (Exception e) {

                }

            }

        }

    } catch (Exception e) {

    }

    session.transfer(flowFile, ORIGINAL);

}

From source file:io.termd.core.telnet.TelnetHandlerTest.java

@Test
public void testAcceptSGA() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    SuppressGAOptionHandler optionHandler = new SuppressGAOptionHandler(false, false, false, true);
    testOptionValue(() -> new TelnetHandler() {
        @Override// w w  w.j a  v  a2 s  .c  om
        protected void onOpen(TelnetConnection conn) {
            conn.writeWillOption(Option.SGA);
        }

        @Override
        protected void onSGA(boolean sga) {
            serverValue.set(sga);
            testComplete();
        }
    }, optionHandler);
    assertEquals(true, serverValue.get());
    assertEquals(true, optionHandler.getAcceptRemote());
}

From source file:io.termd.core.telnet.TelnetHandlerTest.java

@Test
public void testRejectSGA() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    SuppressGAOptionHandler optionHandler = new SuppressGAOptionHandler(false, false, false, false);
    testOptionValue(() -> new TelnetHandler() {
        @Override//from w  ww  .  j  ava 2  s  . c om
        protected void onOpen(TelnetConnection conn) {
            conn.writeWillOption(Option.SGA);
        }

        @Override
        protected void onSGA(boolean sga) {
            serverValue.set(sga);
            testComplete();
        }
    }, optionHandler);
    assertEquals(false, serverValue.get());
    assertEquals(false, optionHandler.getAcceptRemote());
}

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  v a  2s  .c o  m
    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("-----------------------------------------------------------------------");
    }
}

From source file:org.elasticsearch.xpack.test.rest.XPackRestTestHelper.java

/**
 * Waits for the Machine Learning templates to be created
 * and check the version is up to date// ww w.j  av a 2 s.  c  o m
 */
public static void waitForMlTemplates(RestClient client) throws InterruptedException {
    AtomicReference<Version> masterNodeVersion = new AtomicReference<>();
    ESTestCase.awaitBusy(() -> {
        String response;
        try {
            response = EntityUtils.toString(client
                    .performRequest("GET", "/_cat/nodes", singletonMap("h", "master,version")).getEntity());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for (String line : response.split("\n")) {
            if (line.startsWith("*")) {
                masterNodeVersion.set(Version.fromString(line.substring(2).trim()));
                return true;
            }
        }
        return false;
    });

    final List<String> templateNames = Arrays.asList(AuditorField.NOTIFICATIONS_INDEX, MlMetaIndex.INDEX_NAME,
            AnomalyDetectorsIndex.jobStateIndexName(), AnomalyDetectorsIndex.jobResultsIndexPrefix());
    for (String template : templateNames) {
        ESTestCase.awaitBusy(() -> {
            Map<?, ?> response;
            try {
                String string = EntityUtils
                        .toString(client.performRequest("GET", "/_template/" + template).getEntity());
                response = XContentHelper.convertToMap(JsonXContent.jsonXContent, string, false);
            } catch (ResponseException e) {
                if (e.getResponse().getStatusLine().getStatusCode() == 404) {
                    return false;
                }
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Map<?, ?> templateDefinition = (Map<?, ?>) response.get(template);
            return Version.fromId((Integer) templateDefinition.get("version")).equals(masterNodeVersion.get());
        });
    }
}

From source file:io.soabase.web.filters.LanguageFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        AtomicReference<String> fixedQueryString = new AtomicReference<>();
        String queryStringCode = getFromQueryString(httpRequest.getQueryString(), fixedQueryString);
        String expectedLanguageCode = MoreObjects.firstNonNull(queryStringCode,
                getLanguageCode(null, getCookie(httpRequest)));
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        Optional<String> foundCookie = getCookie(httpRequest);
        if (!foundCookie.isPresent() || !foundCookie.get().equals(expectedLanguageCode)) {
            Cookie cookie = new Cookie(cookieName, expectedLanguageCode);
            httpResponse.addCookie(cookie);
        }//  w  w w .  j  av  a2s.c  om

        if (queryStringCode != null) {
            StringBuffer redirectUrl = httpRequest.getRequestURL();
            if (!fixedQueryString.get().isEmpty()) {
                redirectUrl.append("?").append(fixedQueryString.get());
            }
            ((HttpServletResponse) response).sendRedirect(redirectUrl.toString());
            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:net.technicpack.launchercore.install.InstalledPack.java

private boolean loadImage(AtomicReference<BufferedImage> image, String name, Resource resource) {
    File assets = new File(Utils.getAssetsDirectory(), "packs");
    File packs = new File(assets, getName());
    packs.mkdirs();//from   w w  w .j  av  a  2  s  .c  om
    File resourceFile = new File(packs, name);

    String url = "";
    String md5 = "";

    if (resource != null) {
        url = resource.getUrl();
        md5 = resource.getMd5();
    }

    boolean cached = loadCachedImage(image, resourceFile, url, md5);

    if (!cached) {
        downloadImage(image, resourceFile, url, md5);
    }

    if (image.get() == null) {
        return false;
    }

    return cached;
}

From source file:org.apache.beam.runners.apex.ApexRunner.java

@Override
public ApexRunnerResult run(final Pipeline pipeline) {
    pipeline.replaceAll(getOverrides());

    final ApexPipelineTranslator translator = new ApexPipelineTranslator(options);
    final AtomicReference<DAG> apexDAG = new AtomicReference<>();
    final AtomicReference<File> tempDir = new AtomicReference<>();

    StreamingApplication apexApp = (dag, conf) -> {
        apexDAG.set(dag);//from   w w  w.j a  v a 2s.  c o m
        dag.setAttribute(DAGContext.APPLICATION_NAME, options.getApplicationName());
        if (options.isEmbeddedExecution()) {
            // set unique path for application state to allow for parallel execution of unit tests
            // (the embedded cluster would set it to a fixed location under ./target)
            tempDir.set(Files.createTempDir());
            dag.setAttribute(DAGContext.APPLICATION_PATH, tempDir.get().toURI().toString());
        }
        translator.translate(pipeline, dag);
    };

    Properties configProperties = new Properties();
    try {
        if (options.getConfigFile() != null) {
            URI configURL = new URI(options.getConfigFile());
            if (CLASSPATH_SCHEME.equals(configURL.getScheme())) {
                InputStream is = this.getClass().getResourceAsStream(configURL.getPath());
                if (is != null) {
                    configProperties.load(is);
                    is.close();
                }
            } else {
                if (!configURL.isAbsolute()) {
                    // resolve as local file name
                    File f = new File(options.getConfigFile());
                    configURL = f.toURI();
                }
                try (InputStream is = configURL.toURL().openStream()) {
                    configProperties.load(is);
                }
            }
        }
    } catch (IOException | URISyntaxException ex) {
        throw new RuntimeException("Error loading properties", ex);
    }

    if (options.isEmbeddedExecution()) {
        EmbeddedAppLauncher<?> launcher = Launcher.getLauncher(LaunchMode.EMBEDDED);
        Attribute.AttributeMap launchAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
        launchAttributes.put(EmbeddedAppLauncher.RUN_ASYNC, true);
        if (options.isEmbeddedExecutionDebugMode()) {
            // turns off timeout checking for operator progress
            launchAttributes.put(EmbeddedAppLauncher.HEARTBEAT_MONITORING, false);
        }
        Configuration conf = new Configuration(false);
        ApexYarnLauncher.addProperties(conf, configProperties);
        try {
            if (translateOnly) {
                launcher.prepareDAG(apexApp, conf);
                return new ApexRunnerResult(launcher.getDAG(), null);
            }
            ApexRunner.ASSERTION_ERROR.set(null);
            AppHandle apexAppResult = launcher.launchApp(apexApp, conf, launchAttributes);
            return new ApexRunnerResult(apexDAG.get(), apexAppResult) {
                @Override
                protected void cleanupOnCancelOrFinish() {
                    if (tempDir.get() != null) {
                        FileUtils.deleteQuietly(tempDir.get());
                    }
                }
            };
        } catch (Exception e) {
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
        }
    } else {
        try {
            ApexYarnLauncher yarnLauncher = new ApexYarnLauncher();
            AppHandle apexAppResult = yarnLauncher.launchApp(apexApp, configProperties);
            return new ApexRunnerResult(apexDAG.get(), apexAppResult);
        } catch (IOException e) {
            throw new RuntimeException("Failed to launch the application on YARN.", e);
        }
    }
}

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testInvalidPassword() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from  w w  w . j a  va2  s  .  c  o  m*/
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION, "BASIC " + encodeCredentials("user2", "ppp"));
        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();
    Assert.assertEquals(401, statusCode);
    if (statusCode == 401) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10047", status.getCode());
    }
}