AnsweredAssumed Answered

why i am not able to move the content  to failure ?

Question asked by jetty on Jun 29, 2011
Latest reply on Jun 29, 2011 by mrogers
Hi ,
     I am working with  category creation .here I have set up an rule for csv(comma separated values )file in the space  which in turn will call another java file .  In turn this java file will look for errors or any special characters are there or not  and  it will move the file to success or failure spaces accordingly .it will create a category's as given in csv file . they will take each string and create a category in that name  .if there is any error in string i.e any special character is found it will create category's up to the correct strings and  it will log an error text file inside  error log space specifying the error and where it occurred   .so my problem is I am able to move it to failure  if  there is any error in that csv file i.e if it finds any string with special character's .it should move to failure folder below  is  my  code  
.




public class CreateCategoryExecuter extends ActionExecuterAbstractBase {
   public static NodeRef currentNode=null;
   NodeRef parent1 = null;
   ResultSet resultSet_content = null;
   NodeRef dest_node = null;
   SearchParameters search_content = new SearchParameters();
   BufferedReader reader = null;
   String category = null;
   static String error = null;
   public static final String ERROR_FILENAME = "Errorlog";
   private static final String EOF_NAME = ".txt";
   private static final String COMPANY_PATH = "/app:company_home/cm:";
   private static final String CSV_PATH = "Kaplan/cm:Admin/cm:CreateCategory";
   private static final int RESULT_INDEX = 0;
   public static String strLine = "";
   private StringBuffer errorSB;
   private static final String ERROR_MSG = "Creating Cusom Category Failed ";
   private static final String ERROR_MSG1 = ". Error :";
   private static final String SUCCESS_FOLDER = "Success";
   private static final String FAILURE_FOLDER = "Failure";
   private static final String ERRORLOG_FOLDER = "ErrorLog";

   // private static final String ERROR_MSG2
   // ="Following failed during Category Creation.";

   protected SearchService searchService;
   protected ContentService contentService;
   protected NodeService nodeService;
   protected FileFolderService fileFolderService;
   protected WorkflowService workflowService;
   protected PersonService personService;
   protected AuthenticationService authenticationService;
   protected NamespaceService namespaceService;
   protected CategoryService categoryService;
   protected TransactionService transactionService;

   ResultSet resultSet1 = null;
   String path = COMPANY_PATH;
   UserTransaction tx = null;

   private static Log logger = LogFactory.getLog(CreateCategoryExecuter.class);

   public TransactionService getTransactionService() {
      return transactionService;
   }

   public void setTransactionService(TransactionService transactionService) {
      this.transactionService = transactionService;
   }

   public PersonService getPersonService() {
      return personService;
   }

   public void setPersonService(PersonService personService) {
      this.personService = personService;
   }

   public AuthenticationService getAuthenticationService() {
      return authenticationService;
   }

   public void setAuthenticationService(
         AuthenticationService authenticationService) {
      this.authenticationService = authenticationService;
   }

   public NamespaceService getNamespaceService() {
      return namespaceService;
   }

   public void setNamespaceService(NamespaceService namespaceService) {
      this.namespaceService = namespaceService;
   }

   public WorkflowService getWorkflowService() {
      return workflowService;
   }

   public void setWorkflowService(WorkflowService workflowService) {
      this.workflowService = workflowService;
   }

   public NodeService getNodeService() {
      return nodeService;
   }

   public void setNodeService(NodeService nodeService) {
      this.nodeService = nodeService;
   }

   public FileFolderService getFileFolderService() {
      return fileFolderService;
   }

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

   public SearchService getSearchService() {
      return searchService;
   }

   public ContentService getContentService() {
      return contentService;
   }

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

   public void setSearchService(SearchService searchService) {
      this.searchService = searchService;
   }

   public CategoryService getCategoryService() {
      return categoryService;
   }

   public void setCategoryService(CategoryService categoryService) {
      this.categoryService = categoryService;
   }

   protected void executeImpl(Action arg0, NodeRef actionedUponNodeRef) {
      currentNode=actionedUponNodeRef;
      List<String> categories = null;
      errorSB = new StringBuffer();
      PropertyFileReader prop = PropertyFileReader.getInstance();
      String pathSplit = prop.getKeyValue("commaSpliter");

      try {
         ContentReader contentReader = contentService.getReader(
               actionedUponNodeRef, ContentModel.PROP_CONTENT);
         InputStream is = contentReader.getContentInputStream();
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
         String sample = new Node(actionedUponNodeRef).getName().toString();
         System.out.println(sample + System.currentTimeMillis());

         StringTokenizer st = null;
         int lineNumber = 0, tokenNumber = 0;
         if (contentReader.getSize() == 0) {
            errorSB.append("The CSV File is Empty");
         }

         try {
            while ((strLine = br.readLine()) != null) {
               categories = new ArrayList<String>();
               lineNumber++;
               st = new StringTokenizer(strLine, pathSplit);
               NodeRef parent = null;
               while (st.hasMoreTokens()) {
                  tokenNumber++;
                  String temp = st.nextToken();
                  if (isNotValidString(temp) || "".equals(temp)) {
                     errorSB.append("Special Characters are present");
                     continue;
                  }
                  categories.add(temp);
                  System.out.println("Token : " + temp);
                  parent = createCategoryy(parent, categories);
               }

               tokenNumber = 0;
            }
            System.out.println(" ERRO LOGGGGG ::: ");
            System.out.println(" ——————-");

            /*
             * String errorS=errorSB.toString(); System.out.println(errorS);
             */
         } catch (IOException e) {
            e.printStackTrace();
         } catch (AlfrescoRuntimeException e) {
            error = error + e.getMessage() + ",";
            System.out.println("Main exception : " + e.getMessage());
            // throw new
            // AlfrescoRuntimeException("Exception : Illegal characters identified");
         }

      } catch (FileExistsException fileExistsException) {
         fileExistsException.printStackTrace();
      } finally {
         try {
            if ("".equals(errorSB.toString())) {
               moveTo(actionedUponNodeRef, SUCCESS_FOLDER);
            }
            if (errorSB != null && !"".equals(errorSB.toString())) {
               moveTo(actionedUponNodeRef, FAILURE_FOLDER);
               createErrorlog(errorSB);
               System.out.println("Exception OCCURED……….! "
                     + errorSB);
            }

         }

         catch (FileExistsException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }

   }

   private void moveTo(NodeRef csvFileNodeRef, String folderName)
         throws FileExistsException, FileNotFoundException {
      NodeRef folderNodeRef = null;
      String fileName = new Node(csvFileNodeRef).getName().toString() + "_"
            + System.currentTimeMillis();
      String queryString = COMPANY_PATH + CSV_PATH + "/cm:" + folderName;
      StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE,
            "SpacesStore");
      ResultSet resultSet = this.searchService.query(storeRef,
            SearchService.LANGUAGE_XPATH, queryString);
      System.out.println("length:" + resultSet.length());
      if (resultSet.length() == 0) {
         throw new AlfrescoRuntimeException(
               "Did not find the space to move the CSV file.");
      }
      ResultSetRow row = resultSet.getRow(0);
      folderNodeRef = row.getNodeRef();
      System.out.println("folder name:" + new Node(folderNodeRef).getName());
      
   }

   public NodeRef getGenClassifiableNodeRef() {
      NodeRef parent = null;
      try {
         String qry = "TYPE:\"{http://www.alfresco.org/model/content/1.0}category\" AND  PATH:\"/cm:generalclassifiable\"";
         Repository.getServiceRegistry(FacesContext.getCurrentInstance())
               .getSearchService();
         StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE,
               "SpacesStore");
         ResultSet resultSet = searchService.query(storeRef,
               SearchService.LANGUAGE_LUCENE, qry);

         parent = resultSet.getNodeRef(0);
      } catch (Exception e) {
         error = error + e.getMessage() + ",";
         System.out.println("Error : getGenClassifiableNodeRef() "
               + e.getMessage());
         // throw new
         // AlfrescoRuntimeException("Exception : Illegal characters identified");
      }
      String sample_input = new Node(parent).getName();
      System.out.println("Parent name ::::  " + sample_input);
      return parent;

   }

   private ResultSet getCategoryResultSet(NodeRef parent,
         List<String> categories) {
      ResultSet resultSet = null;
      StringBuffer categoryBuffer = new StringBuffer();
      for (String category : categories) {
         categoryBuffer = categoryBuffer.append("/cm:" + category);
      }

      try {
         String qry = "TYPE:\"{http://www.alfresco.org/model/content/1.0}category\" AND  PATH:\"/cm:generalclassifiable"
               + categoryBuffer + "\"";
         System.out.println(" QUERY ::::: " + qry);
         Repository.getServiceRegistry(FacesContext.getCurrentInstance())
               .getSearchService();

         StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE,
               "SpacesStore");
         resultSet = searchService.query(storeRef,
               SearchService.LANGUAGE_LUCENE, qry);
      } catch (Exception ex) {
         ex.printStackTrace();
         errorSB.append(ERROR_MSG);
         errorSB.append(ERROR_MSG1);
         errorSB.append(ex.getMessage() + ",");
         errorSB.append("\n");
         logger.error(
               "com.kpub.web.bean.action.executer.CreateCategoryExecuter",
               ex);
      }

      return resultSet;

   }

   private boolean isCategoryPresent(ResultSet resultSet) {
      try {
         if (null != resultSet && resultSet.length() <= 0) {
            return false;
         }
      } catch (Exception e) {
         error = error + e.getMessage() + ",";
         System.out.println("Error : isCategoryPresent " + e.getMessage());
         // throw new
         // AlfrescoRuntimeException("Exception : Illegal characters identified");
      }
      return true;
   }

   private NodeRef getCategoryNodeRef(ResultSet resultSet) {
      return resultSet.getNodeRef(0);
   }

   public NodeRef createCategoryy(NodeRef parent, List<String> categories) {

      try {
         if (parent == null) {
            parent = getGenClassifiableNodeRef();
         }
         ResultSet resultSet = getCategoryResultSet(parent, categories);
         if (isCategoryPresent(resultSet)) {
            parent = getCategoryNodeRef(resultSet);
         } else {
            String temp = categories.get(categories.size() - 1);
            System.out.println("Temp ::: " + temp);

            parent = categoryService.createCategory(parent, temp);

            System.out.println("Created category::" + temp);
         }
      } catch (AlfrescoRuntimeException e) {
         error = error + e.getMessage() + ",";
         System.out.println("Error : createCategoryy " + e.getMessage());
      }
      return parent;
   }

   private void createErrorlog(StringBuffer errorSB) {
      System.out.println("Entered ErrorLog method……..");
      ResultSet resultSet = null;
      String fileName = ERROR_FILENAME + System.currentTimeMillis()
            + EOF_NAME;
      String queryString = COMPANY_PATH + CSV_PATH + "/cm:" + ERRORLOG_FOLDER;
      StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE,
            "SpacesStore");
      resultSet = searchService.query(storeRef, SearchService.LANGUAGE_XPATH,
            queryString);
      try {
         if (resultSet.length() == 0) {
            throw new AlfrescoRuntimeException(
                  "Did not find the space to store the error log::");
         }

         ResultSetRow row = resultSet.getRow(RESULT_INDEX);
         FileInfo fileInfo = this.fileFolderService.create(row.getNodeRef(),
               fileName, ContentModel.TYPE_CONTENT);

         NodeRef fileRef = fileInfo.getNodeRef();

         // add titled aspect for the read/edit properties screens
         Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(
               1, 1.0f);

         titledProps.put(ContentModel.PROP_TITLE, fileName);
         this.nodeService.addAspect(fileRef, ContentModel.ASPECT_TITLED,
               titledProps);

         // push the content of the file into the node
         ContentWriter writer = this.contentService.getWriter(fileRef,
               ContentModel.PROP_CONTENT, true);

         // writer.setMimetype(this.mimetypeService.guessMimetype(fileName));
         String error = errorSB.toString();
         writer.putContent(error);
         System.out.println("ErrorLog created………..");
         // startWorkflow(fileRef);
         return;
      } catch (Exception e) {
         System.out.println("Failed to create the errorLog::"
               + e.getMessage());
      }

   }

   private void startWorkflow(NodeRef content) {
      NodeRef wfPackage = this.workflowService.createPackage(null);
      this.nodeService.addChild(wfPackage, content,
            ContentModel.ASSOC_CONTAINS, QName.createQName(
                  NamespaceService.CONTENT_MODEL_1_0_URI, QName
                        .createValidLocalName((String) this.nodeService
                              .getProperty(content,
                                    ContentModel.PROP_NAME))));

      NodeRef assigneeNodeRef = this.personService
            .getPerson(this.authenticationService.getCurrentUserName());
      Map<QName, Serializable> workflowProps = new HashMap<QName, Serializable>(
            16);
      workflowProps.put(WorkflowModel.ASSOC_PACKAGE, wfPackage);
      workflowProps.put(WorkflowModel.PROP_DESCRIPTION,
            "Creating categories Error Report");
      workflowProps.put(WorkflowModel.PROP_PRIORITY, 1);
      workflowProps.put(WorkflowModel.ASSOC_ASSIGNEE, assigneeNodeRef);

      // get the moderated workflow
      WorkflowDefinition wfDefinition = this.workflowService
            .getDefinitionByName("jbpm$custom:ContentNotFoundWF");
      if (wfDefinition == null) { // handle workflow definition does not exist
         throw new AlfrescoRuntimeException(
               "no workflow found in name : jbpm$custom:ContentNotFoundWF");
      }
      // start the workflow
      WorkflowPath wfPath = this.workflowService.startWorkflow(wfDefinition
            .getId(), workflowProps);

      String wfPathId = wfPath.id;
      List<WorkflowTask> wfTasks = workflowService
            .getTasksForWorkflowPath(wfPathId);

      WorkflowTask wfFirstStartTask = wfTasks.get(0);
      this.workflowService.endTask(wfFirstStartTask.id, null);

      logger.debug("Workflow started successfully");
      return;
   }

   @Override
   protected void addParameterDefinitions(List<ParameterDefinition> arg0) {

   }

   public boolean isNotValidString(String category) {
      boolean valid = false;
      Pattern escaper = Pattern.compile("[^a-zA-Z0-9]");
      valid = escaper.matcher(category).find();
      if (category.contains("^") || category.contains("[")
            || category.contains("]")) {
         valid = true;
         
      }
      if(valid) {
      
         errorSB.append("Can't create category for " + category);
      }
      return valid;

   }

}

Outcomes