示例#1
1
  /**
   * Get the enum value with the passed ID
   *
   * @param <ENUMTYPE> The enum type
   * @param aClass The enum class
   * @param nID The ID to search
   * @param aDefault The default value to be returned, if the ID was not found.
   * @return The default parameter if no enum item with the given ID is present.
   */
  @Nullable
  public static <ENUMTYPE extends Enum<ENUMTYPE> & IHasSimpleIntID> ENUMTYPE getFromIDOrDefault(
      @Nonnull final Class<ENUMTYPE> aClass, final int nID, @Nullable final ENUMTYPE aDefault) {
    ValueEnforcer.notNull(aClass, "Class");

    final String sCacheKey = aClass.getName();
    Object[] aCachedData;
    s_aRWLockInt.readLock().lock();
    try {
      aCachedData = s_aIntCache.get(sCacheKey);
    } finally {
      s_aRWLockInt.readLock().unlock();
    }
    if (aCachedData == null) {
      s_aRWLockInt.writeLock().lock();
      try {
        // Try again in write lock
        aCachedData = s_aIntCache.get(sCacheKey);
        if (aCachedData == null) {
          // Create new cache entry
          int nMinID = Integer.MAX_VALUE;
          int nMaxID = Integer.MIN_VALUE;
          for (final ENUMTYPE aElement : aClass.getEnumConstants()) {
            final int nElementID = aElement.getID();
            if (nElementID < nMinID) nMinID = nElementID;
            if (nElementID > nMaxID) nMaxID = nElementID;
          }
          if (nMinID >= 0 && nMaxID <= CGlobal.MAX_BYTE_VALUE) {
            // Cachable!
            aCachedData = new Object[nMaxID + 1];
            for (final ENUMTYPE aElement : aClass.getEnumConstants())
              aCachedData[aElement.getID()] = aElement;
          } else {
            // Enum not cachable
            aCachedData = NOT_CACHABLE;
          }
          s_aIntCache.put(sCacheKey, aCachedData);
        }
      } finally {
        s_aRWLockInt.writeLock().unlock();
      }
    }

    if (aCachedData != NOT_CACHABLE) {
      if (nID < 0 || nID >= aCachedData.length) return aDefault;
      return GenericReflection.<Object, ENUMTYPE>uncheckedCast(aCachedData[nID]);
    }

    // Object is not cachable - traverse as ususal
    for (final ENUMTYPE aElement : aClass.getEnumConstants())
      if (aElement.getID() == nID) return aElement;
    return aDefault;
  }
 /**
  * Constructor.
  *
  * @param aType The class of the JAXB document implementation type. May not be <code>null</code>.
  * @param aXSDs The XSDs used to validate document. May be <code>null</code> or empty indicating,
  *     that no XSD check is needed.
  */
 protected AbstractJAXBMarshaller(
     @Nonnull final Class<JAXBTYPE> aType, @Nullable final IReadableResource... aXSDs) {
   m_aType = ValueEnforcer.notNull(aType, "Type");
   if (aXSDs != null) {
     ValueEnforcer.notEmptyNoNullValue(aXSDs, "XSDs");
     for (final IReadableResource aXSD : aXSDs) m_aXSDs.add(aXSD);
   }
 }
 /**
  * Constructor.
  *
  * @param aType The class of the JAXB document implementation type. May not be <code>null</code>.
  * @param aXSDs The XSDs used to validate document. May be <code>null</code> or empty indicating,
  *     that no XSD check is needed.
  */
 protected AbstractJAXBMarshaller(
     @Nonnull final Class<JAXBTYPE> aType,
     @Nullable final List<? extends IReadableResource> aXSDs) {
   m_aType = ValueEnforcer.notNull(aType, "Type");
   if (aXSDs != null) {
     ValueEnforcer.notEmptyNoNullValue(aXSDs, "XSDs");
     m_aXSDs.addAll(aXSDs);
   }
 }
示例#4
0
  /**
   * Create a new object pool for a certain amount of items and a factory that creates the objects
   * on demand.
   *
   * @param nItemCount The number of items in the pool. Must be &ge; 1.
   * @param aFactory The factory to create object. May not be <code>null</code>. The factory may not
   *     create <code>null</code> objects, as this leads to an error!
   */
  public ObjectPool(@Nonnegative final int nItemCount, @Nonnull final IFactory<DATATYPE> aFactory) {
    ValueEnforcer.isGT0(nItemCount, "ItemCount");
    ValueEnforcer.notNull(aFactory, "Factory");

    m_aAvailable = new Semaphore(nItemCount);
    m_aItems = new Object[nItemCount];
    m_aUsed = new boolean[nItemCount];
    Arrays.fill(m_aUsed, 0, nItemCount, false);
    m_aFactory = aFactory;
  }
示例#5
0
  /**
   * Rename a directory.
   *
   * @param aSourceDir The original directory name. May not be <code>null</code>.
   * @param aTargetDir The destination directory name. May not be <code>null</code>.
   * @return A non-<code>null</code> error code.
   */
  @Nonnull
  public static FileIOError renameDir(
      @Nonnull final File aSourceDir, @Nonnull final File aTargetDir) {
    ValueEnforcer.notNull(aSourceDir, "SourceDirectory");
    ValueEnforcer.notNull(aTargetDir, "TargetDirectory");

    // Does the source directory exist?
    if (!FileUtils.existsDir(aSourceDir))
      return EFileIOErrorCode.SOURCE_DOES_NOT_EXIST.getAsIOError(
          EFileIOOperation.RENAME_DIR, aSourceDir);

    // Are source and target different?
    if (EqualsUtils.equals(aSourceDir, aTargetDir))
      return EFileIOErrorCode.SOURCE_EQUALS_TARGET.getAsIOError(
          EFileIOOperation.RENAME_DIR, aSourceDir);

    // Does the target directory already exist?
    if (aTargetDir.exists())
      return EFileIOErrorCode.TARGET_ALREADY_EXISTS.getAsIOError(
          EFileIOOperation.RENAME_DIR, aTargetDir);

    // Is the source a parent of target?
    if (FileUtils.isParentDirectory(aSourceDir, aTargetDir))
      return EFileIOErrorCode.TARGET_IS_CHILD_OF_SOURCE.getAsIOError(
          EFileIOOperation.RENAME_DIR, aSourceDir, aTargetDir);

    // Is the source parent directory writable?
    final File aSourceParentDir = aSourceDir.getParentFile();
    if (aSourceParentDir != null && !FileUtils.canWrite(aSourceParentDir))
      return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError(
          EFileIOOperation.RENAME_DIR, aSourceDir);

    // Is the target parent directory writable?
    final File aTargetParentDir = aTargetDir.getParentFile();
    if (aTargetParentDir != null
        && aTargetParentDir.exists()
        && !FileUtils.canWrite(aTargetParentDir))
      return EFileIOErrorCode.TARGET_PARENT_NOT_WRITABLE.getAsIOError(
          EFileIOOperation.RENAME_DIR, aTargetDir);

    // Ensure parent of target directory is present
    FileUtils.ensureParentDirectoryIsPresent(aTargetDir);

    try {
      final EFileIOErrorCode eError =
          aSourceDir.renameTo(aTargetDir)
              ? EFileIOErrorCode.NO_ERROR
              : EFileIOErrorCode.OPERATION_FAILED;
      return eError.getAsIOError(EFileIOOperation.RENAME_DIR, aSourceDir, aTargetDir);
    } catch (final SecurityException ex) {
      return EFileIOErrorCode.getAsIOError(EFileIOOperation.RENAME_DIR, ex);
    }
  }
 private AbstractJSInvocation(
     @Nullable final IJSGeneratable aLhs, @Nonnull final JSMethod aMethod) {
   this.m_aObject = aLhs;
   this.m_sName = null;
   this.m_aCallee = ValueEnforcer.notNull(aMethod, "Method");
   this.m_aCtorType = null;
 }
  /**
   * Convert the passed object to a new DOM document
   *
   * @param aObject The object to be converted. May not be <code>null</code>.
   * @return <code>null</code> if converting the document failed.
   */
  @Nullable
  public final Document write(@Nonnull final JAXBTYPE aObject) {
    ValueEnforcer.notNull(aObject, "Object");

    final Document aDoc = XMLFactory.newDocument();
    return write(aObject, TransformResultFactory.create(aDoc)).isSuccess() ? aDoc : null;
  }
示例#8
0
  /**
   * Delete an existing file.
   *
   * @param aFile The file to be deleted. May not be <code>null</code>.
   * @return A non-<code>null</code> error code.
   */
  @Nonnull
  public static FileIOError deleteFile(@Nonnull final File aFile) {
    ValueEnforcer.notNull(aFile, "File");

    if (!FileUtils.existsFile(aFile))
      return EFileIOErrorCode.SOURCE_DOES_NOT_EXIST.getAsIOError(
          EFileIOOperation.DELETE_FILE, aFile);

    // Is the parent directory writable?
    final File aParentDir = aFile.getParentFile();
    if (aParentDir != null && !FileUtils.canWrite(aParentDir))
      return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError(
          EFileIOOperation.DELETE_FILE, aFile);

    try {
      // delete may return true even so it internally failed!
      final EFileIOErrorCode eError =
          aFile.delete() && !aFile.exists()
              ? EFileIOErrorCode.NO_ERROR
              : EFileIOErrorCode.OPERATION_FAILED;
      return eError.getAsIOError(EFileIOOperation.DELETE_FILE, aFile);
    } catch (final SecurityException ex) {
      return EFileIOErrorCode.getAsIOError(EFileIOOperation.DELETE_FILE, ex);
    }
  }
示例#9
0
  /**
   * Delete an existing directory. The directory needs to be empty before it can be deleted.
   *
   * @param aDir The directory to be deleted. May not be <code>null</code>.
   * @return A non-<code>null</code> error code.
   */
  @Nonnull
  public static FileIOError deleteDir(@Nonnull final File aDir) {
    ValueEnforcer.notNull(aDir, "Directory");

    // Does the directory not exist?
    if (!FileUtils.existsDir(aDir))
      return EFileIOErrorCode.SOURCE_DOES_NOT_EXIST.getAsIOError(EFileIOOperation.DELETE_DIR, aDir);

    if (isWarnOnDeleteRoot()) {
      // Check that we're not deleting the complete hard drive...
      if (aDir.getAbsoluteFile().getParent() == null)
        throw new IllegalArgumentException(
            "Aren't we deleting the full drive: '" + aDir.getAbsolutePath() + "'");
    }

    // Is the parent directory writable?
    final File aParentDir = aDir.getParentFile();
    if (aParentDir != null && !FileUtils.canWrite(aParentDir))
      return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError(
          EFileIOOperation.DELETE_DIR, aDir);

    try {
      // delete may return true even so it internally failed!
      final EFileIOErrorCode eError =
          aDir.delete() && !aDir.exists()
              ? EFileIOErrorCode.NO_ERROR
              : EFileIOErrorCode.OPERATION_FAILED;
      return eError.getAsIOError(EFileIOOperation.DELETE_DIR, aDir);
    } catch (final SecurityException ex) {
      return EFileIOErrorCode.getAsIOError(EFileIOOperation.DELETE_DIR, ex);
    }
  }
示例#10
0
 public SizeHelper(@Nonnull final Locale aDisplayLocale) {
   ValueEnforcer.notNull(aDisplayLocale, "DisplayLocale");
   m_aDFS = DecimalFormatSymbolsFactory.getInstance(aDisplayLocale);
   m_aDF0 = new DecimalFormat("0", m_aDFS);
   m_aDF1 = new DecimalFormat("0.0", m_aDFS);
   m_aDF2 = new DecimalFormat("0.00", m_aDFS);
 }
  @Nonnull
  @Nonempty
  private static String _createScopeID(@Nonnull final HttpServletRequest aHttpRequest) {
    ValueEnforcer.notNull(aHttpRequest, "HttpRequest"); // $NON-NLS-1$

    return GlobalIDFactory.getNewIntID() + "@" + aHttpRequest.getRequestURI(); // $NON-NLS-1$
  }
  @Override
  @Nonnull
  public ISimpleURL encodeRedirectURL(@Nonnull final ISimpleURL aURL) {
    ValueEnforcer.notNull(aURL, "URL"); // $NON-NLS-1$

    // Encode only the path and copy params and anchor
    return new SimpleURL(encodeRedirectURL(aURL.getPath()), aURL.getAllParams(), aURL.getAnchor());
  }
示例#13
0
  /**
   * Create a new {@link DocumentBuilderFactory} for the specified schema, with the following
   * settings: coalescing, comment ignoring and namespace aware.
   *
   * @param aSchema The schema to use. May not be <code>null</code>.
   * @return Never <code>null</code>.
   */
  @Nonnull
  public static DocumentBuilderFactory createDocumentBuilderFactory(@Nonnull final Schema aSchema) {
    ValueEnforcer.notNull(aSchema, "Schema");

    final DocumentBuilderFactory aDocumentBuilderFactory = createDefaultDocumentBuilderFactory();
    aDocumentBuilderFactory.setSchema(aSchema);
    return aDocumentBuilderFactory;
  }
  /**
   * Convert the passed object to XML.
   *
   * @param aObject The object to be converted. May not be <code>null</code>.
   * @param aResult The result object holder. May not be <code>null</code>.
   * @return {@link ESuccess}
   */
  @Nonnull
  public final ESuccess write(@Nonnull final JAXBTYPE aObject, @Nonnull final Result aResult) {
    ValueEnforcer.notNull(aObject, "Object");
    ValueEnforcer.notNull(aResult, "Result");

    try {
      final Marshaller aMarshaller = _createMarshaller();
      customizeMarshaller(aMarshaller);

      final JAXBElement<JAXBTYPE> aJAXBElement = wrapObject(aObject);
      aMarshaller.marshal(aJAXBElement, aResult);
      return ESuccess.SUCCESS;
    } catch (final JAXBException ex) {
      handleWriteException(ex);
    }
    return ESuccess.FAILURE;
  }
  public void removeAttribute(@Nonnull final String sName) {
    ValueEnforcer.notNull(sName, "Name");

    final Object aValue = m_aAttributes.remove(sName);
    if (aValue instanceof HttpSessionBindingListener)
      ((HttpSessionBindingListener) aValue)
          .valueUnbound(new HttpSessionBindingEvent(this, sName, aValue));
  }
示例#16
0
  /**
   * Create a new XML document without document type using a custom document builder.
   *
   * @param aDocBuilder The document builder to use. May not be <code>null</code>.
   * @param eVersion The XML version to use. If <code>null</code> is passed, {@link
   *     EXMLVersion#DEFAULT} will be used.
   * @return The created document. Never <code>null</code>.
   */
  @Nonnull
  public static Document newDocument(
      @Nonnull final DocumentBuilder aDocBuilder, @Nullable final EXMLVersion eVersion) {
    ValueEnforcer.notNull(aDocBuilder, "DocBuilder");

    final Document aDoc = aDocBuilder.newDocument();
    aDoc.setXmlVersion((eVersion != null ? eVersion : EXMLVersion.DEFAULT).getVersion());
    return aDoc;
  }
示例#17
0
  /**
   * Copies the source file to the target file.
   *
   * @param aSourceFile The source file to use. May not be <code>null</code>. Needs to be an
   *     existing file.
   * @param aTargetFile The destination files. May not be <code>null</code> and may not be an
   *     existing file.
   * @return A non-<code>null</code> error code.
   */
  @Nonnull
  public static FileIOError copyFile(
      @Nonnull final File aSourceFile, @Nonnull final File aTargetFile) {
    ValueEnforcer.notNull(aSourceFile, "SourceFile");
    ValueEnforcer.notNull(aTargetFile, "TargetFile");

    // Does the source file exist?
    if (!FileUtils.existsFile(aSourceFile))
      return EFileIOErrorCode.SOURCE_DOES_NOT_EXIST.getAsIOError(
          EFileIOOperation.COPY_FILE, aSourceFile);

    // Are source and target different?
    if (EqualsUtils.equals(aSourceFile, aTargetFile))
      return EFileIOErrorCode.SOURCE_EQUALS_TARGET.getAsIOError(
          EFileIOOperation.COPY_FILE, aSourceFile);

    // Does the target file already exist?
    if (aTargetFile.exists())
      return EFileIOErrorCode.TARGET_ALREADY_EXISTS.getAsIOError(
          EFileIOOperation.COPY_FILE, aTargetFile);

    // Is the source file readable?
    if (!FileUtils.canRead(aSourceFile))
      return EFileIOErrorCode.SOURCE_NOT_READABLE.getAsIOError(
          EFileIOOperation.COPY_FILE, aSourceFile);

    // Is the target parent directory writable?
    final File aTargetParentDir = aTargetFile.getParentFile();
    if (aTargetParentDir != null
        && aTargetParentDir.exists()
        && !FileUtils.canWrite(aTargetParentDir))
      return EFileIOErrorCode.TARGET_PARENT_NOT_WRITABLE.getAsIOError(
          EFileIOOperation.COPY_FILE, aTargetFile);

    // Ensure the targets parent directory is present
    FileUtils.ensureParentDirectoryIsPresent(aTargetFile);

    // Used FileChannel for better performance
    final EFileIOErrorCode eError =
        _copyFile(aSourceFile, aTargetFile).isSuccess()
            ? EFileIOErrorCode.NO_ERROR
            : EFileIOErrorCode.OPERATION_FAILED;
    return eError.getAsIOError(EFileIOOperation.COPY_FILE, aSourceFile, aTargetFile);
  }
  public void setAttribute(@Nonnull final String sName, @Nullable final Object aValue) {
    ValueEnforcer.notNull(sName, "Name");

    if (aValue != null) {
      m_aAttributes.put(sName, aValue);
      if (aValue instanceof HttpSessionBindingListener)
        ((HttpSessionBindingListener) aValue)
            .valueBound(new HttpSessionBindingEvent(this, sName, aValue));
    } else {
      removeAttribute(sName);
    }
  }
示例#19
0
  /**
   * Get the enum value with the passed name
   *
   * @param <ENUMTYPE> The enum type
   * @param aClass The enum class
   * @param sName The name to search
   * @param aDefault The default value to be returned, if the name was not found.
   * @return The default parameter if no enum item with the given name is present.
   */
  @Nullable
  public static <ENUMTYPE extends Enum<ENUMTYPE> & IHasName> ENUMTYPE getFromNameOrDefault(
      @Nonnull final Class<ENUMTYPE> aClass,
      @Nullable final String sName,
      @Nullable final ENUMTYPE aDefault) {
    ValueEnforcer.notNull(aClass, "Class");

    if (StringHelper.hasText(sName))
      for (final ENUMTYPE aElement : aClass.getEnumConstants())
        if (aElement.getName().equals(sName)) return aElement;
    return aDefault;
  }
  /**
   * Read a document from the specified source. The secure reading feature has <b>NO</b> affect when
   * using this method because the parameter type is too generic.
   *
   * @param aSource The source to read. May not be <code>null</code>.
   * @return <code>null</code> in case reading fails.
   */
  @Nullable
  public final JAXBTYPE read(@Nonnull final Source aSource) {
    ValueEnforcer.notNull(aSource, "Source");

    try {
      final Unmarshaller aUnmarshaller = _createUnmarshaller();
      customizeUnmarshaller(aUnmarshaller);
      return aUnmarshaller.unmarshal(aSource, m_aType).getValue();
    } catch (final JAXBException ex) {
      handleReadException(ex);
    }
    return null;
  }
示例#21
0
  /**
   * Create a document builder without a certain schema, using the passed {@link
   * DocumentBuilderFactory}.
   *
   * @param aDocBuilderFactory The document builder factory to be used. May not be <code>null</code>
   *     .
   * @return The created document builder. Never <code>null</code>.
   * @throws InitializationException In case some DOM initialization goes wrong
   */
  @Nonnull
  public static DocumentBuilder createDocumentBuilder(
      @Nonnull final DocumentBuilderFactory aDocBuilderFactory) {
    ValueEnforcer.notNull(aDocBuilderFactory, "DocBuilderFactory");

    try {
      final DocumentBuilder aDocBuilder = aDocBuilderFactory.newDocumentBuilder();
      aDocBuilder.setErrorHandler(DOMReaderDefaultSettings.getErrorHandler());
      return aDocBuilder;
    } catch (final ParserConfigurationException ex) {
      throw new InitializationException("Failed to create document builder", ex);
    }
  }
示例#22
0
  /**
   * Get the enum value with the passed ID
   *
   * @param <KEYTYPE> The ID type
   * @param <ENUMTYPE> The enum type
   * @param aClass The enum class
   * @param aID The ID to search
   * @param aDefault The default value to be returned, if the ID was not found.
   * @return The default parameter if no enum item with the given ID is present.
   */
  @Nullable
  public static <KEYTYPE, ENUMTYPE extends Enum<ENUMTYPE> & IHasID<KEYTYPE>>
      ENUMTYPE getFromIDOrDefault(
          @Nonnull final Class<ENUMTYPE> aClass,
          @Nullable final KEYTYPE aID,
          @Nullable final ENUMTYPE aDefault) {
    ValueEnforcer.notNull(aClass, "Class");

    if (aID != null)
      for (final ENUMTYPE aElement : aClass.getEnumConstants())
        if (aElement.getID().equals(aID)) return aElement;
    return aDefault;
  }
示例#23
0
  /**
   * Get the enum value with the passed string ID case insensitive
   *
   * @param <ENUMTYPE> The enum type
   * @param aClass The enum class
   * @param sID The ID to search
   * @param aDefault The default value to be returned, if the ID was not found.
   * @return The default parameter if no enum item with the given ID is present.
   */
  @Nullable
  public static <ENUMTYPE extends Enum<ENUMTYPE> & IHasID<String>>
      ENUMTYPE getFromIDCaseInsensitiveOrDefault(
          @Nonnull final Class<ENUMTYPE> aClass,
          @Nullable final String sID,
          @Nullable final ENUMTYPE aDefault) {
    ValueEnforcer.notNull(aClass, "Class");

    if (sID != null)
      for (final ENUMTYPE aElement : aClass.getEnumConstants())
        if (aElement.getID().equalsIgnoreCase(sID)) return aElement;
    return aDefault;
  }
示例#24
0
  @Nonnull
  private String _format(final double dSize, @Nonnegative final int nDecimals) {
    ValueEnforcer.isGE0(nDecimals, "Decimals");

    if (nDecimals == 0) return _format((long) dSize);

    // Cache for the most common formats
    if (nDecimals == 1) return m_aDF1.format(dSize);
    if (nDecimals == 2) return m_aDF2.format(dSize);

    // build formatting string with at least 3 decimals
    final StringBuilder aFormat = new StringBuilder("0.000");
    for (int i = 3; i < nDecimals; ++i) aFormat.append('0');
    return new DecimalFormat(aFormat.toString(), m_aDFS).format(dSize);
  }
示例#25
0
  /**
   * Create a new document with a document type using a custom document builder.
   *
   * @param aDocBuilder the document builder to be used. May not be <code>null</code>.
   * @param eVersion The XML version to use. If <code>null</code> is passed, {@link
   *     EXMLVersion#DEFAULT} will be used.
   * @param sQualifiedName The qualified name to use.
   * @param sPublicId The public ID of the document type.
   * @param sSystemId The system ID of the document type.
   * @return The created document. Never <code>null</code>.
   */
  @Nonnull
  public static Document newDocument(
      @Nonnull final DocumentBuilder aDocBuilder,
      @Nullable final EXMLVersion eVersion,
      @Nonnull final String sQualifiedName,
      @Nullable final String sPublicId,
      @Nullable final String sSystemId) {
    ValueEnforcer.notNull(aDocBuilder, "DocBuilder");

    final DOMImplementation aDomImpl = aDocBuilder.getDOMImplementation();
    final DocumentType aDocType = aDomImpl.createDocumentType(sQualifiedName, sPublicId, sSystemId);

    final Document aDoc = aDomImpl.createDocument(sSystemId, sQualifiedName, aDocType);
    aDoc.setXmlVersion((eVersion != null ? eVersion : EXMLVersion.DEFAULT).getVersion());
    return aDoc;
  }
示例#26
0
  /**
   * Delete an existing directory including all child objects.
   *
   * @param aDir The directory to be deleted. May not be <code>null</code>.
   * @return A non-<code>null</code> error code.
   */
  @Nonnull
  public static FileIOError deleteDirRecursive(@Nonnull final File aDir) {
    ValueEnforcer.notNull(aDir, "Directory");

    // Non-existing directory?
    if (!FileUtils.existsDir(aDir))
      return EFileIOErrorCode.SOURCE_DOES_NOT_EXIST.getAsIOError(
          EFileIOOperation.DELETE_DIR_RECURSIVE, aDir);

    if (isWarnOnDeleteRoot()) {
      // Check that we're not deleting the complete hard drive...
      if (aDir.getAbsoluteFile().getParent() == null)
        throw new IllegalArgumentException(
            "Aren't we deleting the full drive: '" + aDir.getAbsolutePath() + "'");
    }

    // Is the parent directory writable?
    final File aParentDir = aDir.getParentFile();
    if (aParentDir != null && !FileUtils.canWrite(aParentDir))
      return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError(
          EFileIOOperation.DELETE_DIR_RECURSIVE, aDir);

    // iterate directory
    for (final File aChild : FileUtils.getDirectoryContent(aDir)) {
      // is it a file or a directory or ...
      if (aChild.isDirectory()) {
        // Ignore "." and ".." directory
        if (FilenameHelper.isSystemInternalDirectory(aChild.getName())) continue;

        // recursive call
        final FileIOError eCode = deleteDirRecursive(aChild);
        if (eCode.isFailure()) return eCode;
      } else if (aChild.isFile()) {
        // delete file
        final FileIOError eCode = deleteFile(aChild);
        if (eCode.isFailure()) return eCode;
      } else {
        // Neither directory no file - don't know how to handle
        return EFileIOErrorCode.OBJECT_CANNOT_BE_HANDLED.getAsIOError(
            EFileIOOperation.DELETE_DIR_RECURSIVE, aChild);
      }
    }

    // Now this directory should be empty -> delete as if empty
    return deleteDir(aDir);
  }
示例#27
0
  @Nonnull
  public static File getAsFile(@Nonnull final URL aURL) {
    ValueEnforcer.notNull(aURL, "URL");
    if (!PROTOCOL_FILE.equals(aURL.getProtocol()))
      throw new IllegalArgumentException("Not a file URL: " + aURL);

    File aFile;
    try {
      aFile = new File(aURL.toURI().getSchemeSpecificPart());
    } catch (final URISyntaxException ex) {
      // Fallback for URLs that are not valid URIs
      aFile = new File(aURL.getPath());
    }

    // This file may be non-existing
    return aFile;
  }
  public RequestWebScopeNoMultipart(
      @Nonnull final HttpServletRequest aHttpRequest,
      @Nonnull final HttpServletResponse aHttpResponse) {
    super(_createScopeID(aHttpRequest));

    this.m_aHttpRequest = aHttpRequest;
    this.m_aHttpResponse = ValueEnforcer.notNull(aHttpResponse, "HttpResponse"); // $NON-NLS-1$

    // done initialization
    if (ScopeUtils.debugRequestScopeLifeCycle(s_aLogger))
      s_aLogger.info(
          "Created request web scope '"
              + //$NON-NLS-1$
              getID()
              + "' of class "
              + //$NON-NLS-1$
              CGStringHelper.getClassLocalName(this),
          ScopeUtils.getDebugStackTrace());
  }
  @Nonnull
  public static RequestScopeInitializer create(
      @Nonnull @Nonempty final String sApplicationID,
      @Nonnull final HttpServletRequest aHttpRequest,
      @Nonnull final HttpServletResponse aHttpResponse) {
    ValueEnforcer.notEmpty(sApplicationID, "ApplicationID");

    // Check if a request scope is already present
    final IRequestWebScope aExistingRequestScope = WebScopeManager.getRequestScopeOrNull();
    if (aExistingRequestScope != null) {
      // A scope is already present - e.g. from a scope aware filter

      // Check if scope is in destruction or destroyed!
      if (aExistingRequestScope.isValid()) {
        // Check the application IDs
        final String sExistingApplicationID =
            ScopeManager.getRequestApplicationID(aExistingRequestScope);
        if (!sApplicationID.equals(sExistingApplicationID)) {
          // Application ID mismatch!
          s_aLogger.warn(
              "The existing request scope has the application ID '"
                  + sExistingApplicationID
                  + "' but now the application ID '"
                  + sApplicationID
                  + "' should be used. The old application ID '"
                  + sExistingApplicationID
                  + "' is continued to be used!!!");
        }
        return new RequestScopeInitializer(aExistingRequestScope, false);
      }

      // Wow...
      s_aLogger.error(
          "The existing request scope is no longer valid - creating a new one: "
              + aExistingRequestScope.toString());
    }

    // No valid scope present
    // -> create a new scope
    final IRequestWebScope aRequestScope =
        WebScopeManager.onRequestBegin(sApplicationID, aHttpRequest, aHttpResponse);
    return new RequestScopeInitializer(aRequestScope, true);
  }
示例#30
0
  /**
   * Create a new directory. The direct parent directory already needs to exist.
   *
   * @param aDir The directory to be created. May not be <code>null</code>.
   * @return A non-<code>null</code> error code.
   */
  @Nonnull
  public static FileIOError createDir(@Nonnull final File aDir) {
    ValueEnforcer.notNull(aDir, "Directory");

    // Does the directory already exist?
    if (aDir.exists())
      return EFileIOErrorCode.TARGET_ALREADY_EXISTS.getAsIOError(EFileIOOperation.CREATE_DIR, aDir);

    // Is the parent directory writable?
    final File aParentDir = aDir.getParentFile();
    if (aParentDir != null && aParentDir.exists() && !FileUtils.canWrite(aParentDir))
      return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError(
          EFileIOOperation.CREATE_DIR, aDir);

    try {
      final EFileIOErrorCode eError =
          aDir.mkdir() ? EFileIOErrorCode.NO_ERROR : EFileIOErrorCode.OPERATION_FAILED;
      return eError.getAsIOError(EFileIOOperation.CREATE_DIR, aDir);
    } catch (final SecurityException ex) {
      return EFileIOErrorCode.getAsIOError(EFileIOOperation.CREATE_DIR, ex);
    }
  }