com.helger.commons.string.StringHelper Java Examples

The following examples show how to use com.helger.commons.string.StringHelper. 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: SVRLHelper.java    From ph-schematron with 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 #2
Source File: EUBL22DocumentTypeTest.java    From ph-ubl with 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 #3
Source File: PDTFromString.java    From ph-commons with 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 #4
Source File: EUBL21DocumentTypeTest.java    From ph-ubl with 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 #5
Source File: MatrixInt.java    From ph-commons with 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 #6
Source File: SVRLMarshallerTest.java    From ph-schematron with 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 #7
Source File: CSVWriterTest.java    From ph-commons with 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 #8
Source File: MappedCacheTest.java    From ph-commons with 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 #9
Source File: PluginErrorListener.java    From ph-schematron with 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 #10
Source File: GraphNodeTest.java    From ph-commons with 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 #11
Source File: CountryCache.java    From ph-commons with 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 File: CertificateHelper.java    From ph-commons with 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 #13
Source File: Base64Test.java    From ph-commons with 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 #14
Source File: URLHelper.java    From ph-commons with 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 #15
Source File: ILocation.java    From ph-commons with 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 #16
Source File: LanguageCache.java    From ph-commons with 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 #17
Source File: MicroDataAware.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public MicroDataAware (@Nullable final CharSequence aText)
{
  if (StringHelper.hasNoText (aText))
    m_aSB = new StringBuilder ();
  else
    m_aSB = new StringBuilder (aText);
}
 
Example #18
Source File: PSSpan.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
public boolean isValid (@Nonnull final IPSErrorHandler aErrorHandler)
{
  if (StringHelper.hasNoText (m_sClass))
  {
    aErrorHandler.error (this, "<span> has no 'class'");
    return false;
  }
  if (m_aContent.isEmpty ())
  {
    aErrorHandler.error (this, "<span> has no content");
    return false;
  }
  return true;
}
 
Example #19
Source File: CSSParseHelper.java    From ph-css with Apache License 2.0 5 votes vote down vote up
/**
 * Remove surrounding quotes (single or double) of a string (if present). If
 * the start and the end quote are not equal, nothing happens.
 *
 * @param sStr
 *        The string where the quotes should be removed
 * @return The string without quotes.
 */
@Nullable
public static String extractStringValue (@Nullable final String sStr)
{
  if (StringHelper.hasNoText (sStr) || sStr.length () < 2)
    return sStr;

  final char cFirst = sStr.charAt (0);
  if ((cFirst == '"' || cFirst == '\'') && StringHelper.getLastChar (sStr) == cFirst)
  {
    // Remove quotes around the string
    return _trimBy (sStr, 1, 1);
  }
  return sStr;
}
 
Example #20
Source File: PSParam.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
public boolean isValid (@Nonnull final IPSErrorHandler aErrorHandler)
{
  if (StringHelper.hasNoText (m_sName))
  {
    aErrorHandler.error (this, "<param> has no 'name'");
    return false;
  }
  if (StringHelper.hasNoText (m_sValue))
  {
    aErrorHandler.error (this, "<param> has no 'value'");
    return false;
  }
  return true;
}
 
Example #21
Source File: PSActive.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
public void validateCompletely (@Nonnull final IPSErrorHandler aErrorHandler)
{
  for (final Object aContent : m_aContent)
    if (aContent instanceof IPSElement)
      ((IPSElement) aContent).validateCompletely (aErrorHandler);
  if (StringHelper.hasNoText (m_sPattern))
    aErrorHandler.error (this, "<active> has no 'pattern'");
}
 
Example #22
Source File: ECSSColorNameTest.java    From ph-css with Apache License 2.0 5 votes vote down vote up
@Test
public void testAll ()
{
  for (final ECSSColorName eColor : ECSSColorName.values ())
  {
    assertTrue (StringHelper.hasText (eColor.getName ()));
    assertTrue (CSSColorHelper.isColorValue (eColor.getName ()));

    assertSame (eColor, ECSSColorName.getFromNameCaseInsensitiveOrNull (eColor.getName ()));
    assertTrue (ECSSColorName.isDefaultColorName (eColor.getName ()));
  }
}
 
Example #23
Source File: LevenshteinDistance.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Get the distance of the 2 strings, using the costs 1 for insertion,
 * deletion and substitution.
 *
 * @param sStr1
 *        First string.
 * @param sStr2
 *        second string.
 * @return The Levenshtein distance.
 */
public static int getDistance (@Nullable final String sStr1, @Nullable final String sStr2)
{
  final int nLen1 = StringHelper.getLength (sStr1);
  final int nLen2 = StringHelper.getLength (sStr2);

  if (nLen1 == 0)
    return nLen2;
  if (nLen2 == 0)
    return nLen1;

  return _getDistance111 (sStr1.toCharArray (), nLen1, sStr2.toCharArray (), nLen2);
}
 
Example #24
Source File: PSSchema.java    From ph-schematron with 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 #25
Source File: AuthTokenRegistry.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
private static AuthToken _getValidNotExpiredToken (@Nullable final String sTokenID)
{
  if (StringHelper.hasNoText (sTokenID))
    return null;

  final AuthToken aToken = s_aRWLock.readLockedGet ( () -> s_aMap.get (sTokenID));
  return aToken != null && !aToken.isExpired () ? aToken : null;
}
 
Example #26
Source File: PSValueOf.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
public boolean isValid (@Nonnull final IPSErrorHandler aErrorHandler)
{
  if (StringHelper.hasNoText (m_sSelect))
  {
    aErrorHandler.error (this, "<value-of> has no 'select'");
    return false;
  }
  return true;
}
 
Example #27
Source File: FormatterStringSkipPrefixAndSuffix.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Override
public String apply (@Nullable final Object aValue)
{
  String sValue = getValueAsString (aValue);
  // strip prefix and suffix
  if (m_sPrefix.length () > 0)
    sValue = StringHelper.trimStart (sValue, m_sPrefix);
  if (m_sSuffix.length () > 0)
    sValue = StringHelper.trimEnd (sValue, m_sSuffix);
  return sValue;
}
 
Example #28
Source File: AbstractXMLSerializer.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public void addPrefixNamespaceMapping (@Nullable final String sPrefix, @Nonnull final String sNamespaceURI)
{
  if (LOGGER.isTraceEnabled ())
    LOGGER.trace ("Adding namespace mapping " + sPrefix + ":" + sNamespaceURI);

  // namespace prefix uniqueness check
  final String sExistingNamespaceURI = getNamespaceURIOfPrefix (sPrefix);
  if (sExistingNamespaceURI != null && !sExistingNamespaceURI.equals (sNamespaceURI))
    if (LOGGER.isWarnEnabled ())
      LOGGER.warn ("Overwriting namespace prefix '" +
                   sPrefix +
                   "' to use URL '" +
                   sNamespaceURI +
                   "' instead of '" +
                   sExistingNamespaceURI +
                   "'");

  if (StringHelper.hasNoText (sPrefix))
  {
    if (m_sDefaultNamespaceURI != null)
      if (LOGGER.isWarnEnabled ())
        LOGGER.warn ("Overwriting default namespace '" +
                     m_sDefaultNamespaceURI +
                     "' with namespace '" +
                     sNamespaceURI +
                     "'");
    m_sDefaultNamespaceURI = sNamespaceURI;
  }
  else
  {
    if (m_aURL2PrefixMap == null)
      m_aURL2PrefixMap = new CommonsHashMap <> ();
    m_aURL2PrefixMap.put (sNamespaceURI, sPrefix);
  }
}
 
Example #29
Source File: JsonEscapeHelperTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testArbitrary ()
{
  final Random aRandom = new Random ();
  for (int i = 0; i < 100; ++i)
  {
    // Build a random test string
    final int nStringLength = 123;
    final StringBuilder aTestString = new StringBuilder (nStringLength);
    for (int j = 0; j < nStringLength; ++j)
      aTestString.append ((char) aRandom.nextInt (Character.MAX_VALUE));
    final String sTestString = aTestString.toString ();

    // Escape
    final String sEscaped = JsonEscapeHelper.jsonEscape (sTestString);
    // Try to parse escaped string
    assertNotNull (StringHelper.getHexEncoded (sEscaped, StandardCharsets.UTF_8),
                   JsonReader.builder ().setSource ("\"" + sEscaped + "\"").read ());
    // Unescape
    final String sUnescaped = JsonEscapeHelper.jsonUnescape (sEscaped);
    // Must be identical to source string
    assertEquals (StringHelper.getHexEncoded (sTestString, StandardCharsets.UTF_8) +
                  "\nvs.\n" +
                  StringHelper.getHexEncoded (sEscaped, StandardCharsets.UTF_8),
                  sTestString,
                  sUnescaped);
  }
}
 
Example #30
Source File: FilenameHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the passed filename into a valid filename by performing the
 * following actions:
 * <ol>
 * <li>Remove everything after a potential \0 character</li>
 * <li>Remove all characters that are invalid at the end of a file name</li>
 * <li>Replace all characters that are invalid inside a filename with a
 * underscore</li>
 * <li>If the filename is invalid on Windows platforms it is prefixed with an
 * underscore.</li>
 * </ol>
 * Note: this method does not handle Windows full path like
 * "c:\autoexec.bat"<br>
 *
 * @param sFilename
 *        The filename to be made value. May be <code>null</code>.
 * @return <code>null</code> if the input filename was <code>null</code> or if
 *         it consisted only of characters invalid for a filename; the
 *         potentially modified filename otherwise but <b>never</b> an empy
 *         string.
 * @see #getSecureFilename(String)
 */
@Nullable
@Nonempty
public static String getAsSecureValidFilename (@Nullable final String sFilename)
{
  // First secure it, by cutting everything behind the '\0'
  String ret = getSecureFilename (sFilename);

  // empty not allowed
  if (StringHelper.hasText (ret))
  {
    // Remove all trailing invalid suffixes
    while (ret.length () > 0 && StringHelper.endsWithAny (ret, ILLEGAL_SUFFIXES))
      ret = ret.substring (0, ret.length () - 1);

    // Replace all characters that are illegal inside a filename
    for (final char cIllegal : ILLEGAL_CHARACTERS)
      ret = StringHelper.replaceAll (ret, cIllegal, ILLEGAL_FILENAME_CHAR_REPLACEMENT);

    // Check if a file matches an illegal prefix
    final String sTempRet = ret;
    if (ArrayHelper.containsAny (ILLEGAL_PREFIXES, sTempRet::equalsIgnoreCase))
      ret = ILLEGAL_FILENAME_CHAR_REPLACEMENT + ret;

    // check if filename is prefixed with an illegal prefix
    // Note: we can use the default locale, since all fixed names are pure
    // ANSI names
    final String sUCFilename = ret.toUpperCase (SystemHelper.getSystemLocale ());
    if (ArrayHelper.containsAny (ILLEGAL_PREFIXES, x -> sUCFilename.startsWith (x + ".")))
      ret = ILLEGAL_FILENAME_CHAR_REPLACEMENT + ret;
  }

  // Avoid returning an empty string as valid file name
  return StringHelper.hasNoText (ret) ? null : ret;
}