Example usage for org.apache.commons.jxpath JXPathContext getContextBean

List of usage examples for org.apache.commons.jxpath JXPathContext getContextBean

Introduction

In this page you can find the example usage for org.apache.commons.jxpath JXPathContext getContextBean.

Prototype

public Object getContextBean() 

Source Link

Document

Returns the JavaBean associated with this context.

Usage

From source file:org.chiba.xml.xforms.xpath.ChibaExtensionFunctions.java

/**
 * custom extension function to get the lastModified Date of a local file.
 *
 * @param expressionContext// w  ww. j a v  a  2s  .  c  om
 * @param nodeset must contain a single node that has a filename or path as
 * value. The value will be resolved against the baseURI of the processor to
 * find the file.
 * @param format a format pattern conformant with to
 * java.text.SimpleDateFormat. If an empty string is passed the format
 * defaults to "dd.MM.yyyy H:m:s".
 * @return the formatted lastModified Date of the file
 * @see java.text.SimpleDateFormat
 */
public static String fileDate(ExpressionContext expressionContext, List nodeset, String format) {
    if ((nodeset == null) || (nodeset.size() == 0)) {
        return "Error: Nodeset does not exist";
    }
    JXPathContext rootContext = expressionContext.getJXPathContext();

    while (rootContext != null) {
        Object rootNode = rootContext.getContextBean();

        if (rootNode instanceof Instance) {
            //                //get the Context
            //                Instance instance = (Instance) rootNode;
            //                String baseUri = instance.getModel().getContainer().getProcessor().getBaseURI();
            //
            //                File file = new File(baseUri,(String) nodeset.get(0));
            //                if(!file.exists()){
            //                    LOGGER.info("File " + file.toString() + " does not exist");
            //                    return "";
            //                }
            //get the Context
            Instance instance = (Instance) rootNode;
            String baseUri = instance.getModel().getContainer().getProcessor().getBaseURI();
            String path;
            try {
                //                    uri = new URI(baseUri).getPath();
                path = new URI(baseUri).getPath().substring(1);
            } catch (URISyntaxException e) {
                return "Error: base URI not valid: " + baseUri;
            }

            File file = new File(path, (String) nodeset.get(0));
            if (!file.exists() || file.isDirectory()) {
                LOGGER.info("File " + file.toString() + " does not exist or is directory");
                return "";
            }

            return formatDateString(file, format);
        }
        rootContext = rootContext.getParentContext();
    }
    return "Error: Calculation failed";
}

From source file:org.chiba.xml.xforms.xpath.ExtensionFunctionsHelper.java

/**
 * Extracts the Chiba container from an JXPath expression context.
 *
 * @param expressionContext the JXPath expression context.
 * @return the Chiba container./*from ww w .  j  a v a2 s.  c  o  m*/
 */
public static Container getChibaContainer(ExpressionContext expressionContext) {
    if (expressionContext == null) {
        return null;
    }

    Object rootNode;
    JXPathContext rootContext = expressionContext.getJXPathContext();

    while (rootContext != null) {
        rootNode = rootContext.getContextBean();
        if (rootNode instanceof XFormsElement) {
            return ((XFormsElement) rootNode).getModel().getContainer();
        }

        rootContext = rootContext.getParentContext();
    }

    return null;
}

From source file:org.chiba.xml.xforms.xpath.XFormsExtensionFunctions.java

/**
 * The index() Function [7.7.5]./*from   w  ww  . j  av  a  2s  .com*/
 * <p/>
 * Function index takes a string argument that is the idref of a repeat
 * and returns the current 1-based position of the repeat index for the
 * identified repeat see 9.3.1 The repeat Element for details on repeat
 * and its associated repeat index. If the specified argument does not
 * identify a repeat, processing stops with an exception.
 *
 * @param context the expression context.
 * @param idref   the repeat id.
 * @return the specified repeat index.
 * @throws XFormsException if any error occurred during repeat index lookup.
 */
public static int index(ExpressionContext context, String idref) throws XFormsException {
    JXPathContext rootContext = context.getJXPathContext();

    while (rootContext != null) {
        Object rootNode = rootContext.getContextBean();

        if (rootNode instanceof XFormsElement) {
            XFormsElement element = (XFormsElement) rootNode;
            Repeat repeat = (Repeat) element.getModel().getContainer().lookup(idref);

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("index for Element: " + element.getId() + " evaluated to " + repeat.getIndex());
            }
            return repeat.getIndex();
        }

        rootContext = rootContext.getParentContext();
    }

    throw new XFormsException("invalid expression context when evaluating index('" + idref + "')");
}

From source file:org.chiba.xml.xforms.xpath.XFormsExtensionFunctions.java

/**
 * The instance() Function [7.10.1]./*from   www.ja  va  2 s  . c  o  m*/
 * <p/>
 * An XForms Model can contain more that one instance. This function allows
 * access to instance data, within the same XForms Model, but outside the
 * instance data containing the context node.
 * <p/>
 * The argument is converted to a string as if by a call to the string function.
 * This string is treated as an IDREF, which is matched against instance elements
 * in the containing document. If a match is located, and the matching instance
 * data is associated with the same XForms Model as the current context node,
 * this function returns a node-set containing just the root element node (also
 * called the document element node) of the referenced instance data. In all
 * other cases, an empty node-set is returned.
 *
 * @param context the expression context.
 * @param idref   the instance id.
 * @return the specified instance.
 * @throws XFormsException if any error occurred during instance lookup.
 */
public static Object instance(ExpressionContext context, String idref) throws XFormsException {
    JXPathContext rootContext = context.getJXPathContext();

    while (rootContext != null) {
        Object rootNode = rootContext.getContextBean();

        //does not work cause rootnode is no XFormsElement
        if (rootNode instanceof XFormsElement) {
            Object instance = ((XFormsElement) rootNode).getModel().getContainer().lookup(idref);

            if (instance != null && instance instanceof Instance) {
                Pointer pointer = ((Instance) instance).getPointer(BindingResolver.OUTERMOST_CONTEXT);
                return pointer;
            }
        }

        rootContext = rootContext.getParentContext();
    }

    throw new XFormsException("invalid expression context when evaluating instance('" + idref + "')");
}

From source file:org.openvpms.component.business.domain.im.archetype.descriptor.NodeDescriptor.java

/**
 * Returns the value of this node given the specified context.
 *
 * @param context the context to use/*from  w w  w. j av  a  2 s . c  om*/
 * @return Object
 *         the returned object
 */
public Object getValue(JXPathContext context) {
    Object value = null;
    if (context != null) {
        if (isDerived()) {
            value = context.getValue(getDerivedValue());
        } else {
            if (isCollection()) {
                value = getChildren((IMObject) context.getContextBean());
            } else {
                value = context.getValue(getPath());
            }
        }
    }

    return value;
}

From source file:org.openvpms.component.business.service.archetype.AbstractIMObjectFactory.java

/**
 * Iterate through all the nodes in the archetype definition and create the default object.
 *
 * @param context the JXPath/*from ww  w . j  a va  2s  . c om*/
 * @param nodes   the node descriptors for the archetype
 * @throws ArchetypeServiceException if the create fails
 */
private void create(JXPathContext context, Map<String, NodeDescriptor> nodes) {
    for (NodeDescriptor node : nodes.values()) {
        // only create a node if it is a collection, or it has child nodes, or it has a default value
        if (node.isCollection() || node.getNodeDescriptorCount() > 0
                || !StringUtils.isEmpty(node.getDefaultValue())) {
            create(context, node);
        }

        for (AssertionDescriptor assertion : node.getAssertionDescriptorsAsArray()) {
            try {
                assertion.create(context.getContextBean(), node);
            } catch (Exception exception) {
                throw new ArchetypeServiceException(
                        ArchetypeServiceException.ErrorCode.FailedToExecuteCreateFunction, exception,
                        assertion.getName());
            }
        }

        // if this node has children then process them recursively
        if (node.getNodeDescriptors().size() > 0) {
            create(context, node.getNodeDescriptors());
        }
    }
}

From source file:org.openvpms.component.business.service.archetype.AbstractIMObjectFactory.java

/**
 * Creates a node in the context, populating any default value.
 *
 * @param context the jxpath context/*from  w ww . jav a 2  s.  c o  m*/
 * @param node    the node to create
 * @throws ArchetypeServiceException if the create fails
 */
private void create(JXPathContext context, NodeDescriptor node) {
    if (log.isDebugEnabled()) {
        log.debug("Attempting to create path " + node.getPath() + " for node " + node.getName());
    }

    context.getVariables().declareVariable("node", node);
    context.createPath(node.getPath());

    String expression = node.getDefaultValue();
    if (!StringUtils.isEmpty(expression)) {
        if (log.isDebugEnabled()) {
            log.debug("evaluating default value expression for node " + node.getName() + " path "
                    + node.getPath() + " and expression " + expression);
        }
        Object value = context.getValue(expression);
        IMObject object = (IMObject) context.getContextBean();
        if (node.isCollection()) {
            if (value != null) {
                if (Collection.class.isAssignableFrom(value.getClass())) {
                    for (Object v : (Collection) value) {
                        node.addChildToCollection(object, v);
                    }
                } else {
                    node.addChildToCollection(object, value);
                }
            }
        } else {
            node.setValue(object, value);
        }
    }
}

From source file:org.openvpms.component.business.service.archetype.JXPathGenericObjectCreationFactory.java

@Override
public boolean createObject(JXPathContext context, Pointer ptr, Object parent, String name, int index) {
    try {/* w  ww.j av  a 2 s  .  c  om*/
        NodeDescriptor node = (NodeDescriptor) context.getVariables().getVariable("node");

        if (logger.isDebugEnabled()) {
            logger.debug("root: " + context.getContextBean().toString() + " parent: " + parent.toString()
                    + " name: " + name + " index: " + index + " type: " + node.getType());
        }

        Class clazz = Thread.currentThread().getContextClassLoader().loadClass(node.getType());
        if (clazz == Boolean.class) {
            ptr.setValue(new Boolean(false));
        } else if (clazz == Integer.class) {
            ptr.setValue(new Integer(0));
        } else if (clazz == Long.class) {
            ptr.setValue(new Long(0L));
        } else if (clazz == Double.class) {
            ptr.setValue(new Double(0.0));
        } else if (clazz == Float.class) {
            ptr.setValue(new Float(0.0));
        } else if (clazz == Short.class) {
            ptr.setValue(new Short((short) 0));
        } else if (clazz == Byte.class) {
            ptr.setValue(new Byte((byte) 0));
        } else if (clazz == Money.class) {
            ptr.setValue(new Money("0.0"));
        } else if (clazz == BigDecimal.class) {
            ptr.setValue(BigDecimal.valueOf(0.0));
        } else {
            ptr.setValue(clazz.newInstance());
        }
    } catch (Exception exception) {
        logger.error("root: " + context.getContextBean().toString() + " parent: " + parent.toString()
                + " name: " + name + " index: " + index, exception);
        return false;
    }

    return true;
}

From source file:org.xchain.framework.lifecycle.Execution.java

/**
 * Start an execution stack on the current thread.
 * //from  ww  w .  j  a  va2s  . c  om
 * @param globalContext The global JXPathContext for this execution.
 */
public static void startExecution(JXPathContext globalContext) {
    // Wrap the incoming context in a global context
    executionContextTl
            .set(new ScopedJXPathContextImpl(globalContext, globalContext.getContextBean(), Scope.execution));
    executionContextStack.push(new GlobalExecutionContext());
}

From source file:org.xchain.framework.lifecycle.Execution.java

/**
 * <p>Signals that the execute method of a command has been called.  If this command is registered with a catalog, then
 * a new local context is created based on the current context that was passed in.</p>
 *
 * <p>NOTE: This command is used by the engineering framework and should not be called directly by
 * command implementations.</p>/*from   w  w w. j av  a2  s . c om*/
 *
 * @param command the command that is being executed.
 * @param context the current local context or the global context.
 * @return the current local context.  If the command is registered with a catalog, then the context returned is
 * the new local context for this command.  Otherwise, the context returned will be the same as the context passed in.
 */
public static JXPathContext startCommandExecute(Command command, JXPathContext context) {
    JXPathContext localContext = null;

    // push this command onto the stack.
    executionContextStack.push(new CommandExecutionContext(command));

    if (isLocalContextBoundary(command)) {
        // create the new local context.
        localContext = new ScopedJXPathContextImpl(executionContextTl.get(), context.getContextBean(),
                context.getContextPointer(), Scope.chain);

        // push the local context.
        chainContextStack.push(localContext);

        startExecutionTrace(command);
    } else if (!(context instanceof ScopedJXPathContextImpl)) {
        throw new IllegalStateException("Initial call to command that is not registered with a catalog.");
    }

    updateExecutionTraceLocation();

    // get the local context.
    context = getCurrentContext();
    if (command instanceof EngineeredCommand) {
        // Define prefix mappings for engineered commands.
        definePrefixMappings(context, (EngineeredCommand) command);
    }

    // return the context.
    return context;
}