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.onehippo.cms7.autoexport.Exporter.java

private void exportPropertyInstruction(DeltaInstruction instruction, ContentHandler handler, boolean override)
        throws SAXException, RepositoryException {
    Property property = session.getProperty(instruction.getContextPath());
    AttributesImpl attr = new AttributesImpl();
    attr.addAttribute(SV_URI, NAME, QNAME, CDATA, instruction.getName());
    attr.addAttribute(SV_URI, TYPE, QTYPE, CDATA, PropertyType.nameFromValue(property.getType()));
    if (override) {
        attr.addAttribute(DELTA_URI, MERGE, QMERGE, CDATA, "override");
    }//from  www . j av  a 2s . c  o m
    if (property.isMultiple()) {
        attr.addAttribute(SV_URI, "multiple", "sv:multiple", CDATA, "true");
    }
    handler.startElement(SV_URI, PROPERTY, QPROPERTY, attr);
    attr = new AttributesImpl();
    if (property.isMultiple()) {
        for (Value value : property.getValues()) {
            handler.startElement(SV_URI, VALUE, QVALUE, attr);
            String stringValue = value.getString();
            handler.characters(stringValue.toCharArray(), 0, stringValue.length());
            handler.endElement(SV_URI, VALUE, QVALUE);
        }
    } else {
        Value value = property.getValue();
        handler.startElement(SV_URI, VALUE, QVALUE, attr);
        String stringValue = value.getString();
        handler.characters(stringValue.toCharArray(), 0, stringValue.length());
        handler.endElement(SV_URI, VALUE, QVALUE);
    }
    handler.endElement(SV_URI, PROPERTY, QPROPERTY);
}

From source file:org.onehippo.repository.xml.SysViewSAXEventGenerator.java

@Override
protected void entering(Node node, int level) throws RepositoryException, SAXException {
    final AttributesImpl attrs = new AttributesImpl();

    String nodeName;//ww w  .  java 2  s  .  co  m
    if (node.getDepth() == 0) {
        nodeName = jcrRoot;
    } else {
        nodeName = node.getName();
    }

    addAttribute(attrs, SV_NAME, CDATA_TYPE, nodeName);
    startElement(NameConstants.SV_NODE, attrs);
}

From source file:org.onehippo.repository.xml.SysViewSAXEventGenerator.java

@Override
protected void entering(Property prop, int level) throws RepositoryException, SAXException {

    final AttributesImpl attrs = new AttributesImpl();
    addAttribute(attrs, SV_NAME, CDATA_TYPE, prop.getName());
    final String typeName = PropertyType.nameFromValue(prop.getType());
    addAttribute(attrs, SV_TYPE, ENUMERATION_TYPE, typeName);
    if (prop.isMultiple()) {
        addAttribute(attrs, SV_MULTIPLE, CDATA_TYPE, String.valueOf(true));
    }//from   w ww.j ava 2s . c o  m

    startElement(SV_PROPERTY, attrs);

    if (prop.getType() == BINARY && skipBinary) {
        startElement(SV_VALUE, new AttributesImpl());
        endElement(SV_VALUE);
    } else {
        Value[] vals = getValues(prop);
        for (final Value val : vals) {
            exportValue(val);
        }
    }
}

From source file:org.onehippo.repository.xml.SysViewSAXEventGenerator.java

private void exportValue(final Value val) throws RepositoryException, SAXException {

    if (val.getType() == BINARY && binaries != null) {
        File file = createBinaryFile(val);
        binaries.add(file);//from   ww w. ja v  a 2  s  .com
        AttributesImpl attributes = new AttributesImpl();
        attributes.addAttribute(NS_XMLIMPORT_URI, "file", "h:file", CDATA_TYPE, file.getName());
        contentHandler.startPrefixMapping(NS_XMLIMPORT_PREFIX, NS_XMLIMPORT_URI);
        startElement(SV_VALUE, attributes);
        endElement(SV_VALUE);
        contentHandler.endPrefixMapping(NS_XMLIMPORT_PREFIX);
    } else {
        Attributes attributes = ATTRS_EMPTY;
        final boolean mustSendBinary = mustSendBinary(val);
        if (mustSendBinary) {
            contentHandler.startPrefixMapping(NS_XMLSCHEMA_INSTANCE_PREFIX, NS_XMLSCHEMA_INSTANCE_URI);
            contentHandler.startPrefixMapping(NS_XMLSCHEMA_PREFIX, NS_XMLSCHEMA_URI);
            attributes = ATTRS_BINARY_ENCODED_VALUE;
        }
        startElement(SV_VALUE, attributes);

        try {
            ValueHelper.serialize(val, false, mustSendBinary, new ContentHandlerWriter(contentHandler));
        } catch (IOException ioe) {
            Throwable t = ioe.getCause();
            if (t != null && t instanceof SAXException) {
                throw (SAXException) t;
            } else {
                throw new SAXException(ioe);
            }
        }

        endElement(SV_VALUE);

        if (mustSendBinary) {
            contentHandler.endPrefixMapping(NS_XMLSCHEMA_INSTANCE_PREFIX);
            contentHandler.endPrefixMapping(NS_XMLSCHEMA_PREFIX);
        }
    }

}

From source file:org.orbeon.oxf.processor.generator.RequestGenerator.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new DigestTransformerOutputImpl(RequestGenerator.this, name) {
        public void readImpl(final PipelineContext pipelineContext, XMLReceiver xmlReceiver) {
            final State state = (State) getFilledOutState(pipelineContext);
            // Transform the resulting document into SAX

            TransformerUtils.sourceToSAX(new DocumentSource(state.requestDocument),
                    new ForwardingXMLReceiver(xmlReceiver) {
                        @Override
                        public void startElement(String uri, String localname, String qName,
                                Attributes attributes) throws SAXException {
                            try {
                                if (REQUEST_PRIVATE_NAMESPACE_URI.equals(uri)) {
                                    // Special treatment for this element
                                    if (FILE_ITEM_ELEMENT.equals(qName)) {
                                        // Marker for file item

                                        final String parameterName = attributes
                                                .getValue(PARAMETER_NAME_ATTRIBUTE);
                                        final int parameterPosition = Integer
                                                .parseInt(attributes.getValue(PARAMETER_POSITION_ATTRIBUTE));
                                        final FileItem fileItem = (FileItem) ((Object[]) getRequest(
                                                pipelineContext).getParameterMap()
                                                        .get(parameterName))[parameterPosition];

                                        final AttributesImpl newAttributes = new AttributesImpl();
                                        super.startPrefixMapping(XMLConstants.XSI_PREFIX, XMLConstants.XSI_URI);
                                        super.startPrefixMapping(XMLConstants.XSD_PREFIX, XMLConstants.XSD_URI);
                                        newAttributes.addAttribute(XMLConstants.XSI_URI, "type", "xsi:type",
                                                "CDATA",
                                                useBase64(pipelineContext, fileItem)
                                                        ? XMLConstants.XS_BASE64BINARY_QNAME.getQualifiedName()
                                                        : XMLConstants.XS_ANYURI_QNAME.getQualifiedName());
                                        super.startElement("", "value", "value", newAttributes);
                                        writeFileItem(pipelineContext, fileItem, state.isSessionScope,
                                                useBase64(pipelineContext, fileItem), getXMLReceiver());
                                        super.endElement("", "value", "value");
                                        super.endPrefixMapping(XMLConstants.XSD_PREFIX);
                                        super.endPrefixMapping(XMLConstants.XSI_PREFIX);
                                    }//from   ww  w. ja va2 s  .  c o  m
                                } else if (localname.equals("body") && uri.equals("")) {
                                    // Marker for request body

                                    // Read InputStream into FileItem object, if not already present

                                    // We do this so we can read the body multiple times, if needed.
                                    // For large files, there will be a performance hit. If we knew
                                    // we didn't need to read it multiple times, we could avoid
                                    // saving the stream, but practically, it can happen, and it is
                                    // convenient.
                                    final Context context = getContext(pipelineContext);
                                    if (context.bodyFileItem != null
                                            || getRequest(pipelineContext).getInputStream() != null) {

                                        final ExternalContext.Request request = getRequest(pipelineContext);

                                        if (context.bodyFileItem == null) {
                                            final FileItem fileItem = new DiskFileItemFactory(
                                                    getMaxMemorySizeProperty(),
                                                    SystemUtils.getTemporaryDirectory()).createItem("dummy",
                                                            "dummy", false, null);
                                            pipelineContext.addContextListener(
                                                    new PipelineContext.ContextListenerAdapter() {
                                                        public void contextDestroyed(boolean success) {
                                                            fileItem.delete();
                                                        }
                                                    });
                                            final OutputStream outputStream = fileItem.getOutputStream();
                                            NetUtils.copyStream(request.getInputStream(), outputStream);
                                            outputStream.close();
                                            context.bodyFileItem = fileItem;
                                        }
                                        // Serialize the stream into the body element
                                        final AttributesImpl newAttributes = new AttributesImpl();
                                        super.startPrefixMapping(XMLConstants.XSI_PREFIX, XMLConstants.XSI_URI);
                                        super.startPrefixMapping(XMLConstants.XSD_PREFIX, XMLConstants.XSD_URI);
                                        newAttributes.addAttribute(XMLConstants.XSI_URI, "type", "xsi:type",
                                                "CDATA",
                                                useBase64(pipelineContext, context.bodyFileItem)
                                                        ? XMLConstants.XS_BASE64BINARY_QNAME.getQualifiedName()
                                                        : XMLConstants.XS_ANYURI_QNAME.getQualifiedName());
                                        super.startElement(uri, localname, qName, newAttributes);
                                        final String uriOrNull = writeFileItem(pipelineContext,
                                                context.bodyFileItem, state.isSessionScope,
                                                useBase64(pipelineContext, context.bodyFileItem),
                                                getXMLReceiver());
                                        super.endElement(uri, localname, qName);
                                        super.endPrefixMapping(XMLConstants.XSD_PREFIX);
                                        super.endPrefixMapping(XMLConstants.XSI_PREFIX);

                                        // If the body is available as a URL, store it into the pipeline context.
                                        // This is done so that native code can access the body even if it has been read
                                        // already. Possibly, this could be handled more transparently by ExternalContext,
                                        // so that Request.getInputStream() works even upon multiple reads.
                                        // NOTE 2013-05-30: We used to store this into the request, but request attributes
                                        // are forwarded by LocalRequest. This means that a forwarded-to request might get
                                        // the wrong body! Instead, we now use PipelineContext, which is scoped to be per
                                        // request. Again, if ExternalContext was handling this, we could just leave it to
                                        // ExternalContext.
                                        if (uriOrNull != null)
                                            pipelineContext.setAttribute(BODY_REQUEST_ATTRIBUTE, uriOrNull);
                                    }
                                } else {
                                    super.startElement(uri, localname, qName, attributes);
                                }
                            } catch (IOException e) {
                                throw new OXFException(e);
                            }
                        }

                        @Override
                        public void endElement(String uri, String localname, String qName) throws SAXException {
                            if (REQUEST_PRIVATE_NAMESPACE_URI.equals(uri)
                                    || localname.equals("body") && uri.equals("")) {
                                // Ignore end element
                            } else {
                                super.endElement(uri, localname, qName);
                            }
                        }
                    });
        }

        protected boolean fillOutState(PipelineContext pipelineContext, DigestState digestState) {
            final State state = (State) digestState;
            if (state.requestDocument == null) {
                // Read config document
                final Document config = readCacheInputAsDOM4J(pipelineContext, INPUT_CONFIG);

                // Try to find stream-type attribute
                final QName streamTypeQName = Dom4jUtils.extractAttributeValueQName(config.getRootElement(),
                        "stream-type");
                if (streamTypeQName != null && !(streamTypeQName.equals(XMLConstants.XS_BASE64BINARY_QNAME)
                        || streamTypeQName.equals(XMLConstants.XS_ANYURI_QNAME)))
                    throw new OXFException(
                            "Invalid value for stream-type attribute: " + streamTypeQName.getQualifiedName());
                state.requestedStreamType = streamTypeQName;
                state.isSessionScope = "session".equals(config.getRootElement().attributeValue("stream-scope"));

                // Read and store request
                state.requestDocument = readRequestAsDOM4J(pipelineContext, config);

                // Check if the body was requested
                state.bodyRequested = XPathUtils.selectSingleNode(state.requestDocument, "/*/body") != null;
            }
            final Context context = getContext(pipelineContext);
            return !context.hasUpload && !state.bodyRequested;
        }

        protected byte[] computeDigest(PipelineContext pipelineContext, DigestState digestState) {
            final State state = (State) digestState;
            return DigestContentHandler.getDigest(new DocumentSource(state.requestDocument));
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.processor.zip.UnzipProcessor.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(UnzipProcessor.this, name) {

        public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) {
            try {
                // Read input in a temporary file
                final File temporaryZipFile;
                {// w  w  w  .j  av a 2 s . c  o  m
                    final FileItem fileItem = NetUtils.prepareFileItem(NetUtils.REQUEST_SCOPE, logger);
                    final OutputStream fileOutputStream = fileItem.getOutputStream();
                    readInputAsSAX(context, getInputByName(INPUT_DATA),
                            new BinaryTextXMLReceiver(fileOutputStream));
                    temporaryZipFile = ((DiskFileItem) fileItem).getStoreLocation();
                }

                xmlReceiver.startDocument();
                // <files>
                xmlReceiver.startElement("", "files", "files", SAXUtils.EMPTY_ATTRIBUTES);
                ZipFile zipFile = new ZipFile(temporaryZipFile);
                for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
                    // Go through each entry in the zip file
                    ZipEntry zipEntry = (ZipEntry) entries.nextElement();
                    // Get file name
                    String fileName = zipEntry.getName();
                    long fileSize = zipEntry.getSize();
                    String fileTime = DateUtils.DateTime().print(zipEntry.getTime());

                    InputStream entryInputStream = zipFile.getInputStream(zipEntry);
                    String uri = NetUtils.inputStreamToAnyURI(entryInputStream, NetUtils.REQUEST_SCOPE, logger);
                    // <file name="filename.ext">uri</file>
                    AttributesImpl fileAttributes = new AttributesImpl();
                    fileAttributes.addAttribute("", "name", "name", "CDATA", fileName);
                    fileAttributes.addAttribute("", "size", "size", "CDATA", Long.toString(fileSize));
                    fileAttributes.addAttribute("", "dateTime", "dateTime", "CDATA", fileTime);
                    xmlReceiver.startElement("", "file", "file", fileAttributes);
                    xmlReceiver.characters(uri.toCharArray(), 0, uri.length());
                    // </file>
                    xmlReceiver.endElement("", "file", "file");
                }
                // </files>
                xmlReceiver.endElement("", "files", "files");
                xmlReceiver.endDocument();

            } catch (IOException e) {
                throw new OXFException(e);
            } catch (SAXException e) {
                throw new OXFException(e);
            }
        }

        // We don't do any caching here since the file we produce are temporary. So we don't want a processor
        // downstream to keep a reference to a document that contains temporary URI that have since been deleted.

    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.xforms.processor.handlers.xhtml.XFormsBaseHandlerXHTML.java

protected void handleLabelHintHelpAlert(LHHAAnalysis lhhaAnalysis, String targetControlEffectiveId,
        String forEffectiveId, XFormsBaseHandler.LHHAC lhhaType, XFormsControl control, boolean isTemplate,
        boolean isExternal) throws SAXException {

    final AttributesImpl staticLHHAAttributes = Dom4jUtils.getSAXAttributes(lhhaAnalysis.element());

    final boolean isLabel = lhhaType == LHHAC.LABEL;
    final boolean isHelp = lhhaType == LHHAC.HELP;
    final boolean isHint = lhhaType == LHHAC.HINT;
    final boolean isAlert = lhhaType == LHHAC.ALERT;

    if (staticLHHAAttributes != null || isAlert) {
        // If no attributes were found, there is no such label / help / hint / alert

        if (handlerContext.isNoScript() && isHelp) {
            if (control != null) {

                final ContentHandler contentHandler = handlerContext.getController().getOutput();
                final String xhtmlPrefix = handlerContext.findXHTMLPrefix();

                // <a href="#my-control-id-help">

                final AttributesImpl aAttributes = new AttributesImpl();
                aAttributes.addAttribute("", "href", "href", XMLReceiverHelper.CDATA,
                        "#" + getLHHACId(containingDocument, targetControlEffectiveId,
                                LHHAC_CODES.get(LHHAC.HELP)));
                aAttributes.addAttribute("", "class", "class", XMLReceiverHelper.CDATA, "xforms-help-anchor");

                final String aQName = XMLUtils.buildQName(xhtmlPrefix, "a");
                contentHandler.startElement(XMLConstants.XHTML_NAMESPACE_URI, "a", aQName, aAttributes);
                contentHandler.endElement(XMLConstants.XHTML_NAMESPACE_URI, "a", aQName);
            }/*from w ww .  ja v  a2  s.  com*/
        } else {

            final String labelHintHelpAlertValue;
            final boolean mustOutputHTMLFragment;
            if (control != null) {
                // Get actual value from control
                if (isLabel) {
                    labelHintHelpAlertValue = control.getLabel();
                    mustOutputHTMLFragment = control.isHTMLLabel();
                } else if (isHelp) {
                    // NOTE: Special case here where we get the escaped help to facilitate work below. Help is a special
                    // case because it is stored as escaped HTML within a <label> element.
                    labelHintHelpAlertValue = control.getEscapedHelp();
                    mustOutputHTMLFragment = false;
                } else if (isHint) {
                    labelHintHelpAlertValue = control.getHint();
                    mustOutputHTMLFragment = control.isHTMLHint();
                } else if (isAlert) {
                    labelHintHelpAlertValue = control.getAlert();
                    mustOutputHTMLFragment = control.isHTMLAlert();
                } else {
                    throw new IllegalStateException("Illegal type requested");
                }
            } else {
                // Placeholder
                labelHintHelpAlertValue = null;
                mustOutputHTMLFragment = false;
            }

            final String elementName;
            {
                if (isLabel) {
                    elementName = handlerContext.getLabelElementName();
                } else if (isHelp) {
                    elementName = handlerContext.getHelpElementName();
                } else if (isHint) {
                    elementName = handlerContext.getHintElementName();
                } else if (isAlert) {
                    elementName = handlerContext.getAlertElementName();
                } else {
                    throw new IllegalStateException("Illegal type requested");
                }
            }

            final StringBuilder classes = new StringBuilder(30);

            // Put user classes first if any
            if (staticLHHAAttributes != null) {
                final String userClass = staticLHHAAttributes.getValue("class");
                if (userClass != null)
                    classes.append(userClass);
            }

            // Mark alert as active if needed
            if (isAlert) {
                if (control instanceof XFormsSingleNodeControl) {
                    final XFormsSingleNodeControl singleNodeControl = (XFormsSingleNodeControl) control;
                    final scala.Option<ValidationLevels.ValidationLevel> constraintLevel = singleNodeControl
                            .alertLevel();

                    if (constraintLevel.isDefined()) {
                        if (classes.length() > 0)
                            classes.append(' ');
                        classes.append("xforms-active");
                    }

                    // Constraint classes are placed on the control if the alert is not external
                    if (isExternal)
                        addConstraintClasses(classes, constraintLevel);
                }
            }

            // Handle visibility
            // TODO: It would be great to actually know about the relevance of help, hint, and label. Right now, we just look at whether the value is empty
            if (control != null) {
                if (isAlert || isLabel) {
                    // Allow empty labels and alerts
                    if (!control.isRelevant()) {
                        if (classes.length() > 0)
                            classes.append(' ');
                        classes.append("xforms-disabled");
                    }
                } else {
                    // For help and hint, consider "non-relevant" if empty
                    final boolean isHintHelpRelevant = control.isRelevant()
                            && StringUtils.isNotEmpty(labelHintHelpAlertValue);
                    if (!isHintHelpRelevant) {
                        if (classes.length() > 0)
                            classes.append(' ');
                        classes.append("xforms-disabled");
                    }
                }
            } else if (!isTemplate || isHelp) {
                // Null control outside of template OR help within template
                if (classes.length() > 0)
                    classes.append(' ');
                classes.append("xforms-disabled");
            }

            // LHHA name
            if (classes.length() > 0)
                classes.append(' ');
            classes.append("xforms-");
            classes.append(lhhaType.name().toLowerCase());

            // We handle null attributes as well because we want a placeholder for "alert" even if there is no xf:alert
            final Attributes newAttributes = (staticLHHAAttributes != null) ? staticLHHAAttributes
                    : new AttributesImpl();

            lhhaAnalysis.encodeAndAppendAppearances(classes);

            outputLabelFor(handlerContext, getIdClassXHTMLAttributes(newAttributes, classes.toString(), null),
                    targetControlEffectiveId, forEffectiveId, lhhaType, elementName, labelHintHelpAlertValue,
                    mustOutputHTMLFragment, isExternal);
        }
    }
}

From source file:org.orbeon.oxf.xforms.XFormsModelSchemaValidator.java

private boolean validateElement(final Element element, final Acceptor acceptor, final IDConstraintChecker icc,
        final boolean isReportErrors) {

    boolean isElementValid = true;

    // Create StartTagInfo
    final StartTagInfo startTagInfo;
    {/*from  w w  w.  j a  va 2s.com*/
        final String uri = element.getNamespaceURI();
        final String name = element.getName();
        final String qName = element.getQualifiedName();
        final List attributesList = element.attributes();
        final AttributesImpl attributes = new AttributesImpl();

        for (Object anAttributesList : attributesList) {
            final Attribute attribute = (Attribute) anAttributesList;
            final String attributeURI = attribute.getNamespaceURI();
            final String attributeName = attribute.getName();
            final String attributeQName = attribute.getQualifiedName();
            final String attributeValue = attribute.getValue();
            attributes.addAttribute(attributeURI, attributeName, attributeQName, null, attributeValue);
        }
        validationContext.setCurrentElement(element);
        startTagInfo = new StartTagInfo(uri, name, qName, attributes, validationContext);
    }

    final StringRef stringRef = new StringRef();

    // Get child acceptor
    final Acceptor childAcceptor;
    {
        Acceptor tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, null);
        if (tempChildAcceptor == null) {
            if (isReportErrors) {
                tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, stringRef);
                addSchemaError(element, stringRef.str);
                isElementValid = false;
            } else {
                return false;
            }
        }
        childAcceptor = tempChildAcceptor;
    }

    // Handle id errors
    if (icc != null && isReportErrors) {
        icc.onNextAcceptorReady(startTagInfo, childAcceptor, element);
        isElementValid &= handleIDErrors(icc);
    }

    // Validate children
    final DatatypeRef datatypeRef = new DatatypeRef();
    final boolean childrenValid = validateChildren(element, childAcceptor, startTagInfo, icc, datatypeRef,
            isReportErrors);
    if (!childrenValid) {
        if (isReportErrors)
            isElementValid = false;
        else
            return false;
    }

    // TODO: MSV doesn't allow getting the type if validity check fails. However, we would like to obtain datatype validity in XForms.
    if (!childAcceptor.isAcceptState(null)) {
        if (isReportErrors) {
            childAcceptor.isAcceptState(stringRef);
            addSchemaError(element, stringRef.str);
            isElementValid = false;
        } else {
            return false;
        }
    } else {
        // Attempt to set datatype name
        setDataType(datatypeRef, element);
    }

    // Handle id errors
    if (icc != null && isReportErrors) {
        icc.endElement(element, datatypeRef.types);
        isElementValid &= handleIDErrors(icc);
    }

    // Get back to parent acceptor
    if (!acceptor.stepForward(childAcceptor, null)) {
        if (isReportErrors) {
            acceptor.stepForward(childAcceptor, stringRef);
            addSchemaError(element, stringRef.str);
            isElementValid = false;
        } else {
            return false;
        }
    }

    if (isReportErrors) {
        // Element may be invalid or not
        return isElementValid;
    } else {
        // This element is valid
        return true;
    }
}

From source file:org.programmatori.domotica.own.plugin.map.Map.java

private void createStatusFile(String fileName) {
    StreamResult streamResult = new StreamResult(new File(fileName));

    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler hd = null;
    try {//  w  w w .jav a  2 s  .  c om
        hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
    Transformer serializer = hd.getTransformer();

    serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    //serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "users.dtd");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    //serializer.setOutputProperty( XalanOutputKeys.OUTPUT_PROP_INDENT_AMOUNT, "2" );

    hd.setResult(streamResult);
    try {
        hd.startDocument();

        AttributesImpl attrs = new AttributesImpl();
        hd.startElement("", "", "home", attrs);

        hd.startElement("", "", "version", attrs);
        hd.characters("2.0".toCharArray(), 0, 3);
        hd.endElement("", "", "version");

        attrs.clear();
        attrs.addAttribute("", "", "unit", "CDATA", "min");
        hd.startElement("", "", "statusSave", attrs);
        hd.characters("10".toCharArray(), 0, 2);
        hd.endElement("", "", "statusSave");

        // ----------------------------------------- Area
        for (Iterator<Integer> iterAree = localBus.keySet().iterator(); iterAree.hasNext();) {
            Integer area = (Integer) iterAree.next();

            attrs.clear();
            attrs.addAttribute("", "", "id", "CDATA", area.toString());
            attrs.addAttribute("", "", "name", "CDATA", Config.getInstance().getRoomName(area));
            hd.startElement("", "", "area", attrs);

            // ----------------------------------------- Component
            Set<SCSComponent> rooms = localBus.get(area);
            for (Iterator<SCSComponent> iterRoom = rooms.iterator(); iterRoom.hasNext();) {
                SCSComponent c = (SCSComponent) iterRoom.next();
                log.info("PL: " + c.getStatus().getWhere().getPL() + "("
                        + Config.getInstance().getWhoDescription(c.getStatus().getWho().getMain()) + ")");

                attrs.clear();
                attrs.addAttribute("", "", "type", "CDATA",
                        Config.getInstance().getWhoDescription(c.getStatus().getWho().getMain()));
                attrs.addAttribute("", "", "pl", "CDATA", "" + c.getStatus().getWhere().getPL());
                hd.startElement("", "", "component", attrs);
                hd.characters("0".toCharArray(), 0, 1);
                hd.endElement("", "", "component");
            }
            // ----------------------------------------- Component

            hd.endElement("", "", "area");
        }
        // ----------------------------------------- End Area

        // ----------------------------------------- Scheduler
        attrs.clear();
        hd.startElement("", "", "scheduler", attrs);

        attrs.clear();
        attrs.addAttribute("", "", "time", "CDATA", "-1");
        hd.startElement("", "", "command2", attrs);
        hd.characters("*1*1*11##".toCharArray(), 0, 9);
        hd.endElement("", "", "command2");

        hd.endElement("", "", "scheduler");
        // ----------------------------------------- End Scheduler

        hd.endElement("", "", "home");
        hd.endDocument();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    //      for (Iterator<Integer> iterAree = localBus.keySet().iterator(); iterAree.hasNext();) {
    //         Integer area = (Integer) iterAree.next();
    //
    //         log.info("Room: " + area + " - " + Config.getInstance().getRoomName(area));
    //         Set<SCSComponent> rooms = localBus.get(area);
    //         for (Iterator<SCSComponent> iterRoom = rooms.iterator(); iterRoom.hasNext();) {
    //            SCSComponent c = (SCSComponent) iterRoom.next();
    //            log.info("PL: " + c.getStatus().getWhere().getPL() + "(" + Config.getInstance().getWhoDescription(c.getStatus().getWho().getMain()) + ")");
    //         }
    //      }
}

From source file:org.tizzit.util.xml.SAXHelper.java

/**
 * @since tizzit-common 15.10.2009//from  www  . j av a  2 s  .c o m
 */
public static void addElement(ContentHandler handler, String namespaceUri, String elementName,
        String elementValue) throws SAXException {
    addElement(handler, namespaceUri, elementName, elementValue, new AttributesImpl());
}