List of usage examples for java.io OutputStream OutputStream
OutputStream
From source file:ch.cyberduck.core.http.DelayedHttpMultipartEntity.java
public void writeTo(final OutputStream out) throws IOException { try {/*from www . j a va 2 s . c o m*/ stream = new OutputStream() { private final AtomicBoolean close = new AtomicBoolean(); @Override public void write(final byte[] b, final int off, final int len) throws IOException { out.write(b, off, len); } @Override public void write(final int b) throws IOException { out.write(b); } @Override public void write(final byte[] b) throws IOException { out.write(b); } @Override public void close() throws IOException { if (close.get()) { log.warn(String.format("Skip double close of stream %s", this)); return; } try { out.write(footer); super.close(); } finally { // Signal finished writing to stream exit.countDown(); close.set(true); } } }; stream.write(header); } finally { final CountDownLatch entry = this.getEntry(); // Signal stream is ready for writing entry.countDown(); } // Wait for signal when content has been written to the pipe try { exit.await(); } catch (InterruptedException e) { log.error(String.format("Error waiting for exit signal %s", e.getMessage())); throw new IOException(e); } // Entity written to server consumed = true; }
From source file:me.aerovulpe.crawler.data.SimpleDiskCache.java
public synchronized OutputStream openStream(String key, Map<String, ? extends Serializable> metadata) throws IOException { DiskLruCache.Editor editor = diskLruCache.edit(toInternalKey(key)); if (editor == null) { Log.e(TAG, "Unable to open stream."); return new OutputStream() { @Override//from ww w . j a v a 2s .c om public void write(int oneByte) throws IOException { // DO NOTHING } }; } try { writeMetadata(metadata, editor); BufferedOutputStream bos = new BufferedOutputStream(editor.newOutputStream(VALUE_IDX)); return new CacheOutputStream(bos, editor); } catch (IOException e) { editor.abort(); throw e; } }
From source file:it.anyplace.sync.httprelay.client.HttpRelayConnection.java
protected HttpRelayConnection(String httpRelayServerUrl, String deviceId) { this.httpRelayServerUrl = httpRelayServerUrl; try {//from w w w . j a va 2s. co m HttpRelayProtos.HttpRelayServerMessage serverMessage = sendMessage(HttpRelayProtos.HttpRelayPeerMessage .newBuilder().setMessageType(HttpRelayProtos.HttpRelayPeerMessageType.CONNECT) .setDeviceId(deviceId)); checkArgument(equal(serverMessage.getMessageType(), HttpRelayProtos.HttpRelayServerMessageType.PEER_CONNECTED)); checkNotNull(Strings.emptyToNull(serverMessage.getSessionId())); sessionId = serverMessage.getSessionId(); isServerSocket = serverMessage.getIsServerSocket(); outputStream = new OutputStream() { private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private long lastFlush = System.currentTimeMillis(); { flusherStreamService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { if (System.currentTimeMillis() - lastFlush > 1000) { try { flush(); } catch (IOException ex) { } } } }, 1, 1, TimeUnit.SECONDS); } @Override public synchronized void write(int i) throws IOException { checkArgument(!HttpRelayConnection.this.isClosed()); buffer.write(i); } @Override public synchronized void write(byte[] bytes, int offset, int size) throws IOException { checkArgument(!HttpRelayConnection.this.isClosed()); buffer.write(bytes, offset, size); } @Override public synchronized void flush() throws IOException { final ByteString data = ByteString.copyFrom(buffer.toByteArray()); buffer = new ByteArrayOutputStream(); try { if (!data.isEmpty()) { outgoingExecutorService.submit(new Runnable() { @Override public void run() { try { sendMessage(HttpRelayProtos.HttpRelayPeerMessage.newBuilder() .setMessageType( HttpRelayProtos.HttpRelayPeerMessageType.PEER_TO_RELAY) .setSequence(++peerToRelaySequence).setData(data)); } catch (Exception ex) { if (!isClosed()) { logger.error("error", ex); closeBg(); } throw ex; } } }).get(); } lastFlush = System.currentTimeMillis(); } catch (InterruptedException | ExecutionException ex) { logger.error("error", ex); closeBg(); throw new IOException(ex); } } @Override public synchronized void write(byte[] bytes) throws IOException { checkArgument(!HttpRelayConnection.this.isClosed()); buffer.write(bytes); } }; incomingExecutorService.submit(new Runnable() { @Override public void run() { while (!isClosed()) { try { HttpRelayProtos.HttpRelayServerMessage serverMessage = sendMessage( HttpRelayProtos.HttpRelayPeerMessage.newBuilder().setMessageType( HttpRelayProtos.HttpRelayPeerMessageType.WAIT_FOR_DATA)); if (isClosed()) { return; } checkArgument(equal(serverMessage.getMessageType(), HttpRelayProtos.HttpRelayServerMessageType.RELAY_TO_PEER)); checkArgument(serverMessage.getSequence() == relayToPeerSequence + 1); if (!serverMessage.getData().isEmpty()) { incomingDataQueue.add(serverMessage.getData().toByteArray()); } relayToPeerSequence = serverMessage.getSequence(); } catch (Exception ex) { if (!isClosed()) { logger.error("error", ex); closeBg(); } return; } } } }); inputStream = new InputStream() { private boolean noMoreData = false; private ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(new byte[0]); @Override public int read() throws IOException { checkArgument(!HttpRelayConnection.this.isClosed()); if (noMoreData) { return -1; } int bite; while ((bite = byteArrayInputStream.read()) == -1) { try { byte[] data = incomingDataQueue.poll(1, TimeUnit.SECONDS); if (data == null) { //continue } else if (data == STREAM_CLOSED) { noMoreData = true; return -1; } else { byteArrayInputStream = new ByteArrayInputStream(data); } } catch (InterruptedException ex) { } } return bite; } }; socket = new Socket() { @Override public boolean isClosed() { return HttpRelayConnection.this.isClosed(); } @Override public boolean isConnected() { return !isClosed(); } @Override public void shutdownOutput() throws IOException { logger.debug("shutdownOutput"); getOutputStream().flush(); } @Override public void shutdownInput() throws IOException { logger.debug("shutdownInput"); //do nothing } @Override public synchronized void close() throws IOException { logger.debug("received close on socket adapter"); HttpRelayConnection.this.close(); } @Override public OutputStream getOutputStream() throws IOException { return outputStream; } @Override public InputStream getInputStream() throws IOException { return inputStream; } @Override public SocketAddress getRemoteSocketAddress() { return new InetSocketAddress(getInetAddress(), getPort()); } @Override public int getPort() { return 22067; } @Override public InetAddress getInetAddress() { try { return InetAddress .getByName(URI.create(HttpRelayConnection.this.httpRelayServerUrl).getHost()); } catch (UnknownHostException ex) { throw new RuntimeException(ex); } } }; } catch (Exception ex) { close(); throw ex; } }
From source file:io.github.data4all.util.upload.ChangesetUtil.java
/** * Parses all objects from the database into an xml structure to create a * new Changeset.//from w w w.j av a 2 s .co m * * @param context * The application context for the {@link DataBaseHandler}. * @param changesetId * The Changeset ID from the OSM API. * @return The created Changeset. * @throws OsmException * Indicates an failure in an osm progess. */ public static String getChangesetXml(Context context, int changesetId) throws OsmException { final DataBaseHandler db = new DataBaseHandler(context); final List<DataElement> elems = db.getAllDataElements(); db.close(); final StringBuilder builder = new StringBuilder(); final PrintWriter writer = new PrintWriter(new OutputStream() { @Override public void write(int oneByte) throws IOException { builder.append((char) oneByte); } }); OsmChangeParser.parseElements(elems, changesetId, writer); writer.close(); return builder.toString(); }
From source file:org.hibernate.search.elasticsearch.test.GsonStreamedEncodingTest.java
@Test public void testDigestToTriggerLengthComputation() { final List<JsonObject> list = produceLargeBulkJSON(); try (GsonHttpEntity entity = new GsonHttpEntity(gson, list)) { assertEquals(-1l, entity.getContentLength()); } catch (IOException e) { throw new RuntimeException("We're mocking IO operations, this should not happen?", e); }/* w ww. j av a 2s . c o m*/ //Need to discard the entity and get a new one, as the getContentLenght() //invocation will have frozen the value: we can't report inconsistent values //to the Apache HTTP client or it gets confused. try (GsonHttpEntity entity = new GsonHttpEntity(gson, list)) { final MessageDigest digest = getSha256Digest(); OutputStream discardingStream = new OutputStream() { @Override public void write(int b) throws IOException { } }; DigestOutputStream digestStream = new DigestOutputStream(discardingStream, digest); entity.writeTo(digestStream); assertNotEquals(-1l, entity.getContentLength()); final byte[] content = produceContentWithCustomEncoder(entity); assertEquals(content.length, entity.getContentLength()); } catch (IOException e) { throw new RuntimeException("We're mocking IO operations, this should not happen?", e); } }
From source file:com.cw.litenote.DrawerActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { ////*from w ww. j a v a 2 s . c om*/ // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() // // .detectDiskReads() // .detectDiskWrites() // .detectNetwork() // .penaltyLog() // .build()); // // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() //// .detectLeakedSqlLiteObjects() //??? unmark this line will cause strict mode error // .penaltyLog() // .penaltyDeath() // .build()); /// super.onCreate(savedInstanceState); mDrawerActivity = this; setContentView(R.layout.drawer_activity); // Release mode: no debug message if (Define.CODE_MODE == Define.RELEASE_MODE) { OutputStream nullDev = new OutputStream() { public void close() { } public void flush() { } public void write(byte[] b) { } public void write(byte[] b, int off, int len) { } public void write(int b) { } }; System.setOut(new PrintStream(nullDev)); } //Log.d below can be disabled by applying proguard //1. enable proguard-android-optimize.txt in project.properties //2. be sure to use newest version to avoid build error //3. add the following in proguard-project.txt /*-assumenosideeffects class android.util.Log { public static boolean isLoggable(java.lang.String, int); public static int v(...); public static int i(...); public static int w(...); public static int d(...); public static int e(...); } */ Log.d("test log tag", "start app"); System.out.println("================start application =================="); System.out.println("DrawerActivity / onCreate"); UtilImage.getDefaultSacleInPercent(DrawerActivity.this); mAppTitle = getTitle(); mDrawerChildTitles = new ArrayList<String>(); Context context = getApplicationContext(); if (mDb != null) mDb.close(); mDb = new DB(context); mDb.initDrawerDb(mDb); if (mDb_tabs != null) mDb_tabs.close(); mDb_tabs = new DB(context, Util.getPref_lastTimeView_tabs_tableId(this)); mDb_tabs.initTabsDb(mDb_tabs); if (mDb_notes != null) mDb_tabs.close(); mDb_notes = new DB(context, Util.getPref_lastTimeView_notes_tableId(this)); mDb_notes.initNotesDb(mDb_notes); //Add note with the link String intentLink = addIntentLink(getIntent()); if (!Util.isEmptyString(intentLink)) { finish(); // for no active DrawerActivity case } else { // check DB final boolean ENABLE_DB_CHECK = false;//true;// if (ENABLE_DB_CHECK) { // list all drawer tables int drawerCount = mDb.getDrawerChildCount(); for (int drawerPos = 0; drawerPos < drawerCount; drawerPos++) { String drawerTitle = mDb.getDrawerChild_Title(drawerPos); DrawerActivity.mFocus_drawerChildPos = drawerPos; // list all tab tables int tabsTableId = mDb.getTabsTableId(drawerPos); System.out.println("--- tabs table Id = " + tabsTableId + ", drawer title = " + drawerTitle); mDb_tabs = new DB(context, tabsTableId); mDb_tabs.initTabsDb(mDb_tabs); int tabsCount = mDb_tabs.getTabsCount(true); for (int tabPos = 0; tabPos < tabsCount; tabPos++) { TabsHostFragment.mCurrent_tabIndex = tabPos; int tabId = mDb_tabs.getTabId(tabPos, true); int notesTableId = mDb_tabs.getNotesTableId(tabPos, true); String tabTitle = mDb_tabs.getTabTitle(tabPos, true); System.out.println(" --- tab Id = " + tabId); System.out.println(" --- notes table Id = " + notesTableId); System.out.println(" --- tab title = " + tabTitle); mLastOkTabId = tabId; try { mDb_notes = new DB(context, String.valueOf(notesTableId)); mDb_notes.initNotesDb(mDb_notes); mDb_notes.doOpenNotes(); mDb_notes.doCloseNotes(); } catch (Exception e) { } } } // recover focus int tabsTableId = Util.getPref_lastTimeView_tabs_tableId(this); DB.setFocus_tabsTableId(tabsTableId); String notesTableId = Util.getPref_lastTimeView_notes_tableId(this); DB.setFocus_notes_tableId(notesTableId); } //if(ENABLE_DB_CHECK) // get last time drawer number, default drawer number: 1 if (savedInstanceState == null) { for (int i = 0; i < mDb.getDrawerChildCount(); i++) { if (mDb.getTabsTableId(i) == Util.getPref_lastTimeView_tabs_tableId(this)) { mFocus_drawerChildPos = i; System.out .println("DrawerActivity / onCreate / mFocusDrawerId = " + mFocus_drawerChildPos); } } AudioPlayer.mPlayerState = AudioPlayer.PLAYER_AT_STOP; UtilAudio.mIsCalledWhilePlayingAudio = false; } // set drawer title if (mDb.getDrawerChildCount() == 0) { for (int i = 0; i < Define.ORIGIN_TABS_TABLE_COUNT; i++) { String drawerTitle = Define.getDrawerTitle(mDrawerActivity, i); mDrawerChildTitles.add(drawerTitle); mDb.insertDrawerChild(i + 1, drawerTitle); } } else { for (int i = 0; i < mDb.getDrawerChildCount(); i++) { mDrawerChildTitles.add(""); // init only mDrawerChildTitles.set(i, mDb.getDrawerChild_Title(i)); } } mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerListView = (DragSortListView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set adapter mDb.doOpenDrawer(); Cursor cursor = DB.mCursor_drawerChild; String[] from = new String[] { DB.KEY_DRAWER_TITLE }; int[] to = new int[] { R.id.drawerText }; drawerAdapter = new DrawerAdapter(this, R.layout.drawer_list_item, cursor, from, to, 0); mDb.doCloseDrawer(); mDrawerListView.setAdapter(drawerAdapter); // set up click listener MainUi.addDrawerItemListeners();//??? move to resume? mDrawerListView.setOnItemClickListener(MainUi.itemClick); // set up long click listener mDrawerListView.setOnItemLongClickListener(MainUi.itemLongClick); mController = DrawerListview.buildController(mDrawerListView); mDrawerListView.setFloatViewManager(mController); mDrawerListView.setOnTouchListener(mController); // init drawer dragger mPref_show_note_attribute = getSharedPreferences("show_note_attribute", 0); if (mPref_show_note_attribute.getString("KEY_ENABLE_DRAWER_DRAGGABLE", "no").equalsIgnoreCase("yes")) mDrawerListView.setDragEnabled(true); else mDrawerListView.setDragEnabled(false); mDrawerListView.setDragListener(DrawerListview.onDrag); mDrawerListView.setDropListener(DrawerListview.onDrop); // enable ActionBar app icon to behave as action to toggle nav drawer getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); // getActionBar().setBackgroundDrawable(new ColorDrawable(ColorSet.bar_color)); getActionBar().setBackgroundDrawable(new ColorDrawable(ColorSet.getBarColor(mDrawerActivity))); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* navigation drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { System.out.println("mDrawerToggle onDrawerClosed "); int pos = mDrawerListView.getCheckedItemPosition(); int tblId = mDb.getTabsTableId(pos); DB.setSelected_tabsTableId(tblId); mDrawerChildTitle = mDb.getDrawerChild_Title(pos); setTitle(mDrawerChildTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() // add for deleting drawer if (TabsHostFragment.mTabHost == null) { MainUi.selectDrawerChild(mFocus_drawerChildPos); setTitle(mDrawerChildTitle); } } public void onDrawerOpened(View drawerView) { System.out.println("mDrawerToggle onDrawerOpened "); setTitle(mAppTitle); drawerAdapter.notifyDataSetChanged(); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); mContext = getBaseContext(); bEnableConfig = false; // add on back stack changed listener fragmentManager = getSupportFragmentManager(); mOnBackStackChangedListener = DrawerActivity.this; fragmentManager.addOnBackStackChangedListener(mOnBackStackChangedListener); // register an audio stream receiver if (noisyAudioStreamReceiver == null) { noisyAudioStreamReceiver = new NoisyAudioStreamReceiver(); intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY); registerReceiver(noisyAudioStreamReceiver, intentFilter); } } // Show license dialog new EULA_dlg(this).show(); }
From source file:com.medvision360.medrecord.tools.cliclient.RemoteArchetypeStore.java
@Override public WrappedArchetype insert(Archetype archetype) throws DuplicateException, IOException, SerializeException { WrappedArchetype wrapped = new WrappedArchetype(null, archetype); wrapped = m_archetypeSerializer.serialize(wrapped, new OutputStream() { @Override/*from w w w . j a va 2 s .c o m*/ public void write(int b) { } }); return insert(wrapped); }
From source file:hudson.scm.CvsTagsParamDefinition.java
@Exported public ListBoxModel getSymbolicNames() { ListBoxModel model = new ListBoxModel(); CvsChangeSet changeSet = null;//from w w w . ja v a2s . c o m RlogCommand statusCommand = new RlogCommand(); statusCommand.setHeaderOnly(true); statusCommand.setModule(moduleName); statusCommand.setRecursive(true); try { final File tempRlogSpill = File.createTempFile("cvs", "status ); ` "); final DeferredFileOutputStream outputStream = new DeferredFileOutputStream(100 * 1024, tempRlogSpill); final PrintStream logStream = new PrintStream(outputStream, true, getCvsDescriptor().getChangelogEncoding()); final OutputStream errorOutputStream = new OutputStream() { final StringBuffer buffer = new StringBuffer(); @Override public void write(int b) throws IOException { if ((int) ("\n".getBytes()[0]) == b) { flush(); } else { buffer.append(new String(new byte[] { (byte) b })); } } @Override public void flush() throws IOException { logger.info(buffer.toString()); buffer.delete(0, buffer.length()); super.flush(); } public void close() throws IOException { flush(); super.close(); } }; final PrintStream errorPrintStream = new PrintStream(errorOutputStream); Client cvsClient = getCvsClient(cvsRoot, passwordRequired, password); cvsClient.getEventManager().addCVSListener(new BasicListener(logStream, errorPrintStream)); cvsClient.executeCommand(statusCommand, getGlobalOptions(cvsRoot)); logStream.close(); errorPrintStream.flush(); errorPrintStream.close(); CvsLog parser = new CvsLog() { @Override public Reader read() throws IOException { if (outputStream.isInMemory()) return new InputStreamReader(new ByteArrayInputStream(outputStream.getData()), getCvsDescriptor().getChangelogEncoding()); else return new InputStreamReader(new FileInputStream(outputStream.getFile()), getCvsDescriptor().getChangelogEncoding()); } @Override public void dispose() { tempRlogSpill.delete(); } }; changeSet = parser.mapCvsLog(cvsRoot, new CvsRepositoryLocation.HeadRepositoryLocation()); } catch (IOException ex) { model.add(new ListBoxModel.Option("Could not load symbolic names - " + ex.getLocalizedMessage())); return model; } catch (CommandAbortedException ex) { model.add(new ListBoxModel.Option("Could not load symbolic names - " + ex.getLocalizedMessage())); return model; } catch (CommandException ex) { model.add(new ListBoxModel.Option("Could not load symbolic names - " + ex.getLocalizedMessage())); return model; } catch (AuthenticationException ex) { model.add(new ListBoxModel.Option("Could not load symbolic names - " + ex.getLocalizedMessage())); return model; } model.add(new ListBoxModel.Option("Head", "HEAD")); for (String branchName : changeSet.getBranchNames()) { model.add(new ListBoxModel.Option(branchName + " (Branch)", branchName)); } for (String tagName : changeSet.getTagNames()) { model.add(new ListBoxModel.Option(tagName + " (Tag)", tagName)); } return model; }
From source file:org.jcodec.common.io.Buffer.java
public OutputStream os() { return new OutputStream() { public void write(byte[] b, int off, int len) throws IOException { System.arraycopy(b, off, buffer, pos, len); pos += len;/*from w w w. j a va 2 s . c o m*/ } public void write(int b) throws IOException { buffer[pos++] = (byte) b; } }; }
From source file:org.apache.nifi.minifi.toolkit.configuration.ConfigMainTest.java
@Test public void testTransformErrorTransformingTemplate() throws FileNotFoundException { when(pathInputStreamFactory.create(testInput)).thenAnswer( invocation -> ConfigMainTest.class.getClassLoader().getResourceAsStream("CsvToJson.xml")); when(pathOutputStreamFactory.create(testOutput)).thenAnswer(invocation -> new OutputStream() { @Override//w w w.ja v a 2 s . c o m public void write(int b) throws IOException { throw new IOException(); } }); assertEquals(ConfigMain.ERR_UNABLE_TO_TRANSFORM_TEMPLATE, configMain.execute(new String[] { ConfigMain.TRANSFORM, testInput, testOutput })); }