001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2008-2011 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * Sonar is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * Sonar is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public
017     * License along with Sonar; if not, write to the Free Software
018     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019     */
020    package org.sonar.plugins.cobertura.api;
021    
022    import com.google.common.collect.Maps;
023    import org.apache.commons.io.FilenameUtils;
024    import org.apache.commons.lang.StringUtils;
025    import org.codehaus.staxmate.in.SMHierarchicCursor;
026    import org.codehaus.staxmate.in.SMInputCursor;
027    import org.sonar.api.batch.SensorContext;
028    import org.sonar.api.measures.CoverageMeasuresBuilder;
029    import org.sonar.api.measures.Measure;
030    import org.sonar.api.resources.Resource;
031    import org.sonar.api.utils.StaxParser;
032    import org.sonar.api.utils.XmlParserException;
033    
034    import javax.xml.stream.XMLStreamException;
035    import java.io.File;
036    import java.text.ParseException;
037    import java.util.Map;
038    
039    import static java.util.Locale.ENGLISH;
040    import static org.sonar.api.utils.ParsingUtils.parseNumber;
041    
042    /**
043     * @since 2.4
044     */
045    public abstract class AbstractCoberturaParser {
046    
047      public void parseReport(File xmlFile, final SensorContext context) {
048        try {
049          StaxParser parser = new StaxParser(new StaxParser.XmlStreamHandler() {
050    
051            public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException {
052              try {
053                rootCursor.advance();
054                collectPackageMeasures(rootCursor.descendantElementCursor("package"), context);
055              } catch (ParseException e) {
056                throw new XMLStreamException(e);
057              }
058            }
059          });
060          parser.parse(xmlFile);
061        } catch (XMLStreamException e) {
062          throw new XmlParserException(e);
063        }
064      }
065    
066      private void collectPackageMeasures(SMInputCursor pack, SensorContext context) throws ParseException, XMLStreamException {
067        while (pack.getNext() != null) {
068          Map<String, CoverageMeasuresBuilder> builderByFilename = Maps.newHashMap();
069          collectFileMeasures(pack.descendantElementCursor("class"), builderByFilename);
070          for (Map.Entry<String, CoverageMeasuresBuilder> entry : builderByFilename.entrySet()) {
071            String filename = sanitizeFilename(entry.getKey());
072            Resource file = getResource(filename);
073            if (fileExists(context, file)) {
074              for (Measure measure : entry.getValue().createMeasures()) {
075                context.saveMeasure(file, measure);
076              }
077            }
078          }
079        }
080      }
081    
082      private boolean fileExists(SensorContext context, Resource file) {
083        return context.getResource(file) != null;
084      }
085    
086      private void collectFileMeasures(SMInputCursor clazz, Map<String, CoverageMeasuresBuilder> builderByFilename) throws ParseException, XMLStreamException {
087        while (clazz.getNext() != null) {
088          String fileName = clazz.getAttrValue("filename");
089          CoverageMeasuresBuilder builder = builderByFilename.get(fileName);
090          if (builder==null) {
091            builder = CoverageMeasuresBuilder.create();
092            builderByFilename.put(fileName, builder);
093          }
094          collectFileData(clazz, builder);
095        }
096      }
097    
098      private void collectFileData(SMInputCursor clazz, CoverageMeasuresBuilder builder) throws ParseException, XMLStreamException {
099        SMInputCursor line = clazz.childElementCursor("lines").advance().childElementCursor("line");
100        while (line.getNext() != null) {
101          int lineId = Integer.parseInt(line.getAttrValue("number"));
102          builder.setHits(lineId, (int) parseNumber(line.getAttrValue("hits"), ENGLISH));
103    
104          String isBranch = line.getAttrValue("branch");
105          String text = line.getAttrValue("condition-coverage");
106          if (StringUtils.equals(isBranch, "true") && StringUtils.isNotBlank(text)) {
107            String[] conditions = StringUtils.split(StringUtils.substringBetween(text, "(", ")"), "/");
108            builder.setConditions(lineId, Integer.parseInt(conditions[1]), Integer.parseInt(conditions[0]));
109          }
110        }
111      }
112    
113      private String sanitizeFilename(String s) {
114        String fileName = FilenameUtils.removeExtension(s);
115        fileName = fileName.replace('/', '.').replace('\\', '.');
116        return fileName;
117      }
118    
119      protected abstract Resource getResource(String fileName);
120    }