Example usage for java.io Serializable toString

List of usage examples for java.io Serializable toString

Introduction

In this page you can find the example usage for java.io Serializable toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.alfresco.reporting.processor.WorkflowTaskPropertyProcessor.java

/**
 * // w  ww.j  a  v  a2s . c  o m
 * @param s
 * @param dtype
 * @param multiValued
 * @return
 */
private String getPropertyValue(Serializable s, final String dtype, final boolean multiValued) {
    logger.debug("Enter getPropertyValue");
    String returnValue = "";
    if (multiValued && !"category".equals(dtype)) {
        @SuppressWarnings("unchecked")
        ArrayList<Object> values = (ArrayList<Object>) s;

        if ((values != null) && (!values.isEmpty()) && (values.size() > 0)) {

            if (dtype.equals("date") || dtype.equals("datetime")) {

                for (int v = 0; v < values.size(); v++) {
                    returnValue += getSimpleDateFormat().format((Date) values.get(v))
                            + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("id") || dtype.equals("long")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Long.toString((Long) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("int")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Integer.toString((Integer) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("float") || dtype.equals("double")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Double.toString((Double) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("boolean")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Boolean.toString((Boolean) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("text")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += (String) values.get(v) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("noderef")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += values.get(v).toString() + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (returnValue.equals("")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += (String) values.get(v) + Constants.MULTIVALUE_SEPERATOR;
                }
            }
        }
        // end multivalue
    } else {
        if ((s != null) && !"category".equals(dtype)) {

            if (dtype.equals("date") || dtype.equals("datetime")) {

                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(((Date) s).getTime());
                returnValue = getSimpleDateFormat().format((Date) s);
                //returnValue = c.YEAR + "/"+ prefix(c.MONTH+1, 2, "0") + "/"+ prefix(c.DAY_OF_MONTH, 2, "0") + "T" + prefix(c.HOUR_OF_DAY, 2, "0")+":"+prefix(c.MINUTE, 2, "0")+":"+prefix(c.SECOND, 2, "0"); 
            }

            if (dtype.equals("id") || dtype.equals("long")) {
                returnValue = Long.toString((Long) s);
            }

            if (dtype.equals("int")) {
                returnValue = Integer.toString((Integer) s);
            }

            if (dtype.equals("float") || dtype.equals("double")) {
                returnValue = Double.toString((Double) s);
            }

            if (dtype.equals("boolean")) {
                returnValue = Boolean.toString((Boolean) s);
            }

            if (dtype.equals("text")) {
                returnValue = s.toString();
            }

            if (dtype.equals("noderef")) {
                returnValue = s.toString();
            }

            if (returnValue.equals("")) {
                returnValue = s.toString();
            }
        }
    } // end single valued
    /*
    if (qname.toString().endsWith("taggable")) {
    logger.error("I am a taggable!");
    List<String> tags = serviceRegistry.getTaggingService().getTags(nodeRef);
    logger.error("Found " + tags.size() + " tags!");
    for (String tag : tags){
    logger.error("processing tag: " + tag);
    if (returnValue.length()>0) returnValue+=",";
    returnValue+=tag;
    }
    } // end taggable
    */

    // Process categories
    if (dtype.equals("category")) {
        logger.debug("Found a category!");
        @SuppressWarnings("unchecked")
        List<NodeRef> categories = (List<NodeRef>) s;
        if (categories != null) {

            for (NodeRef cat : categories) {
                String catName = getNodeService().getProperty(cat, ContentModel.PROP_NAME).toString();

                if (returnValue.length() > 0)
                    returnValue += ",";
                returnValue += catName;
            } // end for
        } // end if categories != null
    } // end category

    logger.debug("Exit getPropertyValue, returning: " + returnValue);
    return returnValue;
}

From source file:org.nuxeo.ecm.core.storage.sql.Mapper.java

/**
 * Copies the hierarchy starting from a given fragment to a new parent with
 * a new name.//from w w w.  ja v  a  2s .  c o  m
 * <p>
 * If the new parent is {@code null}, then this is a version creation, which
 * doesn't recurse in regular children.
 * <p>
 * If {@code overwriteId} and {@code overwriteMap} are passed, the copy is
 * done onto this existing node as its root (version restore) instead of
 * creating a new node in the parent.
 *
 * @param sourceId the id of fragment to copy (with children)
 * @param typeName the type of the fragment to copy (to avoid refetching
 *            known info)
 * @param destParentId the new parent id, or {@code null}
 * @param destName the new name
 * @param overwriteId when not {@code null}, the copy is done onto this
 *            existing root id
 * @param overwriteMap when overwriting, set these hierarchy columns
 * @param persistenceContext the persistence context, to invalidate
 *            fragments when overwriting
 * @return the id of the root of the copy
 * @throws StorageException
 */
public Serializable copyHierarchy(Serializable sourceId, String typeName, Serializable destParentId,
        String destName, Serializable overwriteId, Map<String, Serializable> overwriteMap,
        PersistenceContext persistenceContext) throws StorageException {
    assert !model.separateMainTable; // other case not implemented
    HierarchyContext hierContext = persistenceContext.getHierContext();
    try {
        Map<Serializable, Serializable> idMap = new LinkedHashMap<Serializable, Serializable>();
        Map<Serializable, String> idType = new HashMap<Serializable, String>();
        // copy the hierarchy fragments recursively
        if (overwriteId != null) {
            // overwrite hier root with explicit values
            updateSingleRowWithValues(model.hierTableName, overwriteId, overwriteMap);
            idMap.put(sourceId, overwriteId);
            // invalidate
            hierContext.markInvalidated(overwriteId, true);
        }
        // create the new hierarchy by copy
        Serializable newRootId = copyHierRecursive(sourceId, typeName, destParentId, destName, overwriteId,
                idMap, idType);
        // invalidate children
        hierContext.markChildrenAdded(overwriteId == null ? destParentId : overwriteId);
        // copy all collected fragments
        for (Entry<String, Set<Serializable>> entry : model.getPerFragmentIds(idType).entrySet()) {
            String tableName = entry.getKey();
            // TODO move ACL skip logic higher
            if (tableName.equals(Model.ACL_TABLE_NAME)) {
                continue;
            }
            Set<Serializable> ids = entry.getValue();
            boolean overwrite = (overwriteId != null) && !tableName.equals(model.mainTableName);
            Boolean invalidation = copyFragments(tableName, ids, idMap, overwrite ? overwriteId : null);
            if (invalidation != null) {
                // make sure things are properly invalidated in this and
                // other sessions
                persistenceContext.getContext(tableName).markInvalidated(overwriteId,
                        invalidation.booleanValue());
            }
        }
        return newRootId;
    } catch (SQLException e) {
        checkConnectionReset(e);
        throw new StorageException("Could not copy: " + sourceId.toString(), e);
    }
}

From source file:org.pentaho.platform.repository2.unified.jcr.JcrRepositoryFileDao.java

private RepositoryFile internalCreateFile(final Serializable parentFolderId, final RepositoryFile file,
        final IRepositoryFileData content, final RepositoryFileAcl acl, final String versionMessage) {
    if (isKioskEnabled()) {
        throw new RuntimeException(
                Messages.getInstance().getString("JcrRepositoryFileDao.ERROR_0006_ACCESS_DENIED")); //$NON-NLS-1$
    }//from w ww . j  a va 2s.  c  o  m

    /*
     * PPP-3049: Changed the Assert.notNull(content) to code that creates a file with a single blank when the assert
     * WOULD have been triggered.
     */
    Assert.notNull(file);
    Assert.isTrue(!file.isFolder());

    // Get repository file info and acl info of parent
    if (parentFolderId != null) {
        RepositoryFile parentRepositoryFile = getFileById(parentFolderId);
        if (parentRepositoryFile != null) {
            RepositoryFileAcl parentAcl = aclDao.getAcl(parentRepositoryFile.getId());
            // Invoke accessVoterManager to see if we have access to perform this operation
            if (!accessVoterManager.hasAccess(parentRepositoryFile, RepositoryFilePermission.WRITE, parentAcl,
                    PentahoSessionHolder.getSession())) {
                return null;
            }
        }
    }
    // Assert.notNull(content);
    DataNode emptyDataNode = new DataNode(file.getName());
    emptyDataNode.setProperty(" ", "content"); //$NON-NLS-1$ //$NON-NLS-2$
    final IRepositoryFileData emptyContent = new NodeRepositoryFileData(emptyDataNode);

    return (RepositoryFile) jcrTemplate.execute(new JcrCallback() {
        @Override
        public Object doInJcr(final Session session) throws RepositoryException, IOException {
            PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
            JcrRepositoryFileUtils.checkoutNearestVersionableFileIfNecessary(session, pentahoJcrConstants,
                    parentFolderId);
            Node fileNode = JcrRepositoryFileUtils.createFileNode(session, pentahoJcrConstants, parentFolderId,
                    file, content == null ? emptyContent : content,
                    findTransformerForWrite(content == null ? emptyContent.getClass() : content.getClass()));
            // create a tmp file with correct path for default acl creation purposes.
            String path = JcrRepositoryFileUtils.getAbsolutePath(session, pentahoJcrConstants, fileNode);
            RepositoryFile tmpFile = new RepositoryFile.Builder(file).path(path).build();
            // we must create the acl during checkout
            aclDao.createAcl(fileNode.getIdentifier(),
                    acl == null ? defaultAclHandler.createDefaultAcl(tmpFile) : acl);
            session.save();
            if (file.isVersioned()) {
                JcrRepositoryFileUtils.checkinNearestVersionableNodeIfNecessary(session, pentahoJcrConstants,
                        fileNode, versionMessage, file.getCreatedDate(), false);

            }
            JcrRepositoryFileUtils.checkinNearestVersionableFileIfNecessary(session, pentahoJcrConstants,
                    parentFolderId,
                    Messages.getInstance().getString("JcrRepositoryFileDao.USER_0002_VER_COMMENT_ADD_FILE", //$NON-NLS-1$
                            file.getName(), (parentFolderId == null ? "root" : parentFolderId.toString()))); //$NON-NLS-1$
            return JcrRepositoryFileUtils.nodeToFile(session, pentahoJcrConstants, pathConversionHelper,
                    lockHelper, fileNode);
        }
    });
}

From source file:org.alfresco.reporting.processor.PropertyProcessor.java

/**
 * //from  w  w  w.ja v  a  2  s.c  o  m
 * @param s
 * @param dtype
 * @param multiValued
 * @return
 */
@SuppressWarnings("unused")
private String getPropertyValue(Serializable s, final String dtype, final boolean multiValued) {
    if (logger.isDebugEnabled())
        logger.debug("Enter getPropertyValue (3 params)");
    String returnValue = "";
    if (multiValued && !"category".equals(dtype)) {
        @SuppressWarnings("unchecked")
        ArrayList<Object> values = (ArrayList<Object>) s;

        if ((values != null) && (!values.isEmpty()) && (values.size() > 0)) {

            if (dtype.equals("date") || dtype.equals("datetime")) {

                for (int v = 0; v < values.size(); v++) {
                    returnValue += getSimpleDateFormat().format((Date) values.get(v))
                            + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("id") || dtype.equals("long")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Long.toString((Long) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("int")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Integer.toString((Integer) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("float") || dtype.equals("double")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Double.toString((Double) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("boolean")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Boolean.toString((Boolean) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("text")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += (String) values.get(v) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("noderef")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += values.get(v).toString() + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (returnValue.equals("")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += (String) values.get(v) + Constants.MULTIVALUE_SEPERATOR;
                }
            }
        }
        // end multivalue
    } else {
        if ((s != null) && !"category".equals(dtype)) {

            if (dtype.equals("date") || dtype.equals("datetime")) {
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(((Date) s).getTime());
                returnValue = getSimpleDateFormat().format((Date) s);
                //returnValue = c.YEAR + "/"+ prefix(c.MONTH+1, 2, "0") + "/"+ prefix(c.DAY_OF_MONTH, 2, "0") + "T" + prefix(c.HOUR_OF_DAY, 2, "0")+":"+prefix(c.MINUTE, 2, "0")+":"+prefix(c.SECOND, 2, "0"); 
            }

            if (dtype.equals("id") || dtype.equals("long")) {
                returnValue = Long.toString((Long) s);
            }

            if (dtype.equals("int")) {
                returnValue = Integer.toString((Integer) s);
            }

            if (dtype.equals("float") || dtype.equals("double")) {
                returnValue = Double.toString((Double) s);
            }

            if (dtype.equals("boolean")) {
                returnValue = Boolean.toString((Boolean) s);
            }

            if (dtype.equals("text")) {
                returnValue = s.toString();
            }

            if (dtype.equals("noderef")) {
                returnValue = s.toString();
            }

            if (returnValue.equals("")) {
                returnValue = s.toString();
            }
        }
    } // end single valued
    /*
    if (qname.toString().endsWith("taggable")) {
    logger.error("I am a taggable!");
    List<String> tags = serviceRegistry.getTaggingService().getTags(nodeRef);
    logger.error("Found " + tags.size() + " tags!");
    for (String tag : tags){
    logger.error("processing tag: " + tag);
    if (returnValue.length()>0) returnValue+=",";
    returnValue+=tag;
    }
    } // end taggable
    */

    // Process categories
    if (dtype.equals("category")) {
        if (logger.isDebugEnabled())
            logger.debug("Found a category!");
        @SuppressWarnings("unchecked")
        List<NodeRef> categories = (List<NodeRef>) s;
        if (categories != null) {

            for (NodeRef cat : categories) {
                String catName = nodeService.getProperty(cat, ContentModel.PROP_NAME).toString();

                if (returnValue.length() > 0)
                    returnValue += ",";
                returnValue += catName;
            } // end for
        } // end if categories != null
    } // end category

    if (logger.isDebugEnabled())
        logger.debug("Exit getPropertyValue, returning: " + returnValue);
    return returnValue;
}

From source file:org.nuxeo.ecm.core.storage.BaseDocument.java

/**
 * Writes state from a complex property.
 * <p>/*from  w w  w. j  a  va  2s .co m*/
 * Writes only properties that are dirty.
 *
 * @return {@code true} if something changed
 */
protected boolean writeComplexProperty(T state, ComplexProperty complexProperty, String xpath, WriteContext wc)
        throws PropertyException {
    @SuppressWarnings("unchecked")
    BlobWriteContext<T> writeContext = (BlobWriteContext<T>) wc;
    if (complexProperty instanceof BlobProperty) {
        Serializable value = ((BlobProperty) complexProperty).getValueForWrite();
        if (value != null && !(value instanceof Blob)) {
            throw new PropertyException("Cannot write a non-Blob value: " + value);
        }
        writeContext.recordBlob(state, (Blob) value, this);
        return true;
    }
    boolean changed = false;
    for (Property property : complexProperty) {
        // write dirty properties, but also phantoms with non-null default values
        // this is critical for DeltaLong updates to work, they need a non-null initial value
        if (property.isDirty() || (property.isPhantom() && property.getField().getDefaultValue() != null)) {
            // do the write
        } else {
            continue;
        }
        String name = property.getField().getName().getPrefixedName();
        name = internalName(name);
        if (checkReadOnlyIgnoredWrite(property, state)) {
            continue;
        }
        String xp = xpath == null ? name : xpath + '/' + name;
        writeContext.recordChange(xp);
        changed = true;

        Type type = property.getType();
        if (type.isSimpleType()) {
            // simple property
            Serializable value = property.getValueForWrite();
            state.setSingle(name, value);
        } else if (type.isComplexType()) {
            // complex property
            T childState = getChildForWrite(state, name, type);
            writeComplexProperty(childState, (ComplexProperty) property, xp, writeContext);
        } else {
            ListType listType = (ListType) type;
            if (listType.getFieldType().isSimpleType()) {
                // array
                Serializable value = property.getValueForWrite();
                if (value instanceof List) {
                    List<?> list = (List<?>) value;
                    Object[] array;
                    if (list.isEmpty()) {
                        array = new Object[0];
                    } else {
                        // use properly-typed array, useful for mem backend that doesn't re-convert all types
                        Class<?> klass = list.get(0).getClass();
                        array = (Object[]) Array.newInstance(klass, list.size());
                    }
                    value = list.toArray(array);
                } else if (value instanceof Object[]) {
                    Object[] ar = (Object[]) value;
                    if (ar.length != 0) {
                        // use properly-typed array, useful for mem backend that doesn't re-convert all types
                        Class<?> klass = Object.class;
                        for (Object o : ar) {
                            if (o != null) {
                                klass = o.getClass();
                                break;
                            }
                        }
                        Object[] array;
                        if (ar.getClass().getComponentType() == klass) {
                            array = ar;
                        } else {
                            // copy to array with proper component type
                            array = (Object[]) Array.newInstance(klass, ar.length);
                            System.arraycopy(ar, 0, array, 0, ar.length);
                        }
                        value = array;
                    }
                } else if (value == null) {
                    // ok
                } else {
                    throw new IllegalStateException(value.toString());
                }
                state.setArray(name, (Object[]) value);
            } else {
                // complex list
                // update it
                List<T> childStates = updateList(state, name, property);
                // write values
                int i = 0;
                for (Property childProperty : property.getChildren()) {
                    T childState = childStates.get(i);
                    String xpi = xp + '/' + i;
                    boolean c = writeComplexProperty(childState, (ComplexProperty) childProperty, xpi,
                            writeContext);
                    if (c) {
                        writeContext.recordChange(xpi);
                    }
                    i++;
                }
            }
        }
    }
    return changed;
}

From source file:org.alfresco.opencmis.CMISConnector.java

/**
 * Sets a property value.//from  www . jav  a 2s  .  c  om
 */
public void setProperty(NodeRef nodeRef, TypeDefinitionWrapper type, String propertyId, Serializable value) {
    if (propertyId == null) {
        throw new CmisInvalidArgumentException("Cannot process not null property!");
    }

    PropertyDefinitionWrapper propDef = type.getPropertyById(propertyId);
    if (propDef == null) {
        throw new CmisInvalidArgumentException("Property " + propertyId + " is unknown!");
    }

    Updatability updatability = propDef.getPropertyDefinition().getUpdatability();
    if ((updatability == Updatability.READONLY) || (updatability == Updatability.WHENCHECKEDOUT
            && !checkOutCheckInService.isWorkingCopy(nodeRef))) {
        throw new CmisInvalidArgumentException("Property " + propertyId + " is read-only!");
    }

    if (propDef.getPropertyId().equals(PropertyIds.SECONDARY_OBJECT_TYPE_IDS)) {
        throw new IllegalArgumentException(
                "Cannot process " + PropertyIds.SECONDARY_OBJECT_TYPE_IDS + " in setProperty");
    } else {
        QName propertyQName = propDef.getPropertyAccessor().getMappedProperty();
        if (propertyQName == null) {
            throw new CmisConstraintException("Unable to set property " + propertyId + "!");
        }

        if (propertyId.equals(PropertyIds.NAME)) {
            if (!(value instanceof String)) {
                throw new CmisInvalidArgumentException("Object name must be a string!");
            }

            try {
                fileFolderService.rename(nodeRef, value.toString());
            } catch (FileExistsException e) {
                throw new CmisContentAlreadyExistsException("An object with this name already exists!", e);
            } catch (FileNotFoundException e) {
                throw new CmisInvalidArgumentException("Object with id " + nodeRef.getId() + " not found!");
            }
        } else {
            // overflow check
            if (propDef.getPropertyDefinition().getPropertyType() == PropertyType.INTEGER
                    && value instanceof BigInteger) {
                org.alfresco.service.cmr.dictionary.PropertyDefinition def = dictionaryService
                        .getProperty(propertyQName);
                QName dataDef = def.getDataType().getName();
                BigInteger bigValue = (BigInteger) value;

                if ((bigValue.compareTo(maxInt) > 0 || bigValue.compareTo(minInt) < 0)
                        && dataDef.equals(DataTypeDefinition.INT)) {
                    throw new CmisConstraintException(
                            "Value is out of range for property " + propertyQName.getLocalName());
                }

                if ((bigValue.compareTo(maxLong) > 0 || bigValue.compareTo(minLong) < 0)
                        && dataDef.equals(DataTypeDefinition.LONG)) {
                    throw new CmisConstraintException(
                            "Value is out of range for property " + propertyQName.getLocalName());
                }
            }

            nodeService.setProperty(nodeRef, propertyQName, value);
        }
    }
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

/**
 * Serializes and packages an intercepted change in object state.
 * <p>/*w w w.  jav  a2 s  .  c o  m*/
 * IMPORTANT serialization notes:
 * <p>
 * Transient Properties. Transients are not serialized/journalled. Marking an object property as
 * transient is the supported way of designating it as something not to be recorded into the
 * journal.
 * <p/>
 * Hibernate Identity property. A property designated in Hibernate as identity (i.e. primary
 * key) *is* not serialized. This is because sync does not enforce global uniqueness of database
 * primary keys. Instead, custom uuid property is used. This allows us to continue to use native
 * types for 'traditional' entity relationships.
 *
 * @param entity The object changed.
 * @param currentState Array containing data for each field in the object as they will be saved.
 * @param propertyNames Array containing name for each field in the object, corresponding to
 *            currentState.
 * @param types Array containing Type of the field in the object, corresponding to currentState.
 * @param state SyncItemState, e.g. NEW, UPDATED, DELETED
 * @param id Value of the identifier for this entity
 */
protected void packageObject(OpenmrsObject entity, Object[] currentState, String[] propertyNames, Type[] types,
        Serializable id, SyncItemState state) throws SyncException {

    String objectUuid = null;
    String originalRecordUuid = null;
    Set<String> transientProps = null;
    String infoMsg = null;

    ClassMetadata data = null;
    String idPropertyName = null;
    org.hibernate.tuple.IdentifierProperty idPropertyObj = null;

    // The container of values to be serialized:
    // Holds tuples of <property-name> -> {<property-type-name>,
    // <property-value as string>}
    HashMap<String, PropertyClassValue> values = new HashMap<String, PropertyClassValue>();

    try {
        objectUuid = entity.getUuid();

        // pull-out sync-network wide change id for the sync *record* (not the entity itself),
        // if one was already assigned (i.e. this change is coming from some other server)
        originalRecordUuid = getSyncRecord().getOriginalUuid();

        if (log.isDebugEnabled()) {
            // build up a starting msg for all logging:
            StringBuilder sb = new StringBuilder();
            sb.append("In PackageObject, entity type:");
            sb.append(entity.getClass().getName());
            sb.append(", entity uuid:");
            sb.append(objectUuid);
            sb.append(", originalUuid uuid:");
            sb.append(originalRecordUuid);
            log.debug(sb.toString());
        }

        // Transient properties are not serialized.
        transientProps = new HashSet<String>();
        for (Field f : entity.getClass().getDeclaredFields()) {
            if (Modifier.isTransient(f.getModifiers())) {
                transientProps.add(f.getName());
                if (log.isDebugEnabled())
                    log.debug("The field " + f.getName() + " is transient - so we won't serialize it");
            }
        }

        /*
         * Retrieve metadata for this type; we need to determine what is the
         * PK field for this type. We need to know this since PK values are
         * *not* journalled; values of primary keys are assigned where
         * physical DB records are created. This is so to avoid issues with
         * id collisions.
         *
         * In case of <generator class="assigned" />, the Identifier
         * property is already assigned value and needs to be journalled.
         * Also, the prop will *not* be part of currentState,thus we need to
         * pull it out with reflection/metadata.
         */
        data = getSessionFactory().getClassMetadata(entity.getClass());
        if (data.hasIdentifierProperty()) {
            idPropertyName = data.getIdentifierPropertyName();
            idPropertyObj = ((org.hibernate.persister.entity.AbstractEntityPersister) data).getEntityMetamodel()
                    .getIdentifierProperty();

            if (id != null && idPropertyObj.getIdentifierGenerator() != null
                    && (idPropertyObj.getIdentifierGenerator() instanceof org.hibernate.id.Assigned
                    //   || idPropertyObj.getIdentifierGenerator() instanceof org.openmrs.api.db.hibernate.NativeIfNotAssignedIdentityGenerator
                    )) {
                // serialize value as string
                values.put(idPropertyName, new PropertyClassValue(id.getClass().getName(), id.toString()));
            }
        } else if (data.getIdentifierType() instanceof EmbeddedComponentType) {
            // if we have a component identifier type (like AlertRecipient),
            // make
            // sure we include those properties
            EmbeddedComponentType type = (EmbeddedComponentType) data.getIdentifierType();
            for (int i = 0; i < type.getPropertyNames().length; i++) {
                String propertyName = type.getPropertyNames()[i];
                Object propertyValue = type.getPropertyValue(entity, i, org.hibernate.EntityMode.POJO);
                addProperty(values, entity, type.getSubtypes()[i], propertyName, propertyValue, infoMsg);
            }
        }

        /*
         * Loop through all the properties/values and put in a hash for
         * duplicate removal
         */
        for (int i = 0; i < types.length; i++) {
            String typeName = types[i].getName();
            if (log.isDebugEnabled())
                log.debug("Processing, type: " + typeName + " Field: " + propertyNames[i]);

            if (propertyNames[i].equals(idPropertyName) && log.isInfoEnabled())
                log.debug(infoMsg + ", Id for this class: " + idPropertyName + " , value:" + currentState[i]);

            if (currentState[i] != null) {
                // is this the primary key or transient? if so, we don't
                // want to serialize
                if (propertyNames[i].equals(idPropertyName)
                        || ("personId".equals(idPropertyName) && "patientId".equals(propertyNames[i]))
                        //|| ("personId".equals(idPropertyName) && "userId".equals(propertyNames[i]))
                        || transientProps.contains(propertyNames[i])) {
                    // if (log.isInfoEnabled())
                    log.debug("Skipping property (" + propertyNames[i]
                            + ") because it's either the primary key or it's transient.");

                } else {

                    addProperty(values, entity, types[i], propertyNames[i], currentState[i], infoMsg);
                }
            } else {
                // current state null -- skip
                if (log.isDebugEnabled())
                    log.debug("Field Type: " + typeName + " Field Name: " + propertyNames[i]
                            + " is null, skipped");
            }
        }

        /*
         * Now serialize the data identified and put in the value-map
         */
        // Setup the serialization data structures to hold the state
        Package pkg = new Package();
        String className = entity.getClass().getName();
        Record xml = pkg.createRecordForWrite(className);
        Item entityItem = xml.getRootItem();

        // loop through the map of the properties that need to be serialized
        for (Map.Entry<String, PropertyClassValue> me : values.entrySet()) {
            String property = me.getKey();

            // if we are processing onDelete event all we need is uuid
            if ((state == SyncItemState.DELETED) && (!"uuid".equals(property))) {
                continue;
            }

            try {
                PropertyClassValue pcv = me.getValue();
                appendRecord(xml, entity, entityItem, property, pcv.getClazz(), pcv.getValue());
            } catch (Exception e) {
                String msg = "Could not append attribute. Error while processing property: " + property + " - "
                        + e.getMessage();
                throw (new SyncException(msg, e));
            }
        }

        values.clear(); // Be nice to GC

        if (objectUuid == null)
            throw new SyncException("uuid is null for: " + className + " with id: " + id);

        /*
         * Create SyncItem and store change in SyncRecord kept in
         * ThreadLocal.
         */
        SyncItem syncItem = new SyncItem();
        syncItem.setKey(new SyncItemKey<String>(objectUuid, String.class));
        syncItem.setState(state);
        syncItem.setContent(xml.toStringAsDocumentFragment());
        syncItem.setContainedType(entity.getClass());

        if (log.isDebugEnabled())
            log.debug("Adding SyncItem to SyncRecord");

        getSyncRecord().addItem(syncItem);
        getSyncRecord().addContainedClass(entity.getClass().getName());

        // set the originating uuid for the record: do this once per Tx;
        // else we may end up with empty string
        if (getSyncRecord().getOriginalUuid() == null || "".equals(getSyncRecord().getOriginalUuid())) {
            getSyncRecord().setOriginalUuid(originalRecordUuid);
        }
    } catch (SyncException ex) {
        log.error("Journal error\n", ex);
        throw (ex);
    } catch (Exception e) {
        log.error("Journal error\n", e);
        throw (new SyncException("Error in interceptor, see log messages and callstack.", e));
    }

    return;
}

From source file:org.alfresco.reporting.processor.PropertyProcessor.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public String getPropertyValue(final NodeRef nodeRef, final QName qname, final String dtype,
        final boolean multiValued) {
    if (logger.isDebugEnabled())
        logger.debug("Enter getPropertyValue (4 params), qname=" + qname + ", noderef=" + nodeRef + ", dtype="
                + dtype);//from  w w  w.j  a va  2s . c  o  m
    String returnValue = ""; // how could this have been null... there are too many += constructs that will fail...
    Serializable s = getNodeService().getProperty(nodeRef, qname);
    if (logger.isDebugEnabled())
        logger.debug("getPropertyType Serialized=" + s);

    // Tjarda: Check of s!=null wel valide is! Bij Tags en Categories
    if (multiValued && !"category".equals(dtype)) {

        ArrayList<Object> values = new ArrayList();

        values = (ArrayList) getNodeService().getProperty(nodeRef, qname);

        if ((values != null) && (!values.isEmpty()) && (values.size() > 0)) {

            if (dtype.equals("date") || dtype.equals("datetime")) {
                SimpleDateFormat dateformat = getSimpleDateFormat();
                //               Calendar c = Calendar.getInstance();

                for (int v = 0; v < values.size(); v++) {
                    returnValue += dateformat.format((Date) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("id") || dtype.equals("long")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Long.toString((Long) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("int")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Integer.toString((Integer) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("float") || dtype.equals("double")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Double.toString((Double) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("boolean")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Boolean.toString((Boolean) values.get(v)) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("text")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += (String) values.get(v) + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (dtype.equals("noderef")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += values.get(v).toString() + Constants.MULTIVALUE_SEPERATOR;
                }
            }

            if (returnValue.equals("")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += (String) values.get(v) + Constants.MULTIVALUE_SEPERATOR;
                }
            }
        }
        // end multivalue
    } else {
        if ((s != null) && !"category".equals(dtype)) {

            if (dtype.equals("date") || dtype.equals("datetime")) {
                SimpleDateFormat dateformat = getSimpleDateFormat();
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(((Date) s).getTime());
                returnValue = dateformat.format((Date) s);
                //returnValue = c.YEAR + "/"+ prefix(c.MONTH+1, 2, "0") + "/"+ prefix(c.DAY_OF_MONTH, 2, "0") + "T" + prefix(c.HOUR_OF_DAY, 2, "0")+":"+prefix(c.MINUTE, 2, "0")+":"+prefix(c.SECOND, 2, "0"); 
            }

            if (dtype.equals("id") || dtype.equals("long")) {
                returnValue = Long.toString((Long) s);
            }

            if (dtype.equals("int")) {
                returnValue = Integer.toString((Integer) s);
            }

            if (dtype.equals("float") || dtype.equals("double")) {
                returnValue = Double.toString((Double) s);
            }

            if (dtype.equals("boolean")) {
                returnValue = Boolean.toString((Boolean) s);
            }

            if (dtype.equals("text")) {
                returnValue = s.toString();
            }

            if (dtype.equals("noderef")) {
                returnValue = s.toString();
            }

            // why this one below?? Without it it doesn't work, but that is a bad excuse...
            if (returnValue.equals("")) {
                returnValue = String.valueOf(s);
            }
        }
    } // end single valued
    /*
    if (qname.toString().endsWith("taggable")) {
       logger.error("I am a taggable!");
       List<String> tags = serviceRegistry.getTaggingService().getTags(nodeRef);
       logger.error("Found " + tags.size() + " tags!");
       for (String tag : tags){
    logger.error("processing tag: " + tag);
    if (returnValue.length()>0) returnValue+=",";
    returnValue+=tag;
       }
    } // end taggable
    */

    if (dtype.equals("category")) {
        if (logger.isDebugEnabled())
            logger.debug("I am a category!");
        List<NodeRef> categories = (List<NodeRef>) nodeService.getProperty(nodeRef, qname);
        if (categories != null) {

            for (NodeRef cat : categories) {
                String catName = nodeService.getProperty(cat, ContentModel.PROP_NAME).toString();
                catName = getCategoryDisplayPath(cat);
                if (returnValue.length() > 0)
                    returnValue += ",";
                returnValue += catName;
            } // end for
        } // end if categories != null
    } // end category

    if (logger.isDebugEnabled())
        logger.debug("Exit getPropertyValue, returning: " + returnValue);
    return returnValue;
}

From source file:org.pentaho.platform.repository2.unified.jcr.JcrRepositoryFileDaoInst.java

public void internalCopyOrMove(Session session, final RepositoryFile file, final String destRelPath,
        final String versionMessage, final boolean copy) throws RepositoryException, IOException {
    if (!hasAccess(file, RepositoryFilePermission.WRITE)) {
        return;/*from   w w  w.  j  av a2  s. c om*/
    }
    PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
    String destAbsPath = pathConversionHelper.relToAbs(destRelPath);
    String cleanDestAbsPath = destAbsPath;
    if (cleanDestAbsPath.endsWith(RepositoryFile.SEPARATOR)) {
        cleanDestAbsPath.substring(0, cleanDestAbsPath.length() - 1);
    }
    Node srcFileNode = session.getNodeByIdentifier(file.getId().toString());
    Serializable srcParentFolderId = JcrRepositoryFileUtils.getParentId(session, file.getId());
    boolean appendFileName = false;
    boolean destExists = true;
    Node destFileNode = null;
    Node destParentFolderNode = null;
    try {
        destFileNode = (Node) session.getItem(JcrStringHelper.pathEncode(cleanDestAbsPath));
    } catch (PathNotFoundException e) {
        destExists = false;
    }
    if (destExists) {
        // make sure it's a file or folder
        Assert.isTrue(JcrRepositoryFileUtils.isSupportedNodeType(pentahoJcrConstants, destFileNode));
        // existing item; make sure src is not a folder if dest is a file
        Assert.isTrue(
                !(JcrRepositoryFileUtils.isPentahoFolder(pentahoJcrConstants, srcFileNode)
                        && JcrRepositoryFileUtils.isPentahoFile(pentahoJcrConstants, destFileNode)),
                Messages.getInstance()
                        .getString("JcrRepositoryFileDao.ERROR_0002_CANNOT_OVERWRITE_FILE_WITH_FOLDER")); //$NON-NLS-1$
        if (JcrRepositoryFileUtils.isPentahoFolder(pentahoJcrConstants, destFileNode)) {
            // existing item; caller is not renaming file, only moving it
            appendFileName = true;
            destParentFolderNode = destFileNode;
        } else {
            // get parent of existing dest item
            int lastSlashIndex = cleanDestAbsPath.lastIndexOf(RepositoryFile.SEPARATOR);
            Assert.isTrue(lastSlashIndex > 1,
                    Messages.getInstance().getString("JcrRepositoryFileDao.ERROR_0003_ILLEGAL_DEST_PATH")); //$NON-NLS-1$
            String absPathToDestParentFolder = cleanDestAbsPath.substring(0, lastSlashIndex);
            destParentFolderNode = (Node) session
                    .getItem(JcrStringHelper.pathEncode(absPathToDestParentFolder));
        }
    } else {
        // destination doesn't exist; go up one level to a folder that does exist
        int lastSlashIndex = cleanDestAbsPath.lastIndexOf(RepositoryFile.SEPARATOR);
        Assert.isTrue(lastSlashIndex > 1,
                Messages.getInstance().getString("JcrRepositoryFileDao.ERROR_0003_ILLEGAL_DEST_PATH")); //$NON-NLS-1$
        String absPathToDestParentFolder = cleanDestAbsPath.substring(0, lastSlashIndex);
        // Not need to check the name if we encoded it
        // JcrRepositoryFileUtils.checkName( cleanDestAbsPath.substring( lastSlashIndex + 1 ) );
        try {
            destParentFolderNode = (Node) session
                    .getItem(JcrStringHelper.pathEncode(absPathToDestParentFolder));
        } catch (PathNotFoundException e1) {
            Assert.isTrue(false,
                    Messages.getInstance().getString("JcrRepositoryFileDao.ERROR_0004_PARENT_MUST_EXIST")); //$NON-NLS-1$
        }
        Assert.isTrue(JcrRepositoryFileUtils.isPentahoFolder(pentahoJcrConstants, destParentFolderNode),
                Messages.getInstance().getString("JcrRepositoryFileDao.ERROR_0005_PARENT_MUST_BE_FOLDER")); //$NON-NLS-1$
    }
    if (!copy) {
        JcrRepositoryFileUtils.checkoutNearestVersionableFileIfNecessary(session, pentahoJcrConstants,
                srcParentFolderId);
    }
    JcrRepositoryFileUtils.checkoutNearestVersionableNodeIfNecessary(session, pentahoJcrConstants,
            destParentFolderNode);
    String finalEncodedSrcAbsPath = srcFileNode.getPath();
    String finalDestAbsPath = appendFileName && !file.isFolder()
            ? cleanDestAbsPath + RepositoryFile.SEPARATOR + srcFileNode.getName()
            : cleanDestAbsPath;
    try {
        if (copy) {
            session.getWorkspace().copy(finalEncodedSrcAbsPath, JcrStringHelper.pathEncode(finalDestAbsPath));
        } else {
            session.getWorkspace().move(finalEncodedSrcAbsPath, JcrStringHelper.pathEncode(finalDestAbsPath));
        }
    } catch (ItemExistsException iae) {
        throw new UnifiedRepositoryException((file.isFolder() ? "Folder " : "File ") + "with path ["
                + cleanDestAbsPath + "] already exists in the repository");
    }

    JcrRepositoryFileUtils.checkinNearestVersionableNodeIfNecessary(session, pentahoJcrConstants,
            destParentFolderNode, versionMessage);
    // if it's a move within the same folder, then the next checkin is unnecessary
    if (!copy && !destParentFolderNode.getIdentifier().equals(srcParentFolderId.toString())) {
        JcrRepositoryFileUtils.checkinNearestVersionableFileIfNecessary(session, pentahoJcrConstants,
                srcParentFolderId, versionMessage);
    }
    session.save();
}

From source file:org.alfresco.reporting.script.AlfrescoReporting.java

private String getPropertyValue(final NodeRef nodeRef, final QName qname, final String dtype,
        final boolean multiValued) {
    logger.debug("Enter getPropertyValue");
    String returnValue = "";
    Serializable s = serviceRegistry.getNodeService().getProperty(nodeRef, qname);
    // Tjarda: Check of s!=null wel valide is! Bij Tags en Categories
    if (multiValued && !"category".equals(dtype)) {
        ArrayList<Object> values = new ArrayList();

        values = (ArrayList) serviceRegistry.getNodeService().getProperty(nodeRef, qname);

        if ((values != null) && (!values.isEmpty()) && (values.size() > 0)) {

            if (dtype.equals("date") || dtype.equals("datetime")) {
                SimpleDateFormat dateformat = new SimpleDateFormat(Constants.DATE_FORMAT_DATABASE);
                Calendar c = Calendar.getInstance();

                for (int v = 0; v < values.size(); v++) {
                    returnValue += dateformat.format((Date) values.get(v)) + multivalue_seperator;
                }//from w  w w  .  j  a  va2  s. c  o  m
            }

            if (dtype.equals("id") || dtype.equals("long")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Long.toString((Long) values.get(v)) + multivalue_seperator;
                }
            }

            if (dtype.equals("int")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Integer.toString((Integer) values.get(v)) + multivalue_seperator;
                }
            }

            if (dtype.equals("float") || dtype.equals("double")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Double.toString((Double) values.get(v)) + multivalue_seperator;
                }
            }

            if (dtype.equals("boolean")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += Boolean.toString((Boolean) values.get(v)) + multivalue_seperator;
                }
            }

            if (dtype.equals("text")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += (String) values.get(v) + multivalue_seperator;
                }
            }

            if (dtype.equals("noderef")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += values.get(v).toString() + multivalue_seperator;
                }
            }

            if (returnValue.equals("")) {
                for (int v = 0; v < values.size(); v++) {
                    returnValue += (String) values.get(v) + multivalue_seperator;
                }
            }
        }
        // end multivalue
    } else {
        if ((s != null) && !"category".equals(dtype)) {

            if (dtype.equals("date") || dtype.equals("datetime")) {
                SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(((Date) s).getTime());
                returnValue = dateformat.format((Date) s);
                //returnValue = c.YEAR + "/"+ prefix(c.MONTH+1, 2, "0") + "/"+ prefix(c.DAY_OF_MONTH, 2, "0") + "T" + prefix(c.HOUR_OF_DAY, 2, "0")+":"+prefix(c.MINUTE, 2, "0")+":"+prefix(c.SECOND, 2, "0"); 
            }

            if (dtype.equals("id") || dtype.equals("long")) {
                returnValue = Long.toString((Long) s);
            }

            if (dtype.equals("int")) {
                returnValue = Integer.toString((Integer) s);
            }

            if (dtype.equals("float") || dtype.equals("double")) {
                returnValue = Double.toString((Double) s);
            }

            if (dtype.equals("boolean")) {
                returnValue = Boolean.toString((Boolean) s);
            }

            if (dtype.equals("text")) {
                returnValue = s.toString();
            }

            if (dtype.equals("noderef")) {
                returnValue = s.toString();
            }

            if (returnValue.equals("")) {
                returnValue = s.toString();
            }
        }
    } // end single valued
    /*
    if (qname.toString().endsWith("taggable")) {
       logger.error("I am a taggable!");
       List<String> tags = serviceRegistry.getTaggingService().getTags(nodeRef);
       logger.error("Found " + tags.size() + " tags!");
       for (String tag : tags){
    logger.error("processing tag: " + tag);
    if (returnValue.length()>0) returnValue+=",";
    returnValue+=tag;
       }
    } // end taggable
    */

    if (dtype.equals("category")) {
        logger.debug("I am a category!");
        List<NodeRef> categories = (List<NodeRef>) nodeService.getProperty(nodeRef, qname);
        if (categories != null) {

            for (NodeRef cat : categories) {
                String catName = nodeService.getProperty(cat, ContentModel.PROP_NAME).toString();

                if (returnValue.length() > 0)
                    returnValue += ",";
                returnValue += catName;
            } // end for
        } // end if categories != null
    } // end category

    logger.debug("Exit getPropertyValue, returning: " + returnValue);
    return returnValue;
}