Example usage for org.apache.commons.lang3 StringUtils defaultString

List of usage examples for org.apache.commons.lang3 StringUtils defaultString

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils defaultString.

Prototype

public static String defaultString(final String str) 

Source Link

Document

Returns either the passed in String, or if the String is null , an empty String ("").

 StringUtils.defaultString(null)  = "" StringUtils.defaultString("")    = "" StringUtils.defaultString("bat") = "bat" 

Usage

From source file:org.displaytag.export.XmlTotalsWriter.java

/**
 * Cdata.//ww  w.  jav a2s.c o m
 *
 * @param str the str
 */
protected void cdata(Object str) {
    this.xml.append("<![CDATA[");
    String defStr = StringUtils.defaultString("" + str);
    this.xml.append(defStr);
    this.xml.append("]]>");
}

From source file:org.displaytag.export.XmlTotalsWriter.java

/**
 * @see org.displaytag.render.TableWriterTemplate#writeDecoratedRowStart(org.displaytag.model.TableModel)
 *///from  w w w . j  ava  2  s. c  o  m
@Override
protected void writeDecoratedRowStart(TableModel model) {
    this.xml.append(StringUtils.defaultString(model.getTableDecorator().startRow()));
}

From source file:org.displaytag.export.XmlTotalsWriter.java

@Override
protected void writeDecoratedRowFinish(TableModel model) {
    this.xml.append(StringUtils.defaultString(model.getTableDecorator().finishRow()));
}

From source file:org.esigate.vars.VariablesResolver.java

private static String processVar(String var, String arg, DriverRequest request) {
    IncomingRequest incomingRequest = null;
    if (request != null) {
        incomingRequest = request.getOriginalRequest();
    }// ww  w  .j  a va 2 s  . c  om
    String res = null;
    if (var.indexOf("QUERY_STRING") != -1) {
        if (arg == null) {
            res = UriUtils.getRawQuery(incomingRequest.getRequestLine().getUri());
        } else {
            res = HttpRequestHelper.getParameter(request, arg);
        }
    } else if (var.indexOf("HTTP_ACCEPT_LANGUAGE") != -1) {
        String langs = HttpRequestHelper.getFirstHeader("Accept-Language", incomingRequest);
        if (arg == null) {
            res = langs;
        } else {
            res = String.valueOf(!(langs == null || langs.indexOf(arg) == -1));
        }
    } else if (var.contains("HTTP_HEADER")) {
        res = HttpRequestHelper.getFirstHeader(arg, incomingRequest);
    } else if (var.indexOf("HTTP_HOST") != -1) {
        res = HttpRequestHelper.getFirstHeader("Host", incomingRequest);
    } else if (var.indexOf("HTTP_REFERER") != -1) {
        res = HttpRequestHelper.getFirstHeader("Referer", incomingRequest);
    } else if (var.indexOf("HTTP_COOKIE") != -1) {
        if (arg == null) {
            // Add cookies
            // In request header
            String cookieHeaderValue = StringUtils.EMPTY;
            for (Cookie c : request.getOriginalRequest().getCookies()) {
                if (StringUtils.isNotBlank(cookieHeaderValue)) {
                    cookieHeaderValue = cookieHeaderValue + "; ";
                }
                cookieHeaderValue = cookieHeaderValue + c.getName() + "=" + c.getValue();
            }
            if (StringUtils.isNotBlank(cookieHeaderValue)) {
                res = cookieHeaderValue;
            }
        } else {
            Cookie[] cookies = request.getOriginalRequest().getCookies();
            for (Cookie c : cookies) {
                if (c.getName().equals(arg)) {
                    res = c.getValue();
                    break;
                }
            }
        }
    } else if (var.indexOf("HTTP_USER_AGENT") != -1) {
        if (arg == null) {
            res = HttpRequestHelper.getFirstHeader("User-agent", incomingRequest);
        } else {
            String userAgent = StringUtils
                    .defaultString(HttpRequestHelper.getFirstHeader("User-Agent", incomingRequest))
                    .toLowerCase();
            if (arg.equals("os")) {
                if (userAgent.indexOf("unix") != -1) {
                    res = "UNIX";
                } else if (userAgent.indexOf("mac") != -1) {
                    res = "MAC";
                } else if (userAgent.indexOf("windows") != -1) {
                    res = "WIN";
                } else {
                    res = "OTHER";
                }
            } else if (arg.equals("browser")) {
                if (userAgent.indexOf("msie") != -1) {
                    res = "MSIE";
                } else {
                    res = "MOZILLA";
                }
            } else if (arg.equals("version")) {
                Matcher m = userAgentVersion.matcher(userAgent);

                if (m.find()) {
                    res = m.group(1);
                }
            }
        }
    } else if (var.indexOf("PROVIDER") != -1) {
        String providerUrl = StringUtils.EMPTY;
        try {
            Driver driver = DriverFactory.getInstance(arg);
            providerUrl = driver.getConfiguration().getBaseUrlRetrieveStrategy()
                    .getBaseURL(request.getOriginalRequest());
        } catch (Exception e) {
            // No driver available for this id.
        }

        return providerUrl;

    }
    return res;
}

From source file:org.exolab.castor.xml.StartElementProcessor.java

public void compute(String name, String namespace, AttributeSet atts) throws SAXException {

    UnmarshalState state = null;/* w w  w.  ja  va2s. co  m*/
    String xmlSpace = null;

    // -- handle special atts
    if (atts != null) {
        // -- xml:space
        xmlSpace = atts.getValue(UnmarshalHandler.XML_SPACE, Namespaces.XML_NAMESPACE);
        if (xmlSpace == null) {
            xmlSpace = atts.getValue(UnmarshalHandler.XML_SPACE_WITH_PREFIX, "");
        }
    }

    if (_unmarshalHandler.getStateStack().isEmpty()) {
        // -- Initialize since this is the first element
        _unmarshalHandler.processFirstElement(name, namespace, atts, xmlSpace);
        return;
    } // --rootElement

    // -- get MarshalDescriptor for the given element
    UnmarshalState parentState = _unmarshalHandler.getStateStack().getLastState();

    // Test if we can accept the field in the parentState
    // in case the parentState fieldDesc is a container
    // -- This following logic tests to see if we are in a
    // -- container and we need to close out the container
    // -- before proceeding:
    boolean canAccept = false;
    while ((parentState.getFieldDescriptor() != null)
            && (parentState.getFieldDescriptor().isContainer() && !canAccept)) {
        XMLClassDescriptor tempClassDesc = parentState.getClassDescriptor();

        // -- Find ClassDescriptor for Parent
        if (tempClassDesc == null) {
            tempClassDesc = (XMLClassDescriptor) parentState.getFieldDescriptor().getClassDescriptor();
            if (tempClassDesc == null)
                tempClassDesc = _unmarshalHandler.getClassDescriptor(parentState.getObject().getClass());
        }

        canAccept = tempClassDesc.canAccept(name, namespace, parentState.getObject());

        if (!canAccept) {
            // -- Does container class even handle this field?
            if (tempClassDesc.getFieldDescriptor(name, namespace, NodeType.Element) != null) {
                if (!parentState.getFieldDescriptor().isMultivalued()) {
                    String error = MessageFormat.format(
                            resourceBundle.getString("unmarshalHandler.error.container.full"),
                            new Object[] { tempClassDesc.getJavaClass().getName(), name });
                    ValidationException vx = new ValidationException(error);
                    throw new SAXException(vx);
                }
            }
            _unmarshalHandler.endElement(parentState.getElementName());
            parentState = _unmarshalHandler.getStateStack().getLastState();
        }
        tempClassDesc = null;
    }

    // -- create new state object
    state = new UnmarshalState();
    state.setElementName(name);
    state.setParent(parentState);

    if (xmlSpace != null) {
        state.setWhitespacePreserving(UnmarshalHandler.PRESERVE.equals(xmlSpace));
    } else {
        state.setWhitespacePreserving(parentState.isWhitespacePreserving());
    }

    _unmarshalHandler.getStateStack().pushState(state);

    // -- make sure we should proceed
    if (parentState.getObject() == null) {
        if (!parentState.isWrapper()) {
            return;
        }
    }

    Class cls = null;

    // -- Find ClassDescriptor for Parent
    XMLClassDescriptor classDesc = parentState.getClassDescriptor();
    if (classDesc == null) {
        classDesc = (XMLClassDescriptor) parentState.getFieldDescriptor().getClassDescriptor();
        if (classDesc == null)
            classDesc = _unmarshalHandler.getClassDescriptor(parentState.getObject().getClass());
    } else {
        // classDesc.resetElementCount();
    }

    // ----------------------------------------------------/
    // - Find FieldDescriptor associated with the element -/
    // ----------------------------------------------------/

    // -- A reference to the FieldDescriptor associated
    // -- the the "current" element
    XMLFieldDescriptor descriptor = null;

    // -- inherited class descriptor
    // -- (only needed if descriptor cannot be found directly)
    XMLClassDescriptor cdInherited = null;

    // -- loop through stack and find correct descriptor
    // int pIdx = _stateInfo.size() - 2; //-- index of parentState
    UnmarshalState targetState = parentState;
    String path = "";
    int count = 0;
    boolean isWrapper = false;
    XMLClassDescriptor oldClassDesc = classDesc;
    while (descriptor == null) {

        // -- NOTE (kv 20050228):
        // -- we need to clean this code up, I made this
        // -- fix to make sure the correct descriptor which
        // -- matches the location path is used
        if (path.length() > 0) {
            String tmpName = path + "/" + name;
            descriptor = classDesc.getFieldDescriptor(tmpName, namespace, NodeType.Element);
        }
        // -- End Patch

        if (descriptor == null) {
            descriptor = classDesc.getFieldDescriptor(name, namespace, NodeType.Element);
        }

        // -- Namespace patch, should be moved to XMLClassDescriptor, but
        // -- this is the least intrusive patch at the moment. kv - 20030423
        if ((descriptor != null) && (!descriptor.isContainer())) {
            if (StringUtils.isNotEmpty(namespace)) {
                if (!MarshalFramework.namespaceEquals(namespace, descriptor.getNameSpaceURI())) {
                    // -- if descriptor namespace is not null, then we must
                    // -- have a namespace match, so set descriptor to null,
                    // -- or if descriptor is not a wildcard we can also
                    // -- set to null.
                    if ((descriptor.getNameSpaceURI() != null) || (!descriptor.matches("*"))) {
                        descriptor = null;
                    }

                }
            }
        }
        // -- end namespace patch

        /*
         * If descriptor is null, we need to handle possible inheritence, which might not be described
         * in the current ClassDescriptor. This can be a slow process...for speed use the match
         * attribute of the xml element in the mapping file. This logic might not be completely
         * necessary, and perhaps we should remove it.
         */
        // handle multiple level locations (where count > 0) (CASTOR-1039)
        // if ((descriptor == null) && (count == 0) &&
        // (!targetState.wrapper)) {
        if ((descriptor == null) && (!targetState.isWrapper())) {
            MarshalFramework.InheritanceMatch[] matches = null;
            try {
                matches = _unmarshalHandler.searchInheritance(name, namespace, classDesc); // TODO:
                                                                                           // Joachim,
                                                                                           // _cdResolver);
            } catch (MarshalException rx) {
                // -- TODO:
            }
            if (matches.length != 0) {
                InheritanceMatch match = null;
                // It may be the case that this class descriptor can
                // appear under multiple parent field descriptors. Look
                // for the first match whose parent file descriptor XML
                // name matches the name of the element we are under
                for (int i = 0; i < matches.length; i++) {
                    if (parentState.getElementName().equals(matches[i].parentFieldDesc.getLocationPath())) {
                        match = matches[i];
                        break;
                    }
                }
                if (match == null)
                    match = matches[0];
                descriptor = match.parentFieldDesc;
                cdInherited = match.inheritedClassDesc;
                break; // -- found
            }
            /* */

            // handle multiple level locations (where count > 0)
            // (CASTOR-1039)
            // isWrapper = (isWrapper || hasFieldsAtLocation(name,
            // classDesc));
            StringBuilder tmpLocation = new StringBuilder();
            if (count > 0) {
                tmpLocation.append(path).append('/');
            }
            tmpLocation.append(name);
            isWrapper = (isWrapper || MarshalFramework.hasFieldsAtLocation(tmpLocation.toString(), classDesc));
        } else if (descriptor != null) {
            String tmpPath = descriptor.getLocationPath();
            if (path.equals(StringUtils.defaultString(tmpPath)))
                break; // -- found
            descriptor = null; // -- not found, try again
        } else {
            isWrapper = (isWrapper || MarshalFramework.hasFieldsAtLocation(path + '/' + name, classDesc));
        }

        // -- Make sure there are more parent classes on stack
        // -- otherwise break, since there is nothing to do
        // if (pIdx == 0) break;
        if (targetState == _unmarshalHandler.getTopState())
            break;

        // -- adjust name and try parent
        if (count == 0)
            path = targetState.getElementName();
        else {
            path = targetState.getElementName() + '/' + path;
        }

        // -- get
        // --pIdx;
        // targetState = (UnmarshalState)_stateInfo.elementAt(pIdx);
        targetState = targetState.getParent();
        classDesc = targetState.getClassDescriptor();
        count++;
    }

    if (descriptor != null && _unmarshalHandler.isValidating()
            && !_unmarshalHandler.getInternalContext().getLenientSequenceOrder()) {
        try {
            classDesc.checkDescriptorForCorrectOrderWithinSequence(descriptor, parentState, name);
        } catch (ValidationException e) {
            throw new SAXException(e);
        }
    }

    // -- The field descriptor is still null, we face a problem
    if (descriptor == null) {

        // -- reset classDesc
        classDesc = oldClassDesc;

        // -- isWrapper?
        if (isWrapper) {
            state.setClassDescriptor(new XMLClassDescriptorImpl(ContainerElement.class, name));
            state.setWrapper(true);
            if (LOG.isDebugEnabled()) {
                LOG.debug("wrapper-element: " + name);
            }
            // -- process attributes
            _unmarshalHandler.processWrapperAttributes(atts);
            return;
        }

        String error = MessageFormat.format(
                resourceBundle.getString("unmarshalHandler.error.find.field.descriptor"),
                new Object[] { name, classDesc.getXMLName() });

        // -- unwrap classDesc, if necessary, for the check
        // -- Introspector.introspected done below
        if (classDesc instanceof InternalXMLClassDescriptor) {
            classDesc = ((InternalXMLClassDescriptor) classDesc).getClassDescriptor();
        }

        // -- If we are skipping elements that have appeared in the XML but
        // for
        // -- which we have no mapping, increase the ignore depth counter
        // and return
        boolean lenientElementStrictnessForIntrospection = _unmarshalHandler.getInternalContext()
                .getBooleanProperty(XMLProperties.LENIENT_INTROSPECTED_ELEMENT_STRICTNESS).booleanValue();
        // checks if the element could be skipped
        if (_unmarshalHandler.getStrictElementHandler().skipStartElementIgnoringDepth()) {
            // -- remove the StateInfo we just added
            _unmarshalHandler.getStateStack().removeLastState();
            // drop Namespace instance as well
            _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
            if (LOG.isDebugEnabled()) {
                String debug = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.log.debug.ignore.extra.element"),
                        new Object[] { error });
                LOG.debug(debug);
            }
            return;
        }
        // if we have no field descriptor and
        // the class descriptor was introspected
        // just log it
        else if (lenientElementStrictnessForIntrospection && Introspector.introspected(classDesc)) {
            LOG.warn(error);
            return;
        }
        // -- otherwise report error since we cannot find a suitable
        // -- descriptor
        else {
            throw new SAXException(error);
        }
    } // -- end null descriptor

    // / DEBUG: System.out.println("path: " + path);

    // -- Save targetState (used in endElement)
    if (targetState != parentState) {
        state.setTargetState(targetState);
        parentState = targetState; // -- reassign
    }

    Object object = parentState.getObject();
    // --container support
    if (descriptor.isContainer()) {
        // create a new state to set the container as the object
        // don't save the current state, it will be recreated later

        if (LOG.isDebugEnabled()) {
            LOG.debug("#container: " + descriptor.getFieldName());
        }

        // -- clear current state and re-use for the container
        state.clear();
        // -- inherit whitespace preserving from the parentState
        state.setWhitespacePreserving(parentState.isWhitespacePreserving());
        state.setParent(parentState);

        // here we can hard-code a name or take the field name
        state.setElementName(descriptor.getFieldName());
        state.setFieldDescriptor(descriptor);
        state.setClassDescriptor((XMLClassDescriptor) descriptor.getClassDescriptor());
        Object containerObject = null;

        // 1-- the container is not multivalued (not a collection)
        if (!descriptor.isMultivalued()) {
            // Check if the container object has already been instantiated
            FieldHandler handler = descriptor.getHandler();
            containerObject = handler.getValue(object);
            if (containerObject != null) {
                if (state.getClassDescriptor() != null) {
                    if (state.getClassDescriptor().canAccept(name, namespace, containerObject)) {
                        // remove the descriptor from the used list
                        parentState.markAsNotUsed(descriptor);
                    }
                } else {
                    // remove the descriptor from the used list
                    parentState.markAsNotUsed(descriptor);
                }
            } else {
                containerObject = handler.newInstance(object);
            }

        }
        // 2-- the container is multivalued
        else {
            Class containerClass = descriptor.getFieldType();
            try {
                containerObject = containerClass.newInstance();
            } catch (Exception ex) {
                throw new SAXException(ex);
            }
        }
        state.setObject(containerObject);
        state.setType(containerObject.getClass());

        // we need to recall startElement()
        // so that we can find a more appropriate descriptor in for the
        // given name
        _unmarshalHandler.getNamespaceHandling().createNamespace();
        _unmarshalHandler.startElementProcessing(name, namespace, atts);
        return;
    }
    // --End of the container support

    // -- Find object type and create new Object of that type
    state.setFieldDescriptor(descriptor);

    /*
     * <update> we need to add this code back in, to make sure we have proper access rights.
     * 
     * if (!descriptor.getAccessRights().isWritable()) { if (debug) { buf.setLength(0); buf.append(
     * "The field for element '"); buf.append(name); buf.append("' is read-only.");
     * message(buf.toString()); } return; }
     */

    // -- Find class to instantiate
    // -- check xml names to see if we should look for a more specific
    // -- ClassDescriptor, otherwise just use the one found in the
    // -- descriptor
    classDesc = null;
    if (cdInherited != null)
        classDesc = cdInherited;
    else if (!name.equals(descriptor.getXMLName()))
        classDesc = _unmarshalHandler.resolveByXMLName(name, namespace, null);

    if (classDesc == null)
        classDesc = (XMLClassDescriptor) descriptor.getClassDescriptor();
    FieldHandler handler = descriptor.getHandler();
    boolean useHandler = true;

    try {

        // -- Get Class type...first use ClassDescriptor,
        // -- since it could be more specific than
        // -- the FieldDescriptor
        if (classDesc != null) {
            cls = classDesc.getJavaClass();

            // -- XXXX This is a hack I know...but we
            // -- XXXX can't use the handler if the field
            // -- XXXX types are different
            if (descriptor.getFieldType() != cls) {
                state.setDerived(true);
            }
        } else {
            cls = descriptor.getFieldType();
        }

        // -- This *shouldn't* happen, but a custom implementation
        // -- could return null in the XMLClassDesctiptor#getJavaClass
        // -- or XMLFieldDescriptor#getFieldType. If so, just replace
        // -- with java.lang.Object.class (basically "anyType").
        if (cls == null) {
            cls = java.lang.Object.class;
        }

        // Retrieving the xsi:type attribute, if present
        String currentPackage = _unmarshalHandler.getJavaPackage(parentState.getType());
        String instanceType = _unmarshalHandler.getInstanceType(atts, currentPackage);
        if (instanceType != null) {

            Class instanceClass = null;
            try {

                XMLClassDescriptor instanceDesc = _unmarshalHandler.getClassDescriptor(instanceType,
                        _unmarshalHandler.getClassLoader());

                boolean loadClass = true;

                if (instanceDesc != null) {
                    instanceClass = instanceDesc.getJavaClass();
                    classDesc = instanceDesc;
                    if (instanceClass != null) {
                        loadClass = (!instanceClass.getName().equals(instanceType));
                    }
                }

                if (loadClass) {
                    instanceClass = _unmarshalHandler.loadClass(instanceType, null);
                    // the FieldHandler can be either an XMLFieldHandler
                    // or a FieldHandlerImpl
                    FieldHandler tempHandler = descriptor.getHandler();

                    boolean collection = false;
                    if (tempHandler instanceof FieldHandlerImpl) {
                        collection = ((FieldHandlerImpl) tempHandler).isCollection();
                    } else {
                        collection = Introspector.isCollection(instanceClass);
                    }

                    if ((!collection) && !cls.isAssignableFrom(instanceClass)) {
                        if (!MarshalFramework.isPrimitive(cls)) {
                            String err = MessageFormat.format(
                                    resourceBundle.getString("unmarshalHandler.error.not.subclass"),
                                    new Object[] { instanceClass.getName(), cls.getName() });
                            throw new SAXException(err);
                        }
                    }
                }
                cls = instanceClass;
                useHandler = false;
            } catch (Exception ex) {
                String err = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.error.unable.instantiate.exception"),
                        new Object[] { instanceType, ex.getMessage() });
                throw new SAXException(err, ex);
            }

        }

        // -- Handle ArrayHandler
        if (cls == Object.class) {
            if (parentState.getObject() instanceof ArrayHandler)
                cls = ((ArrayHandler) parentState.getObject()).componentType();
        }

        // -- Handle support for "Any" type

        if (cls == Object.class) {
            Class pClass = parentState.getType();
            ClassLoader loader = pClass.getClassLoader();
            // -- first look for a descriptor based
            // -- on the XML name
            classDesc = _unmarshalHandler.resolveByXMLName(name, namespace, loader);
            // -- if null, create classname, and try resolving
            String cname = null;
            if (classDesc == null) {
                // -- create class name
                cname = _unmarshalHandler.getJavaNaming().toJavaClassName(name);
                classDesc = _unmarshalHandler.getClassDescriptor(cname, loader);
            }
            // -- if still null, try using parents package
            if (classDesc == null) {
                // -- use parent to get package information
                String pkg = pClass.getName();
                int idx = pkg.lastIndexOf('.');
                if (idx > 0) {
                    pkg = pkg.substring(0, idx + 1);
                    cname = pkg + cname;
                    classDesc = _unmarshalHandler.getClassDescriptor(cname, loader);
                }
            }

            if (classDesc != null) {
                cls = classDesc.getJavaClass();
                useHandler = false;
            } else {
                // we are dealing with an AnyNode
                state.setObject(_unmarshalHandler.getAnyNodeHandler().commonStartElement(name, namespace,
                        state.isWhitespacePreserving()));
                state.setType(cls);
                return;
            }
        }

        boolean byteArray = false;
        if (cls.isArray())
            byteArray = (cls.getComponentType() == Byte.TYPE);

        // -- check for immutable
        if (MarshalFramework.isPrimitive(cls) || descriptor.isImmutable() || byteArray) {
            state.setObject(null);
            state.setPrimitiveOrImmutable(true);
            // -- handle immutable types, such as java.util.Locale
            if (descriptor.isImmutable()) {
                if (classDesc == null)
                    classDesc = _unmarshalHandler.getClassDescriptor(cls);
                state.setClassDescriptor(classDesc);
                Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc);
                if (args != null && args.size() > 0) {
                    state.setConstructorArguments(args);
                }
            }
        } else {
            if (classDesc == null)
                classDesc = _unmarshalHandler.getClassDescriptor(cls);

            // -- XXXX should remove this test once we can
            // -- XXXX come up with a better solution
            if ((!state.isDerived()) && useHandler) {

                boolean create = true;
                if (_unmarshalHandler.isReuseObjects()) {
                    state.setObject(handler.getValue(parentState.getObject()));
                    create = (state.getObject() == null);
                }
                if (create) {
                    Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc);
                    if ((args.getValues() != null) && (args.getValues().length > 0)) {
                        if (handler instanceof ExtendedFieldHandler) {
                            ExtendedFieldHandler efh = (ExtendedFieldHandler) handler;
                            state.setObject(efh.newInstance(parentState.getObject(), args.getValues()));
                        } else {
                            String err = resourceBundle
                                    .getString("unmarshalHandler.error.constructor.arguments");
                            throw new SAXException(err);
                        }
                    } else {
                        state.setObject(handler.newInstance(parentState.getObject()));
                    }
                }
            }
            // -- reassign class in case there is a conflict
            // -- between descriptor#getFieldType and
            // -- handler#newInstance...I should hope not, but
            // -- who knows
            if (state.getObject() != null) {
                cls = state.getObject().getClass();
                if (classDesc != null) {
                    if (classDesc.getJavaClass() != cls) {
                        classDesc = null;
                    }
                }
            } else {
                try {
                    if (cls.isArray()) {
                        state.setObject(new ArrayHandler(cls.getComponentType()));
                        cls = ArrayHandler.class;
                    } else {
                        Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc);
                        state.setObject(_unmarshalHandler.createInstance(cls, args));
                        // state.object = _class.newInstance();
                    }
                } catch (java.lang.Exception ex) {
                    String err = MessageFormat.format(
                            resourceBundle.getString("unmarshalHandler.error.unable.instantiate.exception"),
                            new Object[] { _unmarshalHandler.className(cls), ex.getMessage() });
                    throw new SAXException(err, ex);
                }
            }
        }
        state.setType(cls);
    } catch (java.lang.IllegalStateException ise) {
        LOG.error(ise.toString());
        throw new SAXException(ise);
    }

    // -- At this point we should have a new object, unless
    // -- we are dealing with a primitive type, or a special
    // -- case such as byte[]
    if (classDesc == null) {
        classDesc = _unmarshalHandler.getClassDescriptor(cls);
    }
    state.setClassDescriptor(classDesc);

    if ((state.getObject() == null) && (!state.isPrimitiveOrImmutable())) {
        String err = MessageFormat.format(resourceBundle.getString("unmarshalHandler.error.unable.unmarshal"),
                new Object[] { name, _unmarshalHandler.className(cls) });
        throw new SAXException(err);
    }

    // -- assign object, if incremental

    if (descriptor.isIncremental()) {
        if (LOG.isDebugEnabled()) {
            String debug = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.log.debug.process.incrementally"),
                    new Object[] { name });
            LOG.debug(debug);
        }
        try {
            handler.setValue(parentState.getObject(), state.getObject());
        } catch (java.lang.IllegalStateException ise) {
            String err = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.error.unable.add.element"),
                    new Object[] { name, parentState.getFieldDescriptor().getXMLName(), ise.getMessage() });
            throw new SAXException(err, ise);
        }
    }

    if (state.getObject() != null) {
        // --The object has just been initialized
        // --notify the listener
        Object stateObject = state.getObject();
        Object parentObject = (state.getParent() == null) ? null : state.getParent().getObject();
        _unmarshalHandler.getDelegateUnmarshalListener().initialized(stateObject, parentObject);
        _unmarshalHandler.processAttributes(atts, classDesc);
        _unmarshalHandler.getDelegateUnmarshalListener().attributesProcessed(stateObject, parentObject);
        _unmarshalHandler.getNamespaceHandling().processNamespaces(classDesc,
                _unmarshalHandler.getStateStack().getLastState().getObject());
    } else if ((state.getType() != null) && (!state.isPrimitiveOrImmutable())) {
        if (atts != null) {
            _unmarshalHandler.processWrapperAttributes(atts);
            String warn = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.log.warn.process.attribute.as.location"),
                    new Object[] { name });
            LOG.warn(warn);
        }
    } else {
        // -- check for special attributes, such as xsi:nil
        if (atts != null) {
            String nil = atts.getValue(MarshalFramework.NIL_ATTR, MarshalFramework.XSI_NAMESPACE);
            state.setNil("true".equals(nil));
            _unmarshalHandler.processWrapperAttributes(atts);
        }
    }
}

From source file:org.glom.web.server.ConfiguredDocumentSet.java

public void readConfiguration() throws ServletException {

    // All of the initialisation code is surrounded by a try/catch block so that the servlet can be in an
    // initialised state and the error message can be retrieved by the client code.
    try {//  w  w w . j  a v  a  2 s.com
        // Find the configuration file. See this thread for background info:
        // http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application
        final OnlineGlomProperties config = new OnlineGlomProperties();
        final InputStream is = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("onlineglom.properties");
        if (is == null) {
            final String errorMessage = "onlineglom.properties not found.";
            Log.fatal(errorMessage);
            throw new Exception(errorMessage);
        }
        config.load(is); // can throw an IOException

        // check if we can read the configured glom file directory
        final String documentDirName = config.getDocumentsDirectory();
        final File documentDir = new File(documentDirName);
        if (!documentDir.isDirectory()) {
            final String errorMessage = documentDirName + " is not a directory.";
            Log.fatal(errorMessage);
            throw new Exception(errorMessage);
        }
        if (!documentDir.canRead()) {
            final String errorMessage = "Can't read the files in directory " + documentDirName + " .";
            Log.fatal(errorMessage);
            throw new Exception(errorMessage);
        }

        // get and check the glom files in the specified directory
        // TODO: Test this:
        final String[] extensions = { GLOM_FILE_EXTENSION };
        final Collection<?> glomFiles = FileUtils.listFiles(documentDir, extensions, true /* recursive */);
        if (!(glomFiles instanceof List<?>)) {
            final String errorMessage = "onlineglom.properties: listFiles() failed.";
            Log.fatal(errorMessage);
            throw new Exception(errorMessage);
        }

        // don't continue if there aren't any Glom files to configure
        if (glomFiles.size() <= 0) {
            final String errorMessage = "Unable to find any Glom documents in the configured directory "
                    + documentDirName
                    + " . Check the onlineglom.properties file to ensure that 'glom.document.directory' is set to the correct directory.";
            Log.error(errorMessage);
            throw new Exception(errorMessage);
        }

        // Check for a specified default locale,
        // for table titles, field titles, etc:
        final String globalLocaleID = StringUtils.defaultString(config.getGlobalLocale());

        for (final Object objGlomFile : glomFiles) {
            if (!(objGlomFile instanceof File)) {
                continue;
            }

            final File glomFile = (File) objGlomFile;
            final String filename = glomFile.getName();

            final String documentID = getDocumentIdForFilename(filename);
            final Document document = new Document(documentID);
            document.setFileURI("file://" + glomFile.getAbsolutePath());
            final boolean retval = document.load();
            if (retval == false) {
                final String message = "An error occurred when trying to load file: "
                        + glomFile.getAbsolutePath();
                Log.error(message);
                // continue with for loop because there may be other documents in the directory
                continue;
            }

            final ConfiguredDocument configuredDocument = new ConfiguredDocument(document); // can throw a
            // PropertyVetoException

            final String globalUserName = config.getGlobalUsername();
            final String globalPassword = config.getGlobalPassword();

            // check if a username and password have been set and work for the current document

            // Username/password could be set. Let's check to see if it works.
            ComboPooledDataSource authenticatedConnection = null;
            Credentials docCredentials = config.getCredentials(filename);

            if (docCredentials != null) {
                authenticatedConnection = SqlUtils.tryUsernameAndPassword(document, docCredentials.username,
                        docCredentials.password); // can throw an SQLException
                if (authenticatedConnection != null) {
                    //Use the document-specific credentials:
                    docCredentials = new Credentials(document, docCredentials.username, docCredentials.password,
                            authenticatedConnection);
                }
            }

            // Check the if the global username and password have been set and work with this document
            if (authenticatedConnection == null) {
                authenticatedConnection = SqlUtils.tryUsernameAndPassword(configuredDocument.getDocument(),
                        globalUserName, globalPassword); // can throw an SQLException
                if (authenticatedConnection != null) {
                    //Use the global credentials:
                    docCredentials = new Credentials(document, globalUserName, globalPassword,
                            authenticatedConnection);
                }
            }

            // Store the credentials for the document,
            // also remembering the database connection for some time:
            if (authenticatedConnection != null) {
                configuredDocument.setCredentials(docCredentials);
            }

            if (!StringUtils.isEmpty(globalLocaleID)) {
                configuredDocument.setDefaultLocaleID(globalLocaleID.trim());
            }

            addDocument(configuredDocument, documentID);
        }

    } catch (final Exception e) {
        // Don't throw the Exception so that servlet will be initialised and the error message can be retrieved.
        configurationException = e;
    }

}

From source file:org.glom.web.server.ConfiguredDocumentSet.java

/**
 * @return//from  w  w  w .j  a v a  2  s . c  o m
 */
public Documents getDocuments() {
    final Documents documents = new Documents();
    for (final String documentID : documentMapping.keySet()) {
        final ConfiguredDocument configuredDoc = getDocument(documentID);
        if (configuredDoc == null) {
            continue;
        }

        final Document glomDocument = configuredDoc.getDocument();
        if (glomDocument == null) {
            final String errorMessage = "getDocuments(): getDocument() failed.";
            Log.fatal(errorMessage);
            // TODO: throw new Exception(errorMessage);
            continue;
        }

        final String localeID = StringUtils.defaultString(configuredDoc.getDefaultLocaleID());
        documents.addDocument(documentID, glomDocument.getDatabaseTitle(localeID), localeID);
    }
    return documents;
}

From source file:org.glom.web.server.Log.java

public static void fatal(final String message, final Throwable e) {
    com.allen_sauer.gwt.log.client.Log.fatal(getServletMethodName() + StringUtils.defaultString(message), e);
}

From source file:org.glom.web.server.Log.java

public static void fatal(final String message) {
    com.allen_sauer.gwt.log.client.Log.fatal(getServletMethodName() + StringUtils.defaultString(message));
}

From source file:org.glom.web.server.Log.java

public static void fatal(final String documentID, final String tableName, final String message,
        final Throwable e) {
    com.allen_sauer.gwt.log.client.Log.fatal(getServletMethodName() + StringUtils.defaultString(documentID)
            + " - " + StringUtils.defaultString(tableName) + ": " + StringUtils.defaultString(message), e);
}