Example usage for java.lang IllegalStateException toString

List of usage examples for java.lang IllegalStateException toString

Introduction

In this page you can find the example usage for java.lang IllegalStateException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.vmware.identity.samlservice.impl.CasIdmAccessor.java

@Override
public String getAcsForRelyingParty(String relyingParty, Integer acsIndex, String acsUrl, String binding,
        boolean validateWithMetadata) {
    logger.debug("getAcsForRelyingParty " + relyingParty + ", index " + acsIndex + ", URL " + acsUrl
            + ", binding " + binding);
    String retval = null;/*from   www  .j  av a2  s .c  o m*/

    try {
        RelyingParty rp = client.getRelyingPartyByUrl(tenant, relyingParty);
        Validate.notNull(rp);
        Collection<AssertionConsumerService> assertionServices = rp.getAssertionConsumerServices();
        Validate.notNull(assertionServices);
        Validate.isTrue(assertionServices.size() > 0);
        AssertionConsumerService[] services = assertionServices
                .toArray(new AssertionConsumerService[assertionServices.size()]);

        if (acsIndex != null) {
            // if index is present, URL must not be
            if (acsUrl != null) {
                throw new IllegalStateException("BadRequest.AssertionIndex");
            }
            if (acsIndex < 0 || acsIndex >= assertionServices.size()) {
                throw new IllegalStateException("BadRequest.AssertionIndex");
            }
            Validate.notNull(services[acsIndex]);
            retval = services[acsIndex].getEndpoint();
        } else if (acsUrl != null) {
            // we have no index specified, URL is present
            // find assertion consumer service by URL
            if (validateWithMetadata) {
                for (AssertionConsumerService acs : assertionServices) {
                    if (acs != null && acsUrl.equals(acs.getEndpoint())) {
                        // check binding if specified
                        if (binding == null || (binding != null && binding.equals(acs.getBinding()))) {
                            retval = acs.getEndpoint();
                        }
                    }
                }
            } else { // no validation
                retval = acsUrl;
            }
            // by now we should have found something
            if (retval == null) {
                throw new IllegalStateException("BadRequest.AssertionMetadata");
            }
        } else if (binding != null) {
            // we have to index or URL specified, lookup by binding
            for (AssertionConsumerService acs : assertionServices) {
                if (acs != null && binding.equals(acs.getBinding())) {
                    retval = acs.getEndpoint();
                }
            }
            // by now we should have found something
            if (retval == null) {
                throw new IllegalStateException("BadRequest.AssertionBinding");
            }
        } else {
            // just look for the default service if any
            for (AssertionConsumerService acs : assertionServices) {
                if (acs != null && acs.getName() != null
                        && acs.getName().equals(rp.getDefaultAssertionConsumerService())) {
                    retval = acs.getEndpoint();
                }
            }
            // by now we should have found something
            if (retval == null) {
                throw new IllegalStateException("BadRequest.AssertionNoDefault");
            }
        }
    } catch (IllegalStateException e) {
        logger.error("Caught illegal state exception {}", e.toString());
        throw e;
    } catch (Exception e) {
        logger.error("Caught exception ", e);
        throw new IllegalStateException("BadRequest", e);
    }

    Validate.notNull(retval);
    return retval;
}

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

public void compute(String name) throws org.xml.sax.SAXException {
    if (LOG.isTraceEnabled()) {
        String trace = MessageFormat.format(resourceBundle.getString("unmarshalHandler.log.trace.endElement"),
                new Object[] { name });
        LOG.trace(trace);//from  ww w.j a v  a2 s.co  m
    }

    // -- If we are skipping elements that have appeared in the XML but for
    // -- which we have no mapping, decrease the ignore depth counter and
    // return
    if (_unmarshalHandler.getStrictElementHandler().skipEndElement()) {
        return;
    }

    // -- Do delagation if necessary
    if (_unmarshalHandler.getAnyNodeHandler().hasAnyUnmarshaller()) {
        _unmarshalHandler.getAnyNodeHandler().endElement(name);
        // we are back to the starting node
        if (_unmarshalHandler.getAnyNodeHandler().isStartingNode()) {
            _unmarshalHandler.setAnyNode(_unmarshalHandler.getAnyNodeHandler().getStartingNode());
        } else
            return;
    }

    if (_unmarshalHandler.getStateStack().isEmpty()) {
        String err = MessageFormat.format(
                resourceBundle.getString("unmarshalHandler.error.missing.startElement"), new Object[] { name });
        throw new SAXException(err);
    }

    // -- * Begin Namespace Handling
    // -- XXX Note: This code will change when we update the XML event API

    int idx = name.indexOf(':');
    if (idx >= 0) {
        name = name.substring(idx + 1);
    }
    // -- * End Namespace Handling

    UnmarshalState state = _unmarshalHandler.getStateStack().removeLastState();

    // -- make sure we have the correct closing tag
    XMLFieldDescriptor descriptor = state.getFieldDescriptor();

    if (!state.getElementName().equals(name)) {

        // maybe there is still a container to end
        if (descriptor.isContainer()) {
            _unmarshalHandler.getStateStack().pushState(state);
            // -- check for possible characters added to
            // -- the container's state that should
            // -- really belong to the parent state
            StringBuffer tmpBuffer = null;
            if (state.getBuffer() != null) {
                if (!UnmarshalHandler.isWhitespace(state.getBuffer())) {
                    if (state.getClassDescriptor().getContentDescriptor() == null) {
                        tmpBuffer = state.getBuffer();
                        state.setBuffer(null);
                    }
                }
            }
            // -- end container
            _unmarshalHandler.endElement(state.getElementName());

            if (tmpBuffer != null) {
                state = _unmarshalHandler.getStateStack().getLastState();
                if (state.getBuffer() == null)
                    state.setBuffer(tmpBuffer);
                else
                    state.getBuffer().append(tmpBuffer.toString());
            }
            _unmarshalHandler.endElement(name);
            return;
        }
        String err = MessageFormat.format(
                resourceBundle.getString("unmarshalHandler.error.different.endElement.expected"),
                new Object[] { state.getElementName(), name });
        throw new SAXException(err);
    }

    // -- clean up current Object
    Class<?> type = state.getType();

    if (type == null) {
        if (!state.isWrapper()) {
            // -- this message will only show up if debug
            // -- is turned on...how should we handle this case?
            // -- should it be a fatal error?
            String info = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.log.info.no.Descriptor.found"),
                    new Object[] { state.getElementName() });
            LOG.info(info);
        }

        // -- handle possible location text content
        // -- TODO: cleanup location path support.
        // -- the following code needs to be improved as
        // -- for searching descriptors in this manner can
        // -- be slow
        StringBuffer tmpBuffer = null;
        if (state.getBuffer() != null) {
            if (!UnmarshalHandler.isWhitespace(state.getBuffer())) {
                tmpBuffer = state.getBuffer();
                state.setBuffer(null);
            }
        }
        if (tmpBuffer != null) {
            UnmarshalState targetState = state;
            String locPath = targetState.getElementName();
            while ((targetState = targetState.getParent()) != null) {
                if ((targetState.isWrapper()) || (targetState.getClassDescriptor() == null)) {
                    locPath = targetState.getElementName() + "/" + locPath;
                    continue;
                }

                XMLFieldDescriptor tmpDesc = targetState.getClassDescriptor().getContentDescriptor();
                if (tmpDesc != null && locPath.equals(tmpDesc.getLocationPath())) {
                    if (targetState.getBuffer() == null)
                        targetState.setBuffer(tmpBuffer);
                    else
                        targetState.getBuffer().append(tmpBuffer.toString());
                }
            }
        }

        // -- remove current namespace scoping
        _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
        return;
    }

    // -- check for special cases
    boolean byteArray = false;
    if (type.isArray()) {
        byteArray = (type.getComponentType() == Byte.TYPE);
    }

    // -- If we don't have an instance object and the Class type
    // -- is not a primitive or a byte[] we must simply return
    if ((state.getObject() == null) && (!state.isPrimitiveOrImmutable())) {
        // -- remove current namespace scoping
        _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
        return;
    }

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

    if (state.isPrimitiveOrImmutable()) {

        String str = null;

        if (state.getBuffer() != null) {
            str = state.getBuffer().toString();
            state.getBuffer().setLength(0);
        }

        if (type == String.class && !((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) {
            if (str != null)
                state.setObject(str);
            else if (state.isNil()) {
                state.setObject(null);
            } else {
                state.setObject("");
            }
        }
        // -- special handling for byte[]
        else if (byteArray && !descriptor.isDerivedFromXSList()) {
            if (str == null)
                state.setObject(new byte[0]);
            else {
                state.setObject(_unmarshalHandler.decodeBinaryData(descriptor, str));
            }
        } else if (state.getConstructorArguments() != null) {
            state.setObject(_unmarshalHandler.createInstance(state.getType(), state.getConstructorArguments()));
        } else if (descriptor.isMultivalued() && descriptor.getSchemaType() != null
                && descriptor.getSchemaType().equals("list")
                && ((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) {
            StringTokenizer attrValueTokenizer = new StringTokenizer(str);
            List<Object> primitives = new ArrayList<Object>();
            while (attrValueTokenizer.hasMoreTokens()) {
                String tokenValue = attrValueTokenizer.nextToken();
                if (MarshalFramework.isPrimitive(descriptor.getFieldType())) {
                    primitives.add(
                            _unmarshalHandler.toPrimitiveObject(type, tokenValue, state.getFieldDescriptor()));
                } else {
                    Class<?> valueType = descriptor.getFieldType();
                    // -- handle base64/hexBinary
                    if (valueType.isArray() && (valueType.getComponentType() == Byte.TYPE)) {
                        primitives.add(_unmarshalHandler.decodeBinaryData(descriptor, tokenValue));
                    }
                }

            }
            state.setObject(primitives);
        } else {
            if (state.isNil()) {
                state.setObject(null);
            } else {
                state.setObject(_unmarshalHandler.toPrimitiveObject(type, str, state.getFieldDescriptor()));
            }
        }
    } else if (ArrayHandler.class.isAssignableFrom(state.getType())) {
        state.setObject(((ArrayHandler) state.getObject()).getObject());
        state.setType(state.getObject().getClass());

    }

    // -- check for character content
    if ((state.getBuffer() != null) && (state.getBuffer().length() > 0)
            && (state.getClassDescriptor() != null)) {
        XMLFieldDescriptor cdesc = state.getClassDescriptor().getContentDescriptor();
        if (cdesc != null) {
            Object value = state.getBuffer().toString();
            if (MarshalFramework.isPrimitive(cdesc.getFieldType()))
                value = _unmarshalHandler.toPrimitiveObject(cdesc.getFieldType(), (String) value,
                        state.getFieldDescriptor());
            else {
                Class<?> valueType = cdesc.getFieldType();
                // -- handle base64/hexBinary
                if (valueType.isArray() && (valueType.getComponentType() == Byte.TYPE)) {
                    value = _unmarshalHandler.decodeBinaryData(descriptor, (String) value);
                }
            }

            try {
                FieldHandler handler = cdesc.getHandler();
                boolean addObject = true;
                if (_unmarshalHandler.isReuseObjects()) {
                    // -- check to see if we need to
                    // -- add the object or not
                    Object tmp = handler.getValue(state.getObject());
                    if (tmp != null) {
                        // -- Do not add object if values
                        // -- are equal
                        addObject = (!tmp.equals(value));
                    }
                }
                if (addObject)
                    handler.setValue(state.getObject(), value);
            } catch (java.lang.IllegalStateException ise) {
                String err = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.error.unable.add.text"),
                        new Object[] { descriptor.getXMLName(), ise.toString() });
                throw new SAXException(err, ise);
            }
        }
        // -- Handle references
        else if (descriptor.isReference()) {
            UnmarshalState pState = _unmarshalHandler.getStateStack().getLastState();
            _unmarshalHandler.processIDREF(state.getBuffer().toString(), descriptor, pState.getObject());
            _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
            return;
        } else {
            // -- check for non-whitespace...and report error
            if (!UnmarshalHandler.isWhitespace(state.getBuffer())) {
                String err = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.error.illegal.text"),
                        new Object[] { name, state.getBuffer() });
                throw new SAXException(err);
            }
        }
    }

    // -- We're finished processing the object, so notify the
    // -- Listener (if any).
    Object stateObject = state.getObject();
    Object parentObject = (state.getParent() == null) ? null : state.getParent().getObject();
    _unmarshalHandler.getDelegateUnmarshalListener().unmarshalled(stateObject, parentObject);

    // -- if we are at root....just validate and we are done
    if (_unmarshalHandler.getStateStack().isEmpty()) {
        if (_unmarshalHandler.isValidating()) {
            ValidationException first = null;
            ValidationException last = null;

            // -- check unresolved references
            if (_unmarshalHandler.getResolveTable() != null
                    && !_unmarshalHandler.getInternalContext().getLenientIdValidation()) {
                Enumeration enumeration = _unmarshalHandler.getResolveTable().keys();
                while (enumeration.hasMoreElements()) {
                    Object ref = enumeration.nextElement();
                    // if
                    // (ref.toString().startsWith(MapItem.class.getName()))
                    // continue;
                    String msg = "unable to resolve reference: " + ref;
                    if (first == null) {
                        first = new ValidationException(msg);
                        last = first;
                    } else {
                        last.setNext(new ValidationException(msg));
                        last = last.getNext();
                    }
                }
            }
            try {
                Validator validator = new Validator();
                ValidationContext context = new ValidationContext();
                context.setInternalContext(_unmarshalHandler.getInternalContext());
                validator.validate(state.getObject(), context);
                if (!_unmarshalHandler.getInternalContext().getLenientIdValidation()) {
                    validator.checkUnresolvedIdrefs(context);
                }
                context.cleanup();
            } catch (ValidationException vEx) {
                if (first == null)
                    first = vEx;
                else
                    last.setNext(vEx);
            }
            if (first != null) {
                throw new SAXException(first);
            }
        }
        return;
    }

    // -- Add object to parent if necessary

    if (descriptor.isIncremental()) {
        // -- remove current namespace scoping
        _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
        return; // -- already added
    }

    Object val = state.getObject();

    // --special code for AnyNode handling
    if (_unmarshalHandler.getAnyNode() != null) {
        val = _unmarshalHandler.getAnyNode();
        _unmarshalHandler.setAnyNode(null);
    }

    // -- save fieldState
    UnmarshalState fieldState = state;

    // -- have we seen this object before?
    boolean firstOccurance = false;

    // -- get target object
    state = _unmarshalHandler.getStateStack().getLastState();
    if (state.isWrapper()) {
        state = fieldState.getTargetState();
    }

    // -- check to see if we have already read in
    // -- an element of this type.
    // -- (Q: if we have a container, do we possibly need to
    // -- also check the container's multivalued status?)
    if (!descriptor.isMultivalued()) {

        if (state.isUsed(descriptor)) {

            String location = name;
            while (!_unmarshalHandler.getStateStack().isEmpty()) {
                UnmarshalState tmpState = _unmarshalHandler.getStateStack().removeLastState();
                if (!tmpState.isWrapper()) {
                    if (tmpState.getFieldDescriptor().isContainer())
                        continue;
                }
                location = state.getElementName() + "/" + location;
            }

            String err = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.error.element.occurs.more.than.once"),
                    new Object[] { name, state.getType().getName(), location });

            ValidationException vx = new ValidationException(err);

            throw new SAXException(vx);
        }
        state.markAsUsed(descriptor);
        // -- if this is the identity then save id
        if (state.getClassDescriptor().getIdentity() == descriptor) {
            state.setKey(val);
        }
    } else {
        // -- check occurance of descriptor
        if (!state.isUsed(descriptor)) {
            firstOccurance = true;
        }

        // -- record usage of descriptor
        state.markAsUsed(descriptor);
    }

    try {
        FieldHandler handler = descriptor.getHandler();
        // check if the value is a QName that needs to
        // be resolved (ns:value -> {URI}value)
        String valueType = descriptor.getSchemaType();
        if ((valueType != null) && (valueType.equals(MarshalFramework.QNAME_NAME))) {
            val = _unmarshalHandler.getNamespaceHandling().resolveNamespace(val);
        }

        boolean addObject = true;
        if (_unmarshalHandler.isReuseObjects() && fieldState.isPrimitiveOrImmutable()) {
            // -- check to see if we need to
            // -- add the object or not
            Object tmp = handler.getValue(state.getObject());
            if (tmp != null) {
                // -- Do not add object if values
                // -- are equal
                addObject = (!tmp.equals(val));
            }
        }

        // -- special handling for mapped objects
        if (descriptor.isMapped()) {
            if (!(val instanceof MapItem)) {
                MapItem mapItem = new MapItem(fieldState.getKey(), val);
                val = mapItem;
            } else {
                // -- make sure value exists (could be a reference)
                MapItem mapItem = (MapItem) val;
                if (mapItem.getValue() == null) {
                    // -- save for later...
                    addObject = false;
                    _unmarshalHandler.addReference(mapItem.toString(), state.getObject(), descriptor);
                }
            }
        }

        if (addObject) {
            // -- clear any collections if necessary
            if (firstOccurance && _unmarshalHandler.isClearCollections()) {
                handler.resetValue(state.getObject());
            }

            if (descriptor.isMultivalued() && descriptor.getSchemaType() != null
                    && descriptor.getSchemaType().equals("list")
                    && ((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) {
                List<Object> values = (List<Object>) val;
                for (Object value : values) {
                    // -- finally set the value!!
                    handler.setValue(state.getObject(), value);

                    // If there is a parent for this object, pass along
                    // a notification that we've finished adding a child
                    _unmarshalHandler.getDelegateUnmarshalListener().fieldAdded(descriptor.getFieldName(),
                            state.getObject(), fieldState.getObject());
                }
            } else {

                // -- finally set the value!!
                handler.setValue(state.getObject(), val);

                // If there is a parent for this object, pass along
                // a notification that we've finished adding a child
                _unmarshalHandler.getDelegateUnmarshalListener().fieldAdded(descriptor.getFieldName(),
                        state.getObject(), fieldState.getObject());
            }
        }

    }
    /*
     * catch(java.lang.reflect.InvocationTargetException itx) {
     * 
     * Throwable toss = itx.getTargetException(); if (toss == null) toss = itx;
     * 
     * String err = "unable to add '" + name + "' to <"; err += state.descriptor.getXMLName(); err
     * += "> due to the following exception: " + toss; throw new SAXException(err); }
     */
    catch (Exception ex) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        pw.flush();
        String err = MessageFormat.format(resourceBundle.getString("unmarshalHandler.error.unable.add.element"),
                new Object[] { name, state.getFieldDescriptor().getXMLName(), sw.toString() });
        throw new SAXException(err, ex);
    }

    // -- remove current namespace scoping
    _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();

    // remove additional (artifical aka container) state introduced for
    // single-valued (iow maxOccurs="1") choices.
    if (state.getFieldDescriptor().isContainer() && state.getClassDescriptor().isChoice()
            && !state.getFieldDescriptor().isMultivalued()) {
        _unmarshalHandler.endElement(state.getElementName());
    }

}

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

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

    UnmarshalState state = null;/*from w  w  w .  j  av a 2s.  c  o  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.apache.nifi.controller.StandardFlowSynchronizer.java

private void applyExistingReportingTaskScheduleState(final FlowController controller,
        final ReportingTaskDTO dto, final ReportingTaskNode taskNode) {
    if (!taskNode.getScheduledState().name().equals(dto.getState())) {
        try {//www.ja va 2 s .  c om
            switch (ScheduledState.valueOf(dto.getState())) {
            case DISABLED:
                if (taskNode.isRunning()) {
                    controller.stopReportingTask(taskNode);
                }
                controller.disableReportingTask(taskNode);
                break;
            case RUNNING:
                if (taskNode.getScheduledState() == ScheduledState.DISABLED) {
                    controller.enableReportingTask(taskNode);
                }
                controller.startReportingTask(taskNode);
                break;
            case STOPPED:
                if (taskNode.getScheduledState() == ScheduledState.DISABLED) {
                    controller.enableReportingTask(taskNode);
                } else if (taskNode.getScheduledState() == ScheduledState.RUNNING) {
                    controller.stopReportingTask(taskNode);
                }
                break;
            }
        } catch (final IllegalStateException ise) {
            logger.error("Failed to change Scheduled State of {} from {} to {} due to {}", taskNode,
                    taskNode.getScheduledState().name(), dto.getState(), ise.toString());
            logger.error("", ise);

            // create bulletin for the Processor Node
            controller.getBulletinRepository()
                    .addBulletin(BulletinFactory.createBulletin("Node Reconnection", Severity.ERROR.name(),
                            "Failed to change Scheduled State of " + taskNode + " from "
                                    + taskNode.getScheduledState().name() + " to " + dto.getState() + " due to "
                                    + ise.toString()));

            // create bulletin at Controller level.
            controller.getBulletinRepository()
                    .addBulletin(BulletinFactory.createBulletin("Node Reconnection", Severity.ERROR.name(),
                            "Failed to change Scheduled State of " + taskNode + " from "
                                    + taskNode.getScheduledState().name() + " to " + dto.getState() + " due to "
                                    + ise.toString()));
        }
    }
}

From source file:com.juick.android.MessagesFragment.java

private void init(final boolean moveToTop) {
    if (implicitlyCreated)
        return;//from   w  w w.  ja  va  2 s. c  om

    parent.imagePreviewHelper = listAdapter.imagePreviewHelper = new ImagePreviewHelper(
            (ViewGroup) getView().findViewById(R.id.imagepreview_container), parent);

    final MessageListBackingData savedMainList = JuickAdvancedApplication.instance.getSavedList(getActivity());
    final ListView lv = getListView();
    boolean canUseMainList = getActivity() instanceof MainActivity; //
    if (savedMainList != null && canUseMainList) {
        messagesSource = savedMainList.messagesSource;
        initListWithMessages(savedMainList.messages);
        int selectItem = 0;
        ListAdapter wrappedAdapter = lv.getAdapter();
        for (int i = 0; i < wrappedAdapter.getCount(); i++) {
            Object ai = wrappedAdapter.getItem(i);
            if (ai != null && ai instanceof JuickMessage) {
                if (((JuickMessage) ai).getMID().equals(savedMainList.topMessageId)) {
                    selectItem = i;
                }
            }
        }
        lv.setSelectionFromTop(selectItem, savedMainList.topMessageScrollPos);
        JuickAdvancedApplication.instance.setSavedList(null, false);
    } else {
        final MessagesLoadNotification messagesLoadNotification = new MessagesLoadNotification(getActivity(),
                handler);
        Thread thr = new Thread("Download messages (init)") {

            public void run() {
                final MessagesLoadNotification notification = messagesLoadNotification;
                final Utils.Function<Void, RetainedData> then = new Utils.Function<Void, RetainedData>() {
                    @Override
                    public Void apply(final RetainedData mespos) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                notification.statusText.setText("Filter and format..");
                            }
                        });
                        Log.w("com.juick.advanced", "getFirst: before filter");
                        final ArrayList<JuickMessage> messages = filterMessages(mespos.messages);
                        Log.w("com.juick.advanced", "getFirst: after filter");
                        Boolean ownView = null;
                        if (!JuickMessagesAdapter.dontKeepParsed(parent)) {
                            for (JuickMessage juickMessage : messages) {
                                if (ownView == null) {
                                    MicroBlog blog = MainActivity.microBlogs
                                            .get(juickMessage.getMID().getMicroBlogCode());
                                    ownView = blog instanceof OwnRenderItems;
                                }
                                if (!ownView) {
                                    juickMessage.parsedText = JuickMessagesAdapter.formatMessageText(parent,
                                            juickMessage, false);
                                }
                            }
                        }
                        final Parcelable listPosition = mespos.viewState;
                        if (isAdded()) {
                            if (messages.size() == 0) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (notification.lastError == null) {
                                            notification.statusText
                                                    .setText(parent.getString(R.string.EmptyList));
                                        } else {
                                            notification.statusText.setText(
                                                    "Error obtaining messages: " + notification.lastError);

                                        }
                                        notification.progressBar.setVisibility(View.GONE);
                                    }
                                });
                            }
                            final Activity activity = getActivity();
                            if (activity != null) {
                                final Parcelable finalListPosition = listPosition;
                                activity.runOnUiThread(new Runnable() {

                                    public void run() {
                                        try {
                                            if (isAdded()) {
                                                lastPrepareMessages(messages, new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (!hasListView()) {
                                                            handler.postDelayed(this, 300);
                                                            return;
                                                        }
                                                        initListWithMessages(messages);
                                                        if (moveToTop) {
                                                            lv.setSelection(0);
                                                        } else {
                                                            if (finalListPosition != null) {
                                                                lv.onRestoreInstanceState(finalListPosition);
                                                            } else {
                                                                //setSelection(messagesSource.supportsBackwardRefresh() ? 1 : 0);
                                                                setSelection(0);
                                                            }
                                                        }
                                                        Log.w("com.juick.advanced", "getFirst: end.");
                                                        handler.postDelayed(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                onListLoaded();
                                                            }
                                                        }, 10);
                                                    }
                                                });
                                            }
                                        } catch (IllegalStateException e) {
                                            Toast.makeText(activity, e.toString(), Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            }
                        } else {
                            Log.w("com.juick.advanced", "getFirst: not added!");
                        }
                        return null;
                    }
                };
                if (getActivity() != null)
                    messagesSource.setContext(getActivity());
                if (restoreData == null) {
                    messagesSource.getFirst(notification, new Utils.Function<Void, ArrayList<JuickMessage>>() {
                        @Override
                        public Void apply(ArrayList<JuickMessage> juickMessages) {
                            return then.apply(new RetainedData(juickMessages, null));
                        }
                    });
                } else {
                    then.apply((RetainedData) restoreData);
                    restoreData = null;
                }
            }
        };
        thr.setPriority(Thread.MIN_PRIORITY);
        thr.start();
    }
}

From source file:net.kidlogger.kidlogger.KLService.java

public void startRecord(final String callType, final String callNumber) {
    //Log.i("KLS", "startRecord");
    new Thread(new Runnable() {
        public void run() {
            String rootDir = Environment.getExternalStorageDirectory().getAbsolutePath();
            String path = rootDir + "/.callrecords/" + getDateString();
            String name = new String();
            String tmp = getNameFromContacts(callNumber, true);
            if (tmp.equals("unknown"))
                name = sanityNumber(callNumber) + "_";
            else/*from   w ww  . ja  va2s  .  c om*/
                name = sanityNumber(tmp) + "_";

            recFile = new File(path, callType + name + getTimeString() + ".3gp");

            File directory = recFile.getParentFile();
            //Log.i("KLS", "Audio: " + recFile.getName());
            String state = Environment.getExternalStorageState();

            if (!state.equals(Environment.MEDIA_MOUNTED))
                return;

            if (!directory.exists())
                directory.mkdirs();

            recording = true;
            // Initialize recorder
            recorder = new MediaRecorder();
            try {
                recorder.setAudioSource(AudioSource.VOICE_UPLINK);
                recorder.setOutputFormat(OutputFormat.THREE_GPP);
                recorder.setAudioEncoder(AudioEncoder.DEFAULT);
                recorder.setOutputFile(recFile.getAbsolutePath());
                recorder.setMaxDuration(Settings.getMaxTimeRec(KLService.this));
                recorder.setMaxFileSize(Settings.getMaxSizeRec(KLService.this));
                recorder.setOnInfoListener(new MediaInfoListener());
                recorder.prepare();
                recorder.start();
            } catch (IllegalStateException e) {
                recording = false;
                app.logError("AudioRecordThread", e.toString());
            } catch (IOException e) {
                recording = false;
                app.logError("AudioRecordThread", e.toString());
            }
        }
    }).start();

    // Start recording
    /*new Thread(new Runnable(){
       public void run(){
    recording = true;
    // Initialize recorder
    recorder = new MediaRecorder();
    try{
       recorder.setAudioSource(AudioSource.VOICE_UPLINK);
       recorder.setOutputFormat(OutputFormat.THREE_GPP);
       recorder.setAudioEncoder(AudioEncoder.AMR_NB);
       recorder.setOutputFile(recFile.getAbsolutePath());
       recorder.setMaxDuration(Settings.getMaxTimeRec(KLService.this));
       recorder.setMaxFileSize(Settings.getMaxSizeRec(KLService.this));
       recorder.setOnInfoListener(new MediaInfoListener());
       recorder.prepare();
       recorder.start();
    }catch(IllegalStateException e){
       recording = false;
       app.logError("AudioRecordThread", e.toString());
    }catch(IOException e){
       recording = false;
       app.logError("AudioRecordThread", e.toString());
    }
       }
    }).start();*/

    /*AudioRecordThread art = new AudioRecordThread("record", recFile);
    try{
       art.t.join();
    }catch(InterruptedException e){
       app.logError(CN + "startRecord", e.toString());
    }*/
}

From source file:org.apache.nifi.controller.StandardFlowSynchronizer.java

private ProcessGroup updateProcessGroup(final FlowController controller, final ProcessGroup parentGroup,
        final Element processGroupElement, final StringEncryptor encryptor,
        final FlowEncodingVersion encodingVersion) throws ProcessorInstantiationException {

    // get the parent group ID
    final String parentId = (parentGroup == null) ? null : parentGroup.getIdentifier();

    // get the process group
    final ProcessGroupDTO processGroupDto = FlowFromDOMFactory.getProcessGroup(parentId, processGroupElement,
            encryptor, encodingVersion);

    // update the process group
    if (parentId == null) {

        /*/*from   w  w w. j ava2 s.  co  m*/
         * Labels are not included in the "inherit flow" algorithm, so we cannot
         * blindly update them because they may not exist in the current flow.
         * Therefore, we first remove all labels, and then let the updating
         * process add labels defined in the new flow.
         */
        final ProcessGroup root = controller.getGroup(controller.getRootGroupId());
        for (final Label label : root.findAllLabels()) {
            label.getProcessGroup().removeLabel(label);
        }
    }

    // update the process group
    controller.updateProcessGroup(processGroupDto);

    // get the real process group and ID
    final ProcessGroup processGroup = controller.getGroup(processGroupDto.getId());

    // processors & ports cannot be updated - they must be the same. Except for the scheduled state.
    final List<Element> processorNodeList = getChildrenByTagName(processGroupElement, "processor");
    for (final Element processorElement : processorNodeList) {
        final ProcessorDTO dto = FlowFromDOMFactory.getProcessor(processorElement, encryptor);
        final ProcessorNode procNode = processGroup.getProcessor(dto.getId());

        if (!procNode.getScheduledState().name().equals(dto.getState())) {
            try {
                switch (ScheduledState.valueOf(dto.getState())) {
                case DISABLED:
                    // switch processor do disabled. This means we have to stop it (if it's already stopped, this method does nothing),
                    // and then we have to disable it.
                    procNode.getProcessGroup().stopProcessor(procNode);
                    procNode.getProcessGroup().disableProcessor(procNode);
                    break;
                case RUNNING:
                    // we want to run now. Make sure processor is not disabled and then start it.
                    procNode.getProcessGroup().enableProcessor(procNode);
                    procNode.getProcessGroup().startProcessor(procNode);
                    break;
                case STOPPED:
                    if (procNode.getScheduledState() == ScheduledState.DISABLED) {
                        procNode.getProcessGroup().enableProcessor(procNode);
                    } else if (procNode.getScheduledState() == ScheduledState.RUNNING) {
                        procNode.getProcessGroup().stopProcessor(procNode);
                    }
                    break;
                }
            } catch (final IllegalStateException ise) {
                logger.error("Failed to change Scheduled State of {} from {} to {} due to {}", procNode,
                        procNode.getScheduledState().name(), dto.getState(), ise.toString());
                logger.error("", ise);

                // create bulletin for the Processor Node
                controller.getBulletinRepository()
                        .addBulletin(BulletinFactory.createBulletin(procNode, "Node Reconnection",
                                Severity.ERROR.name(),
                                "Failed to change Scheduled State of " + procNode + " from "
                                        + procNode.getScheduledState().name() + " to " + dto.getState()
                                        + " due to " + ise.toString()));

                // create bulletin at Controller level.
                controller.getBulletinRepository()
                        .addBulletin(BulletinFactory.createBulletin("Node Reconnection", Severity.ERROR.name(),
                                "Failed to change Scheduled State of " + procNode + " from "
                                        + procNode.getScheduledState().name() + " to " + dto.getState()
                                        + " due to " + ise.toString()));
            }
        }
    }

    final List<Element> inputPortList = getChildrenByTagName(processGroupElement, "inputPort");
    for (final Element portElement : inputPortList) {
        final PortDTO dto = FlowFromDOMFactory.getPort(portElement);
        final Port port = processGroup.getInputPort(dto.getId());

        if (!port.getScheduledState().name().equals(dto.getState())) {
            switch (ScheduledState.valueOf(dto.getState())) {
            case DISABLED:
                // switch processor do disabled. This means we have to stop it (if it's already stopped, this method does nothing),
                // and then we have to disable it.
                port.getProcessGroup().stopInputPort(port);
                port.getProcessGroup().disableInputPort(port);
                break;
            case RUNNING:
                // we want to run now. Make sure processor is not disabled and then start it.
                port.getProcessGroup().enableInputPort(port);
                port.getProcessGroup().startInputPort(port);
                break;
            case STOPPED:
                if (port.getScheduledState() == ScheduledState.DISABLED) {
                    port.getProcessGroup().enableInputPort(port);
                } else if (port.getScheduledState() == ScheduledState.RUNNING) {
                    port.getProcessGroup().stopInputPort(port);
                }
                break;
            }
        }
    }

    final List<Element> outputPortList = getChildrenByTagName(processGroupElement, "outputPort");
    for (final Element portElement : outputPortList) {
        final PortDTO dto = FlowFromDOMFactory.getPort(portElement);
        final Port port = processGroup.getOutputPort(dto.getId());

        if (!port.getScheduledState().name().equals(dto.getState())) {
            switch (ScheduledState.valueOf(dto.getState())) {
            case DISABLED:
                // switch processor do disabled. This means we have to stop it (if it's already stopped, this method does nothing),
                // and then we have to disable it.
                port.getProcessGroup().stopOutputPort(port);
                port.getProcessGroup().disableOutputPort(port);
                break;
            case RUNNING:
                // we want to run now. Make sure processor is not disabled and then start it.
                port.getProcessGroup().enableOutputPort(port);
                port.getProcessGroup().startOutputPort(port);
                break;
            case STOPPED:
                if (port.getScheduledState() == ScheduledState.DISABLED) {
                    port.getProcessGroup().enableOutputPort(port);
                } else if (port.getScheduledState() == ScheduledState.RUNNING) {
                    port.getProcessGroup().stopOutputPort(port);
                }
                break;
            }
        }
    }

    // Update scheduled state of Remote Group Ports
    final List<Element> remoteProcessGroupList = getChildrenByTagName(processGroupElement,
            "remoteProcessGroup");
    for (final Element remoteGroupElement : remoteProcessGroupList) {
        final RemoteProcessGroupDTO remoteGroupDto = FlowFromDOMFactory
                .getRemoteProcessGroup(remoteGroupElement, encryptor);
        final RemoteProcessGroup rpg = processGroup.getRemoteProcessGroup(remoteGroupDto.getId());

        // input ports
        final List<Element> inputPortElements = getChildrenByTagName(remoteGroupElement, "inputPort");
        for (final Element inputPortElement : inputPortElements) {
            final RemoteProcessGroupPortDescriptor portDescriptor = FlowFromDOMFactory
                    .getRemoteProcessGroupPort(inputPortElement);
            final String inputPortId = portDescriptor.getId();
            final RemoteGroupPort inputPort = rpg.getInputPort(inputPortId);
            if (inputPort == null) {
                continue;
            }

            if (portDescriptor.isTransmitting()) {
                if (inputPort.getScheduledState() != ScheduledState.RUNNING
                        && inputPort.getScheduledState() != ScheduledState.STARTING) {
                    rpg.startTransmitting(inputPort);
                }
            } else if (inputPort.getScheduledState() != ScheduledState.STOPPED
                    && inputPort.getScheduledState() != ScheduledState.STOPPING) {
                rpg.stopTransmitting(inputPort);
            }
        }

        // output ports
        final List<Element> outputPortElements = getChildrenByTagName(remoteGroupElement, "outputPort");
        for (final Element outputPortElement : outputPortElements) {
            final RemoteProcessGroupPortDescriptor portDescriptor = FlowFromDOMFactory
                    .getRemoteProcessGroupPort(outputPortElement);
            final String outputPortId = portDescriptor.getId();
            final RemoteGroupPort outputPort = rpg.getOutputPort(outputPortId);
            if (outputPort == null) {
                continue;
            }

            if (portDescriptor.isTransmitting()) {
                if (outputPort.getScheduledState() != ScheduledState.RUNNING
                        && outputPort.getScheduledState() != ScheduledState.STARTING) {
                    rpg.startTransmitting(outputPort);
                }
            } else if (outputPort.getScheduledState() != ScheduledState.STOPPED
                    && outputPort.getScheduledState() != ScheduledState.STOPPING) {
                rpg.stopTransmitting(outputPort);
            }
        }
    }

    // add labels
    final List<Element> labelNodeList = getChildrenByTagName(processGroupElement, "label");
    for (final Element labelElement : labelNodeList) {
        final LabelDTO labelDTO = FlowFromDOMFactory.getLabel(labelElement);
        final Label label = controller.createLabel(labelDTO.getId(), labelDTO.getLabel());
        label.setStyle(labelDTO.getStyle());
        label.setPosition(new Position(labelDTO.getPosition().getX(), labelDTO.getPosition().getY()));
        if (labelDTO.getWidth() != null && labelDTO.getHeight() != null) {
            label.setSize(new Size(labelDTO.getWidth(), labelDTO.getHeight()));
        }

        processGroup.addLabel(label);
    }

    // update nested process groups (recursively)
    final List<Element> nestedProcessGroupNodeList = getChildrenByTagName(processGroupElement, "processGroup");
    for (final Element nestedProcessGroupElement : nestedProcessGroupNodeList) {
        updateProcessGroup(controller, processGroup, nestedProcessGroupElement, encryptor, encodingVersion);
    }

    // update connections
    final List<Element> connectionNodeList = getChildrenByTagName(processGroupElement, "connection");
    for (final Element connectionElement : connectionNodeList) {
        final ConnectionDTO dto = FlowFromDOMFactory.getConnection(connectionElement);

        final Connection connection = processGroup.getConnection(dto.getId());
        connection.setName(dto.getName());
        connection.setProcessGroup(processGroup);

        if (dto.getLabelIndex() != null) {
            connection.setLabelIndex(dto.getLabelIndex());
        }
        if (dto.getzIndex() != null) {
            connection.setZIndex(dto.getzIndex());
        }

        final List<Position> bendPoints = new ArrayList<>();
        for (final PositionDTO bend : dto.getBends()) {
            bendPoints.add(new Position(bend.getX(), bend.getY()));
        }
        connection.setBendPoints(bendPoints);

        List<FlowFilePrioritizer> newPrioritizers = null;
        final List<String> prioritizers = dto.getPrioritizers();
        if (prioritizers != null) {
            final List<String> newPrioritizersClasses = new ArrayList<>(prioritizers);
            newPrioritizers = new ArrayList<>();
            for (final String className : newPrioritizersClasses) {
                try {
                    newPrioritizers.add(controller.createPrioritizer(className));
                } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                    throw new IllegalArgumentException("Unable to set prioritizer " + className + ": " + e);
                }
            }
        }

        if (newPrioritizers != null) {
            connection.getFlowFileQueue().setPriorities(newPrioritizers);
        }

        if (dto.getBackPressureObjectThreshold() != null) {
            connection.getFlowFileQueue().setBackPressureObjectThreshold(dto.getBackPressureObjectThreshold());
        }

        if (dto.getBackPressureDataSizeThreshold() != null
                && !dto.getBackPressureDataSizeThreshold().trim().isEmpty()) {
            connection.getFlowFileQueue()
                    .setBackPressureDataSizeThreshold(dto.getBackPressureDataSizeThreshold());
        }

        if (dto.getFlowFileExpiration() != null) {
            connection.getFlowFileQueue().setFlowFileExpiration(dto.getFlowFileExpiration());
        }
    }

    // Replace the templates with those from the proposed flow
    final List<Element> templateNodeList = getChildrenByTagName(processGroupElement, "template");
    for (final Element templateElement : templateNodeList) {
        final TemplateDTO templateDto = TemplateUtils.parseDto(templateElement);
        final Template template = new Template(templateDto);

        // If the Process Group already has the template, remove it and add it again. We do this
        // to ensure that all of the nodes have the same view of the template. Templates are immutable,
        // so any two nodes that have a template with the same ID should have the exact same template.
        // This just makes sure that they do.
        if (processGroup.getTemplate(template.getIdentifier()) != null) {
            processGroup.removeTemplate(template);
        }
        processGroup.addTemplate(template);
    }

    return processGroup;
}

From source file:com.oakesville.mythling.MediaActivity.java

protected void downloadItem(final Item item) {
    try {// w  ww.  java2s  .com
        final URL baseUrl = getAppSettings().getMythTvServicesBaseUrlWithCredentials();

        String fileUrl = baseUrl + "/Content/GetFile?";
        if (item.getStorageGroup() == null)
            fileUrl += "StorageGroup=None&";
        else
            fileUrl += "StorageGroup=" + item.getStorageGroup().getName() + "&";
        fileUrl += "FileName=" + URLEncoder.encode(item.getFilePath(), "UTF-8");

        Uri uri = Uri.parse(fileUrl.toString());
        ProxyInfo proxyInfo = MediaStreamProxy.needsAuthProxy(uri);
        if (proxyInfo != null) {
            // needs proxying to support authentication since DownloadManager doesn't support
            MediaStreamProxy proxy = new MediaStreamProxy(proxyInfo,
                    AuthType.valueOf(appSettings.getMythTvServicesAuthType()));
            proxy.init();
            proxy.start();
            fileUrl = "http://" + proxy.getLocalhost().getHostAddress() + ":" + proxy.getPort() + uri.getPath();
            if (uri.getQuery() != null)
                fileUrl += "?" + uri.getQuery();
        }

        Log.i(TAG, "Media download URL: " + fileUrl);

        stopProgress();

        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        Request request = new Request(Uri.parse(fileUrl));
        request.setTitle(item.getOneLineTitle());
        String downloadFilePath = null;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File downloadDir = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                if (downloadDir.exists()) {
                    String downloadPath = AppSettings.getExternalStorageDir() + "/";
                    if (getPath() != null && !getPath().isEmpty() && !getPath().equals("/"))
                        downloadPath += getPath() + "/";
                    File destDir = new File(downloadDir + "/" + downloadPath);
                    if (destDir.isDirectory() || destDir.mkdirs()) {
                        downloadFilePath = downloadPath + item.getDownloadFilename();
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                downloadFilePath);
                        request.allowScanningByMediaScanner();
                    }
                }
            }
        } catch (IllegalStateException ex) {
            // store internal
        } catch (Exception ex) {
            // log, report and store internal
            Log.e(TAG, ex.getMessage(), ex);
            if (getAppSettings().isErrorReportingEnabled())
                new Reporter(ex).send();
            Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(),
                    Toast.LENGTH_LONG).show();
        }
        long downloadId = dm.enqueue(request);
        registerDownloadReceiver(item, downloadId);
        Toast.makeText(getApplicationContext(), getString(R.string.downloading_) + item.getOneLineTitle(),
                Toast.LENGTH_LONG).show();
        getAppData().addDownload(new Download(item.getId(), downloadId, downloadFilePath, new Date()));
        if (item.isRecording() && (mediaList.isMythTv28() || getAppSettings().isMythlingMediaServices()))
            new GetCutListTask((Recording) item, downloadId).execute();
    } catch (Exception ex) {
        stopProgress();
        Log.e(TAG, ex.getMessage(), ex);
        if (getAppSettings().isErrorReportingEnabled())
            new Reporter(ex).send();
        Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(), Toast.LENGTH_LONG)
                .show();
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAO.java

/**
 * Update the size of specified node, plus set BusyState of the DataNode to not-busy.
 *
 * @param node//from  w  w  w.  j a v  a 2s.  com
 * @param meta the new metadata
 * @param strict If the update should only occur if the lastModified date is the same.
 */
public void updateNodeMetadata(DataNode node, FileMetadata meta, boolean strict) throws TransientException {
    log.debug("updateNodeMetadata: " + node.getUri().getPath());

    expectPersistentNode(node);

    try {
        startTransaction();
        prof.checkpoint("start.DataNodeUpdateStatementCreator");

        // get the last modified date object if matching on the update
        Date lastModified = null;
        if (strict) {
            String lastModStr = node.getPropertyValue(VOS.PROPERTY_URI_DATE);
            lastModified = dateFormat.parse(lastModStr);
        }

        // update contentLength and md5
        DataNodeUpdateStatementCreator dnup = new DataNodeUpdateStatementCreator(getNodeID(node),
                meta.getContentLength(), meta.getMd5Sum(), lastModified);
        int num = jdbc.update(dnup);
        prof.checkpoint("DataNodeUpdateStatementCreator");
        log.debug("updateMetadata, rows updated: " + num);
        if (strict && num != 1)
            throw new IllegalStateException("Node has different lastModified value.");

        // last, update the busy state of the target node
        String trans = getSetBusyStateSQL(node, NodeBusyState.busyWithWrite, NodeBusyState.notBusy);
        log.debug(trans);
        num = jdbc.update(trans);
        prof.checkpoint("getSetBusyStateSQL");
        if (num != 1)
            throw new IllegalStateException(
                    "updateFileMetadata requires a node with busyState=W: " + node.getUri());

        // now safe to update properties of the target node
        List<NodeProperty> props = new ArrayList<NodeProperty>();
        NodeProperty np;

        np = findOrCreate(node, VOS.PROPERTY_URI_CONTENTENCODING, meta.getContentEncoding());
        if (np != null)
            props.add(np);
        np = findOrCreate(node, VOS.PROPERTY_URI_TYPE, meta.getContentType());
        if (np != null)
            props.add(np);

        doUpdateProperties(node, props);

        commitTransaction();
        prof.checkpoint("commit.DataNodeUpdateStatementCreator");
    } catch (IllegalStateException ex) {
        log.debug(ex.toString());
        if (transactionStatus != null)
            try {
                rollbackTransaction();
                prof.checkpoint("rollback.DataNodeUpdateStatementCreator");
            } catch (Throwable oops) {
                log.error("failed to rollback transaction", oops);
            }
        throw ex;
    } catch (Throwable t) {
        log.error("updateNodeMetadata rollback for node: " + node.getUri().getPath(), t);
        if (transactionStatus != null)
            try {
                rollbackTransaction();
                prof.checkpoint("rollback.DataNodeUpdateStatementCreator");
            } catch (Throwable oops) {
                log.error("failed to rollback transaction", oops);
            }

        if (DBUtil.isTransientDBException(t))
            throw new TransientException("failed to updateNodeMetadata " + node.getUri().getPath(), t);
        else
            throw new RuntimeException("failed to updateNodeMetadata " + node.getUri().getPath(), t);

    } finally {
        if (transactionStatus != null)
            try {
                log.warn("delete - BUG - transaction still open in finally... calling rollback");
                rollbackTransaction();
            } catch (Throwable oops) {
                log.error("failed to rollback transaction in finally", oops);
            }
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAO.java

/**
 * Move the node to inside the destination container.
 *
 * @param src The node to move/*from   w w w.j a v a  2  s. co  m*/
 * @param dest The container in which to move the node.
 */
public void move(Node src, ContainerNode dest) throws TransientException {
    log.debug("move: " + src.getUri() + " to " + dest.getUri() + " as " + src.getName());
    expectPersistentNode(src);
    expectPersistentNode(dest);

    // move rule checking
    if (src instanceof ContainerNode) {
        // check that we are not moving root or a root container
        if (src.getParent() == null || src.getParent().getUri().isRoot())
            throw new IllegalArgumentException("Cannot move a root container.");

        // check that 'src' is not in the path of 'dest' so that
        // circular paths are not created
        Node target = dest;
        Long srcNodeID = getNodeID(src);
        Long targetNodeID = null;
        while (target != null && !target.getUri().isRoot()) {
            targetNodeID = getNodeID(target);
            if (targetNodeID.equals(srcNodeID))
                throw new IllegalArgumentException("Cannot move to a contained sub-node.");
            target = target.getParent();
        }
    }

    try {
        startTransaction();
        prof.checkpoint("start.move");

        // get the lock
        String sql = this.getUpdateLockSQL(src);
        jdbc.update(sql);
        prof.checkpoint("getUpdateLockSQL");

        Long contentLength = new Long(0);
        if (!(src instanceof LinkNode)) {
            // get the contentLength
            sql = this.getSelectContentLengthForDeleteSQL(src);

            // Note: if contentLength is null, jdbc template will return zero.
            contentLength = jdbc.queryForLong(sql);
            prof.checkpoint("getSelectContentLengthSQL");
        }

        // re-parent the node
        ContainerNode srcParent = src.getParent();
        src.setParent(dest);

        // update the node with the new parent and potentially new name
        NodePutStatementCreator putStatementCreator = new NodePutStatementCreator(nodeSchema, true);
        putStatementCreator.setValues(src, null);
        int count = jdbc.update(putStatementCreator);
        prof.checkpoint("NodePutStatementCreator");
        if (count == 0) {
            // tried to move a busy data node
            throw new IllegalStateException("src node busy: " + src.getUri());
        }

        if (!(src instanceof LinkNode)) {
            // apply the size difference
            String sql1 = getApplySizeDiffSQL(srcParent, contentLength, false);
            String sql2 = getApplySizeDiffSQL(dest, contentLength, true);

            // these operations should happen in either child-parent or nodeID order
            // for consistency to avoid deadlocks
            if (srcParent.getParent() != null && src.getParent().equals(dest)) {
                // OK: sql1 is child and sql2 is parent
            } else if (dest.getParent() != null && dest.getParent().equals(srcParent)) {
                // sql1 is parent and sql2 is child: swap
                String swap = sql1;
                sql1 = sql2;
                sql2 = swap;
            } else if (getNodeID(srcParent) > getNodeID(dest)) {
                String swap = sql1;
                sql1 = sql2;
                sql2 = swap;
            }

            log.debug(sql1);
            jdbc.update(sql1);
            prof.checkpoint("getApplySizeDiffSQL");
            log.debug(sql2);
            jdbc.update(sql2);
            prof.checkpoint("getApplySizeDiffSQL");
        }

        // recursive chown removed since it is costly and nominally incorrect

        commitTransaction();
        prof.checkpoint("commit.move");
    } catch (IllegalStateException ex) {
        log.debug(ex.toString());
        if (transactionStatus != null)
            try {
                rollbackTransaction();
                prof.checkpoint("rollback.move");
            } catch (Throwable oops) {
                log.error("failed to rollback transaction", oops);
            }
        throw ex;
    } catch (Throwable t) {
        log.error("move rollback for node: " + src.getUri().getPath(), t);
        if (transactionStatus != null)
            try {
                rollbackTransaction();
                prof.checkpoint("rollback.move");
            } catch (Throwable oops) {
                log.error("failed to rollback transaction", oops);
            }

        if (t instanceof IllegalStateException)
            throw (IllegalStateException) t;
        else if (DBUtil.isTransientDBException(t))
            throw new TransientException("failed to move:  " + src.getUri().getPath(), t);
        else
            throw new RuntimeException("failed to move:  " + src.getUri().getPath(), t);
    } finally {
        if (transactionStatus != null) {
            try {
                log.warn("move - BUG - transaction still open in finally... calling rollback");
                rollbackTransaction();
            } catch (Throwable oops) {
                log.error("failed to rollback transaction in finally", oops);
            }
        }
    }
}