Search in sources :

Example 11 with ByteArrayOutputStream

use of java.io.ByteArrayOutputStream in project jetty.project by eclipse.

the class HttpServerTestBase method testRecycledWriters.

@Test
public void testRecycledWriters() throws Exception {
    configureServer(new EchoHandler());
    try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort())) {
        OutputStream os = client.getOutputStream();
        InputStream is = client.getInputStream();
        os.write(("POST /echo?charset=utf-8 HTTP/1.1\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "content-type: text/plain; charset=utf-8\r\n" + "content-length: 10\r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
        os.write(("123456789\n").getBytes("utf-8"));
        os.write(("POST /echo?charset=utf-8 HTTP/1.1\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "content-type: text/plain; charset=utf-8\r\n" + "content-length: 10\r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
        os.write(("abcdefghZ\n").getBytes("utf-8"));
        String content = "Wibble";
        byte[] contentB = content.getBytes("utf-8");
        os.write(("POST /echo?charset=utf-16 HTTP/1.1\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "content-type: text/plain; charset=utf-8\r\n" + "content-length: " + contentB.length + "\r\n" + "connection: close\r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
        os.write(contentB);
        os.flush();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        IO.copy(is, bout);
        byte[] b = bout.toByteArray();
        //System.err.println("OUTPUT: "+new String(b));
        int i = 0;
        while (b[i] != 'Z') i++;
        int state = 0;
        while (state != 4) {
            switch(b[i++]) {
                case '\r':
                    if (state == 0 || state == 2)
                        state++;
                    continue;
                case '\n':
                    if (state == 1 || state == 3)
                        state++;
                    continue;
                default:
                    state = 0;
            }
        }
        String in = new String(b, 0, i, StandardCharsets.UTF_8);
        assertThat(in, containsString("123456789"));
        assertThat(in, containsString("abcdefghZ"));
        assertFalse(in.contains("Wibble"));
        in = new String(b, i, b.length - i, StandardCharsets.UTF_16);
        assertEquals("Wibble\n", in);
    }
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Socket(java.net.Socket) EndPoint(org.eclipse.jetty.io.EndPoint) Test(org.junit.Test)

Example 12 with ByteArrayOutputStream

use of java.io.ByteArrayOutputStream in project jetty.project by eclipse.

the class DatabaseLoginServiceTestServer method runscript.

public static int runscript(File scriptFile) throws Exception {
    //System.err.println("Running script:"+scriptFile.getAbsolutePath());
    try (FileInputStream fileStream = new FileInputStream(scriptFile)) {
        Loader.loadClass("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
        Connection connection = DriverManager.getConnection(__dbURL, "", "");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        return ij.runScript(connection, fileStream, "UTF-8", out, "UTF-8");
    }
}
Also used : Connection(java.sql.Connection) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FileInputStream(java.io.FileInputStream)

Example 13 with ByteArrayOutputStream

use of java.io.ByteArrayOutputStream in project vert.x by eclipse.

the class Http2ClientTest method testResponseCompression.

private void testResponseCompression(boolean enabled) throws Exception {
    byte[] expected = TestUtils.randomAlphaString(1000).getBytes();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream in = new GZIPOutputStream(baos);
    in.write(expected);
    in.close();
    byte[] compressed = baos.toByteArray();
    server.close();
    server = vertx.createHttpServer(serverOptions);
    server.requestHandler(req -> {
        assertEquals(enabled ? "deflate, gzip" : null, req.getHeader(HttpHeaderNames.ACCEPT_ENCODING));
        req.response().putHeader(HttpHeaderNames.CONTENT_ENCODING.toLowerCase(), "gzip").end(Buffer.buffer(compressed));
    });
    startServer();
    client.close();
    client = vertx.createHttpClient(clientOptions.setTryUseCompression(enabled));
    client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
        String encoding = resp.getHeader(HttpHeaderNames.CONTENT_ENCODING);
        assertEquals(enabled ? null : "gzip", encoding);
        resp.bodyHandler(buff -> {
            assertEquals(Buffer.buffer(enabled ? expected : compressed), buff);
            testComplete();
        });
    }).end();
    await();
}
Also used : Arrays(java.util.Arrays) JksOptions(io.vertx.core.net.JksOptions) BiFunction(java.util.function.BiFunction) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) AsciiString(io.netty.util.AsciiString) Cert(io.vertx.test.core.tls.Cert) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) StreamResetException(io.vertx.core.http.StreamResetException) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) 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) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) io.vertx.core(io.vertx.core) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) 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) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) ConnectException(java.net.ConnectException) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) SocketAddress(io.vertx.core.net.SocketAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) 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) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2ServerUpgradeCodec(io.netty.handler.codec.http2.Http2ServerUpgradeCodec) HttpMethod(io.vertx.core.http.HttpMethod) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AsciiString(io.netty.util.AsciiString)

Example 14 with ByteArrayOutputStream

use of java.io.ByteArrayOutputStream in project buck by facebook.

the class SchemeGenerator method writeScheme.

public Path writeScheme() throws IOException {
    Map<PBXTarget, XCScheme.BuildableReference> buildTargetToBuildableReferenceMap = Maps.newHashMap();
    for (PBXTarget target : Iterables.concat(orderedBuildTargets, orderedBuildTestTargets)) {
        String blueprintName = target.getProductName();
        if (blueprintName == null) {
            blueprintName = target.getName();
        }
        Path outputPath = outputDirectory.getParent();
        String buildableReferencePath;
        Path projectPath = Preconditions.checkNotNull(targetToProjectPathMap.get(target));
        if (outputPath == null) {
            //Root directory project
            buildableReferencePath = projectPath.toString();
        } else {
            buildableReferencePath = outputPath.relativize(projectPath).toString();
        }
        XCScheme.BuildableReference buildableReference = new XCScheme.BuildableReference(buildableReferencePath, Preconditions.checkNotNull(target.getGlobalID()), target.getProductReference() != null ? target.getProductReference().getName() : Preconditions.checkNotNull(target.getProductName()), blueprintName);
        buildTargetToBuildableReferenceMap.put(target, buildableReference);
    }
    XCScheme.BuildAction buildAction = new XCScheme.BuildAction(parallelizeBuild);
    // For aesthetic reasons put all non-test build actions before all test build actions.
    for (PBXTarget target : orderedBuildTargets) {
        addBuildActionForBuildTarget(buildTargetToBuildableReferenceMap.get(target), !primaryTargetIsBuildWithBuck || !primaryTarget.isPresent() || target.equals(primaryTarget.get()) ? XCScheme.BuildActionEntry.BuildFor.DEFAULT : XCScheme.BuildActionEntry.BuildFor.INDEXING, buildAction);
    }
    for (PBXTarget target : orderedBuildTestTargets) {
        addBuildActionForBuildTarget(buildTargetToBuildableReferenceMap.get(target), XCScheme.BuildActionEntry.BuildFor.TEST_ONLY, buildAction);
    }
    XCScheme.TestAction testAction = new XCScheme.TestAction(Preconditions.checkNotNull(actionConfigNames.get(SchemeActionType.TEST)));
    for (PBXTarget target : orderedRunTestTargets) {
        XCScheme.BuildableReference buildableReference = buildTargetToBuildableReferenceMap.get(target);
        XCScheme.TestableReference testableReference = new XCScheme.TestableReference(buildableReference);
        testAction.addTestableReference(testableReference);
    }
    Optional<XCScheme.LaunchAction> launchAction = Optional.empty();
    Optional<XCScheme.ProfileAction> profileAction = Optional.empty();
    if (primaryTarget.isPresent()) {
        XCScheme.BuildableReference primaryBuildableReference = buildTargetToBuildableReferenceMap.get(primaryTarget.get());
        if (primaryBuildableReference != null) {
            launchAction = Optional.of(new XCScheme.LaunchAction(primaryBuildableReference, Preconditions.checkNotNull(actionConfigNames.get(SchemeActionType.LAUNCH)), runnablePath, remoteRunnablePath, launchStyle));
            profileAction = Optional.of(new XCScheme.ProfileAction(primaryBuildableReference, Preconditions.checkNotNull(actionConfigNames.get(SchemeActionType.PROFILE))));
        }
    }
    XCScheme.AnalyzeAction analyzeAction = new XCScheme.AnalyzeAction(Preconditions.checkNotNull(actionConfigNames.get(SchemeActionType.ANALYZE)));
    XCScheme.ArchiveAction archiveAction = new XCScheme.ArchiveAction(Preconditions.checkNotNull(actionConfigNames.get(SchemeActionType.ARCHIVE)));
    XCScheme scheme = new XCScheme(schemeName, Optional.of(buildAction), Optional.of(testAction), launchAction, profileAction, Optional.of(analyzeAction), Optional.of(archiveAction));
    outputScheme = Optional.of(scheme);
    Path schemeDirectory = outputDirectory.resolve("xcshareddata/xcschemes");
    projectFilesystem.mkdirs(schemeDirectory);
    Path schemePath = schemeDirectory.resolve(schemeName + ".xcscheme");
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        serializeScheme(scheme, outputStream);
        String contentsToWrite = outputStream.toString();
        if (MoreProjectFilesystems.fileContentsDiffer(new ByteArrayInputStream(contentsToWrite.getBytes(Charsets.UTF_8)), schemePath, projectFilesystem)) {
            projectFilesystem.writeContentsToPath(outputStream.toString(), schemePath);
        }
    }
    return schemePath;
}
Also used : PBXTarget(com.facebook.buck.apple.xcode.xcodeproj.PBXTarget) Path(java.nio.file.Path) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) XCScheme(com.facebook.buck.apple.xcode.XCScheme)

Example 15 with ByteArrayOutputStream

use of java.io.ByteArrayOutputStream in project buck by facebook.

the class WorkspaceGenerator method writeWorkspace.

public Path writeWorkspace() throws IOException {
    DocumentBuilder docBuilder;
    Transformer transformer;
    try {
        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        transformer = TransformerFactory.newInstance().newTransformer();
    } catch (ParserConfigurationException | TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
    DOMImplementation domImplementation = docBuilder.getDOMImplementation();
    final Document doc = domImplementation.createDocument(/* namespaceURI */
    null, "Workspace", /* docType */
    null);
    doc.setXmlVersion("1.0");
    Element rootElem = doc.getDocumentElement();
    rootElem.setAttribute("version", "1.0");
    final Stack<Element> groups = new Stack<>();
    groups.push(rootElem);
    FileVisitor<Map.Entry<String, WorkspaceNode>> visitor = new FileVisitor<Map.Entry<String, WorkspaceNode>>() {

        @Override
        public FileVisitResult preVisitDirectory(Map.Entry<String, WorkspaceNode> dir, BasicFileAttributes attrs) throws IOException {
            Preconditions.checkArgument(dir.getValue() instanceof WorkspaceGroup);
            Element element = doc.createElement("Group");
            element.setAttribute("location", "container:");
            element.setAttribute("name", dir.getKey());
            groups.peek().appendChild(element);
            groups.push(element);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Map.Entry<String, WorkspaceNode> file, BasicFileAttributes attrs) throws IOException {
            Preconditions.checkArgument(file.getValue() instanceof WorkspaceFileRef);
            WorkspaceFileRef fileRef = (WorkspaceFileRef) file.getValue();
            Element element = doc.createElement("FileRef");
            element.setAttribute("location", "container:" + MorePaths.relativize(MorePaths.normalize(outputDirectory), fileRef.getPath()).toString());
            groups.peek().appendChild(element);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Map.Entry<String, WorkspaceNode> file, IOException exc) throws IOException {
            return FileVisitResult.TERMINATE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Map.Entry<String, WorkspaceNode> dir, IOException exc) throws IOException {
            groups.pop();
            return FileVisitResult.CONTINUE;
        }
    };
    walkNodeTree(visitor);
    Path projectWorkspaceDir = getWorkspaceDir();
    projectFilesystem.mkdirs(projectWorkspaceDir);
    Path serializedWorkspace = projectWorkspaceDir.resolve("contents.xcworkspacedata");
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(outputStream);
        transformer.transform(source, result);
        String contentsToWrite = outputStream.toString();
        if (MoreProjectFilesystems.fileContentsDiffer(new ByteArrayInputStream(contentsToWrite.getBytes(Charsets.UTF_8)), serializedWorkspace, projectFilesystem)) {
            projectFilesystem.writeContentsToPath(contentsToWrite, serializedWorkspace);
        }
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
    Path xcshareddata = projectWorkspaceDir.resolve("xcshareddata");
    projectFilesystem.mkdirs(xcshareddata);
    Path workspaceSettingsPath = xcshareddata.resolve("WorkspaceSettings.xcsettings");
    String workspaceSettings = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\"" + " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" + "<plist version=\"1.0\">\n" + "<dict>\n" + "\t<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>\n" + "\t<false/>\n" + "</dict>\n" + "</plist>";
    projectFilesystem.writeContentsToPath(workspaceSettings, workspaceSettingsPath);
    return projectWorkspaceDir;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) Element(org.w3c.dom.Element) DOMImplementation(org.w3c.dom.DOMImplementation) Document(org.w3c.dom.Document) FileVisitor(java.nio.file.FileVisitor) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) TransformerException(javax.xml.transform.TransformerException) Path(java.nio.file.Path) StreamResult(javax.xml.transform.stream.StreamResult) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Stack(java.util.Stack) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) SortedMap(java.util.SortedMap)

Aggregations

ByteArrayOutputStream (java.io.ByteArrayOutputStream)17705 ByteArrayInputStream (java.io.ByteArrayInputStream)4669 Test (org.junit.Test)4609 IOException (java.io.IOException)4326 InputStream (java.io.InputStream)1957 ObjectOutputStream (java.io.ObjectOutputStream)1679 PrintStream (java.io.PrintStream)1544 DataOutputStream (java.io.DataOutputStream)1303 ArrayList (java.util.ArrayList)875 ObjectInputStream (java.io.ObjectInputStream)818 OutputStream (java.io.OutputStream)807 File (java.io.File)770 HashMap (java.util.HashMap)558 Test (org.junit.jupiter.api.Test)526 FileInputStream (java.io.FileInputStream)460 Document (org.w3c.dom.Document)382 DataInputStream (java.io.DataInputStream)378 OutputStreamWriter (java.io.OutputStreamWriter)365 URL (java.net.URL)358 GZIPOutputStream (java.util.zip.GZIPOutputStream)338