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.jahia.services.importexport.DocumentViewExporter.java

private void exportNode(JCRNodeWrapper node) throws SAXException, RepositoryException {
    if (!typesToIgnore.contains(node.getPrimaryNodeTypeName())) {
        String path = "";
        Node current = node;//from   w w  w .  j  av  a2 s  .  c o  m
        while (!current.getPath().equals("/")) {
            path = "/" + current.getName() + path;
            current = current.getParent();
        }
        if (path.equals("")) {
            path = "/";
        }

        if (!path.equals(rootNode.getPath())) {

            String parentpath = path.substring(0, path.lastIndexOf('/'));

            while (!stack.isEmpty() && !parentpath.startsWith(stack.peek() + "/")
                    && !parentpath.equals(stack.peek())) {
                String end = stack.pop();
                if (stack.isEmpty()) {
                    throw new RepositoryException("Node not in path : " + node.getPath());
                }
                String name = end.substring(end.lastIndexOf('/') + 1);
                String encodedName = ISO9075.encode(name);
                endElement(encodedName);
            }
            if (stack.isEmpty() && !node.getPath().equals(rootNode.getPath())) {
                String name = rootNode.getName();
                String encodedName = ISO9075.encode(name);
                AttributesImpl atts = new AttributesImpl();
                startElement(encodedName, atts);
                if (rootNode.getPath().equals("/")) {
                    stack.push("");
                } else {
                    stack.push(rootNode.getPath());
                }
            }

            while (!stack.isEmpty() && !stack.peek().equals(parentpath)) {
                String peek = stack.peek();
                String name = parentpath.substring(peek.length() + 1);
                if (name.contains("/")) {
                    name = name.substring(0, name.indexOf('/'));
                }
                String encodedName = ISO9075.encode(name);
                String currentpath = peek + "/" + name;
                JCRNodeWrapper n = session.getNode(currentpath);
                String pt = n.getPrimaryNodeTypeName();
                AttributesImpl atts = new AttributesImpl();
                atts.addAttribute(Name.NS_JCR_URI, "primaryType", "jcr:primaryType", CDATA, pt);
                setProviderRootAttribute(n, atts);
                startElement(encodedName, atts);
                stack.push(currentpath);
            }
        }
        AttributesImpl atts = new AttributesImpl();
        if (node.isNodeType("jmix:shareable")) {

            if (exportedShareable.containsKey(node.getIdentifier())) {
                atts.addAttribute(Constants.JAHIA_NS, "share", "j:share", CDATA,
                        exportedShareable.get(node.getIdentifier()));
                String encodedName = ISO9075.encode(node.getName());
                startElement(encodedName, atts);
                endElement(encodedName);
                notifyListObservers(node.getPath());
                return;
            } else {
                exportedShareable.put(node.getIdentifier(), node.getPath());
            }
        }
        PropertyIterator propsIterator = node.getRealNode().getProperties();
        SortedSet<String> sortedProps = new TreeSet<String>();
        while (propsIterator.hasNext()) {
            Property property = propsIterator.nextProperty();
            if (node.getProvider().canExportProperty(property)) {
                sortedProps.add(property.getName());
            }
        }
        for (String prop : sortedProps) {
            try {
                Property property = node.getRealNode().getProperty(prop);
                if (node.hasProperty(prop) && (property.getType() != PropertyType.BINARY || !skipBinary)
                        && !propertiestoIgnore.contains(property.getName())) {
                    String key = property.getName();
                    String prefix = null;
                    String localname = key;
                    if (key.indexOf(':') > -1) {
                        prefix = key.substring(0, key.indexOf(':'));
                        localname = key.substring(key.indexOf(':') + 1);
                    }

                    String attrName = ISO9075.encode(localname);

                    String value;
                    if (!property.isMultiple()) {
                        if (property.getDefinition().getRequiredType() == PropertyType.REFERENCE || property
                                .getDefinition().getRequiredType() == ExtendedPropertyType.WEAKREFERENCE) {
                            value = JCRMultipleValueUtils.encode(getValue(property.getValue()));
                        } else {
                            value = getValue(property.getValue());
                        }
                    } else {
                        Value[] vs = property.getValues();
                        List<String> values = new ArrayList<String>();
                        for (Value v : vs) {
                            values.add(JCRMultipleValueUtils.encode(getValue(v)));
                        }
                        Collections.sort(values);
                        StringBuilder b = new StringBuilder();
                        for (int i = 0; i < values.size(); i++) {
                            String v = values.get(i);
                            b.append(v);
                            if (i + 1 < values.size()) {
                                b.append(" ");
                            }
                        }
                        value = b.toString();
                    }

                    if (prefix == null) {
                        atts.addAttribute("", localname, attrName, CDATA, value);
                    } else {
                        atts.addAttribute(prefixes.get(prefix), localname, prefix + ":" + attrName, CDATA,
                                value);
                    }
                }
            } catch (RepositoryException e) {
                logger.error("Cannot export property", e);
            }
        }
        if (publicationStatusSession != null && node.isNodeType("jmix:publication")) {
            String s = Integer.toString(
                    JCRPublicationService.getInstance().getStatus(node, publicationStatusSession, null));
            atts.addAttribute(prefixes.get("j"), "publicationStatus", "j:publicationStatus", CDATA, s);
        }
        setProviderRootAttribute(node, atts);

        String encodedName = ISO9075.encode(node.getName());
        startElement(encodedName, atts);
        if (path.equals("/")) {
            stack.push("");
        } else {
            stack.push(path);
        }

        if (!noRecurse) {
            List<String> exportedMountPointNodes = new ArrayList<String>();
            NodeIterator ni = node.getNodes();
            while (ni.hasNext()) {
                JCRNodeWrapper c = (JCRNodeWrapper) ni.next();
                if (c.getProvider().canExportNode(c) && !exportedMountPointNodes.contains(c.getName())) {
                    if (!"/".equals(path) && !c.getProvider().equals(node.getProvider())) { // is external provider root
                        String mountPointName = c.getName() + JCRMountPointNode.MOUNT_SUFFIX;
                        if (node.hasNode(mountPointName) && !exportedMountPointNodes.contains(mountPointName)) { // mounted from a dynamic mountPoint
                            JCRNodeWrapper mountPointNode = node.getNode(mountPointName);
                            if (mountPointNode.isNodeType(Constants.JAHIANT_MOUNTPOINT)) {
                                exportNode(mountPointNode);
                                exportedMountPointNodes.add(mountPointName);
                            }
                        }
                    }
                    exportNode(c);
                    if (c.getName().endsWith(JCRMountPointNode.MOUNT_SUFFIX)
                            && c.isNodeType(Constants.JAHIANT_MOUNTPOINT)) {
                        exportedMountPointNodes.add(c.getName());
                    }
                }
            }
        }
        notifyListObservers(node.getPath());
    }
}

From source file:org.kalypso.gml.GMLSAXFactory.java

public void process(final GMLWorkspace workspace) throws SAXException {
    final Feature rootFeature = workspace.getRootFeature();

    final IFeatureType rootFT = rootFeature.getFeatureType();
    final QName rootQName = rootFT.getQName();

    // REMARK: always force the root element to have the empty namespace prefix
    final String rootNamespace = rootQName.getNamespaceURI();
    m_usedPrefixes.put(rootNamespace, XMLConstants.DEFAULT_NS_PREFIX);

    forcePrefixes(workspace, rootNamespace);

    // Add schemalocation string
    final AttributesImpl a = new AttributesImpl();
    final String schemaLocationString = workspace.getSchemaLocationString();
    if (schemaLocationString != null && schemaLocationString.length() > 0) {

        addAttribute(a, m_schemaLocationAttributeName, "CDATA", schemaLocationString);
    }/*w w w .j av a2  s .  c om*/

    processFeature(rootFeature, a);
}

From source file:org.kalypso.gml.GMLSAXFactory.java

/**
 * Writes one single property//from  w ww.jav a2 s . com
 */
private void processProperty(final IPropertyType pt, final Object propertyValue) throws SAXException {
    final ContentHandler contentHandler = m_reader.getContentHandler();

    final QName name = pt.getQName();
    final QName prefixedQName = getPrefixedQName(name);
    final String uri = prefixedQName.getNamespaceURI();
    final String localPart = prefixedQName.getLocalPart();

    // Find attributes for the current property
    final Attributes atts = attributeForProperty(pt, propertyValue);

    /* Write starting tag */
    final String qname = elementQName(prefixedQName);
    contentHandler.startElement(uri, localPart, qname, atts);

    if (pt instanceof IRelationType) {
        // Write the feature as content. If it is a reference (i.e. no feature), nothing is written, as the href was
        // already set as an attribute
        if (propertyValue instanceof Feature && !(propertyValue instanceof IXLinkedFeature))
            processFeature((Feature) propertyValue, new AttributesImpl());
    } else if (pt instanceof IValuePropertyType)
        processValueType((IValuePropertyType) pt, propertyValue, prefixedQName);
    else
        throw new UnsupportedOperationException();

    /* Write ending tag */
    contentHandler.endElement(uri, localPart, qname);
}

From source file:org.kalypso.gml.GMLSAXFactory.java

private Attributes attributeForProperty(final IPropertyType pt, final Object propertyValue)
        throws SAXException {
    final AttributesImpl atts = new AttributesImpl();

    if (pt instanceof IRelationType) {
        final String href;
        if (propertyValue instanceof String)
            href = "#" + (String) propertyValue;
        else if (propertyValue instanceof IXLinkedFeature)
            href = ((IXLinkedFeature) propertyValue).getHref();
        else/*from w w  w  .  ja v a 2s  . c o m*/
            href = null;

        if (href != null)
            addAttribute(atts, m_xlinkAttributeName, "CDATA", href);
    }

    return atts;
}

From source file:org.kalypso.ogc.sensor.deegree.ObservationLinkMarshaller.java

@Override
public void marshall(final TimeseriesLinkType element) throws SAXException {
    /* Basic names */
    final QName elementName = ObservationLinkHandler.TYPE_NAME;
    final String namespaceURI = elementName.getNamespaceURI();
    final String qname = QNAME_OBSLINK_PREFIX + elementName.getLocalPart();

    /* Build attributes */
    final AttributesImpl attributes = new AttributesImpl();
    addAttribute(attributes, "href", element.getHref()); //$NON-NLS-1$
    addAttribute(attributes, "actuate", element.getActuate()); //$NON-NLS-1$
    addAttribute(attributes, "arcrole", element.getArcrole()); //$NON-NLS-1$
    //    addAttribute( attributes, "linktype", element.getLinktype() ); //$NON-NLS-1$
    addAttribute(attributes, "role", element.getRole()); //$NON-NLS-1$
    addAttribute(attributes, "show", element.getShow()); //$NON-NLS-1$
    //    addAttribute( attributes, "timeaxis", element.getTimeaxis() ); //$NON-NLS-1$
    addAttribute(attributes, "title", element.getTitle()); //$NON-NLS-1$
    addAttribute(attributes, "type", element.getType()); //$NON-NLS-1$
    //    addAttribute( attributes, "valueaxis", element.getValueaxis() ); //$NON-NLS-1$

    /* write it */
    final ContentHandler contentHandler = m_reader.getContentHandler();
    contentHandler.startPrefixMapping(DeegreeUrlCatalog.PREFIX_OBSLINK, namespaceURI); //$NON-NLS-1$
    contentHandler.startPrefixMapping(PREFIX_XLINK, NS.XLINK); //$NON-NLS-1$
    contentHandler.startElement(namespaceURI, elementName.getLocalPart(), qname, attributes);
    contentHandler.endElement(namespaceURI, elementName.getLocalPart(), qname);
}

From source file:org.kalypsodeegree_impl.io.sax.marshaller.MarshallerUtils.java

public static AttributesImpl createSrsAttributes(final String srsName, final int srsDimension) {
    final AttributesImpl atts = new AttributesImpl();
    addSrsNameAttributes(atts, srsName);
    addSrsDimensionAttributes(atts, srsDimension);
    return atts;// ww  w  .j  a  v a  2 s  .  c  om
}

From source file:org.kohsuke.stapler.jelly.groovy.JellyBuilder.java

private Attributes toAttributes(Map attributes) {
    AttributesImpl atts = new AttributesImpl();
    for (Object o : attributes.entrySet()) {
        Entry e = (Entry) o;/* ww  w  .  j  a  va2  s  .  c o  m*/
        if (e.getKey().toString().equals("xmlns"))
            continue; // we'll process them outside attributes
        atts.addAttribute("", e.getKey().toString(), e.getKey().toString(), null, e.getValue().toString());
    }
    return atts;
}

From source file:org.lilyproject.runtime.tools.plugin.genclassloader.ClassloaderMojo.java

/**
 * Create a project file containing the dependencies.
 *
 * @throws IOException/*from  w  ww.ja  va  2 s.co m*/
 * @throws SAXException
 */
private void createDependencyListing(File classloaderTemplate) throws IOException, SAXException {
    if (classloaderTemplate != null && classloaderTemplate.exists()) {
        getLog().info("Found classloader template, trying to parse it...");
        parseClassloaderTemplate(classloaderTemplate);
    }
    final boolean hasEntries = entryMap.size() > 0;
    // fill in file with all dependencies
    FileOutputStream fos = new FileOutputStream(projectDescriptorFile);
    TransformerHandler ch = null;
    TransformerFactory factory = TransformerFactory.newInstance();
    if (factory.getFeature(SAXTransformerFactory.FEATURE)) {
        try {
            ch = ((SAXTransformerFactory) factory).newTransformerHandler();
            // set properties
            Transformer serializer = ch.getTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            // set result
            Result result = new StreamResult(fos);
            ch.setResult(result);
            // start file generation
            ch.startDocument();
            AttributesImpl atts = new AttributesImpl();
            if (this.shareSelf != null) {
                atts.addAttribute("", "share-self", "share-self", "CDATA", this.shareSelf);
            }
            ch.startElement("", "classloader", "classloader", atts);
            atts.clear();
            ch.startElement("", "classpath", "classpath", atts);
            SortedSet<Artifact> sortedArtifacts = new TreeSet<Artifact>(dependenciesToList);
            Entry entry;
            String entryShare;
            String entryVersion;
            for (Artifact artifact : sortedArtifacts) {
                atts.addAttribute("", "groupId", "groupId", "CDATA", artifact.getGroupId());
                atts.addAttribute("", "artifactId", "artifactId", "CDATA", artifact.getArtifactId());
                if (artifact.getClassifier() != null) {
                    atts.addAttribute("", "classifier", "classifier", "CDATA", artifact.getClassifier());
                }
                if (!artifact.getGroupId().equals("org.lilyproject")) {
                    atts.addAttribute("", "version", "version", "CDATA", artifact.getBaseVersion());
                }
                entry = new Entry(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier());
                if (hasEntries && entryMap.containsKey(entry)) {
                    entryVersion = extractAttVal(entryMap.get(entry).getAttributes(), "version");
                    entryShare = extractAttVal(entryMap.get(entry).getAttributes(), "share");
                    entryMap.remove(entry);
                    if (entryVersion != null && !entryVersion.equals("")
                            && !entryVersion.equals(artifact.getBaseVersion())) {
                        getLog().warn(
                                "version conflict between entry in template and artifact on classpath for "
                                        + entry);
                    }
                    if (entryShare != null) {
                        atts.addAttribute("", "", "share", "CDATA", entryShare);
                    }
                } else {
                    // atts.addAttribute("", "", "share", "CDATA", SHARE_DEFAULT);
                }
                ch.startElement("", "artifact", "artifact", atts);
                ch.endElement("", "artifact", "artifact");
                atts.clear();
            }
            ch.endElement("", "classpath", "classpath");
            ch.endElement("", "classloader", "classloader");
            ch.endDocument();
            fos.close();
            if (entryMap.size() > 0) {
                getLog().warn("Classloader template contains entries that could not be resolved.");
            }
        } catch (TransformerConfigurationException ex) {
            ex.printStackTrace();
            throw new SAXException("Unable to get a TransformerHandler.");
        }
    } else {
        throw new RuntimeException("Could not load SAXTransformerFactory.");
    }
}

From source file:org.nuxeo.ecm.diff.content.adapter.HtmlContentDiffer.java

public List<Blob> getContentDiff(Blob leftBlob, Blob rightBlob, Locale locale) throws ContentDiffException {

    try {// ww  w. java  2 s.  c  om
        List<Blob> blobResults = new ArrayList<Blob>();
        StringWriter sw = new StringWriter();

        SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler transformHandler = stf.newTransformerHandler();
        transformHandler.setResult(new StreamResult(sw));

        XslFilter htmlHeaderXslFilter = new XslFilter();

        StringBuilder sb = new StringBuilder("xslfilter/htmldiffheader");
        sb.append("_");
        sb.append(locale.getLanguage());
        sb.append(".xsl");
        String htmlHeaderXslPath = sb.toString();
        ContentHandler postProcess;
        try {
            postProcess = htmlHeaderXslFilter.xsl(transformHandler, htmlHeaderXslPath);
        } catch (IllegalStateException ise) {
            LOGGER.error(String.format(
                    "Could not find the HTML diff header xsl file '%s', falling back on the default one.",
                    htmlHeaderXslPath), ise);
            postProcess = htmlHeaderXslFilter.xsl(transformHandler, "xslfilter/htmldiffheader.xsl");
        }

        String prefix = "diff";

        HtmlCleaner cleaner = new HtmlCleaner();

        InputSource leftIS = new InputSource(leftBlob.getStream());
        InputSource rightIS = new InputSource(rightBlob.getStream());

        DomTreeBuilder leftHandler = new DomTreeBuilder();
        cleaner.cleanAndParse(leftIS, leftHandler);
        TextNodeComparator leftComparator = new TextNodeComparator(leftHandler, locale);

        DomTreeBuilder rightHandler = new DomTreeBuilder();
        cleaner.cleanAndParse(rightIS, rightHandler);
        TextNodeComparator rightComparator = new TextNodeComparator(rightHandler, locale);

        postProcess.startDocument();
        postProcess.startElement("", "diffreport", "diffreport", new AttributesImpl());
        postProcess.startElement("", "diff", "diff", new AttributesImpl());
        HtmlSaxDiffOutput output = new HtmlSaxDiffOutput(postProcess, prefix);

        HTMLDiffer differ = new HTMLDiffer(output);
        differ.diff(leftComparator, rightComparator);

        postProcess.endElement("", "diff", "diff");
        postProcess.endElement("", "diffreport", "diffreport");
        postProcess.endDocument();

        String stringBlob = sw.toString().replaceAll(NUXEO_DEFAULT_CONTEXT_PATH,
                VirtualHostHelper.getContextPathProperty());
        Blob mainBlob = Blobs.createBlob(stringBlob);
        sw.close();

        mainBlob.setFilename("contentDiff.html");
        mainBlob.setMimeType("text/html");

        blobResults.add(mainBlob);
        return blobResults;

    } catch (Exception e) {
        throw new ContentDiffException(e);
    }
}

From source file:org.onehippo.cms7.autoexport.Exporter.java

private void exportInstruction(DeltaInstruction instruction, ContentHandler handler)
        throws SAXException, RepositoryException {
    if (instruction.isNoneDirective()) {
        if (instruction.isNodeInstruction()) {
            List<String> subContextPaths = new ArrayList<String>();
            for (InitializeItem child : registry.getDescendentInitializeItems(instruction.getContextPath())) {
                subContextPaths.add(child.getContextPath());
            }/*from   w w w  .  jav a2s. c  o m*/
            ExclusionContext exclusionContext = new ExclusionContext(configuration.getExclusionContext(),
                    subModuleExclusionPatterns);
            ContentHandler filter = new FilterContentHandler(new EmbeddedContentHandler(handler),
                    instruction.getParentPath(), subContextPaths, configuration.getFilterUuidPaths(),
                    exclusionContext);
            ((HippoSession) session).exportDereferencedView(instruction.getContextPath(), filter, false, false);
        } else {
            exportPropertyInstruction(instruction, handler, false);
        }
    } else if (instruction.isCombineDirective()) {
        AttributesImpl attr = new AttributesImpl();
        attr.addAttribute(SV_URI, NAME, QNAME, CDATA, instruction.getName());
        attr.addAttribute(DELTA_URI, MERGE, QMERGE, CDATA, instruction.getDirective());
        handler.startElement(SV_URI, NODE, QNODE, attr);
        if (instruction.getPropertyInstructions() != null) {
            for (DeltaInstruction child : instruction.getPropertyInstructions()) {
                exportInstruction(child, handler);
            }
        }
        if (instruction.getNodeInstructions() != null) {
            for (DeltaInstruction child : instruction.getNodeInstructions()) {
                exportInstruction(child, handler);
            }
        }
        handler.endElement(SV_URI, NODE, QNODE);
    } else if (instruction.isOverrideDirective()) {
        exportPropertyInstruction(instruction, handler, true);
    }
}