Java Code Examples for com.helger.commons.ValueEnforcer#isTrue()

The following examples show how to use com.helger.commons.ValueEnforcer#isTrue() . 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: 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 2
Source File: FileSystemResourceProvider.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
public FileSystemResourceProvider (@Nullable final File aBasePath)
{
  if (aBasePath != null)
  {
    ValueEnforcer.isTrue (aBasePath.exists (), () -> "Passed base path '" + aBasePath + "' does not exist!");
    ValueEnforcer.isTrue (aBasePath.isDirectory (), () -> "Passed base path '" + aBasePath + "' is not a directory!");
    if (!aBasePath.canRead ())
      if (LOGGER.isWarnEnabled ())
        LOGGER.warn ("Cannot read passed base path '" + aBasePath + "'!");
    if (!aBasePath.canWrite ())
      if (LOGGER.isWarnEnabled ())
        LOGGER.warn ("Cannot write passed base path '" + aBasePath + "'!");
    if (!aBasePath.canExecute ())
      if (LOGGER.isWarnEnabled ())
        LOGGER.warn ("Cannot execute in passed base path '" + aBasePath + "'!");
  }
  m_aBasePath = aBasePath;
}
 
Example 3
Source File: ChannelHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Copy all content from the source channel to the destination channel.
 *
 * @param aSrc
 *        Source channel. May not be <code>null</code>. Is not closed after
 *        the operation.
 * @param aDest
 *        Destination channel. May not be <code>null</code>. Is not closed
 *        after the operation.
 * @return The number of bytes written.
 * @throws IOException
 *         In case of IO error
 */
@Nonnegative
public static long channelCopy (@Nonnull @WillNotClose final ReadableByteChannel aSrc,
                                @Nonnull @WillNotClose final WritableByteChannel aDest) throws IOException
{
  ValueEnforcer.notNull (aSrc, "SourceChannel");
  ValueEnforcer.isTrue (aSrc.isOpen (), "SourceChannel is not open!");
  ValueEnforcer.notNull (aDest, "DestinationChannel");
  ValueEnforcer.isTrue (aDest.isOpen (), "DestinationChannel is not open!");

  long nBytesWritten;
  if (USE_COPY_V1)
    nBytesWritten = _channelCopy1 (aSrc, aDest);
  else
    nBytesWritten = _channelCopy2 (aSrc, aDest);
  return nBytesWritten;
}
 
Example 4
Source File: VendorInfo.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public static void setVendorEmail (@Nonnull @Nonempty final String sVendorEmail)
{
  ValueEnforcer.notEmpty (sVendorEmail, "VendorEmail");
  ValueEnforcer.isTrue (EmailAddressHelper.isValid (sVendorEmail), () -> "Illegal vendor email: " + sVendorEmail);
  s_sVendorEmail = sVendorEmail;
  s_sVendorEmailSuffix = StringHelper.getFromFirstIncl (sVendorEmail, '@');
}
 
Example 5
Source File: ConcurrentCollectorMultiple.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param nMaxQueueSize
 *        The maximum number of items that can be in the queue. Must be &gt;
 *        0.
 * @param nMaxPerformCount
 *        The maximum number of objects to be put in the queue for execution.
 *        Must be &gt; 0.
 */
public ConcurrentCollectorMultiple (@Nonnegative final int nMaxQueueSize, @Nonnegative final int nMaxPerformCount)
{
  super (nMaxQueueSize);
  ValueEnforcer.isGT0 (nMaxPerformCount, "MaxPerformCount");
  ValueEnforcer.isTrue (nMaxPerformCount <= nMaxQueueSize,
                        () -> "max perform size is illegal " +
                              nMaxPerformCount +
                              " - must be <= queue size " +
                              nMaxQueueSize);
  m_nMaxPerformCount = nMaxPerformCount;
}
 
Example 6
Source File: BasicTreeItem.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for normal elements.
 *
 * @param aParent
 *        Parent item to use. May never be <code>null</code> since only the
 *        root has no parent and for the root item a special no-argument
 *        constructor is present.
 */
public BasicTreeItem (@Nonnull final ITEMTYPE aParent)
{
  ValueEnforcer.notNull (aParent, "Parent");
  ValueEnforcer.isTrue (aParent instanceof BasicTreeItem <?, ?>, "Parent is no BasicTreeItem");
  ValueEnforcer.notNull (aParent.getFactory (), "parent item factory");
  m_aParent = aParent;
  m_aFactory = aParent.getFactory ();
  m_aData = null;
}
 
Example 7
Source File: ScopeManager.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * This method is only to be called by this class and the web scope manager!
 *
 * @param aRequestScope
 *        The request scope to use. May not be <code>null</code>.
 */
public static void internalSetAndInitRequestScope (@Nonnull final IRequestScope aRequestScope)
{
  ValueEnforcer.notNull (aRequestScope, "RequestScope");
  ValueEnforcer.isTrue (ScopeManager::isGlobalScopePresent,
                        "No global context present! May be the global context listener is not installed?");

  // Happens if an internal redirect happens in a web-application (e.g. for
  // 404 page)
  final IRequestScope aExistingRequestScope = s_aRequestScopeTL.get ();
  if (aExistingRequestScope != null)
  {
    if (LOGGER.isWarnEnabled ())
      LOGGER.warn ("A request scope is already present - will overwrite it: " + aExistingRequestScope.toString ());
    if (aExistingRequestScope.isValid ())
    {
      // The scope shall be destroyed here, as this is most probably a
      // programming error!
      LOGGER.warn ("Destroying the old request scope before the new one gets initialized!");
      _destroyRequestScope (aExistingRequestScope);
    }
  }

  // set request context
  s_aRequestScopeTL.set (aRequestScope);

  // Now init the scope
  aRequestScope.initScope ();

  // call SPIs
  ScopeSPIManager.getInstance ().onRequestScopeBegin (aRequestScope);
}
 
Example 8
Source File: SchematronTestHelper.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static ICommonsList <SchematronTestFile> _readDI (@Nonnull final IReadableResource aRes)
{
  if (false)
    ClassPathHelper.getAllClassPathEntries ().forEach (x -> {
      System.out.println (x);
      if (new File (x).isDirectory ())
      {
        final FileSystemRecursiveIterator it = new FileSystemRecursiveIterator (new File (x));
        it.forEach (y -> System.out.println (StringHelper.getRepeated ("  ", it.getLevel ()) + y));
      }
    });
  ValueEnforcer.notNull (aRes, "Resource");
  ValueEnforcer.isTrue (aRes.exists (), () -> "Resource " + aRes + " does not exist!");

  final ICommonsList <SchematronTestFile> ret = new CommonsArrayList <> ();
  final IMicroDocument aDoc = MicroReader.readMicroXML (aRes);
  if (aDoc == null)
    throw new IllegalArgumentException ("Failed to open/parse " + aRes + " as XML");
  String sLastParentDirBaseName = null;
  for (final IMicroElement eItem : aDoc.getDocumentElement ().getAllChildElements ())
    if (eItem.getTagName ().equals ("directory"))
      sLastParentDirBaseName = eItem.getAttributeValue ("basename");
    else
      if (eItem.getTagName ().equals ("file"))
        ret.add (new SchematronTestFile (sLastParentDirBaseName,
                                         new ClassPathResource (eItem.getAttributeValue ("name")),
                                         eItem.getAttributeValue ("basename")));
      else
        throw new IllegalArgumentException ("Cannot handle " + eItem);
  return ret;
}
 
Example 9
Source File: CSSPropertyColors.java    From ph-css with Apache License 2.0 5 votes vote down vote up
public CSSPropertyColors (@Nonnull final ECSSProperty eProp,
                          @Nullable final ECSSVendorPrefix eVendorPrefix,
                          @Nullable final ICSSPropertyCustomizer aCustomizer,
                          @Nonnegative final int nMinArgCount,
                          @Nonnegative final int nMaxArgCount)
{
  super (eProp, eVendorPrefix, aCustomizer);
  ValueEnforcer.isGT0 (nMinArgCount, "MinNumbers");
  ValueEnforcer.isGT0 (nMaxArgCount, "MaxNumbers");
  ValueEnforcer.isTrue (nMinArgCount <= nMaxArgCount,
                        () -> "MaxArgCount (" + nMaxArgCount + ") must be >= MinArgCount (" + nMinArgCount + ")");
  m_nMinArgCount = nMinArgCount;
  m_nMaxArgCount = nMaxArgCount;
}
 
Example 10
Source File: LoggingInvocationHandler.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static <T> T proxying (@Nonnull final Class <? extends T> aInterfaceClass,
                              @Nonnull final T aActualTarget,
                              @Nonnull final Function <? super T, ? extends InvocationHandler> aFactory)
{
  ValueEnforcer.isTrue (aInterfaceClass.isInterface (), "Only interface classes can be proxied!");
  final Object ret = Proxy.newProxyInstance (aInterfaceClass.getClassLoader (),
                                             new Class <?> [] { aInterfaceClass },
                                             aFactory.apply (aActualTarget));
  return GenericReflection.uncheckedCast (ret);
}
 
Example 11
Source File: MatrixInt.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a matrix quickly without checking arguments.
 *
 * @param aOther
 *        Two-dimensional array of doubles. Is directly reused!
 * @param nRows
 *        Number of rows.
 * @param nCols
 *        Number of columns.
 */
@SuppressFBWarnings ("EI_EXPOSE_REP")
MatrixInt (@Nonnull final int [] [] aOther, @Nonnegative final int nRows, @Nonnegative final int nCols)
{
  ValueEnforcer.notNull (aOther, "Other");
  ValueEnforcer.isGT0 (nRows, "rows");
  ValueEnforcer.isGT0 (nCols, "cols");
  ValueEnforcer.isTrue (aOther.length >= nRows, "array is too short");
  for (int nRow = 0; nRow < nRows; nRow++)
    ValueEnforcer.isTrue (aOther[nRow].length >= nCols, "All rows must have the same length.");

  m_aData = aOther;
  m_nRows = nRows;
  m_nCols = nCols;
}
 
Example 12
Source File: Matrix.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a matrix quickly without checking arguments.
 *
 * @param aOther
 *        Two-dimensional array of doubles. Is directly reused!
 * @param nRows
 *        Number of rows.
 * @param nCols
 *        Number of columns.
 */
@SuppressFBWarnings ("EI_EXPOSE_REP")
Matrix (@Nonnull final double [] [] aOther, @Nonnegative final int nRows, @Nonnegative final int nCols)
{
  ValueEnforcer.notNull (aOther, "Other");
  ValueEnforcer.isGT0 (nRows, "rows");
  ValueEnforcer.isGT0 (nCols, "cols");
  ValueEnforcer.isTrue (aOther.length >= nRows, "array is too short");
  for (int nRow = 0; nRow < nRows; nRow++)
    ValueEnforcer.isTrue (aOther[nRow].length >= nCols, "All rows must have the same length.");

  m_aData = aOther;
  m_nRows = nRows;
  m_nCols = nCols;
}
 
Example 13
Source File: BasicTreeItem.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
public final void setData (@Nullable final DATATYPE aData)
{
  ValueEnforcer.isTrue (isValidData (aData), "The passed data object is invalid!");
  m_aData = aData;
}
 
Example 14
Source File: CSSKeyframesRule.java    From ph-css with Apache License 2.0 4 votes vote down vote up
public CSSKeyframesRule (@Nonnull @Nonempty final String sDeclaration, @Nonnull @Nonempty final String sAnimationName)
{
  ValueEnforcer.isTrue (isValidDeclaration (sDeclaration), "Declaration is invalid");
  m_sDeclaration = sDeclaration;
  m_sAnimationName = sAnimationName;
}
 
Example 15
Source File: StreamHelper.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Pass the content of the given input stream to the given output stream. The
 * input stream is automatically closed, whereas the output stream stays open!
 *
 * @param aIS
 *        The input stream to read from. May be <code>null</code>.
 * @param bCloseIS
 *        <code>true</code> to close the InputStream, <code>false</code> to
 *        leave it open.
 * @param aOS
 *        The output stream to write to. May be <code>null</code>.
 * @param bCloseOS
 *        <code>true</code> to close the OutputStream, <code>false</code> to
 *        leave it open.
 * @param aBuffer
 *        The buffer to use. May not be <code>null</code>.
 * @param aLimit
 *        An optional maximum number of bytes to copied from the input stream
 *        to the output stream. May be <code>null</code> to indicate no limit,
 *        meaning all bytes are copied.
 * @param aExceptionCallback
 *        The Exception callback to be invoked, if an exception occurs. May
 *        not be <code>null</code>.
 * @param aCopyByteCount
 *        An optional mutable long object that will receive the total number
 *        of copied bytes. Note: and optional old value is overwritten. Note:
 *        this is only called, if copying was successful, and not in case of
 *        an exception.
 * @return <code>{@link ESuccess#SUCCESS}</code> if copying took place, <code>
 *         {@link ESuccess#FAILURE}</code> otherwise
 * @since 9.3.6
 */
@Nonnull
public static ESuccess copyInputStreamToOutputStream (@Nullable final InputStream aIS,
                                                      final boolean bCloseIS,
                                                      @Nullable final OutputStream aOS,
                                                      final boolean bCloseOS,
                                                      @Nonnull @Nonempty final byte [] aBuffer,
                                                      @Nullable final Long aLimit,
                                                      @Nullable final IExceptionCallback <IOException> aExceptionCallback,
                                                      @Nullable final MutableLong aCopyByteCount)
{
  try
  {
    ValueEnforcer.notEmpty (aBuffer, "Buffer");
    ValueEnforcer.isTrue (aLimit == null || aLimit.longValue () >= 0, () -> "Limit may not be negative: " + aLimit);

    if (aIS != null && aOS != null)
    {
      // both streams are not null
      final long nTotalBytesCopied;
      if (aLimit == null)
        nTotalBytesCopied = _copyInputStreamToOutputStream (aIS, aOS, aBuffer);
      else
        nTotalBytesCopied = _copyInputStreamToOutputStreamWithLimit (aIS, aOS, aBuffer, aLimit.longValue ());

      // Add to statistics
      s_aByteSizeHdl.addSize (nTotalBytesCopied);

      // Remember copied bytes?
      if (aCopyByteCount != null)
        aCopyByteCount.set (nTotalBytesCopied);
      return ESuccess.SUCCESS;
    }
  }
  catch (final IOException ex)
  {
    if (aExceptionCallback != null)
      aExceptionCallback.onException (ex);
    else
      if (!isKnownEOFException (ex))
        LOGGER.error ("Failed to copy from InputStream to OutputStream", _propagate (ex));
  }
  finally
  {
    // Ensure streams are closed under all circumstances
    if (bCloseIS)
      close (aIS);
    if (bCloseOS)
      close (aOS);
  }
  return ESuccess.FAILURE;
}
 
Example 16
Source File: CSSViewportRule.java    From ph-css with Apache License 2.0 4 votes vote down vote up
public CSSViewportRule (@Nonnull @Nonempty final String sDeclaration)
{
  ValueEnforcer.isTrue (isValidDeclaration (sDeclaration), "Declaration is invalid");
  m_sDeclaration = sDeclaration;
}
 
Example 17
Source File: TypeConverterRegistry.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Register a default type converter.
 *
 * @param aSrcClass
 *        A non-<code>null</code> source class to convert from. Must be an
 *        instancable class.
 * @param aDstClass
 *        A non-<code>null</code> destination class to convert to. Must be an
 *        instancable class. May not equal the source class.
 * @param aConverter
 *        The convert to use. May not be <code>null</code>.
 */
private void _registerTypeConverter (@Nonnull final Class <?> aSrcClass,
                                     @Nonnull final Class <?> aDstClass,
                                     @Nonnull final ITypeConverter <?, ?> aConverter)
{
  ValueEnforcer.notNull (aSrcClass, "SrcClass");
  ValueEnforcer.isTrue (ClassHelper.isPublic (aSrcClass), () -> "Source " + aSrcClass + " is no public class!");
  ValueEnforcer.notNull (aDstClass, "DstClass");
  ValueEnforcer.isTrue (ClassHelper.isPublic (aDstClass), () -> "Destination " + aDstClass + " is no public class!");
  ValueEnforcer.isFalse (aSrcClass.equals (aDstClass),
                         "Source and destination class are equal and therefore no converter is required.");
  ValueEnforcer.notNull (aConverter, "Converter");
  ValueEnforcer.isFalse (aConverter instanceof ITypeConverterRule,
                         "Type converter rules must be registered via registerTypeConverterRule");
  if (ClassHelper.areConvertibleClasses (aSrcClass, aDstClass))
    if (LOGGER.isWarnEnabled ())
      LOGGER.warn ("No type converter needed between " +
                   aSrcClass +
                   " and " +
                   aDstClass +
                   " because types are convertible!");

  // The main class should not already be registered
  final Map <Class <?>, ITypeConverter <?, ?>> aSrcMap = _getOrCreateConverterMap (aSrcClass);
  if (aSrcMap.containsKey (aDstClass))
    throw new IllegalArgumentException ("A mapping from " + aSrcClass + " to " + aDstClass + " is already defined!");

  m_aRWLock.writeLocked ( () -> {
    // Automatically register the destination class, and all parent
    // classes/interfaces
    for (final WeakReference <Class <?>> aCurWRDstClass : ClassHierarchyCache.getClassHierarchyIterator (aDstClass))
    {
      final Class <?> aCurDstClass = aCurWRDstClass.get ();
      if (aCurDstClass != null)
        if (!aSrcMap.containsKey (aCurDstClass))
        {
          if (aSrcMap.put (aCurDstClass, aConverter) != null)
          {
            if (LOGGER.isWarnEnabled ())
              LOGGER.warn ("Overwriting converter from " + aSrcClass + " to " + aCurDstClass);
          }
          else
          {
            if (LOGGER.isTraceEnabled ())
              LOGGER.trace ("Registered type converter from '" +
                            aSrcClass.toString () +
                            "' to '" +
                            aCurDstClass.toString () +
                            "'");
          }
        }
    }
  });
}
 
Example 18
Source File: Option.java    From ph-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Set the maximum number of arguments that can be present. By default it is
 * 0. The difference between minimum and maximum arguments are the optional
 * arguments. If the option is repeatable, this value is per occurrence.
 *
 * @param nMaxArgs
 *        Number of maximum arguments. Must be &ge; 0 or
 *        {@link #INFINITE_VALUES}
 * @return this for chaining
 * @see #maxArgsInfinite()
 */
@Nonnull
public Builder maxArgs (final int nMaxArgs)
{
  ValueEnforcer.isTrue (nMaxArgs == INFINITE_VALUES || nMaxArgs >= 0,
                        () -> "MaxArgs must be " + INFINITE_VALUES + " or >= 0!");
  m_nMaxArgs = nMaxArgs;
  return this;
}
 
Example 19
Source File: AESCryptFuncTest.java    From ph-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new AES key from the given byte array. Please note that for more
 * than 16 bytes, you need the "unlimited strength jurisdiction policy
 * files".
 *
 * @param aBytes
 *        Byte array with 16, 24 or 32 bytes. May not be <code>null</code>.
 */
public AESSecretKey (final byte [] aBytes)
{
  ValueEnforcer.notNull (aBytes, "Bytes");
  ValueEnforcer.isTrue (aBytes.length == 16 || aBytes.length == 24 || aBytes.length == 32,
                        () -> "Key byte array must be 16, 24 or 32 bytes but is " + aBytes.length + " bytes!");
  m_aBytes = ArrayHelper.getCopy (aBytes);
}
 
Example 20
Source File: Codepoint.java    From ph-commons with Apache License 2.0 2 votes vote down vote up
/**
 * Create a codepoint from a specific integer value
 *
 * @param nValue
 *        int value
 */
public Codepoint (@Nonnegative final int nValue)
{
  ValueEnforcer.isTrue (Character.isValidCodePoint (nValue), () -> "Invalid Codepoint: " + nValue);
  m_nValue = nValue;
}