Java Code Examples for com.helger.commons.io.stream.StreamHelper#close()

The following examples show how to use com.helger.commons.io.stream.StreamHelper#close() . 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 File: IJAXBWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write the passed object to a {@link Writer}.
 *
 * @param aObject
 *        The object to be written. May not be <code>null</code>.
 * @param aWriter
 *        The writer to write to. Will always be closed. May not be
 *        <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
default ESuccess write (@Nonnull final JAXBTYPE aObject, @Nonnull @WillClose final Writer aWriter)
{
  try
  {
    if (USE_JAXB_CHARSET_FIX)
    {
      return write (aObject, SafeXMLStreamWriter.create (aWriter, getXMLWriterSettings ()));
    }
    return write (aObject, TransformResultFactory.create (aWriter));
  }
  finally
  {
    // Needs to be manually closed
    StreamHelper.close (aWriter);
  }
}
 
Example 2
Source File: IJAXBWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write the passed object to an {@link OutputStream}.
 *
 * @param aObject
 *        The object to be written. May not be <code>null</code>.
 * @param aOS
 *        The output stream to write to. Will always be closed. May not be
 *        <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
default ESuccess write (@Nonnull final JAXBTYPE aObject, @Nonnull @WillClose final OutputStream aOS)
{
  try
  {
    if (USE_JAXB_CHARSET_FIX)
    {
      return write (aObject, SafeXMLStreamWriter.create (aOS, getXMLWriterSettings ()));
    }
    return write (aObject, TransformResultFactory.create (aOS));
  }
  finally
  {
    // Needs to be manually closed
    StreamHelper.close (aOS);
  }
}
 
Example 3
Source File: URLResource.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
public boolean exists ()
{
  // 1. as file
  if (URLHelper.PROTOCOL_FILE.equals (m_aURL.getProtocol ()))
    return getAsFile ().exists ();

  // Not a file URL
  InputStream aIS = null;
  try
  {
    // 2. as stream
    aIS = getInputStream ();
    return aIS != null;
  }
  catch (final Exception ex)
  {
    // 3. no
    return false;
  }
  finally
  {
    StreamHelper.close (aIS);
  }
}
 
Example 4
Source File: SettingsPersistenceXML.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
public ESuccess writeSettings (@Nonnull final ISettings aSettings, @Nonnull @WillClose final OutputStream aOS)
{
  ValueEnforcer.notNull (aSettings, "Settings");
  ValueEnforcer.notNull (aOS, "OutputStream");

  try
  {
    // Inside try so that OS is closed
    ValueEnforcer.notNull (aSettings, "Settings");

    // No event manager invocation on writing
    final SettingsMicroDocumentConverter <T> aConverter = new SettingsMicroDocumentConverter <> (m_aSettingsFactory);
    final IMicroDocument aDoc = new MicroDocument ();
    aDoc.appendChild (aConverter.convertToMicroElement (GenericReflection.uncheckedCast (aSettings),
                                                        getWriteNamespaceURI (),
                                                        getWriteElementName ()));

    // auto-closes the stream
    return MicroWriter.writeToStream (aDoc, aOS, m_aXWS);
  }
  finally
  {
    StreamHelper.close (aOS);
  }
}
 
Example 5
Source File: FileSystemByteStreamProviderTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testAll ()
{
  final FileSystemByteStreamProvider aFSSR = new FileSystemByteStreamProvider (new File ("."));
  final InputStream aIS = aFSSR.getInputStream ("pom.xml");
  assertNotNull (aIS);
  StreamHelper.close (aIS);

  final OutputStream aOS = aFSSR.getOutputStream ("$deleteme.txt", EAppend.DEFAULT);
  assertNotNull (aOS);
  StreamHelper.close (aOS);
  assertTrue (FileOperations.deleteFile (new File ("$deleteme.txt")).isSuccess ());

  CommonsTestHelper.testDefaultImplementationWithEqualContentObject (new FileSystemByteStreamProvider (new File (".")),
                                                                     new FileSystemByteStreamProvider (new File (".")));
  CommonsTestHelper.testDefaultImplementationWithEqualContentObject (new FileSystemByteStreamProvider (new File (".")),
                                                                     new FileSystemByteStreamProvider ("."));
  CommonsTestHelper.testDefaultImplementationWithDifferentContentObject (new FileSystemByteStreamProvider (new File (".")),
                                                                         new FileSystemByteStreamProvider (new File ("..")));
}
 
Example 6
Source File: CharsetHelperTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testGreek () throws Exception
{
  final String sAlpha = "?\u03B1";
  byte [] b = sAlpha.getBytes (StandardCharsets.UTF_8);
  assertEquals (sAlpha, new String (b, StandardCharsets.UTF_8));

  b = sAlpha.getBytes (StandardCharsets.UTF_8);
  assertEquals (sAlpha, new String (b, StandardCharsets.UTF_8));

  NonBlockingBufferedReader aReader = new NonBlockingBufferedReader (new InputStreamReader (new NonBlockingByteArrayInputStream (b),
                                                                                            StandardCharsets.UTF_8));
  assertEquals (sAlpha, aReader.readLine ());
  StreamHelper.close (aReader);

  aReader = new NonBlockingBufferedReader (new InputStreamReader (new NonBlockingByteArrayInputStream (b),
                                                                  StandardCharsets.UTF_8));
  assertEquals (sAlpha, aReader.readLine ());
  StreamHelper.close (aReader);
}
 
Example 7
Source File: CSSReaderDeclarationList.java    From ph-css with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the passed reader can be resembled to valid CSS content. This is
 * accomplished by fully parsing the CSS each time the method is called. This
 * is similar to calling
 * {@link #readFromStream(IHasInputStream, Charset, ECSSVersion)} and checking
 * for a non-<code>null</code> result.
 *
 * @param aReader
 *        The reader to use. May not be <code>null</code>.
 * @param eVersion
 *        The CSS version to use. May not be <code>null</code>.
 * @return <code>true</code> if the CSS is valid according to the version,
 *         <code>false</code> if not
 */
public static boolean isValidCSS (@Nonnull @WillClose final Reader aReader, @Nonnull final ECSSVersion eVersion)
{
  ValueEnforcer.notNull (aReader, "Reader");
  ValueEnforcer.notNull (eVersion, "Version");

  try
  {
    final CSSCharStream aCharStream = new CSSCharStream (aReader);
    final CSSNode aNode = _readStyleDeclaration (aCharStream,
                                                 eVersion,
                                                 getDefaultParseErrorHandler (),
                                                 new DoNothingCSSParseExceptionCallback ());
    return aNode != null;
  }
  finally
  {
    StreamHelper.close (aReader);
  }
}
 
Example 8
Source File: XMLMapHandler.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write the passed map to the passed output stream using the predefined XML
 * layout.
 *
 * @param aMap
 *        The map to be written. May not be <code>null</code>.
 * @param aOS
 *        The output stream to write to. The stream is closed independent of
 *        success or failure. May not be <code>null</code>.
 * @return {@link ESuccess#SUCCESS} when everything went well,
 *         {@link ESuccess#FAILURE} otherwise.
 */
@Nonnull
public static ESuccess writeMap (@Nonnull final Map <String, String> aMap, @Nonnull @WillClose final OutputStream aOS)
{
  ValueEnforcer.notNull (aMap, "Map");
  ValueEnforcer.notNull (aOS, "OutputStream");

  try
  {
    final IMicroDocument aDoc = createMapDocument (aMap);
    return MicroWriter.writeToStream (aDoc, aOS, XMLWriterSettings.DEFAULT_XML_SETTINGS);
  }
  finally
  {
    StreamHelper.close (aOS);
  }
}
 
Example 9
Source File: MicroWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write a Micro Node to a {@link Writer}.
 *
 * @param aNode
 *        The node to be serialized. May be any kind of node (incl.
 *        documents). May not be <code>null</code>.
 * @param aWriter
 *        The writer to write to. May not be <code>null</code>. The writer is
 *        closed anyway directly after the operation finishes (on success and
 *        on error).
 * @param aSettings
 *        The settings to be used for the creation. May not be
 *        <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
public static ESuccess writeToWriter (@Nonnull final IMicroNode aNode,
                                      @Nonnull @WillClose final Writer aWriter,
                                      @Nonnull final IXMLWriterSettings aSettings)
{
  ValueEnforcer.notNull (aNode, "Node");
  ValueEnforcer.notNull (aWriter, "Writer");
  ValueEnforcer.notNull (aSettings, "Settings");

  try
  {
    final MicroSerializer aSerializer = new MicroSerializer (aSettings);
    aSerializer.write (aNode, aWriter);
    return ESuccess.SUCCESS;
  }
  finally
  {
    StreamHelper.close (aWriter);
  }
}
 
Example 10
Source File: ClassPathHelperTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Test for method printClassPathEntries
 *
 * @throws UnsupportedEncodingException
 *         never
 */
@Test
public void testPrintClassPathEntries () throws UnsupportedEncodingException
{
  // Use default separator
  NonBlockingByteArrayOutputStream baos = new NonBlockingByteArrayOutputStream ();
  ClassPathHelper.printClassPathEntries (new PrintStream (baos, false, StandardCharsets.ISO_8859_1.name ()));
  assertTrue (baos.getAsString (StandardCharsets.ISO_8859_1).length () > 0);
  assertTrue (baos.getAsString (StandardCharsets.ISO_8859_1).indexOf ("\n") > 0);
  StreamHelper.close (baos);

  // Use special separator
  baos = new NonBlockingByteArrayOutputStream ();
  ClassPathHelper.printClassPathEntries (new PrintStream (baos, false, StandardCharsets.ISO_8859_1.name ()), "$$$");
  assertTrue (baos.getAsString (StandardCharsets.ISO_8859_1).length () > 0);
  assertTrue (baos.getAsString (StandardCharsets.ISO_8859_1).indexOf ("$$$") > 0);
  assertTrue (baos.getAsString (StandardCharsets.UTF_8).indexOf ("$$$") > 0);
  StreamHelper.close (baos);
}
 
Example 11
Source File: MicroWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write a Micro Node to an {@link OutputStream}.
 *
 * @param aNode
 *        The node to be serialized. May be any kind of node (incl.
 *        documents). May not be <code>null</code>.
 * @param aOS
 *        The output stream to write to. May not be <code>null</code>. The
 *        output stream is closed anyway directly after the operation finishes
 *        (on success and on error).
 * @param aSettings
 *        The settings to be used for the creation. May not be
 *        <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
public static ESuccess writeToStream (@Nonnull final IMicroNode aNode,
                                      @Nonnull @WillClose final OutputStream aOS,
                                      @Nonnull final IXMLWriterSettings aSettings)
{
  ValueEnforcer.notNull (aNode, "Node");
  ValueEnforcer.notNull (aOS, "OutputStream");
  ValueEnforcer.notNull (aSettings, "Settings");

  try
  {
    final MicroSerializer aSerializer = new MicroSerializer (aSettings);
    aSerializer.write (aNode, aOS);
    return ESuccess.SUCCESS;
  }
  finally
  {
    StreamHelper.close (aOS);
  }
}
 
Example 12
Source File: CachingTransformStreamSourceTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic ()
{
  final IReadableResource aRes = new ClassPathResource ("xml/test1.xslt");
  assertTrue (aRes.exists ());
  CachingTransformStreamSource src = new CachingTransformStreamSource (aRes);
  InputStream is = src.getInputStream ();
  assertNotNull (is);
  StreamHelper.close (is);
  is = src.getInputStream ();
  assertNotNull (is);
  StreamHelper.close (is);
  assertEquals (aRes.getResourceID (), src.getSystemId ());
  assertNull (src.getPublicId ());

  src = new CachingTransformStreamSource ((IHasInputStream) aRes);
  is = src.getInputStream ();
  assertNotNull (is);
  StreamHelper.close (is);
  is = src.getInputStream ();
  assertNotNull (is);
  StreamHelper.close (is);
  assertNull (src.getSystemId ());
  assertNull (src.getPublicId ());

  src = new CachingTransformStreamSource (aRes.getInputStream ());
  is = src.getInputStream ();
  assertNotNull (is);
  StreamHelper.close (is);
  is = src.getInputStream ();
  assertNotNull (is);
  StreamHelper.close (is);
  assertNull (src.getSystemId ());
  assertNull (src.getPublicId ());

  CommonsTestHelper.testToStringImplementation (src);
}
 
Example 13
Source File: FileOperations.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Copy the content of the source file to the destination file using
 * {@link InputStream} and {@link OutputStream}.
 *
 * @param aSrcFile
 *        Source file. May not be <code>null</code>.
 * @param aDestFile
 *        Destination file. May not be <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
private static ESuccess _copyFileViaStreams (@Nonnull final File aSrcFile, @Nonnull final File aDestFile)
{
  final InputStream aSrcIS = FileHelper.getInputStream (aSrcFile);
  if (aSrcIS == null)
    return ESuccess.FAILURE;

  try
  {
    final OutputStream aDstOS = FileHelper.getOutputStream (aDestFile, EAppend.TRUNCATE);
    if (aDstOS == null)
      return ESuccess.FAILURE;

    try
    {
      return StreamHelper.copyInputStreamToOutputStream (aSrcIS, aDstOS);
    }
    finally
    {
      StreamHelper.close (aDstOS);
    }
  }
  finally
  {
    StreamHelper.close (aSrcIS);
  }
}
 
Example 14
Source File: XMLListHandler.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Read a predefined XML file that contains list items.
 *
 * @param aIS
 *        The input stream to read from. May not be <code>null</code>.
 *        Automatically closed no matter whether reading succeeded or not.
 * @param aTargetList
 *        The target collection to be filled. May not be <code>null</code>.
 * @return {@link ESuccess#SUCCESS} if reading succeeded,
 *         {@link ESuccess#FAILURE} if the input stream is no valid XML or any
 *         other error occurred.
 */
@Nonnull
public static ESuccess readList (@Nonnull @WillClose final InputStream aIS,
                                 @Nonnull final Collection <String> aTargetList)
{
  ValueEnforcer.notNull (aIS, "InputStream");
  ValueEnforcer.notNull (aTargetList, "TargetList");

  try
  {
    // open file
    final IMicroDocument aDoc = MicroReader.readMicroXML (aIS,
                                                          new SAXReaderSettings ().setFeatureValues (EXMLParserFeature.AVOID_XXE_SETTINGS));
    if (aDoc != null)
    {
      readList (aDoc.getDocumentElement (), aTargetList);
      return ESuccess.SUCCESS;
    }
  }
  catch (final Exception ex)
  {
    if (LOGGER.isWarnEnabled ())
      LOGGER.warn ("Failed to read list resource '" + aIS + "'", ex);
  }
  finally
  {
    StreamHelper.close (aIS);
  }

  return ESuccess.FAILURE;
}
 
Example 15
Source File: FileChannelHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
public static OutputStream getMappedOutputStream (@Nonnull final File aFile, @Nonnull final EAppend eAppend)
{
  ValueEnforcer.notNull (aFile, "File");
  ValueEnforcer.notNull (eAppend, "Append");

  if (FileHelper.internalCheckParentDirectoryExistanceAndAccess (aFile).isInvalid ())
    return null;

  // Open random access file, as only those files deliver a channel that is
  // readable and writable
  final RandomAccessFile aRAF = FileHelper.getRandomAccessFile (aFile, ERandomAccessFileMode.READ_WRITE);
  if (aRAF == null)
  {
    if (LOGGER.isErrorEnabled ())
      LOGGER.error ("Failed to open random access file " + aFile);
    return null;
  }

  // Try to memory map it
  final OutputStream aOS = _getMappedOutputStream (aRAF.getChannel (), aFile);
  if (aOS != null)
    return aOS;

  // Memory mapping failed - return the original output stream
  StreamHelper.close (aRAF);
  if (LOGGER.isWarnEnabled ())
    LOGGER.warn ("Failed to map file " + aFile + ". Falling though to regular FileOutputStream");
  return FileHelper.getOutputStream (aFile, eAppend);
}
 
Example 16
Source File: KeyStoreHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Load a key store from a resource.
 *
 * @param aKeyStoreType
 *        Type of key store. May not be <code>null</code>.
 * @param sKeyStorePath
 *        The path pointing to the key store. May not be <code>null</code>.
 * @param aKeyStorePassword
 *        The key store password. May be <code>null</code> to indicate that no
 *        password is required.
 * @return The Java key-store object.
 * @see KeyStore#load(InputStream, char[])
 * @throws GeneralSecurityException
 *         In case of a key store error
 * @throws IOException
 *         In case key store loading fails
 * @throws IllegalArgumentException
 *         If the key store path is invalid
 */
@Nonnull
public static KeyStore loadKeyStoreDirect (@Nonnull final IKeyStoreType aKeyStoreType,
                                           @Nonnull final String sKeyStorePath,
                                           @Nullable final char [] aKeyStorePassword) throws GeneralSecurityException,
                                                                                      IOException
{
  ValueEnforcer.notNull (aKeyStoreType, "KeyStoreType");
  ValueEnforcer.notNull (sKeyStorePath, "KeyStorePath");

  // Open the resource stream
  final InputStream aIS = getResourceProvider ().getInputStream (sKeyStorePath);
  if (aIS == null)
    throw new IllegalArgumentException ("Failed to open key store '" + sKeyStorePath + "'");

  try
  {
    final KeyStore aKeyStore = aKeyStoreType.getKeyStore ();
    aKeyStore.load (aIS, aKeyStorePassword);
    return aKeyStore;
  }
  catch (final KeyStoreException ex)
  {
    throw new IllegalStateException ("No provider can handle key stores of type " + aKeyStoreType, ex);
  }
  finally
  {
    StreamHelper.close (aIS);
  }
}
 
Example 17
Source File: ClassPathResourceTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidFolder ()
{
  final ClassPathResource aCPISP = new ClassPathResource ("folder/test2.txt");
  assertTrue (aCPISP.exists ());
  assertNotNull (aCPISP.getReadableCloneForPath ("folder/test3-surely not existing.txt"));
  assertNotNull (aCPISP.getAsFile ());
  assertNotNull (aCPISP.getAsURL ());
  assertEquals ("folder/test2.txt", aCPISP.getPath ());
  assertNotNull (aCPISP.getResourceID ());
  final InputStream aIS1 = aCPISP.getInputStream ();
  assertNotNull (aIS1);
  try
  {
    final InputStream aIS2 = aCPISP.getInputStream ();
    assertNotNull (aIS2);
    try
    {
      assertNotSame (aIS1, aIS2);
    }
    finally
    {
      StreamHelper.close (aIS2);
    }
  }
  finally
  {
    StreamHelper.close (aIS1);
  }
}
 
Example 18
Source File: DOMReader.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
public static Document readXMLDOM (@Nonnull @WillClose final InputStream aIS,
                                   @Nonnull final IDOMReaderSettings aSettings)
{
  ValueEnforcer.notNull (aIS, "InputStream");

  try
  {
    return readXMLDOM (InputSourceFactory.create (aIS), aSettings);
  }
  finally
  {
    StreamHelper.close (aIS);
  }
}
 
Example 19
Source File: BenchmarkTrie.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
private static ICommonsList <String> _readWordList (final IReadableResource aRes,
                                                    final Charset aCharset) throws IOException
{
  final ICommonsList <String> ret = new CommonsArrayList <> ();
  final BufferedReader aBR = new BufferedReader (new InputStreamReader (aRes.getInputStream (), aCharset));
  String sLine;
  while ((sLine = aBR.readLine ()) != null)
  {
    ret.add (sLine);
    if (ret.size () > 999)
      break;
  }
  StreamHelper.close (aBR);
  return ret;
}
 
Example 20
Source File: CSSReaderDeclarationList.java    From ph-css with Apache License 2.0 4 votes vote down vote up
/**
 * Read the CSS from the passed {@link Reader}.
 *
 * @param aReader
 *        The reader to use. Will be closed automatically after reading -
 *        independent of success or error. May not be <code>null</code>.
 * @param aSettings
 *        The settings to be used for reading the CSS. May not be
 *        <code>null</code>.
 * @return <code>null</code> if reading failed, the CSS declarations
 *         otherwise.
 * @since 3.8.2
 */
@Nullable
public static CSSDeclarationList readFromReader (@Nonnull @WillClose final Reader aReader,
                                                 @Nonnull final CSSReaderSettings aSettings)
{
  ValueEnforcer.notNull (aReader, "Reader");
  ValueEnforcer.notNull (aSettings, "Settings");

  final ECSSVersion eVersion = aSettings.getCSSVersion ();
  try
  {
    final CSSCharStream aCharStream = new CSSCharStream (aReader);

    // Use the default CSS parse error handler if none is provided
    ICSSParseErrorHandler aRealParseErrorHandler = aSettings.getCustomErrorHandler ();
    if (aRealParseErrorHandler == null)
      aRealParseErrorHandler = getDefaultParseErrorHandler ();

    // Use the default CSS exception handler if none is provided
    ICSSParseExceptionCallback aRealParseExceptionHandler = aSettings.getCustomExceptionHandler ();
    if (aRealParseExceptionHandler == null)
      aRealParseExceptionHandler = getDefaultParseExceptionHandler ();

    final CSSNode aNode = _readStyleDeclaration (aCharStream,
                                                 eVersion,
                                                 aRealParseErrorHandler,
                                                 aRealParseExceptionHandler);

    // Failed to parse content as CSS?
    if (aNode == null)
      return null;

    // Get the interpret error handler
    ICSSInterpretErrorHandler aRealInterpretErrorHandler = aSettings.getInterpretErrorHandler ();
    if (aRealInterpretErrorHandler == null)
      aRealInterpretErrorHandler = getDefaultInterpretErrorHandler ();

    final boolean bUseSourceLocation = aSettings.isUseSourceLocation ();

    // Convert the AST to a domain object
    return CSSHandler.readDeclarationListFromNode (eVersion, aRealInterpretErrorHandler, bUseSourceLocation, aNode);
  }
  finally
  {
    StreamHelper.close (aReader);
  }
}