Java Code Examples for java.io.DataOutputStream
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 activemq-apollo, under directory /apollo-openwire/src/main/scala/org/apache/activemq/apollo/openwire/command/.
Source file: Message.java

public void beforeMarshall(OpenWireFormat wireFormat) throws IOException { if (marshalledProperties == null && properties != null) { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream os=new DataOutputStream(baos); MarshallingSupport.marshalPrimitiveMap(properties,os); os.close(); marshalledProperties=baos.toBuffer(); } }
Example 2
From project akela, under directory /src/main/java/com/mozilla/hadoop/hbase/mapreduce/.
Source file: MultiScanTableMapReduceUtil.java

/** * 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 3
From project android-client_1, under directory /src/com/googlecode/asmack/dns/.
Source file: Question.java

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 4
From project AsmackService, under directory /src/com/googlecode/asmack/dns/.
Source file: Question.java

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 5
From project blacktie, under directory /blacktie-admin-services/src/main/java/org/jboss/narayana/blacktie/administration/.
Source file: BlacktieAdminServiceXATMI.java

private byte[] convertLong(long response) throws IOException { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); ByteBuffer bbuf=ByteBuffer.allocate(BufferImpl.LONG_SIZE); bbuf.order(ByteOrder.BIG_ENDIAN); bbuf.putLong(response); bbuf.order(ByteOrder.LITTLE_ENDIAN); long toWrite=bbuf.getLong(0); dos.writeLong(toWrite); dos.flush(); baos.flush(); return baos.toByteArray(); }
Example 6
From project camel-beanstalk, under directory /src/test/java/com/osinka/camel/beanstalk/.
Source file: Helper.java

public static byte[] stringToBytes(final String s) throws IOException { final ByteArrayOutputStream byteOS=new ByteArrayOutputStream(); final DataOutputStream dataStream=new DataOutputStream(byteOS); try { dataStream.writeBytes(s); dataStream.flush(); return byteOS.toByteArray(); } finally { dataStream.close(); byteOS.close(); } }
Example 7
From project Carolina-Digital-Repository, under directory /djatoka-cdr/src/gov/lanl/adore/djatoka/io/writer/.
Source file: TIFWriter.java

private void writeUsingImageJ(BufferedImage bi,OutputStream os) throws FormatIOException { ImagePlus imp=new ImagePlus("tempTif",bi); TiffEncoder encoder=new TiffEncoder(imp.getFileInfo()); DataOutputStream out=new DataOutputStream(new BufferedOutputStream(os)); try { encoder.write(out); } catch ( IOException e) { logger.error(e); throw new FormatIOException(e); } }
Example 8
public boolean write(OutputStream out,InputStream in) throws IOException { DataOutputStream dOut=new DataOutputStream(out); byte[] dataNullTerm=nullTerminate(data); for (int i=0; i < SERIAL_MAX_RETRY; i++) { dOut.writeInt(PACKET_KEY); dOut.writeInt(dataNullTerm.length); dOut.write(dataNullTerm); if (checkAck(in)) return true; } return false; }
Example 9
From project chukwa, under directory /src/test/java/org/apache/hadoop/chukwa/validationframework/interceptor/.
Source file: ChunkDumper.java

static void close(){ Iterator<String> it=hash.keySet().iterator(); while (it.hasNext()) { String key=it.next(); DataOutputStream dos=hash.get(key); try { dos.close(); } catch ( Exception e) { e.printStackTrace(); } } }
Example 10
From project ciel-java, under directory /examples/kmeans/src/java/skywriting/examples/kmeans/.
Source file: KMeansDataGenerator.java

@Override public void invoke() throws Exception { double minValue=-1000000.0; double maxValue=1000000.0; WritableReference out=Ciel.RPC.getOutputFilename(0); DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(out.open(),1048576)); Random rand=new Random(this.seed); for (int i=0; i < this.numVectors; ++i) { for (int j=0; j < this.numDimensions; ++j) { dos.writeDouble((rand.nextDouble() * (maxValue - minValue)) + minValue); } } dos.close(); }
Example 11
From project Cloud9, under directory /src/dist/edu/umd/cloud9/example/bfs/.
Source file: BFSNode.java

/** * Returns the serialized representation of this object as a byte array. * @return byte array representing the serialized representation of this object * @throws IOException */ public byte[] serialize() throws IOException { ByteArrayOutputStream bytesOut=new ByteArrayOutputStream(); DataOutputStream dataOut=new DataOutputStream(bytesOut); write(dataOut); return bytesOut.toByteArray(); }
Example 12
From project core_3, under directory /src/main/java/org/animotron/manipulator/.
Source file: PFlow.java

public byte[] getPathHash(){ ByteArrayOutputStream bos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(bos); if (path == null) return new byte[0]; try { path.collectHash(dos); } catch ( IOException e) { } MessageDigest md=MessageDigester.md(); md.update(bos.toByteArray()); return md.digest(); }
Example 13
From project CraftMania, under directory /CraftMania/src/org/craftmania/world/characters/.
Source file: Player.java

public void save() throws IOException { File file=Game.getInstance().getRelativeFile(Game.FILE_BASE_USER_DATA,"${world}/player.dat"); DataOutputStream dos=new DataOutputStream(new FileOutputStream(file)); IOUtilities.writeVec3f(dos,getPosition()); dos.writeInt(_rotationSegment); IOUtilities.writeVec3f(dos,getSpawnPoint()); InventoryIO.writeInventory(getInventory(),dos,0,getInventory().size()); dos.writeByte(_selectedInventoryItemIndex); dos.close(); }
Example 14
From project crammer, under directory /src/main/java/uk/ac/ebi/ena/sra/cram/impl/.
Source file: CramWriter.java

private void flushWriterOS() throws IOException { ExposedByteArrayOutputStream compressedOS=new ExposedByteArrayOutputStream(1024); GZIPOutputStream gos=new GZIPOutputStream(compressedOS); gos.write(writerOS.getBuffer(),0,writerOS.size()); gos.close(); writerOS.reset(); DataOutputStream dos=new DataOutputStream(os); dos.writeInt(compressedOS.size()); dos.write(compressedOS.getBuffer(),0,compressedOS.size()); dos.flush(); }
Example 15
From project crest, under directory /core/src/main/java/org/codegist/crest/entity/multipart/.
Source file: MultiPartOctetStreamSerializer.java

public void serialize(MultiPart<T> multipart,Charset charset,OutputStream outputStream) throws Exception { ParamConfig pc=multipart.getParamConfig(); String fileName=getFileName(multipart); String contentType=getContentType(multipart); StringBuilder headerSb=new StringBuilder().append("--").append(multipart.getBoundary()).append(LRLN).append("Content-Disposition: form-data; name=\"").append(pc.getName()).append("\""); if (isNotBlank(fileName)) { headerSb.append("; filename=\"").append(fileName).append("\""); } headerSb.append(LRLN).append("Content-Type: ").append(contentType).append(LRLN).append(LRLN); DataOutputStream out=new DataOutputStream(outputStream); out.writeBytes(headerSb.toString()); pc.getSerializer().serialize(multipart.getValue(),charset,out); out.writeBytes(LRLN); }
Example 16
From project crunch, under directory /crunch/src/main/java/org/apache/crunch/io/hbase/.
Source file: HBaseSourceTarget.java

static String convertScanToString(Scan scan) throws IOException { ByteArrayOutputStream out=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(out); scan.write(dos); return Base64.encodeBytes(out.toByteArray()); }
Example 17
From project culvert, under directory /culvert-main/src/test/java/com/bah/culvert/test/.
Source file: Utils.java

/** * Checks if the writable will successfully read and write using {@link Writable}'s methods. * @param writeable * @return The instance read in using{@link Writable#readFields(java.io.DataInput)}. Can be used for checking equality. * @throws InstantiationException * @throws IllegalAccessException * @throws IOException */ public static Writable testReadWrite(Writable writeable) throws InstantiationException, IllegalAccessException, IOException { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); writeable.write(dos); ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray()); DataInputStream dis=new DataInputStream(bais); Writable inst=writeable.getClass().newInstance(); inst.readFields(dis); return inst; }
Example 18
From project daily-money, under directory /dailymoney/src/com/bottleworks/dailymoney/calculator2/.
Source file: Persist.java

void save(){ try { OutputStream os=new BufferedOutputStream(mContext.openFileOutput(FILE_NAME,0),8192); DataOutputStream out=new DataOutputStream(os); out.writeInt(LAST_VERSION); history.write(out); out.close(); } catch ( IOException e) { Calculator.log("" + e); } }
Example 19
From project datasalt-utils, under directory /src/main/java/com/datasalt/utils/commons/.
Source file: WritableUtils.java

/** * Serialize writable */ public static byte[] serialize(Writable datum) throws IOException { ByteArrayOutputStream bos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(bos); datum.write(dos); return bos.toByteArray(); }
Example 20
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/eventHandling/.
Source file: NetworkHandler.java

public NetworkHandler(String host,int port){ commandStack=new ClientCommands(this); try { s=new Socket(host,port); is=new DataInputStream(s.getInputStream()); os=new DataOutputStream(s.getOutputStream()); } catch ( Exception e) { System.err.println("No connection"); e.printStackTrace(); connected=false; } }
Example 21
From project accent, under directory /src/test/java/net/lshift/accent/.
Source file: ControlledConnectionProxy.java

public void run(){ try { this.inServer=new ServerSocket(listenPort); inServer.setReuseAddress(true); this.inSock=inServer.accept(); this.outSock=new Socket(host,port); DataInputStream iis=new DataInputStream(this.inSock.getInputStream()); DataOutputStream ios=new DataOutputStream(this.inSock.getOutputStream()); DataInputStream ois=new DataInputStream(this.outSock.getInputStream()); DataOutputStream oos=new DataOutputStream(this.outSock.getOutputStream()); byte[] handshake=new byte[8]; iis.readFully(handshake); oos.write(handshake); BlockingCell<Exception> wio=new BlockingCell<Exception>(); new Thread(new DirectionHandler(wio,true,iis,oos)).start(); new Thread(new DirectionHandler(wio,false,ois,ios)).start(); waitAndLogException(wio); } catch ( Exception e) { reportAndLogNonNullException(e); } finally { try { if (this.inSock != null) this.inSock.close(); } catch ( Exception e) { logException(e); } try { if (this.outSock != null) this.outSock.close(); } catch ( Exception e) { logException(e); } this.reportEnd.setIfUnset(null); } }
Example 22
/** * Writes a log entry into the log file of the respective ontology. * @param type The type of the log entry. * @param text The text of the log entry. */ public void log(String type,String text){ Calendar c=Calendar.getInstance(); long timestamp=System.currentTimeMillis(); c.setTimeInMillis(timestamp); String year=c.get(Calendar.YEAR) + ""; String month=makeString(c.get(Calendar.MONTH) + 1,2); String day=makeString(c.get(Calendar.DAY_OF_MONTH),2); String hour=makeString(c.get(Calendar.HOUR_OF_DAY),2); String min=makeString(c.get(Calendar.MINUTE),2); String sec=makeString(c.get(Calendar.SECOND),2); String millis=makeString(c.get(Calendar.MILLISECOND),3); String dateTime=year + "-" + month+ "-"+ day+ " "+ hour+ ":"+ min+ ":"+ sec+ "."+ millis; String session=makeString(sessionID,4); String un; if (username == null || username.equals("")) { un=""; } else { un=" '" + username + "'"; } String dir="logs"; String fn=fileName; if (fileName.indexOf("/") > -1) { dir=fileName.replaceFirst("(.*)/[^/]*","$1"); fn=fileName.replaceFirst(".*/([^/]*)","$1"); } try { if (!(new File(dir)).exists()) (new File(dir)).mkdir(); DataOutputStream out=new DataOutputStream(new FileOutputStream(dir + "/" + fn+ ".log",true)); out.writeBytes(timestamp + " (" + dateTime+ ") ["+ session+ "]"+ un+ " ["+ type+ "] "+ text.replaceAll("\\n","~n")+ "\n"); out.flush(); out.close(); } catch ( IOException ex) { ex.printStackTrace(); } }
Example 23
From project aim3-tu-berlin, under directory /seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/one/.
Source file: PrimeNumbersWritableTest.java

@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 24
From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/io/file/.
Source file: FileUtils.java

/** * Reads a file into a byte array. * @param file The file to read, required. * @return The data in the file as a byte array. * @throws IOException If the file could not be read. */ public static byte[] readFileAsBytes(final File file) throws IOException { AjahUtils.requireParam(file,"file"); if (!file.exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } final FileInputStream in=new FileInputStream(file); final ByteArrayOutputStream baos=new ByteArrayOutputStream(); final DataOutputStream dos=new DataOutputStream(baos); final byte[] data=new byte[4096]; int count=in.read(data); while (count != -1) { dos.write(data,0,count); count=in.read(data); } return baos.toByteArray(); }
Example 25
From project AlbiteREADER, under directory /src/org/albite/albite/.
Source file: AlbiteMIDlet.java

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 26
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/bean/.
Source file: PureJavaReflectionProvider.java

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 27
From project android-aac-enc, under directory /src/com/googlecode/mp4parser/authoring/tracks/.
Source file: TextTrackImpl.java

public List<ByteBuffer> getSamples(){ List<ByteBuffer> samples=new LinkedList<ByteBuffer>(); long lastEnd=0; for ( Line sub : subs) { long silentTime=sub.from - lastEnd; if (silentTime > 0) { samples.add(ByteBuffer.wrap(new byte[]{0,0})); } else if (silentTime < 0) { throw new Error("Subtitle display times may not intersect"); } ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); try { dos.writeShort(sub.text.getBytes("UTF-8").length); dos.write(sub.text.getBytes("UTF-8")); dos.close(); } catch ( IOException e) { throw new Error("VM is broken. Does not support UTF-8"); } samples.add(ByteBuffer.wrap(baos.toByteArray())); lastEnd=sub.to; } return samples; }
Example 28
From project android_packages_apps_Gallery, under directory /src/com/android/camera/.
Source file: ThumbnailController.java

public boolean storeData(String filePath){ if (mUri == null) { return false; } FileOutputStream f=null; BufferedOutputStream b=null; DataOutputStream d=null; try { f=new FileOutputStream(filePath); b=new BufferedOutputStream(f,BUFSIZE); d=new DataOutputStream(b); d.writeUTF(mUri.toString()); mThumb.compress(Bitmap.CompressFormat.PNG,100,d); d.close(); } catch ( IOException e) { return false; } finally { MenuHelper.closeSilently(f); MenuHelper.closeSilently(b); MenuHelper.closeSilently(d); } return true; }
Example 29
From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/app/.
Source file: MoviePlayer.java

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 30
From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/cache/.
Source file: CacheService.java

private static final void putLocaleForAlbumCache(final Locale locale){ final ByteArrayOutputStream bos=new ByteArrayOutputStream(); final DataOutputStream dos=new DataOutputStream(bos); try { Utils.writeUTF(dos,locale.getCountry()); Utils.writeUTF(dos,locale.getLanguage()); Utils.writeUTF(dos,locale.getVariant()); dos.flush(); bos.flush(); final byte[] data=bos.toByteArray(); sAlbumCache.put(ALBUM_CACHE_LOCALE_INDEX,data,0); sAlbumCache.flush(); dos.close(); bos.close(); } catch ( IOException e) { if (DEBUG) Log.i(TAG,"Error writing locale to cache."); ; } }
Example 31
From project android_packages_apps_Nfc, under directory /src/com/android/nfc/ndefpush/.
Source file: NdefPushProtocol.java

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 32
From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/util/.
Source file: Util.java

public static String getSuVersion(){ Process process=null; String inLine=null; try { process=Runtime.getRuntime().exec("sh"); DataOutputStream os=new DataOutputStream(process.getOutputStream()); BufferedReader is=new BufferedReader(new InputStreamReader(new DataInputStream(process.getInputStream())),64); os.writeBytes("su -v\n"); for (int i=0; i < 400; i++) { if (is.ready()) { break; } try { Thread.sleep(5); } catch ( InterruptedException e) { Log.w(TAG,"Sleep timer got interrupted..."); } } if (is.ready()) { inLine=is.readLine(); if (inLine != null) { return inLine; } } else { os.writeBytes("exit\n"); } } catch ( IOException e) { Log.e(TAG,"Problems reading current version.",e); return null; } finally { if (process != null) { process.destroy(); } } return null; }
Example 33
From project archive-commons, under directory /ia-tools/src/test/java/org/archive/hadoop/storage/.
Source file: ZipnumRecordWriterTest.java

public void testCreate() throws IOException, InterruptedException { File m=new File("/tmp/main.gz"); File s=new File("/tmp/summ.txt"); DataOutputStream outM=new DataOutputStream(new FileOutputStream(m)); DataOutputStream outS=new DataOutputStream(new FileOutputStream(s)); ZipNumRecordWriter w=new ZipNumRecordWriter(20,outM,outS); Text key=new Text(); Text val=new Text(); for (int i=0; i < 200; i++) { key.set(String.format("Line number %06d",i).getBytes(IAUtils.UTF8)); val.set(String.format("Value %06d",i).getBytes(IAUtils.UTF8)); w.write(key,val); } w.close(null); }
Example 34
From project Arecibo, under directory /collector/src/test/java/com/ning/arecibo/collector/.
Source file: TestTimelineChunkAndTimes.java

@Test(groups="fast") public void testToString() throws Exception { final int sampleCount=3; final DateTime startTime=new DateTime("2012-01-16T21:23:58.000Z",DateTimeZone.UTC); final List<DateTime> dateTimes=new ArrayList<DateTime>(); final ByteArrayOutputStream out=new ByteArrayOutputStream(); final DataOutputStream stream=new DataOutputStream(out); for (int i=0; i < sampleCount; i++) { sampleCoder.encodeSample(stream,new ScalarSample<Long>(SampleOpcode.LONG,12345L + i)); dateTimes.add(startTime.plusSeconds(1 + i)); } final DateTime endTime=dateTimes.get(dateTimes.size() - 1); final byte[] times=timelineCoder.compressDateTimes(dateTimes); final TimelineChunk timelineChunk=new TimelineChunk(sampleCoder,CHUNK_ID,HOST_ID,SAMPLE_KIND_ID,startTime,endTime,times,out.toByteArray(),sampleCount); Assert.assertEquals(timelineChunk.getSamplesAsCSV(),"1326749039,12345,1326749040,12346,1326749041,12347"); Assert.assertEquals(timelineChunk.getSamplesAsCSV(null,null),"1326749039,12345,1326749040,12346,1326749041,12347"); Assert.assertEquals(timelineChunk.getSamplesAsCSV(startTime,null),"1326749039,12345,1326749040,12346,1326749041,12347"); Assert.assertEquals(timelineChunk.getSamplesAsCSV(null,startTime.plusSeconds(sampleCount)),"1326749039,12345,1326749040,12346,1326749041,12347"); Assert.assertEquals(timelineChunk.getSamplesAsCSV(startTime.plusSeconds(1),startTime.plusSeconds(sampleCount)),"1326749039,12345,1326749040,12346,1326749041,12347"); Assert.assertEquals(timelineChunk.getSamplesAsCSV(startTime.plusSeconds(2),startTime.plusSeconds(sampleCount)),"1326749040,12346,1326749041,12347"); Assert.assertEquals(timelineChunk.getSamplesAsCSV(startTime.plusSeconds(3),startTime.plusSeconds(sampleCount)),"1326749041,12347"); Assert.assertEquals(timelineChunk.getSamplesAsCSV(startTime.plusSeconds(4),startTime.plusSeconds(sampleCount)),""); Assert.assertEquals(timelineChunk.getSamplesAsCSV(startTime.plusSeconds(10),startTime.plusSeconds(sampleCount)),""); Assert.assertEquals(timelineChunk.getSamplesAsCSV(startTime,startTime.minusSeconds(1)),""); }
Example 35
From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/commons/.
Source file: SerialVersionUIDAdder.java

/** * Returns the value of SVUID if the class doesn't have one already. Please note that 0 is returned if the class already has SVUID, thus use <code>isHasSVUID</code> to determine if the class already had an SVUID. * @return Returns the serial version UID * @throws IOException */ protected long computeSVUID() throws IOException { ByteArrayOutputStream bos=null; DataOutputStream dos=null; long svuid=0; try { bos=new ByteArrayOutputStream(); dos=new DataOutputStream(bos); dos.writeUTF(name.replace('/','.')); dos.writeInt(access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_INTERFACE| Opcodes.ACC_ABSTRACT)); Arrays.sort(interfaces); for (int i=0; i < interfaces.length; i++) { dos.writeUTF(interfaces[i].replace('/','.')); } writeItems(svuidFields,dos,false); if (hasStaticInitializer) { dos.writeUTF("<clinit>"); dos.writeInt(Opcodes.ACC_STATIC); dos.writeUTF("()V"); } writeItems(svuidConstructors,dos,true); writeItems(svuidMethods,dos,true); dos.flush(); byte[] hashBytes=computeSHAdigest(bos.toByteArray()); for (int i=Math.min(hashBytes.length,8) - 1; i >= 0; i--) { svuid=(svuid << 8) | (hashBytes[i] & 0xFF); } } finally { if (dos != null) { dos.close(); } } return svuid; }
Example 36
From project Backyard-Brains-Android-App, under directory /src/com/backyardbrains/audio/.
Source file: RecordingSaver.java

/** * Create a the BackyardBrains directory on the sdcard if it doesn't exist, then set up a file output stream in that directory which we'll use to write to later * @param filename */ private void initializeAndCreateFile(String filename){ bybDirectory=createBybDirectory(); mArrayToRecordTo=new ByteArrayOutputStream(); try { bufferedStream=new BufferedOutputStream(mArrayToRecordTo); } catch ( Exception e) { throw new IllegalStateException("Cannot open file for writing",e); } dataOutputStreamInstance=new DataOutputStream(bufferedStream); }
Example 37
From project bdb-index, under directory /src/main/java/org/neo4j/index/bdbje/.
Source file: BerkeleyDbBatchInserterIndex.java

@Override public void add(long entityId,Map<String,Object> properties){ try { for ( Map.Entry<String,Object> entry : properties.entrySet()) { String key=entry.getKey(); Database db=dbs.get(key); if (null == db) { db=createDB(key); dbs.put(key,db); } String value=entry.getValue().toString(); DatabaseEntry valueEntry=new DatabaseEntry(value.getBytes("UTF-8")); ByteArrayOutputStream baus=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baus); dos.writeLong(entityId); dos.flush(); db.put(null,valueEntry,new DatabaseEntry(baus.toByteArray())); dos.close(); } } catch ( Exception e) { throw new RuntimeException(e); } }
Example 38
From project Bit4Tat, under directory /Bit4Tat/src/com/Bit4Tat/.
Source file: PaymentProcessorForMtGox.java

@Override public ResponseContainer checkBalance(){ HttpsURLConnection conn=setupConnection(CHECK_BALANCE); try { String data=URLEncoder.encode("name","UTF-8") + "=" + URLEncoder.encode(user,"UTF-8"); data+="&" + URLEncoder.encode("pass","UTF-8") + "="+ URLEncoder.encode(pass.trim(),"UTF-8"); StringBuffer returnString=new StringBuffer(); try { DataOutputStream wr=new DataOutputStream(conn.getOutputStream()); int queryLength=data.length(); wr.writeBytes(data); BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream())); try { response=new ResponseMtGox(); response.parseCheckBalance(rd); } catch ( Exception ex) { System.out.println("Error filling MtGox json in getResponse()."); ex.printStackTrace(); } String line; while ((line=rd.readLine()) != null) { System.out.println(line); returnString.append(line); } wr.close(); rd.close(); } catch ( Exception e) { e.printStackTrace(); } } catch ( Exception e) { e.printStackTrace(); } conn.disconnect(); return response; }
Example 39
From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/web/.
Source file: MultiPartFormOutputStream.java

/** * Creates a new <code>MultiPartFormOutputStream</code> object using the specified output stream and boundary. The boundary is required to be created before using this method, as described in the description for the <code>getContentType(String)</code> method. The boundary is only checked for <code>null</code> or empty string, but it is recommended to be at least 6 characters. (Or use the static createBoundary() method to create one.) * @param os the output stream * @param boundary the boundary * @see #createBoundary() * @see #getContentType(String) */ public MultiPartFormOutputStream(OutputStream os,String boundary){ if (os == null) { throw new IllegalArgumentException("Output stream is required."); } if (boundary == null || boundary.length() == 0) { throw new IllegalArgumentException("Boundary stream is required."); } this.out=new DataOutputStream(os); this.boundary=boundary; }
Example 40
From project clojure, under directory /src/jvm/clojure/asm/commons/.
Source file: SerialVersionUIDAdder.java

/** * Returns the value of SVUID if the class doesn't have one already. Please note that 0 is returned if the class already has SVUID, thus use <code>isHasSVUID</code> to determine if the class already had an SVUID. * @return Returns the serial version UID * @throws IOException */ protected long computeSVUID() throws IOException { ByteArrayOutputStream bos=null; DataOutputStream dos=null; long svuid=0; try { bos=new ByteArrayOutputStream(); dos=new DataOutputStream(bos); dos.writeUTF(name.replace('/','.')); dos.writeInt(access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_INTERFACE| Opcodes.ACC_ABSTRACT)); Arrays.sort(interfaces); for (int i=0; i < interfaces.length; i++) { dos.writeUTF(interfaces[i].replace('/','.')); } writeItems(svuidFields,dos,false); if (hasStaticInitializer) { dos.writeUTF("<clinit>"); dos.writeInt(Opcodes.ACC_STATIC); dos.writeUTF("()V"); } writeItems(svuidConstructors,dos,true); writeItems(svuidMethods,dos,true); dos.flush(); byte[] hashBytes=computeSHAdigest(bos.toByteArray()); for (int i=Math.min(hashBytes.length,8) - 1; i >= 0; i--) { svuid=(svuid << 8) | (hashBytes[i] & 0xFF); } } finally { if (dos != null) { dos.close(); } } return svuid; }
Example 41
From project cogroo4, under directory /lang/pt_br/cogroo-addon/src/org/cogroo/addon/dialogs/reporterror/.
Source file: Login.java

private static void request(boolean quiet,String method,java.net.URL url,Map<String,String> body) throws IOException { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE,"[issuing request: " + method + " "+ url+ "]"); } HttpURLConnection connection=(HttpURLConnection)url.openConnection(); connection.setRequestMethod(method); if (body != null) { connection.setDoOutput(true); OutputStream output=connection.getOutputStream(); DataOutputStream out2=new DataOutputStream(output); out2.writeBytes(convert(body)); } long time=System.currentTimeMillis(); connection.connect(); connection.disconnect(); time=System.currentTimeMillis() - time; if (!quiet) { String header=null; String headerValue=null; int index=0; while ((headerValue=connection.getHeaderField(index)) != null) { header=connection.getHeaderFieldKey(index); if (header == null) { System.out.println(headerValue); } else { System.out.println(header + ": " + headerValue); } index++; } } }
Example 42
From project core_4, under directory /impl/src/main/java/org/richfaces/util/.
Source file: Util.java

public static Object saveResourceState(FacesContext context,Object resource){ if (resource instanceof StateHolderResource) { StateHolderResource stateHolderResource=(StateHolderResource)resource; if (stateHolderResource.isTransient()) { return null; } ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); try { stateHolderResource.writeState(context,dos); } catch ( IOException e) { throw new FacesException(e.getMessage(),e); } finally { try { dos.close(); } catch ( IOException e) { RESOURCE_LOGGER.debug(e.getMessage(),e); } } return baos.toByteArray(); } else if (resource instanceof StateHolder) { StateHolder stateHolder=(StateHolder)resource; if (stateHolder.isTransient()) { return null; } return stateHolder.saveState(context); } return null; }
Example 43
From project cornerstone, under directory /frameworks/base/services/java/com/android/server/am/.
Source file: ActivityManagerService.java

private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list){ File file=getCalledPreBootReceiversFile(); FileOutputStream fos=null; DataOutputStream dos=null; try { Slog.i(TAG,"Writing new set of last done pre-boot receivers..."); fos=new FileOutputStream(file); dos=new DataOutputStream(new BufferedOutputStream(fos,2048)); dos.writeInt(LAST_DONE_VERSION); dos.writeUTF(android.os.Build.VERSION.RELEASE); dos.writeUTF(android.os.Build.VERSION.CODENAME); dos.writeUTF(android.os.Build.VERSION.INCREMENTAL); dos.writeInt(list.size()); for (int i=0; i < list.size(); i++) { dos.writeUTF(list.get(i).getPackageName()); dos.writeUTF(list.get(i).getClassName()); } } catch ( IOException e) { Slog.w(TAG,"Failure writing last done pre-boot receivers",e); file.delete(); } finally { FileUtils.sync(fos); if (dos != null) { try { dos.close(); } catch ( IOException e) { e.printStackTrace(); } } } }
Example 44
From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/company_server/.
Source file: MobileCompanyServer.java

@Override public void run(){ try { DataInputStream in=new DataInputStream(this._sock.getInputStream()); DataOutputStream out=new DataOutputStream(this._sock.getOutputStream()); String numeroCarte=in.readUTF(); if (this._data.utilisateurAuthorise(numeroCarte)) { out.writeChar('A'); out.flush(); System.out.println("Agent identifi?: " + numeroCarte); this.manageClient(in,out); } else { out.writeChar('F'); out.flush(); System.out.println("Echec d'authentification agent : " + numeroCarte); } this._sock.close(); } catch ( Exception ex) { Logger.getLogger(MobileServerThread.class.getName()).log(Level.SEVERE,null,ex); } }
Example 45
From project craftbook, under directory /circuits/src/main/java/com/sk89q/craftbook/plc/.
Source file: PlcIC.java

private void saveState() throws IOException { DataOutputStream out=new DataOutputStream(new FileOutputStream(getStorageLocation())); try { out.writeInt(PLC_STORE_VERSION); out.writeBoolean(error); out.writeUTF(errorString); out.writeUTF(lang.getName()); out.writeUTF(error ? "(error)" : getID()); out.writeUTF(hashCode(codeString)); lang.writeState(state,out); } finally { out.close(); } }
Example 46
From project curator, under directory /curator-recipes/src/main/java/com/netflix/curator/framework/recipes/queue/.
Source file: ItemSerializer.java

static <T>byte[] serialize(MultiItem<T> items,QueueSerializer<T> serializer) throws Exception { ByteArrayOutputStream bytes=new ByteArrayOutputStream(INITIAL_BUFFER_SIZE); DataOutputStream out=new DataOutputStream(bytes); out.writeInt(VERSION); for (; ; ) { T item=items.nextItem(); if (item == null) { break; } byte[] itemBytes=serializer.serialize(item); out.writeByte(ITEM_OPCODE); out.writeInt(itemBytes.length); if (itemBytes.length > 0) { out.write(itemBytes); } } out.writeByte(EOF_OPCODE); out.close(); return bytes.toByteArray(); }
Example 47
private void writeEdgesToDisk() throws IOException { this.edgesFile=File.createTempFile("fastgraph",null); FileOutputStream outStream=new FileOutputStream(this.edgesFile); BufferedOutputStream bufferedStream=new BufferedOutputStream(outStream); this.edgeDataOutputStream=new DataOutputStream(bufferedStream); for ( int edgeData : edges) { this.edgeDataOutputStream.writeInt(edgeData); } this.edges.clear(); usingEdgeDiskCache=true; }
Example 48
private boolean connectSocket(StreamAuthObject object){ Network._socketAddress=new InetSocketAddress(object.ip,object.port); try { Network._socket=SocketFactory.getDefault().createSocket(); Network._socket.connect(Network._socketAddress,Settings._TimeOut); Network._socket.setSoTimeout(Settings._TimeOut); Network._input=new InputStreamReader(Network._socket.getInputStream()); Network._output=new DataOutputStream(Network._socket.getOutputStream()); return true; } catch ( IOException exception) { Log.w(this.getClass().getName(),exception.toString()); } return false; }
Example 49
From project androidquery, under directory /src/com/androidquery/callback/.
Source file: AbstractAjaxCallback.java

private static void writeObject(DataOutputStream dos,String name,Object obj) throws IOException { if (obj == null) return; if (obj instanceof File) { File file=(File)obj; writeData(dos,name,file.getName(),new FileInputStream(file)); } else if (obj instanceof byte[]) { writeData(dos,name,name,new ByteArrayInputStream((byte[])obj)); } else if (obj instanceof InputStream) { writeData(dos,name,name,(InputStream)obj); } else { writeField(dos,name,obj.toString()); } }
Example 50
From project cascading, under directory /src/hadoop/cascading/tuple/hadoop/.
Source file: TupleSerialization.java

public void write(DataOutputStream outputStream,Object object) throws IOException { Class<?> type=object.getClass(); String className=type.getName(); Integer token=tupleSerialization.getTokenFor(className); if (token == null) { LOG.debug("no serialization token found for classname: {}",className); WritableUtils.writeVInt(outputStream,HadoopTupleOutputStream.WRITABLE_TOKEN); WritableUtils.writeString(outputStream,className); } else WritableUtils.writeVInt(outputStream,token); Serializer serializer=serializers.get(type); if (serializer == null) { serializer=tupleSerialization.getNewSerializer(type); serializer.open(outputStream); serializers.put(type,serializer); } try { serializer.serialize(object); } catch ( IOException exception) { LOG.error("failed serializing token: " + token + " with classname: "+ className,exception); throw exception; } }