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 Project: ph-commons   Author: phax   File: WSHelper.java    License: 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 #2
Source Project: ph-commons   Author: phax   File: FilenameHelper.java    License: 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 #3
Source Project: ph-commons   Author: phax   File: XMLWriter.java    License: 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 Project: ph-commons   Author: phax   File: AbstractPasswordHashCreatorPBKDF2.java    License: 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 #5
Source Project: ph-commons   Author: phax   File: MicroWriter.java    License: 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 #6
Source Project: ph-commons   Author: phax   File: MicroWriter.java    License: 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 #7
Source Project: ph-commons   Author: phax   File: SizeHelperTest.java    License: 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 #8
Source Project: ph-commons   Author: phax   File: MicroHelperTest.java    License: 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 #9
Source Project: ph-commons   Author: phax   File: CombinationGenerator.java    License: 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 #10
Source Project: ph-commons   Author: phax   File: EProcessorArchitectureTest.java    License: 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 #11
Source Project: ph-commons   Author: phax   File: LocaleParserTest.java    License: 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 #12
Source Project: ph-commons   Author: phax   File: StringHelper.java    License: 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 #13
Source Project: ph-commons   Author: phax   File: LocaleHelper.java    License: 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 #14
Source Project: ph-commons   Author: phax   File: BasicThreadFactory.java    License: 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 #15
Source Project: ph-schematron   Author: phax   File: PSBoundSchemaCache.java    License: 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 #16
Source Project: ph-commons   Author: phax   File: JavaBigDecimalFuncTest.java    License: 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 #17
Source Project: ph-commons   Author: phax   File: BitSetHelper.java    License: 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 #18
Source Project: ph-commons   Author: phax   File: BitSetHelper.java    License: 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 #19
Source Project: ph-commons   Author: phax   File: MathHelperTest.java    License: 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 #20
Source Project: ph-commons   Author: phax   File: Matrix.java    License: 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 #21
Source Project: ph-commons   Author: phax   File: MatrixInt.java    License: 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 #22
Source Project: ph-commons   Author: phax   File: PDTDisplayHelper.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Nonempty
public static String getPeriodText (@Nonnull final LocalDateTime aNowLDT,
                                    @Nonnull final LocalDateTime aNotAfter,
                                    @Nonnull final IPeriodTextProvider aTextProvider)
{
  final Period aPeriod = Period.between (aNowLDT.toLocalDate (), aNotAfter.toLocalDate ());
  final Duration aDuration = Duration.between (aNowLDT.toLocalTime (), aNotAfter.toLocalTime ());

  final int nYears = aPeriod.getYears ();
  final int nMonth = aPeriod.getMonths ();
  int nDays = aPeriod.getDays ();

  long nTotalSecs = aDuration.getSeconds ();
  if (nTotalSecs < 0)
  {
    if (nDays > 0 || nMonth > 0 || nYears > 0)
    {
      nTotalSecs += CGlobal.SECONDS_PER_DAY;
      nDays--;
    }
  }

  final long nHours = nTotalSecs / CGlobal.SECONDS_PER_HOUR;
  nTotalSecs -= nHours * CGlobal.SECONDS_PER_HOUR;
  final long nMinutes = nTotalSecs / CGlobal.SECONDS_PER_MINUTE;
  nTotalSecs -= nMinutes * CGlobal.SECONDS_PER_MINUTE;

  return getPeriodText (nYears, nMonth, nDays, nHours, nMinutes, nTotalSecs, aTextProvider);
}
 
Example #23
Source Project: ph-commons   Author: phax   File: MicroHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetChildTextContentWithConversion ()
{
  final IMicroElement e = new MicroElement ("x");
  assertNull (MicroHelper.getChildTextContentWithConversion (e, "y", BigInteger.class));
  final IMicroElement y = e.appendElement ("y");
  assertNull (MicroHelper.getChildTextContentWithConversion (e, "y", BigInteger.class));
  y.appendText ("100");
  assertEquals (CGlobal.BIGINT_100, MicroHelper.getChildTextContentWithConversion (e, "y", BigInteger.class));
  y.appendElement ("a");
  assertEquals (CGlobal.BIGINT_100, MicroHelper.getChildTextContentWithConversion (e, "y", BigInteger.class));
  y.appendCDATA ("234");
  assertEquals (BigInteger.valueOf (100234),
                MicroHelper.getChildTextContentWithConversion (e, "y", BigInteger.class));
}
 
Example #24
Source Project: ph-commons   Author: phax   File: StreamHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Read the content of the passed stream line by line and invoking a callback
 * on all matching lines.
 *
 * @param aIS
 *        The input stream to read from. May be <code>null</code>.
 * @param aCharset
 *        The character set to use. May not be <code>null</code>.
 * @param nLinesToSkip
 *        The 0-based index of the first line to read. Pass in 0 to indicate
 *        to read everything.
 * @param nLinesToRead
 *        The number of lines to read. Pass in {@link CGlobal#ILLEGAL_UINT} to
 *        indicate that all lines should be read. If the number passed here
 *        exceeds the number of lines in the file, nothing happens.
 * @param aLineCallback
 *        The callback that is invoked for all read lines. Each passed line
 *        does NOT contain the line delimiter! Note: it is not invoked for
 *        skipped lines!
 */
public static void readStreamLines (@WillClose @Nullable final InputStream aIS,
                                    @Nonnull @Nonempty final Charset aCharset,
                                    @Nonnegative final int nLinesToSkip,
                                    final int nLinesToRead,
                                    @Nonnull final Consumer <? super String> aLineCallback)
{
  try
  {
    ValueEnforcer.notNull (aCharset, "Charset");
    ValueEnforcer.isGE0 (nLinesToSkip, "LinesToSkip");
    final boolean bReadAllLines = nLinesToRead == CGlobal.ILLEGAL_UINT;
    ValueEnforcer.isTrue (bReadAllLines || nLinesToRead >= 0,
                          () -> "Line count may not be that negative: " + nLinesToRead);
    ValueEnforcer.notNull (aLineCallback, "LineCallback");

    // Start the action only if there is something to read
    if (aIS != null)
      if (bReadAllLines || nLinesToRead > 0)
      {
        try (final NonBlockingBufferedReader aBR = new NonBlockingBufferedReader (createReader (aIS, aCharset)))
        {
          // read with the passed charset
          _readFromReader (nLinesToSkip, nLinesToRead, aLineCallback, bReadAllLines, aBR);
        }
        catch (final IOException ex)
        {
          LOGGER.error ("Failed to read from reader", _propagate (ex));
        }
      }
  }
  finally
  {
    // Close input stream anyway
    close (aIS);
  }
}
 
Example #25
Source Project: ph-commons   Author: phax   File: AbstractStatisticsHandlerNumeric.java    License: Apache License 2.0 5 votes vote down vote up
@CheckForSigned
public final long getAverage ()
{
  return m_aRWLock.readLockedLong ( () -> {
    if (m_nInvocationCount == 0)
      return CGlobal.ILLEGAL_ULONG;
    return m_aSum.divide (BigInteger.valueOf (m_nInvocationCount)).longValue ();
  });
}
 
Example #26
Source Project: ph-commons   Author: phax   File: SizeHelper.java    License: 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 #27
Source Project: ph-commons   Author: phax   File: StatisticsHandlerKeyedCounter.java    License: 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 Project: ph-commons   Author: phax   File: AbstractStatisticsHandlerKeyedNumeric.java    License: 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 #29
Source Project: ph-commons   Author: phax   File: SizeHelperTest.java    License: 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 #30
Source Project: ph-commons   Author: phax   File: StringHelperTest.java    License: 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));
}