AnsweredAssumed Answered

How to list the File Name in Normal Form

Question asked by nobel on Feb 24, 2010
I am using the following code and generated the file-uploading. When i browse and add a file by clicking on "Add to List" button, the file is added in the listbox by listing its name as "org.apache.myfaces.custom.fileupload.UploadedFileDefaultMemoryImpl@e83fda9" instead of listing "FileName.txt".

Plz guide me how to list the file name as "FileName.txt" [Normal file format] in the Listbox, when i upload a file.



The following code is already taken from this forum:

1. FileUploadGenerator.java

package co.com.arkimia.alfresco.web.bean.generator;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.cmr.repository.datatype.TypeConverter;
import org.alfresco.web.app.servlet.FacesHelper;
import org.alfresco.web.bean.generator.TextFieldGenerator;
import org.apache.myfaces.custom.fileupload.UploadedFile;

/**
* Generates an input file component and configures the alfresco converter to
* show the file name.
* @author Juan David Zuluaga Arboleda. Arkimia S.A.
*
*/
public class FileUploadGenerator extends TextFieldGenerator {

   /**
    * Generates an html input file upload and creates a converter from UploadedFile
    * to string;
    */
   public UIComponent generate(FacesContext context, String id) {
      UIComponent component = context.getApplication().createComponent(
            "org.apache.myfaces.HtmlInputFileUpload");
      component.setRendererType("co.com.arkimia.FileUpload");
      FacesHelper.setupComponentId(context, component, id);
      DefaultTypeConverter.INSTANCE.addConverter(UploadedFile.class, String.class,
            new TypeConverter.Converter<UploadedFile, String >()
              {
                  public String convert(UploadedFile source)
                  {
                     int index = Math.max(source.getName().lastIndexOf("\\"),
                           source.getName().lastIndexOf("/"));
                      return source.getName().substring(index + 1);
                  }
              });
      return component;
   }
}


2. FileUploadRenderer.java

package co.com.arkimia.alfresco.web.ui.repo.renderer;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.servlet.http.HttpServletRequest;

import org.apache.myfaces.custom.fileupload.HtmlFileUploadRenderer;

/**
* Renders the input file and renders a script to change the encoding type of
* the container form
* @author Juan David Zuluaga Arboleda. Arkimia S.A.
*
*/
public class FileUploadRenderer extends HtmlFileUploadRenderer {
   private static final String SCRIPT_GENERATED =
      FileUploadRenderer.class.getName()+ ".SCRIPT_GENERATED";

   @Override
   public void encodeEnd(FacesContext facesContext, UIComponent uiComponent)
         throws IOException {
      super.encodeEnd(facesContext, uiComponent);
      HttpServletRequest req = (HttpServletRequest)facesContext
         .getExternalContext().getRequest();
      Boolean scriptGenerated = (Boolean)req.getAttribute(SCRIPT_GENERATED);
      if(scriptGenerated != null && scriptGenerated.booleanValue()) {
         return;
      }
     
      UIForm form = getForm(uiComponent);
      if(form == null) {
         return;
      }
      req.setAttribute(SCRIPT_GENERATED, Boolean.TRUE);
     
      ResponseWriter writer = facesContext.getResponseWriter();
      writer.write("<script>");
      writer.write("window.addEvent('domready', function () {");
      writer.write("var form = document.forms['");
      writer.write(form.getId());
      writer.write("'];");
      writer.write("form.encoding='multipart/form-data';");
      writer.write("});");
      writer.write("</script>");
   }
  
   private UIForm getForm(UIComponent component) {
      while(component != null) {
         if (component instanceof UIForm) {
            return (UIForm) component;
         }
         component = component.getParent();
      }
      return null;
   }

}


3. CustomStartWorkflowWizard.java

package co.com.arkimia.alfresco.repo.workflow;

import javax.faces.context.FacesContext;

import org.alfresco.web.bean.workflow.StartWorkflowWizard;

/**
* Associates uploaded files to a workflow.
*
* TODO cambiar implementacion cuando se realice parche propuesto en
* http://issues.alfresco.com/browse/AR-1685. Borrar el metodo finishImpl
* @author jzuluaga
*
*/
public class CustomStartWorkflowWizard extends StartWorkflowWizard {

   private WorkflowFileUploader fileUploader;
   @Override
   protected String finishImpl(FacesContext context, String outcome)
         throws Exception {
      // TODO: Deal with workflows that don't require any data

      if (logger.isDebugEnabled())
         logger.debug("Starting workflow: " + this.selectedWorkflow);

      // prepare the parameters from the current state of the property sheet
      Map<QName, Serializable> params = WorkflowUtil
            .prepareTaskParams(this.startTaskNode);

      if (logger.isDebugEnabled())
         logger.debug("Starting workflow with parameters: " + params);

      // create a workflow package for the attached items and add them
      NodeRef workflowPackage = this.workflowService.createPackage(null);

        for (String addedItem : this.packageItemsToAdd)
        {
            NodeRef addedNodeRef = new NodeRef(addedItem);
            this.nodeService.addChild(workflowPackage, addedNodeRef,
                ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI,
                QName.createValidLocalName((String)this.nodeService.getProperty(
                        addedNodeRef, ContentModel.PROP_NAME))));
        }

      params.put(WorkflowModel.ASSOC_PACKAGE, workflowPackage);

      // setup the context for the workflow (this is the space the workflow
      // was launched from)
      Node workflowContext = this.navigator.getCurrentNode();
      if (workflowContext != null) {
         params.put(WorkflowModel.PROP_CONTEXT,
               (Serializable) workflowContext.getNodeRef());
      }

      // start the workflow to get access to the start task
      WorkflowPath path = this.workflowService.startWorkflow(
            this.selectedWorkflow, params);
      if (path != null) {
         // extract the start task
         List<WorkflowTask> tasks = this.workflowService
               .getTasksForWorkflowPath(path.id);
         if (tasks.size() == 1) {
            WorkflowTask startTask = tasks.get(0);

            if (logger.isDebugEnabled())
               logger.debug("Found start task:" + startTask);

            if (startTask.state == WorkflowTaskState.IN_PROGRESS) {
               // end the start task to trigger the first 'proper'
               // task in the workflow
               this.workflowService.endTask(startTask.id, null);
            }
         }

         if (logger.isDebugEnabled())
            logger.debug("Started workflow: " + this.selectedWorkflow);
      }

        //////////////////////////////////
      fileUploader.processUploadedFiles(this.startTaskNode, workflowPackage);
        /////////////////////////////////

      return outcome;
   }

   public WorkflowFileUploader getFileUploader() {
      return fileUploader;
   }

   public void setFileUploader(WorkflowFileUploader fileUploader) {
      this.fileUploader = fileUploader;
   }
}


4. CustomManageTaskDialog.java

package co.com.arkimia.alfresco.repo.workflow;

import java.io.IOException;

/**
* Custom implementation of the Manage task dialog; it has the same functionality of
* its parent class, but tries to attach any uploaded files to the workflow package
*
* @author Juan David Zuluaga Arboleda.
*/
public class CustomManageTaskDialog extends
      org.alfresco.web.bean.workflow.ManageTaskDialog {
   private WorkflowFileUploader fileUploader;

   /**
    * Perfors the uploaded files saving after the calling of
    * ManageTaskDialog.updateResources
    */
   protected void updateResources() {
      super.updateResources();

      try {
         fileUploader.processUploadedFiles(this.taskNode, workflowPackage);
      } catch (IOException e) {
         throw new RuntimeException(e);
      }
   }

   public WorkflowFileUploader getFileUploader() {
      return fileUploader;
   }

   public void setFileUploader(WorkflowFileUploader fileUploader) {
      this.fileUploader = fileUploader;
   }
}

5. WorkflowFileUploader.java

package co.com.arkimia.alfresco.repo.workflow;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.alfresco.web.bean.repository.Node;
import org.alfresco.web.bean.repository.Repository;
import org.apache.myfaces.custom.fileupload.UploadedFile;

/**
* Bean that saves content in the repository, whether it comes in the node properties
* as an uploaded file or it comes from an input stream.
* the file.
*
* @author Juan David Zuluaga Arboleda. Arkimia S.A.
*
*/
public class WorkflowFileUploader {
   private ContentService contentService;
   private FileFolderService fileFolderService;

   public ContentService getContentService() {
      return contentService;
   }

   public void setContentService(ContentService contentService) {
      this.contentService = contentService;
   }

   public FileFolderService getFileFolderService() {
      return fileFolderService;
   }

   public void setFileFolderService(FileFolderService fileFolderService) {
      this.fileFolderService = fileFolderService;
   }

   /**
    * Process uploaded files sent in the node properties, whether they comes as an
    * uploadedFile or a list of uploadedFile's
    * @param node the node in which the properties are inspected to find uploadedFiles.
    * @param nodePackage the package in which the content's gonna be saved.
    * @throws IOException if some problems occur trying to save content
    */
   public void processUploadedFiles(Node node, NodeRef nodePackage)
         throws IOException {
      Map<String, Object> props = node.getProperties();
      for (String propName : props.keySet()) {
         QName propQName = Repository.resolveToQName(propName);
         Object value = props.get(propName);
         if (value instanceof UploadedFile) {
            UploadedFile file = (UploadedFile) value;
            addUploadedFile(nodePackage, file);
         } else if (value instanceof ArrayList) {
            List lista = (List) value;
            for (Object uploadedFile : lista) {
               if (uploadedFile instanceof UploadedFile) {
                  addUploadedFile(nodePackage,
                        (UploadedFile) uploadedFile);
               }
            }
         }
      }
   }

   /**
    * Saves the uploadedFile into the repository in the nodePackage sent.
    * @param nodePackage the node in which the conten's gonna be saved
    * @param file the file to be saved; file name, content type and input stream
    * data is taken from this object.
    * @throws IOException
    */
   private void addUploadedFile(NodeRef nodePackage, UploadedFile file)
         throws IOException {
      String fileName = file.getName().substring(
            file.getName().lastIndexOf("\\") + 1);
      createContent(nodePackage, fileName, file.getContentType(),
            file.getInputStream());
   }

   /**
    * Creates content with the fileName name in the node package sent; saves
    * the inputStream with the contentType.
    *
    * @param nodePackage
    * @param fileName
    * @param contentType
    * @param inputStream
    * @throws IOException if file already exists or if some error trying to
    *  save it.
    */
   public void createContent(NodeRef nodePackage, String fileName,
         String contentType, InputStream inputStream) throws IOException {
      FileInfo fileInfo = fileFolderService.create(nodePackage, fileName,
            ContentModel.TYPE_CONTENT);
      NodeRef fileNodeRef = fileInfo.getNodeRef();

      ContentWriter writer = contentService.getWriter(fileNodeRef,
            ContentModel.PROP_CONTENT, true);
      // set the mimetype and encoding
      writer.setMimetype(contentType);
      writer.setEncoding("ISO-8859-1");
      writer.putContent(inputStream);
   }
}

6. faces-config-custom.xml

<managed-bean>
      <description>
         The bean that puts attached files into the workflow
      </description>
      <managed-bean-name>WorkflowFileUploader</managed-bean-name>
      <managed-bean-class>co.com.arkimia.alfresco.repo.workflow.WorkflowFileUploader</managed-bean-class>
      <managed-bean-scope>session</managed-bean-scope>
      <managed-property>
         <property-name>contentService</property-name>
         <value>#{ContentService}</value>
      </managed-property>
      <managed-property>
         <property-name>fileFolderService</property-name>
         <value>#{FileFolderService}</value>
      </managed-property>
   </managed-bean>

    <managed-bean>
      <managed-bean-name>StartWorkflowWizard</managed-bean-name>
      <managed-bean-class>co.com.arkimia.alfresco.repo.workflow.CustomStartWorkflowWizard</managed-bean-class>
      <managed-bean-scope>session</managed-bean-scope>
      <managed-property>
         <property-name>fileUploader</property-name>
         <value>#{WorkflowFileUploader}</value>
      </managed-property>
      <managed-property>
         <property-name>nodeService</property-name>
         <value>#{NodeService}</value>
      </managed-property>
      <managed-property>
         <property-name>fileFolderService</property-name>
         <value>#{FileFolderService}</value>
      </managed-property>
      <managed-property>
         <property-name>searchService</property-name>
         <value>#{SearchService}</value>
      </managed-property>
      <managed-property>
         <property-name>navigator</property-name>
         <value>#{NavigationBean}</value>
      </managed-property>
      <managed-property>
         <property-name>browseBean</property-name>
         <value>#{BrowseBean}</value>
      </managed-property>
      <managed-property>
         <property-name>dictionaryService</property-name>
         <value>#{DictionaryService}</value>
      </managed-property>
      <managed-property>
         <property-name>namespaceService</property-name>
         <value>#{NamespaceService}</value>
      </managed-property>
      <managed-property>
         <property-name>workflowService</property-name>
         <value>#{WorkflowService}</value>
      </managed-property>
    </managed-bean>

   <managed-bean>
      <description>
         The bean that backs up the Manage Task Dialog
      </description>
      <managed-bean-name>ManageTaskDialog</managed-bean-name>
      <managed-bean-class>co.com.arkimia.alfresco.repo.workflow.CustomManageTaskDialog</managed-bean-class>
      <managed-bean-scope>session</managed-bean-scope>
      <managed-property>
         <property-name>fileUploader</property-name>
         <value>#{WorkflowFileUploader}</value>
      </managed-property>
      <managed-property>
         <property-name>nodeService</property-name>
         <value>#{NodeService}</value>
      </managed-property>
      <managed-property>
         <property-name>fileFolderService</property-name>
         <value>#{FileFolderService}</value>
      </managed-property>
      <managed-property>
         <property-name>searchService</property-name>
         <value>#{SearchService}</value>
      </managed-property>
      <managed-property>
         <property-name>navigator</property-name>
         <value>#{NavigationBean}</value>
      </managed-property>
      <managed-property>
         <property-name>browseBean</property-name>
         <value>#{BrowseBean}</value>
      </managed-property>
      <managed-property>
         <property-name>dictionaryService</property-name>
         <value>#{DictionaryService}</value>
      </managed-property>
      <managed-property>
         <property-name>namespaceService</property-name>
         <value>#{NamespaceService}</value>
      </managed-property>
      <managed-property>
         <property-name>workflowService</property-name>
         <value>#{WorkflowService}</value>
      </managed-property>
      <managed-property>
         <property-name>avmService</property-name>
         <value>#{AVMLockingAwareService}</value>
      </managed-property>
      <managed-property>
         <property-name>avmSyncService</property-name>
         <value>#{AVMSyncService}</value>
      </managed-property>
   </managed-bean>

   <managed-bean>
      <description>
         Bean that generates a file upload component
      </description>
      <managed-bean-name>FileUploadGenerator</managed-bean-name>
      <managed-bean-class>
         co.com.arkimia.alfresco.web.bean.generator.FileUploadGenerator
      </managed-bean-class>
      <managed-bean-scope>request</managed-bean-scope>
   </managed-bean>

   <render-kit>
      <renderer>
         <component-family>javax.faces.Input</component-family>
         <renderer-type>co.com.arkimia.FileUpload</renderer-type>
         <renderer-class>co.com.arkimia.alfresco.web.ui.repo.renderer.FileUploadRenderer</renderer-class>
      </renderer>
   </render-kit>

7. web.xml

<filter>
      <filter-name>Extension Filter</filter-name>
      <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
   </filter>

   <filter-mapping>
      <filter-name>Extension Filter</filter-name>
      <url-pattern>/faces/jsp/wizard/container.jsp</url-pattern>
   </filter-mapping>
  
   <filter-mapping>
      <filter-name>Extension Filter</filter-name>
      <url-pattern>/faces/jsp/dialog/container.jsp</url-pattern>
   </filter-mapping>


Plz guide me.
Thanks.

Outcomes