View Javadoc
1   package org.apache.maven.model.transform.pull;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.List;
25  import java.util.Objects;
26  
27  import org.codehaus.plexus.util.xml.pull.XmlPullParser;
28  import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
29  
30  /**
31   * Buffer events while parsing a given element to allow some post-processing.
32   *
33   * @author Guillaume Nodet
34   * @since 4.0.0
35   */
36  public abstract class NodeBufferingParser extends BufferingParser
37  {
38  
39      private final List<Event> buffer = new ArrayList<>();
40  
41      private final String nodeName;
42  
43      private boolean buffering;
44  
45      public NodeBufferingParser( XmlPullParser xmlPullParser, String nodeName )
46      {
47          super( xmlPullParser );
48          this.nodeName = Objects.requireNonNull( nodeName );
49      }
50  
51      @Override
52      protected boolean accept() throws XmlPullParserException, IOException
53      {
54          if ( nodeName.equals( xmlPullParser.getName() ) )
55          {
56              if ( xmlPullParser.getEventType() == START_TAG && !buffering )
57              {
58                  buffer.add( bufferEvent() );
59                  buffering = true;
60                  return false;
61              }
62              if ( xmlPullParser.getEventType() == END_TAG && buffering )
63              {
64                  buffer.add( bufferEvent() );
65                  process( buffer );
66                  buffering = false;
67                  buffer.clear();
68                  return false;
69              }
70          }
71          else if ( buffering )
72          {
73              buffer.add( bufferEvent() );
74              return false;
75          }
76          return true;
77      }
78  
79      protected abstract void process( List<Event> buffer );
80  
81  }