Пример #1
0
 public static void jsonEscape(@Nullable final String sInput, @Nonnull final StringBuilder aSB) {
   if (StringHelper.hasText(sInput)) {
     final char[] aInput = sInput.toCharArray();
     if (!StringHelper.containsAny(aInput, CHARS_TO_MASK)) aSB.append(sInput);
     else _escape(aInput, aSB);
   }
 }
Пример #2
0
 public static void jsonEscape(
     @Nullable final String sInput, @Nonnull @WillNotClose final Writer aWriter)
     throws IOException {
   if (StringHelper.hasText(sInput)) {
     final char[] aInput = sInput.toCharArray();
     if (!StringHelper.containsAny(aInput, CHARS_TO_MASK)) aWriter.write(aInput, 0, aInput.length);
     else _escape(aInput, aWriter);
   }
 }
Пример #3
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();
  }
Пример #4
0
 @Override
 protected void applyProperties(
     @Nonnull final IMicroElement aElement,
     @Nonnull final IHCConversionSettingsToNode aConversionSettings) {
   super.applyProperties(aElement, aConversionSettings);
   if (m_nWidth > 0) aElement.setAttribute(CHTMLAttributes.WIDTH, m_nWidth);
   if (m_nHeight > 0) aElement.setAttribute(CHTMLAttributes.HEIGHT, m_nHeight);
   if (StringHelper.hasText(m_sHSpace)) aElement.setAttribute(CHTMLAttributes.HSPACE, m_sHSpace);
   if (StringHelper.hasText(m_sVSpace)) aElement.setAttribute(CHTMLAttributes.VSPACE, m_sVSpace);
   if (m_eAlign != null) aElement.setAttribute(CHTMLAttributes.ALIGN, m_eAlign);
   if (StringHelper.hasText(m_sArchive))
     aElement.setAttribute(CHTMLAttributes.ARCHIVE, m_sArchive);
   if (StringHelper.hasText(m_sBorder)) aElement.setAttribute(CHTMLAttributes.BORDER, m_sBorder);
   if (StringHelper.hasText(m_sClassID))
     aElement.setAttribute(CHTMLAttributes.CLASSID, m_sClassID);
   if (m_aCodeBase != null)
     aElement.setAttribute(CHTMLAttributes.CODEBASE, m_aCodeBase.getAsString());
   if (m_aCodeType != null)
     aElement.setAttribute(CHTMLAttributes.CODETYPE, m_aCodeType.getAsString());
   if (m_aData != null) aElement.setAttribute(CHTMLAttributes.DATA, m_aData.getAsString());
   if (m_bDeclare) aElement.setAttribute(CHTMLAttributes.DECLARE, CHTMLAttributeValues.DECLARE);
   if (StringHelper.hasText(m_sName)) aElement.setAttribute(CHTMLAttributes.NAME, m_sName);
   if (StringHelper.hasText(m_sStandBy))
     aElement.setAttribute(CHTMLAttributes.STANDBY, m_sStandBy);
   if (m_aType != null) aElement.setAttribute(CHTMLAttributes.TYPE, m_aType.getAsString());
   if (StringHelper.hasText(m_sUseMap)) aElement.setAttribute(CHTMLAttributes.USEMAP, m_sUseMap);
 }
Пример #5
0
 @Nonnull
 public String getAsString() {
   String ret = "";
   if (StringHelper.hasText(m_sResourceID)) ret += m_sResourceID;
   if (m_nLineNumber != ILLEGAL_NUMBER) {
     if (m_nColumnNumber != ILLEGAL_NUMBER)
       ret += "(" + m_nLineNumber + ":" + m_nColumnNumber + ")";
     else ret += "(" + m_nLineNumber + ":?)";
   }
   if (StringHelper.hasText(m_sField)) {
     if (ret.length() > 0) ret += " @ ";
     ret += m_sField;
   }
   return ret;
 }
Пример #6
0
 @Nullable
 @OverrideOnDemand
 public IHCNode getHeaderNode(@Nonnull final WPECTYPE aWPEC) {
   final String sText = getHeaderText(aWPEC);
   if (StringHelper.hasNoText(sText)) return null;
   return HCH1.create(sText);
 }
 @Nullable
 public static EMessageDigestAlgorithm getFromStringIgnoreCase(@Nullable final String sAlgorithm) {
   if (StringHelper.hasText(sAlgorithm))
     for (final EMessageDigestAlgorithm eMD : EMessageDigestAlgorithm.values())
       if (eMD.m_sAlgorithm.equalsIgnoreCase(sAlgorithm)) return eMD;
   return null;
 }
Пример #8
0
 /**
  * Check whether the passed text looks like it contains XHTML code. This is a heuristic check only
  * and does not perform actual parsing!
  *
  * @param sText The text to check.
  * @return <code>true</code> if the text looks like HTML
  */
 public static boolean looksLikeXHTML(@Nullable final String sText) {
   // If the text contains an open angle bracket followed by a character that
   // we think of it as HTML
   // (?s) enables the "dotall" mode - see Pattern.DOTALL
   return StringHelper.hasText(sText)
       && RegExHelper.stringMatchesPattern("(?s).*<[a-zA-Z].+", sText);
 }
Пример #9
0
 @Override
 protected void applyProperties(
     final IMicroElement aElement, final IHCConversionSettingsToNode aConversionSettings) {
   super.applyProperties(aElement, aConversionSettings);
   if (StringHelper.hasText(m_sHref)) aElement.setAttribute(CHTMLAttributes.HREF, m_sHref);
   if (m_aTarget != null) aElement.setAttribute(CHTMLAttributes.TARGET, m_aTarget.getAttrValue());
 }
Пример #10
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(), "_");
  }
Пример #11
0
 @Override
 public String toString() {
   return new ToStringGenerator(this)
       .append("name", m_sEntityName)
       .append("char", "0x" + StringHelper.getHexStringLeadingZero(m_cChar, 4))
       .append("description", m_sDescription)
       .toString();
 }
Пример #12
0
  /**
   * Create a new MockHttpSession.
   *
   * @param aServletContext the ServletContext that the session runs in
   * @param sID a unique identifier for this session
   */
  public MockHttpSession(
      @Nullable final ServletContext aServletContext, @Nullable final String sID) {
    m_aServletContext = aServletContext;
    m_sID = StringHelper.hasText(sID) ? sID : GlobalIDFactory.getNewStringID();

    final HttpSessionEvent aHSE = new HttpSessionEvent(this);
    for (final HttpSessionListener aListener : MockHttpListener.getAllHttpSessionListeners())
      aListener.sessionCreated(aHSE);
  }
 @Nonnull
 private static String _getAsString(@Nonnull final Set<Character> aInvalidChars) {
   if (ContainerHelper.isEmpty(aInvalidChars)) return "NONE";
   final StringBuilder aSB = new StringBuilder();
   for (final Character aChar : aInvalidChars) {
     if (aSB.length() > 0) aSB.append(", ");
     final int nChar = aChar.charValue();
     aSB.append("0x").append(StringHelper.getHexStringLeadingZero(nChar, 2));
   }
   return aSB.toString();
 }
Пример #14
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;
  }
Пример #15
0
  static {
    for (final EHTMLEntity e : values()) {
      final String sEntityRef = e.m_sEntityReference;
      final Character aChar = e.getCharObj();

      if (s_aEntityRefToEntityMap.put(sEntityRef, e) != null)
        throw new IllegalStateException(
            "Another entity reference '" + sEntityRef + "' is already contained!");

      if (s_aCharToEntityMap.put(aChar, e) != null)
        throw new IllegalStateException(
            "Another entity reference for '"
                + "0x"
                + StringHelper.getHexStringLeadingZero(e.m_cChar, 4)
                + "' is already contained!");

      if (s_aEntityRefToCharMap.put(sEntityRef, aChar) != null)
        throw new IllegalStateException(
            "Another char for '" + sEntityRef + "' is already contained!");

      if (s_aEntityRefToCharStringMap.put(sEntityRef, aChar.toString()) != null)
        throw new IllegalStateException(
            "Another char for '" + sEntityRef + "' is already contained!");

      if (s_aCharToEntityRefMap.put(aChar, sEntityRef) != null)
        throw new IllegalStateException(
            "Another entity reference for '"
                + "0x"
                + StringHelper.getHexStringLeadingZero(e.m_cChar, 4)
                + "' is already contained!");

      if (s_aCharStringToEntityRefMap.put(aChar.toString(), sEntityRef) != null)
        throw new IllegalStateException(
            "Another entity reference for '"
                + "0x"
                + StringHelper.getHexStringLeadingZero(e.m_cChar, 4)
                + "' is already contained!");
    }
  }
Пример #16
0
  @Nullable
  public static String beanLowerCaseFirstChar(@Nullable final String s) {
    final int nLength = StringHelper.getLength(s);
    if (nLength == 0) return s;

    // The whole string can be lower-cased
    if (nLength == 1) return s.toLowerCase(Locale.US);

    // If the second char is upper case, don't change the case...
    if (Character.isUpperCase(s.charAt(1))) return s;

    // lower case the first letter
    return Character.toLowerCase(s.charAt(0)) + s.substring(1);
  }
    /**
     * Initialization method.
     *
     * @param sSearchTerms The search term string. It is internally separated into multiple tokens
     *     by using a "\s+" regular expression.
     * @return this
     */
    @Nonnull
    protected Finder initialize(@Nonnull @Nonempty final String sSearchTerms) {
      if (StringHelper.hasNoTextAfterTrim(sSearchTerms))
        throw new IllegalArgumentException("SearchTerms");

      // Split search terms by white spaces
      m_aSearchTerms = RegExHelper.getSplitToArray(sSearchTerms.trim(), "\\s+");
      if (m_aSearchTerms.length == 0)
        throw new IllegalStateException(
            "Weird - splitting of '" + sSearchTerms.trim() + "' failed!");
      for (final String sSearchTerm : m_aSearchTerms)
        if (sSearchTerm.length() == 0)
          throw new IllegalArgumentException("Weird - empty search term present!");
      return this;
    }
 @Nonnull
 private static IResourceError _buildError(
     @Nonnull final TransformerException ex,
     @Nonnull final EErrorLevel eErrorLevel,
     @Nonnull final IHasDisplayText aErrorMsg) {
   final SourceLocator aLocator = ex.getLocator();
   final IResourceLocation aLocation =
       aLocator != null
           ? new ResourceLocation(
               StringHelper.getConcatenatedOnDemand(
                   aLocator.getPublicId(), "/", aLocator.getSystemId()),
               aLocator.getLineNumber(),
               aLocator.getColumnNumber())
           : new ResourceLocation(ex.getLocationAsString());
   return new ResourceError(aLocation, eErrorLevel, aErrorMsg, ex);
 }
Пример #19
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);
       }
     }
   }
 }
Пример #20
0
 /**
  * Parse the given fragment as XHTML 1.1. This is a sanity method for {@link
  * #parseXHTMLFragment(String)} with the predefined XHTML 1.1 document type.
  *
  * @param sXHTMLFragment The XHTML fragment to parse. May be <code>null</code>.
  * @return <code>null</code> if parsing failed.
  */
 @Nullable
 public IMicroDocument parseXHTMLFragment(@Nullable final String sXHTMLFragment) {
   // Build mini HTML and insert fragment in the middle.
   // If parsing succeeds, it is considered valid HTML.
   final String sHTMLNamespaceURI = this.m_eHTMLVersion.getNamespaceURI();
   final String sXHTML =
       XMLEmitterPhloc.getDocTypeHTMLRepresentation(
               EXMLSerializeVersion.XML_10,
               EXMLIncorrectCharacterHandling.DEFAULT,
               this.m_eHTMLVersion.getDocType())
           + "<html"
           + (sHTMLNamespaceURI != null
               ? ' ' + CXML.XML_ATTR_XMLNS + "=\"" + sHTMLNamespaceURI + '"'
               : "")
           + "><head><title></title></head><body>"
           + StringHelper.getNotNull(sXHTMLFragment)
           + "</body></html>";
   return parseXHTMLDocument(sXHTML);
 }
Пример #21
0
  /**
   * 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
  @Nonnull
  protected final IAjaxResponse mainHandleRequest(@Nonnull final LECTYPE aLEC) throws Exception {
    final String sOriginalQuery = getQueryString(aLEC);
    if (StringHelper.hasNoTextAfterTrim(sOriginalQuery)) {
      // May happen when the user enters "  " (only spaces)
      return AjaxDefaultResponse.createSuccess(aLEC.getRequestScope(), new JsonObject());
    }

    // Create the main Finder object
    final Finder aFinder = createFinder(sOriginalQuery, aLEC);

    // Map from ID to name
    final List<? extends TypeaheadDatum> aMatchingDatums = getAllMatchingDatums(aFinder, aLEC);

    // Convert to JSON, sorted by display name using the current display locale
    final JsonArray ret = new JsonArray();
    for (final TypeaheadDatum aDatum : aMatchingDatums) ret.add(aDatum.getAsJson());

    // Use the simple response, because the response layout is predefined!
    return new AjaxSimpleResponse(true, ret);
  }
  @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)));
      }
    }
  }
Пример #24
0
 @Nonnull
 public HCTextNode setText(@Nullable final String sText) {
   m_sText = StringHelper.getNotNull(sText);
   return this;
 }
Пример #25
0
 @Nonnull
 public HCTextNode prependText(@Nullable final String sText) {
   if (StringHelper.hasText(sText)) m_sText = sText + m_sText;
   return this;
 }
Пример #26
0
  /**
   * 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;
  }
Пример #27
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;
 }
 /**
  * Match method for a single string. By default a case-insensitive lookup is performed.
  *
  * @param sSource The source string to search the search term in. Never <code>null</code>.
  * @param sSearchTerm The search term to be searched. Never <code>null</code>.
  * @return <code>true</code> if the source string contains the search term, <code>false</code>
  *     otherwise.
  */
 @OverrideOnDemand
 protected boolean isSingleStringMatching(
     @Nonnull final String sSource, @Nonnull final String sSearchTerm) {
   return StringHelper.containsIgnoreCase(sSource, sSearchTerm, m_aSortLocale);
 }
Пример #29
0
 public MicroDataAware(@Nullable final CharSequence aText) {
   if (StringHelper.hasNoText(aText)) m_aSB = new StringBuilder();
   else m_aSB = new StringBuilder(aText);
 }
Пример #30
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";
 }