Java Code Examples for java.io.ByteArrayInputStream

The following are top voted examples for showing how to use java.io.ByteArrayInputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Melophile   File: BundleUtils.java   Source Code and License 7 votes vote down vote up
public static String decompress(byte[] compressed) {
    if(compressed==null) return null;
    ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
    try {
        GZIPInputStream gis = new GZIPInputStream(bis);
        BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        gis.close();
        bis.close();
        return sb.toString();
    }catch (IOException ex){
        ex.printStackTrace();
    }
    return null;
}
 
Example 2
Project: wangmarket   File: TemplateController.java   Source Code and License 7 votes vote down vote up
/**
 * 导出当前网站当前的模版文件,包含模版页面,模版变量、栏目
 * @throws FileNotFoundException
 * @throws UnsupportedEncodingException
 */
@RequestMapping("exportTemplate")
public void exportTemplate(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, UnsupportedEncodingException {
	BaseVO vo = templateService.exportTemplate(request);
	String fileName = "template"+DateUtil.currentDate("yyyyMMdd_HHmm")+".wscso".toString(); // 文件的默认保存名
	//读到流中
	InputStream inStream = new ByteArrayInputStream(vo.getInfo().getBytes("UTF-8"));  
	
	AliyunLog.addActionLog(getSiteId(), "导出当前网站当前的模版文件");
	
	// 设置输出的格式
	response.reset();
	response.setContentType("bin");
	response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
	byte[] b = new byte[1000];
	int len;
	try {
	    while ((len = inStream.read(b)) > 0)
	        response.getOutputStream().write(b, 0, len);
	    inStream.close();
	} catch (IOException e) {
	    e.printStackTrace();
	}
}
 
Example 3
Project: PeSanKita-android   File: MediaConstraints.java   Source Code and License 6 votes vote down vote up
public MediaStream getResizedMedia(@NonNull Context context,
                                   @NonNull MasterSecret masterSecret,
                                   @NonNull Attachment attachment)
    throws IOException
{
  if (!canResize(attachment)) {
    throw new UnsupportedOperationException("Cannot resize this content type");
  }

  try {
    // XXX - This is loading everything into memory! We want the send path to be stream-like.
    return new MediaStream(new ByteArrayInputStream(BitmapUtil.createScaledBytes(context, new DecryptableUri(masterSecret, attachment.getDataUri()), this)),
                           ContentType.IMAGE_JPEG);
  } catch (BitmapDecodingException e) {
    throw new IOException(e);
  }
}
 
Example 4
Project: openjdk-jdk10   File: LoadAndStoreXML.java   Source Code and License 6 votes vote down vote up
/**
 * Test loadFromXML with a document that does not have an encoding declaration
 */
static void testLoadWithoutEncoding() throws IOException {
    System.out.println("testLoadWithoutEncoding");

    Properties expected = new Properties();
    expected.put("foo", "bar");

    String s = "<?xml version=\"1.0\"?>" +
               "<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">" +
               "<properties>" +
               "<entry key=\"foo\">bar</entry>" +
               "</properties>";
    ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes("UTF-8"));
    Properties props = new Properties();
    props.loadFromXML(in);

    if (!props.equals(expected)) {
        System.err.println("loaded: " + props + ", expected: " + expected);
        throw new RuntimeException("Test failed");
    }
}
 
Example 5
Project: Guardian.java   File: TransactionTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldSerializeCorrectly() throws Exception {
    Transaction transaction = new Transaction("TRANSACTION_TOKEN", "RECOVERY_CODE", "OTP_SECRET");

    // save
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(transaction);
    objectOutputStream.close();
    outputStream.close();

    byte[] binaryData = outputStream.toByteArray();

    // restore
    ByteArrayInputStream inputStream = new ByteArrayInputStream(binaryData);
    ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
    Transaction restoredTransaction = (Transaction) objectInputStream.readObject();
    objectInputStream.close();
    inputStream.close();

    assertThat(restoredTransaction.getTransactionToken(), is(equalTo("TRANSACTION_TOKEN")));
    assertThat(restoredTransaction.getRecoveryCode(), is(equalTo("RECOVERY_CODE")));
}
 
Example 6
Project: redis-client   File: CacheUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * 功能描述:自己数组转换成对象 <br>
 * 〈功能详细描述〉
 * 
 * @param bytes
 *            bytes
 * @return object
 * @throws IOException
 *             ioexception
 * @see [相关类/方法](可选)
 * @since [产品/模块版本](可选)
 */
public static Object byteArrayToObject(byte[] bytes) throws IOException {
    if (bytes == null || bytes.length <= 0) {
        return null;
    }
    Object obj = null;
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bis));
        obj = ois.readObject();
        bis.close();
        ois.close();
    } catch (ClassNotFoundException e) {
        logger.error(e.getMessage());
    }
    return obj;
}
 
Example 7
Project: parabuild-ci   File: SignalRendererTests.java   Source Code and License 6 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {

    SignalRenderer r1 = new SignalRenderer();
    SignalRenderer r2 = null;

    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(r1);
        out.close();

        ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
        r2 = (SignalRenderer) in.readObject();
        in.close();
    }
    catch (Exception e) {
        System.out.println(e.toString());
    }
    assertEquals(r1, r2);

}
 
Example 8
Project: FlashLib   File: CameraViewer.java   Source Code and License 6 votes vote down vote up
@Override
public void newData(byte[] bytes) {
	if(Dashboard.visionInitialized()){
		Mat m = CvProcessing.byteArray2Mat(bytes);
		Dashboard.setForVision(m);
	}
	if(mode == DisplayMode.Normal){
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpeg");
 
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; 
       
		try {
			ImageInputStream iis = ImageIO.createImageInputStream(source); 
		    reader.setInput(iis, true);
		    ImageReadParam param = reader.getDefaultReadParam();
		    BufferedImage image = reader.read(0, param); 
		    setImage(image);
		} catch (IOException e) {
		}
	}

}
 
Example 9
Project: gradle-s3-build-cache   File: AwsS3BuildCacheService.java   Source Code and License 6 votes vote down vote up
@Override
public void store(BuildCacheKey key, BuildCacheEntryWriter writer) {
  logger.info("Start storing cache entry '{}' in S3 bucket", key.getHashCode());
  ObjectMetadata meta = new ObjectMetadata();
  meta.setContentType(BUILD_CACHE_CONTENT_TYPE);

  try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
    writer.writeTo(os);
    meta.setContentLength(os.size());
    try (InputStream is = new ByteArrayInputStream(os.toByteArray())) {
        PutObjectRequest request = getPutObjectRequest(key, meta, is);
        if(this.reducedRedundancy) {
          request.withStorageClass(StorageClass.ReducedRedundancy);
        }
        s3.putObject(request);
    }
  } catch (IOException e) {
    throw new BuildCacheException("Error while storing cache object in S3 bucket", e);
  }
}
 
Example 10
Project: parabuild-ci   File: ComparableObjectSeriesTests.java   Source Code and License 6 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 11
Project: powertext   File: RtfTransferable.java   Source Code and License 6 votes vote down vote up
@Override
public Object getTransferData(DataFlavor flavor)
				throws UnsupportedFlavorException, IOException {
	if (flavor.equals(FLAVORS[0])) { // RTF
		return new ByteArrayInputStream(data==null ? new byte[0] : data);
	}
	else if (flavor.equals(FLAVORS[1])) { // stringFlavor
		return data==null ? "" : RtfToText.getPlainText(data);
	}
	else if (flavor.equals(FLAVORS[2])) { // plainTextFlavor (deprecated)
		String text = ""; // Valid if data==null
		if (data!=null) {
			text = RtfToText.getPlainText(data);
		}
		return new StringReader(text);
	}
	else {
		throw new UnsupportedFlavorException(flavor);
	}
}
 
Example 12
Project: curiostack   File: MessageMarshallerTest.java   Source Code and License 6 votes vote down vote up
private void mergeFromJson(
    String json, boolean ignoringUnknownFields, Builder builder, Message... additionalTypes)
    throws IOException {
  MessageMarshaller.Builder marshallerBuilder =
      MessageMarshaller.builder()
          .register(builder.getDefaultInstanceForType())
          .ignoringUnknownFields(ignoringUnknownFields);
  for (Message prototype : additionalTypes) {
    marshallerBuilder.register(prototype);
  }
  MessageMarshaller marshaller = marshallerBuilder.build();
  marshaller.mergeValue(json, builder);

  Message.Builder builder2 = builder.build().newBuilderForType();
  marshaller.mergeValue(json.getBytes(StandardCharsets.UTF_8), builder2);
  assertThat(builder2.build()).isEqualTo(builder.build());

  Message.Builder builder3 = builder.build().newBuilderForType();
  try (ByteArrayInputStream bis =
      new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))) {
    marshaller.mergeValue(bis, builder3);
  }
  assertThat(builder3.build()).isEqualTo(builder.build());
}
 
Example 13
Project: EatDubbo   File: AbstractSerializationTest.java   Source Code and License 6 votes vote down vote up
<T> void assertObjectWithType(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);

    assertEquals(data, (T) deserialize.readObject(clazz));

    try {
        deserialize.readObject(clazz);
        fail();
    } catch (IOException expected) {
    }
}
 
Example 14
Project: gw4e.project   File: ResourceManager.java   Source Code and License 6 votes vote down vote up
/**
 * Create a file in a folder with the specified name and content
 * 
 * @param fullpath
 * @param filename
 * @param content
 * @throws CoreException
 * @throws InterruptedException
 */
public static IFile createFileDeleteIfExists(String fullpath, String filename, String content,
		IProgressMonitor monitor) throws CoreException, InterruptedException {
	SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
	subMonitor.setTaskName("Create file delete if it exists " + fullpath);
	IFile newFile;
	try {
		IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot();
		IContainer container = (IContainer) wroot.findMember(new Path(fullpath));
		newFile = container.getFile(new Path(filename));
		if (newFile.exists()) {
			JDTManager.rename(newFile, new NullProgressMonitor());
			newFile.delete(true, new NullProgressMonitor());
		}
		subMonitor.split(30);
		byte[] source = content.getBytes(Charset.forName("UTF-8"));
		newFile.create(new ByteArrayInputStream(source), true, new NullProgressMonitor());
		subMonitor.split(70);
	} finally {
		subMonitor.done();
	}
	return newFile;
}
 
Example 15
Project: OSchina_resources_android   File: TeamTweetDetailFragment.java   Source Code and License 6 votes vote down vote up
@Override
public void onSuccess(int code, ByteArrayInputStream is, Object[] args) {
    try {
        Result res = XmlUtils.toBean(ResultBean.class, is).getResult();
        if (res.OK()) {
            AppContext.showToastShort(R.string.delete_success);
            mAdapter.removeItem(args[0]);
            // setTweetCommentCount();
        } else {
            AppContext.showToastShort(res.getErrorMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
        onFailure(code, e.getMessage(), args);
    }
}
 
Example 16
Project: ImageLoaderSupportGif   File: BaseImageDownloader.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}).
 *
 * @param imageUri Image URI
 * @param extra    Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link InputStream} of image
 * @throws FileNotFoundException if the provided URI could not be opened
 */
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
	ContentResolver res = context.getContentResolver();

	Uri uri = Uri.parse(imageUri);
	if (isVideoContentUri(uri)) { // video thumbnail
		Long origId = Long.valueOf(uri.getLastPathSegment());
		Bitmap bitmap = MediaStore.Video.Thumbnails
				.getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null);
		if (bitmap != null) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 0, bos);
			return new ByteArrayInputStream(bos.toByteArray());
		}
	} else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo
		return getContactPhotoStream(uri);
	}

	return res.openInputStream(uri);
}
 
Example 17
Project: directory-ldap-api   File: SchemaAwareDnSerializationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test the serialization of a Dn
 *
 * @throws Exception
 */
@Test
public void testNameSerialization() throws Exception
{
    Dn dn = new Dn( schemaManager, "ou= Some   People   + dc=  And   Some anImAls,dc = eXample,dc= cOm" );

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream( baos );

    dn.writeExternal( out );

    byte[] data = baos.toByteArray();
    ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream( data ) );

    Dn dn2 = new Dn( schemaManager );
    dn2.readExternal( in );

    assertEquals( dn, dn2 );
}
 
Example 18
Project: XinFramework   File: ByteArrayOutputStream.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the current contents of this byte stream as a Input Stream. The
 * returned stream is backed by buffers of <code>this</code> stream,
 * avoiding memory allocation and copy, thus saving space and time.<br>
 * 
 * @return the current contents of this output stream.
 * @see java.io.ByteArrayOutputStream#toByteArray()
 * @see #reset()
 * @since 2.0
 */
private InputStream toBufferedInputStream() {
    int remaining = count;
    if (remaining == 0) {
        return new ClosedInputStream();
    }
    List<ByteArrayInputStream> list = new ArrayList<>(buffers.size());
    for (byte[] buf : buffers) {
        int c = Math.min(buf.length, remaining);
        list.add(new ByteArrayInputStream(buf, 0, c));
        remaining -= c;
        if (remaining == 0) {
            break;
        }
    }
    return new SequenceInputStream(Collections.enumeration(list));
}
 
Example 19
Project: raven   File: ImageUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 灏嗗浘鐗囦互width涓哄噯杩涜绛夋瘮缂╂斁
 * 
 * @param imageBytes
 * @param width
 * @param imageFormatName
 * @return
 */
public static byte[] scaleImageByWidth(byte[] imageBytes, int width,
		String imageFormatName) {
	Image img = null;
	int height = 0;
	try {
		img = ImageIO.read(new ByteArrayInputStream(imageBytes));
		int old_w = img.getWidth(null);
		int old_h = img.getHeight(null);
		if (old_h > 0 && old_w > 0) {
			// 浠ュ搴︿负鍑嗭紝璁$畻楂樺害 绛夋瘮缂╂斁
			height = (int) ((float) width / old_w * old_h);
		}
	} catch (Exception e) {
		logger.error("scaleImageByWidth faild!", e);
	}
	return ImageUtils.scaleImage(imageBytes, width, height,
			Image.SCALE_SMOOTH, imageFormatName);
}
 
Example 20
Project: Java-APIs   File: ModelLoader.java   Source Code and License 6 votes vote down vote up
/**
  * Fetch a model from Ontology Editor, load and return as TDB-backed Jena model.
  *
  * @param endpoint
  * @param tDbDirectoryPath
  * @return
* @throws OEConnectionException 
* @throws IOException 
  */
 public static Model loadOEModelToTdb(OEModelEndpoint endpoint, String tDbDirectoryPath) throws IOException, OEConnectionException {
   Preconditions.checkNotNull(endpoint);
   Preconditions.checkArgument(!Strings.isNullOrEmpty(tDbDirectoryPath));

   if (logger.isDebugEnabled()) {
     logger.debug("OEModelEndpoint: {}", endpoint);
     logger.debug("TDB Dir path   : {}", tDbDirectoryPath);
   }

   String modelAsTTL = endpoint.fetchData();

   Dataset dataset = TDBFactory.createDataset(tDbDirectoryPath);
   Model model = dataset.getNamedModel(endpoint.modelIri);
   model.read(new ByteArrayInputStream(modelAsTTL.getBytes()), "TTL");
   return model;
 }
 
Example 21
Project: openjdk-jdk10   File: ZoneInfoFile.java   Source Code and License 6 votes vote down vote up
private static ZoneInfo getZoneInfo0(String zoneId) {
    try {
        ZoneInfo zi = zones.get(zoneId);
        if (zi != null) {
            return zi;
        }
        String zid = zoneId;
        if (aliases.containsKey(zoneId)) {
            zid = aliases.get(zoneId);
        }
        int index = Arrays.binarySearch(regions, zid);
        if (index < 0) {
            return null;
        }
        byte[] bytes = ruleArray[indices[index]];
        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
        zi = getZoneInfo(dis, zid);
        zones.put(zoneId, zi);
        return zi;
    } catch (Exception ex) {
        throw new RuntimeException("Invalid binary time-zone data: TZDB:" +
            zoneId + ", version: " + versionId, ex);
    }
}
 
Example 22
Project: cyberduck   File: CopyWorkerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCopyFile() throws Exception {
    final Path home = new DefaultHomeFinderService(session).find();
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final Path source = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final Path target = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore());
    cryptomator.create(session, null, new VaultCredentials("test"));
    final DefaultVaultRegistry registry = new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator);
    session.withRegistry(registry);
    final byte[] content = RandomUtils.nextBytes(40500);
    final TransferStatus status = new TransferStatus();
    new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new DropboxDeleteFeature(session), cryptomator).pre(Transfer.Type.upload, Collections.singletonMap(source, status), new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), new CryptoWriteFeature<>(session, new DropboxWriteFeature(session), cryptomator).write(source, status.length(content.length), new DisabledConnectionCallback()));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    final CopyWorker worker = new CopyWorker(Collections.singletonMap(source, target), new TestSessionPool(session, registry), PathCache.empty(), new DisabledProgressListener(), new DisabledConnectionCallback());
    worker.run(session);
    assertTrue(new CryptoFindFeature(session, new DropboxFindFeature(session), cryptomator).find(source));
    assertTrue(new CryptoFindFeature(session, new DropboxFindFeature(session), cryptomator).find(target));
    final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
    assertEquals(content.length, IOUtils.copy(new CryptoReadFeature(session, new DropboxReadFeature(session), cryptomator).read(target, new TransferStatus().length(content.length), new DisabledConnectionCallback()), out));
    assertArrayEquals(content, out.toByteArray());
    new DeleteWorker(new DisabledLoginCallback(), Collections.singletonList(vault), PathCache.empty(), new DisabledProgressListener()).run(session);
    session.close();
}
 
Example 23
Project: PNet   File: TLSClient.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new Client using TLS with given trust store
 */
public TLSClient(final byte[] trustStore, final char[] trustStorePassword, final String trustStoreType)
{
    super(new ClientImpl(
            new SocketFactory()
            {
                @Override
                public Socket getSocket(final String host, final int port) throws Exception
                {
                    return new TLSBuilder()
                            .withHost(host)
                            .withPort(port)
                            .withTrustStore(trustStoreType, new ByteArrayInputStream(trustStore), trustStorePassword)
                            .buildSocket();
                }
            })
    );
}
 
Example 24
Project: lazycat   File: XByteBuffer.java   Source Code and License 6 votes vote down vote up
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls)
		throws IOException, ClassNotFoundException, ClassCastException {
	invokecount.addAndGet(1);
	Object message = null;
	if (cls == null)
		cls = new ClassLoader[0];
	if (data != null && length > 0) {
		InputStream instream = new ByteArrayInputStream(data, offset, length);
		ObjectInputStream stream = null;
		stream = (cls.length > 0) ? new ReplicationStream(instream, cls) : new ObjectInputStream(instream);
		message = stream.readObject();
		instream.close();
		stream.close();
	}
	if (message == null) {
		return null;
	} else if (message instanceof Serializable)
		return (Serializable) message;
	else {
		throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"
				+ message.getClass().getName());
	}
}
 
Example 25
Project: Elf-Editor   File: LEDataInputStream.java   Source Code and License 6 votes vote down vote up
/**
 * 跳转
 * 
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws IOException
 * @throws NoSuchFieldException
 */
public void seek(long position) throws IOException {
	if (is instanceof ByteArrayInputStream) {
		Class<ByteArrayInputStream> clazz = ByteArrayInputStream.class;
		Field field;
		try {
			field = clazz.getDeclaredField("pos");
			field.setAccessible(true);
			field.setInt(is, (int) position);
		} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
			e.printStackTrace();
			throw new IOException("Unsupported");
		}
	} else {
		throw new IOException("Unsupported");
	}
}
 
Example 26
Project: cyberduck   File: DefaultCopyFeatureTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCopy() throws Exception {
    final Host host = new Host(new SFTPProtocol(), "test.cyberduck.ch", new Credentials(
            System.getProperties().getProperty("sftp.user"), System.getProperties().getProperty("sftp.password")
    ));
    final SFTPSession session = new SFTPSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());

    final Path source = new Path(new SFTPHomeDirectoryService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final Path target = new Path(new SFTPHomeDirectoryService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    new DefaultTouchFeature<Void>(new DefaultUploadFeature<Void>(new SFTPWriteFeature(session))).touch(source, new TransferStatus());
    final byte[] content = RandomUtils.nextBytes(524);
    final TransferStatus status = new TransferStatus().length(content.length);
    final OutputStream out = new SFTPWriteFeature(session).write(source, status, new DisabledConnectionCallback());
    assertNotNull(out);
    new StreamCopier(status, status).withLimit(new Long(content.length)).transfer(new ByteArrayInputStream(content), out);
    out.close();
    new DefaultCopyFeature(session).copy(source, target, new TransferStatus(), new DisabledConnectionCallback());
    assertTrue(new DefaultFindFeature(session).find(source));
    assertTrue(new DefaultFindFeature(session).find(target));
    assertEquals(content.length, new DefaultAttributesFinderFeature(session).find(target).getSize());
    new SFTPDeleteFeature(session).delete(Arrays.asList(source, target), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 27
Project: openjdk-jdk10   File: ReadAllBytes.java   Source Code and License 6 votes vote down vote up
static void test(byte[] expectedBytes) throws IOException {
    int expectedLength = expectedBytes.length;
    WrapperInputStream in = new WrapperInputStream(new ByteArrayInputStream(expectedBytes));
    byte[] readBytes = in.readAllBytes();

    int x;
    byte[] tmp = new byte[10];
    check((x = in.read()) == -1,
          "Expected end of stream from read(), got " + x);
    check((x = in.read(tmp)) == -1,
          "Expected end of stream from read(byte[]), got " + x);
    check((x = in.read(tmp, 0, tmp.length)) == -1,
          "Expected end of stream from read(byte[], int, int), got " + x);
    check(in.readAllBytes().length == 0,
          "Expected readAllBytes to return empty byte array");
    check(expectedLength == readBytes.length,
          "Expected length " + expectedLength + ", got " + readBytes.length);
    check(Arrays.equals(expectedBytes, readBytes),
          "Expected[" + expectedBytes + "], got:[" + readBytes + "]");
    check(!in.isClosed(), "Stream unexpectedly closed");
}
 
Example 28
Project: cyberduck   File: S3ReadFeatureTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testReadCloseReleaseEntity() throws Exception {
    final Host host = new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials(
            System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")
    ));
    final S3Session session = new S3Session(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path file = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final int length = 2048;
    final byte[] content = RandomUtils.nextBytes(length);
    final TransferStatus status = new TransferStatus().length(content.length);
    status.setChecksum(new SHA256ChecksumCompute().compute(new ByteArrayInputStream(content), status));
    final OutputStream out = new S3WriteFeature(session).write(file, status, new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out);
    out.close();
    final CountingInputStream in = new CountingInputStream(new S3ReadFeature(session).read(file, status, new DisabledConnectionCallback()));
    in.close();
    assertEquals(0L, in.getByteCount(), 0L);
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 29
Project: java-coap   File: ParsingBenchmark.java   Source Code and License 6 votes vote down vote up
@Before
public void warmUp() throws CoapException {
    ((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(Level.ERROR);

    packet = new CoapPacket(Method.GET, MessageType.Confirmable, "/path-pppppppppppppppppp1/path-dddddddddd-2/dfdshffsdkjfhsdks3/444444444444444444444444444444444444444/55555555555555555555555555555555555555555555555", null);
    packet.setMessageId(1234);
    packet.setToken(new byte[]{1, 2, 3, 4, 5});
    packet.headers().setMaxAge(4321L);
    packet.headers().setEtag(new byte[]{89, 10, 31, 7, 1});
    packet.headers().setObserve(9876);
    packet.headers().setBlock1Req(new BlockOption(13, BlockSize.S_16, true));
    packet.headers().setContentFormat(MediaTypes.CT_APPLICATION_XML);
    packet.headers().setLocationPath("/1/222/33333/4444444/555555555555555555555555");
    packet.headers().setUriQuery("ppar=val1&par222222222222222222222=val2222222222222222222222222222222222");
    packet.setPayload("<k>12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890</k>");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    packet.writeTo(baos);
    CoapPacket.deserialize(null, new ByteArrayInputStream(baos.toByteArray()));

    System.out.println("MSG SIZE: " + packet.toByteArray().length);
}
 
Example 30
Project: openjdk-jdk10   File: SimpleSerialization.java   Source Code and License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final EnumMap<TestEnum, String> enumMap = new EnumMap<>(TestEnum.class);

    enumMap.put(TestEnum.e01, TestEnum.e01.name());
    enumMap.put(TestEnum.e04, TestEnum.e04.name());
    enumMap.put(TestEnum.e05, TestEnum.e05.name());

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(baos);

    oos.writeObject(enumMap);
    oos.close();

    final byte[] data = baos.toByteArray();
    final ByteArrayInputStream bais = new ByteArrayInputStream(data);
    final ObjectInputStream ois = new ObjectInputStream(bais);

    final Object deserializedObject = ois.readObject();
    ois.close();

    if (false == enumMap.equals(deserializedObject)) {
        throw new RuntimeException(getFailureText(enumMap, deserializedObject));
    }
}
 
Example 31
Project: Syn   File: SettingsParserAlgorithmsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testOneSiteHmacInvalidEncoding() throws Exception {
    final String testXml = String.join("\n"
            , "<config version='1'>"
            , "  <site url='http://test.com' algorithm='HS256' encoding='badalgorithm'>"
            , "   this is invalid base64"
            , "  </site>"
            , "</config>"
    );

    final InputStream stream = new ByteArrayInputStream(testXml.getBytes());
    final Map<String,Algorithm> algorithms = SettingsParser.getSiteAlgorithms(stream);
    assertEquals(0, algorithms.size());
}
 
Example 32
Project: openjdk-jdk10   File: PeekInputStreamTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws ReflectiveOperationException,
        IOException {

    InputStream pin = createPeekInputStream(
            new ByteArrayInputStream(new byte[]{1, 2, 3, 4}));
    peek(pin);
    if (pin.skip(1) != 1 || pin.read() != 2)
        throw new AssertionError();

    InputStream pin1 = createPeekInputStream(
            new ByteArrayInputStream(new byte[]{1, 2, 3, 4}));
    if (pin1.skip(1) != 1 || pin1.read() != 2)
        throw new AssertionError();

    InputStream pin2 = createPeekInputStream(
            new ByteArrayInputStream(new byte[]{1, 2, 3, 4}));
    if (pin2.skip(0) != 0 || pin2.read() != 1)
        throw new AssertionError();

    InputStream pin3 = createPeekInputStream(
            new ByteArrayInputStream(new byte[]{1, 2, 3, 4}));
    if (pin3.skip(2) != 2 || pin3.read() != 3)
        throw new AssertionError();

    InputStream pin4 = createPeekInputStream(
            new ByteArrayInputStream(new byte[]{1, 2, 3, 4}));
    if (pin4.skip(3) != 3 || pin4.read() != 4)
        throw new AssertionError();

    InputStream pin5 = createPeekInputStream(
            new ByteArrayInputStream(new byte[]{1, 2, 3, 4}));
    if (pin5.skip(16) != 4 || pin5.read() != -1)
        throw new AssertionError();
}
 
Example 33
Project: letv   File: k.java   Source Code and License 5 votes vote down vote up
public static String a(byte[] bArr) {
    try {
        String obj = ((X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(bArr))).getPublicKey().toString();
        if (obj.indexOf("modulus") != -1) {
            return obj.substring(obj.indexOf("modulus") + 8, obj.lastIndexOf(",")).trim();
        }
    } catch (Exception e) {
    }
    return null;
}
 
Example 34
Project: talchain   File: ECIESTest.java   Source Code and License 5 votes vote down vote up
public static byte[] decrypt(BigInteger prv, byte[] cipher) throws InvalidCipherTextException, IOException {
    ByteArrayInputStream is = new ByteArrayInputStream(cipher);
    byte[] ephemBytes = new byte[2*((curve.getCurve().getFieldSize()+7)/8) + 1];
    is.read(ephemBytes);
    ECPoint ephem = curve.getCurve().decodePoint(ephemBytes);
    byte[] IV = new byte[KEY_SIZE /8];
    is.read(IV);
    byte[] cipherBody = new byte[is.available()];
    is.read(cipherBody);

    EthereumIESEngine iesEngine = makeIESEngine(false, ephem, prv, IV);

    byte[] message = iesEngine.processBlock(cipherBody, 0, cipherBody.length);
    return message;
}
 
Example 35
Project: jdk8u-jdk   File: DriverManagerTests.java   Source Code and License 5 votes vote down vote up
/**
 * Create a PrintStream and use to send output via DriverManager.println
 * Validate that if you disable the stream, the output sent is not present
 */
@Test
public void tests17() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(os);
    DriverManager.setLogStream(ps);
    assertTrue(DriverManager.getLogStream() == ps);

    DriverManager.println(results[0]);
    DriverManager.setLogStream((PrintStream) null);
    assertTrue(DriverManager.getLogStream() == null);
    DriverManager.println(noOutput);
    DriverManager.setLogStream(ps);
    DriverManager.println(results[1]);
    DriverManager.println(results[2]);
    DriverManager.println(results[3]);
    DriverManager.setLogStream((PrintStream) null);
    DriverManager.println(noOutput);

    /*
     * Check we do not get the output when the stream is disabled
     */
    InputStreamReader is
            = new InputStreamReader(new ByteArrayInputStream(os.toByteArray()));
    BufferedReader reader = new BufferedReader(is);
    for (String result : results) {
        assertTrue(result.equals(reader.readLine()));
    }
}
 
Example 36
Project: sumo   File: LookUpTable.java   Source Code and License 5 votes vote down vote up
public void parseLUT() {
    try {
        DataInputStream lutdis = new DataInputStream(new ByteArrayInputStream(lut));
        numberOfElements = (int) lutdis.readDouble();
        pcl = lutdis.readDouble();
        nnu = lutdis.readDouble();
        std[0] = lutdis.readDouble();
        std[1] = lutdis.readDouble();
        standardDeviation2ClippingThresh = new double[numberOfElements];
        clippedStandardDeviation2Threshs = new double[2][numberOfElements];
        for (int i = 0; i < numberOfElements; i++) {
            standardDeviation2ClippingThresh[i] = lutdis.readDouble();
        }
        clippedStd[0] = lutdis.readDouble();
        clippedStd[1] = lutdis.readDouble();
        for (int i = 0; i < numberOfElements; i++) {
            clippedStandardDeviation2Threshs[CLIPPINGTRESH][i] = lutdis.readDouble();
        }
        for (int i = 0; i < numberOfElements; i++) {
            clippedStandardDeviation2Threshs[DETECTIONTRESH][i] = lutdis.readDouble();
        }
    } catch (java.io.IOException e) {
        System.out.println("Cannot read the tables");
    }

    this.step = (numberOfElements - 1) / (std[1] - std[0]);
    this.clippedStep = (numberOfElements - 1) / (clippedStd[1] - clippedStd[0]);

    return;
}
 
Example 37
Project: bitcoinj-thin   File: UTXOTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testJavaSerialization() throws Exception {
    BtcECKey key = new BtcECKey();
    UTXO utxo = new UTXO(Sha256Hash.of(new byte[]{1,2,3}), 1, Coin.COIN, 10, true, ScriptBuilder.createOutputScript(key));
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    new ObjectOutputStream(os).writeObject(utxo);
    UTXO utxoCopy = (UTXO) new ObjectInputStream(
            new ByteArrayInputStream(os.toByteArray())).readObject();
    assertEquals(utxo, utxoCopy);
    assertEquals(utxo.getValue(), utxoCopy.getValue());
    assertEquals(utxo.getHeight(), utxoCopy.getHeight());
    assertEquals(utxo.isCoinbase(), utxoCopy.isCoinbase());
    assertEquals(utxo.getScript(), utxoCopy.getScript());
}
 
Example 38
Project: memento-app   File: AddFaceToPersonActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();

    Uri imageUri = Uri.parse(mImageUriStr);
    mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
            imageUri, getContentResolver());
    if (mBitmap != null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        InputStream imageInputStream = new ByteArrayInputStream(stream.toByteArray());
        addLog("Request: Detecting " + mImageUriStr);
        new DetectionTask().execute(imageInputStream);
    }
}
 
Example 39
Project: openjdk-jdk10   File: UnnamedPackageSwitchTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream oout = new ObjectOutputStream(bout);
    oout.writeObject(new A());
    oout.writeObject(new pkg.A());
    oout.close();

    ObjectInputStream oin = new TestObjectInputStream(
        new ByteArrayInputStream(bout.toByteArray()));
    oin.readObject();
    oin.readObject();
}
 
Example 40
Project: FreeCol   File: SerializationTest.java   Source Code and License 5 votes vote down vote up
public void testGeneratedLists() throws Exception {
    Specification spec1 = null;
    Specification spec2 = null;
    try {
        spec1 = FreeColTcFile.getFreeColTcFile("classic").getSpecification();
        spec1.applyDifficultyLevel("model.difficulty.veryEasy");
        StringWriter sw = new StringWriter();
        try (FreeColXMLWriter xw = new FreeColXMLWriter(sw,
                FreeColXMLWriter.WriteScope.toSave(), false)) {
            spec1.toXML(xw);
        } catch (IOException ioe) {
            fail(ioe.getMessage());
        }

        spec2 = new Specification(new ByteArrayInputStream(sw.toString().getBytes()));
    } catch (Exception e) {
        fail(e.getMessage());
    }

    List<GoodsType> food1 = spec1.getFoodGoodsTypeList();
    List<GoodsType> food2 = spec2.getFoodGoodsTypeList();
    assertEquals(food1.size(), food2.size());
    assertEquals(food1.get(0).getId(), food2.get(0).getId());

    List<GoodsType> farmed1 = spec1.getFarmedGoodsTypeList();
    List<GoodsType> farmed2 = spec2.getFarmedGoodsTypeList();
    assertEquals(farmed1.size(), farmed2.size());
    assertEquals(farmed1.get(0).getId(), farmed2.get(0).getId());
}
 
Example 41
Project: hashsdn-controller   File: ShardSnapshotActorTest.java   Source Code and License 5 votes vote down vote up
private static void testSerializeSnapshot(final String testName, final ShardDataTreeSnapshot snapshot,
        final boolean withInstallSnapshot) throws Exception {
    new JavaTestKit(getSystem()) {
        {
            final ActorRef snapshotActor = getSystem().actorOf(ShardSnapshotActor.props(), testName);
            watch(snapshotActor);

            final NormalizedNode<?, ?> expectedRoot = snapshot.getRootNode().get();

            ByteArrayOutputStream installSnapshotStream = withInstallSnapshot ? new ByteArrayOutputStream() : null;
            ShardSnapshotActor.requestSnapshot(snapshotActor, snapshot,
                    Optional.ofNullable(installSnapshotStream), getRef());

            final CaptureSnapshotReply reply = expectMsgClass(duration("3 seconds"), CaptureSnapshotReply.class);
            assertNotNull("getSnapshotState is null", reply.getSnapshotState());
            assertEquals("SnapshotState type", ShardSnapshotState.class, reply.getSnapshotState().getClass());
            assertEquals("Snapshot", snapshot, ((ShardSnapshotState)reply.getSnapshotState()).getSnapshot());

            if (installSnapshotStream != null) {
                final ShardDataTreeSnapshot deserialized;
                try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(
                        installSnapshotStream.toByteArray()))) {
                    deserialized = ShardDataTreeSnapshot.deserialize(in);
                }

                assertEquals("Deserialized snapshot type", snapshot.getClass(), deserialized.getClass());

                final Optional<NormalizedNode<?, ?>> maybeNode = deserialized.getRootNode();
                assertEquals("isPresent", true, maybeNode.isPresent());
                assertEquals("Root node", expectedRoot, maybeNode.get());
            }
        }
    };
}
 
Example 42
Project: r2cloud   File: ObservationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSuccess() throws Exception {
	String sox = UUID.randomUUID().toString();
	String rtlfm = UUID.randomUUID().toString();
	String wxtoimg = UUID.randomUUID().toString();
	config.setProperty("satellites.sox.path", sox);
	config.setProperty("satellites.rtlsdr.path", rtlfm);
	config.setProperty("satellites.wxtoimg.path", wxtoimg);

	String data = UUID.randomUUID().toString();

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));

	when(factory.create(contains(sox), any(), anyBoolean())).thenReturn(new ProcessWrapperMock(null, baos));
	when(factory.create(contains(rtlfm), any(), anyBoolean())).thenReturn(new ProcessWrapperMock(bais, null));

	SatPass nextPass = create(new Date(), new Date());
	Observation o = new Observation(config, satellite, nextPass, factory, new SatelliteDao(config), new APTDecoder(config, factory));
	o.start();

	File passRoot = new File(tempFolder.getRoot(), satellite.getId() + File.separator + "data" + File.separator + nextPass.getStart().getTime().getTime());
	if (!passRoot.exists() && !passRoot.mkdirs()) {
		throw new IllegalStateException("unable to create: " + passRoot.getAbsolutePath());
	}
	try (FileOutputStream fos = new FileOutputStream(passRoot + File.separator + "output.wav")) {
		fos.write(0);
	}

	assertEquals(data, new String(baos.toByteArray(), StandardCharsets.UTF_8));

	when(factory.create(contains(wxtoimg), any(), anyBoolean())).thenReturn(new ProcessWrapperMock(null, null));
	o.stop();

	verify(factory, times(2)).create(any(), any(), anyBoolean());

}
 
Example 43
Project: uavstack   File: TtlAdaptor.java   Source Code and License 5 votes vote down vote up
private CtClass getCtClass(byte[] classFileBuffer, ClassLoader classLoader) throws IOException {

        ClassPool classPool = new ClassPool(true);
        if (null != classLoader) {
            classPool.appendClassPath(new LoaderClassPath(classLoader));
        }

        CtClass clazz = classPool.makeClass(new ByteArrayInputStream(classFileBuffer), false);
        clazz.defrost();
        return clazz;
    }
 
Example 44
Project: dotwebstack-framework   File: RdfModelTransformer.java   Source Code and License 5 votes vote down vote up
public static Model getModel(InputStream inputStream) throws IOException {
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  RDFWriter turtleWriter = Rio.createWriter(RDFFormat.TURTLE, byteArrayOutputStream);

  RDFParser trigParser = Rio.createParser(RDFFormat.TRIG);
  trigParser.setRDFHandler(turtleWriter);
  trigParser.parse(inputStream, "");

  org.eclipse.rdf4j.model.Model result = Rio.parse(
      new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), "", RDFFormat.TURTLE);

  byteArrayOutputStream.close();
  return result;
}
 
Example 45
Project: dhus-core   File: Node.java   Source Code and License 5 votes vote down vote up
public InputStream toXML ()
{
   initNode ();
   ByteArrayOutputStream out = new ByteArrayOutputStream ();
   XmlFactory.writeXML (drbNode, out);
   return new ByteArrayInputStream (out.toByteArray ());
}
 
Example 46
Project: outlook-message-parser   File: OutlookMessage.java   Source Code and License 5 votes vote down vote up
/**
 * Decompresses compressed RTF data.
 *
 * @param value Data to be decompressed.
 * @return A byte array representing the decompressed data.
 */
private byte[] decompressRtfBytes(final byte[] value) {
	byte[] decompressed = null;
	if (value != null) {
		try {
			final CompressedRTF crtf = new CompressedRTF();
			decompressed = crtf.decompress(new ByteArrayInputStream(value));
		} catch (final IOException e) {
			LOGGER.error("Could not decompress RTF data", e);
		}
	}
	return decompressed;
}
 
Example 47
Project: Robust   File: JavaUtils.java   Source Code and License 5 votes vote down vote up
public static Object getMapFromZippedFile(String path) {
    File file = new File(path);
    Object result = null;
    try {
        if (file.exists()) {
            FileInputStream fileIn = new FileInputStream(file);
            GZIPInputStream gzipIn = new GZIPInputStream(fileIn);
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            int count;
            byte[] data = new byte[1024];
            while ((count = gzipIn.read(data, 0, 1024)) != -1) {
                byteOut.write(data, 0, count);
            }
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(byteIn);
            result = oi.readObject();
            fileIn.close();
            gzipIn.close();
            oi.close();
        } else {
            throw new RuntimeException("getMapFromZippedFile error,file doesn't exist ,path is " + path);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("getMapFromZippedFile from " + path + "  error ");
    }
    return result;
}
 
Example 48
Project: omero-ms-queue   File: CryptoSourceReaderTest.java   Source Code and License 5 votes vote down vote up
private ByteArrayInputStream encrypt(byte[] input) throws Exception {
    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    encryptionFilter.write(sink, input);
    byte[] encrypted = sink.toByteArray();

    return new ByteArrayInputStream(encrypted);
}
 
Example 49
Project: mjolnir   File: Agent.java   Source Code and License 5 votes vote down vote up
public static void premain(String agentArgs, Instrumentation instrumentation) {

//public static void agentmain(String agentArgs, Instrumentation instrumentation) {
  //System.out.println("agent started");
  
  
  Agent.instrumentation = instrumentation;
  
  instrumentation.addTransformer(new ClassFileTransformer() {
    @Override
    public byte[] transform(Module module, ClassLoader loader, String className, Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
      
      //System.out.println("transform " + className + " " + classBeingRedefined);
      
      if (classBeingRedefined == null) {  // do not rewrite too early
        return null;
      }
      
      Function<String, Optional<InputStream>> classFileFinder = internalName -> Optional.ofNullable(loader.getResourceAsStream(internalName + ".class"));
      try {
        return Rewriter.rewrite(new ByteArrayInputStream(classfileBuffer), classFileFinder);
      } catch (IOException e) {
        throw (IllegalClassFormatException)new IllegalClassFormatException().initCause(e);
      }
    }
  }, true);
}
 
Example 50
Project: trellis   File: IOServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testJsonLdCustomSerializer() throws UnsupportedEncodingException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    service.write(getTriples(), out, JSONLD, rdf.createIRI("http://www.w3.org/ns/anno.jsonld"));
    final String output = out.toString("UTF-8");
    assertTrue(output.contains("\"dcterms:title\":\"A title\""));
    assertTrue(output.contains("\"type\":\"Text\""));
    assertTrue(output.contains("\"@context\":"));
    assertTrue(output.contains("\"@context\":\"http://www.w3.org/ns/anno.jsonld\""));
    assertFalse(output.contains("\"@graph\":"));

    final Graph graph = rdf.createGraph();
    service.read(new ByteArrayInputStream(output.getBytes(UTF_8)), null, JSONLD).forEach(graph::add);
    validateGraph(graph);
}
 
Example 51
Project: SparkSeq   File: TestMapDataSerialization.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends Serializable> T deserializationObject(byte[] obj,
                                                         Class<T> clazz) {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.register(clazz, new JavaSerializer());

    ByteArrayInputStream bais = new ByteArrayInputStream(
            obj);
    Input input = new Input(bais);
    return (T) kryo.readClassAndObject(input);
}
 
Example 52
Project: happylifeplat-transaction   File: HessianCodecServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Object decode(byte[] body) throws IOException {
    try {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        closer.register(byteArrayInputStream);
        HessianSerialize hessianSerialization = pool.borrow();
        Object object = hessianSerialization.deserialize(byteArrayInputStream);
        pool.restore(hessianSerialization);
        return object;
    } finally {
        closer.close();
    }
}
 
Example 53
Project: alfresco-core   File: HttpClientFactory.java   Source Code and License 5 votes vote down vote up
public InputStream getContentAsStream() throws IOException
{
    if(decryptedBody != null)
    {
        return new ByteArrayInputStream(decryptedBody);
    }
    else
    {
        return null;
    }
}
 
Example 54
Project: CorePatch   File: BsPatchTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testReadBsdiffLong() throws Exception {
  byte[] data = {
    (byte) 0x78, (byte) 0x56, (byte) 0x34, (byte) 0x12, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
    (byte) 0xef, (byte) 0xbe, (byte) 0xad, (byte) 0x0e, (byte) 0, (byte) 0, (byte) 0, (byte) 0
  };
  ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
  long actual = BsPatch.readBsdiffLong(inputStream);
  Assert.assertEquals(0x12345678, actual);
  actual = BsPatch.readBsdiffLong(inputStream);
  Assert.assertEquals(0x0eadbeef, actual);
}
 
Example 55
Project: Elasticsearch   File: LocalRestChannel.java   Source Code and License 5 votes vote down vote up
@Override
public void doSendResponse(RestResponse response) {
    status = response.status().getStatus();

    byte[] bytes = response.content().toBytes();
    long length = bytes.length;
    Args.check(length <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory");
    if(length < 0) {
        length = 4096;
    }

    InputStream instream =  new ByteArrayInputStream(bytes);
    InputStreamReader reader = new InputStreamReader(instream, Consts.UTF_8);
    CharArrayBuffer buffer = new CharArrayBuffer((int)length);
    char[] tmp = new char[1024];

    int l;
    try {
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        content = buffer.toString();
    } catch (IOException e) {
        status = RestStatus.INTERNAL_SERVER_ERROR.getStatus();
        content = "IOException: " + e.getMessage();
    } finally {
        try {
            reader.close();
            instream.close();
        } catch (IOException e1) {
            content = "IOException: " + e1.getMessage();
        } finally {
            count.countDown();
        }
    }
}
 
Example 56
Project: ibm-cos-sdk-java   File: CRC32ChecksumInputStreamTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCRC32Checksum() throws IOException {
    CRC32 crc32 = new CRC32();
    crc32.update(TEST_DARA.getBytes());
    long expectedCRC32Checksum = crc32.getValue();
    CRC32ChecksumCalculatingInputStream crc32InputStream = new CRC32ChecksumCalculatingInputStream(new ByteArrayInputStream(TEST_DARA.getBytes()));
    while(crc32InputStream.read() != -1);
    assertEquals(expectedCRC32Checksum, crc32InputStream.getCRC32Checksum());
}
 
Example 57
Project: openjdk-jdk10   File: WriteAuUnspecifiedLength.java   Source Code and License 5 votes vote down vote up
public static void main(String argv[]) throws Exception {
    AudioFormat format = new AudioFormat(44100, 16, 2, true, true);
    InputStream is = new ByteArrayInputStream(new byte[1000]);
    AudioInputStream ais = new AudioInputStream(is, format, AudioSystem.NOT_SPECIFIED);
    AudioSystem.write(ais, AudioFileFormat.Type.AU, new ByteArrayOutputStream());
    System.out.println("Test passed.");
}
 
Example 58
Project: incubator-netbeans   File: InstallerTest.java   Source Code and License 5 votes vote down vote up
public void inEQtestNoFormMeansNoButtons() throws Exception {
    String page = 
        "<html><body></body></html>";
    
    InputStream is = new ByteArrayInputStream(page.getBytes());
    DialogDescriptor dd = new DialogDescriptor(null, null);
    Installer.parseButtons(is, null, dd);
    is.close();
    
    Object[] buttons = dd.getOptions();
    assertNotNull("buttons not parsed: ", buttons);
    assertEquals("But empty", 0, buttons.length);
}
 
Example 59
Project: DiavgeiaUtils   File: ValidatorsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testValidateDecisionFixedFields() throws IOException {
    InputStream in = new ByteArrayInputStream(DECISION_MOCK.getBytes(StandardCharsets.UTF_8));
    DecisionDao d = DecisionDaoProvider.readFrom( in);
    if(!Validators.validateDecisionFixedFields(d)){
        throw new ValidationException("Λάθος δομή των πεδίων");
    }    
}
 
Example 60
Project: openjdk-jdk10   File: TransformerTestTemplate.java   Source Code and License 5 votes vote down vote up
public DOMSource getDOMSource(DocumentBuilderFactory dbf)
    throws SAXException, IOException, ParserConfigurationException
{
    return new DOMSource(
        dbf.newDocumentBuilder().parse(
            new InputSource(
                new ByteArrayInputStream(sourceXml.getBytes())
            )
        )
    );
}