Example usage for org.xml.sax ContentHandler characters

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

Introduction

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

Prototype

public void characters(char ch[], int start, int length) throws SAXException;

Source Link

Document

Receive notification of character data.

Usage

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   www.  jav a 2  s . c  o m*/
    }

    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: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  .  j  a  va  2s  .  c o m

    // 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:nl.architolk.ldt.processors.HttpClientProcessor.java

public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException {

    try {/*  w w w .j a va 2 s.c  om*/
        CloseableHttpClient httpclient = HttpClientProperties.createHttpClient();

        try {
            // Read content of config pipe
            Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
            Node configNode = configDocument.selectSingleNode("//config");

            URL theURL = new URL(configNode.valueOf("url"));

            if (configNode.valueOf("auth-method").equals("basic")) {
                HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol());
                //Authentication support
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                        configNode.valueOf("username"), configNode.valueOf("password")));
                // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password"));
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                authCache.put(targetHost, new BasicScheme());

                // Add AuthCache to the execution context
                httpContext = HttpClientContext.create();
                httpContext.setCredentialsProvider(credsProvider);
                httpContext.setAuthCache(authCache);
            } else if (configNode.valueOf("auth-method").equals("form")) {
                //Sign in. Cookie will be remembered bij httpclient
                HttpPost authpost = new HttpPost(configNode.valueOf("auth-url"));
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username")));
                nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password")));
                authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                CloseableHttpResponse httpResponse = httpclient.execute(authpost);
                // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode()));
            }

            CloseableHttpResponse response;
            if (configNode.valueOf("method").equals("post")) {
                // POST
                HttpPost httpRequest = new HttpPost(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("put")) {
                // PUT
                HttpPut httpRequest = new HttpPut(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("delete")) {
                //DELETE
                HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("head")) {
                //HEAD
                HttpHead httpRequest = new HttpHead(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("options")) {
                //OPTIONS
                HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else {
                //Default = GET
                HttpGet httpRequest = new HttpGet(configNode.valueOf("url"));
                String acceptHeader = configNode.valueOf("accept");
                if (!acceptHeader.isEmpty()) {
                    httpRequest.addHeader("accept", configNode.valueOf("accept"));
                }
                //Add proxy route if needed
                HttpClientProperties.setProxy(httpRequest, theURL.getHost());
                response = executeRequest(httpRequest, httpclient);
            }

            try {
                contentHandler.startDocument();

                int status = response.getStatusLine().getStatusCode();
                AttributesImpl statusAttr = new AttributesImpl();
                statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status));
                contentHandler.startElement("", "response", "response", statusAttr);
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    Header contentType = response.getFirstHeader("Content-Type");
                    if (entity != null && contentType != null) {
                        //logger.info("Contenttype: " + contentType.getValue());
                        //Read content into inputstream
                        InputStream inStream = entity.getContent();

                        // output-type = json means: response is json, convert to xml
                        if (configNode.valueOf("output-type").equals("json")) {
                            //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!!
                            //javax.json contains readers to read from an inputstream
                            StringWriter writer = new StringWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            JSONObject json = JSONObject.fromObject(writer.toString());
                            parseJSONObject(contentHandler, json);
                            // output-type = xml means: response is xml, keep it
                        } else if (configNode.valueOf("output-type").equals("xml")) {
                            try {
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml
                        } else if (configNode.valueOf("output-type").equals("jsonld")) {
                            try {
                                Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response!
                                Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback());

                                Any23 runner = new Any23();
                                DocumentSource source = new StringDocumentSource((String) nquads,
                                        configNode.valueOf("url"));
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inJsonStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml
                        } else if (configNode.valueOf("output-type").equals("rdf")) {
                            try {
                                Any23 runner = new Any23();

                                DocumentSource source;
                                //If contentType = text/html than convert from html to xhtml to handle non-xml style html!
                                logger.info("Contenttype: " + contentType.getValue());
                                if (configNode.valueOf("tidy").equals("yes")
                                        && contentType.getValue().startsWith("text/html")) {
                                    org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8",
                                            configNode.valueOf("url")); //TODO UTF-8 should be read from response!

                                    RDFCleaner cleaner = new RDFCleaner();
                                    org.jsoup.nodes.Document cleandoc = cleaner.clean(doc);
                                    cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
                                    cleandoc.outputSettings()
                                            .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
                                    cleandoc.outputSettings().charset("UTF-8");

                                    source = new StringDocumentSource(cleandoc.html(),
                                            configNode.valueOf("url"), contentType.getValue());
                                } else {
                                    source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"),
                                            contentType.getValue());
                                }

                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inAnyStream));

                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                        } else {
                            CharArrayWriter writer = new CharArrayWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            contentHandler.characters(writer.toCharArray(), 0, writer.size());
                        }
                    }
                }
                contentHandler.endElement("", "response", "response");

                contentHandler.endDocument();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }

}

From source file:org.apache.cocoon.components.notification.Notifier.java

/**
 * Generate notification information in XML format.
 *//*from ww w. java  2 s .c  o  m*/
public static void notify(Notifying n, ContentHandler ch, String mimetype) throws SAXException {
    final String PREFIX = Constants.ERROR_NAMESPACE_PREFIX;
    final String URI = Constants.ERROR_NAMESPACE_URI;

    // Start the document
    ch.startDocument();
    ch.startPrefixMapping(PREFIX, URI);

    // Root element.
    AttributesImpl atts = new AttributesImpl();

    atts.addAttribute(URI, "type", PREFIX + ":type", "CDATA", n.getType());
    atts.addAttribute(URI, "sender", PREFIX + ":sender", "CDATA", n.getSender());
    ch.startElement(URI, "notify", PREFIX + ":notify", atts);
    ch.startElement(URI, "title", PREFIX + ":title", new AttributesImpl());
    ch.characters(n.getTitle().toCharArray(), 0, n.getTitle().length());
    ch.endElement(URI, "title", PREFIX + ":title");
    ch.startElement(URI, "source", PREFIX + ":source", new AttributesImpl());
    ch.characters(n.getSource().toCharArray(), 0, n.getSource().length());
    ch.endElement(URI, "source", PREFIX + ":source");
    ch.startElement(URI, "message", PREFIX + ":message", new AttributesImpl());

    if (n.getMessage() != null) {
        ch.characters(n.getMessage().toCharArray(), 0, n.getMessage().length());
    }

    ch.endElement(URI, "message", PREFIX + ":message");
    ch.startElement(URI, "description", PREFIX + ":description", XMLUtils.EMPTY_ATTRIBUTES);
    ch.characters(n.getDescription().toCharArray(), 0, n.getDescription().length());
    ch.endElement(URI, "description", PREFIX + ":description");

    Map extraDescriptions = n.getExtraDescriptions();
    for (Iterator i = extraDescriptions.entrySet().iterator(); i.hasNext();) {
        final Map.Entry me = (Map.Entry) i.next();
        String key = (String) me.getKey();
        String value = String.valueOf(me.getValue());
        atts = new AttributesImpl();
        atts.addAttribute(URI, "description", PREFIX + ":description", "CDATA", key);
        ch.startElement(URI, "extra", PREFIX + ":extra", atts);
        ch.characters(value.toCharArray(), 0, value.length());
        ch.endElement(URI, "extra", PREFIX + ":extra");
    }

    // End root element.
    ch.endElement(URI, "notify", PREFIX + ":notify");

    // End the document.
    ch.endPrefixMapping(PREFIX);
    ch.endDocument();
}

From source file:org.apache.cocoon.components.source.impl.QDoxSource.java

/**
 * Method saxCharacters./*w ww  .j  a  v a 2 s .  c o  m*/
 *
 * @param handler
 * @param text
 */
private void saxCharacters(ContentHandler handler, String text) throws SAXException {
    if (text != null && text.length() > 0) {
        handler.characters(text.toCharArray(), 0, text.length());
    }
}

From source file:org.apache.cocoon.forms.datatype.EnumSelectionList.java

public void generateSaxFragment(ContentHandler contentHandler, Locale locale) throws SAXException {
    try {/*from  w  w w .  j  a v a2  s . c o m*/
        contentHandler.startElement(FormsConstants.INSTANCE_NS, SELECTION_LIST_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + SELECTION_LIST_EL, XMLUtils.EMPTY_ATTRIBUTES);
        // Create void element
        if (nullable) {
            AttributesImpl voidAttrs = new AttributesImpl();
            voidAttrs.addCDATAAttribute("value", "");
            contentHandler.startElement(FormsConstants.INSTANCE_NS, ITEM_EL,
                    FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL, voidAttrs);
            if (this.nullText != null) {
                contentHandler.startElement(FormsConstants.INSTANCE_NS, LABEL_EL,
                        FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL, XMLUtils.EMPTY_ATTRIBUTES);
                contentHandler.startElement(FormsConstants.I18N_NS, TEXT_EL,
                        FormsConstants.I18N_PREFIX_COLON + TEXT_EL, XMLUtils.EMPTY_ATTRIBUTES);
                contentHandler.characters(nullText.toCharArray(), 0, nullText.length());
                contentHandler.endElement(FormsConstants.I18N_NS, TEXT_EL,
                        FormsConstants.I18N_PREFIX_COLON + TEXT_EL);
                contentHandler.endElement(FormsConstants.INSTANCE_NS, LABEL_EL,
                        FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL);
            }
            contentHandler.endElement(FormsConstants.INSTANCE_NS, ITEM_EL,
                    FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL);
        }
        // Test if we have an apache enum class
        boolean apacheEnumDone = false;
        if (Enum.class.isAssignableFrom(clazz)) {
            Iterator iter = EnumUtils.iterator(clazz);
            if (iter != null) {
                apacheEnumDone = true;
                while (iter.hasNext()) {
                    Enum element = (Enum) iter.next();
                    String stringValue = clazz.getName() + "." + element.getName();
                    generateItem(contentHandler, stringValue);
                }
            }
        }
        // If it's not an apache enum or we didn't manage to read the enum list, then proceed with common method.
        if (!apacheEnumDone) {
            Field fields[] = clazz.getDeclaredFields();
            for (int i = 0; i < fields.length; ++i) {
                int mods = fields[i].getModifiers();
                if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)
                        && fields[i].get(null).getClass().equals(clazz)) {
                    String stringValue = clazz.getName() + "." + fields[i].getName();
                    generateItem(contentHandler, stringValue);
                }
            }
        }
        // End the selection-list
        contentHandler.endElement(FormsConstants.INSTANCE_NS, SELECTION_LIST_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + SELECTION_LIST_EL);
    } catch (Exception e) {
        throw new SAXException("Got exception trying to get enum's values", e);
    }
}

From source file:org.apache.cocoon.forms.datatype.EnumSelectionList.java

/**
 * Generates a single selection list item.
 * @param contentHandler The content handler we are streaming sax events to.
 * @param stringValue The string name of the item, composed by FQN and enum item.
 * @throws SAXException//from  w ww.  j a  v a2  s . com
 */
private void generateItem(ContentHandler contentHandler, String stringValue) throws SAXException {
    // Output this item
    AttributesImpl itemAttrs = new AttributesImpl();
    itemAttrs.addCDATAAttribute("value", stringValue);
    contentHandler.startElement(FormsConstants.INSTANCE_NS, ITEM_EL,
            FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL, itemAttrs);
    contentHandler.startElement(FormsConstants.INSTANCE_NS, LABEL_EL,
            FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL, XMLUtils.EMPTY_ATTRIBUTES);
    // TODO: make i18n element optional
    contentHandler.startElement(FormsConstants.I18N_NS, TEXT_EL, FormsConstants.I18N_PREFIX_COLON + TEXT_EL,
            XMLUtils.EMPTY_ATTRIBUTES);
    contentHandler.characters(stringValue.toCharArray(), 0, stringValue.length());
    contentHandler.endElement(FormsConstants.I18N_NS, TEXT_EL, FormsConstants.I18N_PREFIX_COLON + TEXT_EL);
    contentHandler.endElement(FormsConstants.INSTANCE_NS, LABEL_EL,
            FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL);
    contentHandler.endElement(FormsConstants.INSTANCE_NS, ITEM_EL,
            FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL);
}

From source file:org.apache.cocoon.forms.datatype.FlowJXPathSelectionList.java

public void generateSaxFragment(ContentHandler contentHandler, Locale locale) throws SAXException {
    JXPathContext ctx = null;/*from w  ww  .  j  a v a2  s  . c o  m*/
    Iterator iter = null;
    if (model == null) {
        Object flowData = FlowHelper.getContextObject(ContextHelper.getObjectModel(this.context));
        if (flowData == null) {
            throw new SAXException("No flow data to produce selection list");
        }

        // Move to the list location
        ctx = JXPathContext.newContext(flowData);

        // Iterate on all elements of the list
        iter = ctx.iteratePointers(this.listPath);
    } else {
        // Move to the list location
        ctx = JXPathContext.newContext(model);

        // Iterate on all elements of the list
        iter = ctx.iteratePointers(".");
    }

    // Start the selection-list
    contentHandler.startElement(FormsConstants.INSTANCE_NS, SELECTION_LIST_EL,
            FormsConstants.INSTANCE_PREFIX_COLON + SELECTION_LIST_EL, XMLUtils.EMPTY_ATTRIBUTES);
    if (this.nullable) {
        final AttributesImpl voidAttrs = new AttributesImpl();
        voidAttrs.addCDATAAttribute("value", "");
        contentHandler.startElement(FormsConstants.INSTANCE_NS, ITEM_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL, voidAttrs);

        if (this.nullText != null) {
            contentHandler.startElement(FormsConstants.INSTANCE_NS, LABEL_EL,
                    FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL, XMLUtils.EMPTY_ATTRIBUTES);

            if (this.nullTextIsI18nKey) {
                if ((this.i18nCatalog != null) && (this.i18nCatalog.trim().length() > 0)) {
                    new I18nMessage(this.nullText, this.i18nCatalog).toSAX(contentHandler);
                } else {
                    new I18nMessage(this.nullText).toSAX(contentHandler);
                }
            } else {
                contentHandler.characters(this.nullText.toCharArray(), 0, this.nullText.length());
            }

            contentHandler.endElement(FormsConstants.INSTANCE_NS, LABEL_EL,
                    FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL);
        }

        contentHandler.endElement(FormsConstants.INSTANCE_NS, ITEM_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL);
    }

    while (iter.hasNext()) {
        String stringValue = "";
        Object label = null;

        // Get a context on the current item
        Pointer ptr = (Pointer) iter.next();
        if (ptr.getValue() != null) {
            JXPathContext itemCtx = ctx.getRelativeContext(ptr);

            // Get the value as a string
            Object value = itemCtx.getValue(this.valuePath);

            // List may contain null value, and (per contract with convertors),
            // convertors are not invoked on nulls.
            if (value != null) {
                stringValue = this.datatype.convertToString(value, locale);
            }

            // Get the label (can be ommitted)
            itemCtx.setLenient(true);
            label = itemCtx.getValue(this.labelPath);
            if (label == null) {
                label = stringValue;
            }
        }

        // Output this item
        AttributesImpl itemAttrs = new AttributesImpl();
        itemAttrs.addCDATAAttribute("value", stringValue);
        contentHandler.startElement(FormsConstants.INSTANCE_NS, ITEM_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL, itemAttrs);
        if (label != null) {
            contentHandler.startElement(FormsConstants.INSTANCE_NS, LABEL_EL,
                    FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL, XMLUtils.EMPTY_ATTRIBUTES);
            if (label instanceof XMLizable) {
                ((XMLizable) label).toSAX(contentHandler);
            } else if (this.labelIsI18nKey) {
                String stringLabel = label.toString();

                if ((this.i18nCatalog != null) && (this.i18nCatalog.trim().length() > 0)) {
                    new I18nMessage(stringLabel, this.i18nCatalog).toSAX(contentHandler);
                } else {
                    new I18nMessage(stringLabel).toSAX(contentHandler);
                }
            } else {
                String stringLabel = label.toString();
                contentHandler.characters(stringLabel.toCharArray(), 0, stringLabel.length());
            }
            contentHandler.endElement(FormsConstants.INSTANCE_NS, LABEL_EL,
                    FormsConstants.INSTANCE_PREFIX_COLON + LABEL_EL);
        }
        contentHandler.endElement(FormsConstants.INSTANCE_NS, ITEM_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + ITEM_EL);
    }

    // End the selection-list
    contentHandler.endElement(FormsConstants.INSTANCE_NS, SELECTION_LIST_EL,
            FormsConstants.INSTANCE_PREFIX_COLON + SELECTION_LIST_EL);
}

From source file:org.apache.cocoon.forms.formmodel.BooleanField.java

public void generateItemSaxFragment(ContentHandler contentHandler, Locale locale) throws SAXException {
    // value element
    contentHandler.startElement(FormsConstants.INSTANCE_NS, VALUE_EL,
            FormsConstants.INSTANCE_PREFIX_COLON + VALUE_EL, XMLUtils.EMPTY_ATTRIBUTES);

    String stringValue = BooleanUtils.toBoolean(value) ? definition.getTrueParamValue() : "false";

    contentHandler.characters(stringValue.toCharArray(), 0, stringValue.length());
    contentHandler.endElement(FormsConstants.INSTANCE_NS, VALUE_EL,
            FormsConstants.INSTANCE_PREFIX_COLON + VALUE_EL);
    // validation message element: only present if the value is not valid
    if (validationError != null) {
        contentHandler.startElement(FormsConstants.INSTANCE_NS, VALIDATION_MSG_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + VALIDATION_MSG_EL, XMLUtils.EMPTY_ATTRIBUTES);
        validationError.generateSaxFragment(contentHandler);
        contentHandler.endElement(FormsConstants.INSTANCE_NS, VALIDATION_MSG_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + VALIDATION_MSG_EL);
    }/*from w  ww. j  av a2s.co m*/
}

From source file:org.apache.cocoon.forms.formmodel.Field.java

public void generateItemSaxFragment(ContentHandler contentHandler, Locale locale) throws SAXException {
    if (locale == null) {
        locale = getForm().getLocale();/*from   ww w. j a v  a 2 s  .  c o m*/
    }

    if (enteredValue != null || value != null) {
        contentHandler.startElement(FormsConstants.INSTANCE_NS, VALUE_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + VALUE_EL, XMLUtils.EMPTY_ATTRIBUTES);
        String stringValue;
        if (value != null) {
            stringValue = getDatatype().convertToString(value, locale);
        } else {
            stringValue = enteredValue;
        }
        contentHandler.characters(stringValue.toCharArray(), 0, stringValue.length());
        contentHandler.endElement(FormsConstants.INSTANCE_NS, VALUE_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + VALUE_EL);
    }

    // Suggested label, if any
    String suggestedLabel = getSuggestionLabel();
    if (suggestedLabel != null) {
        contentHandler.startElement(FormsConstants.INSTANCE_NS, "suggestion",
                FormsConstants.INSTANCE_PREFIX_COLON + "suggestion", XMLUtils.EMPTY_ATTRIBUTES);
        contentHandler.characters(suggestedLabel.toCharArray(), 0, suggestedLabel.length());
        contentHandler.endElement(FormsConstants.INSTANCE_NS, "suggestion",
                FormsConstants.INSTANCE_PREFIX_COLON + "suggestion");
    }

    // validation message element: only present if the value is not valid
    if (validationError != null
            && (this.valueState == VALUE_DISPLAY_VALIDATION || this.valueState == VALUE_DISPLAY_PARSE_ERROR)) {
        contentHandler.startElement(FormsConstants.INSTANCE_NS, VALIDATION_MSG_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + VALIDATION_MSG_EL, XMLUtils.EMPTY_ATTRIBUTES);
        validationError.generateSaxFragment(contentHandler);
        contentHandler.endElement(FormsConstants.INSTANCE_NS, VALIDATION_MSG_EL,
                FormsConstants.INSTANCE_PREFIX_COLON + VALIDATION_MSG_EL);
    }

    // generate selection list, if any
    if (selectionList != null) {
        selectionList.generateSaxFragment(contentHandler, locale);
    }

    // include some info about the datatype
    fieldDefinition.getDatatype().generateSaxFragment(contentHandler, locale);
}