下面列出了javax.annotation.concurrent.Immutable#com.helger.commons.string.StringHelper 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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 ();
}
@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;
}
/**
* 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;
}
/**
* 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);
}
@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 ());
}
@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);
}
/**
* 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);
}
/**
* @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;
}
/**
* 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;
}
@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);
}
/**
* 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);
}
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 ());
}
@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"));
}
@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));
}
@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 ()));
}
}
@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 ()));
}
}
@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;
}
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, '@');
}
@MustBeLocked (ELockType.READ)
protected final boolean internalContainsWithID (@Nullable final String sID)
{
if (StringHelper.hasNoText (sID))
return false;
return m_aMap.containsKey (sID);
}
/** 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");
}
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 ());
}
@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;
}
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);
}
}
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;
}
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 ("");
}
/**
* Run something in parallel
*
* @param nCalls
* The number of invocations of the passed runnable. Must be ≥ 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));
}
/**
* 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;
}
@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 ()));
}
}
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));
}
/**
* 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);
}