Content control - Java Sax

Asked

Viewed 69 times

1

[Java - Sax Parser] Good afternoon. If anyone can help me I’d be grateful.

I need to build an application that works as follows: In case he finds the tag "classname", and this has an attribute "type" with the value "M" or "V", then arrow the tag name classname.

Tag classname, he checks your daughter tags, and if you have the daughter tag "parameter" and this has the attribute name, then arrow this attribute of parameter. There is yet another situation, where in case it contains a daughter tag called "mapping" then don’t arrow any value. This part is correct and working.

However I now need to do a content control, IE, before setting the value of classname it should check whether this value already exists, if it does not exist, arrow normally as above, if any, then check the values of parameter, and if these values also exist, there is no arrow, but if you have any parameter different, there just this arrow parameter different in the classname existing.

Example XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<prozessdef>
    <beschreibung></beschreibung>
    <kunde></kunde>
    <aktion>
        <parameter name="pPROZESS_ID"/>
        <classname type="M">common.Filecache/AAA</classname>
    </aktion>
    <aktion>
        <parameter name="pPROZESS_ID"/>
        <classname type="M">common.Filecache/BBB</classname>
    </aktion>
    <aktion>
        <parameter name="pPROZESS_ID"/>
        <classname type="V">common.Filecache/AAA</classname>
    </aktion>
</prozessdef>

Class SaxWFReader:

public class SaxWFReader extends DefaultHandler{

    /** Buffer que guarda as informações quando um texto é encontrado */
    private StringBuffer tempValue = new StringBuffer(50); 

    /** Lista que possui as tags do arquivo XML */
    private ArrayList<Aktion> aktion = new ArrayList<Aktion>();

    public ArrayList<Aktion> getAktion() {
        return aktion;
    }

    /** variáveis temporárias, apenas para coletar as informações do XML */
    private Parameter parameterTemp;
    private Classname classTemp;
    private Aktion    aktionTemp;

    //contantes que representam as tags do arquivo XML
    private final String NO_AKTION          = "aktion";
    private final String NO_CLASSNAME       = "classname";
    private final String ATT_CLASSNAME_TYPE = "type";
    private final String NO_PARAMETER       = "parameter";
    private final String NO_MAPPING         = "mapping";

    //variáveis para controle de conteúdo
    boolean mappingOpen   = false;
    boolean mappingExist  = false;
    boolean typeClassName = false;
    boolean parameterOpen = false;
    boolean aktionOpen    = false;

    /**
     * Construtor que irá varrer uma pasta, lendo todos os aquivos terminandos
     * com .xml. Cada vez que encontrar um arquivo, irá fazer o parse do arquivo.
     *  
     * Constutor que inicializa os objetos necessários para fazer o parse
     * do arquivo xml
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public void parse() throws ParserConfigurationException, SAXException, IOException {

        File dir = new File("/home/pal/Área de Trabalho/teste");
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser = spf.newSAXParser();
        if (dir.isDirectory()){
            String[] files = dir.list();
            for (int i = 0; i < files.length; i++) {
                if(files[i].endsWith(".xml")){
                    parser.parse(files[i], this);
                }
            }
        }
    }


    /**
     * Verifica se achou a tag aktion, caso sim, cria um novo objeto aktion.
     * Verifica se encontrou a tag classname e seus atributos e seta os valores conforme a necessidade.
     * Verifica se encontrou a tag parameter e seus atributos e seta os valores conforme a necessidade.
     * Verifica se encontrou a tag mapping e faz o controle de conteúdo. 
     */
    public void startElement(String uri, String localName, String tag, Attributes atts){

        if (tag.equals(NO_AKTION)){
            aktionTemp = new Aktion();
        }   

        if (tag.equals(NO_CLASSNAME)){
            for (int i = 0; i < atts.getLength(); i++) {
                if (atts.getQName(i).equals(ATT_CLASSNAME_TYPE) && (atts.getValue(i).equals("M") || atts.getValue(i).equals("V"))){
                    classTemp = new Classname();
                    typeClassName = true;
                }
            }
        }

        if (tag.equals(NO_MAPPING)){
            mappingOpen  = true;
            mappingExist = true;
        }

        if (tag.equals(NO_PARAMETER)){
            parameterTemp = new Parameter();
            parameterOpen = true;
            for (int j = 0; j < atts.getLength(); j++) {
                if (atts.getQName(j).equalsIgnoreCase("name")){
                    parameterTemp.addListAtts(atts.getValue(j));
                }
            }
        }
    }


    /** 
     * Indica que o parser achou o fim de uma tag/elemento.
     * Este evento fornece o nome do elemento, e também pode
     * fornecer as informações sobre o namespace.
     */
    public void endElement(String uri, String localName, String tag){

        //Se encontrou o final da tag aktion, adiciona o conteúdo da aktionTemp
        if (tag.equals(NO_AKTION)){
            if (typeClassName){
                aktion.add(aktionTemp);
                typeClassName = false;
                aktionOpen    = false;
            }
        }

        //senão, seta os valores conforme a necessidade
        else if (tag.equals(NO_CLASSNAME) && (!aktionOpen)){
            if (typeClassName){
                for (int i = 0; i < classTemp.listTag.size(); i++) {
                    if(!classTemp.getListTag(i).equals(tempValue)){
                        aktionTemp.addClassname(classTemp);
                        classTemp.addListTag(tempValue.toString().trim());
                        aktionOpen = true;
                    }
                }
            }


        } else if (tag.equals(NO_PARAMETER)){
            if (parameterOpen && !mappingExist){
                aktionTemp.addParameter(parameterTemp);
            }
            parameterOpen = false;
            mappingExist  = false;

        } else if (tag.equals(NO_MAPPING)){
            mappingOpen = false;
        }

        //Limpa o conteúdo da tempValue
        tempValue.delete(0, tempValue.length());
    }

    /**
     * Indica que o parser achou algum texto.
     */
    public void characters(char[] ch, int start, int length) {
        tempValue.append(ch, start, length);
    }

    /**
     * Imprime os valores obetidos
     */
    public void imprimeAktion(){
        for (int i=0; i<aktion.size(); i++){
            System.out.println(aktion.get(i));
        }
    }

    public static void main(String[] args){
        try {
            SaxWFReader reader = new SaxWFReader();
            reader.parse();

            System.out.println("VALORES OBTIDOS");
            reader.imprimeAktion();

        } catch (ParserConfigurationException e) {
            System.out.println("Parser não configurado adequadamete: ERRO: " + e);
            e.printStackTrace();
        } catch (SAXException e) {
            System.out.println("Erro ao efetuar o parse do arquivo selecionado: ERRO: " + e);
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Probelmas de Leitura do arquivo: ERRO: " + e);
            e.printStackTrace();
        }
    }
}

Class Classname:

public class Classname {

    List<String> listTag  = new ArrayList<String>();


    public String getListTag(int i) {
        return listTag.get(i);
    }
    public void addListTag(String tag) {
        this.listTag.add(tag);
    }

    public String toString(){
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < listTag.size(); i++) {
            sb.append("classname " + getListTag(i));
        }
        return sb.toString();
    }
}

Class Parameter:

public class Parameter {

    List<String> listAtts = new ArrayList<String>();

    public String getListAtts(int i) {
        return listAtts.get(i);
    }
    public void addListAtts(String tag) {
        this.listAtts.add(tag);
    }

    public String toString(){
        StringBuffer sb = new StringBuffer();
        for (int j = 0; j < listAtts.size(); j++) {
            sb.append("parameter name=" + getListAtts(j));
        }
        return sb.toString();
    }
}

Class Aktion:

public class Aktion {

    private ArrayList<Parameter> parameter = new ArrayList<Parameter>();
    private ArrayList<Classname> classname = new ArrayList<Classname>();

    public Parameter getParameter(int i) {
        return parameter.get(i);
    }
    public void addParameter(Parameter parameter) {
        this.parameter.add(parameter);
    }

    public Classname getClassname(int i) {
        return classname.get(i);
    }
    public void addClassname(Classname classname) {
        this.classname.add(classname);
    }

    public String toString(){
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < classname.size(); i++) {
            if (getClassname(i) != null){
                sb.append(classname.get(i));
            }
        }
        for (int i = 0; i < parameter.size(); i++) {
            if (getClassname(i) != null && getParameter(i) != null){
                sb.append("\n" + parameter.get(i));
            }else
                sb.append(parameter.get(i));
        }
        return sb.toString();
    }
}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.