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

The following examples show how to use com.helger.commons.collection.impl.ICommonsList#size() . 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: BenchmarkLevenshteinDistance.java    From ph-commons with Apache License 2.0 6 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 NonBlockingBufferedReader aBR = new NonBlockingBufferedReader (new InputStreamReader (aRes.getInputStream (),
                                                                                              aCharset));
  String sLine;
  int nIdx = 0;
  while ((sLine = aBR.readLine ()) != null)
  {
    nIdx++;
    if ((nIdx % 3) == 0)
    {
      ret.add (sLine);
      if (ret.size () >= 100)
        break;
    }
  }
  StreamHelper.close (aBR);
  return ret;
}
 
Example 2
Source File: AuthTokenRegistry.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Remove all tokens of the given subject
 *
 * @param aSubject
 *        The subject for which the tokens should be removed.
 * @return The number of removed tokens. Always &ge; 0.
 */
@Nonnegative
public static int removeAllTokensOfSubject (@Nonnull final IAuthSubject aSubject)
{
  ValueEnforcer.notNull (aSubject, "Subject");

  // get all token IDs matching a given subject
  // Note: required IAuthSubject to implement equals!
  final ICommonsList <String> aDelTokenIDs = new CommonsArrayList <> ();
  s_aRWLock.readLocked ( () -> {
    for (final Map.Entry <String, AuthToken> aEntry : s_aMap.entrySet ())
      if (aEntry.getValue ().getIdentification ().hasAuthSubject (aSubject))
        aDelTokenIDs.add (aEntry.getKey ());
  });

  for (final String sDelTokenID : aDelTokenIDs)
    removeToken (sDelTokenID);

  return aDelTokenIDs.size ();
}
 
Example 3
Source File: XMLEmitter.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * CDATA node.
 *
 * @param sText
 *        The contained text
 */
public void onCDATA (@Nullable final String sText)
{
  if (StringHelper.hasText (sText))
  {
    if (sText.indexOf (CDATA_END) >= 0)
    {
      // Split CDATA sections if they contain the illegal "]]>" marker
      final ICommonsList <String> aParts = StringHelper.getExploded (CDATA_END, sText);
      final int nParts = aParts.size ();
      for (int i = 0; i < nParts; ++i)
      {
        _append (CDATA_START);
        if (i > 0)
          _append ('>');
        _appendMasked (EXMLCharMode.CDATA, aParts.get (i));
        if (i < nParts - 1)
          _append ("]]");
        _append (CDATA_END);
      }
    }
    else
    {
      // No special handling required
      _append (CDATA_START)._appendMasked (EXMLCharMode.CDATA, sText)._append (CDATA_END);
    }
  }
}
 
Example 4
Source File: SchemaCache.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static Schema createSchema (@Nonnull final SchemaFactory aSchemaFactory,
                                   @Nonnull final String sSchemaTypeName,
                                   @Nonnull @Nonempty final ICommonsList <? extends IReadableResource> aResources)
{
  ValueEnforcer.notNull (aSchemaFactory, "SchemaFactory");
  ValueEnforcer.notEmptyNoNullValue (aResources, "Resources");

  // Collect all sources
  final Source [] aSources = new Source [aResources.size ()];
  for (int i = 0; i < aResources.size (); ++i)
    aSources[i] = TransformSourceFactory.create (aResources.get (i));

  try
  {
    final Schema ret = aSchemaFactory.newSchema (aSources);
    if (ret == null)
      throw new IllegalStateException ("Failed to create " +
                                       sSchemaTypeName +
                                       " schema from " +
                                       aResources.toString ());
    return ret;
  }
  catch (final SAXException ex)
  {
    throw new IllegalArgumentException ("Failed to parse " + sSchemaTypeName + " from " + aResources.toString (), ex);
  }
}
 
Example 5
Source File: URLHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
@ReturnsMutableCopy
public static URLParameterList getParsedQueryParameters (@Nullable final String sQueryString,
                                                         @Nullable final IDecoder <String, String> aParameterDecoder)
{
  final URLParameterList aMap = new URLParameterList ();
  if (StringHelper.hasText (sQueryString))
  {
    for (final String sKeyValuePair : StringHelper.getExploded (AMPERSAND, sQueryString))
      if (sKeyValuePair.length () > 0)
      {
        final ICommonsList <String> aParts = StringHelper.getExploded (EQUALS, sKeyValuePair, 2);
        final String sKey = aParts.get (0);
        // Maybe empty when passing something like "url?=value"
        if (StringHelper.hasText (sKey))
        {
          final String sValue = aParts.size () == 2 ? aParts.get (1) : "";
          if (sValue == null)
            throw new IllegalArgumentException ("parameter value may not be null");
          if (aParameterDecoder != null)
          {
            // Now decode the name and the value
            aMap.add (aParameterDecoder.getDecoded (sKey), aParameterDecoder.getDecoded (sValue));
          }
          else
            aMap.add (sKey, sValue);
        }
      }
  }
  return aMap;
}
 
Example 6
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 7
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 8
Source File: IntegrationFuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Test the full cycle of write-read
 *
 * @throws IOException
 *         never
 */
@Test
public void testWriteRead () throws IOException
{
  final String [] [] data = new String [] [] { { "hello, a test", "one nested \" test" },
                                               { "\"\"", "test", null, "8" } };
  final Charset aCharset = StandardCharsets.UTF_8;

  try (final CSVWriter writer = new CSVWriter (new OutputStreamWriter (new FileOutputStream (m_aTempFile), aCharset)))
  {
    for (final String [] aData : data)
      writer.writeNext (aData);
  }

  try (final CSVReader reader = new CSVReader (new InputStreamReader (new FileInputStream (m_aTempFile), aCharset)))
  {
    int row = 0;
    while (true)
    {
      final ICommonsList <String> line = reader.readNext ();
      if (line == null)
        break;

      assertEquals (line.size (), data[row].length);

      for (int col = 0; col < line.size (); col++)
      {
        if (data[row][col] == null)
          assertEquals ("", line.get (col));
        else
          assertEquals (data[row][col], line.get (col));
      }
      row++;
    }
  }
}
 
Example 9
Source File: PDTDisplayHelper.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Nonempty
public static String getPeriodText (final int nYears,
                                    final int nMonths,
                                    final int nDays,
                                    final long nHours,
                                    final long nMinutes,
                                    final long nSeconds,
                                    @Nonnull final IPeriodTextProvider aTextProvider)
{
  final String sYear = aTextProvider.getYears (nYears);
  final String sMonth = aTextProvider.getMonths (nMonths);
  final String sDay = aTextProvider.getDays (nDays);
  final String sHour = aTextProvider.getHours (nHours);
  final String sMinute = aTextProvider.getMinutes (nMinutes);
  final String sSecond = aTextProvider.getSeconds (nSeconds);

  // Skip all "leading 0" parts
  final ICommonsList <String> aParts = new CommonsArrayList <> (6);
  if (nYears != 0)
    aParts.add (sYear);
  if (nMonths != 0 || aParts.isNotEmpty ())
    aParts.add (sMonth);
  if (nDays != 0 || aParts.isNotEmpty ())
    aParts.add (sDay);
  if (nHours != 0 || aParts.isNotEmpty ())
    aParts.add (sHour);
  if (nMinutes != 0 || aParts.isNotEmpty ())
    aParts.add (sMinute);
  aParts.add (sSecond);

  final int nParts = aParts.size ();
  if (nParts == 1)
    return aParts.get (0);
  if (nParts == 2)
    return aParts.get (0) + aTextProvider.getAnd () + aParts.get (1);

  final StringBuilder aSB = new StringBuilder ();
  for (int i = 0; i < nParts - 1; ++i)
  {
    if (aSB.length () > 0)
      aSB.append (aTextProvider.getComma ());
    aSB.append (aParts.get (i));
  }
  return aSB.append (aTextProvider.getAnd ()).append (aParts.getLast ()).toString ();
}
 
Example 10
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 11
Source File: ConcurrentCollectorMultiple.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * This method starts the collector by taking objects from the internal
 * {@link BlockingQueue}. So this method blocks and must be invoked from a
 * separate thread. This method runs until {@link #stopQueuingNewObjects()} is
 * new called and the queue is empty.
 *
 * @throws IllegalStateException
 *         if no performer is set - see
 *         {@link #setPerformer(IConcurrentPerformer)}
 */
public final void collect ()
{
  if (m_aPerformer == null)
    throw new IllegalStateException ("No performer set!");

  try
  {
    // The temporary list that contains all objects to be delivered
    final ICommonsList <DATATYPE> aObjectsToPerform = new CommonsArrayList <> ();
    boolean bQueueIsStopped = false;

    while (true)
    {
      // Block until the first object is in the queue
      Object aCurrentObject = m_aQueue.take ();
      if (EqualsHelper.identityEqual (aCurrentObject, STOP_QUEUE_OBJECT))
        break;

      // add current object
      aObjectsToPerform.add (GenericReflection.uncheckedCast (aCurrentObject));

      // take all messages that are in the queue and handle them at once.
      // Handle at last m_nMaxPerformSize objects
      while (aObjectsToPerform.size () < m_nMaxPerformCount && !m_aQueue.isEmpty ())
      {
        // Explicitly handle the "stop queue message" (using "=="!!!)
        aCurrentObject = m_aQueue.take ();
        if (EqualsHelper.identityEqual (aCurrentObject, STOP_QUEUE_OBJECT))
        {
          bQueueIsStopped = true;
          break;
        }

        // add current object
        aObjectsToPerform.add (GenericReflection.uncheckedCast (aCurrentObject));
      }

      _perform (aObjectsToPerform);

      // In case we received a stop message while getting the bulk messages
      // above -> break the loop manually
      // Note: do not include in while-loop above because the conditions may
      // not execute in the correct order since "take" is blocking!
      if (bQueueIsStopped)
        break;
    }

    // perform any remaining actions
    _perform (aObjectsToPerform);
  }
  catch (final Exception ex)
  {
    LOGGER.error ("Error taking elements from queue - queue has been interrupted!!!", ex);
  }
}