summaryrefslogtreecommitdiff
path: root/src/plugins/preflighting/src/com/motorolamobility/preflighting/internal/commandoutput/XmlOutputter.java
blob: 6b717a40d9cd5689701cc9fba5df63f171c07a0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.motorolamobility.preflighting.internal.commandoutput;

import java.io.File;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.xerces.jaxp.DocumentBuilderFactoryImpl;
import org.eclipse.core.runtime.IStatus;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.motorolamobility.preflighting.core.exception.PreflightingToolException;
import com.motorolamobility.preflighting.core.logging.PreflightingLogger;
import com.motorolamobility.preflighting.core.utils.XmlUtils;
import com.motorolamobility.preflighting.core.validation.ApplicationValidationResult;
import com.motorolamobility.preflighting.core.validation.Parameter;
import com.motorolamobility.preflighting.core.validation.ValidationManagerConfiguration;
import com.motorolamobility.preflighting.core.validation.ValidationResult;
import com.motorolamobility.preflighting.core.validation.ValidationResultData;
import com.motorolamobility.preflighting.core.validation.ValidationResultData.SEVERITY;
import com.motorolamobility.preflighting.core.verbose.WarningLevelFilter;
import com.motorolamobility.preflighting.i18n.PreflightingNLS;
import com.motorolamobility.preflighting.internal.PreflightingPlugin;
import com.motorolamobility.preflighting.output.AbstractOutputter;

public class XmlOutputter extends AbstractOutputter
{

    protected Document document = null;

    private static final String XML_TAG_APP_VALIDATOR = "AppValidator";

    private static final String XML_TAG_APPLICATION = "Application";

    private static final String XML_TAG_ERROR = "Error";

    private static final String XML_TAG_FATAL_ERROR = "FatalError";

    private static final String XML_TAG_WARNING = "Warning";

    private static final String XML_TAG_RESOURCE = "Resource";

    private static final String XML_TAG_LINE = "Line";

    private static final String XML_TAG_SUGGESTION = "Suggestion";

    private static final String XML_ATTRIBUTE_CHECKER_ID = "checker_id";

    private static final String XML_ATTRIBUTE_CONDITION_ID = "condition_id";

    private static final String XML_ATTRIBUTE_INFO_URL = "info_url";

    private static final String XML_ATTRIBUTE_PATH = "path";

    private static final String XML_ATTRIBUTE_APP_NAME = "app_name";

    private static final String XML_TAG_DESCRIPTION = "Description";

    private static final String XML_TAG_PREVIEW = "Preview";

    private static final String XML_ATTRIBUTE_APPVALIDATOR_VERSION = "version";

    private static final String XML_ATTRIBUTE_APPLICATION_VERSION = "app_version";

    private static final String XML_ATTRIBUTE_MOTODEV_LINK = "description_url";

    private static final String XML_CHECKER_STATUS_VALUE_FAIL = "Failed";

    private static final String XML_CHECKER_STATUS_VALUE_DISABLED = "Disabled";

    private static final String XML_CHECKER_STATUS_VALUE_OK = "Executed";

    private static final String XML_ATTRIBUTE_MESSAGE = "message";

    private static final String XML_ATTRIBUTE_STATUS = "status";

    private static final String XML_TAG_CHECKER_STATUS = "CheckerStatus";

    private static final String XML_TAG_EXECUTION_REPORT = "ExecutionReport";

    //TODO change tag name
    private static final String XML_TAG_APP_VALIDATOR_EXECUTION_REPORT = "ExecutionReport";

    private static final String XML_TAG_MESSAGES = "Messages";

    /**
     * Writes to file xml or text in the following format: <br>
     * &lt;type (Error/Warning/Info)&gt; &lt;number files involved (Java, XML)&gt; &lt;filePath1 (without OS specific characters)&gt;:&lt;linePath1&gt; ... &lt;filePathN&gt;:&lt;linePathN&gt;  &lt;description&gt;
     * @throws PreflightingToolException 
     */
    @Override
    public void print(ApplicationValidationResult result, OutputStream stream,
            List<Parameter> parameters) throws PreflightingToolException
    {
        initializeParams(parameters);

        try
        {
            Element appValElem = createRootNode();

            Element applicationElem = document.createElement(XML_TAG_APPLICATION);
            applicationElem.setAttribute(XML_ATTRIBUTE_APP_NAME, getApplicationFile().getName());
            applicationElem.setAttribute(XML_ATTRIBUTE_APPLICATION_VERSION,
                    String.valueOf(result.getVersion()));

            generateCustomApplicationNodes(applicationElem, result, parameters);
            appValElem.appendChild(applicationElem);

            Element messagesElement = document.createElement(XML_TAG_MESSAGES);
            applicationElem.appendChild(messagesElement);

            //create result nodes and append them to document
            generateResultNodes(messagesElement, result.getResults());

            generateExecutionReport(applicationElem, result.getExecutionStatus());

            //create XML output
            XmlUtils.printXMLFormat(document);
        }
        catch (Exception e)
        {
            PreflightingLogger.error(getClass(), PreflightingNLS.TextOutputter_IOExceptionMessage
                    + e.getMessage());
            throw new PreflightingToolException(
                    PreflightingNLS.XMLOutputter_PrintResultsErrorMessage, e);
        }
    }

    /*
     * Generates the nodes for the result list
     */
    private void generateResultNodes(Element rootElement, List<ValidationResult> result)
    {
        for (ValidationResult checker : result)
        {
            for (ValidationResultData data : checker.getValidationResult())
            {
                if (SEVERITY.OK.compareTo(data.getSeverity()) != 0)
                {
                    Element issueElement = createIssueNode(data.getSeverity());
                    issueElement.setAttribute(XML_ATTRIBUTE_CHECKER_ID, checker.getCheckerId());
                    issueElement.setAttribute(XML_ATTRIBUTE_CONDITION_ID, data.getConditionID());
                    if (data.getInfoURL() != null)
                    {
                        issueElement.setAttribute(XML_ATTRIBUTE_INFO_URL, data.getInfoURL());
                    }
                    Element descriptionElement = createDescriptionNode(data.getIssueDescription());
                    issueElement.appendChild(descriptionElement);

                    for (File currentFile : data.getFileToIssueLines().keySet())
                    {
                        Element resourceElement =
                                createResourceNode(currentFile,
                                        data.getFileToIssueLines().get(currentFile));
                        issueElement.appendChild(resourceElement);
                    }

                    if (WarningLevelFilter.printQuickFixSuggestions())
                    {
                        Element suggestionElement =
                                createSuggestionNode(data.getQuickFixSuggestion());
                        issueElement.appendChild(suggestionElement);
                    }

                    if (data.getPreview() != null)
                    {
                        Element previewElement = createPreviewNode(data.getPreview());
                        issueElement.appendChild(previewElement);
                    }

                    rootElement.appendChild(issueElement);
                }
            }
        }
    }

    /*
     * Generate the execution report node based on contents from executionStatus map
     */
    private void generateExecutionReport(Element appValElem, Map<String, IStatus> executionStatus)
    {
        Element executionReportElement = document.createElement(XML_TAG_EXECUTION_REPORT);

        for (String checkerId : executionStatus.keySet())
        {
            IStatus checkerStatus = executionStatus.get(checkerId);
            Element checkerStatusElement = document.createElement(XML_TAG_CHECKER_STATUS);

            checkerStatusElement.setAttribute(XML_ATTRIBUTE_CHECKER_ID, checkerId);

            //checker status equal INFO will be displayed as not executed
            String status;
            switch (checkerStatus.getSeverity())
            {
                case IStatus.OK:
                    status = XML_CHECKER_STATUS_VALUE_OK;
                    break;
                case IStatus.INFO:
                    status = XML_CHECKER_STATUS_VALUE_DISABLED;
                    break;
                default: //failed
                    status = XML_CHECKER_STATUS_VALUE_FAIL;
                    break;
            }

            checkerStatusElement.setAttribute(XML_ATTRIBUTE_STATUS, status);
            checkerStatusElement.setAttribute(XML_ATTRIBUTE_MESSAGE, checkerStatus.getMessage());

            executionReportElement.appendChild(checkerStatusElement);
        }

        appValElem.appendChild(executionReportElement);
    }

    /*
     * ERROR, FATAL_ERROR or WARNING nodes
     */
    private Element createIssueNode(SEVERITY severity)
    {
        Element element = null;

        if (SEVERITY.ERROR.compareTo(severity) == 0)
        {
            element = document.createElement(XML_TAG_ERROR);
        }
        else if (SEVERITY.WARNING.compareTo(severity) == 0)
        {
            element = document.createElement(XML_TAG_WARNING);
        }
        else if (SEVERITY.FATAL.compareTo(severity) == 0)
        {
            element = document.createElement(XML_TAG_FATAL_ERROR);
        }

        return element;
    }

    /*
     * Issue description node
     */
    private Element createDescriptionNode(String description)
    {
        Element element = document.createElement(XML_TAG_DESCRIPTION);

        if (description != null)
        {
            element.setTextContent(description);
        }

        return element;
    }

    /**
     * Create resource node
     * @param currentFile (resource)
     * @param lines with errors in this resource
     * @return the resource node
     */
    private Element createResourceNode(File currentFile, List<Integer> lines)
    {
        Element resElement = document.createElement(XML_TAG_RESOURCE);
        resElement.setAttribute(XML_ATTRIBUTE_PATH, computeResourcePath(currentFile));

        for (Integer currentLine : lines)
        {
            Element lineElement = document.createElement(XML_TAG_LINE);
            lineElement.setTextContent(currentLine.toString());
            resElement.appendChild(lineElement);
        }

        return resElement;
    }

    /**
     * Create fix sugestion node
     * @param suggestion text
     * @return the sugestion node
     */
    private Element createSuggestionNode(String suggestion)
    {
        Element sugElement = document.createElement(XML_TAG_SUGGESTION);
        sugElement.setTextContent(suggestion);

        return sugElement;
    }

    /**
     * Create a Preview node with Validation preview
     * @param preview text
     * @return preview node
     */
    private Element createPreviewNode(String preview)
    {
        Element previewElement = document.createElement(XML_TAG_PREVIEW);
        previewElement.setTextContent(preview);

        return previewElement;
    }

    @Override
    public void printError(Exception exceptionThrown, PrintStream out)
    {
        try
        {
            Element appValElem = createRootNode();
            Element executionReportElement =
                    document.createElement(XML_TAG_APP_VALIDATOR_EXECUTION_REPORT);
            executionReportElement
                    .setAttribute(XML_ATTRIBUTE_STATUS, XML_CHECKER_STATUS_VALUE_FAIL);
            executionReportElement
                    .setAttribute(XML_ATTRIBUTE_MESSAGE, exceptionThrown.getMessage());
            appValElem.appendChild(executionReportElement);

            XmlUtils.printXMLFormat(document);
        }
        catch (Exception e)
        {
            PreflightingLogger.error(getClass(),
                    PreflightingNLS.XMLOutputter_PrintResultsErrorMessage + e.getMessage());
        }
    }

    //creates the document and its root node
    private Element createRootNode() throws ParserConfigurationException
    {
        document = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder().newDocument();

        Element appValElem = document.createElement(XML_TAG_APP_VALIDATOR);
        document.appendChild(appValElem);
        String appValidatorVersion = PreflightingPlugin.getInstance().getAppValidatorVersion();
        ValidationManagerConfiguration valManagerConfiguration =
                ValidationManagerConfiguration.getInstance();
        String motodevLink =
                valManagerConfiguration
                        .getProperty(ValidationManagerConfiguration.ConfigProperties.BASE_URL_PROPERTY
                                .getName());
        appValElem.setAttribute(XML_ATTRIBUTE_APPVALIDATOR_VERSION, appValidatorVersion);
        appValElem.setAttribute(XML_ATTRIBUTE_MOTODEV_LINK, motodevLink);

        return appValElem;
    }

    protected void generateCustomApplicationNodes(Element applicationElem,
            ApplicationValidationResult result, List<Parameter> params)
    {
        //Do nothing.
    }
}