Example usage for org.w3c.dom Element hasAttribute

List of usage examples for org.w3c.dom Element hasAttribute

Introduction

In this page you can find the example usage for org.w3c.dom Element hasAttribute.

Prototype

public boolean hasAttribute(String name);

Source Link

Document

Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.

Usage

From source file:com.mdt.rtm.data.RtmTask.java

public RtmTask(Element elt) {
    id = elt.getAttribute("id");
    String dueStr = elt.getAttribute("due");
    due = (dueStr == null || dueStr.length() == 0) ? null : parseDate(dueStr);
    hasDueTime = Integer.parseInt(elt.getAttribute("has_due_time"));
    String addedStr = elt.getAttribute("added");
    added = (addedStr == null || addedStr.length() == 0) ? null : parseDate(addedStr);
    String completedStr = elt.getAttribute("completed");
    completed = (completedStr == null || completedStr.length() == 0) ? null : parseDate(completedStr);
    String deletedStr = elt.getAttribute("deleted");
    deleted = (deletedStr == null || deletedStr.length() == 0) ? null : parseDate(deletedStr);
    String priorityStr = elt.getAttribute("priority");
    if (priorityStr.length() > 0) {
        switch (priorityStr.charAt(0)) {
        case 'N':
        case 'n':
            priority = Priority.None;/* w  w w . ja  v  a  2  s.  co m*/
            break;
        case '3':
            priority = Priority.Low;
            break;
        case '2':
            priority = Priority.Medium;
            break;
        case '1':
            priority = Priority.High;
            break;
        default:
            System.err.println("Unrecognized RTM task priority: '" + priorityStr + "'");
            priority = Priority.Medium;
        }
    } else {
        priority = Priority.None;
    }
    if (elt.hasAttribute("postponed") == true && elt.getAttribute("postponed").length() > 0) {
        postponed = Integer.parseInt(elt.getAttribute("postponed"));
    } else {
        postponed = 0;
    }
    estimate = elt.getAttribute("estimate");
}

From source file:autohit.creator.compiler.SimCompiler.java

/**
 *  handle a ASSERT/*  w  w  w.j  a va 2s.  c  o m*/
 * <code>MICROCODE
 * 
 * 1-    if (oper NOT exists)   OP = NOT
  * 2-    else                 OP = EQ
  * 3-    i.fetch(item)
 * 4-    i.assert(OUTER,OP)
 * 5- INNER:  i.scope
 * 6-    (ANY)*
 * 7-    i.rscope
 * 8- OUTER:   i.nop
 * </code>
 */
private void handleAssert(Element en) {

    VMIAssert myassert;
    int opthang = EQ; // default is =

    //runtimeDebug("handleAssert");

    // 1- if (oper exists)   OP = oper
    if (en.hasAttribute(ATTR_OPERATOR)) {
        String ops = en.getAttribute(ATTR_OPERATOR);
        if (ops.equals(EQ_STRING)) {
            opthang = EQ;
        } else if (ops.equals(NOT_STRING)) {
            opthang = NOT;
        } else {
            runtimeWarning("WARNING If has unrecognized operation.  Using default \"eq\"");
            opthang = EQ;
        }
    }
    //   2-   else         OP = '=' (default)
    // Implied since it is the default.

    //  3-   i.fetch(item)
    this.emitFetch(en.getAttribute(ATTR_ITEM));

    //  4-    i.assert(OUTER,OP)
    myassert = new VMIAssert();
    myassert.operFlag = opthang;
    ob.emit(myassert);
    //runtimeDebug(
    //   "EMIT(" + (ob.nextIP() - 1) + ") i.assert target= FIXUP LATER");

    // 5- INNER:  i.scope
    this.emitScope();

    // 6- (ANY)*
    try {
        processCode(en);
    } catch (Exception e) {
        //   Stop an error unravelling here.  Close the scope and move on
        runtimeError("ERROR Broken ASSERT inner.");
        runtimeError(e.toString());
    }

    // 7- i.rscope
    this.emitRScope();

    // 8- OUTER:   i.nop
    // First fixup the assert.  Put a NOP for safety, so there will always be a target
    myassert.t = ob.nextIP();
    runtimeDebug("FIXUP assert target=" + myassert.t);
    this.emitNOP();
}

From source file:autohit.creator.compiler.SimCompiler.java

/**
 *  handle a IF//from   w  w  w . j  av a 2 s.  co m
 * <code>MICROCODE
 * 1-     if (oper exists)   OP = oper
 * 2-        else         OP = '=' (default)
 * 3-       if (eval exists)         i.eval(eval)
 * 4-          else if (value exists) i.load(value)
 * 5-        else                !!ERROR   
 * 6-       i.right
 * 7-       i.fetch(item)
 * 8-       i.math(operation)
 * 9-      i.if(OUTER,OP)
 * 10- INNER:   i.scope
 * 11-     (ANY)*
 * 12-    i.rscope
 * 13- OUTER:   i.nop </code>
 */
private void handleIf(Element en) {

    VMIIf myif;
    int opthang = EQ; // default is =

    //runtimeDebug("handleIf");

    // 1- if (oper exists)   OP = oper
    if (en.hasAttribute(ATTR_OPERATOR)) {
        String ops = en.getAttribute(ATTR_OPERATOR);
        if (ops.equals(EQ_STRING)) {
            opthang = EQ;
        } else if (ops.equals(LT_STRING)) {
            opthang = LT;
        } else if (ops.equals(GT_STRING)) {
            opthang = GT;
        } else if (ops.equals(NOT_STRING)) {
            opthang = NOT;
        } else {
            runtimeWarning("WARNING If has unrecognized operation.  Using default \"eq\"");
            opthang = EQ;
        }
    }
    //   2-   else         OP = '=' (default)
    // Implied since it is the default.

    // 3- if (eval exists)          i.eval(eval)
    if (en.hasAttribute(ATTR_EVALUATOR)) {
        this.emitEval(en.getAttribute(ATTR_EVALUATOR));

        // 4- else if (value exists) i.load(value)    
    } else if (en.hasAttribute(ATTR_VALUE)) {
        this.emitLoad(en.getAttribute(ATTR_VALUE));

        // 5- else !!ERROR   
    } else {
        runtimeError("ERROR Broken IF.  No right value defined defined.");
        this.emitLoad(en.getAttribute(LITERAL_ZERO));
        // use 0 so we can finish compile
    }

    // 6- i.right
    this.emitRight();

    // 7- i.fetch(item)
    this.emitFetch(en.getAttribute(ATTR_ITEM));

    // 8- i.math(operation)
    this.emitMath(IF_OPERATION);

    // 9- i.if(OUTER, OP)
    myif = new VMIIf();
    myif.operFlag = opthang;
    ob.emit(myif);
    //runtimeDebug(
    //   "EMIT(" + (ob.nextIP() - 1) + ") i.if target= FIXUP LATER");

    // 10- INNER:   i.scope
    this.emitScope();

    // 11- (ANY)*
    try {
        processCode(en);
    } catch (Exception e) {
        //   Stop an error unravelling here.  Close the scope and move on
        runtimeError("ERROR Broken IF inner.");
        runtimeError(e.toString());
    }

    // 12- i.rscope
    this.emitRScope();

    // 13- OUTER:   i.nop
    // First fixup the if.  Put a NOP for safety, so there will always be a target
    myif.t = ob.nextIP();
    runtimeDebug("FIXUP if target=" + myif.t);
    this.emitNOP();
}

From source file:autohit.creator.compiler.SimCompiler.java

/**
 *  handle a FOR/*  www . ja  v  a 2  s  . c om*/
 *  MICROCODE
 * 1-  TOP:   i.scope
 * 2-       if (eval exists)   i.eval(eval)
 * 3-          else if (value exists) i.load(value)
 * 4-         else          !!ERROR   
 * 5-       i.new(count)
 * 6-  LOOP:   i.if(DONE)
 * 7-  DO:   (ANY)*
 * 8-       i.load("1")
 * 9-       i.right   
 * 10-       i.fetch(count)
 * 11-      i.math("-")      // LEFT RESULT will stay in LEFT
 * 12-      i.store(count)      
 * 13-      i.jump(LOOP)      
 * 14- DONE:   i.rscope
 */
private void handleFor(Element en) {

    int loopstop;

    VMIIf myif;
    VMIJump myjump;

    //runtimeDebug("handleFor");

    // 1- i.scope
    this.emitScope();

    // 2- if (eval exists)   i.eval(eval)
    if (en.hasAttribute(ATTR_EVALUATOR)) {
        this.emitEval(en.getAttribute(ATTR_EVALUATOR));

        // 3-   else if (value exists) i.load(value)    
    } else if (en.hasAttribute(ATTR_VALUE)) {
        this.emitLoad(en.getAttribute(ATTR_VALUE));

        // 4-   else          !!ERROR   
    } else {
        runtimeError("ERROR Broken for.  No count value defined.");
        this.emitLoad(en.getAttribute(LITERAL_ZERO));
        // use 0 so we can finish compile
    }

    // 5-    i.new(count)
    this.emitNew(en.getAttribute("count"));

    // 6-  LOOP:   i.if(DONE)
    loopstop = ob.nextIP(); // loop stop points to #6
    myif = new VMIIf();
    // FIXUP the IF later
    ob.emit(myif);
    runtimeDebug("EMIT(" + loopstop + ") i.if target= FIXUP LATER");

    // 7-  DO:   (ANY)*
    try {
        processCode(en);
    } catch (Exception e) {
        //   Stop an error unravelling here.  Close the scope and move on
        runtimeError("ERROR Broken FOR inner.");
        runtimeError(e.toString());
    }

    // 8-  i.load(LITERAL_ONE)
    this.emitLoad(LITERAL_ONE);

    // 9-  i.right
    this.emitRight();

    // 10-  i.fetch(count)
    this.emitFetch(en.getAttribute(ATTR_COUNT));

    // 11-   i.math("-")
    this.emitMath(MINUS_OPERATION);

    // 12-  i.store(count)
    this.emitStore(en.getAttribute(ATTR_COUNT));

    // 13-   i.jump(LOOP)
    this.emitJump(loopstop);

    // 14- DONE:   i.rscope
    // First fixup the jump
    myif.t = ob.nextIP();
    runtimeDebug("FIXUP IF=" + myif.t);
    this.emitRScope();
}

From source file:fr.aliasource.webmail.server.proxy.client.http.AbstractConversationMethod.java

protected ConversationReference parseConversation(Calendar cal, Element cr) {
    String title = DOMUtils.getElementText(cr, "title");

    Element ps = DOMUtils.getUniqueElement(cr, "participants");
    Set<EmailAddress> participants = new HashSet<EmailAddress>();
    String[][] psArray = DOMUtils.getAttributes(ps, "p", new String[] { "addr", "displayName" });
    for (int j = 0; j < psArray.length; j++) {
        participants.add(new EmailAddress(psArray[j][1], psArray[j][0]));
    }/*from   www . j  ava2 s.c om*/

    Element mids = DOMUtils.getUniqueElement(cr, "mids");
    String[][] mArray = DOMUtils.getAttributes(mids, "m", new String[] { "id" });
    List<MessageId> messageIds = new ArrayList<MessageId>(mArray.length);
    for (int j = 0; j < mArray.length; j++) {
        messageIds.add(new MessageId(Long.valueOf(mArray[j][0])));
    }

    ConversationReference c = new ConversationReference();
    c.setParticipants(participants);
    c.setMessageIds(messageIds);
    c.setTitle(title);
    c.setRead("true".equals(cr.getAttribute("read")));
    c.setHasAttachements("true".equals(cr.getAttribute("attach")));
    c.setHasInvitation("true".equals(cr.getAttribute("invitation")));
    c.setStarred("true".equals(cr.getAttribute("star")));
    c.setAnswered("true".equals(cr.getAttribute("answer")));
    c.setHighPriority("true".equals(cr.getAttribute("hp")));
    cal.setTimeInMillis(Long.parseLong(cr.getAttribute("lastMessageDate")));
    c.setLastMessageDate(cal.getTime());
    c.setSourceFolderName(cr.getAttribute("folder"));
    c.setId(new ConversationId(cr.getAttribute("id")));

    if (cr.hasAttribute("prev")) {
        c.setPrev(new ConversationId(cr.getAttribute("prev")));
    }
    if (cr.hasAttribute("next")) {
        c.setNext(new ConversationId(cr.getAttribute("next")));
    }

    parseMetadata(c, cr);
    return c;
}

From source file:autohit.creator.compiler.SimCompiler.java

/**
 *  handle a Buffer./*  w  ww .jav  a2s.  c  om*/
 *  MICROCODE
 *  1- if (clear exists)   i.clear(name), ALREADY = true
 *   2- if (eval exists)   i.eval(eval), i.merge(name) 
 *  3-    else if (value exists) i.left(value), i.merge(name)
 *  4-    else if (buffer exists)i.reduce(buffer), i.merge(name)
 *  5-    else CLEAR = true         
 *  6- if (cdata exists)           i.load(cdata), i.merge(name)
 *  7-      else if (CLEAR true, ALREADY false)      i.clear(name)
 */
private void handleBuffer(Element en) {

    String name = en.getAttribute(ATTR_NAME);
    String cdata;
    boolean clearFlag = false;
    boolean clearAlready = false;

    //runtimeDebug("handleBuffer.  name=" + name);

    // 1- if (clear exists)   i.clear(name)
    if (en.hasAttribute(ATTR_CLEAR)) {
        this.emitClear(name);
        clearAlready = true;
    }

    // 2- if (eval exists)   i.eval(eval), i.merge(name) 
    if (en.hasAttribute(ATTR_EVALUATOR)) {
        this.emitEval(en.getAttribute(ATTR_EVALUATOR));
        this.emitMerge(en.getAttribute(ATTR_NAME));

        // 3-    else if (value exists) i.load(value), i.merge(name)    
    } else if (en.hasAttribute(ATTR_VALUE)) {
        this.emitLoad(en.getAttribute(ATTR_VALUE));
        this.emitMerge(en.getAttribute(ATTR_NAME));

        // 4- else if (buffer exists)i.reduce(buffer), i.merge(name) 
    } else if (en.hasAttribute(ATTR_BUFFER)) {
        this.emitReduce(en.getAttribute(ATTR_BUFFER));
        this.emitMerge(en.getAttribute(ATTR_NAME));

        // 5-    else          i.clear(name), done
    } else {
        clearFlag = true;
    }

    // 6- if (cdata exists)    i.load(cdata), i.merge(name)
    try {
        cdata = getText(en.getFirstChild());
    } catch (Exception e) {
        cdata = null;
    }

    if (cdata != null) {
        this.emitLoad(cdata);
        this.emitMerge(en.getAttribute(ATTR_NAME));

        // 7- else if (CLEAR true, ALREADY false)      i.clear(name)
    } else if ((clearFlag == true) && (clearAlready == false)) {
        this.emitClear(name);
    }
}

From source file:org.shareok.data.dspacemanager.DspaceApiHandlerImpl.java

/**
 * Suppose ONLY two metadata file names for importing: dublin_core.xml and metadata_dcterms.xml
 * /*from  w ww .ja v  a 2 s  .  c o  m*/
 * @param paths : paths of the metadata files
 * @return : string array of metadata information
 */
@Override
public Map<String, String> getMetadataFromXmlFiles(String[] paths) {
    Map<String, String> data = new HashMap<>();
    Document doc = null;
    try {
        for (String path : paths) {
            String json = "";
            String dcType = "dc";
            doc = DocumentProcessorUtil.loadXMLFromString(path);
            if (null != doc) {
                doc.getDocumentElement().normalize();
                Node dcNode = doc.getDocumentElement();
                Node schema = dcNode.getAttributes().getNamedItem("schema");
                if (null != schema) {
                    dcType = schema.getNodeValue();
                }
                NodeList nList = doc.getElementsByTagName("dcvalue");
                for (int temp = 0; temp < nList.getLength(); temp++) {
                    Node nNode = nList.item(temp);
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode;
                        String dcElement = "";
                        String qualifier = "";
                        String lang = "en_US";
                        String value = "";

                        if (eElement.hasAttribute("element")) {
                            dcElement = eElement.getAttribute("element");
                        }
                        if (eElement.hasAttribute("qualifier")) {
                            qualifier = eElement.getAttribute("qualifier");
                            if ("none".equals(qualifier)) {
                                qualifier = "";
                            }
                        }
                        if (eElement.hasAttribute("language")) {
                            lang = eElement.getAttribute("language");
                        }
                        value = StringEscapeUtils.escapeJava(eElement.getTextContent());

                        String key = dcType + "." + dcElement + (!"".equals(qualifier) ? "." + qualifier : "");
                        json += "{\"key\":\"" + key + "\",\"value\":\"" + value + "\",\"language\":\"" + lang
                                + "\"},";
                    }
                }
            }
            if (!"".equals(json)) {
                json = "[" + json.substring(0, json.length() - 1) + "]";
                data.put(path, json);
            }
        }
    } catch (Exception ex) {
        logger.error("Cannot read metadata information from xml files", ex);
    }
    return data;
}

From source file:com.microfocus.application.automation.tools.results.RunResultRecorder.java

/**
 * copies, archives and creates the Test reports of LR and UFT runs.
 *
 * @param build//  w w  w. jav a  2s  . co  m
 * @param listener
 * @param resultFiles
 * @param testResult
 * @param runWorkspace
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws InterruptedException
 */
@SuppressWarnings({ "squid:S134", "squid:S135" })
private void archiveTestsReport(Run<?, ?> build, TaskListener listener, List<String> resultFiles,
        TestResult testResult, FilePath runWorkspace)
        throws ParserConfigurationException, SAXException, IOException, InterruptedException {

    if ((resultFiles == null) || (resultFiles.isEmpty())) {
        return;
    }

    ArrayList<String> zipFileNames = new ArrayList<String>();
    ArrayList<FilePath> reportFolders = new ArrayList<FilePath>();
    List<String> reportNames = new ArrayList<String>();

    listener.getLogger()
            .println("Report archiving mode is set to: " + _resultsPublisherModel.getArchiveTestResultsMode());

    // if user specified not to archive report
    if (_resultsPublisherModel.getArchiveTestResultsMode()
            .equals(ResultsPublisherModel.dontArchiveResults.getValue()))
        return;

    FilePath projectWS = runWorkspace;

    // get the artifacts directory where we will upload the zipped report
    // folder
    File artifactsDir = new File(build.getRootDir(), "archive");
    artifactsDir.mkdirs();

    // read each result.xml
    /*
     * The structure of the result file is: <testsuites> <testsuite>
     * <testcase.........report="path-to-report"/>
     * <testcase.........report="path-to-report"/>
     * <testcase.........report="path-to-report"/>
     * <testcase.........report="path-to-report"/> </testsuite>
     * </testsuites>
     */

    // add previous report names for aggregation when using pipelines.
    PerformanceJobReportAction performanceJobReportAction = build.getAction(PerformanceJobReportAction.class);
    if (performanceJobReportAction != null) {
        reportNames
                .addAll(performanceJobReportAction.getLrResultBuildDataset().getLrScenarioResults().keySet());
    }

    for (String resultsFilePath : resultFiles) {
        FilePath resultsFile = projectWS.child(resultsFilePath);

        List<ReportMetaData> ReportInfoToCollect = new ArrayList<ReportMetaData>();

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        Document doc = dBuilder.parse(resultsFile.read());
        doc.getDocumentElement().normalize();

        Node testSuiteNode = doc.getElementsByTagName("testsuite").item(0);
        Element testSuiteElement = (Element) testSuiteNode;
        if (testSuiteElement.hasAttribute("name") && testSuiteElement.getAttribute("name").endsWith(".lrs")) { // LR test
            NodeList testSuiteNodes = doc.getElementsByTagName("testsuite");
            for (int i = 0; i < testSuiteNodes.getLength(); i++) {
                testSuiteNode = testSuiteNodes.item(i);
                testSuiteElement = (Element) testSuiteNode;
                if (!testSuiteElement.hasAttribute("name")) {
                    continue;
                }
                String testFolderPath = testSuiteElement.getAttribute("name");
                int testPathArr = testFolderPath.lastIndexOf('\\');
                String testName = testFolderPath.substring(testPathArr + 1);
                reportNames.add(testName);
                String testStatus = ("0".equals(testSuiteElement.getAttribute("failures"))) ? "pass" : "fail";

                Node testCaseNode = testSuiteElement.getElementsByTagName("testcase").item(0);
                if (testCaseNode == null) {
                    listener.getLogger().println("No report folder was found in results");
                    return;
                }
                if (testCaseNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element testCaseElement = (Element) testCaseNode;

                    if (!testCaseElement.hasAttribute(REPORT_NAME_FIELD)) {
                        continue;
                    }

                    String reportFolderPath = testCaseElement.getAttribute(REPORT_NAME_FIELD);
                    FilePath reportFolder = new FilePath(projectWS.getChannel(), reportFolderPath);
                    reportFolders.add(reportFolder);

                    FilePath testFolder = new FilePath(projectWS.getChannel(), testFolderPath);
                    String zipFileName = getUniqueZipFileNameInFolder(zipFileNames, testFolder.getName());
                    FilePath archivedFile = new FilePath(new FilePath(artifactsDir), zipFileName);

                    if (archiveFolder(reportFolder, testStatus, archivedFile, listener)) {
                        zipFileNames.add(zipFileName);
                    }

                    createRichReports(reportFolder, testFolderPath, artifactsDir, reportNames, testResult,
                            listener);
                    createHtmlReport(reportFolder, testFolderPath, artifactsDir, reportNames, testResult);
                    createTransactionSummary(reportFolder, testFolderPath, artifactsDir, reportNames,
                            testResult);
                    try {
                        FilePath testSla = copyRunReport(reportFolder, build.getRootDir(),
                                testFolder.getName());
                        if (testSla == null) {
                            listener.getLogger().println("no RunReport.xml file was created");
                        } else {
                            runReportList.add(testSla);
                        }
                    } catch (IOException | InterruptedException e) {
                        listener.getLogger().println(e);
                    }
                }
            }
        } else { // UFT Test
            boolean reportIsHtml = false;
            NodeList testCasesNodes = ((Element) testSuiteNode).getElementsByTagName("testcase");
            Map<String, Integer> fileNameCount = new HashMap<>();

            for (int i = 0; i < testCasesNodes.getLength(); i++) {

                Node nNode = testCasesNodes.item(i);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                    if (!eElement.hasAttribute(REPORT_NAME_FIELD)) {
                        continue;
                    }

                    String reportFolderPath = eElement.getAttribute(REPORT_NAME_FIELD); // e.g. "C:\UFTTest\GuiTest1\Report"

                    String testFolderPath = eElement.getAttribute("name"); // e.g. "C:\UFTTest\GuiTest1"
                    String testStatus = eElement.getAttribute("status"); // e.g. "pass"

                    Node nodeSystemInfo = eElement.getElementsByTagName("system-out").item(0);
                    String sysinfo = nodeSystemInfo.getFirstChild().getNodeValue();
                    String testDateTime = sysinfo.substring(0, 19);

                    FilePath reportFolder = new FilePath(projectWS.getChannel(), reportFolderPath);
                    boolean isParallelRunnerReport = isParallelRunnerReportPath(reportFolder);

                    reportFolders.add(reportFolder);

                    String archiveTestResultMode = _resultsPublisherModel.getArchiveTestResultsMode();
                    boolean archiveTestResult = false;

                    //check for the new html report
                    FilePath htmlReport = new FilePath(reportFolder,
                            isParallelRunnerReport ? PARALLEL_RESULT_FILE : "run_results.html");

                    FilePath rrvReport = new FilePath(reportFolder, "Results.xml");
                    if (htmlReport.exists()) {
                        reportIsHtml = true;
                        String htmlReportDir = reportFolder.getRemote();

                        ReportMetaData reportMetaData = new ReportMetaData();
                        reportMetaData.setFolderPath(htmlReportDir);
                        reportMetaData.setIsHtmlReport(true);
                        reportMetaData.setDateTime(testDateTime);
                        reportMetaData.setStatus(testStatus);
                        reportMetaData.setIsParallelRunnerReport(isParallelRunnerReport); // we need to handle
                        // the type for this report
                        File testFileFullName = new File(testFolderPath);
                        String testName = org.apache.commons.io.FilenameUtils
                                .getName(testFileFullName.getPath());

                        // we must consider the case when we run the same test
                        // in the same build
                        Integer nameCount = 1;

                        if (fileNameCount.containsKey(testName)) {
                            nameCount = fileNameCount.get(testName) + 1;
                        }

                        // update the count for this file
                        fileNameCount.put(testName, nameCount);

                        testName += "[" + nameCount + "]";

                        String resourceUrl = "artifact/UFTReport/" + testName;
                        reportMetaData.setResourceURL(resourceUrl);
                        reportMetaData.setDisPlayName(testName); // use the name, not the full path

                        //don't know reportMetaData's URL path yet, we will generate it later.
                        ReportInfoToCollect.add(reportMetaData);

                        listener.getLogger().println(
                                "add html report info to ReportInfoToCollect: " + "[date]" + testDateTime);
                    }

                    archiveTestResult = isArchiveTestResult(testStatus, archiveTestResultMode);

                    if (archiveTestResult && rrvReport.exists()) {

                        if (reportFolder.exists()) {

                            FilePath testFolder = new FilePath(projectWS.getChannel(), testFolderPath);

                            String zipFileName = getUniqueZipFileNameInFolder(zipFileNames,
                                    testFolder.getName());
                            zipFileNames.add(zipFileName);

                            listener.getLogger().println("Zipping report folder: " + reportFolderPath);

                            ByteArrayOutputStream outstr = new ByteArrayOutputStream();

                            //don't use FileFilter for zip, or it will cause bug when files are on slave
                            reportFolder.zip(outstr);

                            /*
                             * I did't use copyRecursiveTo or copyFrom due to
                             * bug in
                             * jekins:https://issues.jenkins-ci.org/browse
                             * /JENKINS-9189 //(which is cleaimed to have been
                             * fixed, but not. So I zip the folder to stream and
                             * copy it to the master.
                             */

                            ByteArrayInputStream instr = new ByteArrayInputStream(outstr.toByteArray());

                            FilePath archivedFile = new FilePath(new FilePath(artifactsDir), zipFileName);
                            archivedFile.copyFrom(instr);
                            listener.getLogger().println("copy from slave to master: " + archivedFile);
                            outstr.close();
                            instr.close();

                            // add to Report list
                            ReportMetaData reportMetaData = new ReportMetaData();
                            reportMetaData.setIsHtmlReport(false);
                            reportMetaData.setIsParallelRunnerReport(false);
                            // reportMetaData.setFolderPath(htmlReportDir); //no need for RRV
                            File testFileFullName = new File(testFolderPath);
                            String testName = testFileFullName.getName();
                            reportMetaData.setDisPlayName(testName); // use the name, not the full path
                            String zipFileUrlName = "artifact/" + zipFileName;
                            reportMetaData.setUrlName(zipFileUrlName); // for RRV, the file url and resource url are the same.
                            reportMetaData.setResourceURL(zipFileUrlName);
                            reportMetaData.setDateTime(testDateTime);
                            reportMetaData.setStatus(testStatus);
                            ReportInfoToCollect.add(reportMetaData);

                        } else {
                            listener.getLogger().println("No report folder was found in: " + reportFolderPath);
                        }
                    }

                }
            }

            if (reportIsHtml && !ReportInfoToCollect.isEmpty()) {

                listener.getLogger().println("begin to collectAndPrepareHtmlReports");
                collectAndPrepareHtmlReports(build, listener, ReportInfoToCollect, runWorkspace);
            }

            if (!ReportInfoToCollect.isEmpty()) {
                // serialize report metadata
                File reportMetaDataXmlFile = new File(artifactsDir.getParent(), REPORTMETADATE_XML);
                String reportMetaDataXml = reportMetaDataXmlFile.getAbsolutePath();
                writeReportMetaData2XML(ReportInfoToCollect, reportMetaDataXml, listener);

                // Add UFT report action
                try {
                    listener.getLogger().println("Adding a report action to the current build.");
                    HtmlBuildReportAction reportAction = new HtmlBuildReportAction(build);
                    build.addAction(reportAction);

                } catch (IOException | SAXException | ParserConfigurationException ex) {
                    listener.getLogger().println("a problem adding action: " + ex);
                }
            }
        }
    }
}

From source file:io.sunrisedata.wikipedia.WikipediaPageRevision.java

public void readFromXml(String xml) throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new StringInputStream(xml));

    // and now the fun part

    NodeList n = doc.getChildNodes().item(0).getChildNodes();
    for (int i = 0; i < n.getLength(); i++) {
        Node node = n.item(i);//  w w w  . j a  v a2  s  .co m
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element e = (Element) node;
            switch (e.getTagName()) {
            case XML_TAG_CONTRIBUTOR:
                NodeList contribNodes = e.getChildNodes();
                for (int j = 0; j < contribNodes.getLength(); j++) {
                    Node contribNode = contribNodes.item(j);
                    if (contribNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element contribEl = (Element) contribNode;
                        switch (contribEl.getTagName()) {
                        case XML_TAG_CONTRIBUTOR_ID:
                            this.contributorId = contribEl.getTextContent();
                            break;
                        case XML_TAG_CONTRIBUTOR_IP:
                            this.contributorIp = contribEl.getTextContent();
                            break;
                        case XML_TAG_CONTRIBUTOR_USERNAME:
                            this.contributorUsername = contribEl.getTextContent();
                            break;
                        }
                    }
                }
                break;

            case XML_TAG_TEXT:
                contentWikiMarkup = e.getTextContent();
                if (e.hasAttribute(XML_ATTRIBUTE_TEXT_BYTES)) {
                    this.declaredContentLength = Integer.parseInt(e.getAttribute(XML_ATTRIBUTE_TEXT_BYTES));
                    if (this.declaredContentLength > 0 && isEmpty()) {
                        this.isMetadata = true;
                    }
                }
                // determine if article is a disambiguation, redirection, and/or stub page.
                // the first characters of the text must be equal to IDENTIFIER_REDIRECTION_UPPERCASE or IDENTIFIER_REDIRECTION_LOWERCASE
                this.isRedirect = contentWikiMarkup.startsWith(IDENTIFIER_REDIRECTION_LOWERCASE)
                        || contentWikiMarkup.startsWith(IDENTIFIER_REDIRECTION_UPPERCASE);

                // to be a stub, the article must contain the IDENTIFIER_STUB_WIKIPEDIA_NAMESPACE or IDENTIFIER_STUB_TEMPLATE
                this.isStub = contentWikiMarkup.contains(IDENTIFIER_STUB_TEMPLATE);

                break;

            case XML_TAG_ID:
                this.revisionId = e.getTextContent();
                break;

            case XML_TAG_TIMESTAMP:
                this.timestamp = e.getTextContent();
                break;

            case XML_TAG_MINOR:
                // presence of the empty <minor/> tag indicates it is a minor revision
                this.isMinor = true;
                break;

            case XML_TAG_COMMENT:
                this.comment = e.getTextContent();
                break;

            case XML_TAG_SHA1:
                this.sha1 = e.getTextContent();
                break;

            case XML_TAG_MODEL:
                this.model = e.getTextContent();
                break;

            case XML_TAG_FORMAT:
                this.format = e.getTextContent();
                break;

            case XML_TAG_PARENTID:
                this.parentRevisionId = e.getTextContent();
                break;
            }
        }
    }

}

From source file:eap.config.TxAdviceBeanDefinitionParser.java

private RootBeanDefinition parseAttributeSource(Element attrEle, ParserContext parserContext) {
    List<Element> methods = DomUtils.getChildElementsByTagName(attrEle, METHOD_ELEMENT);
    ManagedMap<TypedStringValue, RuleBasedTransactionAttribute> transactionAttributeMap = new ManagedMap<TypedStringValue, RuleBasedTransactionAttribute>(
            methods.size());/*from www .  java2 s.  com*/
    transactionAttributeMap.setSource(parserContext.extractSource(attrEle));

    for (Element methodEle : methods) {
        String name = methodEle.getAttribute(METHOD_NAME_ATTRIBUTE);
        TypedStringValue nameHolder = new TypedStringValue(name);
        nameHolder.setSource(parserContext.extractSource(methodEle));

        RuleBasedTransactionAttribute attribute = new RuleBasedTransactionAttribute();
        String propagation = methodEle.getAttribute(PROPAGATION_ATTRIBUTE);
        String isolation = methodEle.getAttribute(ISOLATION_ATTRIBUTE);
        String timeout = methodEle.getAttribute(TIMEOUT_ATTRIBUTE);
        String readOnly = methodEle.getAttribute(READ_ONLY_ATTRIBUTE);
        if (StringUtils.hasText(propagation)) {
            attribute
                    .setPropagationBehaviorName(RuleBasedTransactionAttribute.PREFIX_PROPAGATION + propagation);
        }
        if (StringUtils.hasText(isolation)) {
            attribute.setIsolationLevelName(RuleBasedTransactionAttribute.PREFIX_ISOLATION + isolation);
        }
        if (StringUtils.hasText(timeout)) {
            try {
                attribute.setTimeout(Integer.parseInt(timeout));
            } catch (NumberFormatException ex) {
                parserContext.getReaderContext().error("Timeout must be an integer value: [" + timeout + "]",
                        methodEle);
            }
        }
        if (StringUtils.hasText(readOnly)) {
            attribute.setReadOnly(Boolean.valueOf(methodEle.getAttribute(READ_ONLY_ATTRIBUTE)));
        }

        List<RollbackRuleAttribute> rollbackRules = new LinkedList<RollbackRuleAttribute>();
        if (methodEle.hasAttribute(ROLLBACK_FOR_ATTRIBUTE)) {
            String rollbackForValue = methodEle.getAttribute(ROLLBACK_FOR_ATTRIBUTE);
            addRollbackRuleAttributesTo(rollbackRules, rollbackForValue);
        }
        if (methodEle.hasAttribute(NO_ROLLBACK_FOR_ATTRIBUTE)) {
            String noRollbackForValue = methodEle.getAttribute(NO_ROLLBACK_FOR_ATTRIBUTE);
            addNoRollbackRuleAttributesTo(rollbackRules, noRollbackForValue);
        }
        attribute.setRollbackRules(rollbackRules);

        transactionAttributeMap.put(nameHolder, attribute);
    }

    RootBeanDefinition attributeSourceDefinition = new RootBeanDefinition(
            NameMatchTransactionAttributeSource.class);
    attributeSourceDefinition.setSource(parserContext.extractSource(attrEle));
    attributeSourceDefinition.getPropertyValues().add("nameMap", transactionAttributeMap);
    return attributeSourceDefinition;
}