Java Code Examples for java.io.FilterOutputStream

The following examples show how to use java.io.FilterOutputStream. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jkube   Source File: UnixSocket.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public OutputStream getOutputStream() throws IOException {
    if (!channel.isOpen()) {
        throw new SocketException("Socket is closed");
    }

    if (!channel.isConnected()) {
        throw new SocketException("Socket is not connected");
    }

    if (outputShutdown) {
        throw new SocketException("Socket output is shutdown");
    }

    return new FilterOutputStream(Channels.newOutputStream(channel)) {
        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            out.write(b, off, len);
        }

        @Override
        public void close() throws IOException {
            shutdownOutput();
        }
    };
}
 
Example 2
Source Project: FHIR   Source File: FHIRJsonGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Temporary workaround for: https://github.com/eclipse-ee4j/jsonp/issues/190
 */
private OutputStream wrap(OutputStream out) {
    return new FilterOutputStream(out) {
        private boolean first = true;
        
        @Override
        public void write(int b) throws IOException {
            if (first && b == '\n') {
                first = false;
                return;
            }
            out.write(b);
        }
        
        @Override
        public void close() {
            // do nothing
        }
    };
}
 
Example 3
Source Project: phonegapbootcampsite   Source File: HttpResponseCache.java    License: MIT License 6 votes vote down vote up
public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
  this.editor = editor;
  this.cacheOut = editor.newOutputStream(ENTRY_BODY);
  this.body = new FilterOutputStream(cacheOut) {
    @Override public void close() throws IOException {
      synchronized (HttpResponseCache.this) {
        if (done) {
          return;
        }
        done = true;
        writeSuccessCount++;
      }
      super.close();
      editor.commit();
    }

    @Override public void write(byte[] buffer, int offset, int length) throws IOException {
      // Since we don't override "write(int oneByte)", we can write directly to "out"
      // and avoid the inefficient implementation from the FilterOutputStream.
      out.write(buffer, offset, length);
    }
  };
}
 
Example 4
Source Project: iaf   Source File: Samba2FileSystem.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OutputStream appendFile(String f) throws FileSystemException, IOException {
	final File file = getFile(f, AccessMask.FILE_APPEND_DATA, SMB2CreateDisposition.FILE_OPEN_IF);
	OutputStream out = file.getOutputStream();
	FilterOutputStream fos = new FilterOutputStream(out) {

		boolean isOpen = true;
		@Override
		public void close() throws IOException {
			if(isOpen) {
				super.close();
				isOpen=false;
			}
			file.close();
		}
	};
	return fos;
}
 
Example 5
Source Project: netbeans   Source File: PropertiesStorage.java    License: Apache License 2.0 6 votes vote down vote up
private OutputStream outputStream() throws IOException {
    FileObject fo = toPropertiesFile(true);
    final FileLock lock = fo.lock();
    OutputStream os = null;
    try {
        os = fo.getOutputStream(lock);
    } finally {
        if(os == null && lock != null) {
            // release lock if getOutputStream failed
            lock.releaseLock();
        }
    }
    return new FilterOutputStream(os) {
        public @Override void close() throws IOException {
            super.close();
            lock.releaseLock();
        }
    };
}
 
Example 6
Source Project: netbeans   Source File: LocalFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
private OutputStream getOutputStreamForMac42624(final OutputStream originalStream, final String name) {
    final File f = getFile(name);
    final long lModified = f.lastModified();
    OutputStream retVal = new FilterOutputStream(originalStream) {

        @Override
        public void close() throws IOException {
            super.close();

            if ((f.length() == 0) && (f.lastModified() == lModified)) {
                f.setLastModified(System.currentTimeMillis());
            }
        }
    };

    return retVal;
}
 
Example 7
Source Project: netbeans   Source File: FileObject75826Test.java    License: Apache License 2.0 6 votes vote down vote up
TestFileSystem(LocalFileSystem lfs, String testName) throws Exception {
    super();
    if ("testOutputStreamFiresIOException".equals(testName)) {
        this.info = new LocalFileSystem.Impl(this) {
            public OutputStream outputStream(String name) throws java.io.IOException {
                throw new IOException();
            }
        };
    } else if ("testCloseStreamFiresIOException".equals(testName)) {
        this.info = new LocalFileSystem.Impl(this) {
            public OutputStream outputStream(String name) throws java.io.IOException {
                return new FilterOutputStream(super.outputStream(name)) {
                    public void close() throws IOException {
                        throw new IOException();
                    }
                };
            }
        };
    }
    setRootDirectory(lfs.getRootDirectory());
}
 
Example 8
public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
  this.editor = editor;
  this.cacheOut = editor.newOutputStream(ENTRY_BODY);
  this.body = new FilterOutputStream(cacheOut) {
    @Override public void close() throws IOException {
      synchronized (HttpResponseCache.this) {
        if (done) {
          return;
        }
        done = true;
        writeSuccessCount++;
      }
      super.close();
      editor.commit();
    }

    @Override
    public void write(byte[] buffer, int offset, int length) throws IOException {
      // Since we don't override "write(int oneByte)", we can write directly to "out"
      // and avoid the inefficient implementation from the FilterOutputStream.
      out.write(buffer, offset, length);
    }
  };
}
 
Example 9
Source Project: openjdk-jdk9   Source File: ToolBox.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public OutputStream openOutputStream() {
    return new FilterOutputStream(new ByteArrayOutputStream()) {
        @Override
        public void close() throws IOException {
            out.close();
            byte[] bytes = ((ByteArrayOutputStream) out).toByteArray();
            save(location, name, new Content() {
                @Override
                public byte[] getBytes() {
                    return bytes;
                }
                @Override
                public String getString() {
                    return new String(bytes);
                }

            });
        }
    };
}
 
Example 10
@Override
public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
    final String name = pkg != null && pkg.name().length() > 0
            ? pkg.name() + '.' + fileName : fileName;

    out.println(
        "-----------------------------------" + name +
        "-----------------------------------");

    return new FilterOutputStream(out) {
        @Override
        public void close() {
            // don't let this stream close
        }
    };
}
 
Example 11
Source Project: iaf   Source File: Samba2FileSystem.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OutputStream createFile(String f) throws FileSystemException, IOException {
	Set<AccessMask> accessMask = new HashSet<AccessMask>(EnumSet.of(AccessMask.FILE_ADD_FILE));
	Set<SMB2CreateOptions> createOptions = new HashSet<SMB2CreateOptions>(
			EnumSet.of(SMB2CreateOptions.FILE_NON_DIRECTORY_FILE, SMB2CreateOptions.FILE_WRITE_THROUGH));
	
	final File file = diskShare.openFile(f, accessMask, null, SMB2ShareAccess.ALL,
			SMB2CreateDisposition.FILE_OVERWRITE_IF, createOptions);
	OutputStream out = file.getOutputStream();
	FilterOutputStream fos = new FilterOutputStream(out) {

		boolean isOpen = true;
		@Override
		public void close() throws IOException {
			if(isOpen) {
				super.close();
				isOpen=false;
			}
			file.close();
		}
	};
	return fos;
}
 
Example 12
Source Project: commons-rng   Source File: OutputCommand.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates the output stream. This will not be buffered.
 *
 * @return the output stream
 */
private OutputStream createOutputStream() {
    if (fileOutput != null) {
        try {
            Files.newOutputStream(fileOutput.toPath());
        } catch (IOException ex) {
            throw new ApplicationException("Failed to create output: " + fileOutput, ex);
        }
    }
    return new FilterOutputStream(System.out) {
        @Override
        public void close() {
            // Do not close stdout
        }
    };
}
 
Example 13
Source Project: commons-rng   Source File: ResultsCommand.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates the output stream. This will not be buffered.
 *
 * @return the output stream
 */
private OutputStream createOutputStream() {
    if (fileOutput != null) {
        try {
            Files.newOutputStream(fileOutput.toPath());
        } catch (final IOException ex) {
            throw new ApplicationException("Failed to create output: " + fileOutput, ex);
        }
    }
    return new FilterOutputStream(System.out) {
        @Override
        public void close() {
            // Do not close stdout
        }
    };
}
 
Example 14
Source Project: lucene-solr   Source File: SerializedDVStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Field[] createIndexableFields(Shape shape) {
  int bufSize = Math.max(128, (int) (this.indexLastBufSize * 1.5));//50% headroom over last
  ByteArrayOutputStream byteStream = new ByteArrayOutputStream(bufSize);
  final BytesRef bytesRef = new BytesRef();//receiver of byteStream's bytes
  try {
    ctx.getBinaryCodec().writeShape(new DataOutputStream(byteStream), shape);
    //this is a hack to avoid redundant byte array copying by byteStream.toByteArray()
    byteStream.writeTo(new FilterOutputStream(null/*not used*/) {
      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        bytesRef.bytes = b;
        bytesRef.offset = off;
        bytesRef.length = len;
      }
    });
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  this.indexLastBufSize = bytesRef.length;//cache heuristic
  return new Field[]{new BinaryDocValuesField(getFieldName(), bytesRef)};
}
 
Example 15
Source Project: beam   Source File: UnownedOutputStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWrite() throws IOException {
  CallCountOutputStream fsCount = new CallCountOutputStream();
  FilterOutputStream fs = new FilterOutputStream(fsCount);
  CallCountOutputStream osCount = new CallCountOutputStream();
  UnownedOutputStream os = new UnownedOutputStream(osCount);

  byte[] data = "Hello World!".getBytes(StandardCharsets.UTF_8);
  fs.write(data, 0, data.length);
  os.write(data, 0, data.length);
  fs.write('\n');
  os.write('\n');

  assertEquals(13, fsCount.callCnt);
  assertEquals(2, osCount.callCnt);
  assertArrayEquals(fsCount.toByteArray(), osCount.toByteArray());
}
 
Example 16
Source Project: docker-maven-plugin   Source File: UnixSocket.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OutputStream getOutputStream() throws IOException {
    if (!channel.isOpen()) {
        throw new SocketException("Socket is closed");
    }

    if (!channel.isConnected()) {
        throw new SocketException("Socket is not connected");
    }

    if (outputShutdown) {
        throw new SocketException("Socket output is shutdown");
    }

    return new FilterOutputStream(Channels.newOutputStream(channel)) {
        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            out.write(b, off, len);
        }

        @Override
        public void close() throws IOException {
            shutdownOutput();
        }
    };
}
 
Example 17
Source Project: IoTgo_Android_App   Source File: HttpResponseCache.java    License: MIT License 6 votes vote down vote up
public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
  this.editor = editor;
  this.cacheOut = editor.newOutputStream(ENTRY_BODY);
  this.body = new FilterOutputStream(cacheOut) {
    @Override public void close() throws IOException {
      synchronized (HttpResponseCache.this) {
        if (done) {
          return;
        }
        done = true;
        writeSuccessCount++;
      }
      super.close();
      editor.commit();
    }

    @Override public void write(byte[] buffer, int offset, int length) throws IOException {
      // Since we don't override "write(int oneByte)", we can write directly to "out"
      // and avoid the inefficient implementation from the FilterOutputStream.
      out.write(buffer, offset, length);
    }
  };
}
 
Example 18
Source Project: database   Source File: AbstractRestApiTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
* Return the {@link ServletOutputStream} associated with the request (and
* stash a copy).
* 
* @throws IOException
* @throws IllegalStateException
*             per the servlet API if the writer has been requested already.
*/
  public OutputStream getOutputStream() throws IOException {

    lock.lock();
    try {

       return new FilterOutputStream(this.os = resp.getOutputStream()) {
          @Override
          public void flush() {
             throw new UnsupportedOperationException();
          }
          @Override
          public void close() {
             throw new UnsupportedOperationException();
          }
       };

    } finally {
       lock.unlock();
}
  	
  }
 
Example 19
Source Project: android-discourse   Source File: HttpResponseCache.java    License: Apache License 2.0 6 votes vote down vote up
public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
    this.editor = editor;
    this.cacheOut = editor.newOutputStream(ENTRY_BODY);
    this.body = new FilterOutputStream(cacheOut) {
        @Override
        public void close() throws IOException {
            synchronized (HttpResponseCache.this) {
                if (done) {
                    return;
                }
                done = true;
                writeSuccessCount++;
            }
            super.close();
            editor.commit();
        }

        @Override
        public void write(byte[] buffer, int offset, int length) throws IOException {
            // Since we don't override "write(int oneByte)", we can write directly to "out"
            // and avoid the inefficient implementation from the FilterOutputStream.
            out.write(buffer, offset, length);
        }
    };
}
 
Example 20
Source Project: bluemix-parking-meter   Source File: HttpResponseCache.java    License: MIT License 6 votes vote down vote up
public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
  this.editor = editor;
  this.cacheOut = editor.newOutputStream(ENTRY_BODY);
  this.body = new FilterOutputStream(cacheOut) {
    @Override public void close() throws IOException {
      synchronized (HttpResponseCache.this) {
        if (done) {
          return;
        }
        done = true;
        writeSuccessCount++;
      }
      super.close();
      editor.commit();
    }

    @Override public void write(byte[] buffer, int offset, int length) throws IOException {
      // Since we don't override "write(int oneByte)", we can write directly to "out"
      // and avoid the inefficient implementation from the FilterOutputStream.
      out.write(buffer, offset, length);
    }
  };
}
 
Example 21
static
public <S extends Serializable> void serialize(S object, OutputStream os) throws IOException {
	FilterOutputStream safeOs = new FilterOutputStream(os){

		@Override
		public void close() throws IOException {
			super.flush();
		}
	};

	try(ObjectOutputStream oos = new ObjectOutputStream(safeOs)){
		oos.writeObject(object);

		oos.flush();
	}
}
 
Example 22
Source Project: CordovaYoutubeVideoPlayer   Source File: HttpResponseCache.java    License: MIT License 6 votes vote down vote up
public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
  this.editor = editor;
  this.cacheOut = editor.newOutputStream(ENTRY_BODY);
  this.body = new FilterOutputStream(cacheOut) {
    @Override public void close() throws IOException {
      synchronized (HttpResponseCache.this) {
        if (done) {
          return;
        }
        done = true;
        writeSuccessCount++;
      }
      super.close();
      editor.commit();
    }

    @Override public void write(byte[] buffer, int offset, int length) throws IOException {
      // Since we don't override "write(int oneByte)", we can write directly to "out"
      // and avoid the inefficient implementation from the FilterOutputStream.
      out.write(buffer, offset, length);
    }
  };
}
 
Example 23
Source Project: cordova-amazon-fireos   Source File: HttpResponseCache.java    License: Apache License 2.0 6 votes vote down vote up
public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
  this.editor = editor;
  this.cacheOut = editor.newOutputStream(ENTRY_BODY);
  this.body = new FilterOutputStream(cacheOut) {
    @Override public void close() throws IOException {
      synchronized (HttpResponseCache.this) {
        if (done) {
          return;
        }
        done = true;
        writeSuccessCount++;
      }
      super.close();
      editor.commit();
    }

    @Override public void write(byte[] buffer, int offset, int length) throws IOException {
      // Since we don't override "write(int oneByte)", we can write directly to "out"
      // and avoid the inefficient implementation from the FilterOutputStream.
      out.write(buffer, offset, length);
    }
  };
}
 
Example 24
Source Project: docker-client   Source File: NamedPipeSocket.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OutputStream getOutputStream() throws IOException {
  if (!channel.isOpen()) {
    throw new SocketException("Socket is closed");
  }

  if (outputShutdown) {
    throw new SocketException("Socket output is shutdown");
  }

  return new FilterOutputStream(Channels.newOutputStream(channel)) {   
    @Override
    public void close() throws IOException {
      shutdownOutput();
    }
  };
}
 
Example 25
Source Project: j2objc   Source File: OldFilterOutputStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test_flush() throws IOException {
    Support_OutputStream sos = new Support_OutputStream(550);
    os = new FilterOutputStream(sos);
    os.write(fileString.getBytes(), 0, 500);
    os.flush();
    assertEquals("Test 1: Bytes not written after flush;",
            500, sos.size());

    sos.setThrowsException(true);
    try {
        os.flush();
        fail("Test 2: IOException expected.");
    } catch (IOException e) {
        // Expected.
    }
    sos.setThrowsException(false);
}
 
Example 26
Source Project: wildfly-samples   Source File: HttpResponseCache.java    License: MIT License 6 votes vote down vote up
public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
  this.editor = editor;
  this.cacheOut = editor.newOutputStream(ENTRY_BODY);
  this.body = new FilterOutputStream(cacheOut) {
    @Override public void close() throws IOException {
      synchronized (HttpResponseCache.this) {
        if (done) {
          return;
        }
        done = true;
        writeSuccessCount++;
      }
      super.close();
      editor.commit();
    }

    @Override public void write(byte[] buffer, int offset, int length) throws IOException {
      // Since we don't override "write(int oneByte)", we can write directly to "out"
      // and avoid the inefficient implementation from the FilterOutputStream.
      out.write(buffer, offset, length);
    }
  };
}
 
Example 27
Source Project: j2objc   Source File: OldFilterOutputStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test_write$BII() throws IOException {
    Support_OutputStream sos = new Support_OutputStream(testLength);
    os = new FilterOutputStream(sos);
    os.write(fileString.getBytes(), 10, testLength - 10);

    bis = new ByteArrayInputStream(sos.toByteArray());
    assertTrue("Test 1: Bytes have not been written.",
            bis.available() == testLength - 10);
    byte[] wbytes = new byte[testLength - 10];
    bis.read(wbytes);
    assertTrue("Test 2: Incorrect bytes written or read.",
            fileString.substring(10).equals(new String(wbytes)));

    try {
        // Support_OutputStream throws an IOException if the internal
        // buffer is full, which it should be eventually.
        os.write(fileString.getBytes());
        fail("Test 2: IOException expected.");
    } catch (IOException e) {
        // Expected.
    }
}
 
Example 28
Source Project: j2objc   Source File: OldFilterOutputStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test_writeI() throws IOException {
    Support_OutputStream sos = new Support_OutputStream(1);
    os = new FilterOutputStream(sos);
    os.write(42);

    bis = new ByteArrayInputStream(sos.toByteArray());
    assertTrue("Test 1: Byte has not been written.",
            bis.available() == 1);
    assertEquals("Test 2: Incorrect byte written or read;",
            42, bis.read());

    try {
        // Support_OutputStream throws an IOException if the internal
        // buffer is full, which it should be now.
        os.write(42);
        fail("Test 2: IOException expected.");
    } catch (IOException e) {
        // Expected.
    }
}
 
Example 29
Source Project: ph-commons   Source File: StreamHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test method flush
 */
@Test
public void testFlush ()
{
  // flush null stream
  assertFalse (StreamHelper.flush ((Flushable) null).isSuccess ());

  // flush stream with exception
  assertFalse (StreamHelper.flush (new MockThrowingFlushable ()).isSuccess ());

  // flush without exception
  assertTrue (StreamHelper.flush (new MockFlushable ()).isSuccess ());

  final MockCloseableWithState c = new MockCloseableWithState ();
  assertTrue (StreamHelper.flush (c).isSuccess ());
  assertFalse (c.isClosed ());
  assertTrue (c.isFlushed ());

  StreamHelper.close (new FilterOutputStream (null));
}
 
Example 30
Source Project: incubator-gobblin   Source File: MeteredOutputStream.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find the lowest {@link MeteredOutputStream} in a chain of {@link FilterOutputStream}s.
 */
public static Optional<MeteredOutputStream> findWrappedMeteredOutputStream(OutputStream os) {
  if (os instanceof FilterOutputStream) {
    try {
      Optional<MeteredOutputStream> meteredOutputStream =
          findWrappedMeteredOutputStream(FilterStreamUnpacker.unpackFilterOutputStream((FilterOutputStream) os));
      if (meteredOutputStream.isPresent()) {
        return meteredOutputStream;
      }
    } catch (IllegalAccessException iae) {
      log.warn("Cannot unpack input stream due to SecurityManager.", iae);
      // Do nothing, we can't unpack the FilterInputStream due to security restrictions
    }
  }
  if (os instanceof MeteredOutputStream) {
    return Optional.of((MeteredOutputStream) os);
  }
  return Optional.absent();
}