Java Code Examples for java.io.OutputStream

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 aether-core, under directory /aether-impl/src/main/java/org/eclipse/aether/internal/impl/.

Source file: DefaultFileProcessor.java

  23 
vote

public void write(File target,String data) throws IOException {
  mkdirs(target.getAbsoluteFile().getParentFile());
  OutputStream fos=null;
  try {
    fos=new FileOutputStream(target);
    if (data != null) {
      fos.write(data.getBytes("UTF-8"));
    }
    fos.close();
  }
  finally {
    close(fos);
  }
}
 

Example 2

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

Source file: MysqlMessageEncoder.java

  19 
vote

@Override public void encode(IoSession session,Object message,ProtocolEncoderOutput encoderOut) throws Exception {
  IoBuffer buffer=IoBuffer.allocate(1024);
  OutputStream out=buffer.asOutputStream();
  try {
    encoder.encode((ClientRequest)message,out);
  }
  finally {
    out.close();
  }
  buffer.flip();
  encoderOut.write(buffer);
}
 

Example 3

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

Source file: AdminServlet.java

  18 
vote

@Override public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
  OutputStream o=res.getOutputStream();
  res.setContentType("text/html");
  o.write(("<html>" + "<head>" + "	<title>Admin-page</title>"+ "</head>"+ "<body>"+ "	<table width=700>"+ "		<tr><th colspan=2>Web Settings</th></tr>"+ "		<tr><td>Websites in directory:</td><td>" + WebOptions.web_dir + "</td></tr>"+ "		<tr><td>DB driver:</td><td>"+ DatabaseOptions.db_driver+ "</td></tr>"+ "		<tr><td>DB user:</td><td>"+ DatabaseOptions.db_user+ "</td></tr>"+ "		<tr><td>DB uri:</td><td>"+ DatabaseOptions.db_uri+ "</td></tr>"+ "		<tr><td>Trace/lvl:</td><td>"+ WebOptions.trace_enabled+ "/"+ WebOptions.trace_priority+ "</td></tr>"+ "	</table>"+ "	<table width=700>"+ "		<tr><th colspan=4>Interpreter setting and tests</th></tr>"+ "		<tr><td>Perl:</td><td>"+ WebOptions.perl_enabled+ "</td><td>"+ WebOptions.perl_bin_location+ "</td><td><iframe width=150 height=40 src='admin/tests/perl.cgi'></iframe></td></tr>"+ "		<tr><td>PHP:</td><td>"+ WebOptions.php_enabled+ "</td><td>"+ WebOptions.php_bin_location+ "</td><td><iframe width=150 height=40 src='admin/tests/php.php'></iframe></td></tr>"+ "		<tr><td>Python:</td><td>"+ WebOptions.python_enabled+ "</td><td>"+ WebOptions.python_bin_location+ "</td><td><iframe width=150 height=40 src='admin/tests/python.py'></iframe></td></tr>"+ "	</table>"+ "</body>").getBytes());
  o.flush();
  o.close();
}
 

Example 4

From project activejdbc, under directory /javalite-common/src/main/java/org/javalite/http/.

Source file: Put.java

  18 
vote

@Override public Put doConnect(){
  try {
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("PUT");
    OutputStream os=connection.getOutputStream();
    os.write(content);
    os.flush();
    return this;
  }
 catch (  Exception e) {
    throw new HttpException("Failed URL: " + url,e);
  }
}
 

Example 5

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

Source file: ConvertDiabetesDatasetUtil.java

  18 
vote

public static void main(String[] args) throws JAXBException, ConversionException, IOException {
  InputStream is=new FileInputStream("diabetes-cleaner.addis");
  AddisData addisData=JAXBHandler.unmarshallAddisData(is);
  is.close();
  Domain domain=JAXBConvertor.convertAddisDataToDomain(addisData);
  ConvertDiabetesDatasetUtil util=new ConvertDiabetesDatasetUtil(domain);
  util.run();
  final AddisData out=JAXBConvertor.convertDomainToAddisData(domain);
  OutputStream fileWrite=new FileOutputStream("converted.addis");
  JAXBHandler.marshallAddisData(out,fileWrite);
  fileWrite.close();
}
 

Example 6

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

Source file: TestStreamManager.java

  18 
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 7

From project alfredo, under directory /alfredo/src/test/java/com/cloudera/alfredo/client/.

Source file: AuthenticatorTestCase.java

  18 
vote

@Override protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  InputStream is=req.getInputStream();
  OutputStream os=resp.getOutputStream();
  int c=is.read();
  while (c > -1) {
    os.write(c);
    c=is.read();
  }
  is.close();
  os.close();
  resp.setStatus(HttpServletResponse.SC_OK);
}
 

Example 8

From project ALP, under directory /workspace/alp-reporter-fe/src/main/java/com/lohika/alp/reporter/fe/controller/.

Source file: LogController.java

  18 
vote

@RequestMapping(method=RequestMethod.GET,value="/results/test-method/{testMethodId}/log/{name}") void getLogBinary(HttpServletRequest request,HttpServletResponse response,@PathVariable("testMethodId") long id) throws IOException {
  String uri=request.getRequestURI();
  String[] parts=uri.split("/");
  String name=parts[parts.length - 1];
  ServletContext sc=request.getSession().getServletContext();
  String datalogsPath=sc.getInitParameter("datalogsPath");
  InputStream is=logStorage.getLog(id,name,datalogsPath);
  OutputStream os=response.getOutputStream();
  int c;
  while ((c=is.read()) != -1)   os.write(c);
}
 

Example 9

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

Source file: EntitySerializer.java

  18 
vote

/** 
 * Writes out the content of the given HTTP entity to the session output buffer based on properties of the given HTTP message.
 * @param outbuffer the output session buffer.
 * @param message the HTTP message.
 * @param entity the HTTP entity to be written out.
 * @throws HttpException in case of HTTP protocol violation.
 * @throws IOException in case of an I/O error.
 */
public void serialize(final SessionOutputBuffer outbuffer,final HttpMessage message,final HttpEntity entity) throws HttpException, IOException {
  if (outbuffer == null) {
    throw new IllegalArgumentException("Session output buffer may not be null");
  }
  if (message == null) {
    throw new IllegalArgumentException("HTTP message may not be null");
  }
  if (entity == null) {
    throw new IllegalArgumentException("HTTP entity may not be null");
  }
  OutputStream outstream=doSerialize(outbuffer,message);
  entity.writeTo(outstream);
  outstream.close();
}
 

Example 10

From project Android-GifStitch, under directory /src/com/phunkosis/gifstitch/settings/.

Source file: GSSettings.java

  18 
vote

public static void copyFile(File srcFile,File destFile) throws IOException {
  InputStream oInStream=new FileInputStream(srcFile);
  OutputStream oOutStream=new FileOutputStream(destFile);
  byte[] oBytes=new byte[1024];
  int nLength;
  BufferedInputStream oBuffInputStream=new BufferedInputStream(oInStream);
  while ((nLength=oBuffInputStream.read(oBytes)) > 0) {
    oOutStream.write(oBytes,0,nLength);
  }
  oInStream.close();
  oOutStream.close();
}
 

Example 11

From project android-vpn-server, under directory /src/com/android/server/vpn/.

Source file: DaemonProxy.java

  18 
vote

void sendCommand(String... args) throws IOException {
  OutputStream out=getControlSocketOutput();
  for (  String arg : args)   outputString(out,arg);
  out.write(END_OF_ARGUMENTS);
  out.flush();
  int result=getResultFromSocket(true);
  if (result != args.length) {
    throw new IOException("socket error, result from service: " + result);
  }
}
 

Example 12

From project android_external_guava, under directory /src/com/google/common/io/.

Source file: ByteStreams.java

  18 
vote

/** 
 * Writes a byte array to an output stream from the given supplier.
 * @param from the bytes to write
 * @param to the output supplier
 * @throws IOException if an I/O error occurs
 */
public static void write(byte[] from,OutputSupplier<? extends OutputStream> to) throws IOException {
  Preconditions.checkNotNull(from);
  boolean threw=true;
  OutputStream out=to.getOutput();
  try {
    out.write(from);
    threw=false;
  }
  finally {
    Closeables.close(out,threw);
  }
}
 

Example 13

From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Commands/.

Source file: cmdRebuild.java

  17 
vote

private boolean downloadSkin(String playerName){
  int len1=0;
  InputStream is=null;
  OutputStream os=null;
  try {
    URL url=new URL("http://s3.amazonaws.com/MinecraftSkins/" + playerName + ".png");
    is=url.openStream();
    os=new FileOutputStream(new File(Core.getInstance().getDataFolder(),"/skins/" + playerName + ".png"));
    byte[] buff=new byte[4096];
    while (-1 != (len1=is.read(buff))) {
      os.write(buff,0,len1);
    }
    os.flush();
  }
 catch (  Exception ex) {
    return false;
  }
 finally {
    if (os != null)     try {
      os.close();
    }
 catch (    IOException ex) {
    }
    if (is != null)     try {
      is.close();
    }
 catch (    IOException ex) {
    }
  }
  return true;
}
 

Example 14

From project activemq-apollo, under directory /apollo-openwire/src/main/scala/org/apache/activemq/apollo/openwire/command/.

Source file: ActiveMQObjectMessage.java

  17 
vote

public void storeContent(){
  Buffer bodyAsBytes=getContent();
  if (bodyAsBytes == null && object != null) {
    try {
      ByteArrayOutputStream bytesOut=new ByteArrayOutputStream();
      OutputStream os=bytesOut;
      if (Settings.enable_compression()) {
        compressed=true;
        os=new DeflaterOutputStream(os);
      }
      DataOutputStream dataOut=new DataOutputStream(os);
      ObjectOutputStream objOut=new ObjectOutputStream(dataOut);
      objOut.writeObject(object);
      objOut.flush();
      objOut.reset();
      objOut.close();
      setContent(bytesOut.toBuffer());
    }
 catch (    IOException ioe) {
      throw new RuntimeException(ioe.getMessage(),ioe);
    }
  }
}
 

Example 15

From project agile, under directory /agile-framework/src/main/java/org/headsupdev/agile/framework/.

Source file: FaviconServlet.java

  17 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException {
  InputStream in=getClass().getClassLoader().getResourceAsStream("/org/headsupdev/agile/web/favicon.ico");
  OutputStream out=res.getOutputStream();
  res.setContentType("image/ico");
  try {
    int read;
    byte[] buff=new byte[1024];
    while ((read=in.read(buff)) != -1) {
      out.write(buff,0,read);
    }
  }
  finally {
    if (in != null) {
      in.close();
    }
    if (out != null) {
      out.close();
    }
  }
}
 

Example 16

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

Source file: TutorialTests.java

  17 
vote

@Test public void example8() throws Exception {
  cat.deleteRepository("example8");
  repo=cat.createRepository("example8");
  closeLater(repo);
  repo.initialize();
  conn=getConnection(repo);
  vf=repo.getValueFactory();
  example6();
  URI context=repo.getValueFactory().createURI("http://example.org#vcards");
{
    File outputFile=AGAbstractTest.createTempFile(getClass().getSimpleName(),".nt");
    println("Writing n-triples to: " + outputFile.getCanonicalPath());
    OutputStream out=new FileOutputStream(outputFile);
    NTriplesWriter ntriplesWriter=new NTriplesWriter(out);
    conn.export(ntriplesWriter,context);
    close(out);
    assertFiles(new File("src/test/tutorial-test8-expected.nt"),outputFile);
    outputFile.delete();
  }
{
    File outputFile=AGAbstractTest.createTempFile(getClass().getSimpleName(),".rdf");
    println("Writing RDF to: " + outputFile);
    OutputStream out=new FileOutputStream(outputFile);
    RDFXMLWriter rdfxmlfWriter=new RDFXMLWriter(out);
    conn.export(rdfxmlfWriter,context);
    out.write('\n');
    close(out);
    assertFiles(new File("src/test/tutorial-test8-expected.rdf"),outputFile);
    outputFile.delete();
  }
}
 

Example 17

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

Source file: CSVHelper.java

  17 
vote

public Uri prepareCSV(Session session) throws IOException {
  OutputStream outputStream=null;
  try {
    File storage=Environment.getExternalStorageDirectory();
    File dir=new File(storage,"aircasting_sessions");
    dir.mkdirs();
    File file=new File(dir,fileName(session.getTitle()));
    outputStream=new FileOutputStream(file);
    Writer writer=new OutputStreamWriter(outputStream);
    CsvWriter csvWriter=new CsvWriter(writer,',');
    csvWriter.write("sensor:model");
    csvWriter.write("sensor:package");
    csvWriter.write("sensor:capability");
    csvWriter.write("Date");
    csvWriter.write("Time");
    csvWriter.write("Timestamp");
    csvWriter.write("geo:lat");
    csvWriter.write("geo:long");
    csvWriter.write("sensor:units");
    csvWriter.write("Value");
    csvWriter.endRecord();
    write(session).toWriter(csvWriter);
    csvWriter.flush();
    csvWriter.close();
    Uri uri=Uri.fromFile(file);
    if (Constants.isDevMode()) {
      Log.i(Constants.TAG,"File path [" + uri + "]");
    }
    return uri;
  }
  finally {
    closeQuietly(outputStream);
  }
}
 

Example 18

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

Source file: TestRackServlet.java

  17 
vote

@Test public void testSimpleRequestWithLogging() throws IOException, ServletException {
  String expectedMessage="FooBarBaz";
  OutputStream stream=new ByteArrayOutputStream();
  ch.qos.logback.classic.Logger rackLogger=(ch.qos.logback.classic.Logger)LoggerFactory.getLogger("helloworldsinatra.rb:HEAD /name-echo");
  rackLogger.setLevel(Level.ALL);
  LoggerContext context=(LoggerContext)LoggerFactory.getILoggerFactory();
  PatternLayoutEncoder encoder=new PatternLayoutEncoder();
  encoder.setPattern("%m%n");
  encoder.setContext(context);
  encoder.start();
  OutputStreamAppender<ILoggingEvent> streamAppender=new OutputStreamAppender<ILoggingEvent>();
  streamAppender.setContext(context);
  streamAppender.setEncoder(encoder);
  streamAppender.setOutputStream(stream);
  streamAppender.start();
  rackLogger.addAppender(streamAppender);
  assertEquals(performRequest("name=" + expectedMessage,"/name-echo","","GET"),expectedMessage);
  streamAppender.stop();
  Assertions.assertContains(stream.toString(),"name-echo was called with " + expectedMessage);
}
 

Example 19

From project Airports, under directory /src/com/nadmm/airports/notams/.

Source file: NotamService.java

  17 
vote

private void fetchNotams(String icaoCode,File notamFile) throws IOException {
  InputStream in=null;
  String params=String.format(NOTAM_PARAM,icaoCode);
  HttpsURLConnection conn=(HttpsURLConnection)NOTAM_URL.openConnection();
  conn.setRequestProperty("Connection","close");
  conn.setDoInput(true);
  conn.setDoOutput(true);
  conn.setUseCaches(false);
  conn.setConnectTimeout(30 * 1000);
  conn.setReadTimeout(30 * 1000);
  conn.setRequestMethod("POST");
  conn.setRequestProperty("User-Agent","Mozilla/5.0 (X11; U; Linux i686; en-US)");
  conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length",Integer.toString(params.length()));
  OutputStream faa=conn.getOutputStream();
  faa.write(params.getBytes("UTF-8"));
  faa.close();
  int response=conn.getResponseCode();
  if (response == HttpURLConnection.HTTP_OK) {
    in=conn.getInputStream();
    ArrayList<String> notams=parseNotamsFromHtml(in);
    in.close();
    BufferedOutputStream cache=new BufferedOutputStream(new FileOutputStream(notamFile));
    for (    String notam : notams) {
      cache.write(notam.getBytes());
      cache.write('\n');
    }
    cache.close();
  }
}
 

Example 20

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

Source file: JSONPFilter.java

  17 
vote

/** 
 * Wraps a JSON response with a JSONP callback, if possible and appropriate.
 * @see com.ajah.servlet.filter.BaseFilter#doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain)
 */
@Override public void doFilter(final ServletRequest request,final ServletResponse response,final FilterChain chain) throws IOException, ServletException {
  final String callback=request.getParameter("callback");
  if (StringUtils.isBlank(callback)) {
    log.finest("Not adding callback, no \"callback\" parameter specified");
    chain.doFilter(request,response);
    return;
  }
  final OutputStream out=response.getOutputStream();
  final GenericResponseWrapper wrapper=new GenericResponseWrapper((HttpServletResponse)response);
  chain.doFilter(request,wrapper);
  if ("application/json".equals(wrapper.getContentType()) || "jsonp".equals(request.getParameter("format"))) {
    if (log.isLoggable(Level.FINEST)) {
      log.finest("Adding callback \"" + callback + "\" to  "+ wrapper.getData().length+ " bytes");
    }
    out.write(callback.getBytes());
    out.write('(');
    out.write(wrapper.getData());
    out.write(");".getBytes());
  }
 else {
    if (log.isLoggable(Level.FINEST)) {
      log.finest("Not adding callback, response is not JSON (" + wrapper.getContentType() + ")");
    }
    out.write(wrapper.getData());
  }
  out.close();
}
 

Example 21

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/controller/.

Source file: FileUploadController.java

  17 
vote

/** 
 * On submit.
 * @param fileUpload the file upload
 * @param errors the errors
 * @param request the request
 * @return the string
 * @throws Exception the exception
 */
@RequestMapping(method=RequestMethod.POST) public String onSubmit(final FileUpload fileUpload,final BindingResult errors,final HttpServletRequest request) throws Exception {
  if (request.getParameter("cancel") != null)   return this.getCancelView();
  if (this.validator != null) {
    this.validator.validate(fileUpload,errors);
    if (errors.hasErrors())     return "fileupload";
  }
  if (fileUpload.getFile().length == 0) {
    final Object[] args=new Object[]{this.getText("uploadForm.file",request.getLocale())};
    errors.rejectValue("file","errors.required",args,"File");
    return "fileupload";
  }
  final MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
  final CommonsMultipartFile file=(CommonsMultipartFile)multipartRequest.getFile("file");
  final String uploadDir=this.getServletContext().getRealPath("/resources") + "/" + request.getRemoteUser()+ "/";
  final File dirPath=new File(uploadDir);
  if (!dirPath.exists()) {
    dirPath.mkdirs();
  }
  final InputStream stream=file.getInputStream();
  final OutputStream bos=new FileOutputStream(uploadDir + file.getOriginalFilename());
  int bytesRead;
  final byte[] buffer=new byte[8192];
  while ((bytesRead=stream.read(buffer,0,8192)) != -1) {
    bos.write(buffer,0,bytesRead);
  }
  bos.close();
  stream.close();
  request.setAttribute("friendlyName",fileUpload.getName());
  request.setAttribute("fileName",file.getOriginalFilename());
  request.setAttribute("contentType",file.getContentType());
  request.setAttribute("size",file.getSize() + " bytes");
  request.setAttribute("location",dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename());
  final String link=request.getContextPath() + "/resources" + "/"+ request.getRemoteUser()+ "/";
  request.setAttribute("link",link + file.getOriginalFilename());
  return this.getSuccessView();
}
 

Example 22

From project amber, under directory /oauth-2.0/integration-tests/src/test/java/org/apache/amber/oauth2/integration/.

Source file: ResourceTest.java

  17 
vote

@Test public void testResourceAccessBodyValidToken() throws Exception {
  URL url=new URL(Common.RESOURCE_SERVER + Common.PROTECTED_RESOURCE_BODY);
  URLConnection c=url.openConnection();
  if (c instanceof HttpURLConnection) {
    HttpURLConnection httpURLConnection=(HttpURLConnection)c;
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setAllowUserInteraction(false);
    httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    httpURLConnection.setRequestProperty("Content-Length",Integer.toString(Common.BODY_OAUTH2.length()));
    OutputStream ost=httpURLConnection.getOutputStream();
    PrintWriter pw=new PrintWriter(ost);
    pw.print(Common.BODY_OAUTH2);
    pw.flush();
    pw.close();
    testValidTokenResponse(httpURLConnection);
  }
}
 

Example 23

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

Source file: AbstractPacketBuffer.java

  17 
vote

public OutputStream asOutputStream(){
  return new OutputStream(){
    @Override public void write(    byte[] b,    int off,    int len){
      AbstractPacketBuffer.this.writeBytes(b,off,len);
    }
    @Override public void write(    int b){
      AbstractPacketBuffer.this.writeByte((byte)b);
    }
  }
;
}
 

Example 24

From project android-database-sqlcipher, under directory /src/net/sqlcipher/database/.

Source file: SQLiteDatabase.java

  17 
vote

private static void loadICUData(Context context,File workingDir){
  try {
    File icuDir=new File(workingDir,"icu");
    if (!icuDir.exists())     icuDir.mkdirs();
    File icuDataFile=new File(icuDir,"icudt46l.dat");
    if (!icuDataFile.exists()) {
      ZipInputStream in=new ZipInputStream(context.getAssets().open("icudt46l.zip"));
      in.getNextEntry();
      OutputStream out=new FileOutputStream(icuDataFile);
      byte[] buf=new byte[1024];
      int len;
      while ((len=in.read(buf)) > 0) {
        out.write(buf,0,len);
      }
      in.close();
      out.flush();
      out.close();
    }
  }
 catch (  Exception e) {
    Log.e(TAG,"Error copying icu data file" + e.getMessage());
  }
}
 

Example 25

From project Android-File-Manager-Tablet, under directory /src/com/nexes/manager/tablet/.

Source file: BluetoothActivity.java

  17 
vote

private void communicateData(BluetoothSocket socket){
  OutputStream writeStrm=null;
  FileInputStream readStrm=null;
  int len=mFilePaths.length;
  byte[] buffer=new byte[1024];
  Log.e("ClientSocketThread","communicateData is called");
  try {
    for (int i=0; i < len; i++) {
      File file=new File(mFilePaths[i]);
      writeStrm=socket.getOutputStream();
      readStrm=new FileInputStream(file);
      int read=0;
      Message msg=new Message();
      msg.obj=(String)file.getName();
      msg.arg2=(int)file.length();
      while ((read=readStrm.read(buffer)) != -1) {
        msg.arg1=read;
        msg.what=DIALOG_UPDATE;
        writeStrm.write(buffer);
        mHandle.sendMessage(msg);
      }
      Log.e("OPENMANAGER","file is done");
    }
    writeStrm.close();
    cancel();
  }
 catch (  IOException e) {
    Message msg=mHandle.obtainMessage();
    msg.obj=e.getMessage();
    msg.what=DIALOG_CANCEL;
    mHandle.sendMessage(msg);
  }
}
 

Example 26

From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/.

Source file: OcrInitAsyncTask.java

  17 
vote

/** 
 * Unzips the given Gzipped file to the given destination, and deletes the gzipped file.
 * @param zippedFile The gzipped file to be uncompressed
 * @param outFilePath File to unzip to, including path
 * @throws FileNotFoundException
 * @throws IOException
 */
private void gunzip(File zippedFile,File outFilePath) throws FileNotFoundException, IOException {
  int uncompressedFileSize=getGzipSizeUncompressed(zippedFile);
  Integer percentComplete;
  int percentCompleteLast=0;
  int unzippedBytes=0;
  final Integer progressMin=0;
  int progressMax=100 - progressMin;
  publishProgress("Uncompressing data for " + languageName + "...",progressMin.toString());
  String extension=zippedFile.toString().substring(zippedFile.toString().length() - 16);
  if (extension.equals(".tar.gz.download")) {
    progressMax=50;
  }
  GZIPInputStream gzipInputStream=new GZIPInputStream(new BufferedInputStream(new FileInputStream(zippedFile)));
  OutputStream outputStream=new FileOutputStream(outFilePath);
  BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream);
  final int BUFFER=8192;
  byte[] data=new byte[BUFFER];
  int len;
  while ((len=gzipInputStream.read(data,0,BUFFER)) > 0) {
    bufferedOutputStream.write(data,0,len);
    unzippedBytes+=len;
    percentComplete=(int)((unzippedBytes / (float)uncompressedFileSize) * progressMax) + progressMin;
    if (percentComplete > percentCompleteLast) {
      publishProgress("Uncompressing data for " + languageName + "...",percentComplete.toString());
      percentCompleteLast=percentComplete;
    }
  }
  gzipInputStream.close();
  bufferedOutputStream.flush();
  bufferedOutputStream.close();
  if (zippedFile.exists()) {
    zippedFile.delete();
  }
}
 

Example 27

From project Android-RTMP, under directory /android-ffmpeg-prototype/src/com/camundo/util/.

Source file: FFMPEGWrapper.java

  17 
vote

/** 
 * Write ffmpeg to data directory and make it executable write in parts because assets can not be bigger then 1MB TODO make it fetch the parts over http, this way consuming less space on the device but...
 * @param overwrite
 * @param target
 * @throws Exception
 */
private void writeFFMPEGToData(boolean overwrite,File target) throws Exception {
  if (!overwrite && target.exists()) {
    return;
  }
  OutputStream out=new FileOutputStream(target);
  byte buf[]=new byte[1024];
  for (  String p : ffmpeg_parts) {
    InputStream inputStream=Camundo.getContext().getAssets().open(p);
    int len;
    while ((len=inputStream.read(buf)) > 0) {
      out.write(buf,0,len);
    }
    inputStream.close();
  }
  out.close();
  Log.d(TAG,executeCommand("/system/bin/chmod 744 " + target.getAbsolutePath()));
  Log.d(TAG,"File [" + target.getAbsolutePath() + "] is created.");
}
 

Example 28

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.

Source file: OAuthSignpostClient.java

  17 
vote

@Override public HttpURLConnection post2_connect(String uri,Map<String,String> vars) throws IOException, OAuthException {
  HttpURLConnection connection=(HttpURLConnection)new URL(uri).openConnection();
  connection.setRequestMethod("POST");
  connection.setDoOutput(true);
  connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  connection.setReadTimeout(timeout);
  connection.setConnectTimeout(timeout);
  final String payload=post2_getPayload(vars);
  HttpURLConnectionRequestAdapter wrapped=new HttpURLConnectionRequestAdapter(connection){
    @Override public InputStream getMessagePayload() throws IOException {
      return new StringBufferInputStream(payload);
    }
  }
;
  consumer.sign(wrapped);
  OutputStream os=connection.getOutputStream();
  os.write(payload.getBytes());
  close(os);
  processError(connection);
  processHeaders(connection);
  return connection;
}
 

Example 29

From project Android-SQL-Helper, under directory /src/com/sgxmobileapps/androidsqlhelper/generator/codemodel/.

Source file: HeaderFileCodeWriter.java

  17 
vote

@Override public OutputStream openBinary(JPackage pkg,String fileName) throws IOException {
  int lastDotIndex=fileName.lastIndexOf(".");
  if (lastDotIndex == -1) {
    throw new IOException("Invalid file extension");
  }
  String noExtFileName=fileName.substring(0,lastDotIndex);
  String fqn=pkg.name().isEmpty() ? noExtFileName : (pkg.name() + "." + noExtFileName);
  JavaFileObject jfo=null;
  if (fileName.substring(lastDotIndex).equals(".java")) {
    jfo=mFiler.createSourceFile(fqn);
  }
 else   if (fileName.substring(lastDotIndex).equals(".class")) {
    jfo=mFiler.createClassFile(fqn);
  }
  if (jfo == null) {
    throw new IOException("Unable to create JavaFileObject");
  }
  OutputStream out=jfo.openOutputStream();
  if (!mSchema.getLicense().isEmpty()) {
    out.write(mSchema.getLicense().getBytes());
    out.write(System.getProperty("line.separator").getBytes());
  }
  return out;
}
 

Example 30

From project Android-Terminal-Emulator, under directory /examples/widget/src/jackpal/androidterm/sample/telnet/.

Source file: TermActivity.java

  17 
vote

private void createTelnetSession(){
  Socket socket=mSocket;
  InputStream termIn;
  OutputStream termOut;
  try {
    termIn=socket.getInputStream();
    termOut=socket.getOutputStream();
  }
 catch (  IOException e) {
    return;
  }
  TermSession session=new TelnetSession(termIn,termOut);
  mEmulatorView.attachSession(session);
  mSession=session;
}
 

Example 31

From project android-tether, under directory /src/og/android/tether/system/.

Source file: CoreTask.java

  17 
vote

public boolean writeLinesToFile(String filename,String lines){
  OutputStream out=null;
  boolean returnStatus=false;
  Log.d(MSG_TAG,"Writing " + lines.length() + " bytes to file: "+ filename);
  try {
    out=new FileOutputStream(filename);
    out.write(lines.getBytes());
    out.flush();
  }
 catch (  Exception e) {
    Log.d(MSG_TAG,"Unexpected error - Here is what I know: " + e.getMessage());
  }
 finally {
    try {
      if (out != null)       out.close();
      returnStatus=true;
    }
 catch (    IOException e) {
      returnStatus=false;
    }
  }
  return returnStatus;
}
 

Example 32

From project android-vpn-settings, under directory /src/com/android/settings/vpn/.

Source file: Util.java

  17 
vote

static boolean copyFiles(File sourceLocation,File targetLocation) throws IOException {
  if (sourceLocation.equals(targetLocation))   return false;
  if (sourceLocation.isDirectory()) {
    if (!targetLocation.exists()) {
      targetLocation.mkdir();
    }
    String[] children=sourceLocation.list();
    for (int i=0; i < children.length; i++) {
      copyFiles(new File(sourceLocation,children[i]),new File(targetLocation,children[i]));
    }
  }
 else   if (sourceLocation.exists()) {
    InputStream in=new FileInputStream(sourceLocation);
    OutputStream out=new FileOutputStream(targetLocation);
    byte[] buf=new byte[1024];
    int len;
    while ((len=in.read(buf)) > 0) {
      out.write(buf,0,len);
    }
    in.close();
    out.close();
  }
  return true;
}
 

Example 33

From project AndroidSensorLogger, under directory /src/com/sstp/androidsensorlogger/.

Source file: CameraActivity.java

  17 
vote

public void onPictureTaken(byte[] data,Camera camera){
  Log.d(TAG,"onPictureTaken()");
  int counter=1;
  try {
    Log.d(TAG,"prepare to open fileOutputStream");
    OutputStream fileOutputStream=getContentResolver().openOutputStream(pictureUri);
    Log.d(TAG,"prepare to write data");
    fileOutputStream.write(data);
    Log.d(TAG,"prepare to flush stream");
    fileOutputStream.flush();
    Log.d(TAG,"prepare to close stream");
    fileOutputStream.close();
    saveResult(RESULT_OK);
    Bitmap bm=null;
    ByteArrayInputStream bytes=new ByteArrayInputStream(data);
    BitmapDrawable bmd=new BitmapDrawable(bytes);
    bm=bmd.getBitmap();
    Save_to_SD(bm,"ImageFile" + counter);
  }
 catch (  Exception e) {
    Log.e(TAG,"mPictureCallbackJpeg exception caught: " + e);
  }
  counter++;
}
 

Example 34

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/vpn/.

Source file: Util.java

  17 
vote

static boolean copyFiles(File sourceLocation,File targetLocation) throws IOException {
  if (sourceLocation.equals(targetLocation))   return false;
  if (sourceLocation.isDirectory()) {
    if (!targetLocation.exists()) {
      targetLocation.mkdir();
    }
    String[] children=sourceLocation.list();
    for (int i=0; i < children.length; i++) {
      copyFiles(new File(sourceLocation,children[i]),new File(targetLocation,children[i]));
    }
  }
 else   if (sourceLocation.exists()) {
    InputStream in=new FileInputStream(sourceLocation);
    OutputStream out=new FileOutputStream(targetLocation);
    byte[] buf=new byte[1024];
    int len;
    while ((len=in.read(buf)) > 0) {
      out.write(buf,0,len);
    }
    in.close();
    out.close();
  }
  return true;
}
 

Example 35

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/aceeditor/.

Source file: ACEEditor.java

  15 
vote

private void saveFile(){
  final String f=getFullText();
  AbstractDownloadProvider provider=new AbstractDownloadProvider(){
    private static final long serialVersionUID=898782345234987345L;
    public String getContentType(){
      return "text/plain";
    }
    public String getFileName(){
      return "text.ace.txt";
    }
    public long getSize(){
      return f.length();
    }
    public void writeFile(    OutputStream out) throws IOException {
      out.write(f.getBytes());
      out.close();
    }
  }
;
  getApplicationInstance().enqueueCommand(new DownloadCommand(provider));
}
 

Example 36

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

Source file: HdfsBrowser.java

  15 
vote

@GET @Produces(MediaType.APPLICATION_JSON) @Path("/json") @Timed public StreamingOutput listingToJson(@QueryParam("path") final String path,@QueryParam("recursive") final boolean recursive,@QueryParam("pretty") final boolean pretty,@QueryParam("raw") final boolean raw) throws IOException {
  final HdfsListing hdfsListing=hdfsReader.getListing(path,raw,recursive);
  return new StreamingOutput(){
    @Override public void write(    OutputStream output) throws IOException, WebApplicationException {
      hdfsListing.toJson(output,pretty);
    }
  }
;
}
 

Example 37

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

Source file: FileAttachmentEditorComponent.java

  15 
vote

protected void initFileUpload(){
  uploadComponent=new UploadComponent(null,new Receiver(){
    private static final long serialVersionUID=1L;
    public OutputStream receiveUpload(    String filename,    String mType){
      fileName=filename;
      String extention=extractExtention(filename);
      if (extention != null) {
        mimeType=mType + MIME_TYPE_EXTENTION_SPLIT_CHAR + extention;
      }
 else {
        mimeType=mType;
      }
      byteArrayOutputStream=new ByteArrayOutputStream();
      return byteArrayOutputStream;
    }
  }
);
  uploadComponent.addFinishedListener(new FinishedListener(){
    private static final long serialVersionUID=1L;
    public void uploadFinished(    FinishedEvent event){
      if (getAttachmentName() == null || "".equals(getAttachmentName())) {
        setAttachmentName(getFriendlyName(fileName));
      }
      fileUploaded=true;
      successIndicator.setVisible(true);
      successIndicator.setCaption(i18nManager.getMessage(Messages.RELATED_CONTENT_TYPE_FILE_UPLOADED,fileName));
      form.setComponentError(null);
    }
  }
);
  addComponent(uploadComponent);
  setExpandRatio(uploadComponent,1.0f);
}
 

Example 38

From project AeminiumRuntime, under directory /src/aeminium/runtime/utils/graphviz/.

Source file: DiGraphViz.java

  15 
vote

public boolean dump(OutputStream os){
  try {
    dumpOutputStream(os);
    return true;
  }
 catch (  IOException e) {
  }
  return false;
}
 

Example 39

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

Source file: LineContextDiffer.java

  15 
vote

private void writeGitLinkDiffText(OutputStream o,DiffEntry ent) throws IOException {
  if (ent.getOldMode() == GITLINK) {
    o.write(encodeASCII("-Subproject commit " + ent.getOldId().name() + "\n"));
  }
  if (ent.getNewMode() == GITLINK) {
    o.write(encodeASCII("+Subproject commit " + ent.getNewId().name() + "\n"));
  }
}
 

Example 40

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

Source file: PointFileReaderWriter.java

  15 
vote

public static void writeOneToOne(final OutputStream sink,final Map<String,Point> mapping) throws Exception {
  final StringBuilder out=new StringBuilder();
  final Iterator<String> keyIter=mapping.keySet().iterator();
  while (keyIter.hasNext()) {
    final String name=keyIter.next();
    out.append(name).append(" ");
    final Point point=mapping.get(name);
    out.append(" (").append(point.x).append(",").append(point.y).append(")");
    if (keyIter.hasNext()) {
      out.append("\n");
    }
  }
  write(out,sink);
}
 

Example 41

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/utils/.

Source file: Utils.java

  15 
vote

public static void fromInputToOutput(InputStream in,OutputStream out) throws IOException {
  byte[] buffer=new byte[1024];
  int length;
  while ((length=in.read(buffer)) > 0) {
    out.write(buffer,0,length);
  }
}
 

Example 42

From project anadix, under directory /anadix-core/src/main/java/org/anadix/impl/.

Source file: DefaultReportFormatter.java

  15 
vote

/** 
 * {@inheritDoc} 
 */
public void formatAndStore(Report report,OutputStream os){
  if (os == null) {
    throw new NullPointerException("os cannot be null");
  }
  formatAndStore(report,new OutputStreamWriter(os));
}
 

Example 43

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

Source file: FilePart.java

  15 
vote

/** 
 * Write the disposition header to the output stream
 * @param out The output stream
 * @throws IOException If an IO problem occurs
 * @see Part#sendDispositionHeader(OutputStream)
 */
@Override protected void sendDispositionHeader(OutputStream out) throws IOException {
  super.sendDispositionHeader(out);
  String filename=this.source.getFileName();
  if (filename != null) {
    out.write(FILE_NAME_BYTES);
    out.write(QUOTE_BYTES);
    out.write(EncodingUtils.getAsciiBytes(filename));
    out.write(QUOTE_BYTES);
  }
}
 

Example 44

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

Source file: XmppOutputStream.java

  15 
vote

/** 
 * Attach this stream to a new OutputStream. This method is usually needed during feature negotiation, as some features like compression or tls require a stream reset.
 * @param out OutputStream The new underlying output stream.
 * @param sendDeclaration boolean True if a <code><?xml></code> headershould be send.
 * @param sendBOM boolean False to suppress the utf-8 byte order marker.This is usually what you want as BOM is poorly tested in the xmpp world and discourged by the unicode spec (at least for utf-8).
 * @throws IOException In case of a transport error.
 * @throws XmlPullParserException In case of a xml error.
 */
public void attach(OutputStream out,boolean sendDeclaration,boolean sendBOM) throws IOException, XmppTransportException {
  if (sendBOM) {
    Log.d(TAG,"BOM");
    out.write(0xEF);
    out.write(0xBB);
    out.write(0xBF);
  }
  if (sendDeclaration) {
    Log.d(TAG,"open stream");
    out.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>".getBytes());
  }
  if (sendBOM || sendDeclaration) {
    Log.d(TAG,"flush()");
    out.flush();
  }
  outputStream=out;
  try {
    xmlSerializer=XMLUtils.getXMLSerializer();
  }
 catch (  XmlPullParserException e) {
    throw new XmppTransportException("Can't initialize the pull parser",e);
  }
  Log.d(TAG,"set output");
  xmlSerializer.setOutput(outputStream,"UTF-8");
  Log.d(TAG,"attached");
}
 

Example 45

From project android-rackspacecloud, under directory /main/java/net/elasticgrid/rackspace/cloudservers/.

Source file: XMLCloudServers.java

  15 
vote

protected <T>T makeEntityRequestInt(HttpEntityEnclosingRequestBase request,final Object entity,Class<T> respType) throws CloudServersException {
  request.setEntity(new EntityTemplate(new ContentProducer(){
    public void writeTo(    OutputStream output) throws IOException {
      try {
        IBindingFactory bindingFactory=BindingDirectory.getFactory(entity.getClass());
        final IMarshallingContext marshallingCxt=bindingFactory.createMarshallingContext();
        marshallingCxt.marshalDocument(entity,"UTF-8",true,output);
      }
 catch (      JiBXException e) {
        IOException ioe=new IOException("Can't marshal server details");
        ioe.initCause(e);
        e.printStackTrace();
        throw ioe;
      }
    }
  }
));
  return makeRequestInt(request,respType);
}
 

Example 46

From project android-rindirect, under directory /maven-rindirect-plugin-it/src/test/java/de/akquinet/android/rindirect/.

Source file: Helper.java

  15 
vote

public static final void copyInputStream(InputStream in,OutputStream out) throws IOException {
  byte[] buffer=new byte[1024];
  int len;
  while ((len=in.read(buffer)) >= 0)   out.write(buffer,0,len);
  in.close();
  out.close();
}
 

Example 47

From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/preference/activity/.

Source file: PreferencesCreateBackupActivity.java

  15 
vote

private void writeBackup(OutputStream out) throws IOException {
  Builder builder=Catalogue.newBuilder();
  writeContexts(builder,10,20);
  writeProjects(builder,20,30);
  writeTasks(builder,30,100);
  builder.build().writeTo(out);
  out.close();
  String message=getString(R.string.status_backup_complete);
  Progress progress=Progress.createProgress(100,message);
  publishProgress(progress);
}
 

Example 48

From project android-thaiime, under directory /makedict/src/com/android/inputmethod/latin/.

Source file: BinaryDictInputOutput.java

  15 
vote

/** 
 * Dumps a FusionDictionary to a file. This is the public entry point to write a dictionary to a file.
 * @param destination the stream to write the binary data to.
 * @param dict the dictionary to write.
 */
public static void writeDictionaryBinary(OutputStream destination,FusionDictionary dict) throws IOException {
  final byte[] buffer=new byte[1 << 24];
  int index=0;
  buffer[index++]=(byte)(0xFF & (MAGIC_NUMBER >> 8));
  buffer[index++]=(byte)(0xFF & MAGIC_NUMBER);
  buffer[index++]=(byte)(0xFF & VERSION);
  buffer[index++]=(byte)(0xFF & (OPTIONS >> 8));
  buffer[index++]=(byte)(0xFF & OPTIONS);
  destination.write(buffer,0,index);
  index=0;
  MakedictLog.i("Flattening the tree...");
  ArrayList<Node> flatNodes=flattenTree(dict.mRoot);
  MakedictLog.i("Computing addresses...");
  computeAddresses(dict,flatNodes);
  MakedictLog.i("Checking array...");
  checkFlatNodeArray(flatNodes);
  MakedictLog.i("Writing file...");
  int dataEndOffset=0;
  for (  Node n : flatNodes) {
    dataEndOffset=writePlacedNode(dict,buffer,n);
  }
  showStatistics(flatNodes);
  destination.write(buffer,0,dataEndOffset);
  destination.close();
  MakedictLog.i("Done");
}
 

Example 49

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

Source file: IOUtilities.java

  15 
vote

/** 
 * Copy the content of the input stream into the output stream, using a temporary byte array buffer whose size is defined by  {@link #IO_BUFFER_SIZE}.
 * @param in The input stream to copy from.
 * @param out The output stream to copy to.
 * @throws java.io.IOException If any error occurs during the copy.
 */
public static void copy(InputStream in,OutputStream out) throws IOException {
  byte[] b=new byte[IO_BUFFER_SIZE];
  int read;
  while ((read=in.read(b)) != -1) {
    out.write(b,0,read);
  }
}
 

Example 50

From project androidannotations, under directory /AndroidAnnotations/androidannotations/src/main/java/com/googlecode/androidannotations/generation/.

Source file: SourceCodewriter.java

  15 
vote

@Override public OutputStream openBinary(JPackage pkg,String fileName) throws IOException {
  String qualifiedClassName=toQualifiedClassName(pkg,fileName);
  message.printMessage(Kind.NOTE,"Generating source file: " + qualifiedClassName);
  try {
    JavaFileObject sourceFile=filer.createSourceFile(qualifiedClassName);
    return sourceFile.openOutputStream();
  }
 catch (  FilerException e) {
    message.printMessage(Kind.NOTE,"Could not generate source file for " + qualifiedClassName + ", message: "+ e.getMessage());
    return VOID_OUTPUT_STREAM;
  }
}
 

Example 51

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/util/.

Source file: IOUtilities.java

  15 
vote

/** 
 * Copy the content of the input stream into the output stream, using a temporary byte array buffer whose size is defined by  {@link #IO_BUFFER_SIZE}.
 * @param in The input stream to copy from.
 * @param out The output stream to copy to.
 * @throws java.io.IOException If any error occurs during the copy.
 */
public static void copy(InputStream in,OutputStream out) throws IOException {
  byte[] b=new byte[IO_BUFFER_SIZE];
  int read;
  while ((read=in.read(b)) != -1) {
    out.write(b,0,read);
  }
}
 

Example 52

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

Source file: AbstractAjaxCallback.java

  15 
vote

private void copy(InputStream is,OutputStream os,String encoding,int max) throws IOException {
  if ("gzip".equalsIgnoreCase(encoding)) {
    is=new GZIPInputStream(is);
  }
  Object o=null;
  if (progress != null) {
    o=progress.get();
  }
  Progress p=null;
  if (o != null) {
    p=new Progress(o);
  }
  AQUtility.copy(is,os,max,p);
}
 

Example 53

From project android_7, under directory /src/org/immopoly/android/helper/.

Source file: ImageListDownloader.java

  15 
vote

public void copy(InputStream in,OutputStream out) throws IOException {
  byte[] b=new byte[IO_BUFFER_SIZE];
  int read;
  while ((read=in.read(b)) != -1) {
    out.write(b,0,read);
  }
}
 

Example 54

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

Source file: SignApk.java

  15 
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 55

From project android_external_oauth, under directory /core/src/main/java/net/oauth/.

Source file: OAuth.java

  15 
vote

/** 
 * Write a form-urlencoded document into the given stream, containing the given sequence of name/value pairs.
 */
public static void formEncode(Iterable<? extends Map.Entry> parameters,OutputStream into) throws IOException {
  if (parameters != null) {
    boolean first=true;
    for (    Map.Entry parameter : parameters) {
      if (first) {
        first=false;
      }
 else {
        into.write('&');
      }
      into.write(percentEncode(toString(parameter.getKey())).getBytes());
      into.write('=');
      into.write(percentEncode(toString(parameter.getValue())).getBytes());
    }
  }
}
 

Example 56

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

Source file: AttachmentLoader.java

  15 
vote

/** 
 * Read the attachment data in chunks and write the data back out to our attachment file
 * @param inputStream the InputStream we're reading the attachment from
 * @param outputStream the OutputStream the attachment will be written to
 * @param len the number of expected bytes we're going to read
 * @throws IOException
 */
public void readChunked(InputStream inputStream,OutputStream outputStream,int len) throws IOException {
  byte[] bytes=new byte[CHUNK_SIZE];
  int length=len;
  int totalRead=0;
  int lastCallbackPct=-1;
  int lastCallbackTotalRead=0;
  mService.userLog("Expected attachment length: ",len);
  while (true) {
    int read=inputStream.read(bytes,0,CHUNK_SIZE);
    if (read < 0) {
      mService.userLog("Attachment load reached EOF, totalRead: ",totalRead);
      break;
    }
    totalRead+=read;
    outputStream.write(bytes,0,read);
    if (length > 0) {
      int pct=(totalRead * 100) / length;
      if ((pct > lastCallbackPct) && (totalRead > (lastCallbackTotalRead + CHUNK_SIZE))) {
        doProgressCallback(pct);
        lastCallbackTotalRead=totalRead;
        lastCallbackPct=pct;
      }
    }
  }
  if (totalRead > length) {
    mService.userLog("Read more than expected: ",totalRead);
  }
}