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: wangmarket   File: TemplateController.java   View source code 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 2
Project: PeSanKita-android   File: MediaConstraints.java   View source code 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 3
Project: openjdk-jdk10   File: LoadAndStoreXML.java   View source code 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 4
Project: Guardian.java   File: TransactionTest.java   View source code 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 5
Project: redis-client   File: CacheUtils.java   View source code 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 6
Project: parabuild-ci   File: SignalRendererTests.java   View source code 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 7
Project: FlashLib   File: CameraViewer.java   View source code 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 8
Project: gradle-s3-build-cache   File: AwsS3BuildCacheService.java   View source code 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 9
Project: parabuild-ci   File: ComparableObjectSeriesTests.java   View source code 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 10
Project: powertext   File: RtfTransferable.java   View source code 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 11
Project: curiostack   File: MessageMarshallerTest.java   View source code 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 12
Project: EatDubbo   File: AbstractSerializationTest.java   View source code 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 13
Project: gw4e.project   File: ResourceManager.java   View source code 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 14
Project: OSchina_resources_android   File: TeamTweetDetailFragment.java   View source code 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 15
Project: ImageLoaderSupportGif   File: BaseImageDownloader.java   View source code 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 16
Project: directory-ldap-api   File: SchemaAwareDnSerializationTest.java   View source code 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 17
Project: XinFramework   File: ByteArrayOutputStream.java   View source code 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 18
Project: Melophile   File: BundleUtils.java   View source code 6 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 19
Project: raven   File: ImageUtils.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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: instalint   File: PluginHashesTest.java   View source code 5 votes vote down vote up
private String hash(String s) {
  InputStream in = new ByteArrayInputStream(s.getBytes());
  try {
    return new PluginHashes().of(in);
  } finally {
    IOUtils.closeQuietly(in);
  }
}
 
Example 39
Project: memento-app   File: AddFaceToPersonActivity.java   View source code 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 40
Project: openjdk-jdk10   File: UnnamedPackageSwitchTest.java   View source code 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();
}