示例#1
0
  @Nonnull
  @Nonempty
  public String getAsCSSString(
      @Nonnull final ICSSWriterSettings aSettings, @Nonnegative final int nIndentLevel) {
    // Always ignore unknown rules?
    if (!aSettings.isWriteUnknownRules()) return "";

    final boolean bOptimizedOutput = aSettings.isOptimizedOutput();

    final StringBuilder aSB = new StringBuilder(m_sDeclaration);

    if (StringHelper.hasText(m_sParameterList)) aSB.append(' ').append(m_sParameterList);

    if (StringHelper.hasNoText(m_sBody)) {
      aSB.append(bOptimizedOutput ? "{}" : " {}\n");
    } else {
      // At least one rule present
      aSB.append(bOptimizedOutput ? "{" : " {\n");
      if (!bOptimizedOutput) aSB.append(aSettings.getIndent(nIndentLevel));
      aSB.append(m_sBody);
      if (!bOptimizedOutput)
        aSB.append('\n' + (nIndentLevel > 0 ? aSettings.getIndent(nIndentLevel - 1) : ""));
      aSB.append('}');
      if (!bOptimizedOutput) aSB.append('\n');
    }
    return aSB.toString();
  }
示例#2
0
 /**
  * Get the data path to be used for this application. By default the servlet context
  * init-parameter {@link #INIT_PARAMETER_DATA_PATH} is evaluated. If non is present, the servlet
  * context path is used.
  *
  * @param aSC The servlet context. Never <code>null</code>.
  * @return The data path to use. May neither be <code>null</code> nor empty.
  */
 @Nonnull
 @Nonempty
 @OverrideOnDemand
 protected String getDataPath(@Nonnull final ServletContext aSC) {
   String sDataPath = aSC.getInitParameter(INIT_PARAMETER_DATA_PATH);
   if (StringHelper.hasNoText(sDataPath)) {
     // Use legacy parameter name
     sDataPath = aSC.getInitParameter("storagePath");
     if (StringHelper.hasText(sDataPath)) {
       s_aLogger.error(
           "You are using the old 'storagePath' parameter. Please use '"
               + INIT_PARAMETER_DATA_PATH
               + "' instead!");
     }
   }
   if (StringHelper.hasNoText(sDataPath)) {
     // No storage path provided in web.xml
     sDataPath = getServletContextPath(aSC);
     if (GlobalDebug.isDebugMode() && s_aLogger.isInfoEnabled())
       s_aLogger.info(
           "No servlet context init-parameter '"
               + INIT_PARAMETER_DATA_PATH
               + "' found! Defaulting to servlet context path '"
               + sDataPath
               + "'");
   }
   return sDataPath;
 }
示例#3
0
  @Nullable
  @ReturnsMutableCopy
  public static byte[] getDecodedASCIIHex(@Nullable final byte[] aEncodedBuffer) {
    if (aEncodedBuffer == null) return null;

    final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream();
    try {
      boolean bFirstByte = true;
      int nFirstByte = 0;
      for (final byte nEncByte : aEncodedBuffer) {
        if (nEncByte == '>') break;

        // Ignore whitespaces
        if (Character.isWhitespace(nEncByte)) continue;

        final byte nDecByte = (byte) StringHelper.getHexValue((char) nEncByte);
        if (nDecByte == CGlobal.ILLEGAL_UINT)
          throw new DecodeException(
              "Failed to convert byte '"
                  + nEncByte
                  + "/"
                  + ((char) nEncByte)
                  + "' to hex value in ASCIIHexDecode");
        if (bFirstByte) nFirstByte = nDecByte;
        else aBAOS.write((byte) (nFirstByte << 4 | nDecByte));
        bFirstByte = !bFirstByte;
      }

      // Write trailing byte
      if (!bFirstByte) aBAOS.write((byte) (nFirstByte << 4));
      return aBAOS.toByteArray();
    } finally {
      StreamHelper.close(aBAOS);
    }
  }
示例#4
0
 static {
   final String sHttpDumpDirectory =
       SystemProperties.getPropertyValueOrNull("AS2.httpDumpDirectory");
   if (StringHelper.hasText(sHttpDumpDirectory)) {
     final File aDumpDirectory = new File(sHttpDumpDirectory);
     IOHelper.getFileOperationManager().createDirIfNotExisting(aDumpDirectory);
     setHTTPIncomingDumper(new HTTPIncomingDumperDirectoryBased(aDumpDirectory));
   }
 }
示例#5
0
 @Nonnull
 protected String getServletContextPath(@Nonnull final ServletContext aSC) {
   String sPath = aSC.getRealPath(".");
   if (sPath == null) {
     // Fallback for Undertow
     sPath = aSC.getRealPath("");
   }
   if (StringHelper.hasNoText(sPath))
     throw new IllegalStateException("Failed to determine real path of ServletContext " + aSC);
   return sPath;
 }
示例#6
0
 /**
  * Returns the XML representation of the segment.
  *
  * @return <code>String</code>
  */
 public String toXML() {
   final StringBuilder aSB = new StringBuilder();
   final String sFirst = m_aElements.get(0);
   aSB.append("<" + sFirst + ">");
   for (int i = 1; i < m_aElements.size(); i++) {
     final String sTag = sFirst + StringHelper.getLeadingZero(i, 2);
     aSB.append("<" + sTag + "><![CDATA[");
     aSB.append(m_aElements.get(i));
     aSB.append("]]></" + sTag + ">");
   }
   aSB.append("</" + sFirst + ">");
   return aSB.toString();
 }
示例#7
0
 @OverrideOnDemand
 @OverridingMethodsMustInvokeSuper
 protected void initPaths(@Nonnull final ServletContext aSC) {
   // Get the ServletContext base path
   final String sServletContextPath = getServletContextPath(aSC);
   // Get the data path
   final String sDataPath = getDataPath(aSC);
   if (StringHelper.hasNoText(sDataPath))
     throw new InitializationException("No data path was provided!");
   final File aDataPath = new File(sDataPath).getAbsoluteFile();
   // Should the file access check be performed?
   final boolean bFileAccessCheck = shouldCheckFileAccess(aSC);
   // Init the IO layer
   WebFileIO.initPaths(aDataPath, new File(sServletContextPath), bFileAccessCheck);
 }
  /**
   * Applies an RFC 1522 compliant decoding scheme to the given string of text.
   *
   * <p>This method processes the "encoded-word" header common to all the RFC 1522 codecs and then
   * invokes {@link #getDecoded(byte [])} method of a concrete class to perform the specific
   * decoding.
   *
   * @param sEncodedText a string to decode
   * @return A new decoded String or {@code null} if the input is {@code null}.
   * @throws DecodeException thrown if there is an error condition during the decoding process.
   */
  @Nullable
  public String getDecodedText(@Nullable final String sEncodedText) throws DecodeException {
    if (sEncodedText == null) return null;

    ValueEnforcer.isTrue(
        sEncodedText.startsWith(PREFIX),
        "RFC 1522 violation: malformed encoded content. Prefix missing.");
    ValueEnforcer.isTrue(
        sEncodedText.endsWith(POSTFIX),
        "RFC 1522 violation: malformed encoded content. Postfix missing.");

    int nFrom = PREFIX.length();
    final int nTerminator = sEncodedText.length() - POSTFIX.length();

    // Read charset
    int nTo = sEncodedText.indexOf(SEP, nFrom);
    if (nTo == nTerminator)
      throw new DecodeException("RFC 1522 violation: charset token not found");
    final String sDestCharset = sEncodedText.substring(nFrom, nTo);
    if (StringHelper.hasNoText(sDestCharset))
      throw new DecodeException("RFC 1522 violation: charset not specified");
    final Charset aDestCharset = CharsetManager.getCharsetFromNameOrNull(sDestCharset);
    if (aDestCharset == null)
      throw new DecodeException("Failed to resolve charset '" + sDestCharset + "'");

    // Read encoding
    nFrom = nTo + 1;
    nTo = sEncodedText.indexOf(SEP, nFrom);
    if (nTo == nTerminator)
      throw new DecodeException("RFC 1522 violation: encoding token not found");
    final String sEncoding = sEncodedText.substring(nFrom, nTo);
    if (!getRFC1522Encoding().equalsIgnoreCase(sEncoding))
      throw new DecodeException("This codec cannot decode '" + sEncoding + "' encoded content");

    // Read encoded data
    nFrom = nTo + 1;
    nTo = sEncodedText.indexOf(SEP, nFrom);
    final byte[] aEncodedBytes =
        CharsetManager.getAsBytes(
            sEncodedText.substring(nFrom, nTo), CCharset.CHARSET_US_ASCII_OBJ);
    final byte[] aDecodedBytes = getDecoded(aEncodedBytes);
    return CharsetManager.getAsString(aDecodedBytes, aDestCharset);
  }
示例#9
0
  @Test
  public void testEntityExpansionLimit() throws SAXException {
    // The XML with XXE problem
    final String sXML =
        "<?xml version='1.0' encoding='utf-8'?>"
            + "<!DOCTYPE root ["
            + " <!ELEMENT root ANY >"
            + " <!ENTITY e1 \"value\" >"
            + " <!ENTITY e2 \"&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;\" >"
            + " <!ENTITY e3 \"&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;\" >"
            + " <!ENTITY e4 \"&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;\" >"
            + " <!ENTITY e5 \"&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;\" >"
            + " <!ENTITY e6 \"&e5;&e5;&e5;&e5;&e5;&e5;&e5;&e5;&e5;&e5;\" >"
            // +
            // " <!ENTITY e7 \"&e6;&e6;&e6;&e6;&e6;&e6;&e6;&e6;&e6;&e6;\" >"
            // +
            // " <!ENTITY e8 \"&e7;&e7;&e7;&e7;&e7;&e7;&e7;&e7;&e7;&e7;\" >"
            // +
            // " <!ENTITY e9 \"&e8;&e8;&e8;&e8;&e8;&e8;&e8;&e8;&e8;&e8;\" >"
            // +
            // " <!ENTITY e10 \"&e9;&e9;&e9;&e9;&e9;&e9;&e9;&e9;&e9;&e9;\" >"
            + "]>"
            + "<root>&e6;</root>";
    final DOMReaderSettings aDRS = new DOMReaderSettings();

    // Read successful - entity expansion!
    final Document aDoc = DOMReader.readXMLDOM(sXML, aDRS);
    assertNotNull(aDoc);
    assertEquals(
        StringHelper.getRepeated("value", (int) Math.pow(10, 5)),
        aDoc.getDocumentElement().getTextContent());

    // Should fail because too many entity expansions
    try {
      DOMReader.readXMLDOM(
          sXML, aDRS.getClone().setFeatureValues(EXMLParserFeature.AVOID_DOS_SETTINGS));
      fail();
    } catch (final SAXParseException ex) {
      // Expected
      assertTrue(ex.getMessage().contains("entity expansions"));
    }
  }
示例#10
0
 /**
  * Adds <code>String</code> with elements to the segment. The elements are added at the end of the
  * elements in the current segment. e.g. <code>addElements("ISA*ISA01*ISA02");</code>
  *
  * @param s elements to be split by the element separator
  * @return boolean if all were added
  */
 public boolean addElements(final String s) {
   return addElements(StringHelper.getExploded(m_aContext.getElementSeparator(), s));
 }
示例#11
0
 /** Removes empty and null elements at the end of segment */
 private void _removeTrailingEmptyElements() {
   for (int i = m_aElements.size() - 1; i >= 0; i--) {
     if (StringHelper.hasNoText(m_aElements.get(i))) m_aElements.remove(i);
     else break;
   }
 }
示例#12
0
 @Nullable
 public static UserDataObject createConditional(@Nullable final String sPath) {
   if (StringHelper.hasNoText(sPath)) return null;
   return new UserDataObject(sPath);
 }
示例#13
0
  @Override
  protected void fillContent(final WebPageExecutionContext aWPEC) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final IIdentifierFactory aIdentifierFactory = PDMetaManager.getIdentifierFactory();

    {
      final BootstrapRow aHeaderRow = aNodeList.addAndReturnChild(new BootstrapRow());
      // The logo
      aHeaderRow.createColumn(12, 12, 1, 2).addClass(CBootstrapCSS.HIDDEN_SM);
      aHeaderRow
          .createColumn(12, 6, 5, 4)
          .addChild(
              new HCExtImg(new SimpleURL("/imgs/pd-logo.png")).addClass(CBootstrapCSS.PULL_LEFT));
      aHeaderRow
          .createColumn(12, 6, 5, 4)
          .addChild(
              new HCExtImg(new SimpleURL("/imgs/peppol.png")).addClass(CBootstrapCSS.PULL_RIGHT));
      aHeaderRow.createColumn(12, 12, 1, 2).addClass(CBootstrapCSS.HIDDEN_SM);
    }

    final String sQuery = aWPEC.getAttributeAsString(FIELD_QUERY);
    final String sParticipantID = aWPEC.getAttributeAsString(FIELD_PARTICIPANT_ID);
    boolean bShowQuery = true;

    if (aWPEC.hasAction(CPageParam.ACTION_VIEW) && StringHelper.hasText(sParticipantID)) {
      final IParticipantIdentifier aParticipantID =
          aIdentifierFactory.parseParticipantIdentifier(sParticipantID);
      if (aParticipantID != null) {
        // Show small query box
        aNodeList.addChild(_createSmallQueryBox(aWPEC));

        // Search document matching participant ID
        final ICommonsList<PDStoredDocument> aResultDocs =
            PDMetaManager.getStorageMgr().getAllDocumentsOfParticipant(aParticipantID);
        // Group by participant ID
        final IMultiMapListBased<IParticipantIdentifier, PDStoredDocument> aGroupedDocs =
            PDStorageManager.getGroupedByParticipantID(aResultDocs);
        if (aGroupedDocs.isEmpty())
          s_aLogger.warn(
              "No stored document matches participant identifier '" + sParticipantID + "'");
        else {
          if (aGroupedDocs.size() > 1)
            s_aLogger.warn(
                "Found "
                    + aGroupedDocs.size()
                    + " entries for participant identifier '"
                    + sParticipantID
                    + "' - weird");
          // Get the first one
          final List<PDStoredDocument> aDocuments =
              CollectionHelper.getFirstElement(aGroupedDocs.values());
          bShowQuery = false;

          aNodeList.addChild(getUIHandler().createPageHeader("Details for " + sParticipantID));

          final BootstrapTabBox aTabBox = aNodeList.addAndReturnChild(new BootstrapTabBox());

          // Business information
          {
            final HCNodeList aOL = new HCNodeList();
            int nIndex = 1;
            for (final PDStoredDocument aStoredDoc : aDocuments) {
              final BootstrapPanel aPanel = aOL.addAndReturnChild(new BootstrapPanel());
              if (aDocuments.size() > 1)
                aPanel.getOrCreateHeader().addChild("Business information entity " + nIndex);
              aPanel
                  .getBody()
                  .addChild(PDCommonUI.showBusinessInfoDetails(aStoredDoc, aDisplayLocale));
              ++nIndex;
            }
            // Add whole list or just the first item?
            final IHCNode aTabLabel =
                new HCSpan()
                    .addChild("Business information ")
                    .addChild(new BootstrapBadge().addChild(Integer.toString(aDocuments.size())));
            aTabBox.addTab("businessinfo", aTabLabel, aOL, true);
          }

          // Document types
          {
            final HCOL aDocTypeCtrl = new HCOL();
            final List<IDocumentTypeIdentifier> aDocTypeIDs =
                CollectionHelper.getSorted(
                    aResultDocs.get(0).getAllDocumentTypeIDs(),
                    IDocumentTypeIdentifier.comparator());
            for (final IDocumentTypeIdentifier aDocTypeID : aDocTypeIDs) {
              final IHCLI<?> aLI = aDocTypeCtrl.addItem();
              aLI.addChild(PDCommonUI.getDocumentTypeID(aDocTypeID));
              try {
                final IPeppolDocumentTypeIdentifierParts aParts =
                    PeppolIdentifierHelper.getDocumentTypeIdentifierParts(aDocTypeID);
                aLI.addChild(PDCommonUI.getDocumentTypeIDDetails(aParts));
              } catch (final IllegalArgumentException ex) {
                // Happens for non-PEPPOL identifiers
              }
            }
            aTabBox.addTab(
                "doctypes",
                new HCSpan()
                    .addChild("Document types ")
                    .addChild(new BootstrapBadge().addChild(Integer.toString(aDocTypeIDs.size()))),
                aDocTypeCtrl.hasChildren()
                    ? aDocTypeCtrl
                    : new BootstrapWarnBox()
                        .addChild("No document types available for this participant"),
                false);
          }
        }
      } else s_aLogger.warn("Failed to parse participant identifier '" + sParticipantID + "'");
    }

    if (bShowQuery) {
      if (StringHelper.hasText(sQuery)) {
        // Show small query box
        aNodeList.addChild(_createSmallQueryBox(aWPEC));

        s_aLogger.info("Searching for '" + sQuery + "'");

        // Build Lucene query
        final Query aLuceneQuery =
            PDQueryManager.convertQueryStringToLuceneQuery(PDMetaManager.getLucene(), sQuery);

        if (s_aLogger.isDebugEnabled())
          s_aLogger.debug("Created query for '" + sQuery + "' is <" + aLuceneQuery + ">");

        // Search all documents
        final ICommonsList<PDStoredDocument> aResultDocs =
            PDMetaManager.getStorageMgr().getAllDocuments(aLuceneQuery);

        s_aLogger.info(
            "  Result for <" + aLuceneQuery + "> are " + aResultDocs.size() + " documents");

        // Group by participant ID
        final IMultiMapListBased<IParticipantIdentifier, PDStoredDocument> aGroupedDocs =
            PDStorageManager.getGroupedByParticipantID(aResultDocs);

        final int nMaxResults = 10;

        // Display results
        if (aGroupedDocs.isEmpty()) {
          aNodeList.addChild(
              new BootstrapInfoBox()
                  .addChild("No search results found for query '" + sQuery + "'"));
        } else {
          final HCOL aOL = new HCOL().setStart(1);
          for (final Map.Entry<IParticipantIdentifier, ICommonsList<PDStoredDocument>> aEntry :
              aGroupedDocs.entrySet()) {
            final IParticipantIdentifier aDocParticipantID = aEntry.getKey();
            final ICommonsList<PDStoredDocument> aDocs = aEntry.getValue();

            // Start result document
            final HCDiv aResultItem = new HCDiv().addClass(CSS_CLASS_RESULT_DOC);
            final HCDiv aHeadRow = aResultItem.addAndReturnChild(new HCDiv());
            aHeadRow.addChild(aDocParticipantID.getURIEncoded());
            if (aDocs.size() > 1) aHeadRow.addChild(" (" + aDocs.size() + " entities)");
            aHeadRow
                .addChild(" ")
                .addChild(
                    new BootstrapButton(EBootstrapButtonType.SUCCESS, EBootstrapButtonSize.MINI)
                        .addChild("Show details")
                        .setIcon(EDefaultIcon.MAGNIFIER)
                        .setOnClick(
                            aWPEC
                                .getSelfHref()
                                .add(FIELD_QUERY, sQuery)
                                .add(CPageParam.PARAM_ACTION, CPageParam.ACTION_VIEW)
                                .add(FIELD_PARTICIPANT_ID, aDocParticipantID.getURIEncoded())));

            // Show all entities of the stored document
            final HCUL aUL = aResultItem.addAndReturnChild(new HCUL());
            for (final PDStoredDocument aStoredDoc : aEntry.getValue()) {
              final IHCLI<?> aLI =
                  aUL.addAndReturnItem(new HCLI().addClass(CSS_CLASS_RESULT_DOC_HEADER));
              final HCDiv aDocHeadRow = new HCDiv();
              if (aStoredDoc.hasCountryCode()) {
                // Add country flag (if available)
                aDocHeadRow.addChild(PDCommonUI.getFlagNode(aStoredDoc.getCountryCode()));
                aDocHeadRow.addChild(
                    new HCSpan()
                        .addChild(aStoredDoc.getCountryCode())
                        .addClass(CSS_CLASS_RESULT_DOC_COUNTRY_CODE));
              }
              if (aStoredDoc.hasName())
                aDocHeadRow.addChild(
                    new HCSpan()
                        .addChild(aStoredDoc.getName())
                        .addClass(CSS_CLASS_RESULT_DOC_NAME));
              if (aDocHeadRow.hasChildren()) aLI.addChild(aDocHeadRow);

              if (aStoredDoc.hasGeoInfo())
                aLI.addChild(
                    new HCDiv()
                        .addChildren(HCExtHelper.nl2divList(aStoredDoc.getGeoInfo()))
                        .addClass(CSS_CLASS_RESULT_DOC_GEOINFO));
              if (aStoredDoc.hasAdditionalInformation())
                aLI.addChild(
                    new HCDiv()
                        .addChildren(HCExtHelper.nl2divList(aStoredDoc.getAdditionalInformation()))
                        .addClass(CSS_CLASS_RESULT_DOC_FREETEXT));
            }

            aOL.addItem(aResultItem);

            // Break at 10 results
            if (aOL.getChildCount() >= nMaxResults) break;
          }
          aNodeList.addChild(aOL);
        }
      } else {
        // Show big query box
        final HCForm aBigQueryBox =
            new HCForm().setAction(aWPEC.getSelfHref()).setMethod(EHCFormMethod.GET);
        aBigQueryBox.addChild(
            new HCDiv().addClass(CSS_CLASS_BIG_QUERY_BOX).addChild(_createQueryEdit()));
        aBigQueryBox.addChild(
            new HCDiv()
                .addClass(CSS_CLASS_BIG_QUERY_BUTTONS)
                .addChild(
                    new BootstrapSubmitButton()
                        .addChild("Search PEPPOL Directory")
                        .setIcon(EDefaultIcon.MAGNIFIER)));

        final BootstrapRow aBodyRow = aNodeList.addAndReturnChild(new BootstrapRow());
        aBodyRow.createColumn(12, 1, 2, 3).addClass(CBootstrapCSS.HIDDEN_XS);
        aBodyRow.createColumn(12, 10, 8, 6).addChild(aBigQueryBox);
        aBodyRow.createColumn(12, 1, 2, 3).addClass(CBootstrapCSS.HIDDEN_XS);
      }
    }
  }
  /**
   * Login the passed user and require a set of certain roles, the used needs to have to login here.
   *
   * @param aUser The user to log-in. May be <code>null</code>. When the user is <code>null</code>
   *     the login must fail.
   * @param sPlainTextPassword Plain text password to use. May be <code>null</code>.
   * @param aRequiredRoleIDs A set of required role IDs, the user needs to have. May be <code>null
   *     </code>.
   * @return Never <code>null</code> login status.
   */
  @Nonnull
  public ELoginResult loginUser(
      @Nullable final IUser aUser,
      @Nullable final String sPlainTextPassword,
      @Nullable final Collection<String> aRequiredRoleIDs) {
    if (aUser == null) return ELoginResult.USER_NOT_EXISTING;

    final String sUserID = aUser.getID();

    // Deleted user?
    if (aUser.isDeleted()) {
      AuditHelper.onAuditExecuteFailure("login", sUserID, "user-is-deleted");
      return _onLoginError(sUserID, ELoginResult.USER_IS_DELETED);
    }

    // Disabled user?
    if (aUser.isDisabled()) {
      AuditHelper.onAuditExecuteFailure("login", sUserID, "user-is-disabled");
      return _onLoginError(sUserID, ELoginResult.USER_IS_DISABLED);
    }

    // Are all roles present?
    if (!SecurityHelper.hasUserAllRoles(sUserID, aRequiredRoleIDs)) {
      AuditHelper.onAuditExecuteFailure(
          "login",
          sUserID,
          "user-is-missing-required-roles",
          StringHelper.getToString(aRequiredRoleIDs));
      return _onLoginError(sUserID, ELoginResult.USER_IS_MISSING_ROLE);
    }

    // Check the password
    final UserManager aUserMgr = PhotonSecurityManager.getUserMgr();
    if (!aUserMgr.areUserIDAndPasswordValid(sUserID, sPlainTextPassword)) {
      AuditHelper.onAuditExecuteFailure("login", sUserID, "invalid-password");
      return _onLoginError(sUserID, ELoginResult.INVALID_PASSWORD);
    }

    // Check if the password hash needs to be updated
    final String sExistingPasswordHashAlgorithmName = aUser.getPasswordHash().getAlgorithmName();
    final String sDefaultPasswordHashAlgorithmName =
        GlobalPasswordSettings.getPasswordHashCreatorManager()
            .getDefaultPasswordHashCreatorAlgorithmName();
    if (!sExistingPasswordHashAlgorithmName.equals(sDefaultPasswordHashAlgorithmName)) {
      // This implicitly implies using the default hash creator algorithm
      // This automatically saves the file
      aUserMgr.setUserPassword(sUserID, sPlainTextPassword);
      s_aLogger.info(
          "Updated password hash of user '"
              + sUserID
              + "' from algorithm '"
              + sExistingPasswordHashAlgorithmName
              + "' to '"
              + sDefaultPasswordHashAlgorithmName
              + "'");
    }

    boolean bLoggedOutUser = false;
    LoginInfo aInfo;
    m_aRWLock.writeLock().lock();
    try {
      if (m_aLoggedInUsers.containsKey(sUserID)) {
        // The user is already logged in
        if (isLogoutAlreadyLoggedInUser()) {
          // Explicitly log out
          logoutUser(sUserID);

          // Just a short check
          if (m_aLoggedInUsers.containsKey(sUserID))
            throw new IllegalStateException("Failed to logout '" + sUserID + "'");

          AuditHelper.onAuditExecuteSuccess("logout-in-login", sUserID);
          bLoggedOutUser = true;
        } else {
          AuditHelper.onAuditExecuteFailure("login", sUserID, "user-already-logged-in");
          return _onLoginError(sUserID, ELoginResult.USER_ALREADY_LOGGED_IN);
        }
      }

      final SessionUserHolder aSUH = SessionUserHolder.getInstance();
      if (aSUH.hasUser()) {
        // This session already has a user
        s_aLogger.warn(
            "The session user holder already has the user ID '"
                + aSUH.getUserID()
                + "' so the new ID '"
                + sUserID
                + "' will not be set!");
        AuditHelper.onAuditExecuteFailure("login", sUserID, "session-already-has-user");
        return _onLoginError(sUserID, ELoginResult.SESSION_ALREADY_HAS_USER);
      }

      aInfo = new LoginInfo(aUser, ScopeManager.getSessionScope());
      m_aLoggedInUsers.put(sUserID, aInfo);
      aSUH.setUser(this, aUser);
    } finally {
      m_aRWLock.writeLock().unlock();
    }

    s_aLogger.info(
        "Logged in user '" + sUserID + "' with login name '" + aUser.getLoginName() + "'");
    AuditHelper.onAuditExecuteSuccess("login", sUserID, aUser.getLoginName());

    // Execute callback as the very last action
    for (final IUserLoginCallback aUserLoginCallback : m_aUserLoginCallbacks.getAllCallbacks())
      try {
        aUserLoginCallback.onUserLogin(aInfo);
      } catch (final Throwable t) {
        s_aLogger.error(
            "Failed to invoke onUserLogin callback on "
                + aUserLoginCallback.toString()
                + "("
                + aInfo.toString()
                + ")",
            t);
      }

    return bLoggedOutUser ? ELoginResult.SUCCESS_WITH_LOGOUT : ELoginResult.SUCCESS;
  }
示例#15
0
  public final void contextInitialized(@Nonnull final ServletContextEvent aSCE) {
    final ServletContext aSC = aSCE.getServletContext();

    if (s_aInited.getAndSet(true))
      throw new IllegalStateException("WebAppListener was already instantiated!");

    final StopWatch aSW = StopWatch.createdStarted();
    m_aInitializationStartDT = PDTFactory.getCurrentLocalDateTime();

    // set global debug/trace mode
    final boolean bDebugMode = StringParser.parseBool(getInitParameterDebug(aSC));
    final boolean bProductionMode = StringParser.parseBool(getInitParameterProduction(aSC));
    GlobalDebug.setDebugModeDirect(bDebugMode);
    GlobalDebug.setProductionModeDirect(bProductionMode);

    final boolean bNoStartupInfo = StringParser.parseBool(getInitParameterNoStartupInfo(aSC));
    if (!bNoStartupInfo) {
      // Requires the global debug things to be present
      logStartupInfo(aSC);
    }

    // StaticServerInfo
    {
      final String sInitParameter = getInitParameterServerURL(aSC, bProductionMode);
      if (StringHelper.hasText(sInitParameter)) {
        final URL aURL = URLHelper.getAsURL(sInitParameter);
        if (aURL != null) {
          StaticServerInfo.init(
              aURL.getProtocol(), aURL.getHost(), aURL.getPort(), aSC.getContextPath());
        } else
          s_aLogger.error(
              "The init-parameter for the server URL"
                  + (bProductionMode ? " (production mode)" : " (non-production mode)")
                  + "contains the non-URL value '"
                  + sInitParameter
                  + "'");
      }
    }

    // Call callback
    beforeContextInitialized(aSC);

    // begin global context
    WebScopeManager.onGlobalBegin(aSC);

    // Init IO
    initPaths(aSC);

    // Set persistent ID provider - must be done after IO is setup
    initGlobalIDFactory();

    // Callback
    afterContextInitialized(aSC);

    // Remember end time
    m_aInitializationEndDT = PDTFactory.getCurrentLocalDateTime();

    // Finally
    if (s_aLogger.isInfoEnabled())
      s_aLogger.info(
          "Servlet context '"
              + aSC.getServletContextName()
              + "' was initialized in "
              + aSW.stopAndGetMillis()
              + " milli seconds");
  }
  /**
   * Verify the content of all contained fields so that all know issues are captured before sending.
   * This method is automatically called before the message is send (see {@link
   * #sendSynchronous()}). All verification warnings and errors are handled via the message handler.
   *
   * @throws AS2ClientBuilderException In case the message handler throws an exception in case of an
   *     error.
   * @see #setMessageHandler(IAS2ClientBuilderMessageHandler)
   */
  public void verifyContent() throws AS2ClientBuilderException {
    if (m_aKeyStoreFile == null) m_aMessageHandler.error("No AS2 key store is defined");
    else {
      if (!m_aKeyStoreFile.exists())
        m_aMessageHandler.error(
            "The provided AS2 key store '"
                + m_aKeyStoreFile.getAbsolutePath()
                + "' does not exist.");
      else if (!m_aKeyStoreFile.isFile())
        m_aMessageHandler.error(
            "The provided AS2 key store '"
                + m_aKeyStoreFile.getAbsolutePath()
                + "' is not a file but potentially a directory.");
      else if (!m_aKeyStoreFile.canWrite())
        m_aMessageHandler.error(
            "The provided AS2 key store '"
                + m_aKeyStoreFile.getAbsolutePath()
                + "' is not writable. As it is dynamically modified, it must be writable.");
    }
    if (m_sKeyStorePassword == null)
      m_aMessageHandler.error(
          "No key store password provided. If you need an empty password, please provide an empty String!");

    if (StringHelper.hasNoText(m_sAS2Subject))
      m_aMessageHandler.error("The AS2 message subject is missing");

    if (StringHelper.hasNoText(m_sSenderAS2ID))
      m_aMessageHandler.error("The AS2 sender ID is missing");
    else if (!m_sSenderAS2ID.startsWith(APP_PREFIX))
      m_aMessageHandler.warn(
          "The AS2 sender ID '"
              + m_sSenderAS2ID
              + "' should start with '"
              + APP_PREFIX
              + "' as required by the PEPPOL specification");

    if (StringHelper.hasNoText(m_sSenderAS2Email))
      m_aMessageHandler.error("The AS2 sender email address is missing");
    else if (!EmailAddressHelper.isValid(m_sSenderAS2Email))
      m_aMessageHandler.warn(
          "The AS2 sender email address '"
              + m_sSenderAS2Email
              + "' seems to be an invalid email address.");

    if (StringHelper.hasNoText(m_sSenderAS2KeyAlias))
      m_aMessageHandler.error("The AS2 sender key alias is missing");
    else if (!m_sSenderAS2KeyAlias.startsWith(APP_PREFIX))
      m_aMessageHandler.warn(
          "The AS2 sender key alias '"
              + m_sSenderAS2KeyAlias
              + "' should start with '"
              + APP_PREFIX
              + "' for the use with the dynamic AS2 partnerships");
    else if (m_sSenderAS2ID != null && !m_sSenderAS2ID.equals(m_sSenderAS2KeyAlias))
      m_aMessageHandler.warn(
          "The AS2 sender key alias ('"
              + m_sSenderAS2KeyAlias
              + "') should match the AS2 sender ID ('"
              + m_sSenderAS2ID
              + "')");

    if (StringHelper.hasNoText(m_sReceiverAS2ID))
      m_aMessageHandler.error("The AS2 receiver ID is missing");
    else if (!m_sReceiverAS2ID.startsWith(APP_PREFIX))
      m_aMessageHandler.warn(
          "The AS2 receiver ID '"
              + m_sReceiverAS2ID
              + "' should start with '"
              + APP_PREFIX
              + "' as required by the PEPPOL specification");

    if (StringHelper.hasNoText(m_sReceiverAS2KeyAlias))
      m_aMessageHandler.error("The AS2 receiver key alias is missing");
    else if (!m_sReceiverAS2KeyAlias.startsWith(APP_PREFIX))
      m_aMessageHandler.warn(
          "The AS2 receiver key alias '"
              + m_sReceiverAS2KeyAlias
              + "' should start with '"
              + APP_PREFIX
              + "' for the use with the dynamic AS2 partnerships");
    else if (m_sReceiverAS2ID != null && !m_sReceiverAS2ID.equals(m_sReceiverAS2KeyAlias))
      m_aMessageHandler.warn(
          "The AS2 receiver key alias ('"
              + m_sReceiverAS2KeyAlias
              + "') should match the AS2 receiver ID ('"
              + m_sReceiverAS2ID
              + "')");

    if (StringHelper.hasNoText(m_sReceiverAS2Url))
      m_aMessageHandler.error("The AS2 receiver URL (AS2 endpoint URL) is missing");
    else if (URLHelper.getAsURL(m_sReceiverAS2Url) == null)
      m_aMessageHandler.warn(
          "The provided AS2 receiver URL '" + m_sReceiverAS2Url + "' seems to be an invalid URL");

    if (m_aReceiverCert == null)
      m_aMessageHandler.error(
          "The receiver X.509 certificate is missing. Usually this is extracted from the SMP response");

    if (m_eSigningAlgo == null)
      m_aMessageHandler.error("The signing algorithm for the AS2 message is missing");

    if (StringHelper.hasNoText(m_sMessageIDFormat))
      m_aMessageHandler.error("The AS2 message ID format is missing.");

    if (m_aBusinessDocumentRes == null && m_aBusinessDocumentElement == null)
      m_aMessageHandler.error("The XML business document to be send is missing.");
    else if (m_aBusinessDocumentRes != null && !m_aBusinessDocumentRes.exists())
      m_aMessageHandler.error(
          "The XML business document to be send '"
              + m_aBusinessDocumentRes.getPath()
              + "' does not exist.");

    if (m_aPeppolSenderID == null)
      m_aMessageHandler.error("The PEPPOL sender participant ID is missing");
    else if (!IdentifierHelper.hasDefaultParticipantIdentifierScheme(m_aPeppolSenderID))
      m_aMessageHandler.warn(
          "The PEPPOL sender participant ID '"
              + IdentifierHelper.getIdentifierURIEncoded(m_aPeppolSenderID)
              + "' is using a non-standard scheme!");

    if (m_aPeppolReceiverID == null)
      m_aMessageHandler.error("The PEPPOL receiver participant ID is missing");
    else if (!IdentifierHelper.hasDefaultParticipantIdentifierScheme(m_aPeppolReceiverID))
      m_aMessageHandler.warn(
          "The PEPPOL receiver participant ID '"
              + IdentifierHelper.getIdentifierURIEncoded(m_aPeppolReceiverID)
              + "' is using a non-standard scheme!");

    if (m_aPeppolDocumentTypeID == null)
      m_aMessageHandler.error("The PEPPOL document type ID is missing");
    else if (!IdentifierHelper.hasDefaultDocumentTypeIdentifierScheme(m_aPeppolDocumentTypeID))
      m_aMessageHandler.warn(
          "The PEPPOL document type ID '"
              + IdentifierHelper.getIdentifierURIEncoded(m_aPeppolDocumentTypeID)
              + "' is using a non-standard scheme!");

    if (m_aPeppolProcessID == null) m_aMessageHandler.error("The PEPPOL process ID is missing");
    else if (!IdentifierHelper.hasDefaultProcessIdentifierScheme(m_aPeppolProcessID))
      m_aMessageHandler.warn(
          "The PEPPOL process ID '"
              + IdentifierHelper.getIdentifierURIEncoded(m_aPeppolProcessID)
              + "' is using a non-standard scheme!");

    if (m_aValidationKey == null)
      m_aMessageHandler.warn(
          "The validation key determining the business document validation is missing. Therefore the outgoing business document is NOT validated!");

    // Ensure that if a non-throwing message handler is installed, that the
    // sending is not performed!
    if (m_aMessageHandler.getErrorCount() > 0)
      throw new AS2ClientBuilderException(
          "Not all required fields are present so the PEPPOL AS2 client call can NOT be performed. See the message handler for details!");
  }
示例#17
0
 @Nonnull
 public CSSUnknownRule setBody(@Nullable final String sBody) {
   m_sBody = StringHelper.trim(sBody);
   return this;
 }
示例#18
0
 @Nonnull
 public CSSUnknownRule setParameterList(@Nullable final String sParameterList) {
   m_sParameterList = StringHelper.trim(sParameterList);
   return this;
 }
示例#19
0
 public static boolean isValidDeclaration(@Nonnull @Nonempty final String sDeclaration) {
   return StringHelper.startsWith(sDeclaration, '@');
 }