Java Code Examples for java.io.ByteArrayOutputStream

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project addis, under directory /application/src/main/java/org/drugis/addis/util/jaxb/.

Source file: JAXBConvertor.java

  34 
vote

/** 
 * Convert legacy XML ("version 0") to schema v1 compliant XML.
 * @param xml Legacy XML input stream.
 * @return Schema v1 compliant XML.
 */
public static InputStream transformLegacyXML(InputStream xml) throws TransformerException, IOException {
  System.setProperty("javax.xml.transform.TransformerFactory","net.sf.saxon.TransformerFactoryImpl");
  TransformerFactory tFactory=TransformerFactory.newInstance();
  InputStream xsltFile=JAXBConvertor.class.getResourceAsStream("transform-0-1.xslt");
  ByteArrayOutputStream os=new ByteArrayOutputStream();
  javax.xml.transform.Source xmlSource=new javax.xml.transform.stream.StreamSource(xml);
  javax.xml.transform.Source xsltSource=new javax.xml.transform.stream.StreamSource(xsltFile);
  javax.xml.transform.Result result=new javax.xml.transform.stream.StreamResult(os);
  javax.xml.transform.Transformer trans=tFactory.newTransformer(xsltSource);
  trans.transform(xmlSource,result);
  os.close();
  return new ByteArrayInputStream(os.toByteArray());
}
 

Example 2

From project agit, under directory /agit/src/main/java/com/madgag/agit/diff/.

Source file: LineContextDiffer.java

  33 
vote

private String extractHunk(RawText rawText,int startLine,int endLine){
  try {
    ByteArrayOutputStream bas=new ByteArrayOutputStream();
    for (int line=startLine; line < endLine; ++line) {
      rawText.writeLine(bas,line);
      bas.write('\n');
    }
    return new String(bas.toByteArray(),"utf-8");
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 3

From project aim3-tu-berlin, under directory /seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/one/.

Source file: PrimeNumbersWritableTest.java

  33 
vote

@Test public void writeAndRead() throws IOException {
  PrimeNumbersWritable original=new PrimeNumbersWritable(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97);
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  original.write(new DataOutputStream(out));
  PrimeNumbersWritable clone=new PrimeNumbersWritable();
  clone.readFields(new DataInputStream(new ByteArrayInputStream(out.toByteArray())));
  assertEquals(original,clone);
}
 

Example 4

From project action-core, under directory /src/main/java/com/ning/metrics/action/endpoint/.

Source file: HdfsBrowser.java

  32 
vote

@GET @Produces(MediaType.APPLICATION_JSON) @Path("/viewer") @Timed public Response prettyPrintOneLine(@QueryParam("object") final String object) throws IOException {
  final ByteArrayOutputStream out=new ByteArrayOutputStream();
  final ObjectMapper mapper=new ObjectMapper();
  final String objectURIDecoded=URLDecoder.decode(object,"UTF-8");
  final byte[] objectBase64Decoded=Base64.decodeBase64(objectURIDecoded.getBytes());
  mapper.configure(SerializationFeature.INDENT_OUTPUT,true);
  final LinkedHashMap map=mapper.readValue(new String(objectBase64Decoded),LinkedHashMap.class);
  mapper.writeValue(out,map);
  return Response.ok().entity(new String(out.toByteArray())).build();
}
 

Example 5

From project adbcj, under directory /mysql/codec/src/main/java/org/adbcj/mysql/codec/.

Source file: IoUtils.java

  32 
vote

/** 
 * Reads a null-terminate string
 * @param in
 * @param charset
 * @return
 * @throws IOException
 */
public static String readString(InputStream in,String charset) throws IOException {
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  int c;
  while ((c=in.read()) > 0) {
    out.write(c);
  }
  return new String(out.toByteArray(),charset);
}
 

Example 6

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/helper/.

Source file: GZIPHelper.java

  32 
vote

public byte[] zippedSession(Session session) throws IOException {
  ByteArrayOutputStream byteStream=new ByteArrayOutputStream();
  Base64OutputStream base64OutputStream=new Base64OutputStream(byteStream);
  GZIPOutputStream gzip=new GZIPOutputStream(base64OutputStream);
  OutputStreamWriter writer=new OutputStreamWriter(gzip);
  gson.toJson(session,session.getClass(),writer);
  writer.flush();
  gzip.finish();
  writer.close();
  return byteStream.toByteArray();
}
 

Example 7

From project airlift, under directory /event/src/test/java/io/airlift/event/client/.

Source file: TestJsonEventSerializer.java

  32 
vote

@Test public void testEventSerializer() throws Exception {
  JsonEventSerializer eventSerializer=new JsonEventSerializer(FixedDummyEventClass.class);
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  JsonGenerator jsonGenerator=new JsonFactory().createJsonGenerator(out,JsonEncoding.UTF8);
  FixedDummyEventClass event=TestingUtils.getEvents().get(0);
  eventSerializer.serialize(event,jsonGenerator);
  String json=out.toString(Charsets.UTF_8.name());
  assertEquals(json,TestingUtils.getNormalizedJson("event.json"));
}
 

Example 8

From project ajah, under directory /ajah-image/src/main/java/com/ajah/image/.

Source file: AutoCrop.java

  32 
vote

/** 
 * Crops an image based on the value of the top left pixel.
 * @param data The image data.
 * @param fuzziness The fuzziness allowed for minor deviations (~5 is recommended).
 * @return The new image data, cropped.
 * @throws IOException If the image could not be read.
 */
public static byte[] autoCrop(final byte[] data,final int fuzziness) throws IOException {
  final BufferedImage image=ImageIO.read(new ByteArrayInputStream(data));
  final BufferedImage cropped=autoCrop(image,fuzziness);
  final ByteArrayOutputStream out=new ByteArrayOutputStream();
  ImageIO.write(cropped,"png",out);
  return out.toByteArray();
}
 

Example 9

From project akela, under directory /src/main/java/com/mozilla/hadoop/hbase/mapreduce/.

Source file: MultiScanTableMapReduceUtil.java

  32 
vote

/** 
 * Converts an array of Scan objects into a base64 string
 * @param scans
 * @return
 * @throws IOException
 */
public static String convertScanArrayToString(final Scan[] scans) throws IOException {
  final ByteArrayOutputStream baos=new ByteArrayOutputStream();
  final DataOutputStream dos=new DataOutputStream(baos);
  ArrayWritable aw=new ArrayWritable(Scan.class,scans);
  aw.write(dos);
  return Base64.encodeBytes(baos.toByteArray());
}
 

Example 10

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/entity/.

Source file: SerializableEntity.java

  32 
vote

private void createBytes(Serializable ser) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream out=new ObjectOutputStream(baos);
  out.writeObject(ser);
  out.flush();
  this.objSer=baos.toByteArray();
}
 

Example 11

From project amplafi-sworddance, under directory /src/test/java/com/sworddance/taskcontrol/.

Source file: TestFutureListenerNotifier.java

  32 
vote

private <F>F serializeDeserialize(F futureResult) throws IOException, ClassNotFoundException {
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(out);
  objectOutputStream.writeObject(futureResult);
  objectOutputStream.close();
  ByteArrayInputStream in=new ByteArrayInputStream(out.toByteArray());
  ObjectInputStream objectInputStream=new ObjectInputStream(in);
  F f=(F)objectInputStream.readObject();
  assertNotNull(f);
  return f;
}
 

Example 12

From project and-bible, under directory /jsword-tweaks/bakup/.

Source file: Zip.java

  32 
vote

public ByteArrayOutputStream compress() throws IOException {
  BufferedInputStream in=new BufferedInputStream(input);
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  DeflaterOutputStream out=new DeflaterOutputStream(bos,new Deflater(),BUF_SIZE);
  byte[] buf=new byte[BUF_SIZE];
  for (int count=in.read(buf); count != -1; count=in.read(buf)) {
    out.write(buf,0,count);
  }
  in.close();
  out.flush();
  out.close();
  return bos;
}
 

Example 13

From project android-aac-enc, under directory /src/com/coremedia/iso/boxes/sampleentry/.

Source file: SampleEntry.java

  32 
vote

public void _writeChildBoxes(ByteBuffer bb){
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  WritableByteChannel wbc=Channels.newChannel(baos);
  try {
    for (    Box box : boxes) {
      box.getBox(wbc);
    }
    wbc.close();
  }
 catch (  IOException e) {
    throw new RuntimeException("Cannot happen. Everything should be in memory and therefore no exceptions.");
  }
  bb.put(baos.toByteArray());
}
 

Example 14

From project android-api_1, under directory /android-lib/src/com/android/http/multipart/.

Source file: MultipartEntity.java

  32 
vote

public InputStream getContent() throws IOException, IllegalStateException {
  if (!isRepeatable() && this.contentConsumed) {
    throw new IllegalStateException("Content has been consumed");
  }
  this.contentConsumed=true;
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  Part.sendParts(baos,this.parts,this.multipartBoundary);
  ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
  return bais;
}
 

Example 15

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: PersistentCookieStore.java

  32 
vote

protected String encodeCookie(SerializableCookie cookie){
  ByteArrayOutputStream os=new ByteArrayOutputStream();
  try {
    ObjectOutputStream outputStream=new ObjectOutputStream(os);
    outputStream.writeObject(cookie);
  }
 catch (  Exception e) {
    return null;
  }
  return byteArrayToHexString(os.toByteArray());
}
 

Example 16

From project android-client_1, under directory /src/com/googlecode/asmack/dns/.

Source file: Question.java

  32 
vote

public byte[] toByteArray() throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream(512);
  DataOutputStream dos=new DataOutputStream(baos);
  dos.write(NameUtil.toByteArray(this.name));
  dos.writeShort(type.getValue());
  dos.writeShort(clazz.getValue());
  dos.flush();
  return baos.toByteArray();
}
 

Example 17

From project android-joedayz, under directory /Proyectos/spring-rest-servidor/src/main/java/com/mycompany/rest/controller/.

Source file: PersonController.java

  32 
vote

@RequestMapping(value="/person/{id}",method=RequestMethod.GET,headers="Accept=image/jpeg, image/jpg, image/png, image/gif") public @ResponseBody byte[] getPhoto(@PathVariable("id") Long id){
  try {
    InputStream is=this.getClass().getResourceAsStream("/bella.jpg");
    BufferedImage img=ImageIO.read(is);
    ByteArrayOutputStream bao=new ByteArrayOutputStream();
    ImageIO.write(img,"jpg",bao);
    logger.debug("Retrieving photo as byte array image");
    return bao.toByteArray();
  }
 catch (  IOException e) {
    logger.error(e);
    throw new RuntimeException(e);
  }
}
 

Example 18

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharingExample/src/com/nostra13/example/socialsharing/.

Source file: FacebookActivity.java

  32 
vote

private void publishImage(){
  Bitmap bmp=((BitmapDrawable)getResources().getDrawable(R.drawable.ic_app)).getBitmap();
  ByteArrayOutputStream stream=new ByteArrayOutputStream();
  bmp.compress(Bitmap.CompressFormat.JPEG,100,stream);
  byte[] bitmapdata=stream.toByteArray();
  facebook.publishImage(bitmapdata,Constants.FACEBOOK_SHARE_IMAGE_CAPTION);
}
 

Example 19

From project android-xbmcremote, under directory /src/org/xbmc/httpapi/client/.

Source file: Client.java

  32 
vote

/** 
 * Doubles the size of a bitmap and re-reads it with samplesize 2. I've  found no other way to smoothely resize images with samplesize = 1.
 * @param source
 * @return
 */
private Bitmap blowup(Bitmap source){
  if (source != null) {
    Bitmap big=Bitmap.createScaledBitmap(source,source.getWidth() * 2,source.getHeight() * 2,true);
    BitmapFactory.Options opts=new BitmapFactory.Options();
    opts.inSampleSize=2;
    ByteArrayOutputStream os=new ByteArrayOutputStream();
    big.compress(CompressFormat.PNG,100,os);
    byte[] array=os.toByteArray();
    return BitmapFactory.decodeByteArray(array,0,array.length,opts);
  }
  return null;
}
 

Example 20

From project androidquery, under directory /src/com/androidquery/util/.

Source file: AQUtility.java

  32 
vote

public static byte[] toBytes(InputStream is){
  byte[] result=null;
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  try {
    copy(is,baos);
    result=baos.toByteArray();
  }
 catch (  IOException e) {
    AQUtility.report(e);
  }
  close(is);
  return result;
}
 

Example 21

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: SOContainer.java

  32 
vote

public static byte[] serialize(Serializable obj) throws IOException {
  final ByteArrayOutputStream bos=new ByteArrayOutputStream();
  final ObjectOutputStream oos=new ObjectOutputStream(bos);
  oos.writeObject(obj);
  return bos.toByteArray();
}
 

Example 22

From project android_external_libphonenumber, under directory /java/src/com/android/i18n/phonenumbers/geocoding/.

Source file: AreaCodeMap.java

  32 
vote

/** 
 * Gets the size of the provided area code map storage. The map storage passed-in will be filled as a result.
 */
private static int getSizeOfAreaCodeMapStorage(AreaCodeMapStorageStrategy mapStorage,SortedMap<Integer,String> areaCodeMap) throws IOException {
  mapStorage.readFromSortedMap(areaCodeMap);
  ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
  mapStorage.writeExternal(objectOutputStream);
  objectOutputStream.flush();
  int sizeOfStorage=byteArrayOutputStream.size();
  objectOutputStream.close();
  return sizeOfStorage;
}
 

Example 23

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/picasa/.

Source file: GDataClient.java

  32 
vote

private ByteArrayEntity getCompressedEntity(byte[] data) throws IOException {
  ByteArrayEntity entity;
  if (data.length >= MIN_GZIP_SIZE) {
    ByteArrayOutputStream byteOutput=new ByteArrayOutputStream(data.length / 2);
    GZIPOutputStream gzipOutput=new GZIPOutputStream(byteOutput);
    gzipOutput.write(data);
    gzipOutput.close();
    entity=new ByteArrayEntity(byteOutput.toByteArray());
  }
 else {
    entity=new ByteArrayEntity(data);
  }
  return entity;
}
 

Example 24

From project android_packages_apps_Tag, under directory /src/com/android/apps/tag/record/.

Source file: ImageRecord.java

  32 
vote

public static NdefRecord newImageRecord(Bitmap bitmap){
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
  byte[] content=out.toByteArray();
  return MimeRecord.newMimeRecord("image/jpeg",content);
}
 

Example 25

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: Utils.java

  32 
vote

/** 
 * Compress data.
 * @param bytesToCompress is the byte array to compress.
 * @return a compressed byte array.
 * @throws java.io.IOException
 */
public static byte[] compress(byte[] bytesToCompress) throws IOException {
  Deflater compressor=new Deflater(Deflater.BEST_COMPRESSION);
  compressor.setInput(bytesToCompress);
  compressor.finish();
  ByteArrayOutputStream bos=new ByteArrayOutputStream(bytesToCompress.length);
  byte[] buf=new byte[bytesToCompress.length + 100];
  while (!compressor.finished()) {
    bos.write(buf,0,compressor.deflate(buf));
  }
  bos.close();
  return bos.toByteArray();
}
 

Example 26

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/visualizers/.

Source file: AbstractIFrameVisualizer.java

  32 
vote

@Override public Component createComponent(VisualizerInput vis,Application application){
  AutoHeightIFrame iframe;
  ApplicationResource resource;
  ByteArrayOutputStream outStream=new ByteArrayOutputStream();
  writeOutput(vis,outStream);
  resource=vis.getVisPanel().createResource(outStream,getContentType());
  String url=vis.getVisPanel().getApplication().getRelativeLocation(resource);
  iframe=new AutoHeightIFrame(url == null ? "/error.html" : url);
  return iframe;
}
 

Example 27

From project annotare2, under directory /app/magetab/src/test/java/uk/ac/ebi/fg/annotare2/magetab/base/.

Source file: TsvGeneratorTest.java

  32 
vote

@Test public void test() throws IOException {
  String[] row=new String[]{"1","2","","3"};
  String s=on("\t").join(row) + "\n";
  s+=s;
  Table table=new Table();
  table.addRow(asList(row));
  table.addRow(asList(row));
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  new TsvGenerator(table).generate(out);
  String s1=out.toString(UTF_8.name());
  assertEquals(s,s1);
  String s2=new TsvGenerator(table).generateString();
  assertEquals(s,s2);
}
 

Example 28

From project ant4eclipse, under directory /org.ant4eclipse.lib.core.test/src-framework/org/ant4eclipse/testframework/.

Source file: TestDirectory.java

  32 
vote

/** 
 * Copies the content from the given input stream to the file. <p> This method closes the input stream after copying it
 * @param fileName The filename that is relative to the root of the test environment
 * @param inputStream The inputStream to read from
 * @return The file that has been createad
 * @throws IOException
 */
public File createFile(String fileName,InputStream inputStream) throws IOException {
  ByteArrayOutputStream output=new ByteArrayOutputStream();
  byte[] buffer=new byte[1024];
  int bytesRead=-1;
  while ((bytesRead=inputStream.read(buffer,0,buffer.length)) != -1) {
    output.write(buffer,0,bytesRead);
  }
  Utilities.close(inputStream);
  return createFile(fileName,output.toString());
}
 

Example 29

From project any23, under directory /core/src/main/java/org/apache/any23/source/.

Source file: FileDocumentSource.java

  32 
vote

public String readStream() throws IOException {
  final ByteArrayOutputStream baos=new ByteArrayOutputStream();
  InputStream is=openInputStream();
  try {
    int c;
    while ((c=is.read()) != -1) {
      baos.write(c);
    }
  }
  finally {
    is.close();
  }
  return new String(baos.toByteArray());
}
 

Example 30

From project apb, under directory /modules/test-tasks/src/apb/tests/tasks/.

Source file: ExecTest.java

  32 
vote

static String invokeExec(String cmd,String... args){
  ByteArrayOutputStream b=new ByteArrayOutputStream();
  PrintStream prev=System.out;
  try {
    PrintStream p=new PrintStream(b);
    System.setOut(p);
    exec(cmd,args).execute();
    p.close();
  }
  finally {
    System.setOut(prev);
  }
  return b.toString();
}
 

Example 31

From project apg, under directory /src/org/thialfihar/android/apg/.

Source file: HkpKeyServer.java

  32 
vote

static private String readAll(InputStream in,String encoding) throws IOException {
  ByteArrayOutputStream raw=new ByteArrayOutputStream();
  byte buffer[]=new byte[1 << 16];
  int n=0;
  while ((n=in.read(buffer)) != -1) {
    raw.write(buffer,0,n);
  }
  if (encoding == null) {
    encoding="utf8";
  }
  return raw.toString(encoding);
}
 

Example 32

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/client/.

Source file: AndroidNativeDriver.java

  32 
vote

protected String imageToBase64Png(BufferedImage image){
  ByteArrayOutputStream rawPngStream=new ByteArrayOutputStream();
  try {
    if (!writeImageAsPng(image,rawPngStream)) {
      throw new RuntimeException("This Java environment does not support converting to PNG.");
    }
  }
 catch (  IOException exception) {
    Throwables.propagate(exception);
  }
  byte[] rawPngBytes=rawPngStream.toByteArray();
  return new Base64Encoder().encode(rawPngBytes);
}
 

Example 33

From project apps-for-android, under directory /Photostream/src/com/google/android/photostream/.

Source file: UserDatabase.java

  32 
vote

static void writeBitmap(ContentValues values,String name,Bitmap bitmap){
  if (bitmap != null) {
    int size=bitmap.getWidth() * bitmap.getHeight() * 2;
    ByteArrayOutputStream out=new ByteArrayOutputStream(size);
    try {
      bitmap.compress(Bitmap.CompressFormat.PNG,100,out);
      out.flush();
      out.close();
      values.put(name,out.toByteArray());
    }
 catch (    IOException e) {
    }
  }
}
 

Example 34

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/extract/.

Source file: WATExtractorOutput.java

  32 
vote

private void writeWARCInfo(OutputStream recOut,MetaData md) throws IOException {
  String filename=JSONUtils.extractSingle(md,"Container.Filename");
  if (filename == null) {
    throw new IOException("No Container.Filename...");
  }
  HttpHeaders headers=new HttpHeaders();
  headers.add("Software-Info",IAUtils.COMMONS_VERSION);
  headers.addDateHeader("Extracted-Date",new Date());
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  headers.write(baos);
  recW.writeWARCInfoRecord(recOut,filename,baos.toByteArray());
}
 

Example 35

From project ardverk-commons, under directory /src/main/java/org/ardverk/io/.

Source file: GzipCompressor.java

  32 
vote

@Override public byte[] compress(byte[] value,int offset,int length) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream(MathUtils.nextPowOfTwo(length));
  try (OutputStream out=new GZIPOutputStream(baos)){
    out.write(value,offset,length);
  }
  finally {
    IoUtils.close(baos);
  }
  return baos.toByteArray();
}
 

Example 36

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  31 
vote

void save(Writer w) throws IOException {
  if (expired)   return;
  w.write(id);
  w.write(':');
  w.write(Integer.toString(inactiveInterval));
  w.write(':');
  w.write(servletContext == null || servletContext.getServletContextName() == null ? "" : servletContext.getServletContextName());
  w.write(':');
  w.write(Long.toString(lastAccessTime));
  w.write("\r\n");
  Enumeration<String> e=getAttributeNames();
  ByteArrayOutputStream os=new ByteArrayOutputStream(1024 * 16);
  while (e.hasMoreElements()) {
    String aname=(String)e.nextElement();
    Object so=get(aname);
    if (so instanceof Serializable) {
      os.reset();
      ObjectOutputStream oos=new ObjectOutputStream(os);
      try {
        oos.writeObject(so);
        w.write(aname);
        w.write(":");
        w.write(Utils.base64Encode(os.toByteArray()));
        w.write("\r\n");
      }
 catch (      IOException ioe) {
        servletContext.log("Can't replicate/store a session value of '" + aname + "' class:"+ so.getClass().getName(),ioe);
      }
    }
 else     servletContext.log("Non serializable session object has been " + so.getClass().getName() + " skiped in storing of "+ aname,null);
    if (so instanceof HttpSessionActivationListener)     ((HttpSessionActivationListener)so).sessionWillPassivate(new HttpSessionEvent((HttpSession)this));
  }
  w.write("$$\r\n");
}
 

Example 37

From project activejdbc, under directory /activejdbc/src/test/java/org/javalite/activejdbc/.

Source file: CacheEventListenerTest.java

  31 
vote

@Test public void shouldNotBreakIfListenerThrowsException() throws IOException {
class BadEventListener implements CacheEventListener {
    public void onFlush(    CacheEvent event){
      throw new RuntimeException("I'm a bad, baaad listener....");
    }
  }
  BadEventListener listener=new BadEventListener();
  Registry.cacheManager().addCacheEventListener(listener);
  PrintStream errOrig=System.err;
  ByteArrayOutputStream bout=new ByteArrayOutputStream();
  PrintStream err=new PrintStream(bout);
  System.setErr(err);
  Person.createIt("name","Matt","last_name","Diamont","dob","1962-01-01");
  err.flush();
  bout.flush();
  String exception=bout.toString();
  a(exception.contains(" I'm a bad, baaad listener")).shouldBeTrue();
  System.setErr(errOrig);
}
 

Example 38

From project activemq-apollo, under directory /apollo-openwire/src/test/scala/org/apache/activemq/apollo/openwire/codec/.

Source file: BooleanStreamTest.java

  31 
vote

protected void assertMarshalBooleans(int count,BooleanValueSet valueSet) throws Exception {
  BooleanStream bs=new BooleanStream();
  for (int i=0; i < count; i++) {
    bs.writeBoolean(valueSet.getBooleanValueFor(i,count));
  }
  ByteArrayOutputStream buffer=new ByteArrayOutputStream();
  DataOutputStream ds=new DataOutputStream(buffer);
  bs.marshal(ds);
  ds.writeInt(endOfStreamMarker);
  ds.close();
  ByteArrayInputStream in=new ByteArrayInputStream(buffer.toByteArray());
  DataInputStream dis=new DataInputStream(in);
  bs=new BooleanStream();
  try {
    bs.unmarshal(dis);
  }
 catch (  Exception e) {
    e.printStackTrace();
    fail("Failed to unmarshal: " + count + " booleans: "+ e);
  }
  for (int i=0; i < count; i++) {
    boolean expected=valueSet.getBooleanValueFor(i,count);
    try {
      boolean actual=bs.readBoolean();
      assertEquals("value of object: " + i + " was: "+ actual,expected,actual);
    }
 catch (    IOException e) {
      e.printStackTrace();
      fail("Failed to parse boolean: " + i + " out of: "+ count+ " due to: "+ e);
    }
  }
  int marker=dis.readInt();
  assertEquals("Marker int when unmarshalling: " + count + " booleans",Integer.toHexString(endOfStreamMarker),Integer.toHexString(marker));
  try {
    byte value=dis.readByte();
    fail("Should have reached the end of the stream");
  }
 catch (  IOException e) {
  }
}
 

Example 39

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/ui/custom/.

Source file: InMemoryUploadReceiver.java

  31 
vote

public OutputStream receiveUpload(String filename,String mimeType){
  this.fileName=filename;
  this.mimeType=mimeType;
  this.outputStream=new ByteArrayOutputStream();
  return outputStream;
}
 

Example 40

From project adg-android, under directory /src/com/analysedesgeeks/android/service/impl/.

Source file: DownloadServiceImpl.java

  31 
vote

@Override public boolean downloadFeed(){
  boolean downloadSuccess=false;
  if (connectionService.isConnected()) {
    InputStream inputStream=null;
    try {
      final HttpGet httpget=new HttpGet(new URI(Const.FEED_URL));
      final HttpResponse response=new DefaultHttpClient().execute(httpget);
      final StatusLine status=response.getStatusLine();
      if (status.getStatusCode() != HttpStatus.SC_OK) {
        Ln.e("Erreur lors du t??hargement:%s,%s",status.getStatusCode(),status.getReasonPhrase());
      }
 else {
        final HttpEntity entity=response.getEntity();
        inputStream=entity.getContent();
        final ByteArrayOutputStream content=new ByteArrayOutputStream();
        int readBytes=0;
        final byte[] sBuffer=new byte[512];
        while ((readBytes=inputStream.read(sBuffer)) != -1) {
          content.write(sBuffer,0,readBytes);
        }
        final String dataAsString=new String(content.toByteArray());
        final List<FeedItem> syndFeed=rssService.parseRss(dataAsString);
        if (syndFeed != null) {
          databaseService.save(dataAsString);
          downloadSuccess=true;
        }
      }
    }
 catch (    final Throwable t) {
      Ln.e(t);
    }
 finally {
      closeQuietly(inputStream);
    }
  }
  return downloadSuccess;
}
 

Example 41

From project Agot-Java, under directory /src/main/java/got/utility/.

Source file: Utility.java

  31 
vote

final static public Image loadImage(final String fileName){
  String keyName=fileName.trim().toLowerCase();
  Image cacheImage=(Image)cacheImages.get(keyName);
  if (cacheImage == null) {
    InputStream in=new BufferedInputStream(classLoader.getResourceAsStream(fileName));
    ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
    try {
      byte[] bytes=new byte[8192];
      int read;
      while ((read=in.read(bytes)) >= 0) {
        byteArrayOutputStream.write(bytes,0,read);
      }
      byte[] arrayByte=byteArrayOutputStream.toByteArray();
      cacheImages.put(keyName,cacheImage=toolKit.createImage(arrayByte));
      mediaTracker.addImage(cacheImage,0);
      mediaTracker.waitForID(0);
      waitImage(100,cacheImage);
    }
 catch (    Exception e) {
      throw new RuntimeException(fileName + " not found!");
    }
 finally {
      try {
        if (byteArrayOutputStream != null) {
          byteArrayOutputStream.close();
          byteArrayOutputStream=null;
        }
        if (in != null) {
          in.close();
        }
      }
 catch (      IOException e) {
      }
    }
  }
  if (cacheImage == null) {
    throw new RuntimeException(("File not found. ( " + fileName + " )").intern());
  }
  return cacheImage;
}
 

Example 42

From project agraph-java-client, under directory /src/test/.

Source file: RepositoryConnectionTest.java

  31 
vote

@Test public void testStatementSerialization() throws Exception {
  testCon.add(bob,name,nameBob);
  Statement st;
  RepositoryResult<Statement> statements=testCon.getStatements(null,null,null,true);
  try {
    st=statements.next();
  }
  finally {
    statements.close();
  }
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream out=new ObjectOutputStream(baos);
  out.writeObject(st);
  out.close();
  ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
  ObjectInputStream in=new ObjectInputStream(bais);
  Statement deserializedStatement=(Statement)in.readObject();
  in.close();
  assertTrue(st.equals(deserializedStatement));
  assertTrue(testCon.hasStatement(st,true));
  assertTrue(testCon.hasStatement(deserializedStatement,true));
}
 

Example 43

From project akubra, under directory /akubra-core/src/test/java/org/akubraproject/impl/.

Source file: TestStreamManager.java

  31 
vote

/** 
 * Managed OutputStreams should be tracked when open and forgotten when closed.
 */
@Test(dependsOnGroups={"init"}) public void testManageOutputStream() throws Exception {
  OutputStream managed=manager.manageOutputStream(null,new ByteArrayOutputStream());
  assertEquals(manager.getOpenOutputStreamCount(),1);
  managed.close();
  assertEquals(manager.getOpenOutputStreamCount(),0);
}
 

Example 44

From project AlbiteREADER, under directory /src/org/albite/albite/.

Source file: AlbiteMIDlet.java

  31 
vote

public final void saveOptionsToRMS(){
  if (bookURL != null && !bookURL.equalsIgnoreCase("")) {
    try {
      ByteArrayOutputStream boas=new ByteArrayOutputStream();
      DataOutputStream dout=new DataOutputStream(boas);
      try {
        RMSHelper.writeVersionNumber(this,dout);
        dout.writeUTF(bookURL);
        dout.writeUTF(dictsFolder);
        byte[] data=boas.toByteArray();
        if (rs.getNumRecords() > 0) {
          rs.setRecord(1,data,0,data.length);
        }
 else {
          rs.addRecord(data,0,data.length);
        }
      }
 catch (      IOException ioe) {
      }
    }
 catch (    RecordStoreException rse) {
    }
  }
}
 

Example 45

From project almira-sample, under directory /almira-sample-client/src/test/java/almira/sample/client/.

Source file: ListCatapultTest.java

  31 
vote

@Test public void executesQueryWithoutErrors(){
  context.checking(new Expectations(){
{
      oneOf(queryService).findAll(0,MAX_RECORDS);
      will(returnValue(RESULT_LIST));
    }
  }
);
  PrintStream sysOut=System.out;
  try {
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));
    ListCatapults.executeQuery(queryService);
    Assert.assertTrue("Output contains Catapult name",baos.toString().contains(CATAPULT_NAME));
  }
  finally {
    System.setOut(sysOut);
  }
}
 

Example 46

From project alphaportal_dev, under directory /sys-src/alphaportal_RESTClient/src/alpha/client/.

Source file: RESTClient.java

  31 
vote

/** 
 * reads the file and transforms it in a payload
 * @param path path of the file
 * @param name name as which the payload should be saved
 * @return a payload
 */
private static Payload readFile(String path,Payload payload){
  InputStream inputStream=null;
  try {
    inputStream=new FileInputStream(path);
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
  ByteArrayOutputStream byteBuffer=new ByteArrayOutputStream();
  byte[] buffer=new byte[BUFFER_SIZE];
  int readBytes=0;
  try {
    while (true) {
      readBytes=inputStream.read(buffer);
      if (readBytes > 0) {
        byteBuffer.write(buffer,0,readBytes);
      }
 else {
        break;
      }
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  payload.setContent(byteBuffer.toByteArray());
  return payload;
}
 

Example 47

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/bean/.

Source file: PureJavaReflectionProvider.java

  31 
vote

private Object instantiateUsingSerialization(Class type){
  try {
    byte[] data;
    if (serializedDataCache.containsKey(type)) {
      data=(byte[])serializedDataCache.get(type);
    }
 else {
      ByteArrayOutputStream bytes=new ByteArrayOutputStream();
      DataOutputStream stream=new DataOutputStream(bytes);
      stream.writeShort(ObjectStreamConstants.STREAM_MAGIC);
      stream.writeShort(ObjectStreamConstants.STREAM_VERSION);
      stream.writeByte(ObjectStreamConstants.TC_OBJECT);
      stream.writeByte(ObjectStreamConstants.TC_CLASSDESC);
      stream.writeUTF(type.getName());
      stream.writeLong(ObjectStreamClass.lookup(type).getSerialVersionUID());
      stream.writeByte(2);
      stream.writeShort(0);
      stream.writeByte(ObjectStreamConstants.TC_ENDBLOCKDATA);
      stream.writeByte(ObjectStreamConstants.TC_NULL);
      data=bytes.toByteArray();
      serializedDataCache.put(type,data);
    }
    ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(data));
    return in.readObject();
  }
 catch (  IOException e) {
    throw new ObjectAccessException("Cannot create " + type.getName() + " by JDK serialization",e);
  }
catch (  ClassNotFoundException e) {
    throw new ObjectAccessException("Cannot find class " + e.getMessage());
  }
}
 

Example 48

From project Android-FFXIEQ, under directory /ffxieq/src/com/github/kanata3249/ffxieq/android/db/.

Source file: FFXIEQSettings.java

  31 
vote

public long saveCharInfo(long id,String name,FFXICharacter charInfo){
  byte[] chardata;
  charInfo.reload();
  try {
    ObjectOutputStream oos;
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    ;
    oos=new ObjectOutputStream(baos);
    oos.writeObject(charInfo);
    oos.close();
    chardata=baos.toByteArray();
    baos.close();
  }
 catch (  IOException e) {
    return -1;
  }
  return saveCharInfo(id,name,chardata,charInfo.getMeritPointId());
}
 

Example 49

From project android-rackspacecloud, under directory /extensions/bouncycastle/src/main/java/org/jclouds/encryption/bouncycastle/.

Source file: BouncyCastleEncryptionService.java

  31 
vote

public MD5InputStreamResult generateMD5Result(InputStream toEncode){
  MD5Digest eTag=new MD5Digest();
  byte[] resBuf=new byte[eTag.getDigestSize()];
  byte[] buffer=new byte[1024];
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  long length=0;
  int numRead=-1;
  try {
    do {
      numRead=toEncode.read(buffer);
      if (numRead > 0) {
        length+=numRead;
        eTag.update(buffer,0,numRead);
        out.write(buffer,0,numRead);
      }
    }
 while (numRead != -1);
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
 finally {
    Closeables.closeQuietly(out);
    Closeables.closeQuietly(toEncode);
  }
  eTag.doFinal(resBuf,0);
  return new MD5InputStreamResult(out.toByteArray(),resBuf,length);
}
 

Example 50

From project android-share-menu, under directory /src/com/eggie5/.

Source file: post_to_eggie5.java

  31 
vote

public static byte[] getBytesFromFile(InputStream is){
  try {
    ByteArrayOutputStream buffer=new ByteArrayOutputStream();
    int nRead;
    byte[] data=new byte[16384];
    while ((nRead=is.read(data,0,data.length)) != -1) {
      buffer.write(data,0,nRead);
    }
    buffer.flush();
    return buffer.toByteArray();
  }
 catch (  IOException e) {
    Log.e("com.eggie5.post_to_eggie5",e.toString());
    return null;
  }
}
 

Example 51

From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/synchronisation/tracks/.

Source file: WebClient.java

  31 
vote

public synchronized String getUrlContent(String url) throws ApiException {
  if (sUserAgent == null) {
    throw new ApiException("User-Agent string must be prepared");
  }
  HttpClient client=CreateClient();
  java.net.URI uri=URI.create(url);
  HttpHost host=GetHost(uri);
  HttpGet request=new HttpGet(uri.getPath());
  request.setHeader("User-Agent",sUserAgent);
  try {
    HttpResponse response=client.execute(host,request);
    StatusLine status=response.getStatusLine();
    Log.i(cTag,"get with response " + status.toString());
    if (status.getStatusCode() != HttpStatus.SC_OK) {
      throw new ApiException("Invalid response from server: " + status.toString());
    }
    HttpEntity entity=response.getEntity();
    InputStream inputStream=entity.getContent();
    ByteArrayOutputStream content=new ByteArrayOutputStream();
    int readBytes;
    while ((readBytes=inputStream.read(sBuffer)) != -1) {
      content.write(sBuffer,0,readBytes);
    }
    return new String(content.toByteArray());
  }
 catch (  IOException e) {
    throw new ApiException("Problem communicating with API",e);
  }
}
 

Example 52

From project android_5, under directory /src/aarddict/.

Source file: Volume.java

  31 
vote

static String decompressZlib(byte[] bytes) throws IOException, DataFormatException {
  Inflater decompressor=new Inflater();
  decompressor.setInput(bytes);
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  try {
    byte[] buf=new byte[1024];
    while (!decompressor.finished()) {
      int count=decompressor.inflate(buf);
      out.write(buf,0,count);
    }
  }
  finally {
    out.close();
  }
  return utf8(out.toByteArray());
}
 

Example 53

From project android_build, under directory /tools/signapk/.

Source file: SignApk.java

  31 
vote

private static void signWholeOutputFile(byte[] zipData,OutputStream outputStream,X509Certificate publicKey,PrivateKey privateKey) throws IOException, GeneralSecurityException {
  if (zipData[zipData.length - 22] != 0x50 || zipData[zipData.length - 21] != 0x4b || zipData[zipData.length - 20] != 0x05 || zipData[zipData.length - 19] != 0x06) {
    throw new IllegalArgumentException("zip data already has an archive comment");
  }
  Signature signature=Signature.getInstance("SHA1withRSA");
  signature.initSign(privateKey);
  signature.update(zipData,0,zipData.length - 2);
  ByteArrayOutputStream temp=new ByteArrayOutputStream();
  byte[] message="signed by SignApk".getBytes("UTF-8");
  temp.write(message);
  temp.write(0);
  writeSignatureBlock(signature,publicKey,temp);
  int total_size=temp.size() + 6;
  if (total_size > 0xffff) {
    throw new IllegalArgumentException("signature is too big for ZIP file comment");
  }
  int signature_start=total_size - message.length - 1;
  temp.write(signature_start & 0xff);
  temp.write((signature_start >> 8) & 0xff);
  temp.write(0xff);
  temp.write(0xff);
  temp.write(total_size & 0xff);
  temp.write((total_size >> 8) & 0xff);
  temp.flush();
  byte[] b=temp.toByteArray();
  for (int i=0; i < b.length - 3; ++i) {
    if (b[i] == 0x50 && b[i + 1] == 0x4b && b[i + 2] == 0x05 && b[i + 3] == 0x06) {
      throw new IllegalArgumentException("found spurious EOCD header at " + i);
    }
  }
  outputStream.write(zipData,0,zipData.length - 2);
  outputStream.write(total_size & 0xff);
  outputStream.write((total_size >> 8) & 0xff);
  temp.writeTo(outputStream);
}
 

Example 54

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/adapter/.

Source file: Parser.java

  31 
vote

/** 
 * Read an inline string from the stream
 * @return the String as parsed from the stream
 * @throws IOException
 */
private String readInlineString() throws IOException {
  ByteArrayOutputStream outputStream=new ByteArrayOutputStream(256);
  while (true) {
    int i=read();
    if (i == 0) {
      break;
    }
 else     if (i == EOF_BYTE) {
      throw new EofException();
    }
    outputStream.write(i);
  }
  outputStream.flush();
  String res=outputStream.toString("UTF-8");
  outputStream.close();
  return res;
}
 

Example 55

From project android_packages_apps_Gallery, under directory /src/com/android/camera/.

Source file: PhotoAppWidgetProvider.java

  31 
vote

/** 
 * Store the given bitmap in this database for the given appWidgetId.
 */
public boolean setPhoto(int appWidgetId,Bitmap bitmap){
  boolean success=false;
  try {
    int size=bitmap.getWidth() * bitmap.getHeight() * 4;
    ByteArrayOutputStream out=new ByteArrayOutputStream(size);
    bitmap.compress(Bitmap.CompressFormat.PNG,100,out);
    out.flush();
    out.close();
    ContentValues values=new ContentValues();
    values.put(PhotoDatabaseHelper.FIELD_APPWIDGET_ID,appWidgetId);
    values.put(PhotoDatabaseHelper.FIELD_PHOTO_BLOB,out.toByteArray());
    SQLiteDatabase db=getWritableDatabase();
    db.insertOrThrow(PhotoDatabaseHelper.TABLE_PHOTOS,null,values);
    success=true;
  }
 catch (  SQLiteException e) {
    Log.e(TAG,"Could not open database",e);
  }
catch (  IOException e) {
    Log.e(TAG,"Could not serialize photo",e);
  }
  if (LOGD) {
    Log.d(TAG,"setPhoto success=" + success);
  }
  return success;
}
 

Example 56

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/app/.

Source file: MoviePlayer.java

  31 
vote

public void setBookmark(Uri uri,int bookmark,int duration){
  try {
    BlobCache cache=CacheManager.getCache(mContext,BOOKMARK_CACHE_FILE,BOOKMARK_CACHE_MAX_ENTRIES,BOOKMARK_CACHE_MAX_BYTES,BOOKMARK_CACHE_VERSION);
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    DataOutputStream dos=new DataOutputStream(bos);
    dos.writeUTF(uri.toString());
    dos.writeInt(bookmark);
    dos.writeInt(duration);
    dos.flush();
    cache.insert(uri.hashCode(),bos.toByteArray());
  }
 catch (  Throwable t) {
    Log.w(TAG,"setBookmark failed",t);
  }
}
 

Example 57

From project android_packages_apps_Nfc, under directory /src/com/android/nfc/ndefpush/.

Source file: NdefPushProtocol.java

  31 
vote

public byte[] toByteArray(){
  ByteArrayOutputStream buffer=new ByteArrayOutputStream(1024);
  DataOutputStream output=new DataOutputStream(buffer);
  try {
    output.writeByte(VERSION);
    output.writeInt(mNumMessages);
    for (int i=0; i < mNumMessages; i++) {
      output.writeByte(mActions[i]);
      byte[] bytes=mMessages[i].toByteArray();
      output.writeInt(bytes.length);
      output.write(bytes);
    }
  }
 catch (  java.io.IOException e) {
    return null;
  }
  return buffer.toByteArray();
}
 

Example 58

From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/impl/util/.

Source file: SerializationUtil.java

  31 
vote

public static byte[] serializeToByteArray(Serializable o){
  try {
    ByteArrayOutputStream bytes=new ByteArrayOutputStream();
    ObjectOutputStream out=new ObjectOutputStream(bytes);
    try {
      out.writeObject(o);
    }
  finally {
      out.close();
    }
    return bytes.toByteArray();
  }
 catch (  IOException e) {
    throw new RuntimeException("Can't serialize object: " + o,e);
  }
}
 

Example 59

From project Archimedes, under directory /br.org.archimedes.io.svg.tests/test/br/org/archimedes/io/svg/elements/.

Source file: PolylineExporterTest.java

  31 
vote

@Before public void setUp() throws Exception {
  List<Point> list=new ArrayList<Point>();
  list.add(new Point(0,0));
  list.add(new Point(0,100));
  list.add(new Point(100,0));
  list.add(new Point(100,100));
  polyline=new Polyline(list);
  exporter=new PolylineExporter();
  stream=new ByteArrayOutputStream();
}
 

Example 60

From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/rsrc/.

Source file: ValueUtils.java

  31 
vote

public static <T extends Value>T valueOf(Class<T> clazz,InputStream in) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  try {
    StreamUtils.copy(in,baos);
  }
  finally {
    IoUtils.close(baos);
  }
  try {
    Constructor<T> constructor=clazz.getConstructor(byte[].class);
    return constructor.newInstance(baos.toByteArray());
  }
 catch (  SecurityException e) {
    throw new IOException("SecurityException",e);
  }
catch (  NoSuchMethodException e) {
    throw new IOException("NoSuchMethodException",e);
  }
catch (  IllegalArgumentException e) {
    throw new IOException("IllegalArgumentException",e);
  }
catch (  InstantiationException e) {
    throw new IOException("InstantiationException",e);
  }
catch (  IllegalAccessException e) {
    throw new IOException("IllegalAccessException",e);
  }
catch (  InvocationTargetException e) {
    throw new IOException("InvocationTargetException",e);
  }
}
 

Example 61

From project aether-core, under directory /aether-api/src/test/java/org/eclipse/aether/.

Source file: RepositoryExceptionTest.java

  29 
vote

private void assertSerializable(RepositoryException e){
  try {
    ObjectOutputStream oos=new ObjectOutputStream(new ByteArrayOutputStream());
    oos.writeObject(e);
    oos.close();
  }
 catch (  IOException ioe) {
    throw new IllegalStateException(ioe);
  }
}
 

Example 62

From project android-thaiime, under directory /latinime/src/com/android/inputmethod/deprecated/voice/.

Source file: RecognitionView.java

  29 
vote

public void showWorking(final ByteArrayOutputStream waveBuffer,final int speechStartPosition,final int speechEndPosition){
  mUiHandler.post(new Runnable(){
    @Override public void run(){
      mState=WORKING;
      prepareDialog(mContext.getText(R.string.voice_working),null,mContext.getText(R.string.cancel));
      final ShortBuffer buf=ByteBuffer.wrap(waveBuffer.toByteArray()).order(ByteOrder.nativeOrder()).asShortBuffer();
      buf.position(0);
      waveBuffer.reset();
      showWave(buf,speechStartPosition / 2,speechEndPosition / 2);
    }
  }
);
}
 

Example 63

From project android_packages_inputmethods_LatinIME, under directory /java/src/com/android/inputmethod/deprecated/voice/.

Source file: RecognitionView.java

  29 
vote

public void showWorking(final ByteArrayOutputStream waveBuffer,final int speechStartPosition,final int speechEndPosition){
  mUiHandler.post(new Runnable(){
    @Override public void run(){
      mState=WORKING;
      prepareDialog(mContext.getText(R.string.voice_working),null,mContext.getText(R.string.cancel));
      final ShortBuffer buf=ByteBuffer.wrap(waveBuffer.toByteArray()).order(ByteOrder.nativeOrder()).asShortBuffer();
      buf.position(0);
      waveBuffer.reset();
      showWave(buf,speechStartPosition / 2,speechEndPosition / 2);
    }
  }
);
}