Java Code Examples for com.helger.commons.string.StringHelper

The following examples show how to use com.helger.commons.string.StringHelper. These examples are extracted from open source projects. 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 Project: ph-commons   Source File: MatrixInt.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Print the matrix to the output stream. Line the elements up in columns. Use
 * the format object, and right justify within columns of width characters.
 * Note that is the matrix is to be read back in, you probably will want to
 * use a NumberFormat that is set to US Locale.
 *
 * @param aPW
 *        the output stream.
 * @param aFormat
 *        A formatting object to format the matrix elements
 * @param nWidth
 *        Column width.
 * @see java.text.DecimalFormat#setDecimalFormatSymbols
 */
public void print (@Nonnull final PrintWriter aPW, @Nonnull final NumberFormat aFormat, @Nonnegative final int nWidth)
{
  aPW.println (); // start on new line.
  for (int nRow = 0; nRow < m_nRows; nRow++)
  {
    for (int nCol = 0; nCol < m_nCols; nCol++)
    {
      // format the number
      final String s = aFormat.format (m_aData[nRow][nCol]);
      // At _least_ 1 space
      final int padding = Math.max (1, nWidth - s.length ());
      aPW.print (StringHelper.getRepeated (' ', padding));
      aPW.print (s);
    }
    aPW.println ();
  }
  // end with blank line.
  aPW.println ();
}
 
Example 2
Source Project: ph-commons   Source File: PDTFromString.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public static LocalDate getLocalDateFromString (@Nullable final String sValue, @Nonnull final DateTimeFormatter aDF)
{
  ValueEnforcer.notNull (aDF, "DateTimeFormatter");

  if (StringHelper.hasText (sValue))
    try
    {
      return aDF.parse (sValue, LocalDate::from);
    }
    catch (final DateTimeParseException ex)
    {
      _onParseException ("LocalDate", sValue, aDF, ex);
    }
  return null;
}
 
Example 3
Source Project: ph-schematron   Source File: SVRLHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert an "unsexy" location string in the for, of
 * <code>*:xx[namespace-uri()='yy']</code> to something more readable like
 * <code>prefix:xx</code> by using the mapping registered in the
 * {@link SVRLLocationBeautifierRegistry}.
 *
 * @param sLocation
 *        The original location string. May not be <code>null</code>.
 * @return The beautified string. Never <code>null</code>. Might be identical
 *         to the original string if the pattern was not found.
 * @since 5.0.1
 */
@Nonnull
public static String getBeautifiedLocation (@Nonnull final String sLocation)
{
  String sResult = sLocation;
  // Handle namespaces:
  // Search for "*:xx[namespace-uri()='yy']" where xx is the localname and yy
  // is the namespace URI
  final Matcher aMatcher = RegExHelper.getMatcher ("\\Q*:\\E([a-zA-Z0-9_]+)\\Q[namespace-uri()='\\E([^']+)\\Q']\\E",
                                                   sResult);
  while (aMatcher.find ())
  {
    final String sLocalName = aMatcher.group (1);
    final String sNamespaceURI = aMatcher.group (2);

    // Check if there is a known beautifier for this pair of namespace and
    // local name
    final String sBeautified = SVRLLocationBeautifierRegistry.getBeautifiedLocation (sNamespaceURI, sLocalName);
    if (sBeautified != null)
      sResult = StringHelper.replaceAll (sResult, aMatcher.group (), sBeautified);
  }
  return sResult;
}
 
Example 4
Source Project: ph-commons   Source File: CSVWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test writing to a list.
 *
 * @throws IOException
 *         if the reader fails.
 */
@Test
public void testWriteAll () throws IOException
{
  final ICommonsList <ICommonsList <String>> allElements = new CommonsArrayList <> ();
  allElements.add (StringHelper.getExploded ('#', "Name#Phone#Email"));
  allElements.add (StringHelper.getExploded ('#', "Glen#1234#[email protected]"));
  allElements.add (StringHelper.getExploded ('#', "John#5678#[email protected]"));

  final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
  try (final CSVWriter aWriter = new CSVWriter (aSW))
  {
    aWriter.writeAll (allElements);
  }

  final String sResult = aSW.getAsString ().trim ();
  final String [] aLines = StringHelper.getExplodedArray ('\n', sResult);

  assertEquals (3, aLines.length);
}
 
Example 5
Source Project: ph-commons   Source File: GraphNodeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCtor ()
{
  final GraphNode n = new GraphNode ();
  assertNotNull (n.getID ());
  assertTrue (StringHelper.hasText (n.getID ()));

  final GraphNode n1 = new GraphNode ("");
  assertNotNull (n1.getID ());
  assertTrue (StringHelper.hasText (n1.getID ()));
  assertFalse (n1.hasRelations ());

  final GraphNode n3 = new GraphNode ("id1");
  assertNotNull (n3.getID ());
  assertEquals ("id1", n3.getID ());
}
 
Example 6
Source Project: ph-commons   Source File: Base64Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeWithBreakLines ()
{
  final byte [] aSource = StringHelper.getRepeated ('a', 100).getBytes (StandardCharsets.ISO_8859_1);
  String sEncoded = Base64.safeEncodeBytes (aSource, Base64.DO_BREAK_LINES);
  assertEquals ("YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh\n" +
                "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==",
                sEncoded);

  // Check that it can be read again
  byte [] aReadBytes = StreamHelper.getAllBytes (new Base64InputStream (new NonBlockingByteArrayInputStream (sEncoded.getBytes (Base64.PREFERRED_ENCODING))));
  assertArrayEquals (aSource, aReadBytes);

  sEncoded = Base64.safeEncodeBytes (aSource, Base64.DO_BREAK_LINES | Base64.DO_NEWLINE_CRLF);
  assertEquals ("YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh\r\n" +
                "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==",
                sEncoded);

  // Check that it can be read again
  aReadBytes = StreamHelper.getAllBytes (new Base64InputStream (new NonBlockingByteArrayInputStream (sEncoded.getBytes (Base64.PREFERRED_ENCODING))));
  assertArrayEquals (aSource, aReadBytes);
}
 
Example 7
Source Project: ph-commons   Source File: LanguageCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Resolve the language from the provided string.<br>
 * Note: this method may be invoked recursively, if the language code contains
 * a locale separator char.
 *
 * @param sLanguage
 *        The language code. May be <code>null</code> or empty.
 * @param aMissingHandler
 *        The missing locale handler to be passed to {@link LocaleCache}. May
 *        be <code>null</code> to use {@link LocaleCache} default handler.
 * @return <code>null</code> if the provided language code is
 *         <code>null</code> or empty.
 * @since 9.4.2
 */
@Nullable
public Locale getLanguageExt (@Nullable final String sLanguage, @Nullable final IMissingLocaleHandler aMissingHandler)
{
  if (StringHelper.hasNoText (sLanguage))
    return null;

  final LocaleCache aLC = LocaleCache.getInstance ();
  final IMissingLocaleHandler aMLH = aMissingHandler != null ? aMissingHandler
                                                             : aLC.getDefaultMissingLocaleHandler ();

  // Was something like "de_" passed in? -> indirect recursion
  if (sLanguage.indexOf (LocaleHelper.LOCALE_SEPARATOR) >= 0)
    return getLanguageExt (aLC.getLocaleExt (sLanguage, aMLH), aMLH);

  final String sValidLanguage = LocaleHelper.getValidLanguageCode (sLanguage);
  if (!containsLanguage (sValidLanguage))
    if (!isSilentMode ())
      if (LOGGER.isWarnEnabled ())
        LOGGER.warn ("Trying to retrieve unsupported language '" + sLanguage + "'");
  return aLC.getLocale (sValidLanguage, "", "", aMLH);
}
 
Example 8
Source Project: ph-commons   Source File: ILocation.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return The display text of the resource location.
 */
@Nonnull
default String getAsString ()
{
  String ret = "";

  final String sResourceID = getResourceID ();
  if (StringHelper.hasText (sResourceID))
    ret += sResourceID;

  if (hasLineNumber ())
  {
    if (hasColumnNumber ())
      ret += "(" + getLineNumber () + ":" + getColumnNumber () + ")";
    else
      ret += "(" + getLineNumber () + ":?)";
  }
  else
  {
    if (hasColumnNumber ())
      ret += "(?:" + getColumnNumber () + ")";
    // else: neither nor
  }
  return ret;
}
 
Example 9
Source Project: ph-commons   Source File: URLHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the passed String as an URI. If the string is empty or not an URI
 * <code>null</code> is returned.
 *
 * @param sURI
 *        Source URI. May be <code>null</code>.
 * @return <code>null</code> if the passed URI is empty or invalid.
 */
@Nullable
public static URI getAsURI (@Nullable final String sURI)
{
  if (StringHelper.hasText (sURI))
    try
    {
      return new URI (sURI);
    }
    catch (final URISyntaxException ex)
    {
      // fall-through
      if (GlobalDebug.isDebugMode ())
        if (LOGGER.isWarnEnabled ())
          LOGGER.warn ("Debug warn: failed to convert '" + sURI + "' to a URI!");
    }
  return null;
}
 
Example 10
Source Project: ph-commons   Source File: CertificateHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public static PrivateKey convertStringToPrivateKey (@Nullable final String sPrivateKey) throws GeneralSecurityException
{
  if (StringHelper.hasNoText (sPrivateKey))
    return null;

  String sRealPrivateKey = StringHelper.trimStart (sPrivateKey, BEGIN_PRIVATE_KEY);
  sRealPrivateKey = StringHelper.trimEnd (sRealPrivateKey, END_PRIVATE_KEY);
  sRealPrivateKey = StringHelper.getWithoutAnySpaces (sRealPrivateKey);
  final byte [] aPrivateKeyBytes = Base64.safeDecode (sRealPrivateKey);
  if (aPrivateKeyBytes == null)
    return null;

  final KeyFactory aKeyFactory = KeyFactory.getInstance ("RSA");
  final PKCS8EncodedKeySpec aKeySpec = new PKCS8EncodedKeySpec (aPrivateKeyBytes);
  return aKeyFactory.generatePrivate (aKeySpec);
}
 
Example 11
Source Project: ph-commons   Source File: CountryCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Resolve the country from the provided string.<br>
 * Note: this method may be invoked recursively, if the country code contains
 * a locale separator char.
 *
 * @param sCountry
 *        The country code. May be <code>null</code> or empty.
 * @param aMissingHandler
 *        The missing locale handler to be passed to {@link LocaleCache}. May
 *        be <code>null</code> to use {@link LocaleCache} default handler.
 * @return <code>null</code> if the provided country code is <code>null</code>
 *         or empty.
 * @since 9.4.2
 */
@Nullable
public Locale getCountryExt (@Nullable final String sCountry, @Nullable final IMissingLocaleHandler aMissingHandler)
{
  if (StringHelper.hasNoText (sCountry))
    return null;

  final LocaleCache aLC = LocaleCache.getInstance ();
  final IMissingLocaleHandler aMLH = aMissingHandler != null ? aMissingHandler
                                                             : aLC.getDefaultMissingLocaleHandler ();

  // Was something like "_AT" (e.g. the result of getCountry (...).toString
  // ()) passed in? -> indirect recursion
  if (sCountry.indexOf (LocaleHelper.LOCALE_SEPARATOR) >= 0)
    return getCountryExt (aLC.getLocaleExt (sCountry, aMLH), aMLH);

  final String sValidCountry = LocaleHelper.getValidCountryCode (sCountry);
  if (!containsCountry (sValidCountry))
    if (!isSilentMode ())
      if (LOGGER.isWarnEnabled ())
        LOGGER.warn ("Trying to retrieve unsupported country '" + sCountry + "'");

  // And use the locale cache
  return aLC.getLocale ("", sValidCountry, "", aMLH);
}
 
Example 12
Source Project: ph-schematron   Source File: PluginErrorListener.java    License: Apache License 2.0 6 votes vote down vote up
public static void logIError (@Nonnull final BuildContext aBuildContext,
                              @Nonnull final File aSourceFile,
                              @Nonnull final IError aResError)
{
  final int nLine = aResError.getErrorLocation ().getLineNumber ();
  final int nColumn = aResError.getErrorLocation ().getColumnNumber ();
  final String sMessage = StringHelper.getImplodedNonEmpty (" - ",
                                                            aResError.getErrorText (Locale.US),
                                                            aResError.getLinkedExceptionMessage ());

  // 0 means undefined line/column
  aBuildContext.addMessage (aSourceFile,
                            nLine <= 0 ? 0 : nLine,
                            nColumn <= 0 ? 0 : nColumn,
                            sMessage,
                            aResError.isError () ? BuildContext.SEVERITY_ERROR : BuildContext.SEVERITY_WARNING,
                            aResError.getLinkedExceptionCause ());
}
 
Example 13
Source Project: ph-commons   Source File: MappedCacheTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPrefilledCache ()
{
  final MappedCache <String, String, String> c = new MappedCache <String, String, String> (x -> x,
                                                                                           StringHelper::getNotNull,
                                                                                           MappedCache.NO_MAX_SIZE,
                                                                                           "Mock",
                                                                                           false)
  {
    {
      putInCache ("a", "b");
    }
  };
  assertEquals (1, c.size ());
  assertTrue (c.isInCache ("a"));
  assertEquals ("b", c.getFromCache ("a"));
  assertEquals (1, c.size ());
  assertFalse (c.isInCache ("b"));
  assertEquals ("b", c.getFromCache ("b"));
  assertEquals (2, c.size ());
  assertTrue (c.isInCache ("b"));
}
 
Example 14
Source Project: ph-schematron   Source File: SVRLMarshallerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteValid () throws Exception
{
  final Document aDoc = SchematronResourceSCH.fromClassPath (VALID_SCHEMATRON)
                                             .applySchematronValidation (new ClassPathResource (VALID_XMLINSTANCE));
  assertNotNull (aDoc);
  final SchematronOutputType aSO = new SVRLMarshaller ().read (aDoc);

  // Create XML
  final Document aDoc2 = new SVRLMarshaller ().getAsDocument (aSO);
  assertNotNull (aDoc2);
  assertEquals (CSVRL.SVRL_NAMESPACE_URI, aDoc2.getDocumentElement ().getNamespaceURI ());

  // Create String
  final String sDoc2 = new SVRLMarshaller ().getAsString (aSO);
  assertTrue (StringHelper.hasText (sDoc2));
  assertTrue (sDoc2.contains (CSVRL.SVRL_NAMESPACE_URI));
}
 
Example 15
Source Project: ph-ubl   Source File: EUBL21DocumentTypeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAll ()
{
  for (final EUBL21DocumentType e : EUBL21DocumentType.values ())
  {
    assertNotNull (e.getImplementationClass ());
    assertTrue (StringHelper.hasText (e.getLocalName ()));
    assertTrue (StringHelper.hasText (e.getNamespaceURI ()));
    assertTrue (e.getAllXSDResources ().size () >= 1);
    for (final IReadableResource aRes : e.getAllXSDResources ())
      assertTrue (e.name (), aRes.exists ());
    assertNotNull (e.getSchema ());
    assertSame (e.getSchema (), e.getSchema ());
    assertSame (e, EUBL21DocumentType.valueOf (e.name ()));
  }
}
 
Example 16
Source Project: ph-ubl   Source File: EUBL22DocumentTypeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAll ()
{
  final ICommonsSet <Class <?>> aClasses = new CommonsHashSet <> ();
  final ICommonsSet <String> aFilenames = new CommonsHashSet <> ();
  for (final EUBL22DocumentType e : EUBL22DocumentType.values ())
  {
    assertNotNull (e.getImplementationClass ());
    assertTrue (StringHelper.hasText (e.getLocalName ()));
    assertTrue (StringHelper.hasText (e.getNamespaceURI ()));
    assertTrue (e.getAllXSDResources ().size () >= 1);
    for (final IReadableResource aRes : e.getAllXSDResources ())
      assertTrue (e.name (), aRes.exists ());
    assertNotNull (e.getSchema ());
    assertSame (e.getSchema (), e.getSchema ());
    assertSame (e, EUBL22DocumentType.valueOf (e.name ()));
    assertTrue (aClasses.add (e.getImplementationClass ()));
    assertTrue (aFilenames.add (e.getAllXSDResources ().getFirst ().getPath ()));
  }
}
 
Example 17
Source Project: ph-schematron   Source File: PSSchema.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public PSPhase getPhaseOfID (@Nullable final String sID)
{
  if (StringHelper.hasText (sID))
    for (final PSPhase aPhase : m_aPhases)
      if (sID.equals (aPhase.getID ()))
        return aPhase;
  return null;
}
 
Example 18
Source Project: ph-commons   Source File: VendorInfo.java    License: Apache License 2.0 5 votes vote down vote up
public static void setVendorEmail (@Nonnull @Nonempty final String sVendorEmail)
{
  ValueEnforcer.notEmpty (sVendorEmail, "VendorEmail");
  ValueEnforcer.isTrue (EmailAddressHelper.isValid (sVendorEmail), () -> "Illegal vendor email: " + sVendorEmail);
  s_sVendorEmail = sVendorEmail;
  s_sVendorEmailSuffix = StringHelper.getFromFirstIncl (sVendorEmail, '@');
}
 
Example 19
Source Project: ph-commons   Source File: AbstractMapBasedWALDAO.java    License: Apache License 2.0 5 votes vote down vote up
@MustBeLocked (ELockType.READ)
protected final boolean internalContainsWithID (@Nullable final String sID)
{
  if (StringHelper.hasNoText (sID))
    return false;

  return m_aMap.containsKey (sID);
}
 
Example 20
Source Project: ph-commons   Source File: MatrixIntTest.java    License: Apache License 2.0 5 votes vote down vote up
/** Print appropriate messages for successful outcome try **/

  private static void _try_success (final String s, final String e)
  {
    _print (">    " + s + "success\n");
    if (StringHelper.hasText (e))
      _print (">      Message: " + e + "\n");
  }
 
Example 21
Source Project: ph-commons   Source File: PDTFormatter.java    License: Apache License 2.0 5 votes vote down vote up
public LocalizedDateFormatCache ()
{
  super (aCacheKey -> {
    String sPattern = getSourcePattern (aCacheKey);

    // Change "year of era" to "year"
    sPattern = StringHelper.replaceAll (sPattern, 'y', 'u');

    if (false)
      if (aCacheKey.m_eMode == EDTFormatterMode.PARSE && StringHelper.getCharCount (sPattern, 'u') == 1)
      {
        // In Java 9, if CLDR mode is active, switch from a single "u" to
        // "uuuu" (for parsing)
        sPattern = StringHelper.replaceAll (sPattern, "u", "uuuu");
      }

    if (aCacheKey.m_eMode == EDTFormatterMode.PARSE &&
        "de".equals (aCacheKey.m_aLocale.getLanguage ()) &&
        aCacheKey.m_eStyle == FormatStyle.MEDIUM)
    {
      // Change from 2 required fields to 1
      sPattern = StringHelper.replaceAll (sPattern, "dd", "d");
      sPattern = StringHelper.replaceAll (sPattern, "MM", "M");
      sPattern = StringHelper.replaceAll (sPattern, "HH", "H");
      sPattern = StringHelper.replaceAll (sPattern, "mm", "m");
      sPattern = StringHelper.replaceAll (sPattern, "ss", "s");
    }

    // And finally create the cached DateTimeFormatter
    // Default to strict - can be changed afterwards
    return DateTimeFormatterCache.getDateTimeFormatterStrict (sPattern);
  }, 1000, LocalizedDateFormatCache.class.getName ());
}
 
Example 22
Source Project: ph-commons   Source File: MimeType.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public MimeTypeParameter getParameterWithName (@Nullable final String sParamName)
{
  if (StringHelper.hasText (sParamName))
    for (final MimeTypeParameter aParam : m_aParameters)
      if (aParam.getAttribute ().equals (sParamName))
        return aParam;
  return null;
}
 
Example 23
Source Project: ph-css   Source File: CSSPropertyEnum.java    License: Apache License 2.0 5 votes vote down vote up
public CSSPropertyEnum (@Nonnull final ECSSProperty eProp,
                        @Nullable final ECSSVendorPrefix eVendorPrefix,
                        @Nullable final ICSSPropertyCustomizer aCustomizer,
                        @Nonnull @Nonempty final String... aEnumValues)
{
  super (eProp, eVendorPrefix, aCustomizer);
  ValueEnforcer.notEmptyNoNullValue (aEnumValues, "EnumValues");
  m_aEnumValues = new CommonsHashSet <> (aEnumValues.length);
  for (final String sPotentialValue : aEnumValues)
  {
    if (StringHelper.hasNoText (sPotentialValue))
      throw new IllegalArgumentException ("At least one enumeration value is empty");
    m_aEnumValues.add (sPotentialValue);
  }
}
 
Example 24
Source Project: ph-schematron   Source File: PSRule.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isValid (@Nonnull final IPSErrorHandler aErrorHandler)
{
  // abstract rules need an ID
  if (m_bAbstract && StringHelper.hasNoText (m_sID))
  {
    aErrorHandler.error (this, "abstract <rule> has no 'id'");
    return false;
  }
  // abstract rules may not have a context
  if (m_bAbstract && StringHelper.hasText (m_sContext))
  {
    aErrorHandler.error (this, "abstract <rule> may not have a 'context'");
    return false;
  }
  // Non-abstract rules need a context
  if (!m_bAbstract && StringHelper.hasNoText (m_sContext))
  {
    aErrorHandler.error (this, "<rule> must have a 'context'");
    return false;
  }
  // At least one assert, report or extends must be present
  if (m_aContent.isEmpty ())
  {
    aErrorHandler.error (this, "<rule> has no content");
    return false;
  }
  for (final Object aContent : m_aContent)
    if (aContent instanceof IPSElement)
      if (!((IPSElement) aContent).isValid (aErrorHandler))
        return false;
  return true;
}
 
Example 25
private static void _boolean (@Nonnull final IMicroElement td, final boolean bSet, @Nullable final String sTitle)
{
  if (bSet)
  {
    td.setAttribute ("class", "center").appendText ("X");
    if (StringHelper.hasText (sTitle))
      td.setAttribute ("title", sTitle);
  }
  else
    td.appendText ("");
}
 
Example 26
Source Project: ph-commons   Source File: CommonsTestHelper.java    License: 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 27
Source Project: ph-commons   Source File: AbstractBaseGraphObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param sID
 *        If <code>null</code> a new ID is generated by the
 *        {@link GraphObjectIDFactory}.
 */
public AbstractBaseGraphObject (@Nullable final String sID)
{
  if (StringHelper.hasNoText (sID))
    m_sID = GraphObjectIDFactory.createNewGraphObjectID ();
  else
    m_sID = sID;
}
 
Example 28
Source Project: ph-commons   Source File: LocaleCacheTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAllLanguages ()
{
  for (final Locale aLocale : LocaleCache.getInstance ().getAllLanguages ())
  {
    assertNotNull (aLocale);
    assertTrue (StringHelper.hasText (aLocale.getLanguage ()));
    assertTrue (StringHelper.hasNoText (aLocale.getCountry ()));
    assertTrue (StringHelper.hasNoText (aLocale.getVariant ()));
  }
}
 
Example 29
Source Project: ph-schematron   Source File: Schematron.java    License: Apache License 2.0 5 votes vote down vote up
void addToMap (@Nonnull final Map <String, String> aMap)
{
  // Only add parameters that have a name
  // If the value is null it becomes ""
  if (StringHelper.hasText (m_sName))
    aMap.put (m_sName, StringHelper.getNotNull (m_sValue));
}
 
Example 30
Source Project: ph-commons   Source File: URLHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Clean an URL part from nasty Umlauts. This mapping needs extension!
 *
 * @param sURLPart
 *        The original URL part. May be <code>null</code>.
 * @return The cleaned version or <code>null</code> if the input was
 *         <code>null</code>.
 */
@Nullable
public static String getCleanURLPartWithoutUmlauts (@Nullable final String sURLPart)
{
  if (s_aCleanURLOld == null)
    _initCleanURL ();
  final char [] ret = StringHelper.replaceMultiple (sURLPart, s_aCleanURLOld, s_aCleanURLNew);
  return new String (ret);
}