com.helger.commons.CGlobal Java Examples

The following examples show how to use com.helger.commons.CGlobal. 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: MathHelperTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetWithoutTrailingZeroes ()
{
  assertNull (MathHelper.getWithoutTrailingZeroes ((String) null));
  assertNull (MathHelper.getWithoutTrailingZeroes ((BigDecimal) null));

  assertEquals (BigDecimal.ZERO, MathHelper.getWithoutTrailingZeroes (BigDecimal.ZERO));
  assertEquals (BigDecimal.ONE, MathHelper.getWithoutTrailingZeroes (BigDecimal.ONE));
  assertEquals (BigDecimal.TEN, MathHelper.getWithoutTrailingZeroes (BigDecimal.TEN));
  assertEquals (BigDecimal.ONE, MathHelper.getWithoutTrailingZeroes ("1.0000"));
  assertEquals (CGlobal.BIGDEC_100, MathHelper.getWithoutTrailingZeroes ("100.000"));
  assertEquals (new BigDecimal ("100.01"), MathHelper.getWithoutTrailingZeroes ("100.0100"));
  assertEquals (new BigDecimal ("600"), MathHelper.getWithoutTrailingZeroes ("6e2"));
  assertEquals (new BigDecimal ("0.1"), MathHelper.getWithoutTrailingZeroes ("0.1000"));
  assertEquals (new BigDecimal ("0.001"), MathHelper.getWithoutTrailingZeroes ("0.001000"));
  assertEquals (BigDecimal.ZERO, MathHelper.getWithoutTrailingZeroes ("0.00000"));
}
 
Example #2
Source File: BitSetHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the long representation of the passed bit set. To avoid loss of
 * data, the bit set may not have more than 64 bits.
 *
 * @param aBS
 *        The bit set to extract the value from. May not be <code>null</code>.
 * @return The extracted value. May be negative if the bit set has 64
 *         elements, the highest order bit is set.
 */
public static long getExtractedLongValue (@Nonnull final BitSet aBS)
{
  ValueEnforcer.notNull (aBS, "BitSet");

  final int nMax = aBS.length ();
  ValueEnforcer.isTrue (nMax <= CGlobal.BITS_PER_LONG,
                        () -> "Can extract only up to " + CGlobal.BITS_PER_LONG + " bits");

  long ret = 0;
  for (int i = nMax - 1; i >= 0; --i)
  {
    ret <<= 1;
    if (aBS.get (i))
      ret += CGlobal.BIT_SET;
  }
  return ret;
}
 
Example #3
Source File: XMLWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the passed DOM node to an XML byte array using the provided XML
 * writer settings.
 *
 * @param aNode
 *        The node to be converted to a byte array. May not be
 *        <code>null</code>.
 * @param aSettings
 *        The XML writer settings to be used. May not be <code>null</code>.
 * @return The byte array representation of the passed node.
 * @since 8.6.3
 */
@Nullable
public static byte [] getNodeAsBytes (@Nonnull final Node aNode, @Nonnull final IXMLWriterSettings aSettings)
{
  ValueEnforcer.notNull (aNode, "Node");
  ValueEnforcer.notNull (aSettings, "Settings");

  try (
      final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream (50 *
                                                                                             CGlobal.BYTES_PER_KILOBYTE))
  {
    // start serializing
    if (writeToStream (aNode, aBAOS, aSettings).isSuccess ())
      return aBAOS.toByteArray ();
  }
  catch (final Exception ex)
  {
    if (LOGGER.isErrorEnabled ())
      LOGGER.error ("Error serializing DOM node with settings " + aSettings.toString (), ex);
  }
  return null;
}
 
Example #4
Source File: BitSetHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the int representation of the passed bit set. To avoid loss of
 * data, the bit set may not have more than 32 bits.
 *
 * @param aBS
 *        The bit set to extract the value from. May not be <code>null</code>.
 * @return The extracted value. May be negative if the bit set has 32
 *         elements, the highest order bit is set.
 */
public static int getExtractedIntValue (@Nonnull final BitSet aBS)
{
  ValueEnforcer.notNull (aBS, "BitSet");

  final int nMax = aBS.length ();
  ValueEnforcer.isTrue (nMax <= CGlobal.BITS_PER_INT,
                        () -> "Can extract only up to " + CGlobal.BITS_PER_INT + " bits");

  int ret = 0;
  for (int i = nMax - 1; i >= 0; --i)
  {
    ret <<= 1;
    if (aBS.get (i))
      ret += CGlobal.BIT_SET;
  }
  return ret;
}
 
Example #5
Source File: WSHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Enable the JAX-WS SOAP debugging. This shows the exchanged SOAP messages in
 * the log file. By default this logging is disabled.
 *
 * @param bServerDebug
 *        <code>true</code> to enable server debugging, <code>false</code> to
 *        disable it.
 * @param bClientDebug
 *        <code>true</code> to enable client debugging, <code>false</code> to
 *        disable it.
 */
public static void enableSoapLogging (final boolean bServerDebug, final boolean bClientDebug)
{
  // Server debug mode
  String sDebug = Boolean.toString (bServerDebug);
  SystemProperties.setPropertyValue ("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", sDebug);
  SystemProperties.setPropertyValue ("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", sDebug);

  // Client debug mode
  sDebug = Boolean.toString (bClientDebug);
  SystemProperties.setPropertyValue ("com.sun.xml.ws.transport.http.HttpTransportPipe.dump", sDebug);
  SystemProperties.setPropertyValue ("com.sun.xml.internal.ws.transport.http.HttpTransportPipe.dump", sDebug);

  // Enlarge dump size
  if (bServerDebug || bClientDebug)
  {
    final String sValue = Integer.toString (2 * CGlobal.BYTES_PER_MEGABYTE);
    SystemProperties.setPropertyValue ("com.sun.xml.ws.transport.http.HttpAdapter.dumpTreshold", sValue);
    SystemProperties.setPropertyValue ("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold", sValue);
  }
  else
  {
    SystemProperties.removePropertyValue ("com.sun.xml.ws.transport.http.HttpAdapter.dumpTreshold");
    SystemProperties.removePropertyValue ("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold");
  }
}
 
Example #6
Source File: JavaBigDecimalFuncTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@SuppressFBWarnings ("RV_RETURN_VALUE_IGNORED")
@Test
public void testDivide ()
{
  final BigDecimal aBD100 = CGlobal.BIGDEC_100;
  final BigDecimal aPerc = new BigDecimal ("20.0");
  final BigDecimal a100AndPerc = aBD100.add (aPerc);
  try
  {
    // 100/120 -> indefinite precision
    aBD100.divide (a100AndPerc);
    fail ();
  }
  catch (final ArithmeticException ex)
  {}

  // With rounding mode it is fine
  assertNotNull (aBD100.divide (a100AndPerc, 2, RoundingMode.HALF_UP));
}
 
Example #7
Source File: FilenameHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Get the path of the passed file name without any eventually contained
 * filename.
 *
 * @param sAbsoluteFilename
 *        The fully qualified file name. May be <code>null</code>.
 * @return The path only including the last trailing path separator character.
 *         Returns <code>null</code> if the passed parameter is
 *         <code>null</code>.
 * @see #getIndexOfLastSeparator(String)
 */
@Nullable
public static String getPath (@Nullable final String sAbsoluteFilename)
{
  /**
   * Note: do not use <code>new File (sFilename).getPath ()</code> since this
   * only invokes the underlying FileSystem implementation which handles path
   * handling only correctly on the native platform. Problem arose when
   * running application on a Linux server and making a file upload from a
   * Windows machine.
   */
  if (sAbsoluteFilename == null)
    return null;
  final int nLastSepIndex = getIndexOfLastSeparator (sAbsoluteFilename);
  return nLastSepIndex == CGlobal.ILLEGAL_UINT ? "" : sAbsoluteFilename.substring (0, nLastSepIndex + 1);
}
 
Example #8
Source File: PSBoundSchemaCache.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
public PSBoundSchemaCache (@Nonnull final String sCacheName)
{
  super (aKey -> {
    ValueEnforcer.notNull (aKey, "Key");

    try
    {
      return aKey.createBoundSchema ();
    }
    catch (final SchematronException ex)
    {
      // Convert to an unchecked exception :(
      throw new IllegalArgumentException (ex);
    }
  }, CGlobal.ILLEGAL_UINT, sCacheName);
}
 
Example #9
Source File: BasicThreadFactory.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the specified thread. This method is called by
 * {@link #newThread(Runnable)} after a new thread has been obtained from the
 * wrapped thread factory. It initializes the thread according to the options
 * set for this factory.
 *
 * @param aThread
 *        the thread to be initialized
 */
@OverrideOnDemand
protected void initializeThread (@Nonnull final Thread aThread)
{
  if (m_sNamingPattern != null)
  {
    final Long aCount = Long.valueOf (m_aThreadCounter.incrementAndGet ());
    aThread.setName (String.format (CGlobal.DEFAULT_LOCALE, m_sNamingPattern, aCount));
  }

  if (m_aUncaughtExceptionHandler != null)
    aThread.setUncaughtExceptionHandler (m_aUncaughtExceptionHandler);

  if (m_aPriority != null)
    aThread.setPriority (m_aPriority.intValue ());

  if (m_eDaemon.isDefined ())
    aThread.setDaemon (m_eDaemon.getAsBooleanValue ());
}
 
Example #10
Source File: AbstractPasswordHashCreatorPBKDF2.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Computes the PBKDF2 hash of a password.
 *
 * @param aPassword
 *        the password to hash.
 * @param aSalt
 *        the salt
 * @param nIterations
 *        the iteration count (slowness factor)
 * @param nBytes
 *        the length of the hash to compute in bytes
 * @return the PBDKF2 hash of the password
 */
@Nonnull
protected static final byte [] pbkdf2 (@Nonnull final char [] aPassword,
                                       @Nonnull final byte [] aSalt,
                                       @Nonnegative final int nIterations,
                                       @Nonnegative final int nBytes)
{
  try
  {
    final PBEKeySpec spec = new PBEKeySpec (aPassword, aSalt, nIterations, nBytes * CGlobal.BITS_PER_BYTE);
    final SecretKeyFactory skf = SecretKeyFactory.getInstance (PBKDF2_ALGORITHM);
    return skf.generateSecret (spec).getEncoded ();
  }
  catch (final GeneralSecurityException ex)
  {
    throw new IllegalStateException ("Failed to apply PBKDF2 algorithm", ex);
  }
}
 
Example #11
Source File: MicroWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the passed micro node to an XML string using the provided settings.
 *
 * @param aNode
 *        The node to be converted to a string. May not be <code>null</code> .
 * @param aSettings
 *        The XML writer settings to use. May not be <code>null</code>.
 * @return The string representation of the passed node.
 */
@Nullable
public static String getNodeAsString (@Nonnull final IMicroNode aNode, @Nonnull final IXMLWriterSettings aSettings)
{
  ValueEnforcer.notNull (aNode, "Node");
  ValueEnforcer.notNull (aSettings, "Settings");

  try (final NonBlockingStringWriter aWriter = new NonBlockingStringWriter (50 * CGlobal.BYTES_PER_KILOBYTE))
  {
    // start serializing
    if (writeToWriter (aNode, aWriter, aSettings).isSuccess ())
      return aWriter.getAsString ();
  }
  catch (final Exception ex)
  {
    if (LOGGER.isErrorEnabled ())
      LOGGER.error ("Error serializing MicroDOM with settings " + aSettings.toString (), ex);
  }
  return null;
}
 
Example #12
Source File: MicroWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the passed micro node to an XML byte array using the provided
 * settings.
 *
 * @param aNode
 *        The node to be converted to a byte array. May not be
 *        <code>null</code> .
 * @param aSettings
 *        The XML writer settings to use. May not be <code>null</code>.
 * @return The byte array representation of the passed node.
 * @since 8.6.3
 */
@Nullable
public static byte [] getNodeAsBytes (@Nonnull final IMicroNode aNode, @Nonnull final IXMLWriterSettings aSettings)
{
  ValueEnforcer.notNull (aNode, "Node");
  ValueEnforcer.notNull (aSettings, "Settings");

  try (
      final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream (50 *
                                                                                           CGlobal.BYTES_PER_KILOBYTE))
  {
    // start serializing
    if (writeToStream (aNode, aBAOS, aSettings).isSuccess ())
      return aBAOS.toByteArray ();
  }
  catch (final Exception ex)
  {
    if (LOGGER.isErrorEnabled ())
      LOGGER.error ("Error serializing MicroDOM with settings " + aSettings.toString (), ex);
  }
  return null;
}
 
Example #13
Source File: SizeHelperTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Test method getAsPB
 */
@Test
public void testGetAsPB ()
{
  // Use fixed locale for constant decimal separator
  final SizeHelper aSH = SizeHelper.getSizeHelperOfLocale (Locale.ENGLISH);

  // default
  assertEquals ("0PB", aSH.getAsPB (0));
  assertEquals ("5PB", aSH.getAsPB (5 * CGlobal.BYTES_PER_PETABYTE));

  // with decimals
  assertEquals ("0.00PB", aSH.getAsPB (0, 2));
  assertEquals ("5PB", aSH.getAsPB (5 * CGlobal.BYTES_PER_PETABYTE, 0));
  assertEquals ("5.0PB", aSH.getAsPB (5 * CGlobal.BYTES_PER_PETABYTE, 1));
  assertEquals ("5.00PB", aSH.getAsPB (5 * CGlobal.BYTES_PER_PETABYTE, 2));
  assertEquals ("5.000PB", aSH.getAsPB (5 * CGlobal.BYTES_PER_PETABYTE, 3));
  assertEquals ("5.0000PB", aSH.getAsPB (5 * CGlobal.BYTES_PER_PETABYTE, 4));
}
 
Example #14
Source File: LocaleHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nullable
public static String getValidCountryCode (@Nullable final String sCode)
{
  // Allow for 2 or 3 letter codes ("AT" and "AUT")
  if (StringHelper.hasText (sCode))
  {
    // Allow for 2 letter codes ("AT")
    if (RegExHelper.stringMatchesPattern ("[a-zA-Z]{2}|[0-9]{3}", sCode))
    {
      return sCode.toUpperCase (CGlobal.LOCALE_FIXED_NUMBER_FORMAT);
    }

    // Allow for 3 letter codes ("AUT")
    if (RegExHelper.stringMatchesPattern ("[a-zA-Z]{3}", sCode))
    {
      final String sAlpha3 = sCode.toUpperCase (CGlobal.LOCALE_FIXED_NUMBER_FORMAT);
      final String sAlpha2 = COUNTRY_ISO3TO2.get (sAlpha3);
      return sAlpha2 != null ? sAlpha2 : sAlpha3;
    }
  }
  return null;
}
 
Example #15
Source File: MicroHelperTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetChildTextContentWithConversionAndNS ()
{
  final String sNSURI = "my-namespace-uri";
  final IMicroElement e = new MicroElement (sNSURI, "x");
  assertNull (MicroHelper.getChildTextContentWithConversion (e, sNSURI, "y", BigInteger.class));
  final IMicroElement y = e.appendElement (sNSURI, "y");
  assertNull (MicroHelper.getChildTextContentWithConversion (e, sNSURI, "y", BigInteger.class));
  y.appendText ("100");
  assertEquals (CGlobal.BIGINT_100, MicroHelper.getChildTextContentWithConversion (e, sNSURI, "y", BigInteger.class));
  y.appendElement ("a");
  assertEquals (CGlobal.BIGINT_100, MicroHelper.getChildTextContentWithConversion (e, sNSURI, "y", BigInteger.class));
  y.appendCDATA ("234");
  assertEquals (BigInteger.valueOf (100234),
                MicroHelper.getChildTextContentWithConversion (e, sNSURI, "y", BigInteger.class));
}
 
Example #16
Source File: CombinationGenerator.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Ctor
 *
 * @param aElements
 *        the elements to fill into the slots for creating all combinations
 *        (must not be empty!)
 * @param nSlotCount
 *        the number of slots to use (must not be greater than the element
 *        count!)
 */
public CombinationGenerator (@Nonnull @Nonempty final ICommonsList <DATATYPE> aElements,
                             @Nonnegative final int nSlotCount)
{
  ValueEnforcer.notEmpty (aElements, "Elements");
  ValueEnforcer.isBetweenInclusive (nSlotCount, "SlotCount", 0, aElements.size ());

  m_aElements = GenericReflection.uncheckedCast (aElements.toArray ());
  m_aIndexResult = new int [nSlotCount];
  final BigInteger aElementFactorial = FactorialHelper.getAnyFactorialLinear (m_aElements.length);
  final BigInteger aSlotFactorial = FactorialHelper.getAnyFactorialLinear (nSlotCount);
  final BigInteger aOverflowFactorial = FactorialHelper.getAnyFactorialLinear (m_aElements.length - nSlotCount);
  m_aTotalCombinations = aElementFactorial.divide (aSlotFactorial.multiply (aOverflowFactorial));
  // Can we use the fallback to long? Is much faster than using BigInteger
  m_bUseLong = m_aTotalCombinations.compareTo (CGlobal.BIGINT_MAX_LONG) < 0;
  m_nTotalCombinations = m_bUseLong ? m_aTotalCombinations.longValue () : CGlobal.ILLEGAL_ULONG;
  reset ();
}
 
Example #17
Source File: StringHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Get the result length (in characters) when replacing all patterns with the
 * replacements on the passed input array.
 *
 * @param aInputString
 *        Input char array. May not be <code>null</code>.
 * @param aSearchChars
 *        The one-character search patterns. May not be <code>null</code>.
 * @param aReplacementStrings
 *        The replacements to be performed. May not be <code>null</code>. The
 *        first dimension of this array must have exactly the same amount of
 *        elements as the patterns parameter array.
 * @return {@link CGlobal#ILLEGAL_UINT} if no replacement was needed, and
 *         therefore the length of the input array could be used.
 */
public static int getReplaceMultipleResultLength (@Nonnull final char [] aInputString,
                                                  @Nonnull @Nonempty final char [] aSearchChars,
                                                  @Nonnull @Nonempty final char [] [] aReplacementStrings)
{
  int nResultLen = 0;
  boolean bAnyReplacement = false;
  for (final char cInput : aInputString)
  {
    // In case no replacement is found use a single char
    int nReplacementLength = 1;
    for (int nIndex = 0; nIndex < aSearchChars.length; nIndex++)
      if (cInput == aSearchChars[nIndex])
      {
        nReplacementLength = aReplacementStrings[nIndex].length;
        bAnyReplacement = true;
        break;
      }
    nResultLen += nReplacementLength;
  }
  return bAnyReplacement ? nResultLen : CGlobal.ILLEGAL_UINT;
}
 
Example #18
Source File: LocaleParserTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseBigDecimal ()
{
  final BigDecimal aBD1M = StringParser.parseBigDecimal ("1000000");
  assertEquals (aBD1M, LocaleParser.parseBigDecimal ("1.000.000", L_DE, CGlobal.BIGDEC_MINUS_ONE));
  assertEquals (aBD1M, LocaleParser.parseBigDecimal ("1,000,000", L_EN, CGlobal.BIGDEC_MINUS_ONE));
  assertEquals (aBD1M, LocaleParser.parseBigDecimal ("1,000,000", (DecimalFormat) NumberFormat.getInstance (L_EN)));
  assertEquals (new BigDecimal ("1234567.8901"),
                LocaleParser.parseBigDecimal ("1.234.567,8901", L_DE, CGlobal.BIGDEC_MINUS_ONE));
  assertEquals (CGlobal.BIGDEC_MINUS_ONE,
                LocaleParser.parseBigDecimal ("... und denken", L_EN, CGlobal.BIGDEC_MINUS_ONE));
  final ChoiceFormat aCF = new ChoiceFormat ("-1#negative|0#zero|1.0#one");
  assertEquals (BigDecimal.valueOf (0.0), LocaleParser.parseBigDecimal ("zero", aCF, CGlobal.BIGDEC_MINUS_ONE));

  try
  {
    LocaleParser.parseBigDecimal ("0", (DecimalFormat) null);
    fail ();
  }
  catch (final NullPointerException ex)
  {}
}
 
Example #19
Source File: EProcessorArchitectureTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testAll ()
{
  for (final EProcessorArchitecture e : EProcessorArchitecture.values ())
  {
    assertSame (e, EProcessorArchitecture.valueOf (e.name ()));
    assertSame (e, EProcessorArchitecture.forBits (e.getBits ()));
  }

  final EProcessorArchitecture eArch = EProcessorArchitecture.getCurrentArchitecture ();
  assertNotNull (eArch);
  assertTrue (eArch.getBits () > 0);
  assertTrue (eArch.getBytes () > 0);

  if (EJVMVendor.getCurrentVendor ().isSun ())
  {
    // For Sun JVMs the architecture must be determined!
    assertNotSame (EProcessorArchitecture.UNKNOWN, eArch);
  }
  assertEquals (CGlobal.ILLEGAL_UINT, EProcessorArchitecture.UNKNOWN.getBytes ());
  assertEquals (CGlobal.ILLEGAL_UINT, EProcessorArchitecture.UNKNOWN.getBits ());
  assertSame (EProcessorArchitecture.UNKNOWN, EProcessorArchitecture.forBits (1));
}
 
Example #20
Source File: StringHelperTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFirstChar ()
{
  assertEquals ('a', StringHelper.getFirstChar ("abc"));
  assertEquals ('a', StringHelper.getFirstChar ("a"));
  assertEquals (CGlobal.ILLEGAL_CHAR, StringHelper.getFirstChar (""));
  assertEquals (CGlobal.ILLEGAL_CHAR, StringHelper.getFirstChar ((CharSequence) null));
  assertEquals (CGlobal.ILLEGAL_CHAR, StringHelper.getFirstChar ((char []) null));
}
 
Example #21
Source File: LocaleParserTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseDouble ()
{
  CommonsAssert.assertEquals (1.1, LocaleParser.parseDouble ("1,1", L_DE, CGlobal.ILLEGAL_DOUBLE));
  CommonsAssert.assertEquals (1.1, LocaleParser.parseDouble ("1.1", L_EN, CGlobal.ILLEGAL_DOUBLE));
  CommonsAssert.assertEquals (CGlobal.ILLEGAL_DOUBLE,
                              LocaleParser.parseDouble ("und wir denken und denken", L_EN, CGlobal.ILLEGAL_DOUBLE));
}
 
Example #22
Source File: SizeHelperTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Test method getAsKB
 */
@SuppressFBWarnings ("TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED")
@Test
public void testGetAsKB ()
{
  // Use fixed locale for constant decimal separator
  final SizeHelper aSH = SizeHelper.getSizeHelperOfLocale (Locale.ENGLISH);

  try
  {
    aSH.getAsKB (5 * CGlobal.BYTES_PER_KILOBYTE, -1);
    fail ();
  }
  catch (final IllegalArgumentException ex)
  {}

  // default
  assertEquals ("0KB", aSH.getAsKB (0));
  assertEquals ("5KB", aSH.getAsKB (5 * CGlobal.BYTES_PER_KILOBYTE));
  assertEquals ("2KB", aSH.getAsKB (2 * CGlobal.BYTES_PER_KILOBYTE));
  assertEquals ("1KB", aSH.getAsKB (2 * CGlobal.BYTES_PER_KILOBYTE - 1));
  assertEquals ("1024KB", aSH.getAsKB (1 * CGlobal.BYTES_PER_MEGABYTE));

  // with decimals
  assertEquals ("0.00KB", aSH.getAsKB (0, 2));
  assertEquals ("5KB", aSH.getAsKB (5 * CGlobal.BYTES_PER_KILOBYTE, 0));
  assertEquals ("5.0KB", aSH.getAsKB (5 * CGlobal.BYTES_PER_KILOBYTE, 1));
  assertEquals ("5.00KB", aSH.getAsKB (5 * CGlobal.BYTES_PER_KILOBYTE, 2));
  assertEquals ("5.000KB", aSH.getAsKB (5 * CGlobal.BYTES_PER_KILOBYTE, 3));
  assertEquals ("5.0000KB", aSH.getAsKB (5 * CGlobal.BYTES_PER_KILOBYTE, 4));
  assertEquals ("2.00KB", aSH.getAsKB (2 * CGlobal.BYTES_PER_KILOBYTE, 2));
  assertEquals ("1.99KB", aSH.getAsKB (2 * CGlobal.BYTES_PER_KILOBYTE - 10, 2));
  assertEquals ("1024.00KB", aSH.getAsKB (1 * CGlobal.BYTES_PER_MEGABYTE, 2));
}
 
Example #23
Source File: MatrixInt.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Print the matrix to the output stream. Line the elements up in columns with
 * a Fortran-like 'Fw.d' style format.
 *
 * @param aPW
 *        Output stream.
 * @param nWidth
 *        Column width.
 * @param nFractionDigits
 *        Number of digits after the decimal.
 */
public void print (@Nonnull final PrintWriter aPW,
                   @Nonnegative final int nWidth,
                   @Nonnegative final int nFractionDigits)
{
  final NumberFormat format = NumberFormat.getInstance (CGlobal.DEFAULT_LOCALE);
  format.setMinimumIntegerDigits (1);
  format.setMaximumFractionDigits (nFractionDigits);
  format.setMinimumFractionDigits (nFractionDigits);
  format.setGroupingUsed (false);
  print (aPW, format, nWidth + 2);
}
 
Example #24
Source File: BitSetHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the passed byte value to an bit set of size 8.
 *
 * @param nValue
 *        The value to be converted to a bit set.
 * @return The non-<code>null</code> bit set.
 */
@Nonnull
public static BitSet createBitSet (final byte nValue)
{
  final BitSet ret = new BitSet (CGlobal.BITS_PER_BYTE);
  for (int i = 0; i < CGlobal.BITS_PER_BYTE; ++i)
    ret.set (i, ((nValue >> i) & 1) == 1);
  return ret;
}
 
Example #25
Source File: MathHelperTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubtractPercent ()
{
  assertEquals (new BigDecimal ("100"), MathHelper.subtractPercent (CGlobal.BIGDEC_100, BigDecimal.ZERO));
  assertEquals (new BigDecimal ("95"), MathHelper.subtractPercent (CGlobal.BIGDEC_100, BigDecimal.valueOf (5)));
  assertEquals (BigDecimal.ZERO, MathHelper.subtractPercent (CGlobal.BIGDEC_100, CGlobal.BIGDEC_100));
  assertEquals (new BigDecimal ("96"), MathHelper.subtractPercent (new BigDecimal ("120"), BigDecimal.valueOf (20)));
}
 
Example #26
Source File: AbstractStatisticsHandlerKeyedNumeric.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@CheckForSigned
public long getMax (@Nullable final String sKey)
{
  return m_aRWLock.readLockedLong ( () -> {
    final Value aValue = m_aMap.get (sKey);
    return aValue == null ? CGlobal.ILLEGAL_ULONG : aValue.getMax ();
  });
}
 
Example #27
Source File: StatisticsHandlerKeyedCounter.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@CheckForSigned
public long getCount (@Nullable final String sKey)
{
  return m_aRWLock.readLockedLong ( () -> {
    final Value aCount = m_aMap.get (sKey);
    return aCount == null ? CGlobal.ILLEGAL_ULONG : aCount.getCount ();
  });
}
 
Example #28
Source File: SizeHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
private static void _checkConvertibility (@Nonnull final BigDecimal aSize)
{
  if (aSize.compareTo (CGlobal.BIGDEC_MAX_LONG) > 0)
    throw new IllegalArgumentException ("The passed BigDecimal is too large to be converted into a long value: " +
                                        aSize.toString ());
  if (aSize.compareTo (CGlobal.BIGDEC_MIN_LONG) < 0)
    throw new IllegalArgumentException ("The passed BigDecimal is too small to be converted into a long value: " +
                                        aSize.toString ());
}
 
Example #29
Source File: ClassHierarchyCacheTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetClassHierarchy ()
{
  // Very basic class
  Collection <Class <?>> aHierarchy = ClassHierarchyCache.getClassHierarchy (Object.class);
  assertEquals (1, aHierarchy.size ());
  assertTrue (aHierarchy.contains (Object.class));

  // More sophisticated static class (no interfaces)
  aHierarchy = ClassHierarchyCache.getClassHierarchy (CGlobal.class);
  // Is usually 2, but with Cobertura enabled, it is 3!
  assertTrue (aHierarchy.size () >= 2);
  assertTrue (aHierarchy.contains (CGlobal.class));
  assertTrue (aHierarchy.contains (Object.class));

  // More sophisticated static class (with interfaces)
  aHierarchy = ClassHierarchyCache.getClassHierarchy (TypedObject.class);
  assertTrue (aHierarchy.size () >= 6);
  assertTrue (aHierarchy.contains (TypedObject.class));
  assertTrue (aHierarchy.contains (IHasObjectType.class));
  assertTrue (aHierarchy.contains (ITypedObject.class));
  assertTrue (aHierarchy.contains (IHasID.class));
  assertTrue (aHierarchy.contains (Object.class));
  assertTrue (aHierarchy.contains (Serializable.class));

  try
  {
    ClassHierarchyCache.getClassHierarchy (null);
    fail ();
  }
  catch (final NullPointerException ex)
  {}
}
 
Example #30
Source File: MathHelperTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddPercent ()
{
  assertEquals (new BigDecimal ("100"), MathHelper.addPercent (CGlobal.BIGDEC_100, BigDecimal.ZERO));
  assertEquals (new BigDecimal ("105"), MathHelper.addPercent (CGlobal.BIGDEC_100, BigDecimal.valueOf (5)));
  assertEquals (new BigDecimal ("200"), MathHelper.addPercent (CGlobal.BIGDEC_100, CGlobal.BIGDEC_100));
}