简体   繁体   中英

PrimeFaces add row to DataTable

I want to make a Log-File-Reader. I have a Upload field, and a dataTable. First I choose the Log-File an Upload it. Then the program Split each line of the Log-File in the separate variables. Now the Log-File should be printet line for line into the table. But I dont know, how i should put the Lines in the Table. It works, when I define the Lines Static bevore. But now when the lines are not defined static it don't update the Table.

Here is my index.xhtml:

<h:form xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:p="http://primefaces.org/ui">
<h:head>
    <title>LogReader</title>
</h:head>
<h:body>
    <p:accordionPanel dynamic="true" cache="true" activeIndex="1" multiple="false"> 
       <p:tab title="Upload File"> 
            <h:panelGrid> 
                <p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}" mode="advanced" dragDropSupport="false" 
                update="messages" fileLimit="1"  allowTypes="/(\.|\/)(log|txt|)$/" /> 

                <p:growl id="messages" showDetail="true"/> 
            </h:panelGrid> 
        </p:tab> 
    </p:accordionPanel>

    <p:dataTable id="dataTable" var="log" value="#{fileUpload.logsSmall}" widgetVar="dataTable"   
                 emptyMessage="No Log found with given criteria" filteredValue="#{tableBean.filteredLogs}"
                 rowKey="#{log.datetime}" paginator="true" rows="20" paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,15,20,50,100" selection="#{tableBean.selectedLog}" selectionMode="single"> 

     <f:facet name="header"> 
        <p:outputPanel> 
            <h:outputText value="Search all fields:" /> 
            <p:inputText id="globalFilter" onkeyup="dataTable.filter();" style="width:150px" /> 
        </p:outputPanel> 
    </f:facet> 

    <p:column id="datetimeColumn" filterBy="datetime" sortBy="datetime"   
            headerText="DateTime" footerText="" 
            filterMatchMode="contains"> 
        <h:outputText value="#{log.datetime}" />
    </p:column> 

    <p:column id="levelColumn" filterBy="level"   
            headerText="LogLevel" footerText="" 
            filterOptions="#{tableBean.levelOptions}" 
            filterMatchMode="exact" sortBy="level"> 
        <h:outputText value="#{log.level}" />
    </p:column> 

    <p:column id="categoryColumn" filterBy="category" sortBy="category"
            headerText="Category" footerText="" 
            filterMatchMode="contains"> 
        <h:outputText value="#{log.category}" />
    </p:column> 

    <p:column id="messageColumn" filterBy="message" sortBy="message" 
            headerText="Message" footerText="" filterMatchMode="contains"> 
        <h:outputText value="#{log.message}" />
    </p:column> 
</p:dataTable>
</h:body>

Here my TableBean:

    package com.rausch.logreader; 

import java.io.Serializable; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.UUID; 
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;

import com.rausch.logreader.Log;

@ViewScoped
@ManagedBean(name = "tableBean")
@SessionScoped

public class TableBean implements Serializable { 

    private final static String[] level;

    private SelectItem[] levelOptions; 

    private List<Log> filteredLogs; 

    private int i = 0;

    private Log selectedLog; 

    private Log[] selectedLogs;


    static { 
        level = new String[5];
        level[0] = "DEBUG";
        level[1] = "INFO";
        level[2] = "WARN";
        level[3] = "ERROR";
        level[4] = "FATAL"; 

    } 


    public TableBean() { 
        levelOptions = createLevelOptions(level); 
    } 

    public Log getSelectedLog() { 
        return selectedLog; 
    } 

    public void setSelectedLog(Log selectedLog) { 
        this.selectedLog = selectedLog; 
    } 

    public void listAdd(List<Log> list, String datetime, String level, String category, String message){
        list.add(new Log(datetime, level, category, message));
    }


    public List<Log> getFilteredLogs() { 
        return filteredLogs; 
    } 

    public void setFilteredLogs(List<Log> filteredCars) { 
        this.filteredLogs = filteredCars; 
    } 

    private SelectItem[] createLevelOptions(String[] data)  { 
        SelectItem[] options = new SelectItem[data.length + 1]; 

        options[0] = new SelectItem("", "Select"); 
        for(int i = 0; i < data.length; i++) { 
            options[i + 1] = new SelectItem(data[i], data[i]); 
        } 

        return options; 
    } 

    public SelectItem[] getLevelOptions() { 
        return levelOptions; 
    } 
} 

And here my FileUploadController:

import java.util.List;
import javax.faces.application.FacesMessage; 
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext; 

import org.primefaces.event.FileUploadEvent; 
import org.primefaces.model.UploadedFile;

@ViewScoped
@ManagedBean(name = "fileUploadController")
@SessionScoped

public class FileUploadController { 

    public List<Log> logsSmall;
    public void handleFileUpload(FileUploadEvent event) { 

        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); 
        FacesContext.getCurrentInstance().addMessage(null, msg);

        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 

    private String destination="C:\\Java\\";

    public void copyFile(String fileName, InputStream in) {
        try {           
             // write the inputStream to a FileOutputStream
             OutputStream out = new FileOutputStream(new File(destination + fileName));

             int read;
             byte[] bytes = new byte[1024];

             while ((read = in.read(bytes)) != -1) {
                 out.write(bytes, 0, read);
             }

             in.close();
             out.flush();
             out.close();

             readFile(destination + fileName);
        } catch (IOException e) {
                 System.out.println(e.getMessage());
        }
    }


    public void readFile(String filePath){
               try
        {
            String sCurrentLine;


            BufferedReader br = new BufferedReader(new FileReader(filePath));           
            String output;
            String datetime = "";
            String level = "";
            String category = "";
            String message;

            TableBean table = new TableBean();

            while ((sCurrentLine = br.readLine()) != null) {
                //System.out.println(sCurrentLine.charAt(4) + "" +  sCurrentLine.charAt(7) + sCurrentLine.charAt(13)  + "" +sCurrentLine.charAt(16));
                if(sCurrentLine.length()<1){                   
                }
                else{
                    if (sCurrentLine.length() >= 16 && sCurrentLine.charAt(4)=='-' && sCurrentLine.charAt(7)=='-' && sCurrentLine.charAt(13)==':' && sCurrentLine.charAt(16)==':'){
                        output = "";
                        message = "";
                        String[] leerzeichen = sCurrentLine.split(" ");

                        datetime = leerzeichen[0] + " " + leerzeichen[1];
                        level = leerzeichen[2];
                        category = leerzeichen[4];

                        int arraylength = leerzeichen.length;

                        for (int l=5; l<arraylength; l++){
                            message = message.concat(leerzeichen[l] + " ");
                        }
                        output = datetime + level + category + message;
                    } else {
                        message = sCurrentLine;     
                        output  = message;
                    }
                    logsSmall = new ArrayList<Log>();
                    table.listAdd(logsSmall, datetime, level, category, message);
                    System.out.println(output);
                }

            }


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}  

Sorry for my bad English. I try to Ask an other way: I want to have a program, where I can upload a *.log File and read it in a table. I open the xhtml, and there is a empty table. Than I Upload the File with the <:pFileUpload. The File Upload Controller takes the Log-File and split each line in the values (datetime, Level, Category and message). Then the Script should add a new row to the table width the datas of the Log-File-Line. Then it goes to the next Line and parses the Text. At the End the Table should show the content of the Log-File. The Problem is, that the Table don't Reload. Or i don't know how i should reload it. When I upload the File, the script correctly read each Line of the Log-File. But the table keeps empty.

I quite don't understand what is yourt question what i see some lack of understanding on how to use the beans to manage the view.

First, you have @ViewScoped and @SessionScoped declared at the same time. There must be only one.

Second, the thing about defining managed beans it's that you don't have to manage the creation or destruction on them, the system does. Thats why they are called managed. So doing this:

TableBean table = new TableBean();

is useless. You are creating and instance of an object inside a funcion. Outside that function the object is unreacheable, as the annotations aren't considered if you create the object in your code.

I would have one managed bean that handles the events on the view, like this:

@ViewScoped
@ManagedBean(name = "logViewController")

public class LogViewController{ 

private List<Log> filteredLogs; 
private List<Log> logsSmall;
public void handleFileUpload(FileUploadEvent event) {....}

// other private functions
//public getters and setters
}

Also, if you are working with java 7, maybe you want to look at the new file I/O .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM