Example usage for org.xml.sax ContentHandler startElement

List of usage examples for org.xml.sax ContentHandler startElement

Introduction

In this page you can find the example usage for org.xml.sax ContentHandler startElement.

Prototype

public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException;

Source Link

Document

Receive notification of the beginning of an element.

Usage

From source file:CSVXMLReader.java

/**
 * Parse a CSV file. SAX events are delivered to the ContentHandler
 * that was registered via <code>setContentHandler</code>.
 *
 * @param input the comma separated values file to parse.
 *//*from  w w  w.ja  va 2 s.  c  om*/
public void parse(InputSource input) throws IOException, SAXException {
    // if no handler is registered to receive events, don't bother
    // to parse the CSV file
    ContentHandler ch = getContentHandler();
    if (ch == null) {
        return;
    }

    // convert the InputSource into a BufferedReader
    BufferedReader br = null;
    if (input.getCharacterStream() != null) {
        br = new BufferedReader(input.getCharacterStream());
    } else if (input.getByteStream() != null) {
        br = new BufferedReader(new InputStreamReader(input.getByteStream()));
    } else if (input.getSystemId() != null) {
        java.net.URL url = new URL(input.getSystemId());
        br = new BufferedReader(new InputStreamReader(url.openStream()));
    } else {
        throw new SAXException("Invalid InputSource object");
    }

    ch.startDocument();

    // emit <csvFile>
    ch.startElement("", "", "csvFile", EMPTY_ATTR);

    // read each line of the file until EOF is reached
    String curLine = null;
    while ((curLine = br.readLine()) != null) {
        curLine = curLine.trim();
        if (curLine.length() > 0) {
            // create the <line> element
            ch.startElement("", "", "line", EMPTY_ATTR);
            // output data from this line
            parseLine(curLine, ch);
            // close the </line> element
            ch.endElement("", "", "line");
        }
    }

    // emit </csvFile>
    ch.endElement("", "", "csvFile");
    ch.endDocument();
}

From source file:com.mirth.connect.model.converters.NCPDPReader.java

private String parseHeader(String message, ContentHandler contentHandler) throws SAXException {
    String headerElementName = StringUtils.EMPTY;

    /*//  w  w w .ja  va 2s . c om
     * The first segment is always the Transaction header so we will process
     * it seperately.
     */
    if (message.indexOf(segmentDelimeter) != -1) {
        String header = message.substring(0, message.indexOf(segmentDelimeter));

        // handle a request (requests have a longer header than responses)
        if (header.length() > 40) {
            String transactionName = NCPDPReference.getInstance().getTransactionName(header.substring(8, 10));
            version = header.substring(6, 8);
            headerElementName = "NCPDP_" + version + "_" + transactionName + "_Request";

            contentHandler.startElement("", headerElementName, "", null);
            contentHandler.startElement("", "TransactionHeaderRequest", "", null);
            contentHandler.startElement("", "BinNumber", "", null);
            contentHandler.characters(header.toCharArray(), 0, 6);
            contentHandler.endElement("", "BinNumber", "");
            contentHandler.startElement("", "VersionReleaseNumber", "", null);
            contentHandler.characters(header.toCharArray(), 6, 2);
            contentHandler.endElement("", "VersionReleaseNumber", "");
            contentHandler.startElement("", "TransactionCode", "", null);
            contentHandler.characters(header.toCharArray(), 8, 2);
            contentHandler.endElement("", "TransactionCode", "");
            contentHandler.startElement("", "ProcessorControlNumber", "", null);
            contentHandler.characters(header.toCharArray(), 10, 10);
            contentHandler.endElement("", "ProcessorControlNumber", "");
            contentHandler.startElement("", "TransactionCount", "", null);
            contentHandler.characters(header.toCharArray(), 20, 1);
            contentHandler.endElement("", "TransactionCount", "");
            contentHandler.startElement("", "ServiceProviderIdQualifier", "", null);
            contentHandler.characters(header.toCharArray(), 21, 2);
            contentHandler.endElement("", "ServiceProviderIdQualifier", "");
            contentHandler.startElement("", "ServiceProviderId", "", null);
            contentHandler.characters(header.toCharArray(), 23, 15);
            contentHandler.endElement("", "ServiceProviderId", "");
            contentHandler.startElement("", "DateOfService", "", null);
            contentHandler.characters(header.toCharArray(), 38, 8);
            contentHandler.endElement("", "DateOfService", "");
            contentHandler.startElement("", "SoftwareVendorCertificationId", "", null);
            contentHandler.characters(header.toCharArray(), 46, 10);
            contentHandler.endElement("", "SoftwareVendorCertificationId", "");
            contentHandler.endElement("", "TransactionHeaderRequest", "");
        } else { // handle a response
            String transaction = NCPDPReference.getInstance().getTransactionName(header.substring(2, 4));
            version = header.substring(0, 2);
            headerElementName = "NCPDP_" + version + "_" + transaction + "_Response";

            contentHandler.startElement("", headerElementName, "", null);
            contentHandler.startElement("", "TransactionHeaderResponse", "", null);
            contentHandler.startElement("", "VersionReleaseNumber", "", null);
            contentHandler.characters(header.toCharArray(), 0, 2);
            contentHandler.endElement("", "VersionReleaseNumber", "");
            contentHandler.startElement("", "TransactionCode", "", null);
            contentHandler.characters(header.toCharArray(), 2, 2);
            contentHandler.endElement("", "TransactionCode", "");
            contentHandler.startElement("", "TransactionCount", "", null);
            contentHandler.characters(header.toCharArray(), 4, 1);
            contentHandler.endElement("", "TransactionCount", "");
            contentHandler.startElement("", "HeaderResponseStatus", "", null);
            contentHandler.characters(header.toCharArray(), 5, 1);
            contentHandler.endElement("", "HeaderResponseStatus", "");
            contentHandler.startElement("", "ServiceProviderIdQualifier", "", null);
            contentHandler.characters(header.toCharArray(), 6, 2);
            contentHandler.endElement("", "ServiceProviderIdQualifier", "");
            contentHandler.startElement("", "ServiceProviderId", "", null);
            contentHandler.characters(header.toCharArray(), 8, 15);
            contentHandler.endElement("", "ServiceProviderId", "");
            contentHandler.startElement("", "DateOfService", "", null);
            contentHandler.characters(header.toCharArray(), 23, 8);
            contentHandler.endElement("", "DateOfService", "");
            contentHandler.endElement("", "TransactionHeaderResponse", "");
        }
    }

    return headerElementName;
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.ER7Reader.java

private void handleFieldOrRepetitions(ContentHandler contentHandler, String fieldSeparator,
        String componentSeparator, String subcomponentSeparator, String repetitionSeparator,
        String escapeCharacter, String segmentId, StringTokenizer fieldTokenizer) throws SAXException {
    int fieldId = 0;
    boolean atLastField = false;

    while (fieldTokenizer.hasMoreTokens()) {
        boolean enteredHeader = false;

        /*/*from  w w  w .  j a  v  a  2  s. c  o m*/
         * Go through each element and add as new child under the segment
         * element
         */
        String field = fieldTokenizer.nextToken();

        // the naming is SEG.<field#>
        if (field.equals(fieldSeparator)) {
            if (atLastField) {
                contentHandler.startElement("", segmentId + "." + fieldId, "", null);
                contentHandler.endElement("", segmentId + "." + fieldId, "");
            }

            fieldId++;
            atLastField = true;
        } else {
            logger.trace("handling field or repetition: " + field);
            atLastField = false;

            // batch support
            if (segmentId.equals("MSH") || segmentId.equals("FHS") || segmentId.equals("BHS")) {
                enteredHeader = true;
            }

            if (enteredHeader && (fieldId == 1)) {
                contentHandler.startElement("", segmentId + "." + fieldId, "", null);
                contentHandler.characters(fieldSeparator.toCharArray(), 0, 1);
                contentHandler.endElement("", segmentId + "." + (fieldId), null);
                fieldId++;
                contentHandler.startElement("", segmentId + "." + fieldId, "", null);

                char[] specialCharacters;
                if (!subcomponentSeparator.isEmpty()) {
                    specialCharacters = new char[] { componentSeparator.charAt(0),
                            repetitionSeparator.charAt(0), escapeCharacter.charAt(0),
                            subcomponentSeparator.charAt(0) };
                } else if (!escapeCharacter.isEmpty()) {
                    specialCharacters = new char[] { componentSeparator.charAt(0),
                            repetitionSeparator.charAt(0), escapeCharacter.charAt(0), };
                } else {
                    specialCharacters = new char[] { componentSeparator.charAt(0),
                            repetitionSeparator.charAt(0), };
                }

                contentHandler.characters(specialCharacters, 0, specialCharacters.length);
                contentHandler.endElement("", segmentId + "." + (fieldId), null);
            } else if (enteredHeader && (fieldId == 2)) {
                // do nothing
            } else {
                if (handleRepetitions) {
                    handleFieldRepetitions(contentHandler, componentSeparator, repetitionSeparator,
                            subcomponentSeparator, segmentId, fieldId, field);
                } else {
                    handleField(contentHandler, componentSeparator, subcomponentSeparator, segmentId, fieldId,
                            field);
                }
            }
        }
    }

    if (atLastField) {
        contentHandler.startElement("", segmentId + "." + fieldId, "", null);
        contentHandler.endElement("", segmentId + "." + fieldId, "");
    }
}

From source file:net.ontopia.topicmaps.db2tm.RelationMapping.java

protected void outputEntities(Relation rel, ContentHandler dh) throws SAXException {
    AttributesImpl atts = new AttributesImpl();

    for (Entity entity : rel.getEntities()) {
        if (entity.getEntityType() == Entity.TYPE_TOPIC) {
            // <topic>
            if (entity.getId() != null)
                addAttribute(atts, "id", "CDATA", entity.getId());
            addAttribute(atts, "type", "CDATA", entity.getAssociationType());
            dh.startElement("", "", "topic", atts);
            atts.clear();// w ww . ja v a  2s  .c  om

            outputFields(entity, dh);

            // </topic>
            dh.endElement("", "", "topic");

        } else if (entity.getEntityType() == Entity.TYPE_ASSOCIATION) {

            // <association>
            if (entity.getId() != null)
                addAttribute(atts, "id", "CDATA", entity.getId());
            addAttribute(atts, "type", "CDATA", entity.getAssociationType());
            addAttribute(atts, "scope", "CDATA", entity.getScope());

            dh.startElement("", "", "association", atts);
            atts.clear();

            outputFields(entity, dh);

            // </association>
            dh.endElement("", "", "association");
        }
    }
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.ER7Reader.java

private String handleSegments(String documentHead, ContentHandler contentHandler, String fieldSeparator,
        String componentSeparator, String subcomponentSeparator, String repetitionSeparator,
        String escapeCharacter, String[] segments) throws SAXException {
    for (int segmentIndex = 0; segmentIndex < segments.length; segmentIndex++) {
        String segment = segments[segmentIndex];
        logger.trace("handling segment: " + segment);
        // loop through each segment and pull out the fields
        StringTokenizer fieldTokenizer = new StringTokenizer(segment, fieldSeparator, true);

        if (fieldTokenizer.hasMoreTokens()) {
            // the XML element is named after the first field
            String segmentId = fieldTokenizer.nextToken().trim();

            if (segmentIndex == 0) {
                documentHead = MESSAGE_ROOT_ID;
                contentHandler.startElement("", documentHead, "", null);
            }//  w w  w . j  a v a 2 s  .com

            contentHandler.startElement("", segmentId, "", null);
            handleFieldOrRepetitions(contentHandler, fieldSeparator, componentSeparator, subcomponentSeparator,
                    repetitionSeparator, escapeCharacter, segmentId, fieldTokenizer);
            contentHandler.endElement("", segmentId, "");
        } else {
            throw new SAXException("Could not find fields in segment: " + segment);
        }
    }

    return documentHead;
}

From source file:biz.taoconsulting.oxf.processor.converter.FromPdfConverter.java

/**
 * processBookmark gets called recursively for all nested bookmarks extracts
 * the bookmark and the text/*from  w  ww. ja va2  s .  c  o  m*/
        
 */
private void processBookmark(ContentHandler hd, PDDocument doc, PDOutlineItem curItem, String scope,
        int level) {
    // First we check on what page the bookmark is. If we can't retrieve the
    // page the bookmark can't be the outline we are looking for, however we
    // would process children (you never know)
    try {

        int curPageNo = getPageNumber(doc, curItem);

        if (curPageNo > -1) {

            AttributesImpl atts = new AttributesImpl();
            atts.addAttribute("", ATT_LEVEL, ATT_LEVEL, ATT_CDATA, Integer.toString(level));
            atts.addAttribute("", ATT_PAGE, ATT_PAGE, ATT_CDATA, Integer.toString(curPageNo));

            hd.startElement("", TAG_BOOKMARK, TAG_BOOKMARK, atts);

            // Write the properties of interest
            atts.clear();
            hd.startElement("", TAG_TITLE, TAG_TITLE, atts);
            String curTitle = curItem.getTitle();
            hd.characters(curTitle.toCharArray(), 0, curTitle.length());
            hd.endElement("", TAG_TITLE, TAG_TITLE);

            //write out the text associated with this bookmark
            // if the scope allows for that

            if (!scope.toLowerCase().equals(SCOPE_BOOKMARKSONLY)) {

                PDFTextStripper stripper = new PDFTextStripper();
                stripper.setStartBookmark(curItem);
                stripper.setEndBookmark(curItem);
                String textBetweenBookmarks = stripper.getText(doc);
                hd.startElement("", TAG_TEXT, TAG_TEXT, atts);
                textBetweenBookmarks = MassageTextResult(textBetweenBookmarks);
                hd.characters(textBetweenBookmarks.toCharArray(), 0, textBetweenBookmarks.length());
                hd.endElement("", TAG_TEXT, TAG_TEXT);

            }

        }
        // Now check the children
        PDOutlineItem child = curItem.getFirstChild();
        while (child != null) {
            processBookmark(hd, doc, child, scope, level + 1);
            logger.info("Child:" + child.getTitle());
            child = child.getNextSibling();
        }
        // Close the mark
        hd.endElement("", TAG_BOOKMARK, TAG_BOOKMARK);
    } catch (SAXException e) {
        logger.error(e);
        addErrorTagToOutput(hd, e.toString());
    } catch (IOException e) {
        logger.error(e);
        addErrorTagToOutput(hd, e.toString());
    } finally {
        // Nothing concluding to do
    }
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.hl7.HL7MapToLexGrid.java

void loadMetaData(CodingScheme csclass, String connectionString, String driver) {

    messages_.info("Loading individual coding scheme metadata");
    Connection c = null;//w  w  w. ja v a  2 s .  c  om

    // create the filename of the metadata file to be created
    String filename = loaderPrefs.getXMLMetadataFilePath() + "/"
            + PreferenceLoaderConstants.META_HL7_METADATA_FILE_NAME;

    FileOutputStream fos;
    try {
        fos = new FileOutputStream(filename);

        OutputFormat of = new OutputFormat("XML", "ISO-8859-1", true);
        of.setIndent(1);
        of.setIndenting(true);
        XMLSerializer serializer = new XMLSerializer(fos, of);

        // SAX2.0 ContentHandler.
        ContentHandler hd = serializer.asContentHandler();
        hd.startDocument();

        // Element attributes.
        AttributesImpl atts = new AttributesImpl();

        // CODINGSCHEMES tag.
        hd.startElement("", "", "codingSchemes", atts);

        String defaultLanguage = "en";
        String isNative = "0";
        String codeSystemId;
        String codeSystemType;
        String codeSystemName;
        String fullName;
        String description;
        String releaseId;
        String copyrightNotice;
        Integer approximateNumberofConcepts;

        try {
            c = DBUtility.connectToDatabase(accessConnectionString, driver, null, null);

            PreparedStatement getCodingSchemeMetaData = c
                    .prepareStatement("SELECT b.codeSystemid, b.codeSystemType, b.codeSystemName, "
                            + "b.fullName, b.description, b.releaseId, b.copyrightNotice "
                            + "FROM VCS_code_system AS b");
            ResultSet codingSchemeMetaData = getCodingSchemeMetaData.executeQuery();

            PreparedStatement getCodingSchemeConceptCount = c
                    .prepareStatement("SELECT VCS_concept_code_xref.codeSystemId2, "
                            + "COUNT (VCS_concept_code_xref.codeSystemId2) as conceptcount "
                            + "FROM VCS_concept_code_xref " + "GROUP BY VCS_concept_code_xref.codeSystemId2;");

            ResultSet codingSchemeConceptCount = getCodingSchemeConceptCount.executeQuery();

            Hashtable<String, Integer> conceptCountList = new Hashtable<String, Integer>();

            while (codingSchemeConceptCount.next()) {

                String codingSchemeId = codingSchemeConceptCount.getString("codeSystemId2");
                String codingSchemeCount = codingSchemeConceptCount.getString("conceptcount");

                conceptCountList.put(new String(codingSchemeId), new Integer(codingSchemeCount));
            }

            codingSchemeConceptCount.close();

            int codeSchemeCounter = 0;

            while (codingSchemeMetaData.next()) {
                codeSystemId = codingSchemeMetaData.getString("codeSystemid");
                if (codeSystemId == null) {
                    codeSystemId = SQLTableConstants.TBLCOLVAL_MISSING;
                }

                codeSystemType = codingSchemeMetaData.getString("codeSystemType");
                if (codeSystemType == null) {
                    codeSystemType = SQLTableConstants.TBLCOLVAL_MISSING;
                }

                codeSystemName = codingSchemeMetaData.getString("codeSystemName");
                if (codeSystemName == null) {
                    codeSystemName = SQLTableConstants.TBLCOLVAL_MISSING;
                }

                fullName = codingSchemeMetaData.getString("fullName");
                if (fullName == null) {
                    fullName = SQLTableConstants.TBLCOLVAL_MISSING;
                }

                description = codingSchemeMetaData.getString("description");
                if (description == null) {
                    description = SQLTableConstants.TBLCOLVAL_MISSING;
                }
                // The description contains HTML tags. We try to remove
                // them.
                else {
                    int begin = description.lastIndexOf("<p>");
                    int end = description.lastIndexOf("</p>");
                    if (begin > -1) {
                        if (begin + 3 < end)
                            description = description.substring(begin + 3, end);
                    }
                }

                releaseId = codingSchemeMetaData.getString("releaseId");
                if (releaseId == null) {
                    releaseId = SQLTableConstants.TBLCOLVAL_MISSING;
                }

                copyrightNotice = codingSchemeMetaData.getString("copyrightNotice");
                if (copyrightNotice == null) {
                    copyrightNotice = SQLTableConstants.TBLCOLVAL_MISSING;
                }

                approximateNumberofConcepts = ((Integer) conceptCountList.get(codeSystemId));
                if (approximateNumberofConcepts == null) {
                    approximateNumberofConcepts = new Integer(0);
                }

                // Begin codingScheme element
                atts.clear();
                atts.addAttribute("", "", SQLTableConstants.TBLCOL_CODINGSCHEMENAME, "CDATA", codeSystemName);
                // May want to change to _fullName
                atts.addAttribute("", "", SQLTableConstants.TBLCOL_FORMALNAME, "CDATA", fullName);
                atts.addAttribute("", "", SQLTableConstants.TBLCOL_CODINGSCHEMEURI, "CDATA", codeSystemId);
                atts.addAttribute("", "", SQLTableConstants.TBLCOL_DEFAULTLANGUAGE, "CDATA", defaultLanguage);
                atts.addAttribute("", "", SQLTableConstants.TBLCOL_REPRESENTSVERSION, "CDATA", releaseId);
                atts.addAttribute("", "", SQLTableConstants.TBLCOL_ISNATIVE, "CDATA", isNative);
                atts.addAttribute("", "", SQLTableConstants.TBLCOL_APPROXNUMCONCEPTS, "CDATA",
                        approximateNumberofConcepts.toString());
                hd.startElement("", "", SQLTableConstants.TBLCOL_CODINGSCHEME, atts);

                // localname
                atts.clear();
                hd.startElement("", "", "localName", atts);
                hd.characters(codeSystemName.toCharArray(), 0, codeSystemName.length());
                hd.endElement("", "", SQLTableConstants.TBLCOLVAL_LOCALNAME);

                // entityDescription
                atts.clear();
                hd.startElement("", "", SQLTableConstants.TBLCOL_ENTITYDESCRIPTION, atts);
                hd.characters(description.toCharArray(), 0, description.length());
                hd.endElement("", "", SQLTableConstants.TBLCOL_ENTITYDESCRIPTION);

                // copyright
                atts.clear();
                hd.startElement("", "", SQLTableConstants.TBLCOL_COPYRIGHT, atts);
                hd.characters(copyrightNotice.toCharArray(), 0, copyrightNotice.length());
                hd.endElement("", "", SQLTableConstants.TBLCOL_COPYRIGHT);

                // May need to include as Property
                // // CodingScheme
                // atts.clear();
                // hd.startElement("","","CodingScheme",atts);
                // hd.characters(_codeSystemType.toCharArray(),0,_codeSystemType.length());
                // hd.endElement("","","CodingScheme");

                // End codingScheme element
                hd.endElement("", "", SQLTableConstants.TBLCOL_CODINGSCHEME);

                codeSchemeCounter++;

            } // End while there are result rows to process

            getCodingSchemeConceptCount.close();

            hd.endElement("", "", "codingSchemes");
            hd.endDocument();
            fos.close();

        } catch (Exception e) {
            messages_.error("Failed while preparing HL7 Code System MetaData.", e);
            e.printStackTrace();
        } finally {
            try {
                c.close();
            } catch (SQLException e) {
                messages_.debug("An error occurred while closing the MS Access connection: " + e.getMessage());
                e.printStackTrace();
            }
        }

    } catch (FileNotFoundException fnfe) {
        messages_.debug("Loader Preferences file was not found, file: " + filename);
        fnfe.printStackTrace();
    } catch (IOException ioe) {
        messages_.debug("IOException, file: " + filename);
        ioe.printStackTrace();
    } catch (SAXException saxe) {
        messages_.debug("SAXException, file: " + filename);
        saxe.printStackTrace();
    }

}

From source file:com.mirth.connect.model.converters.NCPDPReader.java

private void parseSegment(String segment, ContentHandler contentHandler) throws SAXException {
    if (StringUtils.isBlank(segment)) {
        return;//from  w w w .  j a  v  a 2  s .  c  om
    }

    boolean inCounter = false;
    boolean inCount = false;
    boolean hasMoreFields = true;
    String segmentId = StringUtils.EMPTY;
    String subSegment = StringUtils.EMPTY;
    Stack<String> fieldStack = new Stack<String>();

    int fieldDelimeterIndex = segment.indexOf(fieldDelimeter);

    if (fieldDelimeterIndex == 0) {
        segment = segment.substring(fieldDelimeterIndex + fieldDelimeter.length());
        fieldDelimeterIndex = segment.indexOf(fieldDelimeter);
    }

    if (fieldDelimeterIndex == -1) {
        logger.warn("Empty segment with no field seperators. Make sure batch file processing is disabled.");
        hasMoreFields = false;
        segmentId = segment;
    } else {
        segmentId = segment.substring(0, fieldDelimeterIndex);
        subSegment = segment.substring(fieldDelimeterIndex + fieldDelimeter.length(), segment.length());
    }

    contentHandler.startElement("", NCPDPReference.getInstance().getSegment(segmentId, version), "", null);

    while (hasMoreFields) {
        fieldDelimeterIndex = subSegment.indexOf(fieldDelimeter);
        // not last field
        String field;

        if (fieldDelimeterIndex != -1) {
            field = subSegment.substring(0, subSegment.indexOf(fieldDelimeter));
            subSegment = subSegment.substring(fieldDelimeterIndex + fieldDelimeter.length());
        } else {
            field = subSegment;
            hasMoreFields = false;
        }

        String fieldId = field.substring(0, 2);
        String fieldDescription = NCPDPReference.getInstance().getDescription(fieldId, version);
        String fieldMessage = field.substring(2);

        if (inCount && !isRepeatingField(fieldDescription) && !fieldDescription.endsWith("Count")) {
            // if we are were in count field then end the element
            contentHandler.endElement("", fieldStack.pop(), "");

            if (fieldStack.size() == 0) {
                inCount = false;
            }
        }

        if (fieldDescription.endsWith("Counter")) {
            if (inCounter) {
                contentHandler.endElement("", fieldStack.pop(), "");
            }

            inCounter = true;
            AttributesImpl attr = new AttributesImpl();
            attr.addAttribute("", "counter", "counter", "", fieldMessage);
            contentHandler.startElement("", fieldDescription, "", attr);
            fieldStack.push(fieldDescription);
        } else if (fieldDescription.endsWith("Count")) {
            // count field, add complex element
            inCount = true;
            AttributesImpl attr = new AttributesImpl();
            attr.addAttribute("", fieldDescription, fieldDescription, "", fieldMessage);
            // start the repeating field element
            contentHandler.startElement("", fieldDescription, "", attr);
            fieldStack.push(fieldDescription);
        } else {
            contentHandler.startElement("", fieldDescription, "", null);
            contentHandler.characters(fieldMessage.toCharArray(), 0, fieldMessage.length());
            contentHandler.endElement("", fieldDescription, "");
        }
    }

    while (fieldStack.size() > 0) {
        // close remaining count and counters
        contentHandler.endElement("", fieldStack.pop(), "");
    }

    contentHandler.endElement("", NCPDPReference.getInstance().getSegment(segmentId, version), "");
}

From source file:com.mirth.connect.model.converters.NCPDPReader.java

@Override
public void parse(InputSource input) throws SAXException, IOException {
    // convert the InputSource to a String and trim the whitespace
    String message = IOUtils.toString(input.getCharacterStream()).trim();

    ContentHandler contentHandler = getContentHandler();
    contentHandler.startDocument();/*from   w  ww  . j  a  va2 s.co  m*/

    if ((message == null) || (message.length() < 3)) {
        throw new SAXException("Unable to parse, message is null or too short: " + message);
    }

    // process header
    String header = parseHeader(message, contentHandler);

    // process body
    int groupDelimeterIndex = message.indexOf(groupDelimeter);
    int segmentDelimeterIndex = message.indexOf(segmentDelimeter);
    int bodyIndex = 0;

    if ((groupDelimeterIndex == -1) || (segmentDelimeterIndex < groupDelimeterIndex)) {
        bodyIndex = segmentDelimeterIndex;
    } else {
        bodyIndex = groupDelimeterIndex;
    }

    String body = message.substring(bodyIndex, message.length());

    boolean hasMoreSegments = true;
    boolean inGroup = false;
    boolean firstTransaction = true;
    int groupCounter = 0;

    while (hasMoreSegments) {
        // get next segment or group
        groupDelimeterIndex = body.indexOf(groupDelimeter);
        segmentDelimeterIndex = body.indexOf(segmentDelimeter);

        if ((groupDelimeterIndex > -1) && (groupDelimeterIndex < segmentDelimeterIndex)) { // case: next part is a group
            // process last segment before group
            parseSegment(body.substring(0, groupDelimeterIndex), contentHandler);

            if (inGroup) {
                contentHandler.endElement("", "TRANSACTION", "");
            }

            if (firstTransaction) {
                firstTransaction = false;
                contentHandler.startElement("", "TRANSACTIONS", "", null);
            }

            // process a group
            AttributesImpl attr = new AttributesImpl();
            attr.addAttribute("", "counter", "counter", "", Integer.toString(++groupCounter));
            contentHandler.startElement("", "TRANSACTION", "", attr);
            inGroup = true;
        } else if (groupDelimeterIndex == -1 && segmentDelimeterIndex == -1) { // case: last segment
            parseSegment(body, contentHandler);
            hasMoreSegments = false;
        } else { // case: next part is a segment
            String segment = body.substring(0, segmentDelimeterIndex);
            parseSegment(segment, contentHandler);
        }

        // remove processed segment from message body
        body = body.substring(segmentDelimeterIndex + segmentDelimeter.length());
    }

    // end group if we have started one
    if (inGroup) {
        contentHandler.endElement("", "TRANSACTION", "");
        contentHandler.endElement("", "TRANSACTIONS", "");
    }

    contentHandler.endElement("", header, "");
    contentHandler.endDocument();
}

From source file:org.syncope.core.report.UserReportlet.java

private void doExtract(final ContentHandler handler, final UserReportletConf conf,
        final List<SyncopeUser> users) throws SAXException, ReportException {

    AttributesImpl atts = new AttributesImpl();
    for (SyncopeUser user : users) {
        atts.clear();//from   w  ww  .jav a 2 s  .  c om

        for (Feature feature : conf.getFeatures()) {
            String type = null;
            String value = null;
            switch (feature) {
            case id:
                type = XSD_LONG;
                value = String.valueOf(user.getId());
                break;

            case username:
                type = XSD_STRING;
                value = user.getUsername();
                break;

            case workflowId:
                type = XSD_LONG;
                value = String.valueOf(user.getWorkflowId());
                break;

            case status:
                type = XSD_STRING;
                value = user.getStatus();
                break;

            case creationDate:
                type = XSD_DATETIME;
                value = user.getCreationDate() == null ? "" : DATE_FORMAT.get().format(user.getCreationDate());
                break;

            case lastLoginDate:
                type = XSD_DATETIME;
                value = user.getLastLoginDate() == null ? ""
                        : DATE_FORMAT.get().format(user.getLastLoginDate());
                break;

            case changePwdDate:
                type = XSD_DATETIME;
                value = user.getChangePwdDate() == null ? ""
                        : DATE_FORMAT.get().format(user.getChangePwdDate());
                break;

            case passwordHistorySize:
                type = XSD_INT;
                value = String.valueOf(user.getPasswordHistory().size());
                break;

            case failedLoginCount:
                type = XSD_INT;
                value = String.valueOf(user.getFailedLogins());
                break;

            default:
            }

            if (type != null && value != null) {
                atts.addAttribute("", "", feature.name(), type, value);
            }
        }

        handler.startElement("", "", "user", atts);

        // Using UserTO for attribute values, since the conversion logic of
        // values to String is already encapsulated there
        UserTO userTO = userDataBinder.getUserTO(user);

        doExtractAttributes(handler, userTO, conf.getAttrs(), conf.getDerAttrs(), conf.getVirAttrs());

        if (conf.getFeatures().contains(Feature.memberships)) {
            handler.startElement("", "", "memberships", null);

            for (MembershipTO memb : userTO.getMemberships()) {
                atts.clear();

                atts.addAttribute("", "", "id", XSD_LONG, String.valueOf(memb.getId()));
                atts.addAttribute("", "", "roleId", XSD_LONG, String.valueOf(memb.getRoleId()));
                atts.addAttribute("", "", "roleName", XSD_STRING, String.valueOf(memb.getRoleName()));
                handler.startElement("", "", "membership", atts);

                doExtractAttributes(handler, memb, memb.getAttributeMap().keySet(),
                        memb.getDerivedAttributeMap().keySet(), memb.getVirtualAttributeMap().keySet());

                if (conf.getFeatures().contains(Feature.resources)) {
                    Membership actualMemb = user.getMembership(memb.getRoleId());
                    if (actualMemb == null) {
                        LOG.warn("Unexpected: cannot find membership for " + "role {} for user {}",
                                memb.getRoleId(), user);
                    } else {
                        doExtractResources(handler, roleDataBinder.getRoleTO(actualMemb.getSyncopeRole()));
                    }
                }

                handler.endElement("", "", "membership");
            }

            handler.endElement("", "", "memberships");
        }

        if (conf.getFeatures().contains(Feature.resources)) {
            doExtractResources(handler, userTO);
        }

        handler.endElement("", "", "user");
    }
}