Java Code Examples for org.w3c.dom.Document#getChildNodes()

The following examples show how to use org.w3c.dom.Document#getChildNodes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DOMDocumentSerializer.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Serialize a {@link Document}.
 *
 * @param d the document to serialize.
 */
public final void serialize(Document d) throws IOException {
    reset();
    encodeHeader(false);
    encodeInitialVocabulary();

    final NodeList nl = d.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        final Node n = nl.item(i);
        switch (n.getNodeType()) {
            case Node.ELEMENT_NODE:
                serializeElement(n);
                break;
            case Node.COMMENT_NODE:
                serializeComment(n);
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                serializeProcessingInstruction(n);
                break;
        }
    }
    encodeDocumentTermination();
}
 
Example 2
Source File: DOMDocumentSerializer.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Serialize a {@link Document}.
 *
 * @param d the document to serialize.
 */
public final void serialize(Document d) throws IOException {
    reset();
    encodeHeader(false);
    encodeInitialVocabulary();

    final NodeList nl = d.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        final Node n = nl.item(i);
        switch (n.getNodeType()) {
            case Node.ELEMENT_NODE:
                serializeElement(n);
                break;
            case Node.COMMENT_NODE:
                serializeComment(n);
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                serializeProcessingInstruction(n);
                break;
        }
    }
    encodeDocumentTermination();
}
 
Example 3
Source File: DOMDocumentSerializer.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Serialize a {@link Document}.
 *
 * @param d the document to serialize.
 */
public final void serialize(Document d) throws IOException {
    reset();
    encodeHeader(false);
    encodeInitialVocabulary();

    final NodeList nl = d.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        final Node n = nl.item(i);
        switch (n.getNodeType()) {
            case Node.ELEMENT_NODE:
                serializeElement(n);
                break;
            case Node.COMMENT_NODE:
                serializeComment(n);
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                serializeProcessingInstruction(n);
                break;
        }
    }
    encodeDocumentTermination();
}
 
Example 4
Source File: XMP.java    From icafe with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Merge the standard XMP and the extended XMP DOM
 * <p>
 * This is a very expensive operation, avoid if possible
 * 
 * @return a merged Document for the entire XMP data with the GUID from the standard XMP document removed
 */
public Document getMergedDocument() {
	if(mergedXmpDocument != null)
		return mergedXmpDocument;
	else if(getExtendedXmpDocument() != null) { // Merge document
		mergedXmpDocument = XMLUtils.createDocumentNode();
		Document rootDoc = getXmpDocument();
		NodeList children = rootDoc.getChildNodes();
		for(int i = 0; i< children.getLength(); i++) {
			Node importedNode = mergedXmpDocument.importNode(children.item(i), true);
			mergedXmpDocument.appendChild(importedNode);
		}
		// Remove GUID from the standard XMP
		XMLUtils.removeAttribute(mergedXmpDocument, "rdf:Description", "xmpNote:HasExtendedXMP");
		// Copy all the children of rdf:RDF element
		NodeList list = extendedXmpDocument.getElementsByTagName("rdf:RDF").item(0).getChildNodes();
		Element rdf = (Element)(mergedXmpDocument.getElementsByTagName("rdf:RDF").item(0));
	  	for(int i = 0; i < list.getLength(); i++) {
    		Node curr = list.item(i);
    		Node newNode = mergedXmpDocument.importNode(curr, true);
   			rdf.appendChild(newNode);
    	}
    	return mergedXmpDocument;
	} else
		return getXmpDocument();
}
 
Example 5
Source File: DOMDocumentSerializer.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Serialize a {@link Document}.
 *
 * @param d the document to serialize.
 */
public final void serialize(Document d) throws IOException {
    reset();
    encodeHeader(false);
    encodeInitialVocabulary();

    final NodeList nl = d.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        final Node n = nl.item(i);
        switch (n.getNodeType()) {
            case Node.ELEMENT_NODE:
                serializeElement(n);
                break;
            case Node.COMMENT_NODE:
                serializeComment(n);
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                serializeProcessingInstruction(n);
                break;
        }
    }
    encodeDocumentTermination();
}
 
Example 6
Source File: XmlUtils.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Print nodes of a {@link Document} recursively to the local logger.
 *
 * @param doc the document to print
 */
public static void printNodes(Document doc) {
    NodeList children = doc.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node instanceof Element) printNode((Element) node);
    }
}
 
Example 7
Source File: OpensongParser.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<SongDisplayable> getSongs(File location, StatusPanel statusPanel) throws IOException {
    try (ZipFile file = new ZipFile(location, Charset.forName("Cp437"))) {
        List<SongDisplayable> ret = new ArrayList<>();
        final Enumeration<? extends ZipEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            String fileName = null;
            try {
                final ZipEntry entry = entries.nextElement();
                fileName = entry.getName();
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(new InputSource(new UnicodeReader(file.getInputStream(entry), "UTF-8")));
                NodeList list = doc.getChildNodes();
                for (int i = 0; i < list.getLength(); i++) {
                    if (list.item(i).getNodeName().equalsIgnoreCase("song")) {
                        SongDisplayable displayable = getDisplayable(list.item(i));
                        if (displayable != null) {
                            ret.add(displayable);
                        }
                    }
                }
            } catch (IOException | ParserConfigurationException | SAXException ex) {
                LOGGER.log(Level.WARNING, "Error importing opensong: " + fileName, ex);
            }
        }
        return ret;
    }
}
 
Example 8
Source File: TestDocumentImplClone.java    From marklogic-contentpump with Apache License 2.0 5 votes vote down vote up
@Test
public void testAttributeNode() throws IOException {
    List<ExpandedTree> trees = Utils.decodeTreeData(
            new File(testData + System.getProperty("file.separator")
            		+ forest, stand), false);
        assertEquals(num, trees.size());

    StringBuilder expected = new StringBuilder();
    StringBuilder actual = new StringBuilder();
    for (int i = 0; i < trees.size(); i++) {
        ExpandedTree t = trees.get(i);
        String uri = t.getDocumentURI();
        Document doc = Utils.readXMLasDOMDocument(new File(testData, uri));
        if (doc == null) continue;
        expected.append(uri);
        NodeList children = doc.getChildNodes();
        walkDOMElem(children, expected);
        Document d = (Document) new DocumentImpl(t, 0).cloneNode(true);
        NodeList eChildren = d.getChildNodes();
        actual.append(uri);
        walkDOMElem(eChildren, actual);
        
        expected.append("\n");
        actual.append("\n");
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(expected.toString());
        LOG.debug(actual.toString());
    }
    assertEquals(expected.toString(), actual.toString());
}
 
Example 9
Source File: ManifestAttributes.java    From Box with Apache License 2.0 5 votes vote down vote up
private void parse(Document doc) {
	NodeList nodeList = doc.getChildNodes();
	for (int count = 0; count < nodeList.getLength(); count++) {
		Node node = nodeList.item(count);
		if (node.getNodeType() == Node.ELEMENT_NODE
				&& node.hasChildNodes()) {
			parseAttrList(node.getChildNodes());
		}
	}
}
 
Example 10
Source File: XmlUtils.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Replace all text values of a {@link Document} with CDATA values.
 *
 * @param doc the document to update
 */
public static void replaceTextWithCData(Document doc) {
    NodeList children = doc.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        XmlUtils.replaceTextWithCData(doc, children.item(i));
    }
}
 
Example 11
Source File: XmlUtils.java    From Rails with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Opens and parses an xml file. Searches the root level of the file for an
 * element with the supplied name.
 *
 * @param fileName the name of the file to open
 * @param elementName the name of the element to find
 * @return the named element in the named file
 * @throws ConfigurationException if there is any problem opening and
 * parsing the file, or if the file does not contain a top level element
 * with the given name.
 */
public static Element findElementInFile(String fileName, String elementName)
        throws ConfigurationException {
    Document doc = null;
    try {
        // Step 1: create a DocumentBuilderFactory and setNamespaceAware
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        // Step 2: create a DocumentBuilder
        DocumentBuilder db = dbf.newDocumentBuilder();

        // Step 3: parse the input file to get a Document object
        doc = db.parse(net.sf.rails.util.Util.getStreamForFile(fileName));

    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new ConfigurationException("Could not read/parse " + fileName
                                         + " to find element "
                                         + elementName, e);
    }

    if (doc == null) {
        throw new ConfigurationException("Cannot find file " + fileName);
    }

    // Now find the named Element
    NodeList nodeList = doc.getChildNodes();
    for (int iNode = 0; (iNode < nodeList.getLength()); iNode++) {
        Node childNode = nodeList.item(iNode);
        if ((childNode != null)
            && (childNode.getNodeName().equals(elementName))
            && (childNode.getNodeType() == Node.ELEMENT_NODE)) {
            return (Element) childNode;
        }
    }
    throw new ConfigurationException("Could not find " + elementName
                                     + " in " + fileName);
}
 
Example 12
Source File: JTidyHTMLParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void parse( URL pageURL, String pageText, DocumentAdapter adapter ) throws IOException, SAXException {
    try {
        Document jtidyDocument = getParser( pageURL ).parseDOM( new ByteArrayInputStream( pageText.getBytes( UTF_ENCODING ) ), null );
        HTMLDocument htmlDocument = new HTMLDocumentImpl();
        NodeList nl = jtidyDocument.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node importedNode = nl.item(i);
            if (importedNode.getNodeType() != Node.DOCUMENT_TYPE_NODE) htmlDocument.appendChild( htmlDocument.importNode( importedNode, true ) );
        }
        adapter.setDocument( htmlDocument );
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException( "UTF-8 encoding failed" );
    }
}
 
Example 13
Source File: TestDocumentImpl.java    From marklogic-contentpump with Apache License 2.0 5 votes vote down vote up
@Test
public void testPreviousSibling() throws IOException {
    List<ExpandedTree> trees = Utils.decodeTreeData(
        new File(testData + System.getProperty("file.separator")
        		+ forest, stand), false);
    assertEquals(num, trees.size());

    StringBuilder expected = new StringBuilder();
    StringBuilder actual = new StringBuilder();
    for (int i = 0; i < trees.size(); i++) {
        ExpandedTree t = trees.get(i);
        String uri = t.getDocumentURI();
        if (uri.equals("hc_staff.xml"))
            continue;
        Document doc = Utils.readXMLasDOMDocument(new File(testData, uri));
    	if (doc == null) continue;
    	expected.append(uri);
        NodeList children = doc.getChildNodes();
        walkDOMPreviousSibling(children, expected);
        DocumentImpl d = new DocumentImpl(t, 0);
        NodeList eChildren = d.getChildNodes();
        actual.append(uri);
        walkDOMPreviousSibling (eChildren, actual);
        
        expected.append("\n");
        actual.append("\n");
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(expected.toString());
        LOG.debug(actual.toString());
    }
    assertEquals(expected.toString(), actual.toString());
}
 
Example 14
Source File: TestDocumentImplClone.java    From marklogic-contentpump with Apache License 2.0 5 votes vote down vote up
@Test
public void testParent() throws IOException {
    List<ExpandedTree> trees = Utils.decodeTreeData(
            new File(testData + System.getProperty("file.separator")
            		+ forest, stand), false);
        assertEquals(num, trees.size());

    StringBuilder expected = new StringBuilder();
    StringBuilder actual = new StringBuilder();
    for (int i = 0; i < trees.size(); i++) {
        ExpandedTree t = trees.get(i);
        String uri = t.getDocumentURI();
        
        Document doc = Utils.readXMLasDOMDocument(new File(testData, uri));
    	if (doc == null) continue;
    	expected.append(uri);
        NodeList children = doc.getChildNodes();
        walkDOMParent(children, expected);
        Document d = (Document) new DocumentImpl(t, 0).cloneNode(true);
        NodeList eChildren = d.getChildNodes();
        actual.append(uri);
        walkDOMParent (eChildren, actual);
        
        expected.append("\n");
        actual.append("\n");
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(expected.toString());
        LOG.debug(actual.toString());
    }
    assertEquals(expected.toString(), actual.toString());
}
 
Example 15
Source File: DocumentBuilderSafeProperty.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void print(Document doc) {
    NodeList nodeList = doc.getChildNodes();
    for(int i=0 ; i<nodeList.getLength() ;i++ ) {
        Node n = nodeList.item(i);
        System.out.println(n.getTextContent());
    }
}
 
Example 16
Source File: TestDocumentImplClone.java    From marklogic-contentpump with Apache License 2.0 5 votes vote down vote up
@Test
public void testAttributes() throws IOException {
    List<ExpandedTree> trees = Utils.decodeTreeData(
            new File(testData + System.getProperty("file.separator")
            		+ forest, stand), false);
        assertEquals(num, trees.size());

    Set<String> expectedAttrSet = new HashSet<String>();
    Set<String> actualAttrSet = new HashSet<String>();
    for (int i = 0; i < trees.size(); i++) {
        ExpandedTree t = trees.get(i);
        String uri = t.getDocumentURI();
        expectedAttrSet.add(uri);
        actualAttrSet.add(uri);
        Document doc = Utils.readXMLasDOMDocument(new File(testData, uri));
    	if (doc == null) continue;
        NodeList children = doc.getChildNodes();
        walkDOMAttr(children, expectedAttrSet);
        Document d = (Document) new DocumentImpl(t, 0).cloneNode(true);
        NodeList eChildren = d.getChildNodes();
        walkDOMAttr (eChildren, actualAttrSet);
    }
    for(String s : expectedAttrSet) {
        if(actualAttrSet.contains(s) == false && expectedMissingNSDecl.contains(s) == false) {
            if (LOG.isDebugEnabled()) 
                LOG.debug("NOT_FOUND:" + s);
            assertTrue(actualAttrSet.contains(s));
        }
    }

}
 
Example 17
Source File: JaxpResponse.java    From XACML with MIT License 4 votes vote down vote up
/**
 * Creates a new <code>JaxpResponse</code> by loading it from an XML <code>File</code>.
 * 
 * @param fileXmlResponse the <code>File</code> containing the Response XML
 * @return a new <code>JaxpResponse</code> generated by parsing the given XML file 
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 * @throws JAXBException
 */
public static JaxpResponse load(File fileXmlResponse) throws ParserConfigurationException, IOException, SAXException, JAXBException {
	if (fileXmlResponse == null) {
		throw new NullPointerException("Null File");
	}
	
   	/*
   	 * Create XML document factory and builder
   	 */
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
       documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
	
	/*
	 * Parse the file into a Document
	 */
	Document	document	= documentBuilder.parse(fileXmlResponse);
	if (document == null) {
		logger.error("No Document returned parsing {}", fileXmlResponse.getAbsolutePath());
		return null;
	}
	
	NodeList	nodeListRoot	= document.getChildNodes();
	if (nodeListRoot == null || nodeListRoot.getLength() == 0) {
		logger.warn("No child elements of the XML document");
		return null;
	}
	Node		nodeRoot		= nodeListRoot.item(0);
	if (nodeRoot == null || nodeRoot.getNodeType() != Node.ELEMENT_NODE) {
		logger.warn("Root of the document is not an ELEMENT");
		return null;
	}
	
	JAXBContext 				context 			= JAXBContext.newInstance(ResponseType.class);
	Unmarshaller 				unmarshaller 		= context.createUnmarshaller();
	JAXBElement<ResponseType>	jaxbElementResponse = unmarshaller.unmarshal((Element)nodeRoot, ResponseType.class);
	if (jaxbElementResponse == null || jaxbElementResponse.getValue() == null) {
		logger.error("JAXB unmarshalling did not return a ResponseType node");
		return null;
	}
	return JaxpResponse.newInstance(jaxbElementResponse.getValue());
	
}
 
Example 18
Source File: FixUtil.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public static void parseXmlFields(String content, IMessage xmlMessage, IDictionaryStructure dictionary,
                                  IFieldStructure messageStructure, DocumentBuilderFactory documentFactory,
                                  boolean parseFieldsByDictionary)
        throws IOException, SAXException, ParserConfigurationException, MessageConvertException {

    DocumentBuilder docBuilder = documentFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new InputSource(new StringReader(content)));

    NodeList list = document.getChildNodes();

    for (int i = 0; i < list.getLength(); i++) {
        NodeList insideList = list.item(i).getChildNodes();

        for (int j = 0; j < insideList.getLength(); j++) {
            if (!insideList.item(j).hasAttributes()) {
                continue;
            }

            Node nameNode = insideList.item(j).getAttributes().getNamedItem("name");
            Node valueNode = insideList.item(j).getAttributes().getNamedItem("value");

            String fieldName = nameNode.getNodeValue().replaceAll(" ", "");
            String fieldValue = valueNode.getNodeValue().trim();

            if (StringUtils.isNotEmpty(fieldName) && StringUtils.isNotEmpty(fieldValue)) {
                if (parseFieldsByDictionary) {

                    IFieldStructure fieldStructure = messageStructure.getFields().get(fieldName);
                    if (fieldStructure == null) {
                        fieldStructure = dictionary.getFields().get(fieldName);
                    }

                    if (fieldStructure != null && !fieldStructure.isComplex()) {
                        try {
                            switch (fieldStructure.getJavaType()) {
                                case JAVA_LANG_BOOLEAN:
                                    xmlMessage.addField(fieldName, BooleanConverter.convert(fieldValue));
                                    break;
                                case JAVA_LANG_CHARACTER:
                                    xmlMessage.addField(fieldName, fieldValue.charAt(0));
                                    break;
                                case JAVA_LANG_BYTE:
                                    xmlMessage.addField(fieldName, Byte.valueOf(fieldValue));
                                    break;
                                case JAVA_LANG_SHORT:
                                    xmlMessage.addField(fieldName, Short.valueOf(fieldValue));
                                    break;
                                case JAVA_LANG_INTEGER:
                                    xmlMessage.addField(fieldName, Integer.valueOf(fieldValue));
                                    break;
                                case JAVA_LANG_LONG:
                                    xmlMessage.addField(fieldName, Long.valueOf(fieldValue));
                                    break;
                                case JAVA_LANG_FLOAT:
                                    xmlMessage.addField(fieldName, Float.valueOf(fieldValue));
                                    break;
                                case JAVA_LANG_DOUBLE:
                                    xmlMessage.addField(fieldName, Double.valueOf(fieldValue));
                                    break;
                                case JAVA_MATH_BIG_DECIMAL:
                                    xmlMessage.addField(fieldName, new BigDecimal(fieldValue));
                                    break;
                                case JAVA_LANG_STRING:
                                    xmlMessage.addField(fieldName, fieldValue);
                                    break;
                                case JAVA_TIME_LOCAL_DATE_TIME:
                                    LocalDateTime dateTime = DateTimeUtility.toLocalDateTime(
                                            UtcTimestampConverter.convert(fieldValue));
                                    xmlMessage.addField(fieldName, dateTime);
                                    break;
                                case JAVA_TIME_LOCAL_TIME:
                                    LocalTime time = DateTimeUtility.toLocalTime(
                                            UtcTimeOnlyConverter.convert(fieldValue));
                                    xmlMessage.addField(fieldName, time);
                                    break;
                                case JAVA_TIME_LOCAL_DATE:
                                    LocalDate date = DateTimeUtility.toLocalDate(
                                            UtcDateOnlyConverter.convert(fieldValue));
                                    xmlMessage.addField(fieldName, date);
                                    break;
                                default:
                                    xmlMessage.addField(fieldName, fieldValue);
                                    break;
                            }
                        } catch (FieldException | FieldConvertError e) {
                            throw new MessageConvertException(
                                    String.format("Can not parse [%s] value for [%s] field", fieldName, fieldValue), "", e);
                        }
                    }
                } else {
                    xmlMessage.addField(fieldName, fieldValue);
                }
            }
        }
    }
}
 
Example 19
Source File: JpegXMP.java    From icafe with Eclipse Public License 1.0 4 votes vote down vote up
public void write(OutputStream os) throws IOException {		
	Document xmpDoc = getXmpDocument();
	NodeList list = xmpDoc.getChildNodes();
	boolean foundPI = false;
       for (int j = 0; j < list.getLength(); j++) {
           Node currentNode = list.item(j);
           if (currentNode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE && currentNode.getNodeName().equalsIgnoreCase("xpacket")) {
           	foundPI = true;
           	break;
           }            
       }
       if(!foundPI) {
       	// Add packet wrapper to the XMP document
   		// Add PI at the beginning and end of the document, we will support only UTF-8, no BOM
       	XMLUtils.insertLeadingPI(xmpDoc, "xpacket", "begin='?' id='W5M0MpCehiHzreSzNTczkc9d'");
   		XMLUtils.insertTrailingPI(xmpDoc, "xpacket", "end='r'");
       }
     	// Serialize XMP to byte array
	byte[] xmp = XMLUtils.serializeToByteArray(xmpDoc);
	if(xmp.length > MAX_XMP_CHUNK_SIZE) {
		Document extendedXMPDoc = XMLUtils.createDocumentNode();
		// Copy all the children of rdf:RDF element
  		Node xmpRDF = xmpDoc.getElementsByTagName("rdf:RDF").item(0);	  		 
		NodeList nodes = xmpRDF.getChildNodes();
		Element extendedRDF = extendedXMPDoc.createElement("rdf:RDF");
		extendedRDF.setAttribute("xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
		extendedXMPDoc.appendChild(extendedRDF);
	  	for(int i = 0; i < nodes.getLength(); i++) {
	  		Node curr = extendedXMPDoc.importNode(nodes.item(i), true);
    		extendedRDF.appendChild(curr);
    	}
	  	int numOfItems = nodes.getLength();
	  	for(int i = 1; i <= numOfItems; i++) {
	  		xmpRDF.removeChild(nodes.item(numOfItems - i));
    	}		  	
	  	xmp = XMLUtils.serializeToByteArray(xmpDoc);
	  	setExtendedXMPData(XMLUtils.serializeToByteArray(extendedXMPDoc));
	}
	String guid = null;
	byte[] extendedXmp = getExtendedXmpData();	     
	if(extendedXmp != null) { // We have ExtendedXMP
		if(XMLUtils.getAttribute(xmpDoc, "rdf:Description", "xmpNote:HasExtendedXMP").length() == 0) {
			guid = StringUtils.generateMD5(extendedXmp);
			Element node = XMLUtils.createElement(xmpDoc, "rdf:Description");
			node.setAttribute("xmlns:xmpNote", "http://ns.adobe.com/xmp/extension/");
			node.setAttribute("xmpNote:HasExtendedXMP", guid);
			xmpDoc.getElementsByTagName("rdf:RDF").item(0).appendChild(node);
			xmp = XMLUtils.serializeToByteArray(xmpDoc);
		} else {
			guid = XMLUtils.getAttribute(xmpDoc, "rdf:Description", "xmpNote:HasExtendedXMP");
		}
	}	
	// Write XMP segment
	IOUtils.writeShortMM(os, Marker.APP1.getValue());
	// Write segment length
	IOUtils.writeShortMM(os, XMP_ID.length() + 2 + xmp.length);
	// Write segment data
	os.write(XMP_ID.getBytes());
	os.write(xmp);
	// Write ExtendedXMP if we have
	if(extendedXmp != null) { // We have ExtendedXMP
		int numOfChunks = extendedXmp.length / MAX_EXTENDED_XMP_CHUNK_SIZE;
		int extendedXmpLen = extendedXmp.length;
		int offset = 0;
		
		for(int i = 0; i < numOfChunks; i++) {
			IOUtils.writeShortMM(os, Marker.APP1.getValue());
			// Write segment length
			IOUtils.writeShortMM(os, 2 + XMP_EXT_ID.length() + GUID_LEN + 4 + 4 + MAX_EXTENDED_XMP_CHUNK_SIZE);
			// Write segment data
			os.write(XMP_EXT_ID.getBytes());
			os.write(guid.getBytes());
			IOUtils.writeIntMM(os, extendedXmpLen);
			IOUtils.writeIntMM(os, offset);
			os.write(ArrayUtils.subArray(extendedXmp, offset, MAX_EXTENDED_XMP_CHUNK_SIZE));
			offset += MAX_EXTENDED_XMP_CHUNK_SIZE;			
		}
		
		int leftOver = extendedXmp.length % MAX_EXTENDED_XMP_CHUNK_SIZE;
		
		if(leftOver != 0) {
			IOUtils.writeShortMM(os, Marker.APP1.getValue());
			// Write segment length
			IOUtils.writeShortMM(os, 2 + XMP_EXT_ID.length() + GUID_LEN + 4 + 4 + leftOver);
			// Write segment data
			os.write(XMP_EXT_ID.getBytes());
			os.write(guid.getBytes());
			IOUtils.writeIntMM(os, extendedXmpLen);
			IOUtils.writeIntMM(os, offset);
			os.write(ArrayUtils.subArray(extendedXmp, offset, leftOver));
		}
	}
}
 
Example 20
Source File: ResponseProcessor.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {
    ResponseProcessor.LOG.debug("Processing the response...");
    final InvokeResponse invokeResponse = new InvokeResponse();

    if (exchange.getIn().getBody() instanceof HashMap) {

        ResponseProcessor.LOG.debug("Response is of type HashMap.");

        @SuppressWarnings("unchecked") final HashMap<String, String> responseMap = exchange.getIn().getBody(HashMap.class);

        final ParamsMap paramsMap = new ParamsMap();
        for (final Entry<String, String> entry : responseMap.entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();
            ParamsMapItemType mapItem = new ParamsMapItemType();
            mapItem.setKey(key);
            mapItem.setValue(value);
            paramsMap.getParam().add(mapItem);
        }
        invokeResponse.setParams(paramsMap);
        exchange.getIn().setBody(invokeResponse);
    } else if (exchange.getIn().getBody() instanceof Document) {

        ResponseProcessor.LOG.debug("Response is of type Document.");

        final Document responseDoc = exchange.getIn().getBody(Document.class);
        final NodeList nodeList = responseDoc.getChildNodes();

        final Doc ar = new Doc();

        for (int i = 0; i < nodeList.getLength(); i++) {
            ar.setAny((Element) nodeList.item(i));
        }
        invokeResponse.setDoc(ar);
        exchange.getIn().setBody(invokeResponse);
    }

    // Async
    if (exchange.getIn().getHeader("MessageID") != null) {
        final String messageID = exchange.getIn().getHeader("MessageID", String.class);

        exchange.getIn().setHeader("operationName", "callback");
        exchange.getIn().setHeader("operationNamespace", "http://siserver.org/wsdl");

        exchange.getIn().setHeader("RelatesTo", messageID);
        invokeResponse.setMessageID(messageID);
    }
}