Example usage for org.dom4j Element getTextTrim

List of usage examples for org.dom4j Element getTextTrim

Introduction

In this page you can find the example usage for org.dom4j Element getTextTrim.

Prototype

String getTextTrim();

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.openremote.modeler.service.ProtocolParser.java

License:Open Source License

/**
 * Parses the validators./*from   ww  w .j a v  a2  s  . c  o  m*/
 * 
 * @param validationsElement the validations element
 * 
 * @return the list< protocol validator>
 */
private List<ProtocolValidator> parseValidators(Element validationsElement) {
    List<ProtocolValidator> validators = new ArrayList<ProtocolValidator>();

    for (Iterator<Element> validationsItr = validationsElement.elementIterator(); validationsItr.hasNext();) {
        Element validatorElement = validationsItr.next();
        if (getValidatorType(validatorElement.getName()) == -1) {
            throw new ParseProtocolException("Can't find validator " + validatorElement.getName());
        }
        ProtocolValidator protocolValidator = new ProtocolValidator(
                getValidatorType(validatorElement.getName()), validatorElement.getTextTrim(),
                validatorElement.attributeValue(MESSAGE_ATTR_NAME));
        validators.add(protocolValidator);
    }
    return validators;
}

From source file:org.orbeon.oxf.processor.generator.BeanGenerator.java

License:Open Source License

protected Config getConfig(PipelineContext context) {
    return readCacheInputAsObject(context, getInputByName(INPUT_CONFIG), new CacheableInputReader<Config>() {
        public Config read(PipelineContext context, ProcessorInput input) {
            Document dom = readInputAsDOM4J(context, input);
            try {
                Config config2 = new Config();
                for (Iterator i = XPathUtils.selectIterator(dom, "/config/attribute"); i.hasNext();) {
                    Element el = (Element) i.next();
                    config2.addAttribute(el.getTextTrim());
                }/*www.  j a  va2 s. com*/

                for (Iterator i = XPathUtils.selectIterator(dom, "/config/source"); i.hasNext();) {
                    String s = ((Element) i.next()).getTextTrim();
                    if (s.equalsIgnoreCase("request"))
                        config2.addSource(Config.REQUEST);
                    else if (s.equalsIgnoreCase("session"))
                        config2.addSource(Config.SESSION);
                    else
                        throw new OXFException("Wrong source type: must be either request or session");
                }
                return config2;
            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    });
}

From source file:org.orbeon.oxf.processor.generator.URLGenerator.java

License:Open Source License

@Override
public ProcessorOutput createOutput(final String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(URLGenerator.this, name) {
        public void readImpl(PipelineContext pipelineContext, XMLReceiver xmlReceiver) {

            makeSureStateIsSet(pipelineContext);

            // Read config input into a URL, cache if possible
            final ConfigURIReferences configURIReferences = URLGenerator.this.localConfigURIReferences != null
                    ? localConfigURIReferences
                    : readCacheInputAsObject(pipelineContext, getInputByName(INPUT_CONFIG),
                            new CacheableInputReader<ConfigURIReferences>() {
                                public ConfigURIReferences read(PipelineContext context, ProcessorInput input) {
                                    final Element configElement = readInputAsDOM4J(context, input)
                                            .getRootElement();

                                    // Processor location data
                                    final LocationData locationData = URLGenerator.this.getLocationData();

                                    // Shortcut if the url is direct child of config
                                    {//from   ww w . j  a  v  a  2 s  . c om
                                        final String url = configElement.getTextTrim();
                                        if (url != null && !url.equals("")) {
                                            // Legacy, don't even care about handling relative URLs
                                            return new ConfigURIReferences(
                                                    new Config(URLFactory.createURL(url)));
                                        }
                                    }

                                    // We have the /config/url syntax
                                    final String url = XPathUtils.selectStringValueNormalize(configElement,
                                            "/config/url");
                                    if (url == null) {
                                        throw new ValidationException(
                                                "URL generator found null URL for config:\n"
                                                        + Dom4jUtils.domToString(configElement),
                                                locationData);
                                    }

                                    // Get content-type
                                    final String contentType = XPathUtils
                                            .selectStringValueNormalize(configElement, "/config/content-type");
                                    final boolean forceContentType = ProcessorUtils.selectBooleanValue(
                                            configElement, "/config/force-content-type",
                                            DEFAULT_FORCE_CONTENT_TYPE);
                                    if (forceContentType && (contentType == null || contentType.equals("")))
                                        throw new ValidationException(
                                                "The force-content-type element requires a content-type element.",
                                                locationData);

                                    // Get encoding
                                    final String encoding = XPathUtils.selectStringValueNormalize(configElement,
                                            "/config/encoding");
                                    final boolean forceEncoding = ProcessorUtils.selectBooleanValue(
                                            configElement, "/config/force-encoding", DEFAULT_FORCE_ENCODING);
                                    final boolean ignoreConnectionEncoding = ProcessorUtils.selectBooleanValue(
                                            configElement, "/config/ignore-connection-encoding",
                                            DEFAULT_IGNORE_CONNECTION_ENCODING);
                                    if (forceEncoding && (encoding == null || encoding.equals("")))
                                        throw new ValidationException(
                                                "The force-encoding element requires an encoding element.",
                                                locationData);

                                    // Get headers
                                    Map<String, String[]> headerNameValues = null;
                                    for (Object o : configElement.selectNodes("/config/header")) {
                                        final Element currentHeaderElement = (Element) o;
                                        final String currentHeaderName = currentHeaderElement.element("name")
                                                .getStringValue();
                                        final String currentHeaderValue = currentHeaderElement.element("value")
                                                .getStringValue();

                                        if (headerNameValues == null) {
                                            // Lazily create collections
                                            headerNameValues = new LinkedHashMap<String, String[]>();
                                        }

                                        headerNameValues.put(currentHeaderName,
                                                new String[] { currentHeaderValue });
                                    }

                                    final String forwardHeaders;
                                    {
                                        // Get from configuration first, otherwise use global default
                                        final org.dom4j.Node configForwardHeaders = XPathUtils
                                                .selectSingleNode(configElement, "/config/forward-headers");
                                        forwardHeaders = configForwardHeaders != null
                                                ? XPathUtils.selectStringValue(configForwardHeaders, ".")
                                                : Connection.getForwardHeaders();
                                    }

                                    // Validation setting: local, then properties, then hard-coded default
                                    final boolean defaultValidating = getPropertySet()
                                            .getBoolean(VALIDATING_PROPERTY, DEFAULT_VALIDATING);
                                    final boolean validating = ProcessorUtils.selectBooleanValue(configElement,
                                            "/config/validating", defaultValidating);

                                    // XInclude handling
                                    final boolean defaultHandleXInclude = getPropertySet()
                                            .getBoolean(HANDLE_XINCLUDE_PROPERTY, DEFAULT_HANDLE_XINCLUDE);
                                    final boolean handleXInclude = ProcessorUtils.selectBooleanValue(
                                            configElement, "/config/handle-xinclude", defaultHandleXInclude);

                                    // External entities
                                    final boolean externalEntities = ProcessorUtils.selectBooleanValue(
                                            configElement, "/config/external-entities",
                                            DEFAULT_EXTERNAL_ENTITIES);

                                    final boolean defaultHandleLexical = getPropertySet()
                                            .getBoolean(HANDLE_LEXICAL_PROPERTY, DEFAULT_HANDLE_LEXICAL);
                                    final boolean handleLexical = ProcessorUtils.selectBooleanValue(
                                            configElement, "/config/handle-lexical", defaultHandleLexical);

                                    // Output mode
                                    final String mode = XPathUtils.selectStringValueNormalize(configElement,
                                            "/config/mode");

                                    // Cache control
                                    final boolean cacheUseLocalCache = ProcessorUtils.selectBooleanValue(
                                            configElement, "/config/cache-control/use-local-cache",
                                            DEFAULT_CACHE_USE_LOCAL_CACHE);
                                    final boolean enableConditionalGET = ProcessorUtils.selectBooleanValue(
                                            configElement, "/config/cache-control/conditional-get",
                                            DEFAULT_ENABLE_CONDITIONAL_GET);

                                    // Authentication
                                    final org.dom4j.Node configAuthentication = XPathUtils
                                            .selectSingleNode(configElement, "/config/authentication");
                                    final String username = configAuthentication == null ? null
                                            : XPathUtils.selectStringValue(configAuthentication, "username");
                                    final String password = configAuthentication == null ? null
                                            : XPathUtils.selectStringValue(configAuthentication, "password");
                                    final boolean preemptiveAuthentication = ProcessorUtils.selectBooleanValue(
                                            configElement, "/config/authentication/preemptive",
                                            DEFAULT_PREEMPTIVE_AUTHENTICATION);
                                    final String domain = configAuthentication == null ? null
                                            : XPathUtils.selectStringValue(configAuthentication, "domain");

                                    // Get Tidy config (will only apply if content-type is text/html)
                                    final TidyConfig tidyConfig = new TidyConfig(
                                            XPathUtils.selectSingleNode(configElement, "/config/tidy-options"));

                                    // Create configuration object
                                    // Use location data if present so that relative URLs can be supported
                                    // NOTE: We check whether there is a protocol, because we have
                                    // some Java location data which are NOT to be interpreted as
                                    // base URIs
                                    final URL fullURL = (locationData != null
                                            && locationData.getSystemID() != null
                                            && NetUtils.urlHasProtocol(locationData.getSystemID()))
                                                    ? URLFactory.createURL(locationData.getSystemID(), url)
                                                    : URLFactory.createURL(url);

                                    // Create configuration
                                    final Config config = new Config(fullURL, contentType, forceContentType,
                                            encoding, forceEncoding, ignoreConnectionEncoding,
                                            new XMLUtils.ParserConfiguration(validating, handleXInclude,
                                                    externalEntities),
                                            handleLexical, mode, headerNameValues, forwardHeaders,
                                            cacheUseLocalCache, enableConditionalGET, username, password,
                                            preemptiveAuthentication, domain, tidyConfig);
                                    if (logger.isDebugEnabled())
                                        logger.debug("Read configuration: " + config.toString());
                                    return new ConfigURIReferences(config);
                                }
                            });
            try {
                // Never accept a null URL
                if (configURIReferences.config.getURL() == null)
                    throw new OXFException("Missing configuration.");

                // We use the same validity as for the output
                final boolean isUseLocalCache = configURIReferences.config.isCacheUseLocalCache();
                final CacheKey localCacheKey;
                final Object localCacheValidity;
                if (isUseLocalCache) {
                    localCacheKey = new InternalCacheKey(URLGenerator.this, "urlDocument",
                            configURIReferences.config.toString());
                    localCacheValidity = getValidityImpl(pipelineContext);
                } else {
                    localCacheKey = null;
                    localCacheValidity = null;
                }

                // Decide whether to use read from the special oxf: handler or the generic URL handler
                final URLGeneratorState state = (URLGenerator.URLGeneratorState) URLGenerator.this
                        .getState(pipelineContext);
                if (state.getDocument() != null) {
                    // Document was found when retrieving validity in conditional get
                    // NOTE: This only happens if isCacheUseLocalCache() == true
                    // NOTE: Document was re-added to cache in getValidityImpl()
                    state.getDocument().replay(xmlReceiver);
                } else {
                    final Object cachedResource = (localCacheKey == null) ? null
                            : ObjectCache.instance().findValid(localCacheKey, localCacheValidity);
                    if (cachedResource != null) {
                        // Just replay the cached resource
                        ((SAXStore) cachedResource).replay(xmlReceiver);
                    } else {
                        final ResourceHandler handler = state.ensureMainResourceHandler(pipelineContext,
                                configURIReferences.config);
                        try {
                            // We need to read the resource

                            // Find content-type to use. If the config says to force the
                            // content-type, we use the content-type provided by the user.
                            // Otherwise, we give the priority to the content-type provided by
                            // the connection, then the content-type provided by the user, then
                            // we use the default content-type (XML). The user will have to
                            // provide a content-type for example to read HTML documents with
                            // the file: protocol.
                            String contentType;
                            if (configURIReferences.config.isForceContentType()) {
                                contentType = configURIReferences.config.getContentType();
                            } else {
                                contentType = handler.getResourceMediaType();
                                if (contentType == null)
                                    contentType = configURIReferences.config.getContentType();
                                if (contentType == null)
                                    contentType = ProcessorUtils.DEFAULT_CONTENT_TYPE;
                            }

                            // Get and cache validity as the handler is open, as validity is likely to be used later
                            // again for caching reasons
                            final Long validity = (Long) getHandlerValidity(pipelineContext,
                                    configURIReferences.config, configURIReferences.config.getURL(), handler);

                            // Create store for caching if necessary
                            final XMLReceiver output = isUseLocalCache ? new SAXStore(xmlReceiver)
                                    : xmlReceiver;

                            // Handle mode
                            String mode = configURIReferences.config.getMode();
                            if (mode == null) {
                                // Mode is inferred from content-type
                                if (ProcessorUtils.HTML_CONTENT_TYPE.equals(contentType))
                                    mode = "html";
                                else if (XMLUtils.isXMLMediatype(contentType))
                                    mode = "xml";
                                else if (XMLUtils.isTextOrJSONContentType(contentType))
                                    mode = "text";
                                else
                                    mode = "binary";
                            }

                            // Read resource
                            if (mode.equals("html")) {
                                // HTML mode
                                handler.readHTML(output);
                                configURIReferences.uriReferences = null;
                            } else if (mode.equals("xml")) {
                                // XML mode
                                final URIProcessorOutputImpl.URIReferences uriReferences = new URIProcessorOutputImpl.URIReferences();
                                handler.readXML(pipelineContext, output, uriReferences);
                                configURIReferences.uriReferences = uriReferences.getReferences();
                            } else if (mode.equals("text")) {
                                // Text mode
                                handler.readText(output, contentType, validity);
                                configURIReferences.uriReferences = null;
                            } else {
                                // Binary mode
                                handler.readBinary(output, contentType, validity);
                                configURIReferences.uriReferences = null;
                            }

                            // Cache the resource if requested but only if there is not a failure status code. It
                            // seems reasonable to follow the semantic of the web and to never cache unsuccessful
                            // responses.
                            if (isUseLocalCache && !handler.isFailureStatusCode()) {
                                // Make sure SAXStore loses its reference on its output so that we don't clutter the cache
                                ((SAXStore) output).setXMLReceiver(null);
                                // Add to cache
                                ObjectCache.instance().add(localCacheKey, localCacheValidity, output);
                            }
                        } finally {
                            handler.destroy();
                        }
                    }
                }
            } catch (SAXParseException spe) {
                throw new ValidationException(spe.getMessage(), new LocationData(spe));
            } catch (ValidationException e) {
                final LocationData locationData = e.firstLocationData();
                // The system id may not be set
                if (locationData == null || locationData.getSystemID() == null)
                    throw OrbeonLocationException.wrapException(e,
                            new LocationData(configURIReferences.config.getURL().toExternalForm(), -1, -1));
                else
                    throw e;
            } catch (OXFException e) {
                throw e;
            } catch (Exception e) {
                throw new ValidationException(e,
                        new LocationData(configURIReferences.config.getURL().toExternalForm(), -1, -1));
            }
        }

        @Override
        public OutputCacheKey getKeyImpl(PipelineContext pipelineContext) {
            makeSureStateIsSet(pipelineContext);

            final ConfigURIReferences configURIReferences = getConfigURIReferences(pipelineContext);
            if (configURIReferences == null) {
                return null;
            }

            final int keyCount = 1 + ((localConfigURIReferences == null) ? 1 : 0)
                    + ((configURIReferences.uriReferences != null) ? configURIReferences.uriReferences.size()
                            : 0);
            final CacheKey[] outputKeys = new CacheKey[keyCount];

            // Handle config if read as input
            int keyIndex = 0;
            if (localConfigURIReferences == null) {
                KeyValidity configKeyValidity = getInputKeyValidity(pipelineContext, INPUT_CONFIG);
                if (configKeyValidity == null) {
                    return null;
                }
                outputKeys[keyIndex++] = configKeyValidity.key;
            }
            // Handle main document and config
            outputKeys[keyIndex++] = new SimpleOutputCacheKey(getProcessorClass(), name,
                    configURIReferences.config.toString());
            // Handle dependencies if any
            if (configURIReferences.uriReferences != null) {
                for (URIProcessorOutputImpl.URIReference uriReference : configURIReferences.uriReferences) {
                    outputKeys[keyIndex++] = new InternalCacheKey(URLGenerator.this, "urlReference",
                            URLFactory.createURL(uriReference.context, uriReference.spec).toExternalForm());
                }
            }
            return new CompoundOutputCacheKey(getProcessorClass(), name, outputKeys);
        }

        @Override
        public Object getValidityImpl(PipelineContext pipelineContext) {
            makeSureStateIsSet(pipelineContext);

            ConfigURIReferences configURIReferences = getConfigURIReferences(pipelineContext);
            if (configURIReferences == null)
                return null;

            List<Object> validities = new ArrayList<Object>();

            // Handle config if read as input
            if (localConfigURIReferences == null) {
                KeyValidity configKeyValidity = getInputKeyValidity(pipelineContext, INPUT_CONFIG);
                if (configKeyValidity == null)
                    return null;
                validities.add(configKeyValidity.validity);
            }

            // Handle main document and config
            final URLGeneratorState state = (URLGenerator.URLGeneratorState) URLGenerator.this
                    .getState(pipelineContext);
            final ResourceHandler resourceHandler = state.ensureMainResourceHandler(pipelineContext,
                    configURIReferences.config);
            validities.add(getHandlerValidity(pipelineContext, configURIReferences.config,
                    configURIReferences.config.getURL(), resourceHandler));

            // Handle dependencies if any
            if (configURIReferences.uriReferences != null) {
                for (URIProcessorOutputImpl.URIReference uriReference : configURIReferences.uriReferences) {
                    validities.add(getHandlerValidity(pipelineContext, configURIReferences.config,
                            URLFactory.createURL(uriReference.context, uriReference.spec), null));
                }
            }
            return validities;
        }

        private Long getHandlerValidity(PipelineContext pipelineContext, Config config, URL url,
                ResourceHandler handler) {
            final URLGeneratorState state = (URLGenerator.URLGeneratorState) URLGenerator.this
                    .getState(pipelineContext);
            final String urlString = url.toExternalForm();
            if (state.isLastModifiedSet(urlString)) {
                // Found value in state cache
                return state.getLastModified(urlString);
            } else {
                // Get value and cache it in state
                try {
                    final Long validity;
                    if (handler == null) {
                        // Include dependency

                        // Create handler right here
                        handler = OXFHandler.PROTOCOL.equals(url.getProtocol())
                                ? new OXFResourceHandler(new Config(url)) // Should use full config so that headers are forwarded?
                                : new URLResourceHandler(new Config(url));// Should use full config so that headers are forwarded?

                        try {
                            // FIXME: this can potentially be very slow with some URLs like HTTP URLs. We try to
                            // optimized this by keeping the URLConnection for the main document, but dependencies may
                            // cause multiple requests to the same URL.
                            validity = handler.getValidity();
                        } finally {
                            // Destroy handler
                            handler.destroy();
                        }
                    } else {
                        // Main handler

                        // Try to see what we have in cache
                        final CacheEntry cacheEntry;
                        if (config.isEnableConditionalGET()) {
                            // NOTE: This *could* be transparently handled by HttpClient cache if configured properly:
                            // http://hc.apache.org/httpcomponents-client-ga/httpclient-cache/apidocs/org/apache/http/impl/client/cache/CachingHttpClient.html
                            // Although, this would only cache the bytes, and probably not provide us with a
                            // readily-parsed SAXStore.
                            final CacheKey localCacheKey = new InternalCacheKey(URLGenerator.this,
                                    "urlDocument", config.toString());
                            cacheEntry = ObjectCache.instance().findAny(localCacheKey);
                        } else {
                            cacheEntry = null;
                        }

                        if (cacheEntry != null) {
                            // Found some entry in cache for the key
                            final long lastModified = findLastModified(cacheEntry.validity);
                            // This returns the validity and, possibly, stores the document in the state
                            validity = handler.getConditional(lastModified);
                            if (handler.getConnectionStatusCode() == 304) {
                                // The server responded that the resource hasn't changed

                                // Update the entry in cache
                                ObjectCache.instance().add(cacheEntry.key, lastModified, cacheEntry.cacheable);

                                // Remember the document for the rest of this request
                                state.setDocument((SAXStore) cacheEntry.cacheable);
                            }
                        } else {
                            validity = handler.getValidity();
                        }
                    }
                    state.setLastModified(urlString, validity);
                    return validity;

                } catch (Exception e) {
                    // If the file no longer exists, for example, we don't want to throw, just to invalidate
                    // An exception will be thrown if necessary when the document is actually read
                    return null;
                }
            }
        }

        private ConfigURIReferences getConfigURIReferences(PipelineContext context) {
            // Check if config is external
            if (localConfigURIReferences != null)
                return localConfigURIReferences;

            // Make sure the config input is cacheable
            final KeyValidity keyValidity = getInputKeyValidity(context, INPUT_CONFIG);
            if (keyValidity == null) {
                return null;
            }

            // Try to find resource manager key in cache
            final ConfigURIReferences config = (ConfigURIReferences) ObjectCache.instance()
                    .findValid(keyValidity.key, keyValidity.validity);
            if (logger.isDebugEnabled()) {
                if (config != null)
                    logger.debug("Config found: " + config.toString());
                else
                    logger.debug("Config not found");
            }
            return config;
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.processor.LDAPProcessor.java

License:Open Source License

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(LDAPProcessor.this, name) {
        public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) {
            try {
                // Read configuration
                Config config = readCacheInputAsObject(context, getInputByName(INPUT_CONFIG),
                        new CacheableInputReader<Config>() {
                            public Config read(PipelineContext context, ProcessorInput input) {
                                Config config = new Config();
                                Document doc = readInputAsDOM4J(context, input);

                                // Try local configuration first
                                String host = XPathUtils.selectStringValueNormalize(doc, "/config/host");
                                Integer port = XPathUtils.selectIntegerValue(doc, "/config/port");
                                String bindDN = XPathUtils.selectStringValueNormalize(doc, "/config/bind-dn");
                                String password = XPathUtils.selectStringValueNormalize(doc,
                                        "/config/password");
                                String protocol = XPathUtils.selectStringValueNormalize(doc,
                                        "/config/protocol");
                                String referral = XPathUtils.selectStringValueNormalize(doc,
                                        "/config/referral ");
                                String scope = XPathUtils.selectStringValueNormalize(doc, "/config/scope");

                                //logger.info("Referral="+referral);

                                // Override with properties if needed
                                config.setHost(host != null ? host : getPropertySet().getString(HOST_PROPERTY));
                                config.setPort(port != null ? port.intValue()
                                        : getPropertySet().getInteger(PORT_PROPERTY).intValue());
                                config.setBindDN(
                                        bindDN != null ? bindDN : getPropertySet().getString(BIND_PROPERTY));
                                config.setPassword(password != null ? password
                                        : getPropertySet().getString(PASSWORD_PROPERTY));
                                config.setProtocol(protocol != null ? protocol
                                        : getPropertySet().getString(PROTOCOL_PROPERTY));
                                config.setScope(
                                        scope != null ? scope : getPropertySet().getString(SCOPE_PROPERTY));

                                // If not set use providers default. Valid values are follow, ignore, throw
                                if (referral != null) {
                                    config.setReferral(referral);
                                }/*  w  w w  . j a  va2  s. c om*/

                                // The password and bind DN are allowed to be blank
                                if (password == null)
                                    config.setPassword("");
                                if (bindDN == null)
                                    config.setBindDN("");

                                config.setRootDN(XPathUtils.selectStringValueNormalize(doc, "/config/root-dn"));

                                for (Iterator i = XPathUtils.selectIterator(doc, "/config/attribute"); i
                                        .hasNext();) {
                                    Element e = (Element) i.next();
                                    config.addAttribute(e.getTextTrim());
                                }
                                return config;
                            }
                        });

                Command command = readCacheInputAsObject(context, getInputByName(INPUT_FILTER),
                        new CacheableInputReader<Command>() {
                            public Command read(PipelineContext context, ProcessorInput input) {
                                Command command;
                                Document filterDoc = readInputAsDOM4J(context, input);
                                String filterNodeName = filterDoc.getRootElement().getName();

                                if ("update".equals(filterNodeName)) {
                                    command = new Update();
                                    command.setName(XPathUtils.selectStringValue(filterDoc, "/update/name"));
                                    parseAttributes(filterDoc, "/update/attribute", (Update) command);

                                } else if ("add".equals(filterNodeName)) {
                                    command = new Add();
                                    command.setName(XPathUtils.selectStringValue(filterDoc, "/add/name"));
                                    parseAttributes(filterDoc, "/add/attribute", (Add) command);

                                } else if ("delete".equals(filterNodeName)) {
                                    command = new Delete();
                                    command.setName(XPathUtils.selectStringValue(filterDoc, "/delete/name"));

                                } else if ("filter".equals(filterNodeName)) {
                                    command = new Search();
                                    command.setName(
                                            XPathUtils.selectStringValueNormalize(filterDoc, "/filter"));
                                } else {
                                    throw new OXFException("Wrong command: use filter or update");
                                }

                                return command;
                            }
                        });

                if (logger.isDebugEnabled())
                    logger.debug("LDAP Command: " + command.toString());

                DirContext ctx = connect(config);

                if (command instanceof Update) {
                    update(ctx, (Update) command);
                    outputSuccess(xmlReceiver, "update");
                } else if (command instanceof Add) {
                    add(ctx, (Add) command);
                    outputSuccess(xmlReceiver, "add");
                } else if (command instanceof Delete) {
                    delete(ctx, (Delete) command);
                    outputSuccess(xmlReceiver, "delete");
                } else if (command instanceof Search) {
                    // There was incorrect code here earlier testing on instanceof String[], which broke stuff. For
                    // now assume all attrs are strings.
                    final List attributesList = config.getAttributes();
                    final String[] attrs = new String[attributesList.size()];
                    attributesList.toArray(attrs);

                    List results = search(ctx, config.getRootDN(), config.getScope(), command.getName(), attrs);
                    serialize(results, config, xmlReceiver);
                }

                disconnect(ctx);
            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.processor.tamino.dom4j.TDOM4JXMLOutputter.java

License:Open Source License

/**
* <p>//  w  w w. j  a v  a  2 s  .com
* This will handle printing out an <code>{@link Element}</code>,
*   its <code>{@link Attribute}</code>s, and its value.
* </p>
*
* @param element <code>Element</code> to output.
* @param out <code>Writer</code> to write to.
* @param indent <code>int</code> level of indention.
* @param namespaces <code>List</code> stack of Namespaces in scope.
*/
protected void printElement(Element element, Writer out, int indentLevel, TDOM4JNamespaceStack namespaces)
        throws IOException {

    List mixedContent = element.elements();

    boolean empty = mixedContent.size() == 0;
    boolean stringOnly = !empty && mixedContent.size() == 1 && mixedContent.get(0) instanceof String;

    // Print beginning element tag
    /* maybe the doctype, xml declaration, and processing instructions
     should only break before and not after; then this check is
     unnecessary, or maybe the println should only come after and
     never before.  Then the output always ends with a newline */

    indent(out, indentLevel);

    // Print the beginning of the tag plus attributes and any
    // necessary namespace declarations
    out.write("<");
    out.write(element.getQualifiedName());
    int previouslyDeclaredNamespaces = namespaces.size();

    Namespace ns = element.getNamespace();

    // Add namespace decl only if it's not the XML namespace and it's
    // not the NO_NAMESPACE with the prefix "" not yet mapped
    // (we do output xmlns="" if the "" prefix was already used and we
    // need to reclaim it for the NO_NAMESPACE)
    if (ns != Namespace.XML_NAMESPACE && !(ns == Namespace.NO_NAMESPACE && namespaces.getURI("") == null)) {
        String prefix = ns.getPrefix();
        String uri = namespaces.getURI(prefix);
        if (!ns.getURI().equals(uri)) { // output a new namespace decl
            namespaces.push(ns);
            printNamespace(ns, out);
        }
    }

    // Print out additional namespace declarations
    List additionalNamespaces = element.additionalNamespaces();
    if (additionalNamespaces != null) {
        for (int i = 0; i < additionalNamespaces.size(); i++) {
            Namespace additional = (Namespace) additionalNamespaces.get(i);
            String prefix = additional.getPrefix();
            String uri = namespaces.getURI(prefix);
            if (!additional.getURI().equals(uri)) {
                namespaces.push(additional);
                printNamespace(additional, out);
            }
        }
    }

    printAttributes(element.attributes(), element, out, namespaces);

    // handle "" string same as empty
    if (stringOnly) {
        String elementText = trimText ? element.getTextTrim() : element.getText();
        if (elementText == null || elementText.equals("")) {
            empty = true;
        }
    }

    if (empty) {
        // Simply close up
        if (!expandEmptyElements) {
            out.write(" />");
        } else {
            out.write("></");
            out.write(element.getQualifiedName());
            out.write(">");
        }
        maybePrintln(out);
    } else {
        // we know it's not null or empty from above
        out.write(">");

        if (stringOnly) {
            // if string only, print content on same line as tags
            printElementContent(element, out, indentLevel, namespaces, mixedContent);
        } else {
            maybePrintln(out);
            printElementContent(element, out, indentLevel, namespaces, mixedContent);
            indent(out, indentLevel);
        }

        out.write("</");
        out.write(element.getQualifiedName());
        out.write(">");

        maybePrintln(out);
    }

    // remove declared namespaces from stack
    while (namespaces.size() > previouslyDeclaredNamespaces) {
        namespaces.pop();
    }
}

From source file:org.orbeon.oxf.processor.tamino.dom4j.TDOM4JXMLOutputter.java

License:Open Source License

/**
* <p> This will handle printing out an <code>{@link
* Element}</code>'s content only, not including its tag,
* attributes, and namespace info.  </p>
*
* @param element <code>Element</code> to output.
* @param out <code>Writer</code> to write to.
* @param indent <code>int</code> level of indention.  */
protected void printElementContent(Element element, Writer out, int indentLevel,
        TDOM4JNamespaceStack namespaces, List mixedContent) throws IOException {
    // get same local flags as printElement does
    // a little redundant code-wise, but not performance-wise
    boolean empty = mixedContent.size() == 0;
    boolean stringOnly = !empty && (mixedContent.size() == 1) && mixedContent.get(0) instanceof String;

    if (stringOnly) {
        // Print the tag  with String on same line
        // Example: <tag name="value">content</tag>
        String elementText = trimText ? element.getTextTrim() : element.getText();

        out.write(escapeElementEntities(elementText));

    } else {//w w  w  .j av a  2s  .c o m
        /**
         * Print with children on future lines
         * Rather than check for mixed content or not, just print
         * Example: <tag name="value">
         *             <child/>
         *          </tag>
         */
        // Iterate through children
        Object content = null;
        Class justOutput = null;
        for (int i = 0, size = mixedContent.size(); i < size; i++) {
            content = mixedContent.get(i);
            // See if text, an element, a PI or a comment
            if (content instanceof Comment) {
                printComment((Comment) content, out, indentLevel + 1);
                justOutput = Comment.class;
            } else if (content instanceof String) {
                if (padText && (justOutput == Element.class))
                    out.write(padTextString);
                printString((String) content, out);
                justOutput = String.class;
            } else if (content instanceof Element) {
                if (padText && (justOutput == String.class))
                    out.write(padTextString);
                printElement((Element) content, out, indentLevel + 1, namespaces);
                justOutput = Element.class;
            } else if (content instanceof Entity) {
                printEntity((Entity) content, out);
                justOutput = Entity.class;
            } else if (content instanceof ProcessingInstruction) {
                printProcessingInstruction((ProcessingInstruction) content, out, indentLevel + 1);
                justOutput = ProcessingInstruction.class;
            } else if (content instanceof CDATA) {
                printCDATASection((CDATA) content, out, indentLevel + 1);
                justOutput = CDATA.class;
            }
            // Unsupported types are *not* printed
        }
    }
}

From source file:org.orbeon.oxf.xforms.state.XFormsStateManager.java

License:Open Source License

/**
 * Get the document UUID from an incoming request.
 *
 * @param request   incoming//  w  w  w .  j ava 2  s.c o m
 * @return          document UUID
 */
public static String getRequestUUID(Document request) {
    final Element uuidElement = request.getRootElement().element(XFormsConstants.XXFORMS_UUID_QNAME);
    assert uuidElement != null;
    return StringUtils.trimToNull(uuidElement.getTextTrim());
}

From source file:org.orbeon.oxf.xforms.state.XFormsStateManager.java

License:Open Source License

/**
 * Get the request sequence number from an incoming request.
 *
 * @param request   incoming/*from  ww  w .j  a  va 2  s.  c o  m*/
 * @return          request sequence number, or -1 if missing
 */
public static long getRequestSequence(Document request) {
    final Element sequenceElement = request.getRootElement().element(XFormsConstants.XXFORMS_SEQUENCE_QNAME);
    assert sequenceElement != null;
    final String text = StringUtils.trimToNull(sequenceElement.getTextTrim());
    return (text != null) ? Long.parseLong(text) : -1; // allow for empty value for non-Ajax cases
}

From source file:org.orbeon.oxf.xforms.state.XFormsStateManager.java

License:Open Source License

public RequestParameters extractParameters(Document request, boolean isInitialState) {

    // Get UUID//from   w w  w  . j ava2s . c o m
    final String uuid = getRequestUUID(request);
    assert uuid != null;

    // Get static state if any
    final String encodedStaticState;
    {
        final Element staticStateElement = request.getRootElement()
                .element(XFormsConstants.XXFORMS_STATIC_STATE_QNAME);
        encodedStaticState = (staticStateElement != null)
                ? StringUtils.trimToNull(staticStateElement.getTextTrim())
                : null;
    }

    // Get dynamic state if any
    final String encodedDynamicState;
    {
        final QName qName = isInitialState ? XFormsConstants.XXFORMS_INITIAL_DYNAMIC_STATE_QNAME
                : XFormsConstants.XXFORMS_DYNAMIC_STATE_QNAME;
        final Element dynamicStateElement = request.getRootElement().element(qName);
        encodedDynamicState = (dynamicStateElement != null)
                ? StringUtils.trimToNull(dynamicStateElement.getTextTrim())
                : null;
    }

    assert (encodedStaticState != null && encodedDynamicState != null)
            || (encodedStaticState == null && encodedDynamicState == null);

    // Session must be present if state is not coming with the request
    if (NetUtils.getSession(false) == null && encodedStaticState == null) {
        throw new OXFException("Session has expired. Unable to process incoming request.");
    }

    return new RequestParametersImpl(uuid, encodedStaticState, encodedDynamicState);
}

From source file:org.peerfact.impl.scenario.DOMScenarioFactory.java

License:Open Source License

@Override
public void parse(Element elem, Configurator config) {
    // create the scenario wright now.
    ExtendedScenario newScenario = newScenario();
    // List<OperationBasedScenarioAction> actions = new
    // LinkedList<OperationBasedScenarioAction>();
    try {/*from  w ww . ja  va 2 s  .co m*/
        int actionCounter = 0;
        for (Iterator<Element> it = elem.elementIterator(Configurator.ACTION_TAG); it.hasNext();) {
            Element actionElem = it.next();
            String hostId = actionElem.attributeValue("hostID");
            String time = actionElem.attributeValue("time");
            String line = actionElem.getTextTrim();
            String[] tokens = line.split(paramsDelimiter);
            assert tokens.length >= 1 : Arrays.asList(tokens);

            String method = tokens[0];
            String[] params = new String[tokens.length - 1];
            System.arraycopy(tokens, 1, params, 0, params.length);

            newScenario.createActions(hostId, time, method, params);
            actionCounter++;
        }
        log.debug("Created " + actionCounter + " actions");
    } catch (Exception e) {
        throw new ConfigurationException("Failed to parse DOM element " + elem.asXML() + " reason: ", e);
    }
}