java.io.ByteArrayInputStream Java Examples

The following examples show how to use java.io.ByteArrayInputStream. 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
Source File: ComparableObjectSeriesTests.java    From astor with GNU General Public License v2.0 7 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {
    MyComparableObjectSeries s1 = new MyComparableObjectSeries("A");
    s1.add(new Integer(1), "ABC");
    MyComparableObjectSeries s2 = null;
    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(s1);
        out.close();

        ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray()));
        s2 = (MyComparableObjectSeries) in.readObject();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(s1, s2);
}
 
Example #2
Source File: WebsocketClientUtil.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public SignRequest createSignRequest(String method, IpPort ipPort, RequestParam requestParam, String url,
    Map<String, String> headers) {
  SignRequest signReq = new SignRequest();
  StringBuilder endpoint = new StringBuilder("https://" + ipPort.getHostOrIp());
  endpoint.append(":" + ipPort.getPort());
  endpoint.append(url);
  try {
    signReq.setEndpoint(new URI(endpoint.toString()));
  } catch (URISyntaxException e) {
    LOGGER.error("set uri failed, uri is {}, message: {}", endpoint.toString(), e.getMessage());
  }
  signReq.setContent((requestParam.getBody() != null && requestParam.getBody().length > 0)
      ? new ByteArrayInputStream(requestParam.getBody())
      : null);
  signReq.setHeaders(headers);
  signReq.setHttpMethod(method);
  signReq.setQueryParams(requestParam.getQueryParamsMap());
  return signReq;
}
 
Example #3
Source File: XmiParserIT.java    From pentaho-metadata with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testMissingDescriptionRef() throws Exception {
  XmiParser parser = new XmiParser();
  Domain domain = parser.parseXmi( getClass().getResourceAsStream( "/missing_ref.xmi" ) );

  String xmi = parser.generateXmi( domain );

  ByteArrayInputStream is = new ByteArrayInputStream( xmi.getBytes() );
  Domain domain2 = parser.parseXmi( is );

  ByteArrayInputStream is2 = new ByteArrayInputStream( parser.generateXmi( domain2 ).getBytes() );
  Domain domain3 = parser.parseXmi( is2 );

  String xml1 = serializeWithOrderedHashmaps( domain2 );
  String xml2 = serializeWithOrderedHashmaps( domain3 );

  // note: this does not verify security objects at this time
  assertEquals( xml1, xml2 );
}
 
Example #4
Source File: NewPrimitiveTypesTest.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
public void testBlobSerialization() throws Exception {

    // create FS
    createExampleFS(cas);

    // serialize
    ByteArrayOutputStream fos = new ByteArrayOutputStream();
    Serialization.serializeCAS(cas, fos);

    // reset
    cas.reset();

    // deserialize
    ByteArrayInputStream fis = new ByteArrayInputStream(fos.toByteArray());
    Serialization.deserializeCAS(cas, fis);

    // check values
    validateFSData(cas);
  }
 
Example #5
Source File: WSDLCustomParser.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private boolean parseWSDLContent(String content, boolean sendMessages) {
    if (content == null || content.trim().length() <= 0) {
        return false;
    } else {
        // WSDL parsing.
        WSDLParser parser = new WSDLParser();
        try {
            InputStream contentI = new ByteArrayInputStream(content.getBytes("UTF-8"));
            Definitions wsdl = parser.parse(contentI);
            contentI.close();
            parseWSDL(wsdl, sendMessages);
            return true;
        } catch (Exception e) {
            LOG.error("There was an error while parsing WSDL content. ", e);
            return false;
        }
    }
}
 
Example #6
Source File: RSA_SHA1.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private PublicKey getPublicKeyFromPem(String pem) 
throws GeneralSecurityException, IOException {

    InputStream stream = new ByteArrayInputStream(
            pem.getBytes("UTF-8"));

    PEMReader reader = new PEMReader(stream);
    byte[] bytes = reader.getDerBytes(); 	
    PublicKey pubKey;

    if (PEMReader.PUBLIC_X509_MARKER.equals(reader.getBeginMarker())) {
        KeySpec keySpec = new X509EncodedKeySpec(bytes);
        KeyFactory fac = KeyFactory.getInstance("RSA");
        pubKey = fac.generatePublic(keySpec);
    } else if (PEMReader.CERTIFICATE_X509_MARKER.equals(reader.getBeginMarker())) {
        pubKey = getPublicKeyFromDerCert(bytes);
    } else {
        throw new IOException("Invalid PEM fileL: Unknown marker for " + 
                " public key or cert " + reader.getBeginMarker());
    }

    return pubKey;
}
 
Example #7
Source File: VectorDataItemTests.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {
    VectorDataItem v1 = new VectorDataItem(1.0, 2.0, 3.0, 4.0);
    VectorDataItem v2 = null;
    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(v1);
        out.close();

        ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray()));
        v2 = (VectorDataItem) in.readObject();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(v1, v2);
}
 
Example #8
Source File: PEncryption.java    From appcan-android with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 加密解密
 *
 * @param pBuffer 要加密或者 要解密的 字节流
 * @param n       要加密或者 要解密的 字节流的大小
 * @param pKey    加密解密的key
 * @param nKeyLen key 的长度
 * @return 返回加密后或者 解密后的字节流
 */
public static byte[] os_decrypt(byte[] pBuffer, int n, String pKey) {
    // PBytes pBytes = new PBytes(pBuffer);
    ByteArrayInputStream in = new ByteArrayInputStream(pBuffer);
    int[] newInt = new int[in.available()];
    int[] resInt = new int[in.available()];
    int ch;
    int i = 0;
    while ((ch = in.read()) != -1) {
        newInt[i] = ch;
        i++;
    }
    RC4(newInt, n, resInt, pKey);
    byte[] newData = new byte[n];
    for (int k = 0; k < n; k++) {
        newData[k] = (byte) resInt[k];
    }
    return newData;
}
 
Example #9
Source File: MessageReaderTest.java    From amazon-kinesis-client with Apache License 2.0 6 votes vote down vote up
private InputStream buildInputStreamOfGoodInput(String[] sequenceNumbers, String[] responseFors) {
    // Just interlace the lines
    StringBuilder stringBuilder = new StringBuilder();
    // This is just a reminder to anyone who changes the arrays
    Assert.assertTrue(responseFors.length == sequenceNumbers.length + 1);
    stringBuilder.append(buildStatusLine(responseFors[0]));
    stringBuilder.append("\n");
    // Also a white space line, which it should be able to handle with out failing.
    stringBuilder.append("    \n");
    // Also a bogus data line, which it should be able to handle with out failing.
    stringBuilder.append("  bogus data  \n");
    for (int i = 0; i < Math.min(sequenceNumbers.length, responseFors.length); i++) {
        stringBuilder.append(buildCheckpointLine(sequenceNumbers[i]));
        stringBuilder.append("\n");
        stringBuilder.append(buildStatusLine(responseFors[i + 1]));
        stringBuilder.append("\n");
    }

    return new ByteArrayInputStream(stringBuilder.toString().getBytes());
}
 
Example #10
Source File: AbstractSerializationTest.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@Test
public void test_Bool() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeBool(false);
    objectOutput.flushBuffer();

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);

    assertFalse(deserialize.readBool());

    try {
        deserialize.readBool();
        fail();
    } catch (IOException expected) {
    }
}
 
Example #11
Source File: GridFsTests.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldStoreAndReadFile() throws IOException {

	byte[] bytes;
	try (InputStream is = new BufferedInputStream(new ClassPathResource("./example-file.txt").getInputStream())) {
		bytes = StreamUtils.copyToByteArray(is);
	}

	// store file
	gridFsOperations.store(new ByteArrayInputStream(bytes), "example-file.txt");

	GridFsResource resource = gridFsOperations.getResource("example-file.txt");

	byte[] loaded;
	try (InputStream is = resource.getInputStream()) {
		loaded = StreamUtils.copyToByteArray(is);
	}

	assertThat(bytes).isEqualTo(loaded);
}
 
Example #12
Source File: CatalogScanOsgiTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
static void installJavaScanningMoreEntitiesV2(ManagementContext mgmt, Object context) throws FileNotFoundException {
    // scanning bundle functionality added in 0.12.0, relatively new compared to non-osgi scanning
    
    TestResourceUnavailableException.throwIfResourceUnavailable(context.getClass(), OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    TestResourceUnavailableException.throwIfResourceUnavailable(context.getClass(), OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V2_PATH);
    
    CampYamlLiteTest.installWithoutCatalogBom(mgmt, OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    
    BundleMaker bm = new BundleMaker(mgmt);
    File f = Os.newTempFile(context.getClass(), "jar");
    Streams.copy(ResourceUtils.create(context).getResourceFromUrl(OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V2_PATH), new FileOutputStream(f));
    f = bm.copyRemoving(f, MutableSet.of("catalog.bom"));
    f = bm.copyAdding(f, MutableMap.of(new ZipEntry("catalog.bom"),
        new ByteArrayInputStream( Strings.lines(
            "brooklyn.catalog:",
            "  scanJavaAnnotations: true").getBytes() ) ));
    
    ((ManagementContextInternal)mgmt).getOsgiManager().get().install(new FileInputStream(f)).checkNoError();
}
 
Example #13
Source File: HDFSConfigJUnitTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Validates if hdfs store conf is getting complety and correctly parsed
 */
public void testHdfsStoreConfFullParsing() {
  String conf = createStoreConf(null, "123");
  this.c.loadCacheXml(new ByteArrayInputStream(conf.getBytes()));
  HDFSStoreImpl store = ((GemFireCacheImpl)this.c).findHDFSStore("store");
  assertEquals("namenode url mismatch.", "url", store.getNameNodeURL());
  assertEquals("home-dir mismatch.", "dir", store.getHomeDir());
  assertEquals("hdfs-client-config-file mismatch.", "client", store.getHDFSClientConfigFile());
  assertEquals("block-cache-size mismatch.", 24.5f, store.getBlockCacheSize());
  
  HDFSCompactionConfig compactConf = store.getHDFSCompactionConfig();
  assertEquals("compaction strategy mismatch.", "size-oriented", compactConf.getCompactionStrategy());
  assertFalse("compaction auto-compact mismatch.", compactConf.getAutoCompaction());
  assertTrue("compaction auto-major-compact mismatch.", compactConf.getAutoMajorCompaction());
  assertEquals("compaction max-input-file-size mismatch.", 123, compactConf.getMaxInputFileSizeMB());
  assertEquals("compaction min-input-file-count.", 9, compactConf.getMinInputFileCount());
  assertEquals("compaction max-input-file-count.", 1234, compactConf.getMaxInputFileCount());
  assertEquals("compaction max-concurrency", 23, compactConf.getMaxThreads());
  assertEquals("compaction max-major-concurrency", 27, compactConf.getMajorCompactionMaxThreads());
  assertEquals("compaction major-interval", 781, compactConf.getMajorCompactionIntervalMins());
  assertEquals("compaction major-interval", 711, compactConf.getOldFilesCleanupIntervalMins());
}
 
Example #14
Source File: SignIn.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void showFacebookUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.3/me");
    req.addArgumentNoEncoding("access_token", token);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("name");
    d.dispose();
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), "https://graph.facebook.com/v2.3/me/picture?access_token=" + token);
    userForm.show();
}
 
Example #15
Source File: ClientEntitySetIterator.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private ResWrap<Entity> nextAtomEntityFromEntitySet(
        final InputStream input, final OutputStream osEntitySet, final String namespaces) {

  final ByteArrayOutputStream entity = new ByteArrayOutputStream();

  ResWrap<Entity> atomEntity = null;

  try {
    if (consume(input, "<entry>", osEntitySet, false) >= 0) {
      entity.write("<entry ".getBytes(Constants.UTF8));
      entity.write(namespaces.getBytes(Constants.UTF8));
      entity.write(">".getBytes(Constants.UTF8));

      if (consume(input, "</entry>", entity, true) >= 0) {
        atomEntity = odataClient.getDeserializer(ContentType.APPLICATION_ATOM_XML).
                toEntity(new ByteArrayInputStream(entity.toByteArray()));
      }
    }
  } catch (Exception e) {
    LOG.error("Error retrieving entities from EntitySet", e);
  }

  return atomEntity;
}
 
Example #16
Source File: AbstractSerializationTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
<T> void assertObjectArray(T[] data, Class<T[]> clazz) throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(data);
    objectOutput.flushBuffer();

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);

    assertArrayEquals(data, clazz.cast(deserialize.readObject()));

    try {
        deserialize.readObject();
        fail();
    } catch (IOException expected) {
    }
}
 
Example #17
Source File: AbstractSerializationTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void test_charArray_withType() throws Exception {
    char[] data = new char[] { 'a', '中', '无' };
    
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(data);
    objectOutput.flushBuffer();
    
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
    
    assertArrayEquals(data, (char[]) deserialize.readObject(char[].class));
    
    try {
        deserialize.readObject(char[].class);
        fail();
    } catch (IOException expected) {
    }
}
 
Example #18
Source File: BundleMakerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCopyRemovingItems() throws Exception {
    tempJar = bundleMaker.copyAdding(emptyJar, ImmutableMap.of(
            new ZipEntry("myfile.txt"), new ByteArrayInputStream("mytext".getBytes()),
            new ZipEntry("myfile2.txt"), new ByteArrayInputStream("mytext2".getBytes())));
    generatedJar = bundleMaker.copyRemoving(tempJar, ImmutableSet.of("myfile.txt"));
    assertJarContents(generatedJar, ImmutableMap.of("myfile2.txt", "mytext2"), false);
}
 
Example #19
Source File: FileCopyUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Copy the contents of the given byte array to the given output File.
 * @param in the byte array to copy from
 * @param out the file to copy to
 * @throws IOException in case of I/O errors
 */
public static void copy(byte[] in, File out) throws IOException {
	Assert.notNull(in, "No input byte array specified");
	Assert.notNull(out, "No output File specified");
	ByteArrayInputStream inStream = new ByteArrayInputStream(in);
	OutputStream outStream = new BufferedOutputStream(new FileOutputStream(out));
	copy(inStream, outStream);
}
 
Example #20
Source File: JacksonProcessorTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertXMLContent() throws Exception {
    String input = "<user><id>1</id><name>fehguy</name></user>";

    EntityProcessorFactory.addProcessor(JacksonProcessor.class, MediaType.APPLICATION_XML_TYPE);

    InputStream is = new ByteArrayInputStream(input.getBytes());
    ObjectNode o = (ObjectNode) EntityProcessorFactory.readValue(MediaType.APPLICATION_XML_TYPE, is, JsonNode.class);
    assertEquals(o.getClass(), ObjectNode.class);
    assertEquals(o.get("name").asText(), "fehguy");
}
 
Example #21
Source File: JaxbUtils.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public static RR toRR(byte[] rr) throws JAXBException, SAXException {
	init();
	Unmarshaller jaxbUnmarshaller = jaxbRrErContext.createUnmarshaller();
	jaxbUnmarshaller.setSchema(RR_ER_schema);
	JAXBElement<RR> root = jaxbUnmarshaller.unmarshal(new StreamSource(new ByteArrayInputStream(rr)), RR.class);
	return root.getValue();
}
 
Example #22
Source File: JRReportTemplate.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
public static JRReportTemplate getJRReportTemplate(String jrxmlTemplate) throws JRException, IOException {

		InputStream isTemplate = new ByteArrayInputStream(jrxmlTemplate.getBytes(StandardCharsets.UTF_8));
		JRReportTemplate reportTemplate = (JRReportTemplate) JasperCompileManager.compileReport(isTemplate);

		if (isTemplate != null) {
			isTemplate.close();
		}

		return reportTemplate;
	}
 
Example #23
Source File: Serialization.java    From native-obfuscator with GNU General Public License v3.0 5 votes vote down vote up
private static HashSet<Integer> serDeser(HashSet<Integer> hashSet) throws IOException, ClassNotFoundException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(hashSet);
    oos.flush();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bais);
    HashSet<Integer> result = (HashSet<Integer>)ois.readObject();

    oos.close();
    ois.close();

    return result;
}
 
Example #24
Source File: ByteArrayImageSource.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
protected ImageDecoder getDecoder() {
    InputStream is =
        new BufferedInputStream(new ByteArrayInputStream(imagedata,
                                                         imageoffset,
                                                         imagelength));
    return getDecoder(is);
}
 
Example #25
Source File: SerializationUtils.java    From appengine-pipelines with Apache License 2.0 5 votes vote down vote up
public static Object deserialize(byte[] bytes) throws IOException {
  if (bytes.length < 2) {
    throw new IOException("Invalid bytes content");
  }
  InputStream in = new ByteArrayInputStream(bytes);
  if (bytes[0] == 0) {
    in.read(); // consume the marker;
    if (in.read() != ZLIB_COMPRESSION) {
      throw new IOException("Unknown compression type");
    }
    final Inflater inflater =  new Inflater(true);
    in = new InflaterInputStream(in, inflater) {
      @Override public void close() throws IOException {
        try {
          super.close();
        } finally {
          inflater.end();
        }
      }
    };
  }
  try (ObjectInputStream oin = new ObjectInputStream(in)) {
    try {
      return oin.readObject();
    } catch (ClassNotFoundException e) {
      throw new IOException("Exception while deserilaizing.", e);
    }
  }
}
 
Example #26
Source File: PDFSigner.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 
 * Faz a leitura do token em LINUX, precisa setar a lib (.SO) e a senha do token.
 */
@SuppressWarnings("restriction")
private KeyStore getKeyStoreToken() {

	try {
		// ATENÇÃO ALTERAR CONFIGURAÇÃO ABAIXO CONFORME O TOKEN USADO

		// Para TOKEN Branco a linha abaixo
		// String pkcs11LibraryPath =
		// "/usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so";

		// Para TOKEN Azul a linha abaixo
		String pkcs11LibraryPath = "/usr/lib/libeToken.so";

		StringBuilder buf = new StringBuilder();
		buf.append("library = ").append(pkcs11LibraryPath).append("\nname = Provedor\n");
		Provider p = new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(buf.toString().getBytes()));
		Security.addProvider(p);
		// ATENÇÃO ALTERAR "SENHA" ABAIXO
		Builder builder = KeyStore.Builder.newInstance("PKCS11", p,	new KeyStore.PasswordProtection("senha".toCharArray()));
		KeyStore ks;
		ks = builder.getKeyStore();

		return ks;

	} catch (Exception e1) {
		e1.printStackTrace();
		return null;
	} finally {
	}

}
 
Example #27
Source File: GetMessageListMethodTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Category(BasicFeature.class)
@Test
public void getMessageListShouldReturnAllMessagesOfCurrentUserOnlyWhenMultipleMailboxesAndNoParameters() throws Exception {
    String otherUser = "other@" + DOMAIN;
    String password = "password";
    dataProbe.addUser(otherUser, password);

    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, ALICE.asString(), "mailbox");
    ComposedMessageId message1 = mailboxProbe.appendMessage(ALICE.asString(), ALICE_MAILBOX,
            new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()), new Date(), false, new Flags());

    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, ALICE.asString(), "mailbox2");
    ComposedMessageId message2 = mailboxProbe.appendMessage(ALICE.asString(), MailboxPath.forUser(ALICE, "mailbox2"),
            new ByteArrayInputStream("Subject: test2\r\n\r\ntestmail".getBytes()), new Date(), false, new Flags());
    await();

    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, otherUser, "mailbox");
    mailboxProbe.appendMessage(otherUser, MailboxPath.forUser(Username.of(otherUser), "mailbox"),
            new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()), new Date(), false, new Flags());
    await();

    given()
        .header("Authorization", aliceAccessToken.asString())
        .body("[[\"getMessageList\", {}, \"#0\"]]")
    .when()
        .post("/jmap")
    .then()
        .statusCode(200)
        .body(NAME, equalTo("messageList"))
        .body(ARGUMENTS + ".messageIds", containsInAnyOrder(message1.getMessageId().serialize(), message2.getMessageId().serialize()));
}
 
Example #28
Source File: TestWebXmlParser.java    From HttpSessionReplacer with MIT License 5 votes vote down vote up
@Test
public void testDistributable() throws IOException {
  String webXml = Descriptors.create(WebAppDescriptor.class).version("3.0").distributable().exportAsString();
  try (ByteArrayInputStream bais = new ByteArrayInputStream(webXml.getBytes("UTF-8"))) {
    SessionConfiguration sessionConfiguration = new SessionConfiguration();
    sessionConfiguration.setDistributable(false);
    WebXmlParser.parseStream(sessionConfiguration, bais);
    assertEquals(1800, sessionConfiguration.getMaxInactiveInterval());
    assertTrue(sessionConfiguration.isDistributable());
  }
}
 
Example #29
Source File: ClusterTest.java    From terracotta-platform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> T copy(T o) throws IOException, ClassNotFoundException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(baos);
  oos.writeObject(o);
  oos.close();
  ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
  return (T) in.readObject();
}
 
Example #30
Source File: TestFlushableGZIPOutputStream.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Writes data to the stream and returns the size of the file.
 */
private void flowBytes(byte[] bytes, OutputStream output)
        throws IOException {
    // Could use output.write(), but IOTools writes in small portions, and
    // that is more natural
    ByteArrayInputStream byteInStream = new ByteArrayInputStream(bytes);
    try {
        IOTools.flow(byteInStream, output);
    } finally {
        byteInStream.close();
    }
}