Example usage for org.xml.sax.helpers AttributesImpl addAttribute

List of usage examples for org.xml.sax.helpers AttributesImpl addAttribute

Introduction

In this page you can find the example usage for org.xml.sax.helpers AttributesImpl addAttribute.

Prototype

public void addAttribute(String uri, String localName, String qName, String type, String value) 

Source Link

Document

Add an attribute to the end of the list.

Usage

From source file:org.syncope.core.scheduling.ReportJob.java

@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {

    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }//from   ww  w  .  j a v a  2 s .  c  o  m

    // 1. create execution
    ReportExec execution = new ReportExec();
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStartDate(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    // 2. define a SAX handler for generating result as XML
    TransformerHandler handler;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    try {
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        handler = transformerFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        // a single ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(report.getName()));

        // streaming SAX handler in a compressed byte array stream
        handler.setResult(new StreamResult(zos));
    } catch (Exception e) {
        throw new JobExecutionException("While configuring for SAX generation", e, true);
    }

    execution.setStatus(ReportExecStatus.RUNNING);
    execution = reportExecDAO.save(execution);

    ConfigurableListableBeanFactory beanFactory = ApplicationContextManager.getApplicationContext()
            .getBeanFactory();

    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    StringWriter exceptionWriter = new StringWriter();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ATTR_NAME, XSD_STRING, report.getName());
        handler.startElement("", "", ELEMENT_REPORT, atts);

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class reportletClass = null;
            try {
                reportletClass = Class.forName(reportletConf.getReportletClassName());
            } catch (ClassNotFoundException e) {
                LOG.error("Reportlet class not found: {}", reportletConf.getReportletClassName(), e);

            }

            if (reportletClass != null) {
                Reportlet autowired = (Reportlet) beanFactory.createBean(reportletClass,
                        AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                autowired.setConf(reportletConf);

                // invoke reportlet
                try {
                    autowired.extract(handler);
                } catch (Exception e) {
                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable t = e instanceof ReportException ? e.getCause() : e;
                    exceptionWriter.write(t.getMessage() + "\n\n");
                    t.printStackTrace(new PrintWriter(exceptionWriter));
                    reportExecutionMessage.append(exceptionWriter.toString()).append("\n==================\n");
                }
            }
        }

        // report footer
        handler.endElement("", "", ELEMENT_REPORT);
        handler.endDocument();

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {

            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);

        exceptionWriter.write(e.getMessage() + "\n\n");
        e.printStackTrace(new PrintWriter(exceptionWriter));
        reportExecutionMessage.append(exceptionWriter.toString());

        throw new JobExecutionException(e, true);
    } finally {
        try {
            zos.closeEntry();
            zos.close();
            baos.close();
        } catch (IOException e) {
            LOG.error("While closing StreamResult's backend", e);
        }

        execution.setExecResult(baos.toByteArray());
        execution.setMessage(reportExecutionMessage.toString());
        execution.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:hd3gtv.mydmam.db.BackupDbElasticsearch.java

public boolean onFoundHit(SearchHit hit) {
    try {//from www.ja v  a 2  s .  c o  m
        AttributesImpl atts = new AttributesImpl();

        atts.addAttribute("", "", "name", "CDATA", hit.getId());
        atts.addAttribute("", "", "type", "CDATA", hit.getType());
        atts.addAttribute("", "", "version", "CDATA", Long.toString(hit.getVersion()));

        content.startElement("", "", "key", atts);
        if (BackupDb.mode_debug) {
            Object source = gson.fromJson(hit.getSourceAsString(), Object.class);
            serializer.comment(gson.toJson(source));
        }

        String value = new String(quotedprintablecodec.encode(hit.getSourceAsString()));
        content.characters(value.toCharArray(), 0, value.length());

        content.endElement("", "", "key");

        count++;
        return true;
    } catch (Exception e) {
        Log2.log.error("Can't write to XML document", e);
        return false;
    }
}

From source file:hd3gtv.mydmam.db.BackupDbCassandra.java

public void onFoundRow(Row<String, String> row) throws Exception {
    AttributesImpl atts = new AttributesImpl();

    atts.addAttribute("", "", "name", "CDATA", row.getKey());
    content.startElement("", "", "key", atts);

    columnlist = row.getColumns();//from  w  w  w . jav a  2 s. c o m
    String columnvalue = null;
    for (int poscol = 0; poscol < columnlist.size(); poscol++) {
        column = columnlist.getColumnByIndex(poscol);
        atts.clear();
        atts.addAttribute("", "", "name", "CDATA", column.getName());
        atts.addAttribute("", "", "at", "CDATA", String.valueOf(column.getTimestamp() / 1000));
        atts.addAttribute("", "", "ttl", "CDATA", String.valueOf(column.getTtl()));

        columnvalue = new String(quotedprintablecodec.encode(column.getByteArrayValue()));

        if (BackupDb.mode_debug) {
            atts.addAttribute("", "", "at_date", "CDATA", (new Date(column.getTimestamp() / 1000)).toString());
            if (column.getStringValue().equals(columnvalue) == false) {
                atts.addAttribute("", "", "hex_value", "CDATA",
                        MyDMAM.byteToString(column.getByteArrayValue()));
            }
        }

        content.startElement("", "", "col", atts);
        content.characters(columnvalue.toCharArray(), 0, columnvalue.length());
        content.endElement("", "", column.getName());
    }

    content.endElement("", "", "key");
    count++;
}

From source file:hd3gtv.mydmam.db.BackupDbCassandra.java

BackupDbCassandra(Keyspace keyspace, ColumnFamilyDefinition cfd, File outfile) throws Exception {
    quotedprintablecodec = new QuotedPrintableCodec("UTF-8");
    String cfname = cfd.getName();

    /**/*from   w  w  w  .ja  v  a 2 s  . c o  m*/
     * Preparation
     */
    fileoutputstream = new FileOutputStream(outfile);

    OutputFormat of = new OutputFormat();
    of.setMethod("xml");
    of.setEncoding("UTF-8");
    of.setVersion("1.0");
    of.setIndenting(BackupDb.mode_debug);
    if (BackupDb.mode_debug) {
        of.setIndent(2);
    }

    XMLSerializer serializer = new XMLSerializer(fileoutputstream, of);
    content = serializer.asContentHandler();
    content.startDocument();

    /**
     * Headers
     */
    AttributesImpl atts = new AttributesImpl();
    atts.addAttribute("", "", "keyspace", "CDATA", CassandraDb.default_keyspacename);
    atts.addAttribute("", "", "name", "CDATA", cfname);
    atts.addAttribute("", "", "created", "CDATA", String.valueOf(System.currentTimeMillis()));
    if (BackupDb.mode_debug) {
        atts.addAttribute("", "", "created_date", "CDATA", (new Date()).toString());
    }
    content.startElement("", "", "columnfamily", atts);

    /**
     * Import description
     */
    List<ColumnDefinition> l_cd = cfd.getColumnDefinitionList();
    for (int pos = 0; pos < l_cd.size(); pos++) {
        atts.clear();
        atts.addAttribute("", "", "name", "CDATA", l_cd.get(pos).getName());
        atts.addAttribute("", "", "indexname", "CDATA", l_cd.get(pos).getIndexName());
        atts.addAttribute("", "", "validationclass", "CDATA", l_cd.get(pos).getValidationClass());
        content.startElement("", "", "coldef", atts);
        content.endElement("", "", "coldef");
    }
}

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

@Override
@Transactional(readOnly = true)// www .ja  v a 2 s  .co m
public void extract(final ContentHandler handler) throws SAXException, ReportException {

    if (getConf() == null || !(getConf() instanceof UserReportletConf)) {
        throw new ReportException(new IllegalArgumentException(
                "Expected " + UserReportletConf.class.getName() + ", got " + getConf()));
    }

    UserReportletConf conf = (UserReportletConf) getConf();

    AttributesImpl atts = new AttributesImpl();
    atts.addAttribute("", "", ATTR_NAME, XSD_STRING, getConf().getName());
    atts.addAttribute("", "", ATTR_CLASS, XSD_STRING, getClass().getName());
    handler.startElement("", "", ELEMENT_REPORTLET, atts);

    for (int i = 1; i <= (count(conf) / PAGE_SIZE) + 1; i++) {
        doExtract(handler, conf, getPagedUsers(conf, i));
    }

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

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLOptionElement.java

/**
 * JavaScript constructor./* w  w w . j  a  va  2  s  . c  o m*/
 * @param newText the text
 * @param newValue the value
 * @param defaultSelected Whether the option is initially selected
 * @param selected the current selection state of the option
 */
@JsxConstructor({ @WebBrowser(CHROME), @WebBrowser(FF), @WebBrowser(EDGE) })
public void jsConstructor(final String newText, final String newValue, final boolean defaultSelected,
        final boolean selected) {
    final HtmlPage page = (HtmlPage) getWindow().getWebWindow().getEnclosedPage();
    AttributesImpl attributes = null;
    if (defaultSelected) {
        attributes = new AttributesImpl();
        attributes.addAttribute(null, "selected", "selected", null, "selected");
    }

    final HtmlOption htmlOption = (HtmlOption) HTMLParser.getFactory(HtmlOption.TAG_NAME).createElement(page,
            HtmlOption.TAG_NAME, attributes);
    htmlOption.setSelected(selected);
    setDomNode(htmlOption);

    if (!"undefined".equals(newText)) {
        htmlOption.appendChild(new DomText(page, newText));
        htmlOption.setLabelAttribute(newText);
    }
    if (!"undefined".equals(newValue)) {
        htmlOption.setValueAttribute(newValue);
    }
}

From source file:net.javacrumbs.json2xml.JsonSaxAdapter.java

protected Attributes getTypeAttributes() {
    if (addTypeAttributes) {
        String currentTokenType = getCurrentTokenType();
        if (currentTokenType != null) {
            AttributesImpl attributes = new AttributesImpl();
            attributes.addAttribute("", "type", "type", "string", currentTokenType);
            return attributes;
        } else {//from   w  w w .j  ava2 s  . c om
            return EMPTY_ATTRIBUTES;
        }
    } else {
        return EMPTY_ATTRIBUTES;
    }
}

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  v  a 2 s . c o 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:com.mirth.connect.model.converters.NCPDPReader.java

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

    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:hd3gtv.mydmam.db.BackupDbElasticsearch.java

BackupDbElasticsearch(File outfile, String index_name,
        ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mapping,
        ImmutableOpenMap<String, Settings> settings) throws Exception {
    quotedprintablecodec = new QuotedPrintableCodec("UTF-8");
    GsonBuilder g_builder = new GsonBuilder();
    g_builder.disableHtmlEscaping();//from  ww w .j  ava2 s .com
    if (BackupDb.mode_debug) {
        g_builder.setPrettyPrinting();
    }
    gson = g_builder.create();

    /**
     * Preparation
     */
    fileoutputstream = new FileOutputStream(outfile);

    OutputFormat of = new OutputFormat();
    of.setMethod("xml");
    of.setEncoding("UTF-8");
    of.setVersion("1.0");
    of.setIndenting(BackupDb.mode_debug);
    if (BackupDb.mode_debug) {
        of.setIndent(2);
    }

    serializer = new XMLSerializer(fileoutputstream, of);
    content = serializer.asContentHandler();
    content.startDocument();

    /**
     * Headers
     */
    AttributesImpl atts = new AttributesImpl();
    atts.addAttribute("", "", "name", "CDATA", index_name);
    atts.addAttribute("", "", "created", "CDATA", String.valueOf(System.currentTimeMillis()));
    if (BackupDb.mode_debug) {
        atts.addAttribute("", "", "created_date", "CDATA", (new Date()).toString());
    }
    content.startElement("", "", "index", atts);

    /**
     * Import configuration
     * ES Mapping
     */
    String jo_mapping;
    ImmutableOpenMap<String, MappingMetaData> mapping_value;
    for (ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>> mapping_cursor : mapping) {
        mapping_value = mapping_cursor.value;
        for (ObjectObjectCursor<String, MappingMetaData> mapping_value_cursor : mapping_value) {
            atts.clear();
            atts.addAttribute("", "", "name", "CDATA", mapping_value_cursor.key);

            content.startElement("", "", "mapping", atts);

            jo_mapping = gson.toJson(mapping_value_cursor.value.getSourceAsMap());

            if (BackupDb.mode_debug) {
                serializer.comment(jo_mapping);
            }

            jo_mapping = new String(quotedprintablecodec.encode(jo_mapping));
            content.characters(jo_mapping.toCharArray(), 0, jo_mapping.length());

            content.endElement("", "", "mapping");
        }
    }

    /**
     * ES settings
     */
    for (ObjectObjectCursor<String, Settings> settings_cursor : settings) {
        atts.clear();
        content.startElement("", "", "settings", atts);

        jo_mapping = gson.toJson(settings_cursor.value.getAsMap());

        if (BackupDb.mode_debug) {
            serializer.comment(jo_mapping);
        }

        jo_mapping = new String(quotedprintablecodec.encode(jo_mapping));
        content.characters(jo_mapping.toCharArray(), 0, jo_mapping.length());

        content.endElement("", "", "settings");
    }
}