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.syncope.core.logic.report.RoleReportlet.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, AttrTO> attrMap = attributableTO.getPlainAttrMap();

        handler.startElement("", "", "attributes", null);
        for (String attrName : attrs) {
            atts.clear();/*  w w w.  java 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, attributableTO.getClass().getSimpleName(),
                        attributableTO.getKey());
            }

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

    if (!derAttrs.isEmpty()) {
        Map<String, AttrTO> derAttrMap = attributableTO.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, attributableTO.getClass().getSimpleName(),
                        attributableTO.getKey());
            }

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

    if (!virAttrs.isEmpty()) {
        Map<String, AttrTO> virAttrMap = attributableTO.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, attributableTO.getClass().getSimpleName(),
                        attributableTO.getKey());
            }

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

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

private void doExtract(final ContentHandler handler, final List<Role> roles)
        throws SAXException, ReportException {

    AttributesImpl atts = new AttributesImpl();
    for (Role role : roles) {
        atts.clear();//from   w  w  w.  ja v a  2 s.c  o m

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

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

            case roleOwner:
                type = ReportXMLConst.XSD_LONG;
                value = String.valueOf(role.getRoleOwner());
                break;

            case userOwner:
                type = ReportXMLConst.XSD_LONG;
                value = String.valueOf(role.getUserOwner());
                break;

            default:
            }

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

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

        // Using RoleTO for attribute values, since the conversion logic of
        // values to String is already encapsulated there
        RoleTO roleTO = roleDataBinder.getRoleTO(role);

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

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

            for (String ent : roleTO.getEntitlements()) {
                atts.clear();

                atts.addAttribute("", "", "id", ReportXMLConst.XSD_STRING, String.valueOf(ent));

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

            handler.endElement("", "", "entitlements");
        }
        // to get resources associated to a role
        if (conf.getFeatures().contains(Feature.resources)) {
            doExtractResources(handler, roleTO);
        }
        //to get users asscoiated to a role is preferred RoleDAO to RoleTO
        if (conf.getFeatures().contains(Feature.users)) {
            handler.startElement("", "", "users", null);

            for (Membership memb : roleDAO.findMemberships(role)) {
                atts.clear();

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

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

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

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

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

private void doExtract(final ContentHandler handler, final List<User> users) throws SAXException {
    AttributesImpl atts = new AttributesImpl();
    for (User user : users) {
        atts.clear();/*  ww  w  .j  av  a  2s.c om*/

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

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

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

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

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

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

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

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

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

            default:
            }

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

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

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

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

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

            for (RelationshipTO rel : userTO.getRelationships()) {
                atts.clear();

                atts.addAttribute("", "", "anyObjectKey", ReportXMLConst.XSD_STRING, rel.getRightKey());
                handler.startElement("", "", "relationship", atts);

                if (conf.getFeatures().contains(Feature.resources)) {
                    for (URelationship actualRel : user.getRelationships(rel.getRightKey())) {
                        doExtractResources(handler,
                                anyObjectDataBinder.getAnyObjectTO(actualRel.getRightEnd(), true));
                    }
                }

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

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

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

                atts.addAttribute("", "", "groupKey", ReportXMLConst.XSD_STRING, memb.getRightKey());
                atts.addAttribute("", "", "groupName", ReportXMLConst.XSD_STRING, memb.getGroupName());
                handler.startElement("", "", "membership", atts);

                if (conf.getFeatures().contains(Feature.resources)) {
                    UMembership actualMemb = user.getMembership(memb.getRightKey());
                    if (actualMemb == null) {
                        LOG.warn("Unexpected: cannot find membership for group {} for user {}",
                                memb.getRightKey(), user);
                    } else {
                        doExtractResources(handler, groupDataBinder.getGroupTO(actualMemb.getRightEnd(), true));
                    }
                }

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

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

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

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

From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentExporter.java

private void doExportTable(final TransformerHandler handler, final String dbSchema, final Connection conn,
        final String tableName, final String whereClause) throws SQLException, SAXException {

    LOG.debug("Export table {}", tableName);

    AttributesImpl attrs = new AttributesImpl();

    PreparedStatement stmt = null;
    ResultSet rs = null;//from   w ww  .ja va  2s.c om
    try {
        StringBuilder orderBy = new StringBuilder();

        DatabaseMetaData meta = conn.getMetaData();

        // ------------------------------------
        // retrieve foreign keys (linked to the same table) to perform an ordered select
        ResultSet pkeyRS = null;
        try {
            pkeyRS = meta.getImportedKeys(conn.getCatalog(), dbSchema, tableName);
            while (pkeyRS.next()) {
                if (tableName.equals(pkeyRS.getString("PKTABLE_NAME"))) {
                    String columnName = pkeyRS.getString("FKCOLUMN_NAME");
                    if (columnName != null) {
                        if (orderBy.length() > 0) {
                            orderBy.append(",");
                        }

                        orderBy.append(columnName);
                    }
                }
            }
        } finally {
            if (pkeyRS != null) {
                try {
                    pkeyRS.close();
                } catch (SQLException e) {
                    LOG.error("While closing result set", e);
                }
            }
        }

        // retrieve primary keys to perform an ordered select
        try {
            pkeyRS = meta.getPrimaryKeys(null, null, tableName);
            while (pkeyRS.next()) {
                String columnName = pkeyRS.getString("COLUMN_NAME");
                if (columnName != null) {
                    if (orderBy.length() > 0) {
                        orderBy.append(",");
                    }

                    orderBy.append(columnName);
                }
            }
        } finally {
            if (pkeyRS != null) {
                try {
                    pkeyRS.close();
                } catch (SQLException e) {
                    LOG.error("While closing result set", e);
                }
            }
        }

        // ------------------------------------
        StringBuilder query = new StringBuilder();
        query.append("SELECT * FROM ").append(tableName).append(" a");
        if (StringUtils.isNotBlank(whereClause)) {
            query.append(" WHERE ").append(whereClause);
        }
        if (orderBy.length() > 0) {
            query.append(" ORDER BY ").append(orderBy);
        }
        stmt = conn.prepareStatement(query.toString());

        rs = stmt.executeQuery();
        while (rs.next()) {
            attrs.clear();

            final ResultSetMetaData rsMeta = rs.getMetaData();
            for (int i = 0; i < rsMeta.getColumnCount(); i++) {
                final String columnName = rsMeta.getColumnName(i + 1);
                final Integer columnType = rsMeta.getColumnType(i + 1);

                // Retrieve value taking care of binary values.
                String value = getValues(rs, columnName, columnType);
                if (value != null && (!COLUMNS_TO_BE_NULLIFIED.containsKey(tableName)
                        || !COLUMNS_TO_BE_NULLIFIED.get(tableName).contains(columnName))) {

                    attrs.addAttribute("", "", columnName, "CDATA", value);
                }
            }

            handler.startElement("", "", tableName, attrs);
            handler.endElement("", "", tableName);

            LOG.debug("Add record {}", attrs);
        }
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
    }
}

From source file:org.apache.syncope.core.provisioning.java.job.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  ava  2  s.co  m*/
        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.JSON_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.JSON_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.JSON_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.provisioning.java.job.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 = EntityTOUtils.buildAttrMap(anyTO.getPlainAttrs());

        handler.startElement("", "", "attributes", null);
        for (String attrName : attrs) {
            atts.clear();/*from w  w w  . j  a  v a 2s. 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 = EntityTOUtils.buildAttrMap(anyTO.getDerAttrs());

        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 = EntityTOUtils.buildAttrMap(anyTO.getVirAttrs());

        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.provisioning.java.job.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 {/* w  w w .  j  a  va2s .  co 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);

        for (int page = 1; page <= (userDAO.count() / AnyDAO.DEFAULT_PAGE_SIZE) + 1; page++) {
            doExtract(handler, userDAO.findAll(page, AnyDAO.DEFAULT_PAGE_SIZE));
        }
    } 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);

        for (int page = 1; page <= (groupDAO.count() / AnyDAO.DEFAULT_PAGE_SIZE) + 1; page++) {
            doExtract(handler, groupDAO.findAll(page, AnyDAO.DEFAULT_PAGE_SIZE));
        }
    } 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.provisioning.java.job.report.UserReportlet.java

private void doExtract(final ContentHandler handler, final List<User> users) throws SAXException {
    AttributesImpl atts = new AttributesImpl();
    for (User user : users) {
        atts.clear();//  w  w w. ja  va  2 s .c  o  m

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

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

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

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

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

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

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

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

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

            default:
            }

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

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

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

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

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

            for (RelationshipTO rel : userTO.getRelationships()) {
                atts.clear();

                atts.addAttribute("", "", "anyObjectKey", ReportXMLConst.XSD_STRING, rel.getOtherEndKey());
                handler.startElement("", "", "relationship", atts);

                if (conf.getFeatures().contains(Feature.resources)) {
                    for (URelationship actualRel : user.getRelationships(rel.getOtherEndKey())) {
                        doExtractResources(handler,
                                anyObjectDataBinder.getAnyObjectTO(actualRel.getRightEnd(), true));
                    }
                }

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

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

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

                atts.addAttribute("", "", "groupKey", ReportXMLConst.XSD_STRING, memb.getGroupKey());
                atts.addAttribute("", "", "groupName", ReportXMLConst.XSD_STRING, memb.getGroupName());
                handler.startElement("", "", "membership", atts);

                if (conf.getFeatures().contains(Feature.resources)) {
                    UMembership actualMemb = user.getMembership(memb.getGroupKey()).orElse(null);
                    if (actualMemb == null) {
                        LOG.warn("Unexpected: cannot find membership for group {} for user {}",
                                memb.getGroupKey(), user);
                    } else {
                        doExtractResources(handler, groupDataBinder.getGroupTO(actualMemb.getRightEnd(), true));
                    }
                }

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

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

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

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

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

@SuppressWarnings("rawtypes")
@Override/*from   ww  w .ja  v  a  2  s  .c  om*/
public void execute(final JobExecutionContext context) throws JobExecutionException {
    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }

    // 1. create execution
    ReportExec execution = new ReportExec();
    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();
    StringWriter exceptionWriter = new StringWriter();
    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 autowired = (Reportlet) 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(ExceptionUtil.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(ExceptionUtil.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.util.ContentExporter.java

private void doExportTable(final TransformerHandler handler, final Connection conn, final String tableName,
        final String whereClause) throws SQLException, SAXException {

    LOG.debug("Export table {}", tableName);

    AttributesImpl attrs = new AttributesImpl();

    PreparedStatement stmt = null;
    ResultSet rs = null;//www .j  a  v  a2 s . c om
    ResultSet pkeyRS = null;
    try {
        // ------------------------------------
        // retrieve primary keys to perform an ordered select

        final DatabaseMetaData meta = conn.getMetaData();
        pkeyRS = meta.getPrimaryKeys(null, null, tableName);

        final StringBuilder orderBy = new StringBuilder();

        while (pkeyRS.next()) {
            final String columnName = pkeyRS.getString("COLUMN_NAME");
            if (columnName != null) {
                if (orderBy.length() > 0) {
                    orderBy.append(",");
                }

                orderBy.append(columnName);
            }
        }

        // ------------------------------------
        StringBuilder query = new StringBuilder();
        query.append("SELECT * FROM ").append(tableName).append(" a");
        if (StringUtils.isNotBlank(whereClause)) {
            query.append(" WHERE ").append(whereClause);
        }
        if (orderBy.length() > 0) {
            query.append(" ORDER BY ").append(orderBy);
        }
        stmt = conn.prepareStatement(query.toString());

        rs = stmt.executeQuery();
        while (rs.next()) {
            attrs.clear();

            final ResultSetMetaData rsMeta = rs.getMetaData();
            for (int i = 0; i < rsMeta.getColumnCount(); i++) {
                final String columnName = rsMeta.getColumnName(i + 1);
                final Integer columnType = rsMeta.getColumnType(i + 1);

                // Retrieve value taking care of binary values.
                String value = getValues(rs, columnName, columnType);
                if (value != null && (!COLUMNS_TO_BE_NULLIFIED.containsKey(tableName)
                        || !COLUMNS_TO_BE_NULLIFIED.get(tableName).contains(columnName))) {

                    attrs.addAttribute("", "", columnName, "CDATA", value);
                }
            }

            handler.startElement("", "", tableName, attrs);
            handler.endElement("", "", tableName);

            LOG.debug("Add record {}", attrs);
        }
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (pkeyRS != null) {
            try {
                pkeyRS.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
    }
}