Java Code Examples for com.helger.commons.collection.impl.ICommonsList#isEmpty()

The following examples show how to use com.helger.commons.collection.impl.ICommonsList#isEmpty() . 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: CombinationGeneratorFlexible.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Iterate all combination, no matter they are unique or not.
 *
 * @param aElements
 *        List of elements.
 * @param aCallback
 *        Callback to invoke
 */
public void iterateAllCombinations (@Nonnull final ICommonsList <DATATYPE> aElements,
                                    @Nonnull final Consumer <? super ICommonsList <DATATYPE>> aCallback)
{
  ValueEnforcer.notNull (aElements, "Elements");
  ValueEnforcer.notNull (aCallback, "Callback");

  for (int nSlotCount = m_bAllowEmpty ? 0 : 1; nSlotCount <= m_nSlotCount; nSlotCount++)
  {
    if (aElements.isEmpty ())
    {
      aCallback.accept (new CommonsArrayList <> ());
    }
    else
    {
      // Add all permutations for the current slot count
      for (final ICommonsList <DATATYPE> aPermutation : new CombinationGenerator <> (aElements, nSlotCount))
        aCallback.accept (aPermutation);
    }
  }
}
 
Example 2
Source File: CommonsTestHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Run something in parallel
 *
 * @param nCalls
 *        The number of invocations of the passed runnable. Must be &ge; 0.
 * @param aRunnable
 *        The runnable to execute. May not be <code>null</code>.
 */
public static void testInParallel (@Nonnegative final int nCalls, @Nonnull final IThrowingRunnable <? extends Exception> aRunnable)
{
  ValueEnforcer.isGE0 (nCalls, "Calls");
  ValueEnforcer.notNull (aRunnable, "Runnable");

  // More than 20s thread would be overkill!
  final ExecutorService aES = Executors.newFixedThreadPool (20);
  final ICommonsList <String> aErrors = new CommonsVector <> ();
  for (int i = 0; i < nCalls; ++i)
  {
    aES.submit ( () -> {
      try
      {
        aRunnable.run ();
      }
      catch (final Exception ex)
      {
        // Remember thread stack
        aErrors.add (ex.getMessage () + "\n" + StackTraceHelper.getStackAsString (ex));
      }
    });
  }
  ExecutorServiceHelper.shutdownAndWaitUntilAllTasksAreFinished (aES);

  // No errors should have occurred
  if (!aErrors.isEmpty ())
    _fail (StringHelper.getImploded (aErrors));
}
 
Example 3
Source File: ServiceLoaderHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Uses the {@link ServiceLoader} to load all SPI implementations of the
 * passed class and return only the first instance.
 *
 * @param <T>
 *        The implementation type to be loaded
 * @param aSPIClass
 *        The SPI interface class. May not be <code>null</code>.
 * @param aClassLoader
 *        The class loader to use for the SPI loader. May not be
 *        <code>null</code>.
 * @param aLogger
 *        An optional logger to use. May be <code>null</code>.
 * @return A collection of all currently available plugins. Never
 *         <code>null</code>.
 */
@Nullable
public static <T> T getFirstSPIImplementation (@Nonnull final Class <T> aSPIClass,
                                               @Nonnull final ClassLoader aClassLoader,
                                               @Nullable final Logger aLogger)
{
  final Logger aRealLogger = aLogger != null ? aLogger : LOGGER;
  final ICommonsList <T> aAll = getAllSPIImplementations (aSPIClass, aClassLoader, aRealLogger);
  if (aAll.isEmpty ())
  {
    // No SPI implementation found
    return null;
  }

  if (aAll.size () > 1)
  {
    // More than one implementation found
    if (aRealLogger.isWarnEnabled ())
      aRealLogger.warn ("Requested only one SPI implementation of " +
                        aSPIClass +
                        " but found " +
                        aAll.size () +
                        " - using the first one. Details: " +
                        aAll);
  }
  return aAll.getFirst ();
}
 
Example 4
Source File: AuthCredentialValidatorManager.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
@SuppressFBWarnings ("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
public static ICredentialValidationResult validateCredentials (@Nonnull final IAuthCredentials aCredentials)
{
  ValueEnforcer.notNull (aCredentials, "Credentials");

  // Collect all strings of all supporting credential validators
  final ICommonsList <ICredentialValidationResult> aFailedValidations = new CommonsArrayList <> ();

  // Check all credential handlers if the can handle the passed credentials
  for (final IAuthCredentialValidatorSPI aHdl : s_aHdlList)
    if (aHdl.supportsCredentials (aCredentials))
    {
      final ICredentialValidationResult aResult = aHdl.validateCredentials (aCredentials);
      if (aResult == null)
        throw new IllegalStateException ("validateCredentials returned a null object from " +
                                         aHdl +
                                         " for credentials " +
                                         aCredentials);
      if (aResult.isSuccess ())
      {
        // This validator successfully validated the passed credentials
        return aResult;
      }
      aFailedValidations.add (aResult);
    }

  if (aFailedValidations.isEmpty ())
    aFailedValidations.add (new CredentialValidationResult ("No credential validator supported the provided credentials: " +
                                                            aCredentials));

  return new CredentialValidationResultList (aFailedValidations);
}
 
Example 5
Source File: MainFindMaskedXMLChars.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
private static String _getFormatted (final ICommonsList <Integer> x)
{
  if (x.isEmpty ())
    return "false";
  final int nRadix = 16;
  if (x.size () == 1)
    return "c == 0x" + Integer.toString (x.get (0).intValue (), nRadix);
  final StringBuilder ret = new StringBuilder ();
  int nIndex = 0;
  int nFirst = -1;
  int nLast = -1;
  do
  {
    final int nValue = x.get (nIndex).intValue ();
    if (nFirst < 0)
    {
      // First item
      nFirst = nLast = nValue;
    }
    else
      if (nValue == nLast + 1)
      {
        nLast = nValue;
      }
      else
      {
        if (ret.length () > 0)
          ret.append (" || ");
        if (nFirst == nLast)
          ret.append ("(c == 0x" + Integer.toString (nFirst, nRadix) + ")");
        else
          ret.append ("(c >= 0x" +
                      Integer.toString (nFirst, nRadix) +
                      " && c <= 0x" +
                      Integer.toString (nLast, nRadix) +
                      ")");
        nFirst = nLast = nValue;
      }
    ++nIndex;
  } while (nIndex < x.size ());
  if (nLast > nFirst)
  {
    if (ret.length () > 0)
      ret.append (" || ");
    ret.append ("(c >= 0x" +
                Integer.toString (nFirst, nRadix) +
                " && c <= 0x" +
                Integer.toString (nLast, nRadix) +
                ")");
  }
  return ret.toString ();
}
 
Example 6
Source File: PathHelper.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nonnull
@ReturnsMutableCopy
private static ICommonsList <Path> _getDirectoryContent (@Nonnull final Path aDirectory,
                                                         @Nullable final Predicate <? super Path> aPathFilter)
{
  final ICommonsList <Path> ret = new CommonsArrayList <> ();
  walkFileTree (aDirectory, 1, new SimpleFileVisitor <Path> ()
  {
    @Override
    public FileVisitResult visitFile (final Path aCurFile, final BasicFileAttributes attrs) throws IOException
    {
      if (aPathFilter == null || aPathFilter.test (aCurFile))
        ret.add (aCurFile);
      return FileVisitResult.CONTINUE;
    }
  });

  if (ret.isEmpty ())
  {
    // No content returned
    if (aPathFilter == null)
    {
      // Try some diagnosis...
      final File aDirectoryFile = aDirectory.toFile ();
      if (!aDirectoryFile.isDirectory ())
      {
        if (LOGGER.isWarnEnabled ())
          LOGGER.warn ("Cannot list non-directory: " + aDirectory.toAbsolutePath ());
      }
      else
        if (!Files.isExecutable (aDirectory))
        {
          // If this happens, the resulting Path objects are neither files nor
          // directories (isFile() and isDirectory() both return false!!)
          if (LOGGER.isWarnEnabled ())
            LOGGER.warn ("Existing directory is missing the listing permission: " + aDirectory.toAbsolutePath ());
        }
        else
          if (!Files.isReadable (aDirectory))
          {
            if (LOGGER.isWarnEnabled ())
              LOGGER.warn ("Cannot list directory because of no read-rights: " + aDirectory.toAbsolutePath ());
          }
          else
            if (!aDirectoryFile.exists ())
            {
              if (LOGGER.isWarnEnabled ())
                LOGGER.warn ("Cannot list non-existing: " + aDirectory.toAbsolutePath ());
            }
    }
  }
  else
  {
    if (!Files.isExecutable (aDirectory))
    {
      // If this happens, the resulting Path objects are neither files nor
      // directories (isFile() and isDirectory() both return false!!)
      if (LOGGER.isWarnEnabled ())
        LOGGER.warn ("Directory is missing the listing permission: " + aDirectory.toAbsolutePath ());
    }
  }
  return ret;
}