Java Code Examples for com.helger.commons.collection.impl.ICommonsSet#add()

The following examples show how to use com.helger.commons.collection.impl.ICommonsSet#add() . 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: IntObjectMapTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
private void _testPutRandom (final float fillFactor)
{
  final Random aRandom = new Random ();
  final int SIZE = 100 * 1000;
  final ICommonsSet <Integer> set = new CommonsHashSet <> (SIZE);
  final int [] vals = new int [SIZE];
  while (set.size () < SIZE)
    set.add (Integer.valueOf (aRandom.nextInt ()));
  int i = 0;
  for (final Integer v : set)
    vals[i++] = v.intValue ();

  final IntObjectMap <String> map = _makeMap (100, fillFactor);
  for (i = 0; i < vals.length; ++i)
  {
    assertNull ("Inserting " + vals[i], map.put (vals[i], _make (vals[i])));
    assertEquals (i + 1, map.size ());
    assertEquals (_make (vals[i]), map.get (vals[i]));
  }
  // now check the final state
  for (i = 0; i < vals.length; ++i)
    assertEquals (_make (vals[i]), map.get (vals[i]));
}
 
Example 2
Source File: IntIntMapTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
private void _testPutRandom (final float fillFactor)
{
  final Random aRandom = new Random ();
  final int SIZE = 100 * 1000;
  final ICommonsSet <Integer> set = new CommonsHashSet <> (SIZE);
  final int [] vals = new int [SIZE];
  while (set.size () < SIZE)
    set.add (Integer.valueOf (aRandom.nextInt ()));
  int i = 0;
  for (final Integer v : set)
    vals[i++] = v.intValue ();

  final IntIntMap map = _makeMap (100, fillFactor);
  for (i = 0; i < vals.length; ++i)
  {
    assertEquals (0, map.put (vals[i], vals[i]));
    assertEquals (i + 1, map.size ());
    assertEquals (vals[i], map.get (vals[i]));
  }
  // now check the final state
  for (i = 0; i < vals.length; ++i)
    assertEquals (vals[i], map.get (vals[i]));
}
 
Example 3
Source File: CombinationGeneratorTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testStringCombination2 ()
{
  final ICommonsList <String> aElements = new CommonsArrayList <> (A, B, B, C);
  final CombinationGenerator <String> x = new CombinationGenerator <> (aElements, 0);
  assertEquals (BigInteger.ONE, x.getTotalCombinations ());
  assertEquals (BigInteger.ONE, x.getCombinationsLeft ());

  final ICommonsList <ICommonsList <String>> aResultsWithDuplicates = new CommonsArrayList <> ();
  final ICommonsSet <ICommonsList <String>> aResultsWithoutDuplicates = new CommonsHashSet <> ();
  while (x.hasNext ())
  {
    final ICommonsList <String> aResult = x.next ();
    aResultsWithDuplicates.add (aResult);
    aResultsWithoutDuplicates.add (aResult);
  }
  assertEquals (1, aResultsWithDuplicates.size ());
  assertEquals (1, aResultsWithoutDuplicates.size ());
}
 
Example 4
Source File: SingleElementMap.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
@ReturnsMutableCopy
@CodingStyleguideUnaware
public Set <Map.Entry <KEYTYPE, VALUETYPE>> entrySet ()
{
  final ICommonsSet <Map.Entry <KEYTYPE, VALUETYPE>> aSet = new CommonsHashSet <> (size ());
  if (m_bHasElement)
    aSet.add (new MapEntry <> (m_aKey, m_aValue));
  return aSet;
}
 
Example 5
Source File: UTF7CharsetProviderSPITest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testIterator ()
{
  final Iterator <Charset> iterator = tested.charsets ();
  final ICommonsSet <Charset> found = new CommonsHashSet<> ();
  while (iterator.hasNext ())
    found.add (iterator.next ());
  assertEquals (3, found.size ());
  final Charset charset1 = tested.charsetForName ("x-IMAP4-modified-UTF7");
  final Charset charset2 = tested.charsetForName ("UTF-7");
  final Charset charset3 = tested.charsetForName ("X-UTF-7-OPTIONAL");
  assertTrue (found.contains (charset1));
  assertTrue (found.contains (charset2));
  assertTrue (found.contains (charset3));
}
 
Example 6
Source File: LocaleCache.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Get all contained locales that consist only of a non-empty language.
 *
 * @return a set with all contained languages, except "all" and "independent"
 */
@Nonnull
@ReturnsMutableCopy
public ICommonsSet <Locale> getAllLanguages ()
{
  final ICommonsSet <Locale> ret = new CommonsHashSet <> ();
  for (final Locale aLocale : getAllLocales ())
  {
    final String sLanguage = aLocale.getLanguage ();
    if (StringHelper.hasText (sLanguage))
      ret.add (getLocale (sLanguage, null, null));
  }
  return ret;
}
 
Example 7
Source File: CombinationGeneratorTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringCombination ()
{
  final ICommonsList <String> aElements = new CommonsArrayList <> (A, B, B, C);
  final CombinationGenerator <String> x = new CombinationGenerator <> (aElements, 3);
  assertEquals (BigInteger.valueOf (4), x.getTotalCombinations ());
  assertEquals (BigInteger.valueOf (4), x.getCombinationsLeft ());

  final ICommonsList <ICommonsList <String>> aResultsWithDuplicates = new CommonsArrayList <> ();
  final ICommonsSet <ICommonsList <String>> aResultsWithoutDuplicates = new CommonsHashSet <> ();
  while (x.hasNext ())
  {
    final ICommonsList <String> aResult = x.next ();
    aResultsWithDuplicates.add (aResult);
    aResultsWithoutDuplicates.add (aResult);
  }
  assertEquals (4, aResultsWithDuplicates.size ());
  assertEquals (3, aResultsWithoutDuplicates.size ());

  try
  {
    x.remove ();
    fail ();
  }
  catch (final UnsupportedOperationException ex)
  {}
}
 
Example 8
Source File: LanguageCacheTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoConcurrentModificationString ()
{
  final ICommonsSet <Locale> aLanguages = new CommonsHashSet <> ();
  for (final String sLanguage : LanguageCache.getInstance ().getAllLanguages ())
    aLanguages.add (LanguageCache.getInstance ().getLanguage (sLanguage));

  for (final Locale aLanguage : aLanguages)
  {
    assertNotNull (aLanguage);
    assertTrue (StringHelper.hasText (aLanguage.getLanguage ()));
    assertTrue (StringHelper.hasNoText (aLanguage.getCountry ()));
    assertTrue (StringHelper.hasNoText (aLanguage.getVariant ()));
  }
}
 
Example 9
Source File: CountryCacheTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoConcurrentModificationString ()
{
  final ICommonsSet <Locale> aCountries = new CommonsHashSet <> ();
  for (final String sCountry : CountryCache.getInstance ().getAllCountries ())
    aCountries.add (CountryCache.getInstance ().getCountry (sCountry));

  for (final Locale aCountry : aCountries)
  {
    assertNotNull (aCountry);
    assertTrue (StringHelper.hasNoText (aCountry.getLanguage ()));
    assertTrue (StringHelper.hasText (aCountry.getCountry ()));
    assertTrue (StringHelper.hasNoText (aCountry.getVariant ()));
  }
}
 
Example 10
Source File: HelpFormatter.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Prints the usage statement for the specified application.
 *
 * @param aPW
 *        The PrintWriter to print the usage statement
 * @param nWidth
 *        The number of characters to display per line
 * @param sAppName
 *        The application name
 * @param aOptions
 *        The command line Options
 */
public void printUsage (@Nonnull final PrintWriter aPW,
                        final int nWidth,
                        final String sAppName,
                        final Options aOptions)
{
  // initialise the string buffer
  final StringBuilder aSB = new StringBuilder (getSyntaxPrefix ()).append (sAppName).append (' ');

  // create a list for processed option groups
  final ICommonsSet <OptionGroup> aProcessedGroups = new CommonsHashSet <> ();

  final ICommonsList <Option> aOptList = aOptions.getAllResolvedOptions ();
  if (m_aOptionComparator != null)
    aOptList.sort (m_aOptionComparator);

  // iterate over the options
  for (final Iterator <Option> aIt = aOptList.iterator (); aIt.hasNext ();)
  {
    // get the next Option
    final Option aOption = aIt.next ();

    // check if the option is part of an OptionGroup
    final OptionGroup group = aOptions.getOptionGroup (aOption);

    // if the option is part of a group
    if (group != null)
    {
      // and if the group has not already been processed
      if (aProcessedGroups.add (group))
      {
        // add the usage clause
        _appendOptionGroup (aSB, group);
      }

      // otherwise the option was displayed in the group
      // previously so ignore it.
    }
    else
    {
      // if the Option is not part of an OptionGroup
      _appendOption (aSB, aOption, aOption.isRequired ());
    }

    if (aIt.hasNext ())
      aSB.append (' ');
  }

  // call printWrapped
  printWrapped (aPW, nWidth, aSB.toString ().indexOf (' ') + 1, aSB.toString ());
}
 
Example 11
Source File: MainCreateJAXBBinding22.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
public static void main (final String [] args)
{
  // UBL 2.2
  {
    System.out.println ("UBL 2.2");
    final IMicroDocument eDoc = _createBaseDoc ();
    final ICommonsSet <String> aNamespaces = new CommonsHashSet <> ();
    for (final String sPart : new String [] { "common", "maindoc" })
    {
      final String sBasePath = BASE_XSD_PATH + sPart;
      for (final File aFile : _getFileList ("src/main" + sBasePath))
      {
        // Each namespace should handled only once
        final IMicroDocument aDoc = MicroReader.readMicroXML (new FileSystemResource (aFile));
        final String sTargetNamespace = _getTargetNamespace (aDoc);
        if (!aNamespaces.add (sTargetNamespace))
        {
          System.out.println ("Ignored namespace URI " + sTargetNamespace + " in " + aFile.getName ());
          continue;
        }
        String sPackageName = _convertToPackage (sTargetNamespace);
        if (sPackageName.endsWith ("_2"))
        {
          // Change "_2" to "_22"
          sPackageName += "2";
        }
        // schemaLocation must be relative to bindings file!
        final IMicroElement eBindings = eDoc.getDocumentElement ()
                                            .appendElement (JAXB_NS_URI, "bindings")
                                            .setAttribute ("schemaLocation",
                                                           ".." + sBasePath + "/" + aFile.getName ())
                                            .setAttribute ("node", "/xsd:schema");
        eBindings.appendElement (JAXB_NS_URI, "schemaBindings")
                 .appendElement (JAXB_NS_URI, "package")
                 .setAttribute ("name", sPackageName);
      }
    }
    MicroWriter.writeToFile (eDoc,
                             new File (DEFAULT_BINDING_FILE),
                             new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING)
                                                     .setNamespaceContext (new MapBasedNamespaceContext ().addMapping (XMLConstants.DEFAULT_NS_PREFIX,
                                                                                                                       JAXB_NS_URI)
                                                                                                          .addMapping ("xsd",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                                                                                          .addMapping ("xsi",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI))
                                                     .setPutNamespaceContextPrefixesInRoot (true));
  }

  System.out.println ("Done");
}
 
Example 12
Source File: MainCreateJAXBBinding21.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
public static void main (final String [] args)
{
  // UBL 2.1
  {
    System.out.println ("UBL 2.1");
    final IMicroDocument eDoc = _createBaseDoc ();
    final ICommonsSet <String> aNamespaces = new CommonsHashSet <> ();
    for (final String sPart : new String [] { "common", "maindoc" })
    {
      final String sBasePath = BASE_XSD_PATH + sPart;
      for (final File aFile : _getFileList ("src/main" + sBasePath))
      {
        // Each namespace should handled only once
        final IMicroDocument aDoc = MicroReader.readMicroXML (new FileSystemResource (aFile));
        final String sTargetNamespace = _getTargetNamespace (aDoc);
        if (!aNamespaces.add (sTargetNamespace))
        {
          System.out.println ("Ignored " + sTargetNamespace + " in " + aFile.getName ());
          continue;
        }
        String sPackageName = _convertToPackage (sTargetNamespace);
        if (sPackageName.endsWith ("_2"))
        {
          // Change "_2" to "_21"
          sPackageName += "1";
        }
        // schemaLocation must be relative to bindings file!
        final IMicroElement eBindings = eDoc.getDocumentElement ()
                                            .appendElement (JAXB_NS_URI, "bindings")
                                            .setAttribute ("schemaLocation",
                                                           ".." + sBasePath + "/" + aFile.getName ())
                                            .setAttribute ("node", "/xsd:schema");
        eBindings.appendElement (JAXB_NS_URI, "schemaBindings")
                 .appendElement (JAXB_NS_URI, "package")
                 .setAttribute ("name", sPackageName);
      }
    }
    MicroWriter.writeToFile (eDoc,
                             new File (DEFAULT_BINDING_FILE),
                             new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING)
                                                     .setNamespaceContext (new MapBasedNamespaceContext ().addMapping (XMLConstants.DEFAULT_NS_PREFIX,
                                                                                                                       JAXB_NS_URI)
                                                                                                          .addMapping ("xsd",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                                                                                          .addMapping ("xsi",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI))
                                                     .setPutNamespaceContextPrefixesInRoot (true));
  }

  System.out.println ("Done");
}
 
Example 13
Source File: MainCreateJAXBBinding20.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
public static void main (final String [] args)
{
  // UBL 2.0
  {
    System.out.println ("UBL 2.0");
    final IMicroDocument eDoc = _createBaseDoc ();
    final ICommonsSet <String> aNamespaces = new CommonsHashSet <> ();
    for (final String sPart : new String [] { "common", "maindoc" })
    {
      final String sBasePath = "/resources/schemas/ubl20/" + sPart;
      for (final File aFile : _getFileList ("src/main" + sBasePath))
      {
        // Each namespace should handled only once
        final IMicroDocument aDoc = MicroReader.readMicroXML (new FileSystemResource (aFile));
        final String sTargetNamespace = _getTargetNamespace (aDoc);
        if (!aNamespaces.add (sTargetNamespace))
        {
          System.out.println ("Ignored " + sTargetNamespace + " in " + aFile.getName ());
          continue;
        }
        final String sPackageName = _convertToPackage (sTargetNamespace);
        // schemaLocation must be relative to bindings file!
        final IMicroElement eBindings = eDoc.getDocumentElement ()
                                            .appendElement (JAXB_NS_URI, "bindings")
                                            .setAttribute ("schemaLocation",
                                                           ".." + sBasePath + "/" + aFile.getName ())
                                            .setAttribute ("node", "/xsd:schema");

        eBindings.appendElement (JAXB_NS_URI, "schemaBindings")
                 .appendElement (JAXB_NS_URI, "package")
                 .setAttribute ("name", sPackageName);

        if (aFile.getName ().equals ("CodeList_UnitCode_UNECE_7_04.xsd") ||
            aFile.getName ().equals ("CodeList_LanguageCode_ISO_7_04.xsd"))
        {
          _generateExplicitEnumMapping (aDoc, aFile.getName (), eBindings);
        }
      }
    }
    MicroWriter.writeToFile (eDoc,
                             new File ("src/main/jaxb/bindings20.xjb"),
                             new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING)
                                                     .setNamespaceContext (new MapBasedNamespaceContext ().addMapping (XMLConstants.DEFAULT_NS_PREFIX,
                                                                                                                       JAXB_NS_URI)
                                                                                                          .addMapping ("xsd",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                                                                                          .addMapping ("xsi",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI))
                                                     .setPutNamespaceContextPrefixesInRoot (true));
  }

  System.out.println ("Done");
}
 
Example 14
Source File: MainCreateJAXBBinding20.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
private static void _generateExplicitEnumMapping (@Nonnull final IMicroDocument aDoc,
                                                  @Nonnull @Nonempty final String sFilename,
                                                  @Nonnull final IMicroElement eBindings)
{
  final ICommonsSet <String> aUsedNames = new CommonsHashSet <> ();
  final ICommonsNavigableMap <String, String> aValueToConstants = new CommonsTreeMap <> ();
  final IMicroElement eSimpleType = aDoc.getDocumentElement ().getFirstChildElement ();

  final IMicroElement eInnerBindings = eBindings.appendElement (JAXB_NS_URI, "bindings")
                                                .setAttribute ("node",
                                                               "xsd:simpleType[@name='" +
                                                                       eSimpleType.getAttributeValue ("name") +
                                                                       "']");
  final IMicroElement eTypesafeEnumClass = eInnerBindings.appendElement (JAXB_NS_URI, "typesafeEnumClass");

  final IMicroElement eRestriction = eSimpleType.getFirstChildElement ();
  for (final IMicroElement eEnumeration : eRestriction.getAllChildElements (XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                                                            "enumeration"))
  {
    final IMicroElement eAnnotation = eEnumeration.getFirstChildElement (XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                                                         "annotation");
    if (eAnnotation == null)
      throw new IllegalStateException ("annotation is missing");
    final IMicroElement eDocumentation = eAnnotation.getFirstChildElement (XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                                                           "documentation");
    if (eDocumentation == null)
      throw new IllegalStateException ("documentation is missing");
    final IMicroElement eCodeName = eDocumentation.getFirstChildElement ("urn:un:unece:uncefact:documentation:2",
                                                                         "CodeName");
    if (eCodeName == null)
      throw new IllegalStateException ("CodeName is missing");

    final String sValue = eEnumeration.getAttributeValue ("value");
    // Create an upper case Java identifier, without duplicate "_"
    String sCodeName = RegExHelper.getAsIdentifier (eCodeName.getTextContent ().trim ().toUpperCase (Locale.US))
                                  .replaceAll ("_+", "_");

    if (!aUsedNames.add (sCodeName))
    {
      // Ensure uniqueness of the enum member name
      int nSuffix = 1;
      while (true)
      {
        final String sSuffixedCodeName = sCodeName + "_" + nSuffix;
        if (aUsedNames.add (sSuffixedCodeName))
        {
          sCodeName = sSuffixedCodeName;
          break;
        }
        ++nSuffix;
      }
    }

    eTypesafeEnumClass.appendElement (JAXB_NS_URI, "typesafeEnumMember")
                      .setAttribute ("value", sValue)
                      .setAttribute ("name", sCodeName);
    aValueToConstants.put (sValue, sCodeName);
  }

  // Write out the mapping file for easy later-on resolving
  XMLMapHandler.writeMap (aValueToConstants,
                          new FileSystemResource ("src/main/resources/schemas/" + sFilename + ".mapping"));
}
 
Example 15
Source File: MainCreateJAXBBinding23.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
public static void main (final String [] args)
{
  // UBL 2.3
  {
    System.out.println ("UBL 2.3");
    final IMicroDocument eDoc = _createBaseDoc ();
    final ICommonsSet <String> aNamespaces = new CommonsHashSet <> ();
    for (final String sPart : new String [] { "common", "maindoc" })
    {
      final String sBasePath = BASE_XSD_PATH + sPart;
      for (final File aFile : _getFileList ("src/main" + sBasePath))
      {
        // Each namespace should handled only once
        final IMicroDocument aDoc = MicroReader.readMicroXML (new FileSystemResource (aFile));
        final String sTargetNamespace = _getTargetNamespace (aDoc);
        if (!aNamespaces.add (sTargetNamespace))
        {
          System.out.println ("Ignored namespace URI " + sTargetNamespace + " in " + aFile.getName ());
          continue;
        }
        String sPackageName = _convertToPackage (sTargetNamespace);
        if (sPackageName.endsWith ("_2"))
        {
          // Change "_2" to "_23"
          sPackageName += "3";
        }
        // schemaLocation must be relative to bindings file!
        final IMicroElement eBindings = eDoc.getDocumentElement ()
                                            .appendElement (JAXB_NS_URI, "bindings")
                                            .setAttribute ("schemaLocation",
                                                           ".." + sBasePath + "/" + aFile.getName ())
                                            .setAttribute ("node", "/xsd:schema");
        eBindings.appendElement (JAXB_NS_URI, "schemaBindings")
                 .appendElement (JAXB_NS_URI, "package")
                 .setAttribute ("name", sPackageName);
      }
    }
    MicroWriter.writeToFile (eDoc,
                             new File (DEFAULT_BINDING_FILE),
                             new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING)
                                                     .setNamespaceContext (new MapBasedNamespaceContext ().addMapping (XMLConstants.DEFAULT_NS_PREFIX,
                                                                                                                       JAXB_NS_URI)
                                                                                                          .addMapping ("xsd",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                                                                                          .addMapping ("xsi",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI))
                                                     .setPutNamespaceContextPrefixesInRoot (true));
  }

  System.out.println ("Done");
}
 
Example 16
Source File: CommonsMock.java    From ph-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Create a {@link ICommonsSet} of mocked objects.
 *
 * @param nCount
 *        Number of objects to be mocked. Must be &ge; 0.
 * @param aClass
 *        The class to be mocked.
 * @param aParams
 *        An optional array of parameters to be passed to the mocking supplier
 *        for each object to be mocked. May be <code>null</code> or empty.
 * @return The set with <code>nCount</code> entries.
 * @param <T>
 *        The type to be mocked
 */
@Nonnull
@ReturnsMutableCopy
public <T> ICommonsSet <T> mockSet (@Nonnegative final int nCount,
                                    @Nonnull final Class <T> aClass,
                                    @Nullable final Object... aParams)
{
  final ICommonsSet <T> ret = new CommonsHashSet <> (nCount);
  for (int i = 0; i < nCount; ++i)
    ret.add (mock (aClass, aParams));
  return ret;
}