List of usage examples for javax.xml.parsers DocumentBuilder newDocument
public abstract Document newDocument();
From source file:com.centeractive.ws.builder.soap.XmlUtils.java
public static String createJdbcXmlResult(Statement statement) throws SQLException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDocumentResult = builder.newDocument(); Element resultsElement = xmlDocumentResult.createElement("Results"); xmlDocumentResult.appendChild(resultsElement); if (statement != null) { ResultSet resultSet = statement.getResultSet(); if (resultSet != null) { resultSet.setFetchSize(statement.getFetchSize()); xmlDocumentResult = addResultSetXmlPart(resultsElement, resultSet, xmlDocumentResult); while (statement.getMoreResults()) { xmlDocumentResult = addResultSetXmlPart(resultsElement, statement.getResultSet(), xmlDocumentResult); }//from w w w. j a v a 2 s .com } else { Element errorElement = xmlDocumentResult.createElement("UpdateCount"); errorElement .appendChild(xmlDocumentResult.createTextNode(String.valueOf(statement.getUpdateCount()))); resultsElement.appendChild(errorElement); } } StringWriter out = new StringWriter(); OutputFormat outputFormat = new OutputFormat(xmlDocumentResult); outputFormat.setOmitComments(true); outputFormat.setOmitDocumentType(true); outputFormat.setOmitXMLDeclaration(true); // outputFormat.setLineSeparator( "\n" ); // add this line // // outputFormat.setPreserveSpace( true ); outputFormat.setIndent(3); outputFormat.setIndenting(true); try { XMLSerializer serializer = new XMLSerializer(new PrintWriter(out), outputFormat); serializer.asDOMSerializer(); serializer.serialize(xmlDocumentResult); } catch (IOException e) { throw new SoapBuilderException(e); } return out.toString(); }
From source file:com.sms.server.service.AdaptiveStreamingService.java
public Document generateDASHPlaylist(long id, String baseUrl) { Job job = jobDao.getJobByID(id);/* w w w .j a v a 2 s . com*/ 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; }
From source file:Main.java
/** * Try to normalize a document by removing nonsignificant whitespace. * * @see "#62006"/*from w ww .j a v a 2s.com*/ */ private static Document normalize(Document orig) throws IOException { DocumentBuilder builder = null; DocumentBuilderFactory factory = getFactory(false, false); try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException("Cannot create parser satisfying configuration parameters: " + e, e); //NOI18N } DocumentType doctype = null; NodeList nl = orig.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof DocumentType) { // We cannot import DocumentType's, so we need to manually copy it. doctype = (DocumentType) nl.item(i); } } Document doc; if (doctype != null) { doc = builder.getDOMImplementation().createDocument(orig.getDocumentElement().getNamespaceURI(), orig.getDocumentElement().getTagName(), builder.getDOMImplementation().createDocumentType(orig.getDoctype().getName(), orig.getDoctype().getPublicId(), orig.getDoctype().getSystemId())); // XXX what about entity decls inside the DOCTYPE? doc.removeChild(doc.getDocumentElement()); } else { doc = builder.newDocument(); } for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (!(node instanceof DocumentType)) { try { doc.appendChild(doc.importNode(node, true)); } catch (DOMException x) { // Thrown in NB-Core-Build #2896 & 2898 inside GeneratedFilesHelper.applyBuildExtensions throw new IOException("Could not import or append " + node + " of " + node.getClass(), x); } } } doc.normalize(); nl = doc.getElementsByTagName("*"); // NOI18N for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); removeXmlBase(e); NodeList nl2 = e.getChildNodes(); for (int j = 0; j < nl2.getLength(); j++) { Node n = nl2.item(j); if (n instanceof Text && ((Text) n).getNodeValue().trim().length() == 0) { e.removeChild(n); j--; // since list is dynamic } } } return doc; }
From source file:au.edu.rmit.GalagoSearchClient.java
protected Document runSearchXML(String query, int count) throws ParserConfigurationException, UnsupportedEncodingException { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XPath xpath = XPathFactory.newInstance().newXPath(); String baseURI = "http://" + host + ":" + Integer.toString(port) + "/searchxml"; String uri = baseURI + "?q=" + URLEncoder.encode(query, "UTF-8") + "&n=" + Integer.toString(count); Document result;//from www. ja va2 s .com try { result = builder.parse(uri); } catch (Exception e) { e.printStackTrace(); result = builder.newDocument(); } return result; }
From source file:com.microsoft.windowsazure.management.sql.RestoreDatabaseOperationsImpl.java
/** * Issues a restore request for an Azure SQL Database. * * @param sourceServerName Required. The name of the Azure SQL Database * Server where the source database is, or was, hosted. * @param parameters Required. Additional parameters for the Create Restore * Database Operation request./*from w w w . j ava 2 s .c o m*/ * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Contains the response to the Create Restore Database Operation * request. */ @Override public RestoreDatabaseOperationCreateResponse create(String sourceServerName, RestoreDatabaseOperationCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (sourceServerName == null) { throw new NullPointerException("sourceServerName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getSourceDatabaseName() == null) { throw new NullPointerException("parameters.SourceDatabaseName"); } if (parameters.getTargetDatabaseName() == null) { throw new NullPointerException("parameters.TargetDatabaseName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("sourceServerName", sourceServerName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(sourceServerName, "UTF-8"); url = url + "/restoredatabaseoperations"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2012-03-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceResource"); requestDoc.appendChild(serviceResourceElement); Element sourceDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); sourceDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getSourceDatabaseName())); serviceResourceElement.appendChild(sourceDatabaseNameElement); if (parameters.getSourceDatabaseDeletionDate() != null) { Element sourceDatabaseDeletionDateElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "SourceDatabaseDeletionDate"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); sourceDatabaseDeletionDateElement.appendChild(requestDoc .createTextNode(simpleDateFormat.format(parameters.getSourceDatabaseDeletionDate().getTime()))); serviceResourceElement.appendChild(sourceDatabaseDeletionDateElement); } if (parameters.getTargetServerName() != null) { Element targetServerNameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetServerName"); targetServerNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetServerName())); serviceResourceElement.appendChild(targetServerNameElement); } Element targetDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); targetDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetDatabaseName())); serviceResourceElement.appendChild(targetDatabaseNameElement); if (parameters.getPointInTime() != null) { Element targetUtcPointInTimeElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetUtcPointInTime"); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); targetUtcPointInTimeElement.appendChild( requestDoc.createTextNode(simpleDateFormat2.format(parameters.getPointInTime().getTime()))); serviceResourceElement.appendChild(targetUtcPointInTimeElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_CREATED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RestoreDatabaseOperationCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RestoreDatabaseOperationCreateResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement2 != null) { RestoreDatabaseOperation serviceResourceInstance = new RestoreDatabaseOperation(); result.setOperation(serviceResourceInstance); Element requestIDElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "RequestID"); if (requestIDElement != null) { String requestIDInstance; requestIDInstance = requestIDElement.getTextContent(); serviceResourceInstance.setId(requestIDInstance); } Element sourceDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); if (sourceDatabaseNameElement2 != null) { String sourceDatabaseNameInstance; sourceDatabaseNameInstance = sourceDatabaseNameElement2.getTextContent(); serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance); } Element sourceDatabaseDeletionDateElement2 = XmlUtility.getElementByTagNameNS( serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseDeletionDate"); if (sourceDatabaseDeletionDateElement2 != null && sourceDatabaseDeletionDateElement2.getTextContent() != null && !sourceDatabaseDeletionDateElement2.getTextContent().isEmpty()) { Calendar sourceDatabaseDeletionDateInstance; sourceDatabaseDeletionDateInstance = DatatypeConverter .parseDateTime(sourceDatabaseDeletionDateElement2.getTextContent()); serviceResourceInstance.setSourceDatabaseDeletionDate(sourceDatabaseDeletionDateInstance); } Element targetServerNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetServerName"); if (targetServerNameElement2 != null) { String targetServerNameInstance; targetServerNameInstance = targetServerNameElement2.getTextContent(); serviceResourceInstance.setTargetServerName(targetServerNameInstance); } Element targetDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); if (targetDatabaseNameElement2 != null) { String targetDatabaseNameInstance; targetDatabaseNameInstance = targetDatabaseNameElement2.getTextContent(); serviceResourceInstance.setTargetDatabaseName(targetDatabaseNameInstance); } Element targetUtcPointInTimeElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetUtcPointInTime"); if (targetUtcPointInTimeElement2 != null) { Calendar targetUtcPointInTimeInstance; targetUtcPointInTimeInstance = DatatypeConverter .parseDateTime(targetUtcPointInTimeElement2.getTextContent()); serviceResourceInstance.setPointInTime(targetUtcPointInTimeInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.kaikoda.cah.TestDeck.java
@Test public void testDeckTransform_nullParamValue() throws SAXException, IOException, TransformerException, ParserConfigurationException { // Retrieve the control card data for Dutch English CAH (so can assume // all pre-processing complete). Document xml = this.getDocument("/data/control/cards/netherlands.xml"); Deck customDeck = new Deck(xml); customDeck.setErrorListener(new ProgressReporter()); // Create a container to hold the result of the transformation DocumentBuilder documentBuilder = Deck.newDocumentBuilder(); Document document = documentBuilder.newDocument(); DOMResult result = new DOMResult(document); // Build the parameter list TreeMap<String, String> params = new TreeMap<String, String>(); params.put("path-to-dictionary", TestDeck.DICTIONARY_DATA_ENGLISH.getAbsolutePath()); params.put("output-language", null); customDeck.transform(new DOMSource(xml), Deck.getXsl(Deck.PATH_TO_TRANSLATION_XSL), result, params); // Retrieve the control card data for American CAH. Document expected = xml;//from w w w . j a v a 2s. c o m // Check that the result is the same cards, translated into American // English (which is the default output language). assertXMLEqual(expected, document); }
From source file:com.photon.phresco.util.Utility.java
public static DOMSource createXML(String browsePath, String fileType) throws PhrescoException { try {/*from w ww .j a v a 2s .c o m*/ File inputPath = new File(browsePath); if (!inputPath.isDirectory() || inputPath.isFile()) { return null; } DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElement("root"); document.appendChild(rootElement); Element mainFolder = document.createElement("Item"); mainFolder.setAttribute("name", inputPath.getName()); mainFolder.setAttribute("path", inputPath.toString()); mainFolder.setAttribute("type", "Folder"); rootElement.appendChild(mainFolder); listDirectories(mainFolder, document, inputPath, fileType); DOMSource source = new DOMSource(document); return source; } catch (DOMException e) { throw new PhrescoException(e); } catch (ParserConfigurationException e) { throw new PhrescoException(e); } }
From source file:com.limegroup.gnutella.archive.ArchiveContribution.java
/** * @throws IllegalStateException//from www. j ava 2 s .c om * If java's xml parser configuration is bad */ private Document getMetaDocument() { /* * Sample _meta.xml file: * * <metadata> * <collection>opensource_movies</collection> * <mediatype>movies</mediatype> * <title>My Home Movie</title> * <runtime>2:30</runtime> * <director>Joe Producer</director> * </metadata> * */ final String METADATA_ELEMENT = "metadata"; final String COLLECTION_ELEMENT = "collection"; final String MEDIATYPE_ELEMENT = "mediatype"; final String TITLE_ELEMENT = "title"; final String DESCRIPTION_ELEMENT = "description"; final String LICENSE_URL_ELEMENT = "licenseurl"; final String UPLOAD_APPLICATION_ELEMENT = "upload_application"; final String APPID_ATTR = "appid"; final String APPID_ATTR_VALUE = "LimeWire"; final String VERSION_ATTR = "version"; final String UPLOADER_ELEMENT = "uploader"; final String IDENTIFIER_ELEMENT = "identifier"; final String TYPE_ELEMENT = "type"; try { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder db = dbf.newDocumentBuilder(); final Document document = db.newDocument(); final Element metadataElement = document.createElement(METADATA_ELEMENT); document.appendChild(metadataElement); final Element collectionElement = document.createElement(COLLECTION_ELEMENT); metadataElement.appendChild(collectionElement); collectionElement.appendChild(document.createTextNode(Archives.getCollectionString(getCollection()))); final Element mediatypeElement = document.createElement(MEDIATYPE_ELEMENT); metadataElement.appendChild(mediatypeElement); mediatypeElement.appendChild(document.createTextNode(Archives.getMediaString(getMedia()))); final Element typeElement = document.createElement(TYPE_ELEMENT); metadataElement.appendChild(typeElement); typeElement.appendChild(document.createTextNode(Archives.getTypeString(getType()))); final Element titleElement = document.createElement(TITLE_ELEMENT); metadataElement.appendChild(titleElement); titleElement.appendChild(document.createTextNode(getTitle())); final Element descriptionElement = document.createElement(DESCRIPTION_ELEMENT); metadataElement.appendChild(descriptionElement); descriptionElement.appendChild(document.createTextNode(getDescription())); final Element identifierElement = document.createElement(IDENTIFIER_ELEMENT); metadataElement.appendChild(identifierElement); identifierElement.appendChild(document.createTextNode(getIdentifier())); final Element uploadApplicationElement = document.createElement(UPLOAD_APPLICATION_ELEMENT); metadataElement.appendChild(uploadApplicationElement); uploadApplicationElement.setAttribute(APPID_ATTR, APPID_ATTR_VALUE); uploadApplicationElement.setAttribute(VERSION_ATTR, CommonUtils.getLimeWireVersion()); final Element uploaderElement = document.createElement(UPLOADER_ELEMENT); metadataElement.appendChild(uploaderElement); uploaderElement.appendChild(document.createTextNode(getUsername())); //take licenseurl from the first File final Iterator filesIterator = getFiles().iterator(); if (filesIterator.hasNext()) { final File firstFile = (File) filesIterator.next(); final String licenseUrl = firstFile.getLicenseUrl(); if (licenseUrl != null) { final Element licenseUrlElement = document.createElement(LICENSE_URL_ELEMENT); metadataElement.appendChild(licenseUrlElement); licenseUrlElement.appendChild(document.createTextNode(licenseUrl)); } } // now build user-defined elements final Map userFields = getFields(); for (final Iterator i = userFields.keySet().iterator(); i.hasNext();) { final Object field = i.next(); final Object value = userFields.get(field); if (field instanceof String) { final Element e = document.createElement((String) field); metadataElement.appendChild(e); if (value != null && value instanceof String) { e.appendChild(document.createTextNode((String) value)); } } } return document; } catch (final ParserConfigurationException e) { final IllegalStateException ise = new IllegalStateException(); ise.initCause(e); throw ise; } }
From source file:de.mpg.escidoc.services.transformation.Util.java
/** * Queries CoNE service and returns the result as DOM node. * The returned XML has the following structure: * <cone>// ww w . j a v a 2 s . com * <author> * <familyname>Buxtehude-Mlln</familyname> * <givenname>Heribert</givenname> * <prefix>von und zu</prefix> * <title>Knig</title> * </author> * <author> * <familyname>Mller</familyname> * <givenname>Peter</givenname> * </author> * </authors> * * @param Single instituteId for an institute without departments or list of Ids. Every department has his own Id. * @return */ public static Node queryReportPersonCone(String model, String query) { DocumentBuilder documentBuilder; String queryUrl; List<String> childIds = new ArrayList<String>(); // get the childOUs if any in the query if (query.contains(" ")) { String[] result = query.split("\\s+"); for (String s : result) { childIds.add(s); } } logger.info("queryReportPersonCone: " + model + " query: " + query); logger.info("childIds " + Arrays.toString(childIds.toArray())); try { documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); HttpClient client = new HttpClient(); if (childIds.size() > 0) { // execute a method for every child ou for (String childId : childIds) { queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("escidoc:position/dc:identifier", "UTF-8") + "=" + URLEncoder.encode("\"" + childId + "\"", "UTF-8") + "&n=0"; executeGetMethod(client, queryUrl, documentBuilder, document, element); } } else { // there are no child ous, methid is called once queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("escidoc:position/dc:identifier", "UTF-8") + "=" + URLEncoder.encode("\"" + query + "\"", "UTF-8") + "&n=0"; executeGetMethod(client, queryUrl, documentBuilder, document, element); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; } }
From source file:com.apricot.eating.xml.XMLParser.java
private XMLParser(InputStream is) { try {/*from w w w. j a v a 2 s .c om*/ DocumentBuilderFactory factory = new DocumentBuilderFactoryImpl(); DocumentBuilder builder = factory.newDocumentBuilder(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); StringBuffer sb = new StringBuffer(); int b; while ((b = isr.read()) != -1) { sb.append((char) b); } is = new ByteArrayInputStream(sb.toString().getBytes("utf-8")); if (is != null) { document = builder.parse(is); } else { document = builder.newDocument(); } } catch (Exception e) { e.printStackTrace(System.out); } }