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.apache.fop.render.svg.SVGDataUrlImageHandler.java

/** {@inheritDoc} */
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException {
    SVGRenderingContext svgContext = (SVGRenderingContext) context;
    ImageRawStream raw = (ImageRawStream) image;
    InputStream in = raw.createInputStream();
    try {/*from w  w  w. jav  a  2 s . c om*/
        ContentHandler handler = svgContext.getContentHandler();
        String url = DataURLUtil.createDataURL(in, raw.getMimeType());
        AttributesImpl atts = new AttributesImpl();
        addAttribute(atts, IFConstants.XLINK_HREF, url);
        atts.addAttribute("", "x", "x", CDATA, Integer.toString(pos.x));
        atts.addAttribute("", "y", "y", CDATA, Integer.toString(pos.y));
        atts.addAttribute("", "width", "width", CDATA, Integer.toString(pos.width));
        atts.addAttribute("", "height", "height", CDATA, Integer.toString(pos.height));
        try {
            handler.startElement(NAMESPACE, "image", "image", atts);
            handler.endElement(NAMESPACE, "image", "image");
        } catch (SAXException e) {
            throw new IOException(e.getMessage());
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.syncope.core.logic.report.AuditReportlet.java

private void doExtractConf(final ContentHandler handler) throws SAXException {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
    jdbcTemplate.setMaxRows(conf.getSize());
    List<Map<String, Object>> rows = jdbcTemplate
            .queryForList("SELECT * FROM SYNCOPEAUDIT ORDER BY EVENT_DATE DESC");

    handler.startElement("", "", "events", null);
    AttributesImpl atts = new AttributesImpl();
    for (Map<String, Object> row : rows) {
        AuditEntry auditEntry = POJOHelper.deserialize(row.get("MESSAGE").toString(), AuditEntry.class);

        atts.clear();//from  w ww  .j av  a 2s .  c om
        if (StringUtils.isNotBlank(auditEntry.getWho())) {
            atts.addAttribute("", "", "who", ReportXMLConst.XSD_STRING, auditEntry.getWho());
        }
        handler.startElement("", "", "event", atts);

        atts.clear();
        if (StringUtils.isNotBlank(auditEntry.getLogger().getCategory())) {
            atts.addAttribute("", "", "category", ReportXMLConst.XSD_STRING,
                    auditEntry.getLogger().getCategory());
        }
        if (StringUtils.isNotBlank(auditEntry.getLogger().getSubcategory())) {
            atts.addAttribute("", "", "subcategory", ReportXMLConst.XSD_STRING,
                    auditEntry.getLogger().getSubcategory());
        }
        if (StringUtils.isNotBlank(auditEntry.getLogger().getEvent())) {
            atts.addAttribute("", "", "event", ReportXMLConst.XSD_STRING, auditEntry.getLogger().getEvent());
        }
        if (auditEntry.getLogger().getResult() != null) {
            atts.addAttribute("", "", "result", ReportXMLConst.XSD_STRING,
                    auditEntry.getLogger().getResult().name());
        }
        handler.startElement("", "", "logger", atts);
        handler.endElement("", "", "logger");

        if (auditEntry.getBefore() != null) {
            char[] before = ToStringBuilder
                    .reflectionToString(auditEntry.getBefore(), ToStringStyle.MULTI_LINE_STYLE).toCharArray();
            handler.startElement("", "", "before", null);
            handler.characters(before, 0, before.length);
            handler.endElement("", "", "before");
        }

        if (auditEntry.getInput() != null) {
            handler.startElement("", "", "inputs", null);
            for (Object inputObj : auditEntry.getInput()) {
                char[] input = ToStringBuilder.reflectionToString(inputObj, ToStringStyle.MULTI_LINE_STYLE)
                        .toCharArray();
                handler.startElement("", "", "input", null);
                handler.characters(input, 0, input.length);
                handler.endElement("", "", "input");
            }
            handler.endElement("", "", "inputs");
        }

        if (auditEntry.getOutput() != null) {
            char[] output = ToStringBuilder
                    .reflectionToString(auditEntry.getOutput(), ToStringStyle.MULTI_LINE_STYLE).toCharArray();
            handler.startElement("", "", "output", null);
            handler.characters(output, 0, output.length);
            handler.endElement("", "", "output");
        }

        handler.startElement("", "", "throwable", null);
        char[] throwable = row.get("THROWABLE").toString().toCharArray();
        handler.characters(throwable, 0, throwable.length);
        handler.endElement("", "", "throwable");

        handler.endElement("", "", "event");
    }
    handler.endElement("", "", "events");
}

From source file:org.apache.syncope.core.logic.report.GroupReportlet.java

private void doExtractResources(final ContentHandler handler, final AnyTO anyTO) throws SAXException {

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

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

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

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

From source file:org.apache.syncope.core.logic.report.GroupReportlet.java

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

    AttributesImpl atts = new AttributesImpl();
    if (!attrs.isEmpty()) {
        Map<String, AttrTO> attrMap = anyTO.getPlainAttrMap();

        handler.startElement("", "", "attributes", null);
        for (String attrName : attrs) {
            atts.clear();/*www  .  j a va  2 s  .c  o m*/

            atts.addAttribute("", "", ReportXMLConst.ATTR_NAME, ReportXMLConst.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 {}[{}]", attrName, anyTO.getClass().getSimpleName(),
                        anyTO.getKey());
            }

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

    if (!derAttrs.isEmpty()) {
        Map<String, AttrTO> derAttrMap = anyTO.getDerAttrMap();

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

            atts.addAttribute("", "", ReportXMLConst.ATTR_NAME, ReportXMLConst.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 {}[{}]", attrName, anyTO.getClass().getSimpleName(),
                        anyTO.getKey());
            }

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

    if (!virAttrs.isEmpty()) {
        Map<String, AttrTO> virAttrMap = anyTO.getVirAttrMap();

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

            atts.addAttribute("", "", ReportXMLConst.ATTR_NAME, ReportXMLConst.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 {}[{}]", attrName, anyTO.getClass().getSimpleName(),
                        anyTO.getKey());
            }

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

From source file:org.apache.syncope.core.logic.report.GroupReportlet.java

private void doExtract(final ContentHandler handler, final List<Group> groups) throws SAXException {
    AttributesImpl atts = new AttributesImpl();
    for (Group group : groups) {
        atts.clear();/*from  w w w  . ja  va2  s.  c  o m*/

        for (Feature feature : conf.getFeatures()) {
            String type = null;
            String value = null;
            switch (feature) {
            case key:
                type = ReportXMLConst.XSD_STRING;
                value = group.getKey();
                break;

            case name:
                type = ReportXMLConst.XSD_STRING;
                value = String.valueOf(group.getName());
                break;

            case groupOwner:
                type = ReportXMLConst.XSD_STRING;
                value = group.getGroupOwner().getKey();
                break;

            case userOwner:
                type = ReportXMLConst.XSD_STRING;
                value = group.getUserOwner().getKey();
                break;

            default:
            }

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

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

        // Using GroupTO for attribute values, since the conversion logic of
        // values to String is already encapsulated there
        GroupTO groupTO = groupDataBinder.getGroupTO(group, true);

        doExtractAttributes(handler, groupTO, conf.getPlainAttrs(), conf.getDerAttrs(), conf.getVirAttrs());

        // to get resources associated to a group
        if (conf.getFeatures().contains(Feature.resources)) {
            doExtractResources(handler, groupTO);
        }
        //to get users asscoiated to a group is preferred GroupDAO to GroupTO
        if (conf.getFeatures().contains(Feature.users)) {
            handler.startElement("", "", "users", null);

            for (UMembership memb : groupDAO.findUMemberships(group)) {
                atts.clear();

                atts.addAttribute("", "", "key", ReportXMLConst.XSD_STRING, memb.getLeftEnd().getKey());
                atts.addAttribute("", "", "username", ReportXMLConst.XSD_STRING,
                        String.valueOf(memb.getLeftEnd().getUsername()));

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

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

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

From source file:org.apache.syncope.core.logic.report.ReconciliationReportlet.java

private void doExtract(final ContentHandler handler, final Any<?> any, final Set<Missing> missing,
        final Set<Misaligned> misaligned) throws SAXException {

    AttributesImpl atts = new AttributesImpl();

    for (Feature feature : conf.getFeatures()) {
        String type = null;/*  ww  w  .  j ava2s .  c  o  m*/
        String value = null;
        switch (feature) {
        case key:
            type = ReportXMLConst.XSD_STRING;
            value = any.getKey();
            break;

        case username:
            if (any instanceof User) {
                type = ReportXMLConst.XSD_STRING;
                value = User.class.cast(any).getUsername();
            }
            break;

        case groupName:
            if (any instanceof Group) {
                type = ReportXMLConst.XSD_STRING;
                value = Group.class.cast(any).getName();
            }
            break;

        case workflowId:
            type = ReportXMLConst.XSD_STRING;
            value = any.getWorkflowId();
            break;

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

        case creationDate:
            type = ReportXMLConst.XSD_DATETIME;
            value = any.getCreationDate() == null ? StringUtils.EMPTY
                    : FormatUtils.format(any.getCreationDate());
            break;

        case lastLoginDate:
            if (any instanceof User) {
                type = ReportXMLConst.XSD_DATETIME;
                value = User.class.cast(any).getLastLoginDate() == null ? StringUtils.EMPTY
                        : FormatUtils.format(User.class.cast(any).getLastLoginDate());
            }
            break;

        case changePwdDate:
            if (any instanceof User) {
                type = ReportXMLConst.XSD_DATETIME;
                value = User.class.cast(any).getChangePwdDate() == null ? StringUtils.EMPTY
                        : FormatUtils.format(User.class.cast(any).getChangePwdDate());
            }
            break;

        case passwordHistorySize:
            if (any instanceof User) {
                type = ReportXMLConst.XSD_INT;
                value = String.valueOf(User.class.cast(any).getPasswordHistory().size());
            }
            break;

        case failedLoginCount:
            if (any instanceof User) {
                type = ReportXMLConst.XSD_INT;
                value = String.valueOf(User.class.cast(any).getFailedLogins());
            }
            break;

        default:
        }

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

    handler.startElement("", "", getAnyElementName(any.getType().getKind()), atts);

    for (Missing item : missing) {
        atts.clear();
        atts.addAttribute("", "", "resource", ReportXMLConst.XSD_STRING, item.getResource());
        atts.addAttribute("", "", "connObjectKeyValue", ReportXMLConst.XSD_STRING,
                item.getConnObjectKeyValue());

        handler.startElement("", "", "missing", atts);
        handler.endElement("", "", "missing");
    }
    for (Misaligned item : misaligned) {
        atts.clear();
        atts.addAttribute("", "", "resource", ReportXMLConst.XSD_STRING, item.getResource());
        atts.addAttribute("", "", "connObjectKeyValue", ReportXMLConst.XSD_STRING,
                item.getConnObjectKeyValue());
        atts.addAttribute("", "", ReportXMLConst.ATTR_NAME, ReportXMLConst.XSD_STRING, item.getName());

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

        handler.startElement("", "", "onSyncope", null);
        if (item.getOnSyncope() != null) {
            for (Object value : item.getOnSyncope()) {
                char[] asChars = value.toString().toCharArray();

                handler.startElement("", "", "value", null);
                handler.characters(asChars, 0, asChars.length);
                handler.endElement("", "", "value");
            }
        }
        handler.endElement("", "", "onSyncope");

        handler.startElement("", "", "onResource", null);
        if (item.getOnResource() != null) {
            for (Object value : item.getOnResource()) {
                char[] asChars = value.toString().toCharArray();

                handler.startElement("", "", "value", null);
                handler.characters(asChars, 0, asChars.length);
                handler.endElement("", "", "value");
            }
        }
        handler.endElement("", "", "onResource");

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

    handler.endElement("", "", getAnyElementName(any.getType().getKind()));
}

From source file:org.apache.syncope.core.logic.report.ReconciliationReportlet.java

@Override
protected void doExtract(final ReportletConf conf, final ContentHandler handler) throws SAXException {
    if (conf instanceof ReconciliationReportletConf) {
        this.conf = ReconciliationReportletConf.class.cast(conf);
    } else {//from   w  w  w  .  j av  a 2  s .c o m
        throw new ReportException(new IllegalArgumentException("Invalid configuration provided"));
    }

    AttributesImpl atts = new AttributesImpl();

    if (StringUtils.isBlank(this.conf.getUserMatchingCond())) {
        atts.addAttribute("", "", "total", ReportXMLConst.XSD_INT, String.valueOf(userDAO.count()));
        handler.startElement("", "", getAnyElementName(AnyTypeKind.USER) + "s", atts);

        doExtract(handler, userDAO.findAll());
    } else {
        SearchCond cond = SearchCondConverter.convert(this.conf.getUserMatchingCond());

        int count = searchDAO.count(SyncopeConstants.FULL_ADMIN_REALMS, cond, AnyTypeKind.USER);
        atts.addAttribute("", "", "total", ReportXMLConst.XSD_INT, String.valueOf(count));
        handler.startElement("", "", getAnyElementName(AnyTypeKind.USER) + "s", atts);

        doExtract(handler, count, cond, AnyTypeKind.USER);
    }
    handler.endElement("", "", getAnyElementName(AnyTypeKind.USER) + "s");

    atts.clear();
    if (StringUtils.isBlank(this.conf.getGroupMatchingCond())) {
        atts.addAttribute("", "", "total", ReportXMLConst.XSD_INT, String.valueOf(groupDAO.count()));
        handler.startElement("", "", getAnyElementName(AnyTypeKind.GROUP) + "s", atts);

        doExtract(handler, groupDAO.findAll());
    } else {
        SearchCond cond = SearchCondConverter.convert(this.conf.getUserMatchingCond());

        int count = searchDAO.count(SyncopeConstants.FULL_ADMIN_REALMS, cond, AnyTypeKind.GROUP);
        atts.addAttribute("", "", "total", ReportXMLConst.XSD_INT, String.valueOf(count));
        handler.startElement("", "", getAnyElementName(AnyTypeKind.GROUP) + "s", atts);

        doExtract(handler, count, cond, AnyTypeKind.GROUP);
    }
    handler.endElement("", "", getAnyElementName(AnyTypeKind.GROUP) + "s");

    for (AnyType anyType : anyTypeDAO.findAll()) {
        if (!anyType.equals(anyTypeDAO.findUser()) && !anyType.equals(anyTypeDAO.findGroup())) {
            AnyTypeCond anyTypeCond = new AnyTypeCond();
            anyTypeCond.setAnyTypeKey(anyType.getKey());
            SearchCond cond = StringUtils.isBlank(this.conf.getAnyObjectMatchingCond())
                    ? SearchCond.getLeafCond(anyTypeCond)
                    : SearchCond.getAndCond(SearchCond.getLeafCond(anyTypeCond),
                            SearchCondConverter.convert(this.conf.getAnyObjectMatchingCond()));

            int count = searchDAO.count(SyncopeConstants.FULL_ADMIN_REALMS, cond, AnyTypeKind.ANY_OBJECT);

            atts.clear();
            atts.addAttribute("", "", "type", ReportXMLConst.XSD_STRING, anyType.getKey());
            atts.addAttribute("", "", "total", ReportXMLConst.XSD_INT, String.valueOf(count));
            handler.startElement("", "", getAnyElementName(AnyTypeKind.ANY_OBJECT) + "s", atts);

            doExtract(handler, count, cond, AnyTypeKind.ANY_OBJECT);

            handler.endElement("", "", getAnyElementName(AnyTypeKind.ANY_OBJECT) + "s");
        }
    }
}

From source file:org.apache.syncope.core.logic.report.ReportJob.java

@SuppressWarnings("rawtypes")
@Override//  w  w  w.j a v a 2  s. c  o  m
public void execute(final JobExecutionContext context) throws JobExecutionException {
    Report report = reportDAO.find(reportKey);
    if (report == null) {
        throw new JobExecutionException("Report " + reportKey + " not found");
    }

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

    report.addExec(execution);
    report = reportDAO.save(report);

    // 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 tFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        handler = tFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, SyncopeConstants.DEFAULT_ENCODING);
        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);

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

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class<Reportlet> reportletClass = dataBinder
                    .findReportletClassHavingConfClass(reportletConf.getClass());
            if (reportletClass != null) {
                Reportlet<ReportletConf> autowired = (Reportlet<ReportletConf>) ApplicationContextProvider
                        .getBeanFactory()
                        .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;
                    reportExecutionMessage.append(ExceptionUtils2.getFullStackTrace(t))
                            .append("\n==================\n");
                }
            }
        }

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

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {
            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);
        reportExecutionMessage.append(ExceptionUtils2.getFullStackTrace(e));

        throw new JobExecutionException(e, true);
    } finally {
        try {
            zos.closeEntry();
            IOUtils.closeQuietly(zos);
            IOUtils.closeQuietly(baos);
        } 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:org.apache.syncope.core.logic.report.ReportJobDelegate.java

@Transactional
public void execute(final String reportKey) throws JobExecutionException {
    Report report = reportDAO.find(reportKey);
    if (report == null) {
        throw new JobExecutionException("Report " + reportKey + " not found");
    }/*from   ww w .  j  a  v  a 2  s .  c  om*/

    if (!report.isActive()) {
        LOG.info("Report {} not active, aborting...", reportKey);
        return;
    }

    // 1. create execution
    ReportExec execution = entityFactory.newEntity(ReportExec.class);
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStart(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    report.add(execution);
    report = reportDAO.save(report);

    // 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 tFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        tFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
        handler = tFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, SyncopeConstants.DEFAULT_ENCODING);
        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);

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

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class<? extends Reportlet> reportletClass = implementationLookup
                    .getReportletClass(reportletConf.getClass());
            if (reportletClass == null) {
                LOG.warn("Could not find matching reportlet for {}", reportletConf.getClass());
            } else {
                // fetch (or create) reportlet
                Reportlet reportlet;
                if (ApplicationContextProvider.getBeanFactory().containsSingleton(reportletClass.getName())) {
                    reportlet = (Reportlet) ApplicationContextProvider.getBeanFactory()
                            .getSingleton(reportletClass.getName());
                } else {
                    reportlet = (Reportlet) ApplicationContextProvider.getBeanFactory()
                            .createBean(reportletClass, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                    ApplicationContextProvider.getBeanFactory().registerSingleton(reportletClass.getName(),
                            reportlet);
                }

                // invoke reportlet
                try {
                    reportlet.extract(reportletConf, handler);
                } catch (Throwable t) {
                    LOG.error("While executing reportlet {} for report {}", reportlet, reportKey, t);

                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable effective = t instanceof ReportException ? t.getCause() : t;
                    reportExecutionMessage.append(ExceptionUtils2.getFullStackTrace(effective))
                            .append("\n==================\n");
                }
            }
        }

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

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {
            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);
        reportExecutionMessage.append(ExceptionUtils2.getFullStackTrace(e));

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

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

From source file:org.apache.syncope.core.logic.report.RoleReportlet.java

private void doExtractResources(final ContentHandler handler, final AbstractSubjectTO subjectTO)
        throws SAXException {

    if (subjectTO.getResources().isEmpty()) {
        LOG.debug("No resources found for {}[{}]", subjectTO.getClass().getSimpleName(), subjectTO.getKey());
    } else {//  www  .  jav a  2s  .  c  o m
        AttributesImpl atts = new AttributesImpl();
        handler.startElement("", "", "resources", null);

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

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

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