2015-01-21 36 views
0

我想初始化一個變量,並希望它與HTML中的文本字段相結合。 當我調用一個函數時,我想用這個變量在數據庫中插入一些東西。但目前我一直得到該字段的空值。有任何想法嗎 ? (請參見下面的代碼)初始化變量seam的正確方法

目前我有這樣的:

Name("orderUploadAction") 
@Scope(ScopeType.CONVERSATION) 
public class OrderUploadAction implements Serializable { 

    public static final int MAX_SYNC_PART_AMOUNT = 50; 

    private final static String SEAM_UPLOAD = "seamUpload"; 
    private final static String COMMONS_UPLOAD = "commonsUpload"; 

    @Logger 
    static Log log; 

    @In 
    Identity identity; 

    @In(create = true) 
    private ProductDao productDao; 

    @In(scope = ScopeType.SESSION) 
    private PortalUserHome portalUserHome; 

    @In(create=true,required=false,scope=ScopeType.CONVERSATION) 
    private String refNumber; 


    @In 
    private EntityManager entityManager; 

    private UploadItem uploadItem; 
    private ArrayList<String> errors = null; 

    @In(required=false,scope=ScopeType.CONVERSATION) 
    @Out(required=false) 
    private String refNumber; 


    @Email 
    private String email; 





    public 

    // Upload Method 
    boolean usedSeamBuildInUpload = true; 

    // Apache Commons FileUpload 
    byte[] byteArray; 


    public OrderUploadAction() { 

    } 

    @Create 
    public void init(){ 
     log.debug("Initing CONVERSATION component FileUploadAction..."); 
     uploadItem = null; 
     errors = new ArrayList<String>(); 
     errors.clear(); 
     refNumber = ""; 

    } 

    // listener for the upload function on fileUpload.xhtml 
    public void listener(UploadEvent event) throws Exception { 
     uploadItem = event.getUploadItem(); 
     log.debug("File uploaded with name: #0", uploadItem.getFileName()); 
    } 

    public String decideWhatToDo(){ 

     errors = new ArrayList<String>(); 
     String s = refNumber; 
     String x = customerOrderHome.getInstance().getReferenceNumber(); 
     System.out.println(s); 
     if(refNumber == null || refNumber == ""){ 
      errors.add("Please fill in a P.O number before starting upload"); 
      return "error"; 

     } 
     else if(uploadItem == null || uploadItem.getData() == null){ 
       log.debug("Cannot decide, there is no file"); 
       log.debug("-> Decision outcome: ERROR"); 
       return "error"; 
      } 
     else{ 
      doSyncProcessing(); 
      return "success"; 
     } 







    } 

    /** 
    * @return the refNumber 
    */ 
    public String getRefNumber() { 
     return refNumber; 
    } 

    /** 
    * @param refNumber the refNumber to set 
    */ 
    public void setRefNumber(String refNumber) { 
     this.refNumber = refNumber; 
    } 

    /** 
    * @param errors the errors to set 
    */ 
    public void setErrors(ArrayList<String> errors) { 
     this.errors = errors; 
    } 

    private String doSyncProcessing() { 
     return doSyncProcessing(true, false); 
    } 



    public String doSyncProcessing(boolean buildInSeamUpload, boolean convarFlag){ 
     usedSeamBuildInUpload = buildInSeamUpload; 
     log.debug("Starting SYNCHRONOUS processing..."); 

     ByteArrayInputStream bis = null; 
     if(usedSeamBuildInUpload) { 
      bis = new ByteArrayInputStream(uploadItem.getData()); 
     }else { 
      bis = new ByteArrayInputStream(byteArray); 
     } 

     return createOrder(null,bis,identity, convarFlag); 
    } 



    public String createOrder(String email,InputStream bis,Identity identity, boolean convarFlag){ 
     log.debug("Transforming to a Order"); 
     // Load the byte array to an input stream for reading. 



     // Load the input stream to a buffered reader to read the data. 
     BufferedReader br = new BufferedReader(new InputStreamReader(bis)); 

     String csvLine; 
     int nextTxt = 0; 
     int index = 0; 
     UploadOrderItem item = new UploadOrderItem(); 
     ArrayList<UploadOrderItem> items= new ArrayList<UploadOrderItem>(); 
     // here we go... 
     try { 
      // start reading 
      while ((csvLine = br.readLine()) != null) { 
       if(!csvLine.toUpperCase().contains("PRODUCTCODE")){ 

        if (!(csvLine.equals("EOF"))) { 

         nextTxt = 0; 
         index = 2; 

         for(int i=0;i<csvLine.length();i++) { 

          if(csvLine.charAt(i) == ';'){ 
           switch(index){ 

           /*case 0: 
            item.setCustomerSAP(Integer.parseInt(csvLine.substring(0, (i)).trim())); 
           break;*/ 

           /*case 1: 
            item.setRefPO(csvLine.substring(nextTxt,(i)).trim()); 
           break;*/ 

           case 2: 
            item.setProductCode(csvLine.substring(nextTxt,(i)).trim()); 
           break; 

           case 3: 
            try{ 
             int quantity = Integer.parseInt(csvLine.substring(nextTxt,(i)).trim()); 
             item.setQuantity(Integer.parseInt(csvLine.substring(nextTxt,(i)).trim())); 
            }catch(Exception e){ 
             errors.add("Quantity incorrect with productcode "+item.getProductCode()); 
            } 
           break; 

           } 
            index++; 
            nextTxt = i +1; 

          } 

         } 
         if(csvLine.substring(nextTxt,csvLine.length()).trim().equals("Y")){ 

          item.setFOC(true); 

         } 
         else if(!csvLine.substring(nextTxt,csvLine.length()).trim().equals("")){ 
          errors.add("Free of charge incorrect with productcode "+item.getProductCode()); 
         } 
         items.add(item); 
         item = new UploadOrderItem(); 

        } else { 
         index =0; 
         break; 
        } 

       } 

      } 


     } catch (IOException e) { 
      log.debug("IOException occured when reading the CSV file."); 
     } catch (Exception e) { 
      log.error("Intern error occured while processing the CSV file!"); 
     } 


     // close the reader 
     try{ 
      br.close(); 
     } catch (IOException e) { 
      log.warn("Buffered Reader from file upload could not be closed for some reason..."); 
     } 

     log.debug("-> Transformation done!"); 

     //Check items 
     CustomerOrder currentOrder = new CustomerOrder(); 

     OrderItem oItem; 

     for (UploadOrderItem ul : items) { 
      oItem = new OrderItem(); 
      oItem.setCurrency("EUR"); 
      Product x = null; 
      try{ 
       x = productDao.findProductByProductCode(ul.getProductCode()); 
       oItem.setProduct(x); 
      }catch(Exception e){ 
       log.error("Error occured while getting product"); 
       errors.add("Error getting product for "+ul.getProductCode()+"\n"); 
       e.printStackTrace(); 
      } 

      if(ul.isFOC()){ 
       int foc = 100; 
       oItem.setDiscountType(DiscountType.PERCENTAGE); 
       oItem.setDiscountValue(BigDecimal.valueOf(foc)); 
      } 

      oItem.setQuantity(ul.getQuantity()); 
      oItem.setStatus(OrderStatus.INITIAL); 
      oItem.setTotalNetPrice(null); 
      oItem.setVatAmount(null); 
      oItem.setVatRate(null); 
      oItem.setTotalSurcharges(null); 
      oItem.setCustomerOrder(currentOrder); 
      currentOrder.getOrderItems().add(oItem); 
      currentOrder.setReferenceNumber(refNumber); 
     } 

     String fullName = ""; 
     if(portalUserHome.getInstance().getFirstName() != null) { 
      fullName+= portalUserHome.getInstance().getFirstName() + " "; 
     } 
     if (portalUserHome.getInstance().getLastName() != null) { 
      fullName += portalUserHome.getInstance().getLastName(); 
     } else { 
      fullName = fullName.trim(); 
     } 

     currentOrder.setCreatorFullName(fullName); 
     currentOrder.setCreatorUserName(portalUserHome.getInstance().getUserName()); 
     currentOrder.setCreatedOn(new Date()); 

     customerOrderHome.setInstance(currentOrder); 

     Customer customer = entityManager.find(Customer.class, portalUserHome.getInstance() 
       .getCustomer().getId()); 

     portalUserHome.getInstance().setCustomer(customer); 

     customerOrderHome.getInstance().setCustomer(customer); 
     customerOrderHome.getInstance().setAddress(customer.getDefaultAddress()); 

     if(errors.size()==0){ 
      try{ 
       customerOrderHome.persist(); 
      }catch(Exception e){ 
       e.printStackTrace(); 
      } 
     } 
     else{ 
      return "error"; 
     } 




     return "success"; 
    } 


    /** 
    * Very fast method to give an approximate number of lines in the file 
    * @param data A byte[] representing the data 
    * @return int The number of lines 
    * @throws IOException If IO exceptions occurs 
    */ 
    private int count(byte[] data) throws IOException {  
     ByteArrayInputStream is = new ByteArrayInputStream(data); 
     try { 
      byte[] c = new byte[1024]; 
      int count = 0; 
      int readChars = 0; 
      while ((readChars = is.read(c)) != -1) { 
       for (int i = 0; i < readChars; ++i) { 
        if (c[i] == '\n') 
         ++count; 
       } 
      } 
      return count; 
     } finally { 
      is.close(); 
     } 
    } 



    public String getEmail() { 
     return email; 
    } 

    public void setEmail(String email) { 
     this.email = email; 
    } 


    // GETTERS & SETTERS 



    public List<String> getErrors() { 
     return errors; 
    } 

和XHTML:

<ui:composition xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:s="http://jboss.com/products/seam/taglib" 
    xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:f="http://java.sun.com/jsf/core" 
    xmlns:c="http://java.sun.com/jstl/core" 
    xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:rich="http://richfaces.org/rich" 
    xmlns:a="http://richfaces.org/a4j" 
    xmlns:pioneer="http://www.pioneer.com/jsf" 
    template="/layout/template.xhtml"> 


    <ui:define name="body"> 

     <h1> 
      <h:outputText value="#{messages.upload_title}" /> 
     </h1> 

     <div class="clearfix"> 

      <rich:panel> 
       <script> 

        function showErrors(){ 
         alert("File upload has failed please see the output below the fileupload"); 

        } 

        function showComplete(){ 
         alert("File successfully processed. Orders are placed."); 
        } 

       </script> 

       <s:div styleClass="block bgcolor-6" id="orderSearchFields"> 
        <div class="hd"> 
         <h3>#{messages.upload_subTitle}</h3> 
        </div> 

        <div class="bd"> 
         #{messages.upload_info}<br /> #{messages.upload_csv}<br /> 



         <br /> 

         <s:decorate id="refNumBer" template="/layout/editShort.xhtml"> 
          <h:inputText id="refNumBer" 
           value="#{orderUploadAction.refNumber}" styleClass="txt" /> 
         </s:decorate> 


         <a:status for="uploadRegion" 
          onstart="Richfaces.showModalPanel('confirmWait');"> 
          <f:facet name="start"> 
           <h:column> 
            <br /> 
            <h:outputText> 
             <b>#{messages.upload_wait_process}</b> 
            </h:outputText> 
            <h:graphicImage value="/img/pioneer/spinner.gif" /> 
           </h:column> 
          </f:facet> 
         </a:status> 
        </div> 
       </s:div> 
       <h:form> 
         <rich:panel id="fileUpload"> 
         <a:region id="uploadRegion"> 
          <rich:fileUpload 
           fileUploadListener="#{orderUploadAction.listener}" id="upload" 
           addControlLabel="Add" acceptedTypes="csv" maxFilesQuantity="1"> 
           <a:support event="onuploadcomplete" 
            action="#{orderUploadAction.decideWhatToDo()}" 
            reRender="errorUpload,fileUpload" /> 
            <!-- oncomplete="if (#{orderUploadAction.errors.size()==0}) {showComplete();} 
            else{showErrors();} "--> 
          </rich:fileUpload> 
         </a:region> 


        </rich:panel> 

       </h:form> 
       <br /> 

       <!-- <rich:panel id="errorUpload" rendered="orderUploadAction.errors !=0"> 

        <c:forEach items="#{orderUploadAction.errors}" var="error"> 
         <h:outputText value="#{error}" style="color:red"> 
         </h:outputText> 
         <br /> 
        </c:forEach> 

       </rich:panel>--> 
      </rich:panel> 
     </div> 
    </ui:define> 
</ui:composition> 
+0

你的refNumber在bean類中哪裏?或任何錯誤不顯示??例如。 doAction解析爲空... – 2015-01-21 07:47:06

+0

我不能只使用一個字符串嗎? – David 2015-01-21 07:49:01

+0

在xhtml中將refNumber更改爲myNumber,或將myNumber更改爲bean類中的refNumber。 – 2015-01-21 07:51:16

回答

1

如果你想在你orderUploadAction.decideWhatToDo()動作事件初始化variablen。 我認爲你的表格標籤應該移動到開始。 例如。

<h:form> 
    <s:div styleClass="block bgcolor-6" id="orderSearchFields"> 
    ... 

<s:decorate id="refNumBer" template="/layout/editShort.xhtml"> 
          <h:inputText id="refNumBer" 
           value="#{orderUploadAction.refNumber}" styleClass="txt" /> 
         </s:decorate> 

    ... 
    decideWhatToDo() action.. 
    ... 
    </h:form> 
+0

對不起myNumber是refNumber。我輸入了它。 – David 2015-01-21 07:52:30

+0

這意味着你的輸入在問題中是錯誤的? – 2015-01-21 07:53:01

+0

對不起,現在是正確的 – David 2015-01-21 07:54:05