2015-01-21 13 views
0

변수를 초기화하고 HTML의 텍스트 필드와 결합하려고합니다. 함수를 호출 할 때이 변수를 사용하여 데이터베이스에 무언가를 삽입하려고합니다. 하지만 현재 필드에 null 값이 계속 표시됩니다. 어떤 아이디어?올바른 변수 초기화 방법 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

여기서 bean 클래스의 refNumber는 무엇입니까 ?? 또는 표시되지 않는 오류? 예. doAction null로 해결 ... –

+0

그냥 문자열을 사용할 수 있습니까? – David

+0

xNhtml에서 myNumber로 refNumber를 변경하거나 bean 클래스에서 refNumber로 myNumber를 변경하십시오. –

답변

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

+0

질문에 입력 한 내용이 잘못되었음을 의미합니까? –

+0

그래, 죄송합니다 지금은 그것이 정확합니다 – David