コード例 #1
0
 /**
  * Sets up all of the comments about the classified used in the current test. The comment to use
  * in the invocation of the callback is also set.
  */
 protected void setUpClassifiedComments() {
   ForeignPK classifiedPk = new ForeignPK(String.valueOf(CLASSIFIED_ID), CLASSIFIED_INSTANCEID);
   for (int i = 0; i < 5; i++) {
     Date date = new Date();
     UserDetail commentAuthor = new UserDetail();
     commentAuthor.setId(String.valueOf(i));
     Comment aComment =
         new Comment(
             new CommentPK(String.valueOf(i), CLASSIFIED_INSTANCEID),
             COMMENT_RESOURCETYPE,
             classifiedPk,
             i,
             "Toto" + i,
             "comment " + i,
             date,
             date);
     aComment.setOwnerDetail(commentAuthor);
     classifiedComments.add(aComment);
   }
   Date date = new Date();
   UserDetail commentAuthor = new UserDetail();
   commentAuthor.setId(String.valueOf(COMMENT_AUTHORID));
   concernedComment =
       new Comment(
           new CommentPK("10", CLASSIFIED_INSTANCEID),
           COMMENT_RESOURCETYPE,
           classifiedPk,
           Integer.parseInt(COMMENT_AUTHORID),
           "Toto" + COMMENT_AUTHORID,
           "concerned comment",
           date,
           date);
   concernedComment.setOwnerDetail(commentAuthor);
   classifiedComments.add(concernedComment);
 }
コード例 #2
0
  @Override
  public String doAction(HttpServletRequest request) {
    HttpSession session = request.getSession();
    String key = (String) session.getAttribute("svplogin_Key");
    boolean answerCrypted = getAuthenticationSettings().getBoolean("loginAnswerCrypted", false);

    try {
      String userId = getAdmin().authenticate(key, session.getId(), false, false);
      UserDetail userDetail = getAdmin().getUserDetail(userId);
      String question = request.getParameter("question");
      String answer = request.getParameter("answer");
      userDetail.setLoginQuestion(question);

      // encrypt the answer if needed
      if (answerCrypted) {
        answer = CryptMD5.encrypt(answer);
      }
      userDetail.setLoginAnswer(answer);
      getAdmin().updateUser(userDetail);

      if (getGeneral().getBoolean("userLoginForcePasswordChange", false)) {
        return getGeneral().getString("userLoginForcePasswordChangePage");
      }
      return sessionOpenener.openSession(request, key);
    } catch (AdminException e) {
      // Error : go back to login page
      SilverTrace.error(
          "peasCore", "validationQuestionHandler.doAction()", "peasCore.EX_USER_KEY_NOT_FOUND", e);
      return "/Login.jsp";
    }
  }
コード例 #3
0
 protected static Classified aClassified() {
   UserDetail author = new UserDetail();
   author.setId("0");
   Classified classified =
       new Classified(CLASSIFIED_ID, CLASSIFIED_INSTANCEID)
           .createdBy(author)
           .entitled("a classified");
   return classified;
 }
コード例 #4
0
  /**
   * Logs in the user.
   *
   * @see javax.security.auth.spi.LoginModule#login()
   */
  @SuppressWarnings("unchecked")
  @Override
  public boolean login() throws LoginException {
    HttpRequestCallback rcb = new HttpRequestCallback();
    AuthorizerCallback acb = new AuthorizerCallback();
    Callback[] callbacks = new Callback[] {rcb, acb};
    try {
      // First, try to extract a Principal object out of the request
      // directly. If we find one, we're done.
      m_handler.handle(callbacks);
      HttpServletRequest request = rcb.getRequest();
      if (request == null) {
        throw new LoginException("No Http request supplied.");
      }
      UserDetail userDetail =
          (UserDetail) request.getAttribute(SilverpeasWikiAuthorizer.USER_ATTR_NAME);
      if (userDetail == null) {
        throw new LoginException("No user supplied.");
      }
      String[] userRoles = (String[]) request.getAttribute(SilverpeasWikiAuthorizer.ROLE_ATTR_NAME);
      Principal principal = new WikiPrincipal(userDetail.getLogin(), WikiPrincipal.LOGIN_NAME);
      Principal principalFullName =
          new WikiPrincipal(userDetail.getDisplayedName(), WikiPrincipal.FULL_NAME);
      Principal principalWikiName =
          new WikiPrincipal(userDetail.getDisplayedName(), WikiPrincipal.WIKI_NAME);
      SilverTrace.debug(
          "wiki",
          "SilverpeasWikiLoginModule",
          "Added Principal " + principal.getName() + ",Role.ANONYMOUS,Role.ALL");
      m_principals.add(new PrincipalWrapper(principal));
      m_principals.add(new PrincipalWrapper(principalWikiName));
      m_principals.add(new PrincipalWrapper(principalFullName));
      // Add any container roles
      injectWebAuthorizerRoles(acb.getAuthorizer(), request);
      // If login succeeds, commit these roles
      for (String userRole : userRoles) {
        m_principals.add(convertSilverpeasRole(userRole));
      }
      // If login succeeds, remove these principals/roles
      m_principalsToOverwrite.add(WikiPrincipal.GUEST);
      m_principalsToOverwrite.add(Role.ANONYMOUS);
      m_principalsToOverwrite.add(Role.ASSERTED);
      // If login fails, remove these roles
      m_principalsToRemove.add(Role.AUTHENTICATED);

      return true;
    } catch (IOException e) {
      SilverTrace.error("wiki", "SilverpeasWikiLoginModule", "wiki.EX_LOGIN", e);
      return false;
    } catch (UnsupportedCallbackException e) {
      SilverTrace.error("wiki", "SilverpeasWikiLoginModule", "wiki.EX_LOGIN", e);
      return false;
    }
  }
  /**
   * @param question the current question-reply question
   * @param users list of users to notify
   * @throws QuestionReplyException
   */
  private void notifyTemplateReply(Question question, Reply reply, UserDetail[] users)
      throws QuestionReplyException {
    try {
      UserDetail user = getUserDetail(getUserId());
      String senderName = user.getFirstName() + " " + user.getLastName();
      String subject = getString("questionReply.notification") + getComponentLabel();
      // String message = senderName + intro + " \n" + content + "\n \n";

      // Get default resource bundle
      String resource = "com.stratelia.webactiv.survey.multilang.surveyBundle";
      ResourceLocator message = new ResourceLocator(resource, I18NHelper.defaultLanguage);

      // Initialize templates
      Map<String, SilverpeasTemplate> templates = new HashMap<String, SilverpeasTemplate>();
      NotificationMetaData notifMetaData =
          new NotificationMetaData(NotificationParameters.NORMAL, subject, templates, "reply");

      List<String> languages = DisplayI18NHelper.getLanguages();
      for (String language : languages) {
        // initialize new resource locator
        message = new ResourceLocator(resource, language);

        // Create a new silverpeas template
        SilverpeasTemplate template = getNewTemplate();
        template.setAttribute("UserDetail", user);
        template.setAttribute("userName", senderName);
        template.setAttribute("QuestionDetail", question);
        template.setAttribute("ReplyDetail", reply);
        template.setAttribute("replyTitle", reply.getTitle());
        template.setAttribute("replyContent", reply.getContent());
        templates.put(language, template);
        notifMetaData.addLanguage(
            language,
            message.getString("questionReply.notification", "") + getComponentLabel(),
            "");
      }
      notifMetaData.setSender(getUserId());
      notifMetaData.addUserRecipients(users);
      notifMetaData.setSource(getSpaceLabel() + " - " + getComponentLabel());
      // notifMetaData.setLink(question._getURL());
      getNotificationSender().notifyUser(notifMetaData);
    } catch (Exception e) {
      throw new QuestionReplyException(
          "QuestionReplySessionController.notify()",
          SilverpeasException.ERROR,
          "questionReply.EX_NOTIFICATION_MANAGER_FAILED",
          "",
          e);
    }
  }
コード例 #6
0
  /** Constructs a new comment service and mocks some of the underlying resource. */
  public MyCommentService() {
    super();
    Comment aComment = CommentBuilder.getBuilder().buildWith("Toto", "Vu à la télé");
    List<Comment> comments = new ArrayList<Comment>();
    comments.add(aComment);
    comments.add(CommentBuilder.getBuilder().buildWith("Titi", "Repasses demain"));
    mockedDAO = mock(CommentDAO.class);
    when(mockedDAO.getAllCommentsByForeignKey(any(ForeignPK.class))).thenReturn(comments);
    when(mockedDAO.getComment(any(CommentPK.class))).thenReturn(aComment);

    UserDetail userDetail = new UserDetail();
    userDetail.setFirstName("Toto");
    userDetail.setLastName("Chez-les-papoos");
    mockedController = mock(OrganizationController.class);
    when(mockedController.getUserDetail(anyString())).thenReturn(userDetail);
  }
コード例 #7
0
  /**
   * Returns the string value of this field : the user names (FirstName LastName,FirstName
   * LastName,FirstName LastName, ...)
   */
  public String getValue() {
    String theUserCardIds = getUserCardIds(); // userCardId-userId,userCardId-userId
    // ....
    if (!StringUtil.isDefined(theUserCardIds)) {
      return theUserCardIds;
    }

    try {

      theUserCardIds += ",";
      String userCardIdUserId = null;
      int index = -1;
      String userCardId = null;
      String userId = null;
      UserDetail user = null;
      StringBuffer names = new StringBuffer("");
      int begin = 0;
      int end = 0;

      end = theUserCardIds.indexOf(',', begin);
      while (end != -1) {
        userCardIdUserId = theUserCardIds.substring(begin, end); // userCardId-userId
        index = userCardIdUserId.indexOf("-");
        userCardId = userCardIdUserId.substring(0, index);
        userId = userCardIdUserId.substring(index + 1);

        user = organizationController.getUserDetail(userId);
        if (user == null) {
          names.append("userCardId(").append(userCardId).append(")");
        } else {
          names.append(user.getFirstName()).append(" ").append(user.getLastName());
        }
        names.append(",");
        begin = end + 1;
        end = theUserCardIds.indexOf(',', begin);
      }

      if (!names.toString().equals("")) {
        names = names.deleteCharAt(names.length() - 1);
      }

      return names.toString();
    } catch (Exception e) {
      SilverTrace.error("form", "PdcUserField.getValue", "root.MSG_GEN_PARAM_VALUE", "", e);
      return null;
    }
  }
  /*
   * Récupère la liste des experts du domaine de la question qui ne sont pas déjà destinataires
   */
  public Collection<UserDetail> getCurrentQuestionAvailableWriters() throws QuestionReplyException {
    Collection<UserDetail> users = getCurrentQuestionWriters();
    Collection<UserDetail> availableUsers = new ArrayList<UserDetail>();
    Collection<Recipient> recipients = getCurrentQuestion().readRecipients();

    for (UserDetail user : users) {
      boolean isRecipient = false;
      for (Recipient recipient : recipients) {
        if (user.getId().equals(recipient.getUserId())) {
          isRecipient = true;
        }
      }
      if (!isRecipient) {
        availableUsers.add(user);
      }
    }
    return availableUsers;
  }
コード例 #9
0
ファイル: Ticket.java プロジェクト: ndup0nt/Silverpeas-Core
 protected Ticket(
     int sharedObjectId,
     String componentId,
     UserDetail creator,
     Date creationDate,
     Date endDate,
     int nbAccessMax) {
   this(sharedObjectId, componentId, creator.getId(), creationDate, endDate, nbAccessMax);
 }
 /*
  * Retourne true si la liste contient deja le user
  */
 private boolean exist(UserDetail user, Collection<UserDetail> listUser) {
   int i = 0;
   List<UserDetail> arrayUser = new ArrayList<UserDetail>(listUser);
   if (user != null) {
     String idUser = user.getId();
     while (i < arrayUser.size()) {
       UserDetail theUser = arrayUser.get(i);
       String theId = theUser.getId();
       if (theId.equals(idUser)) {
         return true;
       }
       i++;
     }
   } else {
     return true;
   }
   return false;
 }
コード例 #11
0
 /**
  * Is the specified user can access this publication?
  *
  * <p>A user can access a publication if he has enough rights to access both the application
  * instance in which is managed this publication and one of the nodes to which this publication
  * belongs to.
  *
  * @param user a user in Silverpeas.
  * @return true if the user can access this publication, false otherwise.
  */
 @Override
 public boolean canBeAccessedBy(final UserDetail user) {
   AccessController<String> accessController =
       AccessControllerProvider.getAccessController("componentAccessController");
   boolean canBeAccessed =
       accessController.isUserAuthorized(user.getId(), getComponentInstanceId());
   if (canBeAccessed) {
     AccessController<NodePK> nodeAccessController =
         AccessControllerProvider.getAccessController("nodeAccessController");
     Collection<NodePK> nodes =
         getPublicationBm().getAllFatherPK(new PublicationPK(getId(), getInstanceId()));
     for (NodePK aNode : nodes) {
       canBeAccessed = nodeAccessController.isUserAuthorized(user.getId(), aNode);
       if (canBeAccessed) {
         break;
       }
     }
   }
   return canBeAccessed;
 }
コード例 #12
0
 @Override
 public String doAction(HttpServletRequest request) {
   String login = request.getParameter("Login");
   String domainId = request.getParameter("DomainId");
   try {
     String userId = getAdmin().getUserIdByLoginAndDomain(login, domainId);
     UserDetail userDetail = getAdmin().getUserDetail(userId);
     if (StringUtil.isDefined(userDetail.getLoginQuestion())) {
       request.setAttribute("userDetail", userDetail);
       return getGeneral().getString("userLoginQuestionPage");
     } else {
       // page d'erreur : veuillez contacter votre admin
       return "/Login.jsp";
     }
   } catch (AdminException e) {
     // Error : go back to login page
     SilverTrace.error(
         "peasCore",
         "loginQuestionHandler.doAction()",
         "peasCore.EX_USER_KEY_NOT_FOUND",
         "login="******"/Login.jsp";
   }
 }
コード例 #13
0
  private PublicationDetail importFile(
      File file,
      ImportReportManager reportManager,
      MassiveReport massiveReport,
      GEDImportExport gedIE,
      PdcImportExport pdcIE,
      ImportSettings settings) {
    SilverTrace.debug(
        "importExport",
        "RepositoriesTypeManager.importFile",
        "root.MSG_GEN_ENTER_METHOD",
        "file = " + file.getName());
    String componentId = gedIE.getCurrentComponentId();
    UserDetail userDetail = gedIE.getCurentUserDetail();
    PublicationDetail pubDetailToCreate = null;
    try {
      // Création du rapport unitaire
      UnitReport unitReport = new UnitReport();
      massiveReport.addUnitReport(unitReport);

      // Check the file size
      ResourceLocator uploadSettings =
          new ResourceLocator("org.silverpeas.util.uploads.uploadSettings", "");
      long maximumFileSize = uploadSettings.getLong("MaximumFileSize", 10485760);
      long fileSize = file.length();
      if (fileSize <= 0L) {
        unitReport.setError(UnitReport.ERROR_NOT_EXISTS_OR_INACCESSIBLE_FILE);
        reportManager.addNumberOfFilesNotImported(1);
        return pubDetailToCreate;
      } else if (fileSize > maximumFileSize) {
        unitReport.setError(UnitReport.ERROR_FILE_SIZE_EXCEEDS_LIMIT);
        reportManager.addNumberOfFilesNotImported(1);
        return pubDetailToCreate;
      }

      // On récupére les infos nécéssaires à la création de la publication
      pubDetailToCreate =
          PublicationImportExport.convertFileInfoToPublicationDetail(file, settings);
      pubDetailToCreate.setPk(new PublicationPK("unknown", "useless", componentId));
      if ((settings.isDraftUsed() && pdcIE.isClassifyingMandatory(componentId))
          || settings.isDraftUsed()) {
        pubDetailToCreate.setStatus(PublicationDetail.DRAFT);
        pubDetailToCreate.setStatusMustBeChecked(false);
      }
      SilverTrace.debug(
          "importExport",
          "RepositoriesTypeManager.importFile",
          "root.MSG_GEN_PARAM_VALUE",
          "pubDetailToCreate.status = " + pubDetailToCreate.getStatus());

      // Création de la publication
      pubDetailToCreate =
          gedIE.createPublicationForMassiveImport(unitReport, pubDetailToCreate, settings);
      unitReport.setLabel(pubDetailToCreate.getPK().getId());

      SilverTrace.debug(
          "importExport",
          "RepositoriesTypeManager.importFile",
          "root.MSG_GEN_PARAM_VALUE",
          "pubDetailToCreate created");

      if (FileUtil.isMail(file.getName())) {
        // if imported file is an e-mail, its textual content is saved in a dedicated form
        // and attached files are attached to newly created publication
        processMailContent(
            pubDetailToCreate, file, reportManager, unitReport, gedIE, settings.isVersioningUsed());
      }

      // add attachment
      SimpleDocument document;
      SimpleDocumentPK pk = new SimpleDocumentPK(null, componentId);
      if (settings.isVersioningUsed()) {
        document = new HistorisedDocument();
        document.setPublicDocument(
            settings.getVersionType() == DocumentVersion.TYPE_PUBLIC_VERSION);
      } else {
        document = new SimpleDocument();
      }
      document.setPK(pk);
      document.setFile(new SimpleAttachment());
      document.setFilename(file.getName());
      document.setSize(fileSize);
      document.getFile().setCreatedBy(userDetail.getId());
      if (settings.useFileDates()) {
        document.setCreated(pubDetailToCreate.getCreationDate());
        if (pubDetailToCreate.getUpdateDate() != null) {
          document.setUpdated(pubDetailToCreate.getUpdateDate());
        }
      } else {
        document.setCreated(new Date());
      }
      document.setForeignId(pubDetailToCreate.getPK().getId());
      document.setContentType(FileUtil.getMimeType(file.getName()));
      AttachmentServiceFactory.getAttachmentService()
          .createAttachment(document, file, pubDetailToCreate.isIndexable(), false);
      reportManager.addNumberOfFilesProcessed(1);
      reportManager.addImportedFileSize(document.getSize(), componentId);
    } catch (Exception ex) {
      massiveReport.setError(UnitReport.ERROR_ERROR);
      SilverTrace.error(
          "importExport", "RepositoriesTypeManager.importFile", "root.EX_NO_MESSAGE", ex);
    }
    return pubDetailToCreate;
  }
コード例 #14
0
ファイル: Ticket.java プロジェクト: ndup0nt/Silverpeas-Core
 public void setCreator(final UserDetail creator) {
   this.creatorId = creator.getId();
 }
コード例 #15
0
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    SilverTrace.info("peasUtil", "RssServlet.doPost", "root.MSG_GEN_ENTER_METHOD");
    String instanceId = getObjectId(req);
    String userId = getUserId(req);
    String login = getLogin(req);
    String password = getPassword(req);
    // rechercher si le composant a bien le flux RSS autorisé
    if (isComponentRss(instanceId)) {
      try {
        SilverTrace.info(
            "peasUtil",
            "RssServlet.doPost",
            "root.MSG_GEN_PARAM_VALUE",
            "InstanceId = " + instanceId);

        // Vérification que le user a droit d'accès au composant
        AdminController adminController = new AdminController(null);
        UserFull user = adminController.getUserFull(userId);
        if (user != null
            && login.equals(user.getLogin())
            && password.equals(user.getPassword())
            && isComponentAvailable(adminController, instanceId, userId)) {

          String serverURL = getServerURL(adminController, user.getDomainId());
          ChannelIF channel = new Channel();

          // récupération de la liste des N éléments à remonter dans le flux
          int nbReturnedElements = getNbReturnedElements();
          Collection<T> listElements = getListElements(instanceId, nbReturnedElements);

          // création d'une liste de ItemIF en fonction de la liste des éléments

          for (T element : listElements) {
            String title = getElementTitle(element, userId);
            URL link = new URL(serverURL + getElementLink(element, userId));
            String description = getElementDescription(element, userId);
            Date dateElement = getElementDate(element);
            String creatorId = getElementCreatorId(element);
            ItemIF item = new Item();
            item.setTitle(title);
            item.setLink(link);
            item.setDescription(description);
            item.setDate(dateElement);

            if (StringUtil.isDefined(creatorId)) {
              UserDetail creator = adminController.getUserDetail(creatorId);
              if (creator != null) {
                item.setCreator(creator.getDisplayedName());
              }
            } else if (StringUtil.isDefined(getExternalCreatorId(element))) {
              item.setCreator(getExternalCreatorId(element));
            }
            channel.addItem(item);
          }

          // construction de l'objet Channel
          channel.setTitle(getChannelTitle(instanceId));
          URL componentUrl =
              new URL(
                  serverURL
                      + URLManager.getApplicationURL()
                      + URLManager.getURL("useless", instanceId));
          channel.setLocation(componentUrl);

          // exportation du channel
          res.setContentType("application/rss+xml");
          res.setHeader("Content-Disposition", "inline; filename=feeds.rss");
          Writer writer = res.getWriter();
          RSS_2_0_Exporter rssExporter = new RSS_2_0_Exporter(writer, "UTF-8");
          rssExporter.write(channel);
        } else {
          objectNotFound(req, res);
        }
      } catch (Exception e) {
        objectNotFound(req, res);
      }
    }
  }
コード例 #16
0
ファイル: Ticket.java プロジェクト: ndup0nt/Silverpeas-Core
 public void setLastModifier(UserDetail modifier) {
   this.updaterId = modifier.getId();
 }
コード例 #17
0
 @Override
 public UserDetail getCreator() {
   return UserDetail.getById(getCreatorId());
 }
コード例 #18
0
  /**
   * Method declaration
   *
   * @param req
   * @param res
   * @throws IOException
   * @throws ServletException
   * @see
   */
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    HttpRequest request = HttpRequest.decorate(req);
    if (!request.isContentInMultipart()) {
      res.getOutputStream().println("SUCCESS");
      return;
    }

    String userId = req.getParameter("UserId");
    try {
      request.setCharacterEncoding(CharEncoding.UTF_8);
      String componentId = request.getParameter("ComponentId");
      String id = request.getParameter("PubId");
      String lang = I18NHelper.checkLanguage(request.getParameter("lang"));
      SilverTrace.info(
          "attachment",
          "DragAndDrop.doPost",
          "root.MSG_GEN_PARAM_VALUE",
          "componentId = " + componentId + ", id = " + id + ", userId = " + userId);
      boolean bIndexIt = StringUtil.getBooleanValue(request.getParameter("IndexIt"));

      List<FileItem> items = request.getFileItems();
      for (FileItem item : items) {
        SilverTrace.info(
            "attachment",
            "DragAndDrop.doPost",
            "root.MSG_GEN_PARAM_VALUE",
            "item = " + item.getFieldName());
        SilverTrace.info(
            "attachment",
            "DragAndDrop.doPost",
            "root.MSG_GEN_PARAM_VALUE",
            "item = " + item.getName() + "; " + item.getString(CharEncoding.UTF_8));

        if (!item.isFormField()) {
          String fileName = item.getName();
          if (fileName != null) {
            String mimeType = FileUtil.getMimeType(fileName);
            SilverTrace.info(
                "attachment",
                "DragAndDrop.doPost",
                "root.MSG_GEN_PARAM_VALUE",
                "item size = " + item.getSize());
            // create AttachmentDetail Object
            SimpleDocument document =
                new SimpleDocument(
                    new SimpleDocumentPK(null, componentId),
                    id,
                    0,
                    false,
                    new SimpleAttachment(
                        fileName,
                        lang,
                        null,
                        null,
                        item.getSize(),
                        mimeType,
                        userId,
                        new Date(),
                        null));
            document.setDocumentType(determineDocumentType(request));
            File tempFile = File.createTempFile("silverpeas_", fileName);
            try {
              FileUploadUtil.saveToFile(tempFile, item);
              MetadataExtractor extractor = MetadataExtractor.getInstance();
              MetaData metadata = extractor.extractMetadata(tempFile);
              document.setSize(tempFile.length());
              document.setTitle(metadata.getTitle());
              document.setDescription(metadata.getSubject());
              document =
                  AttachmentServiceFactory.getAttachmentService()
                      .createAttachment(document, tempFile, bIndexIt);
            } finally {
              FileUtils.deleteQuietly(tempFile);
            }
            // Specific case: 3d file to convert by Actify Publisher
            ActifyDocumentProcessor.getProcessor().process(document);
          }
        }
      }
    } catch (Exception e) {
      SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e);
      final StringBuilder sb = new StringBuilder("ERROR: ");
      final String errorMessage =
          SilverpeasTransverseWebErrorUtil.performAppletAlertExceptionMessage(
              e, UserDetail.getById(userId).getUserPreferences().getLanguage());
      if (StringUtil.isDefined(errorMessage)) {
        sb.append(errorMessage);
      } else {
        sb.append(e.getMessage());
      }
      res.getOutputStream().println(sb.toString());
      return;
    }
    res.getOutputStream().println("SUCCESS");
  }
コード例 #19
0
  /**
   * This method generates the Javascript instructions to retrieve in AJAX the comments on the given
   * resource and to display them. The generated code is built upon the JQuery toolkit, so that it
   * is required to be included within the the XHTML header section.
   *
   * @return the javascript code to handle a list of comments on a given resource.
   */
  private String setUpJQueryCommentPlugin() {
    String context = URLManager.getApplicationURL();

    OrganisationController controller = OrganisationControllerFactory.getOrganisationController();
    ResourcesWrapper settings = getSettings();
    UserDetail currentUser = controller.getUserDetail(getUserId());
    String[] profiles = controller.getUserProfiles(getUserId(), getComponentId());
    final boolean isAdmin;
    if (profiles != null) {
      isAdmin = Arrays.asList(profiles).contains(SilverpeasRole.admin.name());
    } else {
      isAdmin = currentUser.isAccessAdmin();
    }
    boolean canBeUpdated = settings.getSetting("AdminAllowedToUpdate", true) && isAdmin;

    String script =
        "$('#commentaires').comment({"
            + "uri: '"
            + context
            + "/services/comments/"
            + getComponentId()
            + "/"
            + getResourceType()
            + "/"
            + getResourceId()
            + "', author: { avatar: '"
            + URLManager.getApplicationURL()
            + currentUser.getAvatar()
            + "', id: '"
            + getUserId()
            + "', anonymous: "
            + currentUser.isAnonymous()
            + "}, "
            + "update: { activated: function( comment ) {"
            + "if ("
            + canBeUpdated
            + "|| (comment.author.id === '"
            + getUserId()
            + "'))"
            + "return true; else return false;},icon: '"
            + getUpdateIconURL()
            + "',"
            + "altText: '"
            + settings.getString("GML.update")
            + "'},"
            + "deletion: {activated: function( comment ) {if ("
            + canBeUpdated
            + " || (comment.author.id === '"
            + getUserId()
            + "')) return true; else return false;},"
            + "confirmation: '"
            + settings.getString("comment.suppressionConfirmation")
            + "',"
            + "icon: '"
            + getDeletionIconURL()
            + "',altText: '"
            + settings.getString("GML.delete")
            + "'}, updateBox: { title: '"
            + settings.getString("comment.comment")
            + "'}, editionBox: { title: '"
            + settings.getString("comment.add")
            + "', ok: '"
            + settings.getString("GML.validate")
            + "'}, validate: function(text) { if (text == null || $.trim(text).length == 0) { "
            + "alert('"
            + settings.getString("comment.pleaseFill_single")
            + "');"
            + "} else if (!isValidTextArea(text)) { alert('"
            + settings.getString("comment.champsTropLong")
            + "'); } else { return true; } return false; },"
            + "mandatory: '"
            + getMandatoryFieldSymbolURL()
            + "', mandatoryText: '"
            + settings.getString("GML.requiredField")
            + "'";
    if (isDefined(getCallback())) {
      script += ",callback: " + getCallback() + "});";
    } else {
      script += "});";
    }

    return script;
  }
コード例 #20
0
  private void processMailContent(
      PublicationDetail pubDetail,
      File file,
      ImportReportManager reportManager,
      UnitReport unitReport,
      GEDImportExport gedIE,
      boolean isVersioningUsed)
      throws ImportExportException {

    String componentId = gedIE.getCurrentComponentId();
    UserDetail userDetail = gedIE.getCurentUserDetail();
    MailExtractor extractor = null;
    Mail mail = null;
    try {
      extractor = Extractor.getExtractor(file);
      mail = extractor.getMail();
    } catch (Exception e) {
      SilverTrace.error(
          "importExport",
          "RepositoriesTypeManager.processMailContent",
          "importExport.EX_CANT_EXTRACT_MAIL_DATA",
          e);
    }
    if (mail != null) {
      // save mail data into dedicated form
      String content = mail.getBody();
      PublicationContentType pubContent = new PublicationContentType();
      XMLModelContentType modelContent = new XMLModelContentType("mail");
      pubContent.setXMLModelContentType(modelContent);
      List<XMLField> fields = new ArrayList<XMLField>();
      modelContent.setFields(fields);

      XMLField subject = new XMLField("subject", mail.getSubject());
      fields.add(subject);

      XMLField body = new XMLField("body", ESCAPE_ISO8859_1.translate(content));
      fields.add(body);

      XMLField date = new XMLField("date", DateUtil.getOutputDateAndHour(mail.getDate(), "fr"));
      fields.add(date);

      InternetAddress address = mail.getFrom();
      String from = "";
      if (StringUtil.isDefined(address.getPersonal())) {
        from += address.getPersonal() + " - ";
      }
      from += "<a href=\"mailto:" + address.getAddress() + "\">" + address.getAddress() + "</a>";
      XMLField fieldFROM = new XMLField("from", from);
      fields.add(fieldFROM);

      Address[] recipients = mail.getAllRecipients();
      String to = "";
      for (Address recipient : recipients) {
        InternetAddress ia = (InternetAddress) recipient;
        if (StringUtil.isDefined(ia.getPersonal())) {
          to += ia.getPersonal() + " - ";
        }
        to += "<a href=\"mailto:" + ia.getAddress() + "\">" + ia.getAddress() + "</a></br>";
      }
      XMLField fieldTO = new XMLField("to", to);
      fields.add(fieldTO);

      // save form
      gedIE.createPublicationContent(
          reportManager,
          unitReport,
          Integer.parseInt(pubDetail.getPK().getId()),
          pubContent,
          userDetail.getId(),
          null);

      // extract each file from mail...
      try {
        List<AttachmentDetail> documents = new ArrayList<AttachmentDetail>();

        List<MailAttachment> attachments = extractor.getAttachments();
        for (MailAttachment attachment : attachments) {
          if (attachment != null) {
            AttachmentDetail attDetail = new AttachmentDetail();
            AttachmentPK pk = new AttachmentPK("unknown", "useless", componentId);
            attDetail.setLogicalName(attachment.getName());
            attDetail.setPhysicalName(attachment.getPath());
            attDetail.setAuthor(userDetail.getId());
            attDetail.setSize(attachment.getSize());
            attDetail.setPK(pk);

            documents.add(attDetail);
          }
        }

        // ... and save it
        if (isVersioningUsed) {
          // versioning mode
          VersioningImportExport versioningIE = new VersioningImportExport(userDetail);
          versioningIE.importDocuments(
              pubDetail.getPK().getId(),
              componentId,
              documents,
              Integer.parseInt(userDetail.getId()),
              pubDetail.isIndexable());
        } else {
          // classic mode
          AttachmentImportExport attachmentIE = new AttachmentImportExport();
          attachmentIE.importAttachments(
              pubDetail.getPK().getId(),
              componentId,
              documents,
              userDetail.getId(),
              pubDetail.isIndexable());
        }
      } catch (Exception e) {
        SilverTrace.error(
            "importExport", "RepositoriesTypeManager.processMailContent", "root.EX_NO_MESSAGE", e);
      }
    }
  }