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

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

Introduction

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

Prototype

public AttributesImpl() 

Source Link

Document

Construct a new, empty AttributesImpl object.

Usage

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 .  com
     * 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

private void doExtractResources(final ContentHandler handler, final AbstractAttributableTO attributableTO)
        throws SAXException {

    if (attributableTO.getResources().isEmpty()) {
        LOG.debug("No resources found for {}[{}]", attributableTO.getClass().getSimpleName(),
                attributableTO.getId());
    } else {/*w ww  . j  a va  2s  . c o  m*/
        AttributesImpl atts = new AttributesImpl();
        handler.startElement("", "", "resources", null);

        for (String resourceName : attributableTO.getResources()) {
            atts.clear();

            atts.addAttribute("", "", ATTR_NAME, XSD_STRING, resourceName);
            handler.startElement("", "", "resource", atts);
            handler.endElement("", "", "resource");
        }

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

From source file:de.tudarmstadt.ukp.csniper.webapp.analysis.uima.HTMLColorMarkerConsumer.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    // TODO notify user that the number of arguments is not equal
    // if (markedAnnotations.length != markerColors.length) {
    // throw new IllegalArgumentException(
    // "The amount of colors and annotation types have to be equal.");
    // }/*from  w  w  w  .j  a v a 2  s  .c o m*/
    typeCount = Math.min(markerColors.length, markedTypes.length);

    // build map: type->color
    colors = new HashMap<String, String>();
    for (int i = 0; i < typeCount; i++) {
        colors.put(markedTypes[i], markerColors[i]);
    }

    handler = new SAXContentHandler();
    try {
        // add stylesheet information
        handler.startDocument();
        AttributesImpl attr = new AttributesImpl();
        attr.addAttribute("", "", "id", "CDATA", outputClass);
        handler.startElement("", "div", "", attr);

        AttributesImpl style = new AttributesImpl();
        style.addAttribute("", "", "type", "CDATA", "text/css");
        handler.startElement("", "style", "", style);

        StringBuffer headerCss = new StringBuffer();
        headerCss.append("div#");
        headerCss.append(outputClass);
        headerCss.append(" span {");
        headerCss.append(" display:inline-block; padding:0 1 0 1;");
        headerCss.append(" margin:1px; border:solid 1px #FFFFFF; }");

        handler.characters(headerCss.toString().toCharArray(), 0, headerCss.toString().length());
        handler.endElement("", "style", "");
    } catch (SAXException e) {
        throw new ResourceInitializationException(e);
    }
}

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

/**
 * JavaScript constructor.//  www  .j av a  2  s  . co  m
 */
@JsxConstructor({ @WebBrowser(CHROME), @WebBrowser(FF), @WebBrowser(EDGE) })
public void jsConstructor() {
    final SgmlPage page = (SgmlPage) getWindow().getWebWindow().getEnclosedPage();
    final DomElement fake = HTMLParser.getFactory(HtmlImage.TAG_NAME).createElement(page, HtmlImage.TAG_NAME,
            new AttributesImpl());
    setDomNode(fake);
}

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

private void doExtractAttributes(final ContentHandler handler, final AbstractAttributableTO attributableTO,
        final Collection<String> attrs, final Collection<String> derAttrs, final Collection<String> virAttrs)
        throws SAXException {

    AttributesImpl atts = new AttributesImpl();
    if (!attrs.isEmpty()) {
        Map<String, AttributeTO> attrMap = attributableTO.getAttributeMap();

        handler.startElement("", "", "attributes", null);
        for (String attrName : attrs) {
            atts.clear();/*  ww  w. j av a 2s  . c  om*/

            atts.addAttribute("", "", ATTR_NAME, XSD_STRING, attrName);
            handler.startElement("", "", "attribute", atts);

            if (attrMap.containsKey(attrName)) {
                for (String value : attrMap.get(attrName).getValues()) {
                    handler.startElement("", "", "value", null);
                    handler.characters(value.toCharArray(), 0, value.length());
                    handler.endElement("", "", "value");
                }
            } else {
                LOG.debug("{} not found for {}[{}]", new Object[] { attrName,
                        attributableTO.getClass().getSimpleName(), attributableTO.getId() });
            }

            handler.endElement("", "", "attribute");
        }
        handler.endElement("", "", "attributes");
    }

    if (!derAttrs.isEmpty()) {
        Map<String, AttributeTO> derAttrMap = attributableTO.getDerivedAttributeMap();

        handler.startElement("", "", "derivedAttributes", null);
        for (String attrName : derAttrs) {
            atts.clear();

            atts.addAttribute("", "", ATTR_NAME, XSD_STRING, attrName);
            handler.startElement("", "", "derivedAttribute", atts);

            if (derAttrMap.containsKey(attrName)) {
                for (String value : derAttrMap.get(attrName).getValues()) {
                    handler.startElement("", "", "value", null);
                    handler.characters(value.toCharArray(), 0, value.length());
                    handler.endElement("", "", "value");
                }
            } else {
                LOG.debug("{} not found for {}[{}]", new Object[] { attrName,
                        attributableTO.getClass().getSimpleName(), attributableTO.getId() });
            }

            handler.endElement("", "", "derivedAttribute");
        }
        handler.endElement("", "", "derivedAttributes");
    }

    if (!virAttrs.isEmpty()) {
        Map<String, AttributeTO> virAttrMap = attributableTO.getVirtualAttributeMap();

        handler.startElement("", "", "virtualAttributes", null);
        for (String attrName : virAttrs) {
            atts.clear();

            atts.addAttribute("", "", ATTR_NAME, XSD_STRING, attrName);
            handler.startElement("", "", "virtualAttribute", atts);

            if (virAttrMap.containsKey(attrName)) {
                for (String value : virAttrMap.get(attrName).getValues()) {
                    handler.startElement("", "", "value", null);
                    handler.characters(value.toCharArray(), 0, value.length());
                    handler.endElement("", "", "value");
                }
            } else {
                LOG.debug("{} not found for {}[{}]", new Object[] { attrName,
                        attributableTO.getClass().getSimpleName(), attributableTO.getId() });
            }

            handler.endElement("", "", "virtualAttribute");
        }
        handler.endElement("", "", "virtualAttributes");
    }
}

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 w  w w. j  a v  a2s .  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 w ww .j a  va  2s . 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:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java

@Test
public void startElementTest() throws Exception {
    ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS);
    AttributesImpl attrs = new AttributesImpl();
    test.startDocument();//from   w w  w.j a  v a 2 s . c  o  m
    attrs.addAttribute("", "", "name", "", "Stream attr name"); // NON-NLS
    attrs.addAttribute("", "", "type", "", "java.lang.String"); // NON-NLS
    attrs.addAttribute("", "", "class", "", "Stream attr class"); // NON-NLS
    attrs.addAttribute("", "", "filter", "", "Stream attr filter"); // NON-NLS
    // attrs.addAttribute("", "", "rule", "", "Stream attr rule"); // NON-NLS
    // attrs.addAttribute("", "", "step", "", "Stream attr step"); // NON-NLS
    attrs.addAttribute("", "", "tnt4j-properties", "", "Stream attr tnt4j-properties"); // NON-NLS
    attrs.addAttribute("", "", "java-object", "", "Stream attr java-object"); // NON-NLS
    attrs.addAttribute("", "", "param", "", "Stream attr param"); // NON-NLS
    attrs.addAttribute("", "", "tags", "", "Stream attr tags"); // NON-NLS
    attrs.addAttribute("", "", "value", "", "Stream attr value"); // NON-NLS

    // test.startElement("TEST_URL", "TEST_LOCALNAME", "filter", attrs); // NON-NLS
    // test.startElement("TEST_URL", "TEST_LOCALNAME", "rule", attrs); // NON-NLS
    // test.startElement("TEST_URL", "TEST_LOCALNAME", "step", attrs); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "java-object", attrs); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "param", attrs); // NON-NLS
    test.startElement("TEST_URL", "TEST_LOCALNAME", "tnt-data-source", attrs); // NON-NLS
}

From source file:de.tudarmstadt.ukp.csniper.webapp.analysis.uima.HTMLColorMarkerConsumer.java

@Override
public void process(CAS cas) throws AnalysisEngineProcessException {
    List<AnnotationFS> filtered = new ArrayList<AnnotationFS>();
    Iterator<CAS> viewIterator = cas.getViewIterator();
    while (viewIterator.hasNext()) {
        CAS view = viewIterator.next();/*from   w  w w . ja va  2s  .  c  o m*/

        for (int i = 0; i < typeCount; i++) {
            try {
                Type type = CasUtil.getType(view, markedTypes[i]);
                filtered.addAll(CasUtil.select(view, type));
            } catch (IllegalArgumentException e) {
                // TODO at the moment, don't do anything when a type is not found
            }
        }

        try {
            for (AnnotationFS root : CasUtil.select(view, rootType)) {
                for (AnnotationFS token : CasUtil.selectCovered(view, tokenType, root)) {
                    for (AnnotationFS a : getAnnotationsBeginningAt(token.getBegin(), filtered)) {
                        String color = "background:" + colors.get(a.getType().getName()) + "; color:#DDDDDD;";
                        AttributesImpl attr = new AttributesImpl();
                        attr.addAttribute("", "", "style", "CDATA", color);
                        handler.startElement("", "span", "", attr);
                    }
                    char[] t = token.getCoveredText().toCharArray();
                    handler.characters(t, 0, t.length);
                    for (AnnotationFS a : getAnnotationsEndingAt(token.getEnd(), filtered)) {
                        handler.endElement("", "span", "");
                    }
                    handler.characters(new char[] { ' ' }, 0, 1);
                }
                // newline for each sentence
                handler.startElement("", "br", "", new AttributesImpl());
                handler.endElement("", "br", "");
            }
        } catch (SAXException e) {
            throw new AnalysisEngineProcessException(e);
        }
    }
}

From source file:de.tudarmstadt.ukp.lmf.writer.xml.LMFXmlWriter.java

/**
 * This method consumes a LMF Object and transforms it to XML. The method
 * iterates over all fields of a class and searches for the {@link AccessType} annotations.
 * Depending on the value of the annotation, the method reads the values of the objects
 * fields by invoking a getter or by directly accessing the field.
 * //from   w  w w . j a  va  2s  .c om
 * @param lmfObject An LMF Object for which an Element should be created
 * @param writeEndElement If TRUE the closing Tag for the XML-Element will be created
 *  
 * @throws IllegalAccessException when a direct access to a field of the class is for some reason not possible 
 * @throws IllegalArgumentException when a direct access to a field of the class is for some reason not possible 
 * @throws SAXException if writing to XML-file is for some reason not possible
 */
@SuppressWarnings("unchecked")
private void doTransform(Object lmfObject, boolean writeEndElement)
        throws IllegalArgumentException, IllegalAccessException, SAXException {

    Class<?> something = lmfObject.getClass();
    String elementName = something.getSimpleName();
    int hibernateSuffixIdx = elementName.indexOf("_$$");
    if (hibernateSuffixIdx > 0)
        elementName = elementName.substring(0, hibernateSuffixIdx);
    AttributesImpl atts = new AttributesImpl();
    List<Object> children = new ArrayList<Object>();

    // find all field, also the inherited ones 
    ArrayList<Field> fields = new ArrayList<Field>();
    fields.addAll(Arrays.asList(something.getDeclaredFields()));
    Class<?> superClass = something.getSuperclass();
    while (superClass != null) {
        fields.addAll(Arrays.asList(superClass.getDeclaredFields()));
        superClass = superClass.getSuperclass();
    }

    // Iterating over all fields
    for (Field field : fields) {
        String fieldName = field.getName().replace("_", "");
        Class<?> fieldClass = field.getType();
        VarType varType = field.getAnnotation(VarType.class);
        // No VarType-Annotation found for the field, then don't save to XML 
        if (varType == null)
            continue;

        EVarType type = varType.type();

        // VarType is NONE, don't save to XML
        if (type.equals(EVarType.NONE))
            continue;

        Object retObj = null;

        /*
         * Determine how to access the variable
         */
        AccessType accessType = field.getAnnotation(AccessType.class);
        if (accessType == null || accessType.equals(EAccessType.GETTER)) {
            // access using a canonical getter
            String setFieldName = fieldName;

            if (fieldName.startsWith("is")) // E.g. isHead --> setHead
                setFieldName = setFieldName.replaceFirst("is", "");

            // Get-Method for the field
            String getFuncName = setFieldName.substring(0, 1).toUpperCase() + setFieldName.substring(1);
            if (fieldClass.equals(Boolean.class)) {
                getFuncName = "is" + getFuncName;
            } else
                getFuncName = "get" + getFuncName;

            Method getMethod = null;
            try {
                getMethod = something.getMethod(getFuncName);
                retObj = getMethod.invoke(lmfObject); // Run the Get-Method
            } catch (Exception e) {
                logger.warn("There was an error on accessing the method " + getFuncName + " in " + elementName
                        + " class. Falling back to field access");
                field.setAccessible(true);
                retObj = field.get(lmfObject);
            }
        } else {
            // Directly read the value of the field
            field.setAccessible(true);
            retObj = field.get(lmfObject);
        }

        if (retObj != null) {
            if (type.equals(EVarType.ATTRIBUTE)) { // Save Attribute to the new element
                atts.addAttribute("", "", fieldName, "CDATA", retObj.toString());
            } else if (type.equals(EVarType.IDREF)) { // Save IDREFs as attribute of the new element
                atts.addAttribute("", "", fieldName, "CDATA", ((IHasID) retObj).getId());
            } else if (type.equals(EVarType.CHILD)) { // Transform children of the new element to XML
                children.add(retObj);
            } else if (type.equals(EVarType.CHILDREN) && writeEndElement) {
                for (Object obj : (Iterable<Object>) retObj) {
                    children.add(obj);
                }
            } else if (type.equals(EVarType.ATTRIBUTE_OPTIONAL)) {
                atts.addAttribute("", "", fieldName, "CDATA", retObj.toString());
            } else if (type.equals(EVarType.IDREFS)) {
                String attrValue = "";
                for (Object obj : (Iterable<Object>) retObj) {
                    attrValue += ((IHasID) obj).getId() + " ";
                }
                if (!attrValue.isEmpty())
                    atts.addAttribute("", "", fieldName, "CDATA",
                            attrValue.substring(0, attrValue.length() - 1));
            }
        } else { // Element is null, save only if it is a non-optional Attribute or IDREF
            if (type.equals(EVarType.ATTRIBUTE) || type.equals(EVarType.IDREF)) { // Save Attribute to the new element
                //atts.addAttribute("", "", fieldName, "CDATA", "NULL");
            }
        }
    }

    // Save the current element and its children
    th.startElement("", "", elementName, atts);
    for (Object child : children) {
        //System.out.println("CHILD: "+child.getClass().getSimpleName());
        doTransform(child, true);
    }
    if (writeEndElement)
        th.endElement("", "", elementName);
}