Java Code Examples for java.io.ByteArrayOutputStream

The following examples show how to use java.io.ByteArrayOutputStream. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void invokeHandler_invalidModelTypes_causesSchemaValidationFailure() throws IOException {
    // use actual validator to verify behaviour
    final WrapperOverride wrapper = new WrapperOverride(providerLoggingCredentialsProvider, platformEventsLogger,
                                                        providerEventsLogger, providerMetricsPublisher, new Validator() {
                                                        }, httpClient);

    wrapper.setTransformResponse(resourceHandlerRequest);

    try (final InputStream in = loadRequestStream("create.request.with-invalid-model-types.json");
        final OutputStream out = new ByteArrayOutputStream()) {
        final Context context = getLambdaContext();

        wrapper.handleRequest(in, out, context);

        // verify output response
        verifyHandlerResponse(out,
            ProgressEvent.<TestModel, TestContext>builder().errorCode(HandlerErrorCode.InvalidRequest)
                .status(OperationStatus.FAILED)
                .message("Model validation failed (#/property1: expected type: String, found: JSONArray)").build());
    }
}
 
Example 2
Source Project: yosegi   Source File: TestPushdownSupportedBlockWriter.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void T_dataSizeAfterAppend_equalsDataBinarySize_withNestedSimpleCaseChild() throws IOException {
  PushdownSupportedBlockWriter writer = new PushdownSupportedBlockWriter();
  writer.setup( 1024 * 1024 * 8 , new Configuration() );
  List<ColumnBinary> childList = createSimpleCaseData();
  List<ColumnBinary> list = Arrays.asList( DumpSpreadColumnBinaryMaker.createSpreadColumnBinary(
      "parent" , 10 , childList ) );
  int sizeAfterAppend = writer.sizeAfterAppend( list );
  writer.append( 10 , list );

  int outputDataSize = writer.size();
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  writer.writeVariableBlock( out );
  byte[] block = out.toByteArray();
  assertEquals( outputDataSize , block.length );
}
 
Example 3
Source Project: TencentKona-8   Source File: VMSupport.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Write the given properties list to a byte array and return it. Properties with
 * a key or value that is not a String is filtered out. The stream written to the byte
 * array is ISO 8859-1 encoded.
 */
private static byte[] serializePropertiesToByteArray(Properties p) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream(4096);

    Properties props = new Properties();

    // stringPropertyNames() returns a snapshot of the property keys
    Set<String> keyset = p.stringPropertyNames();
    for (String key : keyset) {
        String value = p.getProperty(key);
        props.put(key, value);
    }

    props.store(out, null);
    return out.toByteArray();
}
 
Example 4
Source Project: jdk8u60   Source File: BandStructure.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void setInputStreamFrom(InputStream in) throws IOException {
    assert(bytes == null);
    assert(assertReadyToReadFrom(this, in));
    setPhase(READ_PHASE);
    this.in = in;
    if (optDumpBands) {
        // Tap the stream.
        bytesForDump = new ByteArrayOutputStream();
        this.in = new FilterInputStream(in) {
            @Override
            public int read() throws IOException {
                int ch = in.read();
                if (ch >= 0)  bytesForDump.write(ch);
                return ch;
            }
            @Override
            public int read(byte b[], int off, int len) throws IOException {
                int nr = in.read(b, off, len);
                if (nr >= 0)  bytesForDump.write(b, off, nr);
                return nr;
            }
        };
    }
    super.readyToDisburse();
}
 
Example 5
Source Project: Tok-Android   Source File: ImageUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static Bitmap compressBitmap(Bitmap bitmap, long sizeLimit) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int quality = 90;
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
    LogUtil.i(TAG, "origin size:" + baos.size());
    //TODO has problem
    while (baos.size() / 1024 > sizeLimit) {
        LogUtil.i(TAG, "after size:" + baos.size());
        // 清空baos
        baos.reset();
        quality -= 10;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
    }

    return BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, null);
}
 
Example 6
Source Project: openjdk-jdk8u   Source File: Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
static void serial(URI u) throws IOException, URISyntaxException {

        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);

        oo.writeObject(u);
        oo.close();

        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        try {
            Object o = oi.readObject();
            eq(u, (URI)o);
        } catch (ClassNotFoundException x) {
            x.printStackTrace();
            throw new RuntimeException(x.toString());
        }

        testCount++;
    }
 
Example 7
Source Project: gadtry   Source File: IOUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void copyByTestReturnCheckError()
        throws InstantiationException
{
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintStream printStream = AopFactory.proxy(PrintStream.class)
            .byInstance(UnsafeHelper.allocateInstance(PrintStream.class))
            .whereMethod(methodInfo -> methodInfo.getName().equals("checkError"))
            .around(proxyContext -> true);

    try (ByteArrayInputStream inputStream = new ByteArrayInputStream("IOUtilsTest".getBytes(UTF_8))) {
        IOUtils.copyBytes(inputStream, printStream, 1024, false);
        Assert.assertEquals("IOUtilsTest", outputStream.toString(UTF_8.name()));
        Assert.fail();
    }
    catch (IOException e) {
        Assert.assertEquals(e.getMessage(), "Unable to write to output stream.");
    }
}
 
Example 8
Source Project: xian   Source File: GelfMessage.java    License: Apache License 2.0 6 votes vote down vote up
private byte[] gzipMessage(byte[] message) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        GZIPOutputStream stream = new GZIPOutputStream(bos);

        stream.write(message);
        stream.finish();
        Closer.close(stream);
        byte[] zipped = bos.toByteArray();
        Closer.close(bos);
        return zipped;
    } catch (IOException e) {
        return null;
    }
}
 
Example 9
private static void testWrapEncode2(final Base64.Encoder encoder)
        throws IOException {
    System.err.println("\nEncoder.wrap test II ");
    final byte[] secondTestBuffer =
            "api/java_util/Base64/index.html#GetEncoderMimeCustom[noLineSeparatorInEncodedString]"
            .getBytes(US_ASCII);
    String base64EncodedString;
    ByteArrayOutputStream secondEncodingStream = new ByteArrayOutputStream();
    OutputStream base64EncodingStream = encoder.wrap(secondEncodingStream);
    base64EncodingStream.write(secondTestBuffer);
    base64EncodingStream.close();

    final byte[] encodedByteArray = secondEncodingStream.toByteArray();

    System.err.print("result = " + new String(encodedByteArray, US_ASCII)
            + "  after wrap Base64 encoding of string");

    base64EncodedString = new String(encodedByteArray, US_ASCII);

    if (base64EncodedString.contains("$$$")) {
        throw new RuntimeException(
                "Base64 encoding contains line separator after wrap 2 invoked  ... \n");
    }
}
 
Example 10
@Override
public byte[] generatorCode(String[] tableNames) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(outputStream);

    for(String tableName : tableNames){
        //查询表信息
        Map<String, String> table = queryTable(tableName);
        //查询列信息
        List<Map<String, String>> columns = queryColumns(tableName);
        //生成代码
        GenUtils.generatorCode(table, columns, zip);
    }
    IOUtils.closeQuietly(zip);
    return outputStream.toByteArray();
}
 
Example 11
Source Project: xyz-hub   Source File: Compression.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Decompress a byte array which was compressed using Deflate.
 * @param bytearray non-null byte array to be decompressed
 * @return the decompressed payload or an empty array in case of bytearray is null
 * @throws DataFormatException in case the payload cannot be decompressed
 */
public static byte[] decompressUsingInflate(byte[] bytearray) throws DataFormatException {
  if (bytearray == null) return new byte[0];

  try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
    final Inflater inflater = new Inflater();
    final byte[] buff = new byte[1024];

    inflater.setInput(bytearray);

    while (!inflater.finished()) {
      int count = inflater.inflate(buff);
      bos.write(buff, 0, count);
    }

    inflater.end();
    bos.flush();
    return bos.toByteArray();
  } catch (IOException e) {
    throw new DataFormatException(e.getMessage());
  }
}
 
Example 12
DistributedKeySignature(String signatureAlgorithm) throws NoSuchAlgorithmException {
   LOG.debug("constructor: " + signatureAlgorithm);
   this.signatureAlgorithm = signatureAlgorithm;
   if (!digestAlgos.containsKey(signatureAlgorithm)) {
      LOG.error("no such algo: " + signatureAlgorithm);
      throw new NoSuchAlgorithmException(signatureAlgorithm);
   } else {
      String digestAlgo = (String)digestAlgos.get(signatureAlgorithm);
      if (null != digestAlgo) {
         this.messageDigest = MessageDigest.getInstance(digestAlgo);
         this.precomputedDigestOutputStream = null;
      } else {
         LOG.debug("NONE message digest");
         this.messageDigest = null;
         this.precomputedDigestOutputStream = new ByteArrayOutputStream();
      }

   }
}
 
Example 13
Source Project: snowblossom   Source File: KeyUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Produce a string that is a decomposition of the given x.509 or ASN1 encoded
 * object.  For learning and debugging purposes.
 */
public static String decomposeASN1Encoded(ByteString input)
  throws Exception
{
  ByteArrayOutputStream byte_out = new ByteArrayOutputStream();
  PrintStream out = new PrintStream(byte_out);

  ASN1StreamParser parser = new ASN1StreamParser(input.toByteArray());
  out.println("ASN1StreamParser");

  while(true)
  {
    ASN1Encodable encodable = parser.readObject();
    if (encodable == null) break;

    decomposeEncodable(encodable, 2, out);
  }

  out.flush();
  return new String(byte_out.toByteArray());

}
 
Example 14
Source Project: Ffast-Java   Source File: GzipUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 解压
 * @param data
 * @return
 * @throws Exception
 */
public static byte[] ungzip(byte[] data) throws Exception {
    ByteArrayInputStream bis = new ByteArrayInputStream(data);
    GZIPInputStream gzip = new GZIPInputStream(bis);
    byte[] buf = new byte[1024];
    int num = -1;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((num = gzip.read(buf, 0, buf.length)) != -1) {
        bos.write(buf, 0, num);
    }
    gzip.close();
    bis.close();
    byte[] ret = bos.toByteArray();
    bos.flush();
    bos.close();
    return ret;
}
 
Example 15
Source Project: org.hl7.fhir.core   Source File: CDARoundTripTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
/**
 * verify that umlaut like äö etc are not encoded in UTF-8 in attributes
 */
public void testSerializeUmlaut() throws IOException {
  Element xml = Manager.parse(context,
	  TestingUtilities.loadTestResourceStream("validator", "cda", "example.xml"), FhirFormat.XML);
  
  List<Element> title = xml.getChildrenByName("title");
  assertTrue(title != null && title.size() == 1);
  
  
  Element value = title.get(0).getChildren().get(0);
  Assertions.assertEquals("Episode Note", value.getValue());
  value.setValue("öé");
  
  ByteArrayOutputStream baosXml = new ByteArrayOutputStream();
  Manager.compose(TestingUtilities.context(), xml, baosXml, FhirFormat.XML, OutputStyle.PRETTY, null);
  String cdaSerialised = baosXml.toString("UTF-8");
  assertTrue(cdaSerialised.indexOf("öé") > 0);
}
 
Example 16
Source Project: db   Source File: PercentEncoder.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Encodes a byte array into percent encoding
 *
 * @param source The byte-representation of the string.
 * @param bitSet The BitSet for characters to skip encoding
 * @return The percent-encoded byte array
 */
public static byte[] encode(byte[] source, BitSet bitSet) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(source.length * 2);
    for (int i = 0; i < source.length; i++) {
        int b = source[i];
        if (b < 0) {
            b += 256;
        }
        if (bitSet.get(b)) {
            bos.write(b);
        } else {
            bos.write('%');
            char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16));
            char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
            bos.write(hex1);
            bos.write(hex2);
        }
    }
    return bos.toByteArray();
}
 
Example 17
Source Project: sofa-hessian   Source File: MicroHessianInput.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads a byte array
 *
 * <pre>
 * B b16 b8 data value
 * </pre>
 */
public byte[] readBytes()
    throws IOException
{
    int tag = is.read();

    if (tag == 'N')
        return null;

    if (tag != 'B')
        throw expect("bytes", tag);

    int b16 = is.read();
    int b8 = is.read();

    int len = (b16 << 8) + b8;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    for (int i = 0; i < len; i++)
        bos.write(is.read());

    return bos.toByteArray();
}
 
Example 18
Source Project: arcusplatform   Source File: HttpService.java    License: Apache License 2.0 6 votes vote down vote up
public static byte[] content(URI uri, ProgressMonitor<Long> monitor) throws IOException {
   try (CloseableHttpResponse rsp = get(uri)) {
      if (rsp.getStatusLine().getStatusCode() != 200) {
         throw new IOException("http request failed: " + rsp.getStatusLine().getStatusCode());
      }

      HttpEntity entity = rsp.getEntity();

      long length = entity.getContentLength();
      int clength = (int)length;
      if (clength <= 0 || length >= Integer.MAX_VALUE) clength = 256;

      try (InputStream is = entity.getContent();
           ByteArrayOutputStream os = new ByteArrayOutputStream(clength)) {
         copy(is, os, length, monitor);
         EntityUtils.consume(entity);
         return os.toByteArray();
      }
   }
}
 
Example 19
Source Project: Kepler   Source File: HtmlUtil.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();

        imageString =  new String(Base64.encodeBase64(imageBytes));

        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}
 
Example 20
Source Project: tessera   Source File: CrossDomainConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void marshal() {
    CrossDomainConfig config = new CrossDomainConfig();
    config.setAllowedMethods(Arrays.asList("GET", "OPTIONS"));
    config.setAllowedOrigins(Arrays.asList("a", "b"));
    config.setAllowedHeaders(Arrays.asList("A", "B"));
    config.setAllowCredentials(Boolean.TRUE);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JaxbUtil.marshal(config, out);

    JsonObject result = Json.createReader(new ByteArrayInputStream(out.toByteArray())).readObject();

    assertThat(result.getJsonArray("allowedMethods").getValuesAs(JsonString.class)).containsExactlyInAnyOrder(Json.createValue("GET"), Json.createValue("OPTIONS"));
    assertThat(result.getJsonArray("allowedOrigins").getValuesAs(JsonString.class)).containsExactlyInAnyOrder(Json.createValue("a"), Json.createValue("b"));
    assertThat(result.getJsonArray("allowedHeaders").getValuesAs(JsonString.class)).containsExactlyInAnyOrder(Json.createValue("A"), Json.createValue("B"));
    assertThat(result.get("allowCredentials")).isEqualTo(JsonValue.TRUE);
}
 
Example 21
private static MyClassLoader createClassLoaderWithEventClass() throws Exception {
    String resourceName = EVENT_NAME.replace('.', '/') + ".class";
    try (InputStream is = TestUnloadEventClassCount.class.getClassLoader().getResourceAsStream(resourceName)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int byteValue = 0;
        while ((byteValue = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, byteValue);
        }
        baos.flush();
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> eventClass = myClassLoader.defineClass(EVENT_NAME, baos.toByteArray());
        if (eventClass == null) {
            throw new Exception("Could not define test class");
        }
        if (eventClass.getSuperclass() != Event.class) {
            throw new Exception("Superclass should be jdk.jfr.Event");
        }
        if (eventClass.getSuperclass().getClassLoader() != null) {
            throw new Exception("Class loader of jdk.jfr.Event should be null");
        }
        if (eventClass.getClassLoader() != myClassLoader) {
            throw new Exception("Incorrect class loader for event class");
        }
        eventClass.newInstance(); // force <clinit>
        return myClassLoader;
    }
}
 
Example 22
Source Project: localization_nifi   Source File: PutTCP.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * event handler method to handle the FlowFile being forwarded to the Processor by the framework. The FlowFile contents is sent out over a TCP connection using an acquired ChannelSender object. If
 * the FlowFile contents was sent out successfully then the FlowFile is forwarded to the success relationship. If an error occurred then the FlowFile is forwarded to the failure relationship.
 *
 * @param context
 *            - the current process context.
 *
 * @param sessionFactory
 *            - a factory object to obtain a process session.
 */
@Override
public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory) throws ProcessException {
    final ProcessSession session = sessionFactory.createSession();
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        pruneIdleSenders(context.getProperty(IDLE_EXPIRATION).asTimePeriod(TimeUnit.MILLISECONDS).longValue());
        context.yield();
        return;
    }

    ChannelSender sender = acquireSender(context, session, flowFile);
    if (sender == null) {
        return;
    }

    try {
        String outgoingMessageDelimiter = getOutgoingMessageDelimiter(context, flowFile);
        ByteArrayOutputStream content = readContent(session, flowFile);
        if (outgoingMessageDelimiter != null) {
            Charset charset = Charset.forName(context.getProperty(CHARSET).getValue());
            content = appendDelimiter(content, outgoingMessageDelimiter, charset);
        }
        StopWatch stopWatch = new StopWatch(true);
        sender.send(content.toByteArray());
        session.getProvenanceReporter().send(flowFile, transitUri, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
        session.transfer(flowFile, REL_SUCCESS);
        session.commit();
    } catch (Exception e) {
        onFailure(context, session, flowFile);
        getLogger().error("Exception while handling a process session, transferring {} to failure.", new Object[] { flowFile }, e);
    } finally {
        // If we are going to use this sender again, then relinquish it back to the pool.
        if (!isConnectionPerFlowFile(context)) {
            relinquishSender(sender);
        } else {
            sender.close();
        }
    }
}
 
Example 23
Source Project: shadowsocks-java   Source File: SeedCrypt.java    License: MIT License 5 votes vote down vote up
@Override
protected void _decrypt(byte[] data, ByteArrayOutputStream stream) {
    int noBytesProcessed;
    byte[] buffer = new byte[data.length];

    noBytesProcessed = decCipher.processBytes(data, 0, data.length, buffer, 0);
    stream.write(buffer, 0, noBytesProcessed);
}
 
Example 24
Source Project: JDKSourceCode1.8   Source File: XMLSignatureInput.java    License: MIT License 5 votes vote down vote up
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
Example 25
@Override
protected void compile() throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ByteArrayOutputStream err = new ByteArrayOutputStream();
    final List<String> args = getCompilerArgs();
    int errors;
    try {
        errors = evaluateScript(out, err, args.toArray(new String[args.size()]));
    } catch (final AssertionError e) {
        final PrintWriter writer = new PrintWriter(err);
        e.printStackTrace(writer);
        writer.flush();
        errors = 1;
    }
    if (errors != 0 || checkCompilerMsg) {
        result.err = err.toString();
        if (expectCompileFailure || checkCompilerMsg) {
            final PrintStream outputDest = new PrintStream(new FileOutputStream(getErrorFileName()));
            TestHelper.dumpFile(outputDest, new StringReader(new String(err.toByteArray())));
            outputDest.println("--");
        }
        if (errors != 0 && !expectCompileFailure) {
            fail(String.format("%d errors compiling %s", errors, testFile));
        }
        if (checkCompilerMsg) {
            compare(getErrorFileName(), expectedFileName, true);
        }
    }
    if (expectCompileFailure && errors == 0) {
        fail(String.format("No errors encountered compiling negative test %s", testFile));
    }
}
 
Example 26
Source Project: hop   Source File: XmlHandler.java    License: Apache License 2.0 5 votes vote down vote up
public static String encodeBinaryData( byte[] val ) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  GZIPOutputStream gzos = new GZIPOutputStream( baos );
  BufferedOutputStream bos = new BufferedOutputStream( gzos );
  bos.write( val );
  bos.flush();
  bos.close();

  return new String( Base64.encodeBase64( baos.toByteArray() ) );
}
 
Example 27
static byte[] inputStreamToByteArray(final InputStream is) throws IOException {
    final ByteArrayOutputStream buf = new ByteArrayOutputStream();
    final byte[] temp = new byte[1024];
    int read;
    while ((read = is.read(temp)) > 0) {
        buf.write(temp, 0, read);
    }
    is.close();
    return buf.toByteArray();
}
 
Example 28
Source Project: milkman   Source File: NashornExecutor.java    License: MIT License 5 votes vote down vote up
@Override
public ExecutionResult executeScript(String source, RequestContainer request, ResponseContainer response, RequestExecutionContext context) {
    ByteArrayOutputStream logStream = new ByteArrayOutputStream();
    initGlobalBindings();

    Bindings bindings = engine.createBindings();
    engine.setContext(new SimpleScriptContext());

    //we need to use globalBindings as engnine bindings and the normal bindings as globalBindings, otherwise things like chai dont work
    //bc they modify object prototype and this change is not resolved if in global scope

    engine.getContext().setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
    engine.getContext().setBindings(globalBindings, ScriptContext.ENGINE_SCOPE);

    engine.getContext().setErrorWriter(new OutputStreamWriter(logStream));
    engine.getContext().setWriter(new OutputStreamWriter(logStream));

    var facade = new MilkmanNashornFacade(request, response, context, toaster);
    bindings.put("milkman", facade);
    bindings.put("mm", facade);

    try {
        Object eval = engine.eval(source);
        return new ExecutionResult(logStream.toString(), Optional.ofNullable(eval));
    } catch (Exception e) {
        String causeMessage = ExceptionUtils.getRootCauseMessage(e);
        toaster.showToast("Failed to execute script: " + causeMessage);
        log.error("failed to execute script", e);
    }
    return new ExecutionResult(logStream.toString(), Optional.empty());
}
 
Example 29
static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
        double ii = i / 1024.0;
        ii = ii * ii;
        testarray[i] = (float)Math.sin(10*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI);
        testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    buffer = new ModelByteBuffer(test_byte_array);

    byte[] test_byte_array2 = new byte[testarray.length*3];
    buffer24 = new ModelByteBuffer(test_byte_array2);
    test_byte_array_8ext = new byte[testarray.length];
    byte[] test_byte_array_8_16 = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format24).toByteArray(testarray, test_byte_array2);
    int ix = 0;
    int x = 0;
    for (int i = 0; i < test_byte_array_8ext.length; i++) {
        test_byte_array_8ext[i] = test_byte_array2[ix++];
        test_byte_array_8_16[x++] = test_byte_array2[ix++];
        test_byte_array_8_16[x++] = test_byte_array2[ix++];
    }
    buffer16_8 = new ModelByteBuffer(test_byte_array_8_16);
    buffer8 = new ModelByteBuffer(test_byte_array_8ext);

    AudioInputStream ais = new AudioInputStream(buffer.getInputStream(), format, testarray.length);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    AudioSystem.write(ais, AudioFileFormat.Type.WAVE, baos);
    buffer_wave = new ModelByteBuffer(baos.toByteArray());
}
 
Example 30
Source Project: native-obfuscator   Source File: Test.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Character encodeDecode(Character character) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(out);
    encoder.writeObject(character);
    encoder.close();
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    return (Character)new XMLDecoder(in).readObject();

}