MessageContentUtil { public static void encryptContent( SecurityManager securityManager, String hostIdSource, String hostIdTarget, Message message ) { OutputStream os = message.getContent( OutputStream.class ); CachedStream cs = new CachedStream(); message.setContent( OutputStream.class, cs ); message.getInterceptorChain().doIntercept( message ); LOG.debug( String.format( "Encrypting IDs: %s -> %s", hostIdSource, hostIdTarget ) ); try { cs.flush(); CachedOutputStream csnew = ( CachedOutputStream ) message.getContent( OutputStream.class ); byte[] originalMessage = org.apache.commons.io.IOUtils.toByteArray( csnew.getInputStream() ); LOG.debug( String.format( "Original payload: \"%s\"", new String( originalMessage ) ) ); csnew.flush(); org.apache.commons.io.IOUtils.closeQuietly( cs ); org.apache.commons.io.IOUtils.closeQuietly( csnew ); byte[] finalMessage = originalMessage.length > 0 ? encryptData( securityManager, hostIdTarget, originalMessage ) : null; if ( !ArrayUtils.isEmpty( finalMessage ) ) { InputStream replaceInStream = new ByteArrayInputStream( finalMessage ); org.apache.commons.io.IOUtils.copy( replaceInStream, os ); replaceInStream.close(); org.apache.commons.io.IOUtils.closeQuietly( replaceInStream ); os.flush(); message.setContent( OutputStream.class, os ); } org.apache.commons.io.IOUtils.closeQuietly( os ); } catch ( Exception ioe ) { throw new ActionFailedException( "Error encrypting content", ioe ); } } private  MessageContentUtil(); static void abortChain( Message message, Throwable ex ); static void abortChain( Message message, int errorStatus, String errorMessage ); static void decryptContent( SecurityManager securityManager, Message message, String hostIdSource,
                                       String hostIdTarget ); static void encryptContent( SecurityManager securityManager, String hostIdSource, String hostIdTarget,
                                       Message message );  }
@Test public void testEncryptContent() throws Exception { doReturn( new ByteArrayInputStream( "OK".getBytes() ) ).when( cachedOutputStream ).getInputStream(); doReturn( pgpPublicKey ).when( keyManager ).getRemoteHostPublicKey( anyString() ); doReturn( "OK".getBytes() ).when( encryptionTool ) .encrypt( isA( byte[].class ), isA( PGPPublicKey.class ), eq( true ) ); MessageContentUtil.encryptContent( securityManager, SRC, TARGET, message ); verify( encryptionTool ).encrypt( isA( byte[].class ), eq( pgpPublicKey ), eq( true ) ); }