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 |
/** * 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: AbstractSerializationTest.java From dubbox with Apache License 2.0 | 6 votes |
@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 #3
Source File: WSDLCustomParser.java From zap-extensions with Apache License 2.0 | 6 votes |
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 #4
Source File: WebsocketClientUtil.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
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 #5
Source File: NewPrimitiveTypesTest.java From uima-uimaj with Apache License 2.0 | 6 votes |
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 #6
Source File: RSA_SHA1.java From sakai with Educational Community License v2.0 | 6 votes |
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 |
/** * 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 |
/** * 加密解密 * * @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 |
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: GridFsTests.java From spring-data-examples with Apache License 2.0 | 6 votes |
@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 #11
Source File: XmiParserIT.java From pentaho-metadata with GNU Lesser General Public License v2.1 | 6 votes |
@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 #12
Source File: AbstractSerializationTest.java From dubbo-2.6.5 with Apache License 2.0 | 6 votes |
<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 #13
Source File: ClientEntitySetIterator.java From olingo-odata4 with Apache License 2.0 | 6 votes |
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 #14
Source File: HDFSConfigJUnitTest.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * 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 #15
Source File: CatalogScanOsgiTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
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 #16
Source File: SignIn.java From CodenameOne with GNU General Public License v2.0 | 6 votes |
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 #17
Source File: AbstractSerializationTest.java From dubbox-hystrix with Apache License 2.0 | 6 votes |
@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 #18
Source File: PassBooleanByValueBinaryTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public void testSerializeDeserializeUsingUtils() throws IOException, ClassNotFoundException { // Write final ByteArrayOutputStream baos = new ByteArrayOutputStream(111); final DataOutputStream dos = new DataOutputStream(baos); SerializerUtils.writeBinary(dos, binary); dos.flush(); // Read final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final DataInputStream dis = new DataInputStream(bais); final Binary newBinary = SerializerUtils.readBinary(dis); assertEquals(binary, newBinary); }
Example #19
Source File: StreamsTest.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** * Test method for * {@link com.google.api.ads.common.lib.utils.Streams#readAll(java.io.InputStream)}. */ @SuppressWarnings({"deprecation", "javadoc"}) @Test public void testReadAll() throws Exception { String testString = "Testing©ÿ»"; String actual = Streams.readAll(new ByteArrayInputStream(testString.getBytes(Charset.defaultCharset()))); String expected = new String(testString.getBytes(Charset.defaultCharset()), Charset.defaultCharset()); assertEquals(expected, actual); }
Example #20
Source File: CertTest.java From julongchain with Apache License 2.0 | 5 votes |
@Test public void cryptogenCertTest() throws IOException, CspException { String skPath = "msp/keystore"; String signcerts = "msp/signcerts"; String testData = "this is test data"; //签名证书 List<byte[]> signCerts = new LoadLocalMspFiles().getCertFromDir(signcerts); Certificate signCert = Certificate.getInstance( new PemReader(new InputStreamReader(new ByteArrayInputStream(signCerts.get(0)))).readPemObject().getContent()); byte[] publickey = signCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); List<byte[]> sks = new LoadLocalMspFiles().getSkFromDir(skPath); byte[] sign = sm2.sign(sks.get(0), testData.getBytes()); boolean result = sm2.verify(publickey, sign, testData.getBytes()); assertEquals(true, result); }
Example #21
Source File: SybasePlatform.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ protected void setStatementParameterValue(PreparedStatement statement, int sqlIndex, int typeCode, Object value) throws SQLException { if ((typeCode == Types.BLOB) || (typeCode == Types.LONGVARBINARY)) { // jConnect doesn't like the BLOB type, but works without problems with LONGVARBINARY // even when using the Blob class if (value instanceof byte[]) { byte[] data = (byte[])value; statement.setBinaryStream(sqlIndex, new ByteArrayInputStream(data), data.length); } else { // Sybase doesn't like the BLOB type, but works without problems with LONGVARBINARY // even when using the Blob class super.setStatementParameterValue(statement, sqlIndex, Types.LONGVARBINARY, value); } } else if (typeCode == Types.CLOB) { // Same for CLOB and LONGVARCHAR super.setStatementParameterValue(statement, sqlIndex, Types.LONGVARCHAR, value); } else { super.setStatementParameterValue(statement, sqlIndex, typeCode, value); } }
Example #22
Source File: MvtBuildTest.java From mapbox-vector-tile-java with Apache License 2.0 | 5 votes |
@Test public void testPolygon() throws IOException { // Create input geometry final GeometryFactory geomFactory = new GeometryFactory(); final Geometry inputGeom = buildPolygon(RANDOM, 200, geomFactory); // Build tile envelope - 1 quadrant of the world final Envelope tileEnvelope = new Envelope(0d, WORLD_SIZE * .5d, 0d, WORLD_SIZE * .5d); // Build MVT tile geometry final TileGeomResult tileGeom = JtsAdapter.createTileGeom(inputGeom, tileEnvelope, geomFactory, DEFAULT_MVT_PARAMS, ACCEPT_ALL_FILTER); // Create MVT layer final VectorTile.Tile mvt = encodeMvt(DEFAULT_MVT_PARAMS, tileGeom); // MVT Bytes final byte[] bytes = mvt.toByteArray(); assertNotNull(bytes); JtsMvt expected = new JtsMvt(singletonList(new JtsLayer(TEST_LAYER_NAME, tileGeom.mvtGeoms))); // Load multipolygon z0 tile JtsMvt actual = MvtReader.loadMvt( new ByteArrayInputStream(bytes), new GeometryFactory(), new TagKeyValueMapConverter()); // Check that MVT geometries are the same as the ones that were encoded above assertEquals(expected, actual); }
Example #23
Source File: AbstractSerializationTest.java From dubbox with Apache License 2.0 | 5 votes |
@Test public void test_BizExceptionNoDefaultConstructor() throws Exception { BizExceptionNoDefaultConstructor e = new BizExceptionNoDefaultConstructor("Hello"); ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); objectOutput.writeObject(e); objectOutput.flushBuffer(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( byteArrayOutputStream.toByteArray()); ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream); Object read = deserialize.readObject(); assertEquals("Hello", ((BizExceptionNoDefaultConstructor) read).getMessage()); }
Example #24
Source File: CertificateUtils.java From product-microgateway with Apache License 2.0 | 5 votes |
/** * Used to get the certificate alias for a certificate which is get from header send by payload. */ public static String getAliasFromTrustStore(X509Certificate certificate, KeyStore truststore) throws java.security.cert.CertificateException, CertificateEncodingException, KeyStoreException { KeyStore trustStore = truststore; CertificateFactory cf = CertificateFactory.getInstance("X.509"); byte[] certificateEncoded = certificate.getEncoded(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(certificateEncoded); java.security.cert.X509Certificate x509Certificate = (java.security.cert.X509Certificate) cf.generateCertificate(byteArrayInputStream); x509Certificate.checkValidity(); String certificateAlias = trustStore.getCertificateAlias(x509Certificate); return certificateAlias; }
Example #25
Source File: JacksonProcessorTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@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 #26
Source File: JaxbUtils.java From govpay with GNU General Public License v3.0 | 5 votes |
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 #27
Source File: Serialization.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
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 #28
Source File: RevisionTest.java From yangtools with Eclipse Public License 1.0 | 5 votes |
@Test public void testSerialization() throws IOException, ClassNotFoundException { final Revision source = Revision.of("2017-12-25"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(bos)) { oos.writeObject(source); } final Object read; try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))) { read = ois.readObject(); } assertEquals(source, read); }
Example #29
Source File: FileBlock.java From incubator-nemo with Apache License 2.0 | 5 votes |
/** * Retrieves the partitions of this block from the file in a specific key range and deserializes it. * * @param keyRange the key range. * @return an iterable of {@link NonSerializedPartition}s. * @throws BlockFetchException for any error occurred while trying to fetch a block. */ @Override public Iterable<NonSerializedPartition<K>> readPartitions(final KeyRange keyRange) { if (!metadata.isCommitted()) { throw new BlockFetchException(new Throwable(CANNOT_RETRIEVE_BEFORE_COMMITED)); } else { // Deserialize the data final List<NonSerializedPartition<K>> deserializedPartitions = new ArrayList<>(); try { final List<Pair<K, byte[]>> partitionKeyBytesPairs = new ArrayList<>(); try (FileInputStream fileStream = new FileInputStream(filePath)) { for (final PartitionMetadata<K> partitionMetadata : metadata.getPartitionMetadataList()) { final K key = partitionMetadata.getKey(); if (keyRange.includes(key)) { // The key value of this partition is in the range. final byte[] partitionBytes = new byte[partitionMetadata.getPartitionSize()]; fileStream.read(partitionBytes, 0, partitionMetadata.getPartitionSize()); partitionKeyBytesPairs.add(Pair.of(key, partitionBytes)); } else { // Have to skip this partition. skipBytes(fileStream, partitionMetadata.getPartitionSize()); } } } for (final Pair<K, byte[]> partitionKeyBytes : partitionKeyBytesPairs) { final NonSerializedPartition<K> deserializePartition = DataUtil.deserializePartition( partitionKeyBytes.right().length, serializer, partitionKeyBytes.left(), new ByteArrayInputStream(partitionKeyBytes.right())); deserializedPartitions.add(deserializePartition); } } catch (final IOException e) { throw new BlockFetchException(e); } return deserializedPartitions; } }
Example #30
Source File: JRReportTemplate.java From opencps-v2 with GNU Affero General Public License v3.0 | 5 votes |
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; }