List of usage examples for org.w3c.dom Document normalizeDocument
public void normalizeDocument();
From source file:de.qucosa.webapi.v1.DocumentResource.java
@RequestMapping(value = "/document/{qucosaID}", method = RequestMethod.GET) public ResponseEntity<String> getDocument(@PathVariable String qucosaID) throws FedoraClientException, IOException, SAXException, TransformerException { String pid = "qucosa:".concat(qucosaID); InputStream dsContent = fedoraRepository.getDatastreamContent(pid, DSID_QUCOSA_XML); Document doc = documentBuilder.parse(dsContent); doc.normalizeDocument(); removeEmtpyFields(doc);// w ww . jav a 2 s .c o m removeFileElementsWithoutCorrespondingDatastream(pid, doc); return new ResponseEntity<>(DOMSerializer.toString(doc), HttpStatus.OK); }
From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.spec.DuplicateGerritListenersPreloadedProjectHudsonTestCase.java
/** * Adds a new gerritProject configuration to the gived XML document. * Assumes that the document is structured like the original project config.xml in the LocalData for this class. * * @param gerritProjectPattern the {@link GerritProject#pattern} to set. * @param document the config.xml * @return the new xml/*from w w w . j a v a2s.c om*/ * @throws Exception if so */ private String changeConfigXml(String gerritProjectPattern, Document document) throws Exception { Node projects = xPath(document, "/project/triggers/*[1]/gerritProjects"); String tagName = "com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data.GerritProject"; Node newProject = document.createElement(tagName); setXmlConfig(document, newProject, "ANT", gerritProjectPattern); Node branches = document.createElement("branches"); tagName = "com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data.Branch"; Node branch = document.createElement(tagName); setXmlConfig(document, branch, "ANT", "**"); branches.appendChild(branch); newProject.appendChild(branches); projects.appendChild(newProject); document.normalizeDocument(); return xmlToString(document); }
From source file:org.geowebcache.jetty.RestIntegrationTest.java
private Document getResponseEntityAsXML(CloseableHttpResponse response) throws Exception { Document doc; doc = XMLUnit.buildTestDocument(new InputSource(response.getEntity().getContent())); doc.normalizeDocument(); return doc;// www . j a v a2 s . c o m }
From source file:no.digipost.api.SdpMeldingSigner.java
public Document sign(final StandardBusinessDocument sbd) { try {/*from w ww. j a va 2 s. c o m*/ PrivateKey privateKey = keystoreInfo.getPrivateKey(); X509Certificate certificate = keystoreInfo.getCertificate(); DOMResult result = new DOMResult(); Marshalling.marshal(marshaller, sbd, result); Document doc = (Document) result.getNode(); Marshalling.trimNamespaces(doc); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA256, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(Constants.RSA_SHA256, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data xd = kif.newX509Data(Collections.singletonList(certificate)); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); XMLSignature signature = fac.newXMLSignature(si, ki); Node digitalPostNode = doc.getDocumentElement().getFirstChild().getNextSibling(); Node avsenderNode = digitalPostNode.getFirstChild(); DOMSignContext dsc = new DOMSignContext(privateKey, digitalPostNode, avsenderNode); signature.sign(dsc); doc.normalizeDocument(); return doc; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnrecoverableKeyException e) { throw new RuntimeException(e); } catch (XMLSignatureException e) { throw new RuntimeException(e); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (MarshalException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private Tuple<Collection<String>> updateWith(Document targetDocument, final Document updateDocument, List<FileUpdateOperation> fileUpdateOperations) throws XPathExpressionException, IOException, FedoraClientException { Element targetRoot = (Element) targetDocument.getElementsByTagName("Opus_Document").item(0); Element updateRoot = (Element) updateDocument.getElementsByTagName("Opus_Document").item(0); Set<String> distinctUpdateFieldList = new LinkedHashSet<>(); NodeList updateFields = updateRoot.getChildNodes(); for (int i = 0; i < updateFields.getLength(); i++) { distinctUpdateFieldList.add(updateFields.item(i).getNodeName()); }// w ww. java2 s . com for (String fn : distinctUpdateFieldList) { // cannot use getElementsByTagName() here because it searches recursively for (Node victim : getChildNodesByName(targetRoot, fn)) { if (!victim.getLocalName().equals("File")) { targetRoot.removeChild(victim); } } } for (int i = 0; i < updateFields.getLength(); i++) { // Update node needs to be cloned, otherwise it will // be removed from updateFields by adoptNode(). Node updateNode = updateFields.item(i).cloneNode(true); if (updateNode.hasChildNodes() && !updateNode.getLocalName().equals("File")) { targetDocument.adoptNode(updateNode); targetRoot.appendChild(updateNode); } } List<String> purgeDatastreamList = new LinkedList<>(); if ((Boolean) xPath.evaluate("//File", updateDocument, XPathConstants.BOOLEAN)) { updateFileElementsInPlace(targetDocument, updateDocument, fileUpdateOperations, targetRoot, updateRoot, purgeDatastreamList); } targetDocument.normalizeDocument(); return new Tuple<>(distinctUpdateFieldList, purgeDatastreamList); }
From source file:eu.europa.ec.markt.dss.applet.view.validationpolicy.EditView.java
private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath, final XmlDomAdapterNode clickedItem, final JTree tree) { final Element clickedElement = (Element) clickedItem.node; // popup menu for list -> add final JPopupMenu popup = new JPopupMenu(); //delete node final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE")); menuItemToDelete.addActionListener(new ActionListener() { @Override//w w w . jav a2 s. co m public void actionPerformed(ActionEvent actionEvent) { // find the order# of the child to delete final int index = clickedItem.getParent().index(clickedItem); Node oldChild = clickedElement.getParentNode().removeChild(clickedElement); if (index > -1) { validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild); } } }); popup.add(menuItemToDelete); //Add node/value final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree(); final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree); for (final XsdNode xsdChild : children) { final String xmlName = xsdChild.getLastNameOfPath(); final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " " + xsdChild.getType().toString().toLowerCase() + ")"); popup.add(menuItem); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { Document document = getModel().getValidationPolicy().getDocument(); final Node newElement; if (xsdChild.getType() == XsdNodeType.TEXT) { // TEXT element always appended (last child) newElement = clickedElement.appendChild(document.createTextNode("VALUE")); } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) { newElement = document.createAttributeNS(null, xmlName); ((Attr) newElement).setValue("VALUE"); clickedElement.setAttributeNode((Attr) newElement); } else if (xsdChild.getType() == XsdNodeType.ELEMENT) { final Element childToAdd = document .createElementNS("http://dss.markt.ec.europa.eu/validation/diagnostic", xmlName); // find the correct possition to add the child // Get all allowed children Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree); boolean toAddSeen = false; Element elementIsToAddBeforeThisOne = null; for (final XsdNode allowed : childrenMap.keySet()) { if (!toAddSeen && allowed == xsdChild) { toAddSeen = true; continue; } if (toAddSeen) { final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS( "http://dss.markt.ec.europa.eu/validation/diagnostic", allowed.getLastNameOfPath()); if (elementsByTagNameNS.getLength() > 0) { // we found an element that is supposed to be after the one to add elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0); break; } } } if (elementIsToAddBeforeThisOne != null) { newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne); } else { newElement = clickedElement.appendChild(childToAdd); } } else { throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType()); } document.normalizeDocument(); int indexOfAddedItem = 0; final int childCount = clickedItem.childCount(); for (int i = 0; i < childCount; i++) { if (clickedItem.child(i).node == newElement) { indexOfAddedItem = i; break; } } TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath, new int[] { indexOfAddedItem }, new Object[] { newElement }); validationPolicyTreeModel.fireTreeNodesInserted(event); tree.expandPath(selectedPath); //Update model getModel().getValidationPolicy().setXmlDom(new XmlDom(document)); } }); } popup.show(tree, mouseEvent.getX(), mouseEvent.getY()); }
From source file:eu.europa.esig.dss.applet.view.validationpolicy.EditView.java
private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath, final XmlDomAdapterNode clickedItem, final JTree tree) { final Element clickedElement = (Element) clickedItem.node; // popup menu for list -> add final JPopupMenu popup = new JPopupMenu(); //delete node final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE")); menuItemToDelete.addActionListener(new ActionListener() { @Override//w ww . j av a 2 s . c o m public void actionPerformed(ActionEvent actionEvent) { // find the order# of the child to delete final int index = clickedItem.getParent().index(clickedItem); Node oldChild = clickedElement.getParentNode().removeChild(clickedElement); if (index > -1) { validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild); } } }); popup.add(menuItemToDelete); //Add node/value final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree(); final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree); for (final XsdNode xsdChild : children) { final String xmlName = xsdChild.getLastNameOfPath(); final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " " + xsdChild.getType().toString().toLowerCase() + ")"); popup.add(menuItem); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { Document document = getModel().getValidationPolicy().getDocument(); final Node newElement; if (xsdChild.getType() == XsdNodeType.TEXT) { // TEXT element always appended (last child) newElement = clickedElement.appendChild(document.createTextNode("VALUE")); } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) { newElement = document.createAttributeNS(null, xmlName); ((Attr) newElement).setValue("VALUE"); clickedElement.setAttributeNode((Attr) newElement); } else if (xsdChild.getType() == XsdNodeType.ELEMENT) { final Element childToAdd = document .createElementNS("http://dss.esig.europa.eu/validation/diagnostic", xmlName); // find the correct possition to add the child // Get all allowed children Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree); boolean toAddSeen = false; Element elementIsToAddBeforeThisOne = null; for (final XsdNode allowed : childrenMap.keySet()) { if (!toAddSeen && (allowed == xsdChild)) { toAddSeen = true; continue; } if (toAddSeen) { final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS( "http://dss.esig.europa.eu/validation/diagnostic", allowed.getLastNameOfPath()); if (elementsByTagNameNS.getLength() > 0) { // we found an element that is supposed to be after the one to add elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0); break; } } } if (elementIsToAddBeforeThisOne != null) { newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne); } else { newElement = clickedElement.appendChild(childToAdd); } } else { throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType()); } document.normalizeDocument(); int indexOfAddedItem = 0; final int childCount = clickedItem.childCount(); for (int i = 0; i < childCount; i++) { if (clickedItem.child(i).node == newElement) { indexOfAddedItem = i; break; } } TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath, new int[] { indexOfAddedItem }, new Object[] { newElement }); validationPolicyTreeModel.fireTreeNodesInserted(event); tree.expandPath(selectedPath); //Update model getModel().getValidationPolicy().setXmlDom(new XmlDom(document)); } }); } popup.show(tree, mouseEvent.getX(), mouseEvent.getY()); }
From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java
/** * ?SAML????.//from www . j ava2 s. c om * @return SAML */ public String toSamlString() { /* * Creation of SAML2.0 Document * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.newDocument(); Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion"); doc.appendChild(assertion); assertion.setAttribute("ID", this.id); assertion.setAttribute("Version", "2.0"); // Dummy Date DateTime dateTime = new DateTime(this.issuedAt); assertion.setAttribute("IssueInstant", dateTime.toString()); // Issuer Element issuer = doc.createElement("Issuer"); issuer.setTextContent(this.issuer); assertion.appendChild(issuer); // Subject Element subject = doc.createElement("Subject"); Element nameId = doc.createElement("NameID"); nameId.setTextContent(this.subject); Element subjectConfirmation = doc.createElement("SubjectConfirmation"); subject.appendChild(nameId); subject.appendChild(subjectConfirmation); assertion.appendChild(subject); // Conditions Element conditions = doc.createElement("Conditions"); Element audienceRestriction = doc.createElement("AudienceRestriction"); for (String aud : new String[] { this.target, this.schema }) { Element audience = doc.createElement("Audience"); audience.setTextContent(aud); audienceRestriction.appendChild(audience); } conditions.appendChild(audienceRestriction); assertion.appendChild(conditions); // AuthnStatement Element authnStmt = doc.createElement("AuthnStatement"); authnStmt.setAttribute("AuthnInstant", dateTime.toString()); Element authnCtxt = doc.createElement("AuthnContext"); Element authnCtxtCr = doc.createElement("AuthnContextClassRef"); authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"); authnCtxt.appendChild(authnCtxtCr); authnStmt.appendChild(authnCtxt); assertion.appendChild(authnStmt); // AttributeStatement Element attrStmt = doc.createElement("AttributeStatement"); Element attribute = doc.createElement("Attribute"); for (Role role : this.roleList) { Element attrValue = doc.createElement("AttributeValue"); Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); attr.setPrefix("xsi"); attr.setValue("string"); attrValue.setAttributeNodeNS(attr); attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer)); attribute.appendChild(attrValue); } attrStmt.appendChild(attribute); assertion.appendChild(attrStmt); // Normalization doc.normalizeDocument(); // Dsig?? // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement()); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); // Marshal, generate, and sign the enveloped signature. try { signature.sign(dsc); // ? return DcCoreUtils.nodeToString(doc.getDocumentElement()); } catch (MarshalException e1) { // DOM??????? throw new RuntimeException(e1); } catch (XMLSignatureException e1) { // ?????????? throw new RuntimeException(e1); } /* * ------------------------------------------------------------ * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10 * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648] * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/ * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be * line wrapped and pad characters ("=") SHOULD NOT be included. */ }
From source file:io.personium.common.auth.token.TransCellAccessToken.java
/** * ?SAML????.//from w ww. j a va2 s . c o m * @return SAML */ public String toSamlString() { /* * Creation of SAML2.0 Document * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.newDocument(); Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion"); doc.appendChild(assertion); assertion.setAttribute("ID", this.id); assertion.setAttribute("Version", "2.0"); // Dummy Date DateTime dateTime = new DateTime(this.issuedAt); assertion.setAttribute("IssueInstant", dateTime.toString()); // Issuer Element issuer = doc.createElement("Issuer"); issuer.setTextContent(this.issuer); assertion.appendChild(issuer); // Subject Element subject = doc.createElement("Subject"); Element nameId = doc.createElement("NameID"); nameId.setTextContent(this.subject); Element subjectConfirmation = doc.createElement("SubjectConfirmation"); subject.appendChild(nameId); subject.appendChild(subjectConfirmation); assertion.appendChild(subject); // Conditions Element conditions = doc.createElement("Conditions"); Element audienceRestriction = doc.createElement("AudienceRestriction"); for (String aud : new String[] { this.target, this.schema }) { Element audience = doc.createElement("Audience"); audience.setTextContent(aud); audienceRestriction.appendChild(audience); } conditions.appendChild(audienceRestriction); assertion.appendChild(conditions); // AuthnStatement Element authnStmt = doc.createElement("AuthnStatement"); authnStmt.setAttribute("AuthnInstant", dateTime.toString()); Element authnCtxt = doc.createElement("AuthnContext"); Element authnCtxtCr = doc.createElement("AuthnContextClassRef"); authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"); authnCtxt.appendChild(authnCtxtCr); authnStmt.appendChild(authnCtxt); assertion.appendChild(authnStmt); // AttributeStatement Element attrStmt = doc.createElement("AttributeStatement"); Element attribute = doc.createElement("Attribute"); for (Role role : this.roleList) { Element attrValue = doc.createElement("AttributeValue"); Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); attr.setPrefix("xsi"); attr.setValue("string"); attrValue.setAttributeNodeNS(attr); attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer)); attribute.appendChild(attrValue); } attrStmt.appendChild(attribute); assertion.appendChild(attrStmt); // Normalization doc.normalizeDocument(); // Dsig?? // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement()); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); // Marshal, generate, and sign the enveloped signature. try { signature.sign(dsc); // ? return PersoniumCoreUtils.nodeToString(doc.getDocumentElement()); } catch (MarshalException e1) { // DOM??????? throw new RuntimeException(e1); } catch (XMLSignatureException e1) { // ?????????? throw new RuntimeException(e1); } /* * ------------------------------------------------------------ * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10 * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648] * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/ * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be * line wrapped and pad characters ("=") SHOULD NOT be included. */ }
From source file:com.sms.server.service.AdaptiveStreamingService.java
public Document generateDASHPlaylist(long id, String baseUrl) { Job job = jobDao.getJobByID(id);/*from ww w. j a va 2 s. c om*/ if (job == null) { return null; } MediaElement mediaElement = mediaDao.getMediaElementByID(job.getMediaElement()); if (mediaElement == null) { return null; } AdaptiveStreamingProfile profile = getProfileByID(id); if (profile == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Unable to get transcode profile to generate manifest for job " + id, null); return null; } // Transcode Parameters Dimension resolution = transcodeService.getVideoResolution(profile.getVideoQuality(), mediaElement); String codec; String mimeType; switch (profile.getType()) { case StreamType.DASH: codec = "avc1"; mimeType = "video/MP2T"; break; case StreamType.DASH_MP4: codec = "avc1"; mimeType = "video/mp4"; break; case StreamType.DASH_WEBM: codec = "vp8"; mimeType = "video/webm"; break; default: return null; } try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Root MPD Element Document mpd = docBuilder.newDocument(); Element root = mpd.createElement("MPD"); root.setAttribute("xmnls", "urn:mpeg:dash:schema:mpd:2011"); root.setAttribute("profiles", "urn:mpeg:dash:profile:isoff-on-demand:2011"); root.setAttribute("type", "static"); root.setAttribute("mediaPresentationDuration", "PT" + mediaElement.getDuration() + "S"); root.setAttribute("minBufferTime", "PT2.0S"); mpd.appendChild(root); // Program Information Element programInformation = mpd.createElement("ProgramInformation"); root.appendChild(programInformation); // Title Element title = mpd.createElement("Title"); title.appendChild(mpd.createTextNode(mediaElement.getTitle())); programInformation.appendChild(title); // Period Element period = mpd.createElement("Period"); period.setAttribute("duration", "PT" + mediaElement.getDuration() + "S"); period.setAttribute("start", "PT0S"); root.appendChild(period); // Adaptation Set Element adaptationSet = mpd.createElement("AdaptationSet"); adaptationSet.setAttribute("bitstreamSwitching", "false"); period.appendChild(adaptationSet); // Representation Element representation = mpd.createElement("Representation"); representation.setAttribute("id", "1"); representation.setAttribute("codecs", codec); representation.setAttribute("mimeType", mimeType); representation.setAttribute("width", String.valueOf(resolution.width)); representation.setAttribute("height", String.valueOf(resolution.height)); adaptationSet.appendChild(representation); // Segment List Element segmentList = mpd.createElement("SegmentList"); segmentList.setAttribute("timescale", "1000"); segmentList.setAttribute("duration", Integer.toString(DASHTranscode.DEFAULT_SEGMENT_DURATION * 1000)); representation.appendChild(segmentList); // Initialisation Element initialisation = mpd.createElement("Initialization"); initialisation.setAttribute("sourceURL", createDASHSegmentUrl(baseUrl, job.getID(), 0)); segmentList.appendChild(initialisation); // Segment URLs for (int i = 1; i < (mediaElement.getDuration() / DASHTranscode.DEFAULT_SEGMENT_DURATION); i++) { Element segmentUrl = mpd.createElement("SegmentURL"); segmentUrl.setAttribute("media", createDASHSegmentUrl(baseUrl, job.getID(), i)); segmentList.appendChild(segmentUrl); } // Determine the duration of the final segment. Integer remainder = mediaElement.getDuration() % DASHTranscode.DEFAULT_SEGMENT_DURATION; if (remainder > 0) { Element segmentUrl = mpd.createElement("SegmentURL"); segmentUrl.setAttribute("media", createDASHSegmentUrl(baseUrl, job.getID(), mediaElement.getDuration() / HLSTranscode.DEFAULT_SEGMENT_DURATION)); segmentList.appendChild(segmentUrl); } mpd.normalizeDocument(); return mpd; } catch (ParserConfigurationException ex) { } return null; }