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:com.networknt.client.oauth.OauthHelper.java

/**
 * Get a signed JWT token from token service to ensure that nobody can modify the payload when the token
 * is passed from service to service. Unlike the access JWT token, this token is ensure the data integrity
 * with signature.//w w  w  .  j  a v a2s. c o m
 *
 * @param signRequest SignRequest that is constructed from the client.yml sign section
 * @param envTag environment tag that is used for service lookup if serviceId is used.
 * @return Result that contains TokenResponse or error status when failed.
 */
public static Result<TokenResponse> getSignResult(SignRequest signRequest, String envTag) {
    final AtomicReference<Result<TokenResponse>> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        if (signRequest.getServerUrl() != null) {
            connection = client.connect(new URI(signRequest.getServerUrl()), Http2Client.WORKER,
                    Http2Client.SSL, Http2Client.BUFFER_POOL,
                    signRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                            : OptionMap.EMPTY)
                    .get();
        } else if (signRequest.getServiceId() != null) {
            Cluster cluster = SingletonServiceFactory.getBean(Cluster.class);
            String url = cluster.serviceToUrl("https", signRequest.getServiceId(), envTag, null);
            connection = client
                    .connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL,
                            signRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                                    : OptionMap.EMPTY)
                    .get();
        } else {
            // both server_url and serviceId are empty in the config.
            logger.error("Error: both server_url and serviceId are not configured in client.yml for "
                    + signRequest.getClass());
            throw new ClientException("both server_url and serviceId are not configured in client.yml for "
                    + signRequest.getClass());
        }
    } catch (Exception e) {
        logger.error("cannot establish connection:", e);
        return Failure.of(new Status(ESTABLISH_CONNECTION_ERROR,
                signRequest.getServerUrl() != null ? signRequest.getServerUrl() : signRequest.getServiceId()));
    }

    try {
        Map<String, Object> map = new HashMap<>();
        map.put("expires", signRequest.getExpires());
        map.put("payload", signRequest.getPayload());
        String requestBody = Config.getInstance().getMapper().writeValueAsString(map);
        connection.getIoThread().execute(() -> {
            final ClientRequest request = new ClientRequest().setMethod(Methods.POST)
                    .setPath(signRequest.getUri());
            request.getRequestHeaders().put(Headers.HOST, "localhost");
            request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
            request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
            request.getRequestHeaders().put(Headers.AUTHORIZATION,
                    getBasicAuthHeader(signRequest.getClientId(), signRequest.getClientSecret()));
            connection.sendRequest(request, new ClientCallback<ClientExchange>() {
                @Override
                public void completed(ClientExchange result) {
                    new StringWriteChannelListener(requestBody).setup(result.getRequestChannel());
                    result.setResponseListener(new ClientCallback<ClientExchange>() {
                        @Override
                        public void completed(ClientExchange result) {
                            new StringReadChannelListener(Http2Client.BUFFER_POOL) {

                                @Override
                                protected void stringDone(String string) {

                                    logger.debug("getToken response = " + string);
                                    reference.set(handleResponse(getContentTypeFromExchange(result), string));
                                    latch.countDown();
                                }

                                @Override
                                protected void error(IOException e) {
                                    logger.error("IOException:", e);
                                    reference.set(Failure.of(new Status(FAIL_TO_SEND_REQUEST)));
                                    latch.countDown();
                                }
                            }.setup(result.getResponseChannel());
                        }

                        @Override
                        public void failed(IOException e) {
                            logger.error("IOException:", e);
                            reference.set(Failure.of(new Status(FAIL_TO_SEND_REQUEST)));
                            latch.countDown();
                        }
                    });
                }

                @Override
                public void failed(IOException e) {
                    logger.error("IOException:", e);
                    reference.set(Failure.of(new Status(FAIL_TO_SEND_REQUEST)));
                    latch.countDown();
                }
            });
        });

        latch.await(signRequest.getTimeout(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        return Failure.of(new Status(FAIL_TO_SEND_REQUEST));
    } finally {
        IoUtils.safeClose(connection);
    }

    //if reference.get() is null at this point, mostly likely couldn't get token within latch.await() timeout.
    return reference.get() == null ? Failure.of(new Status(GET_TOKEN_TIMEOUT)) : reference.get();
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.Workstation.java

private Workstation(final WorkstationType type, final PersistenceStoreProvider persistenceProvider) {
    Check.notNull(type, "type"); //$NON-NLS-1$

    this.type = type;

    if (type == WorkstationType.CURRENT) {
        Check.notNull(persistenceProvider, "persistenceProvider"); //$NON-NLS-1$

        synchronized (cacheMutex) {
            // Detect if cache directory is available
            cacheDirectory = getCacheDirectory(persistenceProvider);

            cacheEnabled = cacheDirectory != null
                    ? ensureLocalPathIsUsable(cacheDirectory, InternalCacheLoader.FILE_NAME)
                    : false;//  w w w .j a v  a2 s. c  o  m

            workspaceCacheFile = cacheEnabled ? new File(cacheDirectory, InternalCacheLoader.FILE_NAME) : null;

            /*
             * Load the cache. After this, it will be reloaded by the Cache
             * property when the FSW sets the flag indicating the cache file
             * changed. Use the Cache property everywhere else. We are not
             * performing any merging on mappings, so we can safely ignore
             * the warnings
             */
            final AtomicReference<InternalWorkspaceConflictInfo[]> conflictingWorkspaces = new AtomicReference<InternalWorkspaceConflictInfo[]>();
            workspaceCache = InternalCacheLoader.loadConfig(null, cacheEnabled, conflictingWorkspaces,
                    cacheMutex, workspaceCacheFile);
            Check.isTrue(conflictingWorkspaces.get().length == 0, "conflictingWorkspaces.get().length == 0"); //$NON-NLS-1$
        }

        synchronized (configurationMutex) {
            // Detect if configuration directory is available
            configurationDirectory = getConfigurationDirectory(persistenceProvider);

            configurationEnabled = configurationDirectory != null
                    ? ensureLocalPathIsUsable(configurationDirectory, LocalItemExclusionCache.FILE_NAME)
                    : false;

            localItemExclusionCacheFile = configurationEnabled
                    ? new File(configurationDirectory, LocalItemExclusionCache.FILE_NAME)
                    : null;
        }
    } else {
        cacheDirectory = null;
        cacheEnabled = false;
        workspaceCacheFile = null;

        configurationDirectory = null;
        configurationEnabled = false;
        localItemExclusionCacheFile = null;
    }
}

From source file:org.dataconservancy.packaging.tool.integration.PackageGenerationTest.java

@Test
public void verifyRemediationTest() throws Exception {

    PackageState state = initializer.initialize(DCS_PROFILE);

    Set<URI> originalFileLocations = new HashSet<>();

    ipm2rdf.transformToNode(state.getPackageTree())
            .walk(node -> originalFileLocations.add(node.getFileInfo().getLocation()));

    // The package should contain two files:
    // - READMX//from  w  ww . j av  a 2  s.  com
    // - READM
    //
    // The file with the acute E will be remediated to a resource named 'READMX', which will collide with
    // an existing resource of the same name.

    // assert that our sample problem files are in the content to be packaged
    assertTrue(originalFileLocations.stream().anyMatch(uri -> uri.getPath().endsWith("READMX")));
    // 0x0301 is the UTF-16 encoding of the 'COMBINING ACUTE ACCENT' combining diacritic
    // 0x00c9 is the UTF-16 encoding of 'LATIN CAPITAL LETTER E WITH ACUTE'
    assertTrue(originalFileLocations.stream().anyMatch(uri -> (uri.getPath().endsWith("README" + '\u0301'))
            || (uri.getPath().endsWith("READM" + '\u00c9'))));

    OpenedPackage opened = packager.createPackage(state, folder.getRoot());

    AtomicBoolean foundIllegal = new AtomicBoolean(Boolean.FALSE);
    AtomicBoolean foundRemediated = new AtomicBoolean(Boolean.FALSE);
    AtomicReference<String> remediatedFilename = new AtomicReference<>();
    AtomicBoolean foundCollision = new AtomicBoolean(Boolean.FALSE);
    AtomicReference<String> collidingFilename = new AtomicReference<>();

    // Walk the generated package, and make sure that
    // 1. That a resource with illegal characters does not exist
    // 2. That a resource named 'READMX' does exist
    // 3. That a resource named after the SHA-1 hex of its identifier exists
    // 4. That those two resources originate from two different files in the original package content
    opened.getPackageTree().walk(node -> {
        if (node.getFileInfo() == null || !node.getFileInfo().isFile()) {
            return;
        }

        System.err.println(node.getFileInfo().getName());
        System.err.println("  " + node.getFileInfo().getLocation().toString());

        // this should not happen, because a file name with invalid characters should have
        // been remediated prior to being inserted into the package
        if (node.getFileInfo().getLocation().getPath().endsWith("README" + '\u0301')
                || node.getFileInfo().getLocation().getPath().endsWith("READM" + '\u00c9')) {
            foundIllegal.set(Boolean.TRUE);
        }

        if (node.getFileInfo().getLocation().getPath().endsWith(shaHex(node.getIdentifier().toString()))) {
            foundRemediated.set(Boolean.TRUE);
            remediatedFilename.set(node.getFileInfo().getName());
            // short circuit
            return;
        }

        if (node.getFileInfo().getName().equals("READMX") || node.getFileInfo().getName().equals("READM")) {
            foundCollision.set(Boolean.TRUE);
            collidingFilename.set(node.getFileInfo().getName());
        }
    });

    assertFalse(foundIllegal.get());
    assertTrue(foundCollision.get());
    assertTrue(foundRemediated.get());

    assertNotNull(remediatedFilename.get());
    assertNotNull(collidingFilename.get());
    assertNotEquals(remediatedFilename.get(), collidingFilename.get());

}

From source file:com.collaborne.jsonschema.generator.pojo.PojoClassGenerator.java

@Override
public void generateType(PojoCodeGenerationContext context, SchemaTree schema, JavaWriter writer)
        throws IOException, CodeGenerationException {
    Mapping mapping = context.getMapping();

    // Process the properties into PropertyGenerators
    List<PojoPropertyGenerator> propertyGenerators = new ArrayList<>();

    visitProperties(schema, new PropertyVisitor<CodeGenerationException>() {
        @Override//  w w  w .j a  v  a 2s .c  om
        public void visitProperty(String propertyName, URI type, SchemaTree schema)
                throws CodeGenerationException {
            String defaultValue;
            JsonNode defaultValueNode = schema.getNode().path("default");
            if (defaultValueNode.isMissingNode() || defaultValueNode.isNull()) {
                defaultValue = null;
            } else if (defaultValueNode.isTextual()) {
                defaultValue = '"' + defaultValueNode.textValue() + '"';
            } else {
                defaultValue = defaultValueNode.asText();
            }

            PojoPropertyGenerator propertyGenerator = context.createPropertyGenerator(type, propertyName,
                    defaultValue);
            propertyGenerators.add(propertyGenerator);
        }

        @Override
        public void visitProperty(String propertyName, URI type) throws CodeGenerationException {
            propertyGenerators.add(context.createPropertyGenerator(type, propertyName, null));
        }
    });

    for (PojoPropertyGenerator propertyGenerator : propertyGenerators) {
        propertyGenerator.generateImports(writer);
    }

    // check whether we need to work with additionalProperties:
    // - schema can say "yes", or "yes-with-this-type"
    // - mapping can say "yes", or "ignore"
    // Ultimately if we have to handle them we let the generated class extend AbstractMap<String, TYPE>,
    // where TYPE is either the one from the schema, or Object (if the schema didn't specify anything.
    // XXX: "Object" should probably be "whatever our factory/reader would produce"
    // XXX: Instead an AbstractMap, should we have a standard class in our support library?
    ClassName additionalPropertiesValueClassName = null;
    ClassName extendedClass = mapping.getExtends();
    JsonNode additionalPropertiesNode = schema.getNode().path("additionalProperties");
    if (!additionalPropertiesNode.isMissingNode() && !additionalPropertiesNode.isNull()
            && !mapping.isIgnoreAdditionalProperties()) {
        if (additionalPropertiesNode.isBoolean()) {
            if (additionalPropertiesNode.booleanValue()) {
                additionalPropertiesValueClassName = ClassName.create(Object.class);
            }
        } else {
            assert additionalPropertiesNode.isContainerNode();

            AtomicReference<ClassName> ref = new AtomicReference<>();
            SchemaTree additionalPropertiesSchema = schema.append(JsonPointer.of("additionalProperties"));
            URI additionalPropertiesUri = additionalPropertiesSchema.getLoadingRef().toURI()
                    .resolve("#" + additionalPropertiesSchema.getPointer().toString());
            visitSchema(additionalPropertiesUri, additionalPropertiesSchema,
                    new SchemaVisitor<CodeGenerationException>() {
                        @Override
                        public void visitSchema(URI type, SchemaTree schema) throws CodeGenerationException {
                            visitSchema(type);
                        }

                        @Override
                        public void visitSchema(URI type) throws CodeGenerationException {
                            ref.set(context.getGenerator().generate(type));
                        }
                    });
            additionalPropertiesValueClassName = ref.get();
        }

        if (additionalPropertiesValueClassName != null) {
            if (extendedClass != null) {
                // FIXME: handle this by using an interface instead
                throw new CodeGenerationException(context.getType(),
                        "additionalProperties is incompatible with 'extends'");
            }
            extendedClass = ClassName.create(AbstractMap.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(extendedClass);
            ClassName mapClass = ClassName.create(Map.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(mapClass);
            ClassName hashMapClass = ClassName.create(HashMap.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(hashMapClass);
            ClassName mapEntryClass = ClassName.create(Map.Entry.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(mapEntryClass);
            ClassName setMapEntryClass = ClassName.create(Set.class, mapEntryClass);
            writer.writeImport(setMapEntryClass);
        }
    }

    if (mapping.getImplements() != null) {
        for (ClassName implementedInterface : mapping.getImplements()) {
            writer.writeImport(implementedInterface);
        }
    }

    writeSchemaDocumentation(schema, writer);
    writer.writeClassStart(mapping.getGeneratedClassName(), extendedClass, mapping.getImplements(), Kind.CLASS,
            Visibility.PUBLIC, mapping.getModifiers());
    try {
        // Write properties
        for (PojoPropertyGenerator propertyGenerator : propertyGenerators) {
            propertyGenerator.generateFields(writer);
        }
        if (additionalPropertiesValueClassName != null) {
            ClassName mapClass = ClassName.create(Map.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            ClassName hashMapClass = ClassName.create(HashMap.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeField(Visibility.PRIVATE, mapClass, "additionalPropertiesMap", () -> {
                writer.write(" = new ");
                // XXX: If code generation would know about java 7/8, we could use diamond here
                writer.writeClassName(hashMapClass);
                writer.write("()");
            });
        }

        // Write accessors
        // TODO: style to create them: pairs, or ordered?
        // TODO: whether to generate setters in the first place, or just getters
        for (PojoPropertyGenerator propertyGenerator : propertyGenerators) {
            propertyGenerator.generateGetter(writer);
            propertyGenerator.generateSetter(writer);
        }

        if (additionalPropertiesValueClassName != null) {
            ClassName mapEntryClass = ClassName.create(Map.Entry.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            ClassName setMapEntryClass = ClassName.create(Set.class, mapEntryClass);
            writer.writeAnnotation(ClassName.create(Override.class));
            writer.writeMethodBodyStart(Visibility.PUBLIC, setMapEntryClass, "entrySet");
            writer.writeCode("return additionalPropertiesMap.entrySet();");
            writer.writeMethodBodyEnd();
        }
    } finally {
        writer.writeClassEnd();
    }
}

From source file:org.hawkular.listener.cache.InventoryHelperTest.java

@Test
public void shouldListEmptyMetricTypesWhenChunksAreIncomplete() {
    // Data & mocks
    Metric<String> m1 = new Metric<>("inventory.123.mt.m1", null, 7, MetricType.STRING, null);
    long currentTime = System.currentTimeMillis();
    when(metricsService.findMetricsWithFilters(anyString(), anyObject(), anyString()))
            .thenAnswer(invocationOnMock -> Observable.just(m1));
    DataPoint<String> tempDataPoint = buildMetricTypeDatapoint(currentTime - 500, "metricType1",
            "metric type 1");
    DataPoint<String> dataPoint = new DataPoint<>(tempDataPoint.getTimestamp(), tempDataPoint.getValue(),
            ImmutableMap.<String, String>builder().put("chunks", "3").put("size", "1000").build());
    when(metricsService.findStringData(m1.getMetricId(), 0, currentTime, false, 0, Order.DESC))
            .thenReturn(Observable.just(dataPoint));

    // Test & assertions
    AtomicReference<Throwable> refException = new AtomicReference<>();
    InventoryHelper.listMetricTypes(metricsService, "tenant", "feed", currentTime).toList().subscribe(a -> {
    }, refException::set);//w  w w  .  jav a2  s . c  o  m
    Assert.assertEquals(InvalidInventoryChunksException.class, refException.get().getCause().getClass());
    Assert.assertTrue("Unexpected message: " + refException.get().getCause().getMessage(),
            refException.get().getCause().getMessage()
                    .contains("Inventory sanity check failure: 3 chunks expected, only 1 are available"));
}

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

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

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

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

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

@Test
public void testInvalidBasicHeader() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from  ww  w .  ja v a2 s . c  om
        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,
                "Bearer " + encodeCredentials("user1", "user1pass"));
        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("ERR10046", status.getCode());
    }
}

From source file:com.example.app.profile.ui.company.CompanyValueEditor.java

@Override
public void init() {
    VTCropPictureEditorConfig webLogoConfig = _companyConfig.companyWebLogoConfig();
    _webLogoEditor = new VTCropPictureEditor(webLogoConfig);
    _webLogoEditor.addClassName("company-web-logo");
    _webLogoEditor.setDefaultResource(_appUtil.getDefaultResourceImage());

    VTCropPictureEditorConfig emailLogoConfig = _companyConfig.companyEmailLogoConfig();
    _emailLogoEditor = new VTCropPictureEditor(emailLogoConfig);
    _emailLogoEditor.addClassName("company-web-logo");
    _emailLogoEditor.setDefaultResource(_appUtil.getDefaultResourceImage());

    super.init();

    Label webLogoInstructions = new Label(createText(INSTRUCTIONS_PICTURE_EDITOR_FMT(),
            webLogoConfig.getCropWidth(), webLogoConfig.getCropHeight()));
    webLogoInstructions.addClassName(CSS_INSTRUCTIONS);
    webLogoInstructions.withHTMLElement(HTMLElement.div);

    Label emailLogoInstructions = new Label(createText(INSTRUCTIONS_PICTURE_EDITOR_FMT(),
            emailLogoConfig.getCropWidth(), emailLogoConfig.getCropHeight()));
    emailLogoInstructions.addClassName(CSS_INSTRUCTIONS);
    emailLogoInstructions.withHTMLElement(HTMLElement.div);

    add(of("logos", of("prop", LABEL_WEB_LOGO(), _webLogoEditor, webLogoInstructions),
            of("prop", LABEL_EMAIL_LOGO(), _emailLogoEditor, emailLogoInstructions)));
    CommonEditorFields.addNameEditor(this);
    addEditorForProperty(() -> {//from w w w.j  a  va 2 s  .  com
        final CompositeValueEditor<Location> editor = new CompositeValueEditor<>(Location.class);

        editor.addEditorForProperty(() -> {
            AddressValueEditorConfig cfg = new AddressValueEditorConfig();
            return new AddressValueEditor(cfg);
        }, Location.ADDRESS_PROP);

        //            editor.addEditorForProperty(() -> {
        //                EmailAddressValueEditorConfig cfg = new EmailAddressValueEditorConfig();
        //                return new EmailAddressValueEditor(cfg);
        //            }, Location.EMAIL_ADDRESS_PROP);

        editor.addEditorForProperty(() -> {
            PhoneNumberValueEditorConfig cfg = new PhoneNumberValueEditorConfig();
            return new PhoneNumberValueEditor(cfg);
        }, Location.PHONE_NUMBER_PROP);

        return editor;
    }, Company.PRIMARY_LOCATION_PROP);

    addEditorForProperty(() -> {
        final URLEditor editor = new URLEditor(LABEL_WEBSITE(), null);
        editor.addClassName("website");
        return editor;
    }, ce -> stringToURL(ce.getWebsiteLink(), null), (ce, url) -> ce.setWebsiteLink(urlToString(url)));

    if (_editMode == AbstractCompanyPropertyEditor.EditMode.StandardCompany) {
        final String superdomainName = _appUtil.getSite().getDefaultHostname().getName();
        final AtomicReference<TextEditor> domainNameEditor = new AtomicReference<>();
        final AtomicReference<Container> inputInstructionsRef = new AtomicReference<>();
        final AtomicReference<Container> customDomainInstructionsRef = new AtomicReference<>();
        final AtomicReference<Label> superdomainLabelRef = new AtomicReference<>();
        Function<String, String> convertDomainUIValue = val -> {
            if (!StringFactory.isEmptyString(val)) {
                String converted = val;
                if (converted.endsWith('.' + superdomainName))
                    converted = converted.replace('.' + superdomainName, "");
                converted = HOSTNAME_VALIDITY_PATTERN1.matcher(converted).replaceAll("-");
                converted = HOSTNAME_VALIDITY_PATTERN2.matcher(converted).replaceAll("").toLowerCase();
                return converted;
            }
            return val;
        };
        addEditorForProperty(() -> {
            final TextEditor editor = new TextEditor(LABEL_SUB_DOMAIN(), null);
            final Container inputInstructions = _uiHelper
                    .createInputInstructions(INSTRUCTIONS_SUB_DOMAIN(_terms.company()));
            final Container customDomainInstructions = _uiHelper
                    .createInputInstructions(INSTRUCTIONS_CUSTOM_DOMAIN(_terms.company()));
            final Label superdomainNameLabel = new Label(createText('.' + superdomainName), span,
                    "super-domain-name");
            editor.moveToTop(customDomainInstructions);
            editor.moveToTop(inputInstructions);
            editor.moveToTop(editor.getLabel());
            editor.add(editor.getValueComponent());
            editor.add(superdomainNameLabel);
            editor.getValueComponent().addPropertyChangeListener(Field.PROP_TEXT, evt -> {
                if (editor.isEditable()) {
                    String uiValue = editor.getValueComponent().getText();
                    editor.getValueComponent().setText(convertDomainUIValue.apply(uiValue));
                }
            });

            editor.setRequiredValueValidator();
            domainNameEditor.set(editor);
            inputInstructionsRef.set(inputInstructions);
            customDomainInstructionsRef.set(customDomainInstructions);
            superdomainLabelRef.set(superdomainNameLabel);
            return editor;
        }, ce -> {
            final TextEditor editor = domainNameEditor.get();
            String cehostname = ce.getHostname().getName();
            if (cehostname == null)
                cehostname = "";
            domainNameEditor.get().setEditable(
                    !(!StringFactory.isEmptyString(cehostname) && !cehostname.endsWith('.' + superdomainName)));
            if (editor.isEditable()) {
                cehostname = convertDomainUIValue.apply(cehostname.replace('.' + superdomainName, ""));
            }
            inputInstructionsRef.get().setVisible(editor.isEditable());
            superdomainLabelRef.get().setVisible(editor.isEditable());
            customDomainInstructionsRef.get().setVisible(!editor.isEditable());
            return cehostname;
        }, (ce, value) -> {
            if (domainNameEditor.get().isEditable())
                ce.getHostname().setName(String.join(".", value, superdomainName));
            else
                ce.getHostname().setName(ce.getHostname().getName());
        });
    }

    addEditorForProperty(() -> {
        final URLEditor editor = new URLEditor(LABEL_LINKEDIN(), null);
        editor.addClassName("linkedin");
        return editor;
    }, company -> stringToURL(company.getLinkedInLink(), null),
            (company, url) -> company.setLinkedInLink(urlToString(url)));

    addEditorForProperty(() -> {
        final URLEditor editor = new URLEditor(LABEL_TWITTER(), null);
        editor.addClassName("twitter");
        return editor;
    }, company -> stringToURL(company.getTwitterLink(), null),
            (company, url) -> company.setTwitterLink(urlToString(url)));

    addEditorForProperty(() -> {
        final URLEditor editor = new URLEditor(LABEL_FACEBOOK(), null);
        editor.addClassName("facebook");
        return editor;
    }, company -> stringToURL(company.getFacebookLink(), null),
            (company, url) -> company.setFacebookLink(urlToString(url)));
}

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

@Test
public void testValidPost() throws Exception {
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from w ww. ja  v  a  2  s .  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);
    }

    try {
        String post = "{\"id\":0,\"category\":{\"id\":0,\"name\":\"string\"},\"name\":\"doggie\",\"photoUrls\":[\"string\"],\"tags\":[{\"id\":0,\"name\":\"string\"}],\"status\":\"available\"}";
        connection.getIoThread().execute(new Runnable() {
            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/v1/pets");
                request.getRequestHeaders().put(Headers.HOST, "localhost");
                request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
                request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                connection.sendRequest(request, client.createClientCallback(reference, latch, post));
            }
        });

        latch.await(10, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", 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("addPet", body);
    }
}