/** @return Returns the message to display when a file has been uploaded */
  public String getFileUploadSuccessMsg() {
    // NOTE: This is a far from ideal solution but will do until we have
    //       a pure JSF upload solution working. This method is only called
    //       after a file is uploaded, so we can calculate the mime type and
    //       determine whether to enable inline editing in here.
    FacesContext fc = FacesContext.getCurrentInstance();
    this.mimeType = Repository.getMimeTypeForFileName(fc, this.fileName);
    this.encoding = "UTF-8";
    InputStream is = null;
    try {
      if (this.file != null) {
        is = new BufferedInputStream(new FileInputStream(this.file));
        this.encoding = Repository.guessEncoding(fc, is, this.mimeType);
      }
    } catch (Throwable e) {
      // Not terminal
      logger.error("Failed to get encoding from file: " + this.fileName, e);
    } finally {
      try {
        is.close();
      } catch (Throwable e) {
      } // Includes NPE
    }

    this.inlineEdit = (this.mimeType.equals(MimetypeMap.MIMETYPE_HTML));

    // get the file upload message
    String msg = Application.getMessage(FacesContext.getCurrentInstance(), "file_upload_success");
    return MessageFormat.format(msg, new Object[] {Utils.encode(getFileName())});
  }
  /** @param p The person context to set. */
  public void setPerson(final Node p) {
    // perform the set in a txn as certain bean calls require it
    FacesContext context = FacesContext.getCurrentInstance();
    RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context);
    RetryingTransactionCallback callback =
        new RetryingTransactionCallback() {
          public Object execute() throws Throwable {
            person = p;
            userName = (String) person.getProperties().get(ContentModel.PROP_USERNAME);

            // rebuild the property immutability map helper object
            immutabilty =
                new PropertyImmutabilityMap(
                    getUserRegistrySynchronizer().getPersonMappedProperties(userName));

            return null;
          }
        };
    try {
      txnHelper.doInTransaction(callback, false);
    } catch (Throwable e) {
      // reset the flag so we can re-attempt the operation
      if (e instanceof ReportedException == false) {
        Utils.addErrorMessage(e.getMessage(), e);
      }
      ReportedException.throwIfNecessary(e);
    }
  }
  @Override
  protected String doPostCommitProcessing(FacesContext context, String outcome) {
    clearUpload();

    // as we were successful, go to the set properties dialog if asked
    // to otherwise just return
    if (this.showOtherProperties) {
      // check whether the created node is checked out, if a 'check out'
      // rule is present in the space the new node will be and an
      // attempt to modify the properties will cause an error (ALF-438)
      if (getNodeService().hasAspect(this.createdNode, ContentModel.ASPECT_LOCKABLE)) {
        Utils.addErrorMessage(
            Application.getMessage(FacesContext.getCurrentInstance(), MSG_NODE_LOCKED));
        return outcome;
      } else {
        // we are going to immediately edit the properties so we need
        // to setup the BrowseBean context appropriately
        this.browseBean.setDocument(new Node(this.createdNode));

        return "dialog:setContentProperties";
      }
    } else {
      return outcome;
    }
  }
 public String getPersonDescription() {
   ContentService cs =
       Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService();
   ContentReader reader = cs.getReader(this.person.getNodeRef(), ContentModel.PROP_PERSONDESC);
   if (reader != null && reader.exists()) {
     return Utils.stripUnsafeHTMLTags(reader.getContentString()).replace("\r\n", "<p>");
   } else {
     return null;
   }
 }
 public boolean checkTenantUserName() {
   try {
     this.userName = PersonServiceImpl.updateUsernameForTenancy(this.userName, getTenantService());
     return true;
   } catch (TenantDomainMismatchException e) {
     Utils.addErrorMessage(
         MessageFormat.format(
             Application.getMessage(FacesContext.getCurrentInstance(), ERROR_DOMAIN_MISMATCH),
             e.getTenantA(),
             e.getTenantB()));
     return false;
   }
 }
  /**
   * Checkout document to the same space as original one and then add the OFFLINE_EDITING property.
   */
  private void checkoutFile(Node node) {
    UserTransaction tx = null;
    FacesContext context = FacesContext.getCurrentInstance();

    if (node != null) {
      try {
        tx = Repository.getUserTransaction(context, false);
        tx.begin();

        if (logger.isDebugEnabled())
          logger.debug("Trying to checkout content node Id: " + node.getId());
        NodeRef workingCopyRef = null;

        // checkout the content to the current space
        workingCopyRef = property.getVersionOperationsService().checkout(node.getNodeRef());
        getNodeService()
            .setProperty(workingCopyRef, ContentModel.PROP_WORKING_COPY_MODE, OFFLINE_EDITING);

        // set the working copy Node instance
        Node workingCopy = new Node(workingCopyRef);
        property.setWorkingDocument(workingCopy);

        // create content URL to the content download servlet with ID and
        // expected filename
        String url =
            DownloadContentServlet.generateDownloadURL(workingCopyRef, workingCopy.getName());

        workingCopy.getProperties().put("url", url);
        workingCopy
            .getProperties()
            .put("fileType32", FileTypeImageUtils.getFileTypeImage(workingCopy.getName(), false));

        // commit the transaction
        tx.commit();
      } catch (Throwable err) {
        try {
          if (tx != null) {
            tx.rollback();
          }
        } catch (Exception tex) {
        }

        Utils.addErrorMessage(
            Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_CHECKOUT)
                + err.getMessage(),
            err);
      }
    } else {
      logger.warn("WARNING: checkoutFile called without a current Document!");
    }
  }
  /** @return Returns the summary data for the wizard. */
  public String getSummary() {
    ResourceBundle bundle = Application.getBundle(FacesContext.getCurrentInstance());

    String homeSpaceLabel = this.homeSpaceName;
    if (this.homeSpaceName.length() == 0 && this.homeSpaceLocation != null) {
      homeSpaceLabel = Repository.getNameForNode(this.getNodeService(), this.homeSpaceLocation);
    }

    String quotaLabel = "";
    if (this.sizeQuota != null && this.sizeQuota != -1L) {
      quotaLabel = Long.toString(this.sizeQuota) + bundle.getString(this.sizeQuotaUnits);
    }

    String presenceLabel = "";
    if (this.presenceProvider != null && this.presenceProvider.length() != 0) {
      presenceLabel = this.presenceUsername + " (" + presenceProvider + ")";
    }

    return buildSummary(
        new String[] {
          bundle.getString("name"), bundle.getString("username"),
          bundle.getString("password"), bundle.getString("homespace"),
          bundle.getString("email"), bundle.getString("user_organization"),
          bundle.getString("user_jobtitle"), bundle.getString("user_location"),
          bundle.getString("presence_username"), bundle.getString("quota")
        },
        new String[] {
          Utils.encode(this.firstName + " " + this.lastName),
          Utils.encode(this.userName),
          "********",
          Utils.encode(homeSpaceLabel),
          Utils.encode(this.email),
          Utils.encode(this.organisation),
          Utils.encode(this.jobtitle),
          Utils.encode(this.location),
          Utils.encode(presenceLabel),
          quotaLabel
        });
  }
 /**
  * @see org.alfresco.web.app.servlet.command.CommandProcessor#outputStatus(java.io.PrintWriter)
  */
 public void outputStatus(PrintWriter out) {
   out.print("UI Action command: '");
   out.print(Utils.encode(this.command));
   out.print("' executed with args: ");
   out.println(this.args != null ? (Utils.encode(this.args.toString())) : "");
 }
  @Override
  protected String finishImpl(FacesContext context, String outcome) throws Throwable {
    // TODO: implement create new Person object from specified details
    try {
      if (!this.password.equals(this.confirm)) {
        Utils.addErrorMessage(Application.getMessage(context, UsersDialog.ERROR_PASSWORD_MATCH));
        outcome = null;
      }

      if (checkTenantUserName() == false) {
        outcome = null;
      }

      if (outcome != null) {
        // create properties for Person type from submitted Form data
        Map<QName, Serializable> props = new HashMap<QName, Serializable>(7, 1.0f);
        setPersonPropertiesAndCreateHomeSpaceIfNeeded(props, null, context);

        // create the node to represent the Person
        getPersonService().createPerson(props);

        // ensure the user can access their own Person object
        // getPermissionService().setPermission(newPerson, this.userName,
        // getPermissionService().getAllPermission(), true);
        // Not required - now done by the person service.

        if (logger.isDebugEnabled())
          logger.debug("Created Person node for username: "******"Created User Authentication instance for username: " + this.userName);

        if ((this.sizeQuota != null) && (this.sizeQuota < 0L)) {
          Utils.addErrorMessage(
              MessageFormat.format(
                  Application.getMessage(context, UsersDialog.ERROR_NEGATIVE_QUOTA),
                  this.sizeQuota));
          outcome = null;
        } else {
          putSizeQuotaProperty(this.userName, this.sizeQuota, this.sizeQuotaUnits);
        }
      }
      invalidateUserList();
    } catch (Throwable e) {
      Utils.addErrorMessage(
          MessageFormat.format(
              Application.getMessage(FacesContext.getCurrentInstance(), ERROR), e.getMessage()),
          e);
      outcome = null;
      this.isFinished = false;
      ReportedException.throwIfNecessary(e);
    }

    if (outcome == null) {
      this.isFinished = false;
    }

    return outcome;
  }