Example usage for org.apache.commons.lang RandomStringUtils randomAlphabetic

List of usage examples for org.apache.commons.lang RandomStringUtils randomAlphabetic

Introduction

In this page you can find the example usage for org.apache.commons.lang RandomStringUtils randomAlphabetic.

Prototype

public static String randomAlphabetic(int count) 

Source Link

Document

Creates a random string whose length is the number of characters specified.

Characters will be chosen from the set of alphabetic characters.

Usage

From source file:com.zimbra.cs.mime.MimeTest.java

@Test
public void strayBoundaryInEpilogue() throws Exception {
    String content = baseMpMixedContent + "\r\n";
    StringBuilder sb = new StringBuilder(content);
    sb.append("------------1111971890AC3BB91\r\n").append("Content-Type: text/plain; charset=windows-1250\r\n")
            .append("Content-Transfer-Encoding: quoted-printable\r\n\r\n");
    String plainText = RandomStringUtils.randomAlphabetic(10);
    sb.append(plainText).append("\r\n");
    sb.append("------------1111971890AC3BB91--").append("\r\n");

    //this is the point of this test; if MIME has a stray boundary it used to cause NPE
    sb.append("\r\n").append("--bogusBoundary").append("\r\n").append("\r\n");

    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession(),
            new SharedByteArrayInputStream(sb.toString().getBytes()));
    List<MPartInfo> parts = Mime.getParts(mm);

    Assert.assertEquals(2, parts.size());

    MPartInfo body = Mime.getTextBody(parts, false);
    Assert.assertNotNull(body);//from w  ww . j  av a2s .c  o  m

    Assert.assertTrue(TestUtil.bytesEqual(plainText.getBytes(), body.getMimePart().getInputStream()));
}

From source file:com.hihframework.core.utils.StringHelpers.java

/**
 * ?./*from  w w w.  j a v a2 s  . co  m*/
 *
 * @return the string
 */
public static String createRandomString() {
    String random = null;
    // ?
    random = RandomStringUtils.randomAlphabetic(10);
    // ??? long
    random += DateUtils.getNowDateTimeToLong();
    return random;
}

From source file:com.google.cloud.bigtable.hbase.TestFilters.java

@Test
public void testRowFilterBinaryComparator_Equals() throws Exception {
    // Initialize data
    Table table = getTable();//from  w  w w. j  av  a  2 s. com
    String rowKeyPrefix = "testRowFilter-" + RandomStringUtils.randomAlphabetic(10);
    byte[] rowKey1 = Bytes.toBytes(rowKeyPrefix + "A");
    byte[] rowKey2 = Bytes.toBytes(rowKeyPrefix + "AA");
    byte[] rowKey3 = Bytes.toBytes(rowKeyPrefix + "B");
    byte[] rowKey4 = Bytes.toBytes(rowKeyPrefix + "BB");
    byte[] qual = Bytes.toBytes("testqual");
    byte[] value = Bytes.toBytes("testvalue");
    for (byte[] rowKey : new byte[][] { rowKey1, rowKey2, rowKey3, rowKey4 }) {
        Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qual, value);
        table.put(put);
    }

    // Test BinaryComparator - EQUAL
    ByteArrayComparable rowKey2Comparable = new BinaryComparator(rowKey2);
    Filter filter = new RowFilter(CompareFilter.CompareOp.EQUAL, rowKey2Comparable);
    Result[] results = scanWithFilter(table, rowKey1, rowKey4, qual, filter);
    Assert.assertEquals("# results", 1, results.length);
    Assert.assertArrayEquals(rowKey2, results[0].getRow());
}

From source file:net.shopxx.controller.shop.RegisterController.java

/**
 * ??/*w w  w.  j  a  v  a  2  s .  c om*/
 */
@RequestMapping(value = "/submit_email", method = RequestMethod.POST)
public @ResponseBody Message submitEmail(String captchaId, String captcha, String email, Long userId,
        String registStep, String userImg, String trueName, String idCardImg, HttpServletRequest request,
        HttpServletResponse response, HttpSession session, ModelMap model) {
    Setting setting = SettingUtils.get();
    Member member = new Member();
    if (userId != null) {// id?
        member = memberService.find(userId);
        if ("2".equals(registStep)) {// 
            member.setUserImg(userImg);
            List<MemberAttribute> memberAttributes = memberAttributeService.findList();
            for (MemberAttribute memberAttribute : memberAttributes) {
                String parameter = request.getParameter("memberAttribute_" + memberAttribute.getId());
                if (memberAttribute.getType() == Type.name || memberAttribute.getType() == Type.address
                        || memberAttribute.getType() == Type.zipCode || memberAttribute.getType() == Type.phone
                        || memberAttribute.getType() == Type.mobile || memberAttribute.getType() == Type.text
                        || memberAttribute.getType() == Type.select) {
                    if (memberAttribute.getIsRequired() && StringUtils.isEmpty(parameter)) {
                        return Message.error("shop.common.invalid");
                    }
                    member.setAttributeValue(memberAttribute, parameter);
                } else if (memberAttribute.getType() == Type.gender) {
                    Gender gender = StringUtils.isNotEmpty(parameter) ? Gender.valueOf(parameter) : null;
                    if (memberAttribute.getIsRequired() && gender == null) {
                        return Message.error("shop.common.invalid");
                    }
                    member.setGender(gender);
                } else if (memberAttribute.getType() == Type.birth) {
                    try {
                        Date birth = StringUtils.isNotEmpty(parameter)
                                ? DateUtils.parseDate(parameter, CommonAttributes.DATE_PATTERNS)
                                : null;
                        if (memberAttribute.getIsRequired() && birth == null) {
                            return Message.error("shop.common.invalid");
                        }
                        member.setBirth(birth);
                    } catch (ParseException e) {
                        return Message.error("shop.common.invalid");
                    }
                } else if (memberAttribute.getType() == Type.area) {
                    Area area = StringUtils.isNotEmpty(parameter) ? areaService.find(Long.valueOf(parameter))
                            : null;
                    if (area != null) {
                        member.setArea(area);
                    } else if (memberAttribute.getIsRequired()) {
                        return Message.error("shop.common.invalid");
                    }
                } else if (memberAttribute.getType() == Type.checkbox) {
                    String[] parameterValues = request
                            .getParameterValues("memberAttribute_" + memberAttribute.getId());
                    List<String> options = parameterValues != null ? Arrays.asList(parameterValues) : null;
                    if (memberAttribute.getIsRequired() && (options == null || options.isEmpty())) {
                        return Message.error("shop.common.invalid");
                    }
                    member.setAttributeValue(memberAttribute, options);
                }
            }
            net.shopxx.Template activateAccountMailTemplate = templateService.get("activateAccount");
            SafeKey safeKey = new SafeKey();
            safeKey.setValue(
                    UUID.randomUUID().toString() + DigestUtils.md5Hex(RandomStringUtils.randomAlphabetic(30)));
            safeKey.setExpire(setting.getSafeKeyExpiryTime() != 0
                    ? DateUtils.addMinutes(new Date(), setting.getSafeKeyExpiryTime())
                    : null);
            member.setSafeKey(safeKey);
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("member", member);
            param.put("domain", setting.getSiteUrl());// http

            mailService.send(member.getEmail(), "???",
                    activateAccountMailTemplate.getTemplatePath(), param);

        } else if ("3".equals(registStep)) {
            member.setTrueName(trueName);
            member.setIdCardImg(idCardImg);
        }

        member.setRegistStep(registStep);// ??
        memberService.update(member);
    } else {// id
        String password = rsaService.decryptParameter("enPassword", request);
        rsaService.removePrivateKey(request);

        if (!captchaService.isValid(CaptchaType.memberRegister, captchaId, captcha)) {
            return Message.error("shop.captcha.invalid");
        }

        if (!setting.getIsRegisterEnabled()) {
            return Message.error("shop.register.disabled");
        }
        if (!isValid(Member.class, "password", password, Save.class)) {
            return Message.error("shop.common.invalid");
        }
        if (password.length() < setting.getPasswordMinLength()
                || password.length() > setting.getPasswordMaxLength()) {
            return Message.error("shop.common.invalid");
        }
        member.setPassword(DigestUtils.md5Hex(password));
        member.setPoint(setting.getRegisterPoint());
        member.setAmount(new BigDecimal(0));
        member.setBalance(new BigDecimal(0));
        member.setIsEnabled(true);
        member.setIsLocked(false);
        member.setLoginFailureCount(0);
        member.setLockedDate(null);
        member.setRegisterIp(request.getRemoteAddr());
        member.setLoginIp(request.getRemoteAddr());
        member.setLoginDate(new Date());
        member.setSafeKey(null);
        member.setMemberRank(memberRankService.findDefault());
        member.setFavoriteProducts(null);

        member.setUsername(email);// ??
        member.setEmail(email);// 
        member.setRegistStep("1");// ??

        memberService.save(member);
    }
    Cart cart = cartService.getCurrent();
    if (cart != null && cart.getMember() == null) {
        cartService.merge(member, cart);
        WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
        WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
    }

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }
    member = memberService.find(member.getId());
    // Message message = new Message();
    // message.setType(Message.Type.success);
    // message.setContent("????");
    // message.setScript(member.getId().toString());
    request.getSession().setAttribute("currentMemberSession", member);
    return Message.success("????");
}

From source file:com.google.cloud.bigtable.hbase.TestFilters.java

/**
 * Requirement 9.5// w ww . jav a2 s .c  o m
 *
 * Test the BinaryPrefixComparator against EQUAL, GREATER, GREATER_OR_EQUAL, LESS, LESS_OR_EQUAL,
 * NOT_EQUAL, and NO_OP.  BinaryPrefixComparator compares against a specified byte array, up to
 * the length of this byte array.
 */
@Test
@Category(KnownGap.class)
public void testRowFilterBinaryPrefixComparator() throws Exception {
    // Initialize data
    Table table = getTable();
    String rowKeyPrefix = "testRowFilter-" + RandomStringUtils.randomAlphabetic(10);
    byte[] rowA = Bytes.toBytes(rowKeyPrefix + "A");
    byte[] rowAA = Bytes.toBytes(rowKeyPrefix + "AA");
    byte[] rowB = Bytes.toBytes(rowKeyPrefix + "B");
    byte[] rowBB = Bytes.toBytes(rowKeyPrefix + "BB");
    byte[] rowC = Bytes.toBytes(rowKeyPrefix + "C");
    byte[] rowCC = Bytes.toBytes(rowKeyPrefix + "CC");
    byte[] rowD = Bytes.toBytes(rowKeyPrefix + "D");
    byte[] qual = Bytes.toBytes("testqual");
    byte[] value = Bytes.toBytes("testvalue");
    for (byte[] rowKey : new byte[][] { rowA, rowAA, rowB, rowBB, rowC, rowCC, rowD }) {
        Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qual, value);
        table.put(put);
    }

    // Test BinaryPrefixComparator - EQUAL
    ByteArrayComparable rowBComparable = new BinaryPrefixComparator(rowB);
    Filter filter = new RowFilter(CompareFilter.CompareOp.EQUAL, rowBComparable);
    Result[] results = scanWithFilter(table, rowA, rowD, qual, filter);
    Assert.assertEquals("# results", 2, results.length);
    Assert.assertArrayEquals(rowB, results[0].getRow());
    Assert.assertArrayEquals(rowBB, results[1].getRow());

    // Test BinaryPrefixComparator - GREATER
    filter = new RowFilter(CompareFilter.CompareOp.GREATER, rowBComparable);
    results = scanWithFilter(table, rowA, rowD, qual, filter);
    Assert.assertEquals("# results", 2, results.length);
    Assert.assertArrayEquals(rowC, results[0].getRow());
    Assert.assertArrayEquals(rowCC, results[1].getRow());

    // Test BinaryPrefixComparator - GREATER_OR_EQUAL
    filter = new RowFilter(CompareFilter.CompareOp.GREATER_OR_EQUAL, rowBComparable);
    results = scanWithFilter(table, rowA, rowD, qual, filter);
    Assert.assertEquals("# results", 4, results.length);
    Assert.assertArrayEquals(rowB, results[0].getRow());
    Assert.assertArrayEquals(rowBB, results[1].getRow());
    Assert.assertArrayEquals(rowC, results[2].getRow());
    Assert.assertArrayEquals(rowCC, results[3].getRow());

    // Test BinaryPrefixComparator - LESS
    filter = new RowFilter(CompareFilter.CompareOp.LESS, rowBComparable);
    results = scanWithFilter(table, rowA, rowD, qual, filter);
    Assert.assertEquals("# results", 2, results.length);
    Assert.assertArrayEquals(rowA, results[0].getRow());
    Assert.assertArrayEquals(rowAA, results[1].getRow());

    // Test BinaryPrefixComparator - LESS_OR_EQUAL
    filter = new RowFilter(CompareFilter.CompareOp.LESS_OR_EQUAL, rowBComparable);
    results = scanWithFilter(table, rowA, rowD, qual, filter);
    Assert.assertEquals("# results", 4, results.length);
    Assert.assertArrayEquals(rowA, results[0].getRow());
    Assert.assertArrayEquals(rowAA, results[1].getRow());
    Assert.assertArrayEquals(rowB, results[2].getRow());
    Assert.assertArrayEquals(rowBB, results[3].getRow());

    // Test BinaryPrefixComparator - NOT_EQUAL
    filter = new RowFilter(CompareFilter.CompareOp.NOT_EQUAL, rowBComparable);
    results = scanWithFilter(table, rowA, rowD, qual, filter);
    Assert.assertEquals("# results", 4, results.length);
    Assert.assertArrayEquals(rowA, results[0].getRow());
    Assert.assertArrayEquals(rowAA, results[1].getRow());
    Assert.assertArrayEquals(rowC, results[2].getRow());
    Assert.assertArrayEquals(rowCC, results[3].getRow());

    // Test BinaryPrefixComparator - NO_OP
    filter = new RowFilter(CompareFilter.CompareOp.NO_OP, rowBComparable);
    results = scanWithFilter(table, rowA, rowD, qual, filter);
    Assert.assertEquals("# results", 0, results.length);

    table.close();
}

From source file:com.frequentis.maritime.mcsr.web.rest.InstanceResourceIntTest.java

@Test
@Transactional/*  w w w.  ja  v a2s.c om*/
public void updateInstance() throws Exception {
    // Initialize the database
    instanceService.save(instance);

    int databaseSizeBeforeUpdate = instanceRepository.findAll().size();

    // Update the instance
    Instance updatedInstance = new Instance();
    updatedInstance.setId(instance.getId());
    updatedInstance.setGeometryContentType(UPDATED_GEOMETRY_CONTENT_TYPE);
    updatedInstance.setOrganizationId(UPDATED_ORGANIZATION_ID);
    updatedInstance.setEndpointType(UPDATED_ENDPOINT_TYPE);

    // Required by validation in controller
    updatedInstance.setName(DEFAULT_NAME);
    updatedInstance.setVersion(DEFAULT_VERSION);
    updatedInstance.setComment(DEFAULT_COMMENT);
    updatedInstance.setInstanceId(DEFAULT_INSTANCE_ID);
    updatedInstance.setKeywords(DEFAULT_KEYWORDS);
    updatedInstance.setStatus(DEFAULT_STATUS);
    updatedInstance.setUnlocode(DEFAULT_UNLOCODE);
    updatedInstance.setEndpointUri(DEFAULT_ENDPOINT_URI);

    Xml xml = new Xml();
    xml.setName(DEFAULT_NAME);
    xml.setComment(DEFAULT_COMMENT);
    xml.setContentContentType(MediaType.APPLICATION_XML_VALUE);

    XMLInstanceBuilder xmlBuilder = new XMLInstanceBuilder();
    InstanceXML x = xmlBuilder.getBuilderXml();
    x.setName(UPDATED_VERSION);
    x.setDescription(UPDATED_COMMENT);
    x.setURL(UPDATED_ENDPOINT_URI);
    x.setKeywords(UPDATED_KEYWORDS);
    x.setId(UPDATED_INSTANCE_ID);
    x.setStatus(Status.valueOf(UPDATED_STATUS));
    x.setServiceType(UPDATED_ENDPOINT_TYPE);
    x.setIMO(UPDATED_IMO);
    x.setVersion(UPDATED_VERSION);
    x.setMMSI(RandomStringUtils.randomAlphabetic(5));
    x.setRequiresAuthorization("false");

    VendorInfo producedBy = x.getProducedBy();
    producedBy.setContactInfo(RandomStringUtils.randomAlphabetic(15));
    producedBy.setName(UPDATED_NAME);
    producedBy.setId(RandomStringUtils.randomAlphabetic(15));
    producedBy.setOrganizationId(RandomStringUtils.randomAlphabetic(15));
    producedBy.setDescription(RandomStringUtils.randomAlphabetic(15));

    VendorInfo providedBy = x.getProvidedBy();
    providedBy.setContactInfo(RandomStringUtils.randomAlphabetic(15));
    providedBy.setName(RandomStringUtils.randomAlphabetic(15));
    providedBy.setId(RandomStringUtils.randomAlphabetic(15));
    providedBy.setOrganizationId(RandomStringUtils.randomAlphabetic(15));
    providedBy.setDescription(RandomStringUtils.randomAlphabetic(15));

    ServiceLevel offersServiceLevel = x.getOffersServiceLevel();
    offersServiceLevel.setName(RandomStringUtils.randomAlphabetic(15));
    offersServiceLevel.setAvailability(1);
    offersServiceLevel.setDescription(RandomStringUtils.randomAlphabetic(15));

    CoversAreaType conversAreas = x.getCoversAreas();
    // Requires plenty of heap (parsing JSON with unls)
    // conversAreas.setUnLoCode(DEFAULT_UNLOCODE);

    List<CoverageArea> coversArea = new ArrayList<>();
    CoverageArea ca = new CoverageArea();
    ca.setName("Bermuda Triangle");
    ca.setDescription("Loosely defined region in the western part of the North Atlantic Ocean.");
    ca.setGeometryAsWKT("POLYGON((-80.190 25.774, -66.118 18.466, -64.757 32.321, -80.190 25.774))");
    coversArea.add(ca);
    conversAreas.setCoversArea(coversArea);

    ServiceDesignReference implementsServiceDesign = x.getImplementsServiceDesign();
    implementsServiceDesign.setId("awdwad");
    implementsServiceDesign.setVersion("dwadwdwad");

    xml.setContent(xmlBuilder.buildXmlString());
    xmlService.save(xml);

    updatedInstance.setInstanceAsXml(xml);

    restInstanceMockMvc.perform(put("/api/instances").contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(updatedInstance))).andExpect(status().isOk());

    // Validate the Instance in the database
    List<Instance> instances = instanceRepository.findAll();
    assertThat(instances).hasSize(databaseSizeBeforeUpdate);
    Instance testInstance = instances.get(instances.size() - 1);
    assertThat(testInstance.getName()).isEqualTo(UPDATED_NAME);
    assertThat(testInstance.getVersion()).isEqualTo(UPDATED_VERSION);
    assertThat(testInstance.getComment()).isEqualTo(UPDATED_COMMENT);
    assertThat(testInstance.getGeometryContentType()).isEqualTo(UPDATED_GEOMETRY_CONTENT_TYPE);
    assertThat(testInstance.getInstanceId()).isEqualTo(UPDATED_INSTANCE_ID);
    assertThat(testInstance.getKeywords()).isEqualTo(UPDATED_KEYWORDS);
    assertThat(testInstance.getStatus()).isEqualTo(UPDATED_STATUS);
    assertThat(testInstance.getOrganizationId()).isEqualTo(UPDATED_ORGANIZATION_ID);
    //        assertThat(testInstance.getUnlocode()).isEqualTo(UPDATED_UNLOCODE);
    assertThat(testInstance.getEndpointUri()).isEqualTo(UPDATED_ENDPOINT_URI);
    assertThat(testInstance.getEndpointType()).isEqualTo(UPDATED_ENDPOINT_TYPE);

    // Validate the Instance in ElasticSearch
    Instance instanceEs = instanceSearchRepository.findById(testInstance.getId()).get();
    assertThat(instanceEs.getName()).isEqualTo(UPDATED_NAME);
    assertThat(instanceEs.getVersion()).isEqualTo(UPDATED_VERSION);
    assertThat(instanceEs.getComment()).isEqualTo(UPDATED_COMMENT);
    assertThat(instanceEs.getGeometryContentType()).isEqualTo(UPDATED_GEOMETRY_CONTENT_TYPE);
    assertThat(instanceEs.getInstanceId()).isEqualTo(UPDATED_INSTANCE_ID);
    assertThat(instanceEs.getKeywords()).isEqualTo(UPDATED_KEYWORDS);
    assertThat(instanceEs.getStatus()).isEqualTo(UPDATED_STATUS);
    assertThat(instanceEs.getOrganizationId()).isEqualTo(UPDATED_ORGANIZATION_ID);
    //        assertThat(instanceEs.getUnlocode()).isEqualTo(UPDATED_UNLOCODE);
    assertThat(instanceEs.getEndpointUri()).isEqualTo(UPDATED_ENDPOINT_URI);
    assertThat(instanceEs.getEndpointType()).isEqualTo(UPDATED_ENDPOINT_TYPE);
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithJsonWithHTTPSAndHTTP() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();

    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("https.enabled", "true");
    properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("https.hostname", "localhost");
    properties.put("https.selfSigned", "true");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {/*from   w w w .  j a va2  s  .c  om*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new X509HostnameVerifier() {
                    @Override
                    public void verify(String host, SSLSocket ssl) throws IOException {
                    }

                    @Override
                    public void verify(String host, X509Certificate cert) throws SSLException {
                    }

                    @Override
                    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                    }

                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory()).build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());

        RestTemplate httpClient = new RestTemplate(requestFactory);
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("stuff"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithProtobuf() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {//from  w  ww  .j a  v a2 s. c o  m
        context.refresh();

        final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class);

        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);

        error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/headerRequired"), null,
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithXml() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.enabled", "false");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {/*ww w.  j  a  v  a2s .com*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(XmlMessageSerDe.class);

        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithYaml() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.enabled", "false");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {/*  w  ww .  j a  v a  2  s  .  c o  m*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(YamlJacksonMessageSerDe.class);

        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}