List of usage examples for javax.xml.parsers DocumentBuilder newDocument
public abstract Document newDocument();
From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java
/** * Convert to oai.//ww w.j a v a 2 s . c o m * * @param studyId the study id * @return the organization assigned identifier * @throws XMLUtilityException the xML utility exception * @throws ParserConfigurationException the parser configuration exception */ private OrganizationAssignedIdentifier convertToOAI(Element studyId) throws XMLUtilityException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); doc.appendChild(doc.importNode(studyId, true)); DOMBuilder jdomBuilder = new DOMBuilder(); org.jdom.Document jdomDoc = jdomBuilder.build(doc); String xmlRep = new XMLOutputter().outputString(jdomDoc); OrganizationAssignedIdentifier oai = (OrganizationAssignedIdentifier) marshaller .fromXML(new StringReader(xmlRep)); return oai; }
From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java
/** * Process study import request./*from www . ja v a2s . c o m*/ * * @param body the body * @return the sOAP message * @throws DOMException the dOM exception * @throws RuntimeException the runtime exception * @throws ParserConfigurationException the parser configuration exception * @throws C3PRCodedException the c3 pr coded exception * @throws SOAPException the sOAP exception */ private SOAPMessage processStudyImportRequest(SOAPBody body) throws DOMException, RuntimeException, ParserConfigurationException, C3PRCodedException, SOAPException { NodeList nodes = body.getElementsByTagNameNS(SERVICE_NS, IMPORT_STUDY_REQUEST); Node importStudyRequestNode = nodes.item(0); NodeList studyNodes = ((Element) importStudyRequestNode).getElementsByTagNameNS(C3PR_NS, STUDY_ELEMENT); if (studyNodes.getLength() != 1) { throw new RuntimeException("Malformed SOAP request. Please check the WSDL."); } Element study = (Element) studyNodes.item(0); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); doc.appendChild(doc.importNode(study, true)); List<Study> studies = studyXMLImporterService.importStudies(doc, new ErrorsImpl()); if (CollectionUtils.isEmpty(studies)) { throw new RuntimeException("No studies have been imported."); } return createImportStudyResponse(); }
From source file:com.commander4j.thread.AutoLabellerThread.java
public void run() { logger.debug("AutoLabeller Thread running"); setSessionID(JUnique.getUniqueID()); JDBUser user = new JDBUser(getHostID(), getSessionID()); user.setUserId("interface"); user.setPassword("interface"); user.setLoginPassword("interface"); Common.userList.addUser(getSessionID(), user); Common.sd.setData(getSessionID(), "silentExceptions", "Yes", true); Boolean dbconnected = false;/*from ww w .j a v a 2 s. c o m*/ if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) { dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID); } else { dbconnected = true; } if (dbconnected) { JDBViewAutoLabellerPrinter alp = new JDBViewAutoLabellerPrinter(getHostID(), getSessionID()); LinkedList<JDBViewAutoLabellerPrinter> autolabellerList = new LinkedList<JDBViewAutoLabellerPrinter>(); int noOfMessages = 0; while (true) { JWait.milliSec(500); if (allDone) { if (dbconnected) { Common.hostList.getHost(hostID).disconnect(getSessionID()); } return; } autolabellerList.clear(); autolabellerList = alp.getModifiedPrinterLines(); noOfMessages = autolabellerList.size(); if (noOfMessages > 0) { for (int x = 0; x < noOfMessages; x++) { JWait.milliSec(100); JDBViewAutoLabellerPrinter autolabview = autolabellerList.get(x); messageProcessedOK = true; messageError = ""; if (autolabview.getPrinterObj().isEnabled()) { logger.debug("Line =" + autolabview.getAutoLabellerObj().getLine()); logger.debug("Line Description =" + autolabview.getAutoLabellerObj().getDescription()); logger.debug("Printer ID =" + autolabview.getPrinterObj().getPrinterID()); logger.debug("Printer Enabled =" + autolabview.getPrinterObj().isEnabled()); logger.debug("Export Path =" + autolabview.getPrinterObj().getExportRealPath()); logger.debug("Export Enabled =" + autolabview.getPrinterObj().isExportEnabled()); logger.debug("Export Format =" + autolabview.getPrinterObj().getExportFormat()); logger.debug("Direct Print =" + autolabview.getPrinterObj().isDirectPrintEnabled()); logger.debug("Printer Type =" + autolabview.getPrinterObj().getPrinterType()); logger.debug("Printer IP =" + autolabview.getPrinterObj().getIPAddress()); logger.debug("Printer Port =" + autolabview.getPrinterObj().getPort()); logger.debug("Process Order =" + autolabview.getLabelDataObj().getProcessOrder()); logger.debug("Material =" + autolabview.getLabelDataObj().getMaterial()); logger.debug("Module ID =" + autolabview.getModuleObj().getModuleId()); logger.debug("Module Type =" + autolabview.getModuleObj().getType()); if (autolabview.getPrinterObj().isExportEnabled()) { String exportPath = JUtility.replaceNullStringwithBlank( JUtility.formatPath(autolabview.getPrinterObj().getExportRealPath())); if (exportPath.equals("") == false) { if (exportPath.substring(exportPath.length() - 1) .equals(File.separator) == false) { exportPath = exportPath + File.separator; } } else { exportPath = Common.interface_output_path + "Auto Labeller" + File.separator; } String exportFilename = exportPath + JUtility.removePathSeparators(autolabview.getAutoLabellerObj().getLine()) + "_" + JUtility.removePathSeparators(autolabview.getPrinterObj().getPrinterID()) + "." + autolabview.getPrinterObj().getExportFormat(); String exportFilenameTemp = exportFilename + ".out"; logger.debug("Export Filename =" + exportFilename); /* ================CSV================ */ if (autolabview.getPrinterObj().getExportFormat().equals("CSV")) { try { PreparedStatement stmt = null; ResultSet rs; String labelType = autolabview.getLabelDataObj().getLabelType(); stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()) .prepareStatement( Common.hostList.getHost(getHostID()).getSqlstatements() .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties" + "_" + labelType)); stmt.setString(1, autolabview.getAutoLabellerObj().getLine()); stmt.setString(2, autolabview.getPrinterObj().getPrinterID()); stmt.setFetchSize(50); rs = stmt.executeQuery(); logger.debug("Writing CSV"); CSVWriter writer = new CSVWriter(new FileWriter(exportFilenameTemp), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); writer.writeAll(rs, true); rs.close(); stmt.close(); writer.close(); File fromFile = new File(exportFilenameTemp); File toFile = new File(exportFilename); FileUtils.deleteQuietly(toFile); FileUtils.moveFile(fromFile, toFile); fromFile = null; toFile = null; } catch (Exception e) { messageProcessedOK = false; messageError = e.getMessage(); } } /* ================XML================ */ if (autolabview.getPrinterObj().getExportFormat().equals("XML")) { try { PreparedStatement stmt = null; ResultSet rs; stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()) .prepareStatement(Common.hostList.getHost(getHostID()) .getSqlstatements() .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties")); stmt.setString(1, autolabview.getAutoLabellerObj().getLine()); stmt.setString(2, autolabview.getPrinterObj().getPrinterID()); stmt.setFetchSize(50); rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int colCount = rsmd.getColumnCount(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element message = (Element) document.createElement("message"); Element hostUniqueID = addElement(document, "hostRef", Common.hostList.getHost(getHostID()).getUniqueID()); message.appendChild(hostUniqueID); Element messageRef = addElement(document, "messageRef", autolabview.getAutoLabellerObj().getUniqueID()); message.appendChild(messageRef); Element messageType = addElement(document, "interfaceType", "Auto Labeller Data"); message.appendChild(messageType); Element messageInformation = addElement(document, "messageInformation", "Unique ID=" + autolabview.getAutoLabellerObj().getUniqueID()); message.appendChild(messageInformation); Element messageDirection = addElement(document, "interfaceDirection", "Output"); message.appendChild(messageDirection); Element messageDate = addElement(document, "messageDate", JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime())); message.appendChild(messageDate); if (rs.first()) { Element labelData = (Element) document.createElement("LabelData"); Element row = document.createElement("Row"); labelData.appendChild(row); for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object value = rs.getObject(i); Element node = document.createElement(columnName); node.appendChild(document.createTextNode(value.toString())); row.appendChild(node); } message.appendChild(labelData); document.appendChild(message); JXMLDocument xmld = new JXMLDocument(); xmld.setDocument(document); // =============================== DOMImplementationLS DOMiLS = null; FileOutputStream FOS = null; // testing the support for DOM // Load and Save if ((document.getFeature("Core", "3.0") != null) && (document.getFeature("LS", "3.0") != null)) { DOMiLS = (DOMImplementationLS) (document.getImplementation()) .getFeature("LS", "3.0"); // get a LSOutput object LSOutput LSO = DOMiLS.createLSOutput(); FOS = new FileOutputStream(exportFilename); LSO.setByteStream((OutputStream) FOS); // get a LSSerializer object LSSerializer LSS = DOMiLS.createLSSerializer(); // do the serialization LSS.write(document, LSO); FOS.close(); } // =============================== } rs.close(); stmt.close(); } catch (Exception e) { messageError = e.getMessage(); } } if (autolabview.getPrinterObj().getExportFormat().equals("LQF")) { } } if (autolabview.getPrinterObj().isDirectPrintEnabled()) { } } if (messageProcessedOK == true) { autolabview.getAutoLabellerObj().setModified(false); autolabview.getAutoLabellerObj().update(); } else { logger.debug(messageError); } autolabview = null; } } } } }
From source file:de.uni_potsdam.hpi.bpt.promnicat.importer.sap_rm.SapReferenceModelImporter.java
public void splitEPML(File file) throws ParserConfigurationException, SAXException, IOException, TransformerException, JSONException { DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = fac.newDocumentBuilder(); Document doc = builder.parse(file); NodeList epcNodes = doc.getElementsByTagName("epc"); for (int i = 0; i < epcNodes.getLength(); i++) { String epcName = epcNodes.item(i).getAttributes().getNamedItem("name").getNodeValue(); Model model = this.persistenceApi.loadCompleteModelWithImportedId(epcName); if (model != null) { continue; }//from w w w .j a v a 2 s.c o m Document newEpcDoc = builder.newDocument(); Element epml = newEpcDoc.createElement("epml:epml"); Element directory = newEpcDoc.createElement("directory"); newEpcDoc.appendChild(epml); epml.appendChild(directory); directory.setAttribute("name", "ROOT"); Node epcNode = newEpcDoc.importNode(epcNodes.item(i), true); directory.appendChild(epcNode); DOMSource epmlSource = new DOMSource(newEpcDoc); final File epml2eRDFxsltFile = new File("resources/xslt/EPML2eRDF.xslt"); final Source epml2eRDFxsltSource = new StreamSource(epml2eRDFxsltFile); // Transformer Factory final TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Get the epml source Transformer transformer = transformerFactory.newTransformer(epml2eRDFxsltSource); StringWriter writer = new StringWriter(); transformer.transform(epmlSource, new StreamResult(writer)); String erdf = writer.toString(); String rdf = erdfToRdf(erdf); rdf = rdf.replaceAll("ns[0-9]+:", ""); rdf = rdf.replace("#resource", "#"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Document rdfDoc = builder.parse(new ByteArrayInputStream(rdf.getBytes("UTF-8"))); String json = RdfJsonTransformation.toJson(rdfDoc, "").toString(); //Diagram diagram = DiagramBuilder.parseJson(json); Representation representation = new Representation(Constants.FORMAT_BPMAI_JSON, Constants.NOTATION_EPC); Diagram parseJson = DiagramBuilder.parseJson(json); representation.setDataContent(json.getBytes()); model = new Model(epcName, Constants.ORIGIN_SAP_RM); model.setImportedId(epcName); Revision revision = new Revision(0); revision.connectRepresentation(representation); model.connectLatestRevision(revision); revision.connectModel(model); model.connectLatestRevision(revision); persistenceApi.savePojo(model); } }
From source file:com.hp.mqm.atrf.App.java
private void convertToXml(List<TestRunResultEntity> runResults, StreamResult result, boolean formatXml) { try {/* w w w. j a v a2 s . c o m*/ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("test_result"); doc.appendChild(rootElement); Element testRuns = doc.createElement("test_runs"); rootElement.appendChild(testRuns); for (TestRunResultEntity runResult : runResults) { Element testRun = doc.createElement("test_run"); testRuns.appendChild(testRun); testRun.setAttribute("module", runResult.getModule()); testRun.setAttribute("package", runResult.getPackageValue()); testRun.setAttribute("class", runResult.getClassValue()); testRun.setAttribute("name", runResult.getTestName()); testRun.setAttribute("duration", runResult.getDuration()); testRun.setAttribute("status", runResult.getStatus()); testRun.setAttribute("started", runResult.getStartedTime()); testRun.setAttribute("external_report_url", runResult.getExternalReportUrl()); testRun.setAttribute("run_name", runResult.getRunName()); Element testFields = doc.createElement("test_fields"); testRun.appendChild(testFields); if (StringUtils.isNotEmpty(runResult.getTestingToolType())) { Element testField = doc.createElement("test_field"); testFields.appendChild(testField); testField.setAttribute("type", "Testing_Tool_Type"); testField.setAttribute("value", runResult.getTestingToolType()); } if (OCTANE_RUN_FAILED_STATUS.equals(runResult.getStatus())) { Element error = doc.createElement("error"); testRun.appendChild(error); error.setAttribute("type", "Error"); error.setAttribute("message", "For more details , goto ALM run : " + runResult.getExternalReportUrl()); } } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); if (formatXml) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(doc); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:com.adaptris.core.services.splitter.XpathMessageSplitter.java
@Override public List<AdaptrisMessage> splitMessage(AdaptrisMessage msg) throws CoreException { List<AdaptrisMessage> result = new ArrayList<AdaptrisMessage>(); try {/*www . ja v a 2 s. c o m*/ NamespaceContext namespaceCtx = SimpleNamespaceContext.create(getNamespaceContext(), msg); DocumentBuilderFactoryBuilder factoryBuilder = documentFactoryBuilder(); if (namespaceCtx != null) { factoryBuilder = documentFactoryBuilder().withNamespaceAware(true); } DocumentBuilder docBuilder = factoryBuilder.configure(DocumentBuilderFactory.newInstance()) .newDocumentBuilder(); XmlUtils xml = new XmlUtils(namespaceCtx, factoryBuilder.configure(DocumentBuilderFactory.newInstance())); NodeList list = resolveXpath(msg, namespaceCtx, factoryBuilder); String encodingToUse = evaluateEncoding(msg); for (int i = 0; i < list.getLength(); i++) { Document splitXmlDoc = docBuilder.newDocument(); Node e = list.item(i); Node dup = splitXmlDoc.importNode(e, true); splitXmlDoc.appendChild(dup); AdaptrisMessage splitMsg = selectFactory(msg).newMessage("", encodingToUse); try (Writer writer = splitMsg.getWriter()) { xml.writeDocument(splitXmlDoc, writer, encodingToUse); copyMetadata(msg, splitMsg); result.add(splitMsg); } } } catch (Exception e) { throw new CoreException(e); } finally { } return result; }
From source file:org.gvnix.web.report.roo.addon.addon.ReportJspMetadataListener.java
/** * Generates a JSPX with a form requesting the report. The form has as many * radio buttons as formats has set the report. * /*from w w w. ja va2 s.c o m*/ * @param reportName * @param formats * @param controllerPath * @return */ private Document getReportFormJsp(String reportName, String controllerPath) { DocumentBuilder builder = XmlUtils.getDocumentBuilder(); Document document = builder.newDocument(); Map<String, String> properties = new HashMap<String, String>(); // Add document namespaces Element div = (Element) document.appendChild( new XmlElementBuilder("div", document).addAttribute("xmlns:c", "http://java.sun.com/jsp/jstl/core") .addAttribute("xmlns:fn", "http://java.sun.com/jsp/jstl/functions") .addAttribute("xmlns:spring", "http://www.springframework.org/tags") .addAttribute("xmlns:jsp", "http://java.sun.com/JSP/Page") .addAttribute("xmlns:form", "http://www.springframework.org/tags/form") .addAttribute("version", "2.0") .addChild(new XmlElementBuilder("jsp:directive.page", document) .addAttribute("contentType", "text/html;charset=UTF-8").build()) .addChild(new XmlElementBuilder("jsp:output", document) .addAttribute("omit-xml-declaration", "yes").build()) .build()); // Add div panel Element divPanel = (Element) new XmlElementBuilder("div", document) .addAttribute("class", "panel panel-default").build(); // Add div header Element divPanelHeader = (Element) new XmlElementBuilder("div", document) .addAttribute("class", "panel-heading").build(); // Add h3 title with content Element h3PanelTitle = (Element) new XmlElementBuilder("h3", document).addAttribute("class", "panel-title") .addChild(new XmlElementBuilder("spring:message", document) .addAttribute("code", "label_report_" + controllerPath + "_" + reportName) .addAttribute("htmlEscape", "false").build()) .build(); // Adding title panel to panel header divPanelHeader.appendChild(h3PanelTitle); // Adding panel header to div panel divPanel.appendChild(divPanelHeader); // Add div panel body Element divPanelBody = (Element) new XmlElementBuilder("div", document).addAttribute("class", "panel-body") .build(); // Add if not empty error Element ifNotEmptyError = (Element) new XmlElementBuilder("c:if", document) .addAttribute("test", "${not empty error}").build(); // Add h3 title with error message Element h3ErrorMessage = (Element) new XmlElementBuilder("h3", document) .addAttribute("class", "panel-title").addChild(new XmlElementBuilder("spring:message", document) .addAttribute("code", "${error}").addAttribute("htmlEscape", "false").build()) .build(); // Adding h3 message to if empty error ifNotEmptyError.appendChild(h3ErrorMessage); // Adding if not empty error to divPanelBody divPanelBody.appendChild(ifNotEmptyError); // Add form element Element formElement = (Element) new XmlElementBuilder("form:form", document) .addAttribute("class", "form-horizontal").addAttribute("role", "form") .addAttribute("action", reportName) .addAttribute("id", XmlUtils.convertId("fr_" + formbackingObject.getFullyQualifiedTypeName())) .addAttribute("method", "GET").build(); // Add div control group Element divControlGroup = (Element) new XmlElementBuilder("div", document) .addAttribute("class", "control-group form-group").build(); // Add div controls col Element divControlsCol = (Element) new XmlElementBuilder("div", document) .addAttribute("class", "controls col-xs-7 col-sm-8 col-md-12 col-lg-12").build(); // Add a drop-down select Element cifSelectFormat = (Element) new XmlElementBuilder("c:if", document) .addAttribute("test", "${not empty report_formats}").build(); Element selectFormat = (Element) new XmlElementBuilder("select", document) .addAttribute("class", "form-control input-sm").addAttribute("id", "_select_format") .addAttribute("name", "format").build(); Element cforEach = (Element) new XmlElementBuilder("c:forEach", document) .addAttribute("items", "${report_formats}").addAttribute("var", "format").build(); Element optionFormat = (Element) new XmlElementBuilder("option", document) .addAttribute("id", "option_format_${format}").addAttribute("value", "${format}").build(); Element coutFormat = (Element) new XmlElementBuilder("c:out", document) .addAttribute("value", "${fn:toUpperCase(format)}").build(); optionFormat.appendChild(coutFormat); cforEach.appendChild(optionFormat); selectFormat.appendChild(cforEach); cifSelectFormat.appendChild(selectFormat); // Add input element Element inputElement = (Element) new XmlElementBuilder("input", document) .addAttribute("class", "btn btn-primary btn-block").addAttribute("type", "submit").build(); // Adding elements to divControlsCol divControlsCol.appendChild(cifSelectFormat); divControlsCol.appendChild(inputElement); // Adding controls col to div control group divControlGroup.appendChild(divControlsCol); // Adding control group to form formElement.appendChild(divControlGroup); // Adding form to Panel Body divPanelBody.appendChild(formElement); // Adding Panel Body to Main Panel divPanel.appendChild(divPanelBody); // Adding Main Panel to general div div.appendChild(divPanel); // Add the message error to the application.properties properties.put("label_report_" + controllerPath + "_" + reportName, "Report " + reportName); getPropFileOperations().addProperties(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), "/WEB-INF/i18n/application.properties", properties, true, false); return document; }
From source file:edu.clemson.lph.civet.xml.StdeCviXmlBuilder.java
public StdeCviXmlBuilder() { try {//w w w . j ava2 s. co m DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = db.newDocument(); doc.setXmlStandalone(true); root = doc.createElementNS("http://www.usaha.org/xmlns/ecvi", "eCVI"); doc.appendChild(root); helper = new XMLDocHelper(doc); } catch (ParserConfigurationException e) { logger.error("Could not set up parser for stdXML", e); } }
From source file:com.castlemock.web.mock.rest.converter.swagger.SwaggerRestDefinitionConverter.java
/** * The method provides the functionality to generate an XML body based on a provided {@link Response} * and a list of {@link Model}s that might be required. * @param response The Swagger response which the XML body will be based on. * @param definitions Definitions of Swagger models * @return An XML response body.//from w w w . java 2s . c om * @since 1.13 */ private String generateXmlBody(final Response response, final Map<String, Model> definitions) { final Property schema = response.getSchema(); if (schema == null) { return null; } final StringWriter stringWriter = new StringWriter(); try { final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); final Document document = docBuilder.newDocument(); final Element root = getXmlElement(null, schema, definitions, document); document.appendChild(root); final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); final DOMSource source = new DOMSource(document); final StreamResult result = new StreamResult(stringWriter); transformer.transform(source, result); return stringWriter.toString(); } catch (Exception e) { LOGGER.error("Unable to generate a XML response body", e); } return stringWriter.toString(); }
From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java
public DOMSource generateDashPlaylist(UUID id, String baseUrl) { Job job = jobDao.getJobByID(id);/* www . ja v a2s . c o m*/ if (job == null) { return null; } MediaElement mediaElement = mediaDao.getMediaElementByID(job.getMediaElement()); if (mediaElement == null) { return null; } baseUrl = baseUrl + "/stream/segment/" + id + "/"; try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; docBuilder = docFactory.newDocumentBuilder(); // Root elements Document playlist = docBuilder.newDocument(); Element mpd = playlist.createElement("MPD"); playlist.appendChild(mpd); mpd.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); mpd.setAttribute("xmlns", "urn:mpeg:dash:schema:mpd:2011"); mpd.setAttribute("xsi:schemaLocation", "urn:mpeg:DASH:schema:MPD:2011 DASH-MPD.xsd"); //mpd.setAttribute("profiles", "urn:mpeg:dash:profile:full:2011"); mpd.setAttribute("profiles", "urn:mpeg:dash:profile:isoff-live:2011"); mpd.setAttribute("minBufferTime", "PT" + DASH_SEGMENT_DURATION + "S"); mpd.setAttribute("type", "static"); mpd.setAttribute("mediaPresentationDuration", "PT" + mediaElement.getDuration() + "S"); Element period = playlist.createElement("Period"); mpd.appendChild(period); period.setAttribute("duration", "PT" + mediaElement.getDuration() + "S"); Element adaptationSet = playlist.createElement("AdaptationSet"); period.appendChild(adaptationSet); adaptationSet.setAttribute("segmentAlignment", "true"); adaptationSet.setAttribute("contentType", "audio"); Element representation = playlist.createElement("Representation"); adaptationSet.appendChild(representation); representation.setAttribute("id", "audio"); representation.setAttribute("mimeType", "audio/mp4"); representation.setAttribute("codecs", "mp4a.40.2"); representation.setAttribute("audioSamplingRate", "44100"); representation.setAttribute("bandwidth", "128000"); Element audioChannelConfig = playlist.createElement("AudioChannelConfiguration"); representation.appendChild(audioChannelConfig); audioChannelConfig.setAttribute("schemeIdUri", "urn:mpeg:dash:23003:3:audio_channel_configuration:2011"); audioChannelConfig.setAttribute("value", "2"); Element segmentTemplate = playlist.createElement("SegmentTemplate"); representation.appendChild(segmentTemplate); segmentTemplate.setAttribute("duration", "5000"); segmentTemplate.setAttribute("initialization", baseUrl + "init-stream0.m4s"); segmentTemplate.setAttribute("media", baseUrl + "chunk-stream0-$Number%05d$.m4s"); segmentTemplate.setAttribute("startNumber", "1"); DOMSource result = new DOMSource(playlist); return result; } catch (ParserConfigurationException ex) { return null; } }