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:org.syncope.core.report.UserReportlet.java

private void doExtract(final ContentHandler handler, final UserReportletConf conf,
        final List<SyncopeUser> users) throws SAXException, ReportException {

    AttributesImpl atts = new AttributesImpl();
    for (SyncopeUser user : users) {
        atts.clear();//from   w ww . j a v a  2s .co m

        for (Feature feature : conf.getFeatures()) {
            String type = null;
            String value = null;
            switch (feature) {
            case id:
                type = XSD_LONG;
                value = String.valueOf(user.getId());
                break;

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

            case workflowId:
                type = XSD_LONG;
                value = String.valueOf(user.getWorkflowId());
                break;

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

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

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

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

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

            case failedLoginCount:
                type = 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);

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

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

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

                atts.addAttribute("", "", "id", XSD_LONG, String.valueOf(memb.getId()));
                atts.addAttribute("", "", "roleId", XSD_LONG, String.valueOf(memb.getRoleId()));
                atts.addAttribute("", "", "roleName", XSD_STRING, String.valueOf(memb.getRoleName()));
                handler.startElement("", "", "membership", atts);

                doExtractAttributes(handler, memb, memb.getAttributeMap().keySet(),
                        memb.getDerivedAttributeMap().keySet(), memb.getVirtualAttributeMap().keySet());

                if (conf.getFeatures().contains(Feature.resources)) {
                    Membership actualMemb = user.getMembership(memb.getRoleId());
                    if (actualMemb == null) {
                        LOG.warn("Unexpected: cannot find membership for " + "role {} for user {}",
                                memb.getRoleId(), user);
                    } else {
                        doExtractResources(handler, roleDataBinder.getRoleTO(actualMemb.getSyncopeRole()));
                    }
                }

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

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

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

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

From source file:com.adobe.acs.commons.rewriter.impl.VersionedClientlibsTransformerFactoryTest.java

@Test
public void testCssClientLibraryWithDot() throws Exception {
    final String path = PATH + ".foo";

    when(htmlLibraryManager.getLibrary(eq(LibraryType.CSS), eq(path))).thenReturn(htmlLibrary);
    when(htmlLibrary.getLibraryPath()).thenReturn(path);

    final AttributesImpl in = new AttributesImpl();
    in.addAttribute("", "href", "", "CDATA", path + ".css");
    in.addAttribute("", "type", "", "CDATA", "text/css");
    in.addAttribute("", "rel", "", "CDATA", "stylesheet");

    transformer.startElement(null, "link", null, in);

    ArgumentCaptor<Attributes> attributesCaptor = ArgumentCaptor.forClass(Attributes.class);

    verify(handler, only()).startElement(isNull(String.class), eq("link"), isNull(String.class),
            attributesCaptor.capture());

    assertEquals(path + "." + FAKE_STREAM_CHECKSUM + ".css", attributesCaptor.getValue().getValue(0));
}

From source file:org.syncope.core.util.ImportExport.java

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

    AttributesImpl atts = new AttributesImpl();

    PreparedStatement stmt = null;
    ResultSet rs = null;/*from  www.  ja  va2  s.  c om*/
    try {
        stmt = conn.prepareStatement("SELECT * FROM " + tableName + " a");
        rs = stmt.executeQuery();
        for (int rowNo = 0; rs.next(); rowNo++) {
            atts.clear();

            ResultSetMetaData metaData = rs.getMetaData();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i + 1);
                String value = rs.getString(columnName);
                if (value != null) {
                    atts.addAttribute("", "", columnName, "CDATA", value);
                }
            }

            handler.startElement("", "", tableName, atts);
            handler.endElement("", "", tableName);
        }
    } 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:biz.taoconsulting.oxf.processor.converter.FromPdfConverter.java

private void extractFromPDF(InputStream inputStream, XMLReceiver xmlReceiver, String scope) {

    logger.info("Extract from PDF started");
    // Write the header information of the PDF
    PDDocument doc = null;//w  ww  .j  a va  2s .co  m

    try {
        xmlReceiver.startDocument();
        logger.info("Start document completed");

        // Some variables for our PDF processing
        doc = getPDFdocument(inputStream, xmlReceiver); // PDF
        // Document

        if (doc == null) {
            xmlReceiver.startElement("", TAG_ROOT, TAG_ROOT, null);
            addErrorTagToOutput(xmlReceiver, "No PDF Information could be extracted");
            xmlReceiver.endElement("", TAG_ROOT, TAG_ROOT);
            return; //No processing on empty documents

        }

    } catch (SAXException e) {
        logger.error(e);
    }

    // Get a handle on all pages in the PDF. Needed for page lookup
    try {
        logger.info("Try to get handle on all pages array");
        this.allPages = doc.getDocumentCatalog().getAllPages();
        logger.info("Got handle to allPages in PDF");
    } catch (Exception e) {
        logger.error(e);
        addErrorTagToOutput(xmlReceiver, e.toString());
        this.allPages = null;
    }

    try {

        // Get the document information
        logger.info("Ready to retrieve basic PDF information");
        PDDocumentInformation docInfo = getDocumentInformation(doc, xmlReceiver);
        AttributesImpl atts = new AttributesImpl();
        // Capture the number of pages
        addPageCountAttribute(atts, doc);

        // Now add some document Info
        addDocInfoAttributes(atts, docInfo);

        // Start the PDF Document
        logger.info("writing the root element PDFDocument");
        xmlReceiver.startElement("", TAG_ROOT, TAG_ROOT, atts);

        logger.info("PDFDocument tag succesful opened");
        //Pull the Meta data from the PDF Document
        atts = new AttributesImpl();

        logger.info("PDFMetadata Element start");
        xmlReceiver.startElement("", TAG_META, TAG_META, atts);
        extractMetaDataFromPDF(xmlReceiver, doc);
        xmlReceiver.endElement("", TAG_META, TAG_META);
        logger.info("PDFMetadata Element end");
        // Get the PDF Content based on the selection in config

        if (scope.equals(SCOPE_PAGES)) {
            //PDF page by page
            logger.info("Will extract pages");
            extractPagesFromPDF(xmlReceiver, doc);
        } else if (scope.equals(SCOPE_METADATA)) {
            logger.info("No action bejond meta data");
            // No further action required since it was meta data only!
        } else if (scope.equals(SCOPE_BOOKMARKPAGES)) {
            // Try bookmarks then pages
            logger.info("Will extract bookmarks first then pages");
            if (!extractOutlineFromPDF(xmlReceiver, doc, scope)) {
                logger.info("No outline found, using pages");
                extractPagesFromPDF(xmlReceiver, doc);
            }

        } else {
            // PDF in outlines - default
            logger.info("Will extract: " + scope);
            extractOutlineFromPDF(xmlReceiver, doc, scope);
        }

        //If we got here it worked
        logger.info("Writing end element " + TAG_ROOT);
        xmlReceiver.endElement("", TAG_ROOT, TAG_ROOT);
        logger.info("About to close PDFDocument and SaxDocument");
        xmlReceiver.endDocument();
        doc.close(); // We finish it once we are done
        logger.info("Closed PDF and XML");
    } catch (IOException e) {
        logger.error(e);
        addErrorTagToOutput(xmlReceiver, e.toString());
    } catch (SAXException e) {
        logger.error(e);
        addErrorTagToOutput(xmlReceiver, e.toString());
    }
}

From source file:com.netspective.axiom.schema.BasicSchema.java

/**
 * This method will be called by the DataModelSchema automatically when all the children have been added. We call
 * the other methods "finishConstruction" so they are not called automatically by the DataModelSchema. We want to
 * do all construction finalization in this method only.
 */// w  w  w.  ja v a  2 s  . c  om
public void finalizeConstruction(XdmParseContext pc, Object element, String elementName)
        throws DataModelException {
    getTables().finishConstruction();

    try {
        TemplateContentHandler handler = (TemplateContentHandler) pc.getParser().getContentHandler();
        AttributesImpl dialogsPackageAttrs = new AttributesImpl();
        dialogsPackageAttrs.addAttribute(null, null, "package", "CDATA", "schema." + getName());
        Template dialogsPackage = new Template("schema." + getName() + "-tables", handler,
                new InputSourceLocator(pc.getInputSrcTracker(), pc.getLocator().getLineNumber(),
                        pc.getLocator().getColumnNumber()),
                handler.getTemplatCatalog(), handler.getDynamicTemplatesProducer(), null, "dialogs", "dialogs",
                dialogsPackageAttrs);

        // now go through and generate dialog templates for each of the tables
        Tables tables = getTables();
        for (int i = 0; i < tables.size(); i++) {
            Table table = tables.get(i);
            table.addSchemaRecordEditorDialogTemplates(dialogsPackage);
        }

        handler.addDynamicTemplate(dialogsPackage);
    } catch (SAXException e) {
        throw new DataModelException(pc, e);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java

@Test(expected = SAXException.class)
public void processParserTryCatchTest() throws Exception {
    ConfigParserHandler test = Mockito.mock(ConfigParserHandler.class, Mockito.CALLS_REAL_METHODS);
    AttributesImpl attrs = new AttributesImpl();
    test.startDocument();/*from   w  ww  .  jav a2 s. c o m*/
    attrs.addAttribute("", "", "name", "", "Stream attr name"); // NON-NLS
    attrs.addAttribute("", "", "type", "", "Stream attr type"); // NON-NLS
    attrs.addAttribute("", "", "class", "", "java.lang.String"); // 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
    test.startElement("TEST_URL", "TEST_LOCALNAME", "parser", attrs); // NON-NLS
}

From source file:com.adobe.acs.commons.rewriter.impl.VersionedClientlibsTransformerFactoryTest.java

@Test
public void testMinifiedCssClientLibrary() throws Exception {

    when(htmlLibraryManager.getLibrary(eq(LibraryType.CSS), eq(PATH))).thenReturn(htmlLibrary);

    final AttributesImpl in = new AttributesImpl();
    in.addAttribute("", "href", "", "CDATA", PATH + ".min.css");
    in.addAttribute("", "type", "", "CDATA", "text/css");
    in.addAttribute("", "rel", "", "CDATA", "stylesheet");

    transformer.startElement(null, "link", null, in);

    ArgumentCaptor<Attributes> attributesCaptor = ArgumentCaptor.forClass(Attributes.class);

    verify(handler, only()).startElement(isNull(String.class), eq("link"), isNull(String.class),
            attributesCaptor.capture());

    assertEquals(PATH + ".min." + FAKE_STREAM_CHECKSUM + ".css", attributesCaptor.getValue().getValue(0));
}

From source file:com.gargoylesoftware.htmlunit.xml.XmlUtil.java

private static Attributes namedNodeMapToSaxAttributes(final NamedNodeMap attributesMap) {
    final AttributesImpl attributes = new AttributesImpl();
    final int length = attributesMap.getLength();
    for (int i = 0; i < length; i++) {
        final Node attr = attributesMap.item(i);
        attributes.addAttribute(attr.getNamespaceURI(), attr.getLocalName(), attr.getNodeName(), null,
                attr.getNodeValue());/*w  w w  .  jav  a  2  s.c o m*/
    }

    return attributes;
}

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

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

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

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

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

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

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

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

From source file:org.apache.syncope.core.util.ImportExport.java

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

    AttributesImpl attrs = new AttributesImpl();

    PreparedStatement stmt = null;
    ResultSet rs = null;/* w  w  w. java 2 s  . c o  m*/
    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);
            }
        }

        // ------------------------------------
        stmt = conn.prepareStatement(
                "SELECT * FROM " + tableName + " a" + (orderBy.length() > 0 ? " ORDER BY " + orderBy : ""));

        rs = stmt.executeQuery();
        for (int rowNo = 0; rs.next(); rowNo++) {
            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) {
                    attrs.addAttribute("", "", columnName, "CDATA", value);
                }
            }

            handler.startElement("", "", tableName, attrs);
            handler.endElement("", "", tableName);
        }
    } 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);
            }
        }
    }
}