@Nullable
 @OverrideOnDemand
 public IHCNode getHeaderNode(@Nonnull final WPECTYPE aWPEC) {
   final String sText = getHeaderText(aWPEC);
   if (StringHelper.hasNoText(sText)) return null;
   return HCH1.create(sText);
 }
示例#2
0
  @Nullable
  public static String jsonEscape(@Nullable final String sInput) {
    if (StringHelper.hasNoText(sInput)) return sInput;

    final char[] aInput = sInput.toCharArray();
    if (!StringHelper.containsAny(aInput, CHARS_TO_MASK)) return sInput;

    final StringBuilder aSB = new StringBuilder(aInput.length * 2);
    _escape(aInput, aSB);
    return aSB.toString();
  }
示例#3
0
  @Nullable
  public static String beanCamelCaseName(@Nullable final String sInput) {
    if (StringHelper.hasNoText(sInput)) return sInput;

    // required if a string contains both "." and "_"
    final String s = RegExHelper.stringReplacePattern("\\.", sInput, "_");

    // avoid creating StringBuilder if not necessary
    if (s.indexOf('_') == -1)
      return beanUpperCaseFirstChar(RegExHelper.stringReplacePattern("\\$", s, "_"));

    final StringBuilder ret = new StringBuilder(s.length());
    for (final String sPart : StringHelper.getExploded('_', s))
      ret.append(beanUpperCaseFirstChar(sPart));
    // This replacement is required for nested classes!
    return RegExHelper.stringReplacePattern("\\$", ret.toString(), "_");
  }
示例#4
0
 public CSSFiles(@Nonnull final IReadableResource aFile) {
   final IMicroDocument aDoc = MicroReader.readMicroXML(aFile);
   if (aDoc != null) {
     final IMicroElement eRoot = aDoc.getDocumentElement();
     if (eRoot.getTagName().equals("list")) {
       // Old style
       s_aLogger.warn("CSS file " + aFile.getPath() + " is in old syntax");
       final List<String> aAllCSSFiles = new ArrayList<String>();
       if (XMLListHandler.readList(eRoot, aAllCSSFiles).isFailure())
         s_aLogger.error("Failed to read " + aFile.getPath());
       for (final String sCSS : aAllCSSFiles) addGlobalItem(null, sCSS, null);
     } else {
       // New style
       for (final IMicroElement eChild : eRoot.getAllChildElements("css")) {
         final String sCondComment = eChild.getAttribute("condcomment");
         final String sPath = eChild.getAttribute("path");
         if (StringHelper.hasNoText(sPath)) {
           s_aLogger.error("Found CSS item without a path in " + aFile.getPath());
           continue;
         }
         final String sMedia = eChild.getAttribute("media");
         // ESCA-JAVA0261:
         final Set<ECSSMedium> aMediaList = new LinkedHashSet<ECSSMedium>();
         if (sMedia != null)
           for (final String sMedium : RegExHelper.getSplitToArray(sMedia, ",\\s*")) {
             final ECSSMedium eMedium = ECSSMedium.getFromNameOrNull(sMedium);
             if (eMedium == null) {
               s_aLogger.warn(
                   "CSS item '"
                       + sPath
                       + "' in "
                       + aFile.getPath()
                       + " has an invalid medium '"
                       + sMedium
                       + "' - ignoring");
               continue;
             }
             aMediaList.add(eMedium);
           }
         addGlobalItem(sCondComment, sPath, aMediaList);
       }
     }
   }
 }
  /**
   * Call this method as the first action in your servlet, to ensure that the files are technically
   * handled, before your business logic takes places. This method should only be invoked for POST
   * calls.
   *
   * @param aRequestScope Current request scope
   * @throws FileUploadException
   */
  public static void handleUpload(@Nonnull final IRequestWebScopeWithoutResponse aRequestScope)
      throws FileUploadException {
    s_aLogger.info("handleUpload");
    // get the upload ID that was sent via a hidden field from the upload frame
    final String sUploadID = aRequestScope.getAttributeAsString(PARAM_UPLOAD_ID);
    if (StringHelper.hasNoText(sUploadID)) {
      FileUploadProgressListener.getInstance().reset();
      throw new FileUploadException("Unable to retrieve upload ID for received request!");
    }

    // Check if we have the matching upload context
    final UploadContext aContext = UploadContextRegistry.getInstance().getContext(sUploadID);
    if (aContext == null) {
      FileUploadProgressListener.getInstance().reset();
      throw new FileUploadException(
          "Unable to retrieve upload context for received request with ID '" + sUploadID + "'!");
    }
    // Ensure that the upload directory exists
    final File aUploadDir = aContext.getUploadDirectory();
    if (!aUploadDir.exists()) {
      final FileIOError aErr = FileOperations.createDirRecursive(aUploadDir);
      if (aErr.isFailure()) {
        FileUploadProgressListener.getInstance().reset();
        throw new FileUploadException(
            "Failed to create upload directory "
                + aUploadDir
                + ": "
                + aErr.toString()); // $NON-NLS-2$
      }
    }

    for (final IFileItem aFileItem : aRequestScope.getAllUploadedFileItemValues()) {
      final File aUploadedFile = _handleUploadFileItem(aFileItem, aContext);
      if (aUploadedFile != null) {
        FileUploadProgressListener.getInstance()
            .setFileName(FilenameHelper.getRelativeToParentDirectory(aUploadedFile, aUploadDir));
      }
    }
    FileUploadProgressListener.getInstance().setUploadFinished();
  }
  @Override
  @SuppressWarnings("null")
  protected void validateAndSaveInputParameters(
      @Nonnull final WebPageExecutionContext aWPEC,
      @Nullable final IUser aSelectedObject,
      @Nonnull final FormErrors aFormErrors,
      final boolean bEdit) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final boolean bIsAdministrator = aSelectedObject != null && aSelectedObject.isAdministrator();
    final AccessManager aAccessMgr = AccessManager.getInstance();
    String sLoginName = aWPEC.getAttr(FIELD_LOGINNAME);
    final String sFirstName = aWPEC.getAttr(FIELD_FIRSTNAME);
    final String sLastName = aWPEC.getAttr(FIELD_LASTNAME);
    final String sEmailAddress = aWPEC.getAttr(FIELD_EMAILADDRESS);
    final String sPassword = aWPEC.getAttr(FIELD_PASSWORD);
    final String sPasswordConf = aWPEC.getAttr(FIELD_PASSWORD_CONFIRM);
    final boolean bEnabled =
        bIsAdministrator ? true : aWPEC.getCheckBoxAttr(FIELD_ENABLED, DEFAULT_ENABLED);
    final Collection<String> aUserGroupIDs =
        bIsAdministrator
            ? aAccessMgr.getAllUserGroupIDsWithAssignedUser(aSelectedObject.getID())
            : aWPEC.getAttrs(FIELD_USERGROUPS);

    if (useEmailAddressAsLoginName()) {
      sLoginName = sEmailAddress;
    } else {
      if (StringHelper.hasNoText(sLoginName))
        aFormErrors.addFieldError(
            FIELD_LOGINNAME, EText.ERROR_LOGINNAME_REQUIRED.getDisplayText(aDisplayLocale));
    }

    if (StringHelper.hasNoText(sLastName)) {
      if (isLastNameMandatory())
        aFormErrors.addFieldError(
            FIELD_LASTNAME, EText.ERROR_LASTNAME_REQUIRED.getDisplayText(aDisplayLocale));
    }

    if (StringHelper.hasNoText(sEmailAddress)) {
      if (isEmailMandatory())
        aFormErrors.addFieldError(
            FIELD_EMAILADDRESS, EText.ERROR_EMAIL_REQUIRED.getDisplayText(aDisplayLocale));
    } else if (!EmailAddressUtils.isValid(sEmailAddress))
      aFormErrors.addFieldError(
          FIELD_EMAILADDRESS, EText.ERROR_EMAIL_INVALID.getDisplayText(aDisplayLocale));
    else {
      final IUser aSameLoginUser = aAccessMgr.getUserOfLoginName(sEmailAddress);
      if (aSameLoginUser != null)
        if (!bEdit || !aSameLoginUser.equals(aSelectedObject))
          aFormErrors.addFieldError(
              FIELD_EMAILADDRESS, EText.ERROR_EMAIL_IN_USE.getDisplayText(aDisplayLocale));
    }

    if (!bEdit) {
      final List<String> aPasswordErrors =
          GlobalPasswordSettings.getPasswordConstraintList()
              .getInvalidPasswordDescriptions(sPassword, aDisplayLocale);
      for (final String sPasswordError : aPasswordErrors)
        aFormErrors.addFieldError(FIELD_PASSWORD, sPasswordError);
      if (!EqualsUtils.equals(sPassword, sPasswordConf))
        aFormErrors.addFieldError(
            FIELD_PASSWORD_CONFIRM,
            EText.ERROR_PASSWORDS_DONT_MATCH.getDisplayText(aDisplayLocale));
    }

    if (ContainerHelper.isEmpty(aUserGroupIDs))
      aFormErrors.addFieldError(
          FIELD_USERGROUPS, EText.ERROR_NO_USERGROUP.getDisplayText(aDisplayLocale));
    else if (!aAccessMgr.containsAllUserGroupsWithID(aUserGroupIDs))
      aFormErrors.addFieldError(
          FIELD_USERGROUPS, EText.ERROR_INVALID_USERGROUPS.getDisplayText(aDisplayLocale));

    // Call custom method
    final Map<String, String> aCustomAttrMap =
        validateCustomParameters(aWPEC, aSelectedObject, aFormErrors, bEdit);

    if (aFormErrors.isEmpty()) {
      // All fields are valid -> save
      if (bEdit) {
        final String sUserID = aSelectedObject.getID();

        final Map<String, Object> aAttrMap = aSelectedObject.getAllAttributes();
        if (aCustomAttrMap != null) aAttrMap.putAll(aCustomAttrMap);

        // We're editing an existing object
        aAccessMgr.setUserData(
            sUserID,
            sLoginName,
            sEmailAddress,
            sFirstName,
            sLastName,
            m_aDefaultUserLocale,
            aAttrMap,
            !bEnabled);
        aNodeList.addChild(
            getStyler().createSuccessBox(EText.SUCCESS_EDIT.getDisplayText(aDisplayLocale)));

        // assign to the matching user groups
        final Collection<String> aPrevUserGroupIDs =
            aAccessMgr.getAllUserGroupIDsWithAssignedUser(sUserID);
        // Create all missing assignments
        final Set<String> aUserGroupsToBeAssigned =
            ContainerHelper.getDifference(aUserGroupIDs, aPrevUserGroupIDs);
        for (final String sUserGroupID : aUserGroupsToBeAssigned)
          aAccessMgr.assignUserToUserGroup(sUserGroupID, sUserID);

        // Delete all old assignments
        final Set<String> aUserGroupsToBeUnassigned =
            ContainerHelper.getDifference(aPrevUserGroupIDs, aUserGroupIDs);
        for (final String sUserGroupID : aUserGroupsToBeUnassigned)
          aAccessMgr.unassignUserFromUserGroup(sUserGroupID, sUserID);

      } else {
        // We're creating a new object
        final IUser aNewUser =
            aAccessMgr.createNewUser(
                sLoginName,
                sEmailAddress,
                sPassword,
                sFirstName,
                sLastName,
                m_aDefaultUserLocale,
                aCustomAttrMap,
                !bEnabled);
        if (aNewUser != null) {
          aNodeList.addChild(
              getStyler().createSuccessBox(EText.SUCCESS_CREATE.getDisplayText(aDisplayLocale)));

          // assign to the matching internal user groups
          for (final String sUserGroupID : aUserGroupIDs)
            aAccessMgr.assignUserToUserGroup(sUserGroupID, aNewUser.getID());
        } else
          aNodeList.addChild(
              getStyler().createErrorBox(EText.FAILURE_CREATE.getDisplayText(aDisplayLocale)));
      }
    }
  }
示例#7
0
 /**
  * Check if the given fragment is valid XHTML 1.1 mark-up. This method tries to parse the XHTML
  * fragment, so it is potentially slow!
  *
  * @param sXHTMLFragment The XHTML fragment to parse. It is not checked, whether the value looks
  *     like HTML or not.
  * @return <code>true</code> if the fragment is valid, <code>false</code> otherwise.
  */
 public boolean isValidXHTMLFragment(@Nullable final String sXHTMLFragment) {
   return StringHelper.hasNoText(sXHTMLFragment) || parseXHTMLFragment(sXHTMLFragment) != null;
 }
示例#8
0
 public MicroDataAware(@Nullable final CharSequence aText) {
   if (StringHelper.hasNoText(aText)) m_aSB = new StringBuilder();
   else m_aSB = new StringBuilder(aText);
 }
  /**
   * Called after successful external validation
   *
   * @param aItem Uploaded file item
   * @param aContext The non-<code>null</code> Upload context
   * @return The file which has been written in on the server, or <code>null</code> in case of an
   *     error
   * @throws FileUploadException
   */
  @Nullable
  private static File _handleUploadFileItem(
      @Nonnull final IFileItem aItem, @Nonnull final UploadContext aContext)
      throws FileUploadException {
    final String sFieldName = aItem.getFieldName();
    final String sSourceFileName = aItem.getName();
    final String sContentType = aItem.getContentType();
    final boolean bInMemory = aItem.isInMemory();
    final long nSizeInBytes = aItem.getSize();
    File aUploadedFile = null;

    s_aLogger.info(
        "Processing file item [field:"
            + sFieldName
            + ", file:"
            + sSourceFileName
            + ", contenttype:"
            + sContentType
            + ", inmemory:"
            + bInMemory
            + ", size:"
            + nSizeInBytes
            + (aContext.getPostProcessor() == null
                ? ""
                : ", post processor "
                    + CGStringHelper.getClassLocalName(aContext.getPostProcessor()))
            + "]");

    // Validate the original filename
    final IUploadFilenameFilter aFilter = aContext.getFilenameFilter();
    if (aFilter != null && !aFilter.matchesFilter(sSourceFileName)) {
      FileUploadProgressListener.getInstance()
          .setFailed(
              aFilter.getErrorCode(),
              aFilter.getErrorMessage(),
              ArrayHelper.newArray(aFilter.getErrorArguments(), String.class));
      final String sMsg =
          "Uploaded file '"
              + sSourceFileName
              + "' does not satisfy the active filename filter!"; //$NON-NLS-2$
      s_aLogger.warn(sMsg);
      throw new FileUploadException(sMsg);
    }

    final IUploadFileSizeFilter aSizeFilter = aContext.getFileSizeFilter();
    if (aSizeFilter != null && !aSizeFilter.matchesFilter(Long.valueOf(nSizeInBytes))) {
      FileUploadProgressListener.getInstance()
          .setFailed(
              EFileUploadText.ERROR_FILESIZE_EXCEEDED.getStringPropertyName(),
              EFileUploadText.ERROR_FILESIZE_EXCEEDED,
              sSourceFileName,
              SizeHelper.getSizeHelperOfLocale(Locale.US)
                  .getAsMatching(aSizeFilter.getMaxBytes(), 2));
      final String sMsg =
          "Uploaded file '"
              + sSourceFileName
              + "' does not satisfy the maximum file size filter!"; //$NON-NLS-2$
      s_aLogger.warn(sMsg);
      throw new FileUploadException(sMsg);
    }

    // Size may be 0 if no file was selected
    if (nSizeInBytes > 0) {
      // Set the post processor only, if a file is present, to avoid endless
      // loops on "post processing file ..."
      final FileUploadProgressListener aProgListener = FileUploadProgressListener.getInstance();
      final IUploadPostProcessor aPostProcessor = aContext.getPostProcessor();
      if (aPostProcessor != null) {
        aProgListener.setPostProcessor(aPostProcessor);
      }
      // Ensure the file does not contain any harmful characters etc.
      final String sFileName = FileUploadHelper.getUnifiedFilename(aItem);
      String sTargetFileName = aContext.getTargetFileName();
      if (StringHelper.hasNoText(sTargetFileName)) {
        sTargetFileName = sFileName;
      }
      final String sTargetDir =
          FilenameHelper.getAbsoluteWithEnsuredParentDirectory(
              aContext.getUploadDirectory(), FilenameHelper.getPath(sTargetFileName));

      // This is the main copy action
      aUploadedFile =
          FileUploadHelper.saveUploadedFile(
              aItem,
              new File(sTargetDir),
              FilenameHelper.getBaseName(sTargetFileName),
              FilenameHelper.getExtension(sTargetFileName));

      if (aUploadedFile == null) {
        // Something went wrong in copying
        s_aLogger.error("Upload failed.");
      } else {
        s_aLogger.info(
            "Upload completed successfully to destination " + aUploadedFile.getAbsolutePath());
        if (aPostProcessor != null) {
          s_aLogger.info("Starting post processing...");
          try {
            aProgListener.setPostProcessing();
            final UploadPostProcessingResult aResult =
                aPostProcessor.performPostProcessing(
                    aUploadedFile, sFileName, aContext.getProperties());
            aProgListener.setPostProcessorResult(aResult);
          } catch (final RuntimeException ex) {
            // Catch any exception
            s_aLogger.error("Internal error in post processing", ex);
            aProgListener.setPostProcessorResult(
                new UploadPostProcessingResult(
                    ESuccess.FAILURE,
                    EFileUploadText.ERROR_POST_PROCESSING,
                    EFileUploadText.ERROR_POST_PROCESSING.getStringPropertyName(),
                    null));
          }
        }
      }
    } else {
      FileUploadProgressListener.getInstance()
          .setFailed(
              EFileUploadText.ERROR_NO_FILE_OR_EMPTY.getStringPropertyName(),
              EFileUploadText.ERROR_NO_FILE_OR_EMPTY);
      final String sMsg =
          "No file or empty file selected: '" + sSourceFileName + "'!"; // $NON-NLS-2$
      s_aLogger.warn(sMsg);
      throw new FileUploadException(sMsg);
    }
    return aUploadedFile;
  }
示例#10
0
 /**
  * Convert a given name to plural. For consistency only a "List" is appended.
  *
  * @param sSingular The string to pluralize. May not be <code>null</code> or empty.
  * @return The pluralized string.
  */
 @Nonnull
 public static String getPlural(@Nonnull final String sSingular) {
   if (StringHelper.hasNoText(sSingular))
     throw new IllegalArgumentException("passed text is empty");
   return sSingular + "List";
 }