Search in sources :

Example 21 with Arrays

use of java.util.Arrays in project vert.x by eclipse.

the class Http2ServerTest method testRequestResponseLifecycle.

@Test
public void testRequestResponseLifecycle() throws Exception {
    waitFor(2);
    server.requestHandler(req -> {
        req.endHandler(v -> {
            assertIllegalStateException(() -> req.setExpectMultipart(false));
            assertIllegalStateException(() -> req.handler(buf -> {
            }));
            assertIllegalStateException(() -> req.uploadHandler(upload -> {
            }));
            assertIllegalStateException(() -> req.endHandler(v2 -> {
            }));
            complete();
        });
        HttpServerResponse resp = req.response();
        resp.setChunked(true).write(Buffer.buffer("whatever"));
        assertTrue(resp.headWritten());
        assertIllegalStateException(() -> resp.setChunked(false));
        assertIllegalStateException(() -> resp.setStatusCode(100));
        assertIllegalStateException(() -> resp.setStatusMessage("whatever"));
        assertIllegalStateException(() -> resp.putHeader("a", "b"));
        assertIllegalStateException(() -> resp.putHeader("a", (CharSequence) "b"));
        assertIllegalStateException(() -> resp.putHeader("a", (Iterable<String>) Arrays.asList("a", "b")));
        assertIllegalStateException(() -> resp.putHeader("a", (Arrays.<CharSequence>asList("a", "b"))));
        assertIllegalStateException(resp::writeContinue);
        resp.end();
        assertIllegalStateException(() -> resp.write("a"));
        assertIllegalStateException(() -> resp.write("a", "UTF-8"));
        assertIllegalStateException(() -> resp.write(Buffer.buffer("a")));
        assertIllegalStateException(resp::end);
        assertIllegalStateException(() -> resp.end("a"));
        assertIllegalStateException(() -> resp.end("a", "UTF-8"));
        assertIllegalStateException(() -> resp.end(Buffer.buffer("a")));
        assertIllegalStateException(() -> resp.sendFile("the-file.txt"));
        assertIllegalStateException(() -> resp.closeHandler(v -> {
        }));
        assertIllegalStateException(() -> resp.endHandler(v -> {
        }));
        assertIllegalStateException(() -> resp.drainHandler(v -> {
        }));
        assertIllegalStateException(() -> resp.exceptionHandler(err -> {
        }));
        assertIllegalStateException(resp::writeQueueFull);
        assertIllegalStateException(() -> resp.setWriteQueueMaxSize(100));
        assertIllegalStateException(() -> resp.putTrailer("a", "b"));
        assertIllegalStateException(() -> resp.putTrailer("a", (CharSequence) "b"));
        assertIllegalStateException(() -> resp.putTrailer("a", (Iterable<String>) Arrays.asList("a", "b")));
        assertIllegalStateException(() -> resp.putTrailer("a", (Arrays.<CharSequence>asList("a", "b"))));
        assertIllegalStateException(() -> resp.push(HttpMethod.GET, "/whatever", ar -> {
        }));
        complete();
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}
Also used : Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http1xOrH2CHandler(io.vertx.core.http.impl.Http1xOrH2CHandler) Context(io.vertx.core.Context) Utils(io.vertx.core.impl.Utils) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Trust(io.vertx.test.tls.Trust) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Http2Error(io.netty.handler.codec.http2.Http2Error) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) DetectFileDescriptorLeaks(io.vertx.test.core.DetectFileDescriptorLeaks) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) ChannelFuture(io.netty.channel.ChannelFuture) Test(org.junit.Test)

Example 22 with Arrays

use of java.util.Arrays in project vert.x by eclipse.

the class Http2ClientTest method testHeaders.

@Test
public void testHeaders() throws Exception {
    AtomicInteger reqCount = new AtomicInteger();
    server.requestHandler(req -> {
        assertEquals("https", req.scheme());
        assertEquals(HttpMethod.GET, req.method());
        assertEquals("/somepath", req.path());
        assertEquals(DEFAULT_HTTPS_HOST_AND_PORT, req.host());
        assertEquals("foo_request_value", req.getHeader("Foo_request"));
        assertEquals("bar_request_value", req.getHeader("bar_request"));
        assertEquals(2, req.headers().getAll("juu_request").size());
        assertEquals("juu_request_value_1", req.headers().getAll("juu_request").get(0));
        assertEquals("juu_request_value_2", req.headers().getAll("juu_request").get(1));
        assertEquals(new HashSet<>(Arrays.asList("foo_request", "bar_request", "juu_request")), new HashSet<>(req.headers().names()));
        reqCount.incrementAndGet();
        HttpServerResponse resp = req.response();
        resp.putHeader("content-type", "text/plain");
        resp.putHeader("Foo_response", "foo_value");
        resp.putHeader("bar_response", "bar_value");
        resp.putHeader("juu_response", (List<String>) Arrays.asList("juu_value_1", "juu_value_2"));
        resp.end();
    });
    startServer();
    client.request(new RequestOptions().setPort(DEFAULT_HTTPS_PORT).setHost(DEFAULT_HTTPS_HOST).setURI("/somepath")).onComplete(onSuccess(req -> {
        req.putHeader("Foo_request", "foo_request_value").putHeader("bar_request", "bar_request_value").putHeader("juu_request", Arrays.<String>asList("juu_request_value_1", "juu_request_value_2"));
        req.send(onSuccess(resp -> {
            Context ctx = vertx.getOrCreateContext();
            assertOnIOContext(ctx);
            assertEquals(1, resp.request().streamId());
            assertEquals(1, reqCount.get());
            assertEquals(HttpVersion.HTTP_2, resp.version());
            assertEquals(200, resp.statusCode());
            assertEquals("OK", resp.statusMessage());
            assertEquals("text/plain", resp.getHeader("content-type"));
            assertEquals("foo_value", resp.getHeader("foo_response"));
            assertEquals("bar_value", resp.getHeader("bar_response"));
            assertEquals(2, resp.headers().getAll("juu_response").size());
            assertEquals("juu_value_1", resp.headers().getAll("juu_response").get(0));
            assertEquals("juu_value_2", resp.headers().getAll("juu_response").get(1));
            assertEquals(new HashSet<>(Arrays.asList("content-type", "content-length", "foo_response", "bar_response", "juu_response")), new HashSet<>(resp.headers().names()));
            resp.endHandler(v -> {
                assertOnIOContext(ctx);
                testComplete();
            });
        }));
    }));
    await();
}
Also used : Arrays(java.util.Arrays) io.netty.handler.codec.http2(io.netty.handler.codec.http2) BiFunction(java.util.function.BiFunction) MultiMap(io.vertx.core.MultiMap) AsciiString(io.netty.util.AsciiString) Context(io.vertx.core.Context) HttpClientConnection(io.vertx.core.http.impl.HttpClientConnection) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Cert(io.vertx.test.tls.Cert) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Assume(org.junit.Assume) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) VertxInternal(io.vertx.core.impl.VertxInternal) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) AtomicLong(java.util.concurrent.atomic.AtomicLong) Ignore(org.junit.Ignore) AsyncTestBase(io.vertx.test.core.AsyncTestBase) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsciiString(io.netty.util.AsciiString) Test(org.junit.Test)

Example 23 with Arrays

use of java.util.Arrays in project immutables by immutables.

the class Mappings method of.

/**
 * Reflectively build  <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html">elastic mapping</a>
 * for a class. Currently works only for immutable interfaces and is
 * very limited in its functionality.
 */
static Mapping of(Class<?> clazz) {
    Objects.requireNonNull(clazz, "clazz");
    Preconditions.checkArgument(clazz.isInterface(), "Expected %s to be an interface", clazz);
    Map<String, String> map = new LinkedHashMap<>();
    Stream<Method> methods = Arrays.stream(clazz.getDeclaredMethods()).filter(m -> m.getParameterCount() == 0).filter(m -> m.getReturnType() != Void.class).filter(m -> Modifier.isPublic(m.getModifiers())).filter(m -> !Modifier.isStatic(m.getModifiers())).filter(m -> m.getDeclaringClass() != Object.class);
    for (Method method : methods.collect(Collectors.toSet())) {
        Class<?> returnType = method.getReturnType();
        // skip arrays and iterables (we don't handle them yet)
        if (returnType.isArray() || Iterable.class.isAssignableFrom(returnType)) {
            continue;
        }
        Type type = method.getGenericReturnType();
        map.put(method.getName(), elasticType(type));
    }
    return Mapping.ofElastic(map);
}
Also used : Arrays(java.util.Arrays) Date(java.util.Date) LocalDateTime(java.time.LocalDateTime) OptionalDouble(java.util.OptionalDouble) Instant(java.time.Instant) OptionalInt(java.util.OptionalInt) Collectors(java.util.stream.Collectors) LinkedHashMap(java.util.LinkedHashMap) Objects(java.util.Objects) BigDecimal(java.math.BigDecimal) OptionalLong(java.util.OptionalLong) Stream(java.util.stream.Stream) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Modifier(java.lang.reflect.Modifier) LocalDate(java.time.LocalDate) Map(java.util.Map) Preconditions(com.google.common.base.Preconditions) BigInteger(java.math.BigInteger) Method(java.lang.reflect.Method) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Method(java.lang.reflect.Method) LinkedHashMap(java.util.LinkedHashMap)

Example 24 with Arrays

use of java.util.Arrays in project jsonschema2pojo by joelittlejohn.

the class ObjectRule method addToString.

private void addToString(JDefinedClass jclass) {
    Map<String, JFieldVar> fields = jclass.fields();
    JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString");
    Set<String> excludes = new HashSet<>(Arrays.asList(ruleFactory.getGenerationConfig().getToStringExcludes()));
    JBlock body = toString.body();
    // The following toString implementation roughly matches the commons ToStringBuilder for
    // backward compatibility
    JClass stringBuilderClass = jclass.owner().ref(StringBuilder.class);
    JVar sb = body.decl(stringBuilderClass, "sb", JExpr._new(stringBuilderClass));
    // Write the header, e.g.: example.domain.MyClass@85e382a7[
    body.add(sb.invoke("append").arg(jclass.dotclass().invoke("getName")).invoke("append").arg(JExpr.lit('@')).invoke("append").arg(jclass.owner().ref(Integer.class).staticInvoke("toHexString").arg(jclass.owner().ref(System.class).staticInvoke("identityHashCode").arg(JExpr._this()))).invoke("append").arg(JExpr.lit('[')));
    // If this has a parent class, include its toString()
    if (!jclass._extends().fullName().equals(Object.class.getName())) {
        JVar baseLength = body.decl(jclass.owner().INT, "baseLength", sb.invoke("length"));
        JVar superString = body.decl(jclass.owner().ref(String.class), "superString", JExpr._super().invoke("toString"));
        JBlock superToStringBlock = body._if(superString.ne(JExpr._null()))._then();
        // If super.toString() is in the Clazz@2ee6529d[field=10] format, extract the fields
        // from the wrapper
        JVar contentStart = superToStringBlock.decl(jclass.owner().INT, "contentStart", superString.invoke("indexOf").arg(JExpr.lit('[')));
        JVar contentEnd = superToStringBlock.decl(jclass.owner().INT, "contentEnd", superString.invoke("lastIndexOf").arg(JExpr.lit(']')));
        JConditional superToStringInnerConditional = superToStringBlock._if(contentStart.gte(JExpr.lit(0)).cand(contentEnd.gt(contentStart)));
        superToStringInnerConditional._then().add(sb.invoke("append").arg(superString).arg(contentStart.plus(JExpr.lit(1))).arg(contentEnd));
        // Otherwise, just append super.toString()
        superToStringInnerConditional._else().add(sb.invoke("append").arg(superString));
        // Append a comma if needed
        body._if(sb.invoke("length").gt(baseLength))._then().add(sb.invoke("append").arg(JExpr.lit(',')));
    }
    // For each included instance field, add to the StringBuilder in the field=value format
    for (JFieldVar fieldVar : fields.values()) {
        if (excludes.contains(fieldVar.name()) || (fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
            continue;
        }
        body.add(sb.invoke("append").arg(fieldVar.name()));
        body.add(sb.invoke("append").arg(JExpr.lit('=')));
        if (fieldVar.type().isPrimitive()) {
            body.add(sb.invoke("append").arg(JExpr.refthis(fieldVar.name())));
        } else if (fieldVar.type().isArray()) {
            // Only primitive arrays are supported
            if (!fieldVar.type().elementType().isPrimitive()) {
                throw new UnsupportedOperationException("Only primitive arrays are supported");
            }
            // Leverage Arrays.toString()
            body.add(sb.invoke("append").arg(JOp.cond(JExpr.refthis(fieldVar.name()).eq(JExpr._null()), JExpr.lit("<null>"), jclass.owner().ref(Arrays.class).staticInvoke("toString").arg(JExpr.refthis(fieldVar.name())).invoke("replace").arg(JExpr.lit('[')).arg(JExpr.lit('{')).invoke("replace").arg(JExpr.lit(']')).arg(JExpr.lit('}')).invoke("replace").arg(JExpr.lit(", ")).arg(JExpr.lit(",")))));
        } else {
            body.add(sb.invoke("append").arg(JOp.cond(JExpr.refthis(fieldVar.name()).eq(JExpr._null()), JExpr.lit("<null>"), JExpr.refthis(fieldVar.name()))));
        }
        body.add(sb.invoke("append").arg(JExpr.lit(',')));
    }
    // Add the trailer
    JConditional trailerConditional = body._if(sb.invoke("charAt").arg(sb.invoke("length").minus(JExpr.lit(1))).eq(JExpr.lit(',')));
    trailerConditional._then().add(sb.invoke("setCharAt").arg(sb.invoke("length").minus(JExpr.lit(1))).arg(JExpr.lit(']')));
    trailerConditional._else().add(sb.invoke("append").arg(JExpr.lit(']')));
    body._return(sb.invoke("toString"));
    toString.annotate(Override.class);
}
Also used : JClass(com.sun.codemodel.JClass) JFieldVar(com.sun.codemodel.JFieldVar) JBlock(com.sun.codemodel.JBlock) JConditional(com.sun.codemodel.JConditional) JMethod(com.sun.codemodel.JMethod) Arrays(java.util.Arrays) HashSet(java.util.HashSet) JVar(com.sun.codemodel.JVar)

Example 25 with Arrays

use of java.util.Arrays in project jsonschema2pojo by joelittlejohn.

the class DefaultRule method getDefaultSet.

/**
 * Creates a default value for a set property by:
 * <ol>
 * <li>Creating a new {@link LinkedHashSet} with the correct generic type
 * <li>Using {@link Arrays#asList(Object...)} to initialize the set with the
 * correct default values
 * </ol>
 *
 * @param fieldType
 *            the java type that applies for this field ({@link Set} with
 *            some generic type argument)
 * @param node
 *            the node containing default values for this set
 * @return an expression that creates a default value that can be assigned
 *         to this field
 */
private JExpression getDefaultSet(JType fieldType, JsonNode node) {
    JClass setGenericType = ((JClass) fieldType).getTypeParameters().get(0);
    JClass setImplClass = fieldType.owner().ref(LinkedHashSet.class);
    setImplClass = setImplClass.narrow(setGenericType);
    JInvocation newSetImpl = JExpr._new(setImplClass);
    if (node instanceof ArrayNode && node.size() > 0) {
        JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList");
        for (JsonNode defaultValue : node) {
            invokeAsList.arg(getDefaultValue(setGenericType, defaultValue));
        }
        newSetImpl.arg(invokeAsList);
    } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) {
        return null;
    }
    return newSetImpl;
}
Also used : JClass(com.sun.codemodel.JClass) JInvocation(com.sun.codemodel.JInvocation) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Arrays(java.util.Arrays)

Aggregations

Arrays (java.util.Arrays)69 List (java.util.List)45 ArrayList (java.util.ArrayList)39 Map (java.util.Map)31 Test (org.junit.Test)23 Collections (java.util.Collections)21 HashMap (java.util.HashMap)18 Collectors (java.util.stream.Collectors)14 Set (java.util.Set)12 Function (java.util.function.Function)12 Stream (java.util.stream.Stream)12 IOException (java.io.IOException)11 TimeUnit (java.util.concurrent.TimeUnit)11 Optional (java.util.Optional)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 Logger (org.slf4j.Logger)9 LoggerFactory (org.slf4j.LoggerFactory)9 HashSet (java.util.HashSet)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6