List of usage examples for org.w3c.dom Element setTextContent
public void setTextContent(String textContent) throws DOMException;
From source file:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToForms.java
/** * Adds the form field value and creates the appropriate node in the XML instance. Sets the * value for the given field in the given instance. A candidate value may be provided, in which * case either a default field value had been specified (via uri or mapping file) or an * alfrescoId is known.//from www .j a v a 2s .c om * <p/> * If the field is an enumeration, the value must be a key instead of an enumeration literal. * * @param formInstance * the form instance * @param formElement * the form element * @param formFieldType * the form field type * @param value * the value * @param transaction * @param alfrescoId * @param isMassTagging * @param initParams */ private void addFormFieldValue(Document formInstance, Element formElement, FormFieldType formFieldType, String value, AlfrescoTransaction transaction, String alfrescoId, boolean formIsReadOnly) { Element formField = formInstance.createElement(formFieldType.getUniqueName()); // file fields need additional attributes if (formFieldType instanceof FileFieldType) { formField.setAttribute("file", ""); formField.setAttribute("type", ""); } // // ** #1421: mass tagging. No initial value for mass tagging. // if (isMassTagging) { // formElement.appendChild(formField); // return; // } // ** #1421 boolean applyUserFormat = formIsReadOnly || isReadOnly(formFieldType); String type = formFieldType.getType(); if (type.equals("DateTime")) { String dateValue = getDateFromDateTime(value); String timeValue = getTimeFromDateTime(value); if (applyUserFormat) { dateValue = transformDateValueForDisplay(dateValue); timeValue = transformTimeValueForDisplay(timeValue); formField.setTextContent(dateValue + " " + timeValue); } else { Element dateField = formInstance.createElement("date"); dateField.setTextContent(dateValue); formField.appendChild(dateField); Element timeField = formInstance.createElement("time"); timeField.setTextContent(timeValue); formField.appendChild(timeField); } } else if (type.equals("Date")) { String dateValue = value; if (applyUserFormat) { dateValue = transformDateValueForDisplay(value); } formField.setTextContent(dateValue); } else if (type.equals("Time")) { String timeValue = value; if (applyUserFormat) { transformTimeValueForDisplay(value); } formField.setTextContent(timeValue); } else if (isSelectionCapable(formFieldType)) { Element selItemElt = formInstance.createElement(MsgId.INT_INSTANCE_ASSOCIATION_ITEM.getText()); Element idElt = formInstance.createElement(MsgId.INT_INSTANCE_SIDEID.getText()); Element labelElt = formInstance.createElement(MsgId.INT_INSTANCE_SIDELABEL.getText()); Element typeElt = formInstance.createElement(MsgId.INT_INSTANCE_SIDETYPE.getText()); // **try** to initialize using the 'value' variable if (StringUtils.trimToNull(value) != null) { String datatype = getXtensionDataType(formFieldType); String identifier = getXtensionIdentifier(formFieldType); String format = getXtensionFormat(formFieldType); String labelLength = getXtensionLabelLength(formFieldType); try { String nodeInfo = controller.resolveObjectInfo(transaction, datatype, identifier, format, labelLength, value); String label = getLabelFromObjectInfo(nodeInfo); String qname = getQNameFromObjectInfo(nodeInfo); idElt.setTextContent(value); labelElt.setTextContent(label); typeElt.setTextContent(qname); if (logger.isWarnEnabled() && qname.equals(datatype) == false) { logger.warn("Got QName '" + qname + "' when resolving object info for value '" + value + "' of type '" + datatype + "' with identifier '" + identifier + "'"); } } catch (ServletException e) { // nothing to do, the fields just don't get initialized } } selItemElt.appendChild(idElt); selItemElt.appendChild(labelElt); selItemElt.appendChild(typeElt); formField.appendChild(selItemElt); } else if (isSearchEnum(formFieldType)) { Element idField = formInstance.createElement(MsgId.INT_INSTANCE_SIDEID.getText()); idField.setTextContent(value); formField.appendChild(idField); Element labelField = formInstance.createElement(MsgId.INT_INSTANCE_SIDELABEL.getText()); if (StringUtils.trimToNull(value) != null) { String enumCaption; try { enumCaption = controller.getEnumCaption(transaction, value); labelField.setTextContent(enumCaption); } catch (ServletException e) { logger.error("Error getting an enum caption", e); } } else { labelField.setTextContent(""); } formField.appendChild(labelField); } else { // covers the cases of 1- single value, 2-single enum and 3- multiple enum // // String enumType = formFieldType.getStaticEnumType(); // if (StringUtils.trimToNull(enumType) != null) { // String enumvalue = StringUtils.trimToNull(EnumAction // .getEnumKey(enumType, value)); // // if alfrescoId is given, variable "value" is already a key // value = (alfrescoId == null) ? enumvalue : value; // } formField.setTextContent(value); if (formFieldType instanceof FileFieldType) { if (controller.getParamUploadRepoFormatInfo(transaction.getInitParams())) { FileFieldType fileFieldType = (FileFieldType) formFieldType; if ((alfrescoId != null) && (isInRepository(fileFieldType))) { formField.setTextContent(controller.getNodeContentInfo(transaction, value)); } } } } formElement.appendChild(formField); }
From source file:com.moviejukebox.writer.MovieJukeboxXMLWriter.java
private Element processCategoryIndex(Document doc, String indexName, String indexOriginalName, List<Movie> indexMovies, String categoryKey, int categoryMinCount, Library library) { List<Movie> allMovies = library.getMoviesList(); int countMovieCat = library.getMovieCountForIndex(categoryKey, indexName); boolean skipSet = "Set".equalsIgnoreCase(categoryKey) && countMovieCat <= 1; LOG.debug("Index: {}, Category: {}, count: {}", categoryKey, indexName, indexMovies.size()); JukeboxStatistic js = JukeboxStatistic.fromString("index_" + categoryKey); JukeboxStatistics.setStatistic(js, indexMovies.size()); // Display a message about the category we're indexing if (countMovieCat < categoryMinCount && (skipSet || !INDEXES_FOR_CATEGORIES_XML.contains(categoryKey))) { LOG.debug(/* w w w.j a v a 2 s.co m*/ "Category '{}' Index '{}' does not contain enough videos ({}/{}), not adding to categories.xml.", categoryKey, indexName, countMovieCat, categoryMinCount); return null; } if (setsExcludeTV && categoryKey.equalsIgnoreCase(Library.INDEX_SET) && indexMovies.get(0).isTVShow()) { // Do not include the video in the set because it's a TV show return null; } String indexFilename = FileTools.makeSafeFilename(FileTools.createPrefix(categoryKey, indexName)) + "1"; Element eCategory = doc.createElement(INDEX); eCategory.setAttribute(NAME, indexName); eCategory.setAttribute(ORIGINAL_NAME, indexOriginalName); if (includeMoviesInCategories) { eCategory.setAttribute("filename", indexFilename); for (Identifiable movie : indexMovies) { DOMHelper.appendChild(doc, eCategory, MOVIE, String.valueOf(allMovies.indexOf(movie))); } } else { eCategory.setTextContent(indexFilename); } return eCategory; }
From source file:com.twinsoft.convertigo.engine.localbuild.BuildLocally.java
/*** * Explore "config.xml", handle plugins and copy needed resources to appropriate platforms folders. * @param wwwDir/* w ww . j a v a 2s. c o m*/ * @param platform * @param cordovaDir */ private void processConfigXMLResources(File wwwDir, File cordovaDir) throws Throwable { try { File configFile = new File(cordovaDir, "config.xml"); Document doc = XMLUtils.loadXml(configFile); TwsCachedXPathAPI xpathApi = new TwsCachedXPathAPI(); Element singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/preference[@name='phonegap-version']"); // Changes icons and splashs src in config.xml file because it was moved to the parent folder NodeIterator nodeIterator = xpathApi.selectNodeIterator(doc, "//*[local-name()='splash' or local-name()='icon']"); singleElement = (Element) nodeIterator.nextNode(); while (singleElement != null) { String src = singleElement.getAttribute("src"); src = "www/" + src; File file = new File(cordovaDir, src); if (file.exists()) { singleElement.setAttribute("src", src); } singleElement = (Element) nodeIterator.nextNode(); } //ANDROID if (mobilePlatform instanceof Android) { singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/name"); if (singleElement != null) { String name = singleElement.getTextContent(); name = name.replace("\\", "\\\\"); name = name.replace("'", "\\'"); name = name.replace("\"", "\\\""); singleElement.setTextContent(name); } } //iOS // if (mobilePlatform instanceof IOs) { // } //WINPHONE if (mobilePlatform instanceof WindowsPhone8) { // Without these width and height the local build doesn't work but with these the remote build doesn't work singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/platform[@name='wp8']/icon[not(@role)]"); if (singleElement != null) { singleElement.setAttribute("width", "99"); singleElement.setAttribute("height", "99"); } singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/platform[@name='wp8']/icon[@role='background']"); if (singleElement != null) { singleElement.setAttribute("width", "159"); singleElement.setAttribute("height", "159"); } // /widget/platform[@name='wp8']/splash singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/platform/splash"); if (singleElement != null) { singleElement.setAttribute("width", "768"); singleElement.setAttribute("height", "1280"); } singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/plugin[@name='phonegap-plugin-push']/param[@name='SENDER_ID']"); if (singleElement != null) { // Remote build needs a node named 'param' and local build needs a node named 'variable' singleElement.getParentNode().appendChild(cloneNode(singleElement, "variable")); singleElement.getParentNode().removeChild(singleElement); } } // if (mobilePlatform instanceof Windows) { // TODO : Add platform Windows 8 // } // XMLUtils.saveXml(doc, configFile.getAbsolutePath()); // We have to add the root config.xml all our app's config.xml preferences. // Cordova will use this file to generates the platform specific config.xml // Get preferences from current config.xml NodeIterator preferences = xpathApi.selectNodeIterator(doc, "//preference"); // File configFile = new File(cordovaDir, "config.xml"); // doc = XMLUtils.loadXml(configFile); // The root config.xml NodeList preferencesList = doc.getElementsByTagName("preference"); // Remove old preferences while (preferencesList.getLength() > 0) { Element pathNode = (Element) preferencesList.item(0); // Remove empty lines Node prev = pathNode.getPreviousSibling(); if (prev != null && prev.getNodeType() == Node.TEXT_NODE && prev.getNodeValue().trim().length() == 0) { doc.getDocumentElement().removeChild(prev); } doc.getDocumentElement().removeChild(pathNode); } for (Element preference = (Element) preferences .nextNode(); preference != null; preference = (Element) preferences.nextNode()) { String name = preference.getAttribute("name"); String value = preference.getAttribute("value"); Element elt = doc.createElement("preference"); elt.setAttribute("name", name); elt.setAttribute("value", value); Engine.logEngine.info("Adding preference'" + name + "' with value '" + value + "'"); doc.getDocumentElement().appendChild(elt); } Engine.logEngine.trace("New config.xml is: " + XMLUtils.prettyPrintDOM(doc)); File resXmlFile = new File(cordovaDir, "config.xml"); // FileUtils.deleteQuietly(resXmlFile); XMLUtils.saveXml(doc, resXmlFile.getAbsolutePath()); // Last part, as all resources has been copied to the correct location, we can remove // our "www/res" directory before packaging to save build time and size... // FileUtils.deleteDirectory(new File(wwwDir, "res")); } catch (Exception e) { logException(e, "Unable to process config.xml in your project, check the file's validity"); } }
From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java
@Test //KEYCLOAK-4020/*from ww w. j av a 2 s . c o m*/ public void testBooleanAttribute() throws Exception { new SamlClientBuilder() .authnRequest(getAuthServerSamlEndpoint(SAMLSERVLETDEMO), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2, getAppServerSamlEndpoint(employee2ServletPage).toString(), Binding.POST) .build().login().user(bburkeUser).build().processSamlResponse(Binding.POST) .transformDocument(responseDoc -> { Element attribute = responseDoc.createElement("saml:Attribute"); attribute.setAttribute("Name", "boolean-attribute"); attribute.setAttribute("NameFormat", "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"); Element attributeValue = responseDoc.createElement("saml:AttributeValue"); attributeValue.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema"); attributeValue.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); attributeValue.setAttribute("xsi:type", "xs:boolean"); attributeValue.setTextContent("true"); attribute.appendChild(attributeValue); IOUtil.appendChildInDocument(responseDoc, "samlp:Response/saml:Assertion/saml:AttributeStatement", attribute); return responseDoc; }).build() .navigateTo(employee2ServletPage.toString() + "/getAttributes") .execute(r -> { Assert.assertThat(r, statusCodeIsHC(Response.Status.OK)); Assert.assertThat(r, bodyHC(containsString("boolean-attribute: true"))); }); }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
private byte[] executeMethod(HttpMethod method, final Context context) throws IOException, URIException, MalformedURLException, EngineException { Header[] requestHeaders, responseHeaders = null; byte[] result = null; String contents = null;//from w w w . ja va2s . c om int statuscode = -1; if (!context.requestedObject.runningThread.bContinue) return null; Engine.logBeans .debug("(HttpConnector) Executing method - " + method.getName() + "(" + method.getPath() + ")"); try { requestHeaders = method.getRequestHeaders(); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans .trace("(HttpConnector) Request headers :\n" + Arrays.asList(requestHeaders).toString()); statuscode = doExecuteMethod(method, context); Engine.logBeans.debug("(HttpConnector) Status: " + method.getStatusLine().toString()); responseHeaders = method.getResponseHeaders(); context.setResponseHeaders(responseHeaders); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans .trace("(HttpConnector) Response headers:\n" + Arrays.asList(responseHeaders).toString()); if (statuscode != -1) { InputStream in = method.getResponseBodyAsStream(); if (in != null) { /** * Retrieve response charset if available in responseHeaders */ charset = null; boolean checkGZip = false; // add GZip support #320 for (int i = 0; i < responseHeaders.length && (charset == null || !checkGZip); i++) { Header head = responseHeaders[i]; if (HeaderName.ContentType.is(head)) { context.contentType = head.getValue(); HeaderElement[] els = head.getElements(); for (int j = 0; j < els.length && charset == null; j++) { NameValuePair nvp = els[j].getParameterByName("charset"); if (nvp != null) charset = nvp.getValue(); } } else if (HeaderName.ContentEncoding.is(head)) { checkGZip = true; HeaderElement[] els = head.getElements(); for (int j = 0; j < els.length; j++) if ("gzip".equals(els[j].getName())) { Engine.logBeans.debug("(HttpConnector) Decode GZip stream"); in = new GZIPInputStream(in); } } } if (context.contentType != null && context.contentType.startsWith("multipart/") && context.requestedObject instanceof AbstractHttpTransaction) { Engine.logBeans.debug("(HttpConnector) Decoding multipart contentType"); try { AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; BigMimeMultipart mp = new BigMimeMultipart(new BufferedInputStream(in), context.contentType); ByteArrayOutputStream bos = new ByteArrayOutputStream(); mp.nextPart(bos); result = bos.toByteArray(); if (transaction.getAllowDownloadAttachment()) { Document doc = context.outputDocument; Element attInfo = null; File file = File.createTempFile("c8o_", ".part"); for (MimePart bp = mp.nextPart(file); bp != null; bp = mp.nextPart(file)) { try { file.deleteOnExit(); if (attInfo == null) { Engine.logBeans.debug("(HttpConnector) Saving attachment(s)"); attInfo = doc.createElement("AttachmentInfo"); doc.getDocumentElement().appendChild(attInfo); } Element att = doc.createElement("attachment"); attInfo.appendChild(att); String cid = bp.getContentID(); if (cid != null) { cid = cid.replaceFirst("^<?(.*?)>?$", "$1"); att.setAttribute("cid", "cid:" + cid); } Engine.logBeans.debug("(HttpConnector) Saving the attachment cid: " + cid + " in file: " + file.getAbsolutePath()); att.setAttribute("filepath", file.getAbsolutePath()); Enumeration<javax.mail.Header> headers = GenericUtils .cast(bp.getAllHeaders()); while (headers.hasMoreElements()) { javax.mail.Header header = headers.nextElement(); Element eHeader = doc.createElement("header"); att.appendChild(eHeader); eHeader.setAttribute("name", header.getName()); eHeader.setAttribute("value", header.getValue()); } } catch (Exception e1) { Engine.logBeans .error("(HttpConnector) Failed to retrieve the attachment in " + file.getAbsolutePath(), e1); } file = File.createTempFile("c8o_", ".part"); } file.delete(); in.close(); } } catch (Exception e) { Engine.logBeans.error("(HttpConnector) Failed to retrieve attachments", e); } } else { result = IOUtils.toByteArray(in); in.close(); } } if (Engine.logBeans.isTraceEnabled()) { contents = new String((result != null) ? result : new byte[] {}); Engine.logBeans.trace("(HttpConnector) Response content:\n" + contents); } String redirectUrl, newuri; GetMethod redirectMethod = null; // Handles REDIRECTION through Location header if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = method.getResponseHeader("Location"); if (location != null) { newuri = location.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } // ignore any data after the ";" character int split = newuri.indexOf(';'); if (split != -1) { newuri = newuri.substring(0, split); } redirectUrl = getAbsoluteUrl(method, newuri); Engine.logBeans.debug("(HttpConnector) Redirecting to : " + redirectUrl); redirectMethod = new GetMethod(redirectUrl); // set headers for (int i = 0; i < requestHeaders.length; i++) redirectMethod.setRequestHeader(requestHeaders[i]); referer = redirectUrl.startsWith("http") ? redirectUrl : (hostConfiguration.getHostURL() + redirectUrl); result = executeMethod(redirectMethod, context); // recurse } else { Engine.logBeans.debug("(HttpConnector) Invalid redirect!"); } } else { /* * String lwContents = contents.toLowerCase(); int index, i, * j, k, z; // Handles REDIRECTION through META Refresh if * (((index = lwContents.indexOf("http-equiv='refresh'")) != * -1) || ((index = * lwContents.indexOf("http-equiv=\"refresh\"")) != -1)) { * if ((i = lwContents.indexOf("content=", index + 20)) != * -1) { char c = lwContents.charAt(i+8); if ((j = * lwContents.indexOf("url=", i)) != -1) { if ((k = * lwContents.indexOf(c, j + 1)) != -1) { newuri = * lwContents.substring(j+4, k); redirectUrl = * getAbsoluteUrl(method,newuri); * Engine.logBeans.debug("(HttpConnector) Redirecting to : " * + redirectUrl); redirectMethod = new * GetMethod(redirectUrl); * * // set headers for (z=0; z<requestHeaders.length; z++) * redirectMethod.setRequestHeader(requestHeaders[z]); * * referer = redirectUrl; result = * executeMethod(redirectMethod, context); // recurse } } } * } // Handles FRAMESET else if * (lwContents.indexOf("frameset") != -1) { * Engine.logBeans.debug * ("(HttpConnector) Analyzing frameset..."); * StringTokenizer st = new StringTokenizer(lwContents); * StringEx newcontents = new StringEx(lwContents); while * (st.hasMoreTokens()) { String token = st.nextToken(); * String uri; if (token.startsWith("src=")) { if * ((token.indexOf("\"") != -1) || (token.indexOf("'") != * -1)) { token = token.substring(5); uri = * token.substring(0,token.length()-1); newuri = * getAbsoluteUrl(method,uri); * Engine.logBeans.trace("(HttpConnector) Replaced uri ("+ * uri +") with newuri("+ newuri +")"); * * newcontents.replaceAll(token,newuri); } } } * Engine.logBeans * .trace("(HttpConnector) New response content:\n"+ * newcontents); result = newcontents.toString().getBytes(); * } */ } } //Added by julienda - #3433 - 04/03/2013 AbstractHttpTransaction abstractHttpTransaction = (AbstractHttpTransaction) context.transaction; if (abstractHttpTransaction.getHttpInfo()) { Document doc = context.outputDocument; //Remove the node HTTPInfo if we have a redirect NodeList nodeList = XMLUtils.findElements(context.outputDocument.getDocumentElement(), abstractHttpTransaction.getHttpInfoTagName()); if (nodeList != null) { XMLUtils.removeNodeListContent(nodeList); } //Parent Element httpInfoElement = doc.createElement(abstractHttpTransaction.getHttpInfoTagName()); //Add requested URL Element urlElement = doc.createElement("url"); urlElement.setTextContent(method.getURI().toString()); httpInfoElement.appendChild(urlElement); //Add status code Element httpStatusElement = doc.createElement("status"); httpStatusElement.setAttribute("code", Integer.toString(statuscode)); httpStatusElement.setAttribute("text", method.getStatusText()); httpInfoElement.appendChild(httpStatusElement); //We add headers informations List<Header> headers = Arrays.asList(requestHeaders); if (!headers.isEmpty()) { Element httpHeadersElement = doc.createElement("headers"); for (int i = 0; i < headers.size(); i++) { Element elt = doc.createElement("header"); elt.setAttribute("name", headers.get(i).getName()); elt.setAttribute("value", headers.get(i).getValue()); httpHeadersElement.appendChild(elt); } httpInfoElement.appendChild(httpHeadersElement); } // we add response header information if (responseHeaders.length != 0) { Element httpHeadersElement = doc.createElement("responseHeaders"); for (int i = 0; i < responseHeaders.length; i++) { Element elt = doc.createElement("header"); elt.setAttribute("name", responseHeaders[i].getName()); elt.setAttribute("value", responseHeaders[i].getValue()); httpHeadersElement.appendChild(elt); } httpInfoElement.appendChild(httpHeadersElement); } doc.getDocumentElement().appendChild(httpInfoElement); } } finally { method.releaseConnection(); } return result; }
From source file:com.bluexml.side.Integration.alfresco.xforms.webscript.XFormsWork.java
private void replaceIds(Element element, Map<String, String> created) { if (StringUtils.equals(element.getTagName(), "target") || StringUtils.equals(element.getTagName(), "associationClass")) { String newId = created.get(element.getTextContent()); if (newId != null) { element.setTextContent(newId); }// w w w.j av a 2 s. c o m } String elementId = element.getAttribute("id"); String newId = created.get(elementId); if (newId != null) { element.setAttribute("id", newId); } List<Element> children = DOMUtil.getAllChildren(element); for (Element child : children) { replaceIds(child, created); } }
From source file:com.occamlab.te.parsers.ImageParser.java
private static Document parse(InputStream source, Element instruction, PrintWriter logger) throws Exception { ImageReader reader;// ww w.j a v a2s . com try { ImageInputStream iis = ImageIO.createImageInputStream(source); reader = ImageIO.getImageReaders(iis).next(); reader.setInput(iis); } catch (Exception e) { logger.println("No image handlers available for the data stream. " + e.getMessage()); throw e; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(instruction), new DOMResult(doc)); Element new_instruction = doc.getDocumentElement(); int framesRead = 0; boolean containsFrames = false; Element framesElement = null; Element metadataElement = null; NodeList nodes = new_instruction.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // System.out.println(node.getLocalName()); if (node.getLocalName().equals("type")) { node.setTextContent(reader.getFormatName().toLowerCase()); } else if (node.getLocalName().equals("frames")) { framesElement = (Element) node; containsFrames = true; } else if (node.getLocalName().equals("metadata")) { metadataElement = (Element) node; } else if (node.getLocalName().equals("frame")) { int frame; String frameStr = ((Element) node).getAttribute("num"); if (frameStr.length() == 0) { frame = framesRead; framesRead++; ((Element) node).setAttribute("num", Integer.toString(frame)); } else { frame = Integer.parseInt(frameStr); framesRead = frame + 1; } processFrame(reader, frame, node.getChildNodes(), logger); containsFrames = true; } } } if (containsFrames) { if (metadataElement != null) { IIOMetadata metadata = reader.getStreamMetadata(); if (metadata != null) { String format = metadataElement.getAttribute("format"); if (format.length() == 0) { format = metadata.getNativeMetadataFormatName(); } Node tree = metadata.getAsTree(format); t.transform(new DOMSource(tree), new DOMResult(metadataElement)); } } if (framesElement != null) { boolean allowSearch = !reader.isSeekForwardOnly(); int frames = reader.getNumImages(allowSearch); if (frames == -1) { try { while (true) { reader.read(framesRead); framesRead++; } } catch (Exception e) { jlogger.log(Level.SEVERE, "", e); frames = framesRead + 1; } } framesElement.setTextContent(Integer.toString(frames)); } } else { processFrame(reader, 0, nodes, logger); framesRead = 1; } // t.transform(new DOMSource(doc), new StreamResult(System.out)); return doc; }
From source file:fr.inria.atlanmod.collaboro.ui.views.NotationView.java
/** * Builds the SVG for the corresponding notationElement. The representation is for * the abstract syntax element./* www. j ava2 s . c om*/ * * @param notationElement * @param doc * @param x * @param y */ private Box buildSVG(NotationElement notationElement, SVGDocument doc, int x, int y) { Element svgRoot = doc.getDocumentElement(); Box result = new Box(0, 0, x, y); if (notationElement instanceof Composite) { Composite composite = (Composite) notationElement; result.setX(x); int oldX = x; for (NotationElement subElement : composite.getSubElements()) { if (subElement instanceof Composite) { x = oldX + TAB; y = y + VERTICAL_SEP; } Box subBox = buildSVG(subElement, doc, x, y); if ((subElement instanceof Composite) || (subElement instanceof SyntaxOf)) { x = oldX; y = y + subBox.getHeight() - VERTICAL_SEP; if (result.getWidth() < subBox.getWidth()) result.setWidth(subBox.getWidth()); result.setHeight(result.getHeight() + subBox.getHeight()); } else { x = x + subBox.getWidth(); result.setWidth(result.getWidth() + subBox.getWidth()); if (result.getHeight() < subBox.getHeight()) result.setHeight(subBox.getHeight()); } } } else if (notationElement instanceof TextualElement) { TextualElement textualElement = (TextualElement) notationElement; Element text = doc.createElementNS(SVGDOMImplementation.SVG_NAMESPACE_URI, "text"); text.setAttributeNS(null, "x", String.valueOf(x)); text.setAttributeNS(null, "y", String.valueOf(y)); text.setAttributeNS(null, "font-size", DEFAULT_FONT_SIZE); text.setAttributeNS(null, "font-family", DEFAULT_FONT_FAMILY); String value = ""; if (textualElement instanceof Keyword) { Keyword keyword = (Keyword) notationElement; text.setAttributeNS(null, "font-weight", "bold"); text.setAttributeNS(null, "fill", "green"); text.setAttributeNS(null, "stroke", "none"); value = keyword.getId(); } else if (textualElement instanceof Token) { Token token = (Token) notationElement; text.setAttributeNS(null, "fill", "black"); text.setAttributeNS(null, "stroke", "none"); value = token.getId(); } else if (textualElement instanceof AttributeValue) { AttributeValue attributeValue = (AttributeValue) notationElement; text.setAttributeNS(null, "fill", "orange"); value = "<value of '" + attributeValue.getAttribute().getName() + "' attribute>"; } else if (textualElement instanceof ReferenceValue) { ReferenceValue referenceValue = (ReferenceValue) notationElement; text.setAttributeNS(null, "fill", "orange"); value = "<value of '" + referenceValue.getReference().getName() + "' reference>"; } result.setWidth(value.length() * CHAR_SEP + CHAR_SEP); result.setHeight(VERTICAL_SEP); text.setTextContent(value); svgRoot.appendChild(text); } else if (notationElement instanceof SyntaxOf) { SyntaxOf syntaxOf = (SyntaxOf) notationElement; Element text = doc.createElementNS(SVGDOMImplementation.SVG_NAMESPACE_URI, "text"); text.setAttributeNS(null, "x", String.valueOf(x)); text.setAttributeNS(null, "y", String.valueOf(y)); text.setAttributeNS(null, "font-size", DEFAULT_FONT_SIZE); text.setAttributeNS(null, "font-family", DEFAULT_FONT_FAMILY); text.setAttributeNS(null, "fill", "blue"); String value = "<syntax of '" + syntaxOf.getReference().getName() + "' reference>"; text.setTextContent(value); result.setWidth(value.length() * CHAR_SEP + CHAR_SEP); result.setHeight(VERTICAL_SEP); svgRoot.appendChild(text); } return result; }
From source file:com.connectsdk.service.DLNAService.java
protected String getMetadata(String mediaURL, String subsUrl, String mime, String title, String description, String iconUrl) {/* w w w. ja v a2 s .c om*/ try { String objectClass = ""; if (mime.startsWith("image")) { objectClass = "object.item.imageItem"; } else if (mime.startsWith("video")) { objectClass = "object.item.videoItem"; } else if (mime.startsWith("audio")) { objectClass = "object.item.audioItem"; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element didlRoot = doc.createElement("DIDL-Lite"); Element itemElement = doc.createElement("item"); Element titleElement = doc.createElement("dc:title"); Element descriptionElement = doc.createElement("dc:description"); Element resElement = doc.createElement("res"); Element albumArtElement = doc.createElement("upnp:albumArtURI"); Element clazzElement = doc.createElement("upnp:class"); didlRoot.appendChild(itemElement); itemElement.appendChild(titleElement); itemElement.appendChild(descriptionElement); itemElement.appendChild(resElement); itemElement.appendChild(albumArtElement); itemElement.appendChild(clazzElement); didlRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"); didlRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:upnp", "urn:schemas-upnp-org:metadata-1-0/upnp/"); didlRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dc", "http://purl.org/dc/elements/1.1/"); didlRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:sec", "http://www.sec.co.kr/"); titleElement.setTextContent(title); descriptionElement.setTextContent(description); resElement.setTextContent(encodeURL(mediaURL)); albumArtElement.setTextContent(encodeURL(iconUrl)); clazzElement.setTextContent(objectClass); itemElement.setAttribute("id", "1000"); itemElement.setAttribute("parentID", "0"); itemElement.setAttribute("restricted", "0"); resElement.setAttribute("protocolInfo", "http-get:*:" + mime + ":DLNA.ORG_OP=01"); if (subsUrl != null) { resElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:pv", "http://www.pv.com/pvns/"); resElement.setAttribute("pv:subtitleFileUri", subsUrl); resElement.setAttribute("pv:subtitleFileType", "srt"); Element smiResElement = doc.createElement("res"); smiResElement.setAttribute("protocolInfo", "http-get::smi/caption:"); smiResElement.setTextContent(subsUrl); itemElement.appendChild(smiResElement); Element srtResElement = doc.createElement("res"); srtResElement.setAttribute("protocolInfo", "http-get::text/srt:"); srtResElement.setTextContent(subsUrl); itemElement.appendChild(srtResElement); Element captionInfoExElement = doc.createElement("sec:CaptionInfoEx"); captionInfoExElement.setAttribute("sec:type", "srt"); captionInfoExElement.setTextContent(subsUrl); itemElement.appendChild(captionInfoExElement); Element captionInfoElement = doc.createElement("sec:CaptionInfo"); captionInfoElement.setAttribute("sec:type", "srt"); captionInfoElement.setTextContent(subsUrl); itemElement.appendChild(captionInfoElement); } doc.appendChild(didlRoot); return xmlToString(doc, false); } catch (Exception e) { return null; } }
From source file:com.moviejukebox.writer.MovieJukeboxXMLWriter.java
private Element processIndexCategory(Document doc, String categoryName, String categoryKey, boolean isCurrentKey, IndexInfo idx, int indexSize, int previous, int current, int next, int last) { String encakey = FileTools.createCategoryKey(categoryName); boolean isCurrentCat = isCurrentKey && encakey.equalsIgnoreCase(idx.key); // Check to see if we need the non-current index if (!isCurrentCat && !fullCategoriesInIndexes) { // We don't need this index, so skip it return null; }/*from ww w. j a v a2 s. c om*/ // FIXME This is horrible! Issue 735 will get rid of it. if (indexSize < Library.calcMinCategoryCount(categoryName) && !Arrays.asList("Other,Genres,Title,Year,Library,Set".split(",")).contains(categoryKey)) { return null; } String prefix = FileTools.makeSafeFilename(FileTools.createPrefix(categoryKey, encakey)); Element eCategory = doc.createElement(INDEX); eCategory.setAttribute(NAME, categoryName); // The category changes only occur for "Other" category if (Library.INDEX_OTHER.equals(categoryKey)) { eCategory.setAttribute(ORIGINAL_NAME, Library.getOriginalCategory(encakey, Boolean.TRUE)); } // if currently writing this page then add current attribute with value true if (isCurrentCat) { eCategory.setAttribute("current", TRUE); eCategory.setAttribute("first", prefix + '1'); eCategory.setAttribute("previous", prefix + previous); eCategory.setAttribute("next", prefix + next); eCategory.setAttribute("last", prefix + last); eCategory.setAttribute("currentIndex", Integer.toString(current)); eCategory.setAttribute("lastIndex", Integer.toString(last)); } eCategory.setTextContent(prefix + '1'); return eCategory; }