List of usage examples for org.dom4j Element getStringValue
String getStringValue();
From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java
License:Apache License
private String loadTitle(Document xmlDoc) { Element el = xmlDoc.getRootElement().element(new QName(KEYWORD_TITLE, namespaceDC)); if (el != null) return el.getStringValue(); else/*from w ww . j a v a 2 s. c o m*/ return null; }
From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java
License:Apache License
private String loadVersion(Document xmlDoc) { Element el = xmlDoc.getRootElement().element(new QName(KEYWORD_VERSION, namespaceCP)); if (el != null) return el.getStringValue(); else// w w w.j av a2s. c om return null; }
From source file:org.orbeon.oxf.portlet.processor.PortletPreferencesSerializer.java
License:Open Source License
public void start(PipelineContext pipelineContext) { final ExternalContext externalContext = (ExternalContext) pipelineContext .getAttribute(PipelineContext.EXTERNAL_CONTEXT); final PortletRequest portletRequest = (PortletRequest) externalContext.getRequest().getNativeRequest(); final PortletPreferences preferences = portletRequest.getPreferences(); final Document document = readInputAsDOM4J(pipelineContext, INPUT_DATA); boolean modified = false; for (Iterator i = document.getRootElement().elements().iterator(); i.hasNext();) { final Element currentElement = (Element) i.next(); final String currentName = currentElement.element("name").getStringValue(); final List valueElements = currentElement.elements("value"); if (valueElements.size() > 0) { // There are some values, extract them... final String[] currentValuesArray = new String[valueElements.size()]; int valueIndex = 0; for (Iterator j = valueElements.iterator(); j.hasNext(); valueIndex++) { final Element currentValueElement = (Element) j.next(); final String currentValue = currentValueElement.getStringValue(); currentValuesArray[valueIndex] = currentValue; }// ww w. jav a 2s. co m try { // ...and set the values preferences.setValues(currentName, currentValuesArray); modified = true; } catch (ReadOnlyException e) { throw new OXFException(e); } } else { // If no value was passed, we take it that we want to reset the preference try { preferences.reset(currentName); } catch (ReadOnlyException e) { throw new OXFException(e); } } } if (modified) { try { preferences.store(); } catch (Exception e) { throw new OXFException(e); } } }
From source file:org.orbeon.oxf.processor.converter.QNameConverter.java
License:Open Source License
@Override public ProcessorOutput createOutput(String name) { final ProcessorOutput output = new CacheableTransformerOutputImpl(QNameConverter.this, name) { public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) { // Read config input final Config config = readCacheInputAsObject(context, getInputByName(INPUT_CONFIG), new CacheableInputReader<Config>() { public Config read(org.orbeon.oxf.pipeline.api.PipelineContext context, ProcessorInput input) { Config result = new Config(); Element configElement = readInputAsDOM4J(context, input).getRootElement(); {/*from w w w.j a va2 s.c o m*/ Element matchURIElement = configElement.element("match").element("uri"); result.matchURI = (matchURIElement == null) ? null : matchURIElement.getStringValue(); Element matchPrefixElement = configElement.element("match").element("prefix"); result.matchPrefix = (matchPrefixElement == null) ? null : matchPrefixElement.getStringValue(); } { Element replaceURIElement = configElement.element("replace").element("uri"); result.replaceURI = (replaceURIElement == null) ? null : replaceURIElement.getStringValue(); Element replacePrefixElement = configElement.element("replace") .element("prefix"); result.replacePrefix = (replacePrefixElement == null) ? null : replacePrefixElement.getStringValue(); } return result; } }); // Do the conversion readInputAsSAX(context, INPUT_DATA, new ForwardingXMLReceiver(xmlReceiver) { private NamespaceContext namespaceContext = new NamespaceContext(); @Override public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { namespaceContext.startElement(); if (config.matchURI == null || config.matchURI.equals(uri)) { int colonIndex = qName.indexOf(':'); String prefix = (colonIndex == -1) ? "" : qName.substring(0, colonIndex); if (config.matchPrefix == null || config.matchPrefix.equals(prefix)) { // Match: replace prefix or URI or both String newURI = (config.replaceURI == null) ? uri : config.replaceURI; String newQName; if (config.replacePrefix == null) { newQName = qName; } else if (colonIndex == -1) { final StringBuilder sb = new StringBuilder( config.replacePrefix.length() + qName.length() + 1); sb.append(config.replacePrefix); sb.append(':'); sb.append(qName); newQName = sb.toString(); } else { final StringBuilder sb = new StringBuilder( config.replacePrefix.length() + qName.length()); sb.append(config.replacePrefix); sb.append(qName.substring(colonIndex)); newQName = sb.toString(); } checkNamespace(uri, newURI, prefix, (config.replacePrefix == null) ? prefix : config.replacePrefix, true); super.startElement(newURI, localname, newQName, attributes); } else { // No match super.startElement(uri, localname, qName, attributes); } } else { // No match super.startElement(uri, localname, qName, attributes); } } @Override public void endElement(String uri, String localname, String qName) throws SAXException { if (config.matchURI == null || config.matchURI.equals(uri)) { int colonIndex = qName.indexOf(':'); String prefix = (colonIndex == -1) ? "" : qName.substring(0, colonIndex); if (config.matchPrefix == null || config.matchPrefix.equals(prefix)) { // Match: replace prefix or URI or both String newURI = (config.replaceURI == null) ? uri : config.replaceURI; String newQName; if (config.replacePrefix == null) { newQName = qName; } else if (colonIndex == -1) { final StringBuilder sb = new StringBuilder( config.replacePrefix.length() + qName.length() + 1); sb.append(config.replacePrefix); sb.append(':'); sb.append(qName); newQName = sb.toString(); } else { final StringBuilder sb = new StringBuilder( config.replacePrefix.length() + qName.length()); sb.append(config.replacePrefix); sb.append(qName.substring(colonIndex)); newQName = sb.toString(); } super.endElement(newURI, localname, newQName); checkNamespace(uri, newURI, prefix, (config.replacePrefix == null) ? prefix : config.replacePrefix, false); } else { // No match super.endElement(uri, localname, qName); } } else { // No match super.endElement(uri, localname, qName); } namespaceContext.endElement(); } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { namespaceContext.startPrefixMapping(prefix, uri); super.startPrefixMapping(prefix, uri); } @Override public void endPrefixMapping(String prefix) throws SAXException { super.endPrefixMapping(prefix); } private void checkNamespace(String matchURI, String newURI, String matchPrefix, String newPrefix, boolean start) throws SAXException { if (matchURI.equals(newURI) && !matchPrefix.equals(newPrefix)) { // Changing prefixes but keeping URI if (!isURIInScopeForPrefix(newPrefix, newURI)) { // new prefix -> URI not in scope if (start) { super.startPrefixMapping(newPrefix, newURI); if (namespaceContext.getURI(newPrefix) == null) namespaceContext.startPrefixMapping(newPrefix, newURI); } else { super.endPrefixMapping(newPrefix); } } } } private boolean isURIInScopeForPrefix(String prefix, String uri) { String inScopeURIForPrefix = namespaceContext.getURI(prefix); return (inScopeURIForPrefix != null) && inScopeURIForPrefix.equals(uri); } }); } }; addOutput(name, output); return output; }
From source file:org.orbeon.oxf.processor.EmailProcessor.java
License:Open Source License
public void start(PipelineContext pipelineContext) { try {//from ww w. j a v a2 s . c o m final Document dataDocument = readInputAsDOM4J(pipelineContext, INPUT_DATA); final Element messageElement = dataDocument.getRootElement(); // Get system id (will likely be null if document is generated dynamically) final LocationData locationData = (LocationData) messageElement.getData(); final String dataInputSystemId = locationData.getSystemID(); // Set SMTP host final Properties properties = new Properties(); final String testSmtpHostProperty = getPropertySet().getString(EMAIL_TEST_SMTP_HOST); if (testSmtpHostProperty != null) { // Test SMTP Host from properties overrides the local configuration properties.setProperty("mail.smtp.host", testSmtpHostProperty); } else { // Try regular config parameter and property String host = messageElement.element("smtp-host").getTextTrim(); if (host != null && !host.equals("")) { // Precedence goes to the local config parameter properties.setProperty("mail.smtp.host", host); } else { // Otherwise try to use a property host = getPropertySet().getString(EMAIL_SMTP_HOST); if (host == null) host = getPropertySet().getString(EMAIL_HOST_DEPRECATED); if (host == null) throw new OXFException("Could not find SMTP host in configuration or in properties"); properties.setProperty("mail.smtp.host", host); } } // Create session final Session session; { // Get credentials final String usernameTrimmed; final String passwordTrimmed; { final Element credentials = messageElement.element("credentials"); if (credentials != null) { final Element usernameElement = credentials.element("username"); final Element passwordElement = credentials.element("password"); usernameTrimmed = (usernameElement != null) ? usernameElement.getStringValue().trim() : null; passwordTrimmed = (passwordElement != null) ? passwordElement.getStringValue().trim() : ""; } else { usernameTrimmed = null; passwordTrimmed = null; } } // Check if credentials are supplied if (StringUtils.isNotEmpty(usernameTrimmed)) { // NOTE: A blank username doesn't trigger authentication if (logger.isInfoEnabled()) logger.info("Authentication"); // Set the auth property to true properties.setProperty("mail.smtp.auth", "true"); if (logger.isInfoEnabled()) logger.info("Username: " + usernameTrimmed); // Create an authenticator final Authenticator authenticator = new SMTPAuthenticator(usernameTrimmed, passwordTrimmed); // Create session with authenticator session = Session.getInstance(properties, authenticator); } else { if (logger.isInfoEnabled()) logger.info("No Authentication"); session = Session.getInstance(properties); } } // Create message final Message message = new MimeMessage(session); // Set From message.addFrom(createAddresses(messageElement.element("from"))); // Set To String testToProperty = getPropertySet().getString(EMAIL_TEST_TO); if (testToProperty == null) testToProperty = getPropertySet().getString(EMAIL_FORCE_TO_DEPRECATED); if (testToProperty != null) { // Test To from properties overrides local configuration message.addRecipient(Message.RecipientType.TO, new InternetAddress(testToProperty)); } else { // Regular list of To elements for (final Element toElement : Dom4jUtils.elements(messageElement, "to")) { final InternetAddress[] addresses = createAddresses(toElement); message.addRecipients(Message.RecipientType.TO, addresses); } } // Set Cc for (final Element ccElement : Dom4jUtils.elements(messageElement, "cc")) { final InternetAddress[] addresses = createAddresses(ccElement); message.addRecipients(Message.RecipientType.CC, addresses); } // Set Bcc for (final Element bccElement : Dom4jUtils.elements(messageElement, "bcc")) { final InternetAddress[] addresses = createAddresses(bccElement); message.addRecipients(Message.RecipientType.BCC, addresses); } // Set headers if any for (final Element headerElement : Dom4jUtils.elements(messageElement, "header")) { final String headerName = headerElement.element("name").getTextTrim(); final String headerValue = headerElement.element("value").getTextTrim(); // NOTE: Use encodeText() in case there are non-ASCII characters message.addHeader(headerName, MimeUtility.encodeText(headerValue, DEFAULT_CHARACTER_ENCODING, null)); } // Set the email subject // The JavaMail spec is badly written and is not clear about whether this needs to be done here. But it // seems to use the platform's default charset, which we don't want to deal with. So we preemptively encode. // The result is pure ASCII so that setSubject() will not attempt to re-encode it. message.setSubject(MimeUtility.encodeText(messageElement.element("subject").getStringValue(), DEFAULT_CHARACTER_ENCODING, null)); // Handle body final Element textElement = messageElement.element("text"); final Element bodyElement = messageElement.element("body"); if (textElement != null) { // Old deprecated mechanism (simple text body) message.setText(textElement.getStringValue()); } else if (bodyElement != null) { // New mechanism with body and parts handleBody(pipelineContext, dataInputSystemId, message, bodyElement); } else { throw new OXFException("Main text or body element not found");// TODO: location info } // Send message final Transport transport = session.getTransport("smtp"); Transport.send(message); transport.close(); } catch (Exception e) { throw new OXFException(e); } }
From source file:org.orbeon.oxf.processor.EmailProcessor.java
License:Open Source License
private InternetAddress[] createAddresses(Element addressElement) throws AddressException, UnsupportedEncodingException { final String email = addressElement.element("email").getStringValue(); final Element nameElement = addressElement.element("name"); // If only the <email> element is specified, allow for comma-separated addresses return nameElement == null ? InternetAddress.parse(email) : new InternetAddress[] { new InternetAddress(email, nameElement.getStringValue()) }; }
From source file:org.orbeon.oxf.processor.generator.XLSGenerator.java
License:Open Source License
@Override public ProcessorOutput createOutput(String name) { ProcessorOutput output = new ProcessorOutputImpl(XLSGenerator.this, name) { public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) { try { // Read binary content of uploaded Excel file final byte[] fileContent; {//from w w w . j av a 2s. co m final String NO_FILE = "No file was uploaded"; final DocumentInfo requestDocument = readInputAsTinyTree(context, getInputByName(INPUT_REQUEST), XPathCache.getGlobalConfiguration()); final PooledXPathExpression expr = XPathCache.getXPathExpression( requestDocument.getConfiguration(), requestDocument, "/request/parameters/parameter[1]/value", getLocationData()); final Element valueElement = (Element) expr.evaluateSingleToJavaReturnToPoolOrNull(); if (valueElement == null) throw new OXFException(NO_FILE); String type = valueElement.attributeValue(XMLConstants.XSI_TYPE_QNAME); if (type == null) throw new OXFException(NO_FILE); if (type.endsWith("anyURI")) { // Read file from disk String url = valueElement.getStringValue(); InputStream urlInputStream = new URL(url).openStream(); byte[] buffer = new byte[1024]; ByteArrayOutputStream fileByteArray = new ByteArrayOutputStream(); int size; while ((size = urlInputStream.read(buffer)) != -1) fileByteArray.write(buffer, 0, size); urlInputStream.close(); fileContent = fileByteArray.toByteArray(); } else { // Decode base64 fileContent = Base64.decode(valueElement.getStringValue()); } } // Generate XML from Excel file final java.io.ByteArrayInputStream bais = new ByteArrayInputStream(fileContent); final org.dom4j.Document d = extractFromXLS(bais); final DOMGenerator domGenerator = new DOMGenerator(d, "xls generator output", DOMGenerator.ZeroValidity, DOMGenerator.DefaultContext); domGenerator.createOutput(OUTPUT_DATA).read(context, xmlReceiver); } catch (IOException e) { throw new OXFException(e); } } private Document extractFromXLS(InputStream inputStream) throws IOException { // Create workbook HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(inputStream)); // Create document final NonLazyUserDataElement root = new NonLazyUserDataElement("workbook"); final Document resultDocument = new NonLazyUserDataDocument(root); // Add elements for each sheet for (int i = 0; i < workbook.getNumberOfSheets(); i++) { HSSFSheet sheet = workbook.getSheetAt(i); final Element element = new NonLazyUserDataElement("sheet"); resultDocument.getRootElement().add(element); // Go though each cell XLSUtils.walk(workbook.createDataFormat(), sheet, new XLSUtils.Handler() { public void cell(HSSFCell cell, String sourceXPath, String targetXPath) { if (targetXPath != null) { int cellType = cell.getCellType(); String value = null; switch (cellType) { case HSSFCell.CELL_TYPE_STRING: case HSSFCell.CELL_TYPE_BLANK: value = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: double doubleValue = cell.getNumericCellValue(); if (((double) ((int) doubleValue)) == doubleValue) { // This is an integer value = Integer.toString((int) doubleValue); } else { // This is a floating point number value = XMLUtils.removeScientificNotation(doubleValue); } break; } if (value == null) throw new OXFException("Unkown cell type " + cellType + " for XPath expression '" + targetXPath + "'"); addToElement(element, targetXPath, value); } } }); } return resultDocument; } private void addToElement(Element element, String xpath, String value) { StringTokenizer elements = new StringTokenizer(xpath, "/"); while (elements.hasMoreTokens()) { String name = elements.nextToken(); if (elements.hasMoreTokens()) { // Not the last: try to find sub element, otherwise create Element child = element.element(name); if (child == null) { child = new NonLazyUserDataElement(name); element.add(child); } element = child; } else { // Last: add element, set content to value Element child = new NonLazyUserDataElement(name); child.add(Dom4jUtils.createText(value)); element.add(child); } } } }; addOutput(name, output); return output; }
From source file:org.orbeon.oxf.processor.scope.ScopeProcessorBase.java
License:Open Source License
protected ContextConfig readConfig(PipelineContext context) { return readCacheInputAsObject(context, getInputByName(ProcessorImpl.INPUT_CONFIG), new CacheableInputReader<ContextConfig>() { public ContextConfig read(PipelineContext context, ProcessorInput input) { final Element rootElement = readInputAsDOM4J(context, input).getRootElement(); final String contextName = rootElement.element("scope").getStringValue(); final Element sessionScopeElement = rootElement.element("session-scope"); final Element contentTypeElement = rootElement.element("content-type"); final String contentType = (contentTypeElement == null) ? APPLICATION_XML : (TEXT_PLAIN.equals(contentTypeElement.getStringValue())) ? TEXT_PLAIN : null; final String sessionScopeValue = (sessionScopeElement == null) ? null : sessionScopeElement.getStringValue(); return new ContextConfig( "request".equals(contextName) ? REQUEST_CONTEXT : "session".equals(contextName) ? SESSION_CONTEXT : "application".equals(contextName) ? APPLICATION_CONTEXT : -1, "application".equals(sessionScopeValue) ? ExternalContext.Session.APPLICATION_SCOPE : "portlet".equals(sessionScopeValue) ? ExternalContext.Session.PORTLET_SCOPE : -1, rootElement.element("key").getStringValue(), contentType, ProcessorUtils.selectBooleanValue(rootElement, "/*/test-ignore-stored-key-validity", false)); }/*ww w. j a v a2s . c o m*/ }); }
From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java
License:Open Source License
/** * Extract a QName from an Element's string value. The prefix of the QName must be in scope. * Return null if the text is empty./* ww w.ja va 2 s . co m*/ */ public static QName extractTextValueQName(Element element, boolean unprefixedIsNoNamespace) { return extractTextValueQName(element, element.getStringValue(), unprefixedIsNoNamespace); }
From source file:org.pentaho.platform.plugin.services.pluginmgr.SystemPathXmlPluginProvider.java
License:Open Source License
protected void processExternalResources(PlatformPlugin plugin, Document doc) { Node parentNode = doc.selectSingleNode("//external-resources"); //$NON-NLS-1$ if (parentNode == null) { return;//from w ww . j a v a 2 s. co m } for (Object obj : parentNode.selectNodes("file")) { Element node = (Element) obj; if (node != null) { String context = node.attributeValue("context"); //$NON-NLS-1$ String resource = node.getStringValue(); plugin.addExternalResource(context, resource); } } }