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.rhq.plugins.jbossas5.ApplicationServerComponent.java

public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> requests) {
    ManagementView managementView = getConnection().getManagementView();
    for (MeasurementScheduleRequest request : requests) {
        String requestName = request.getName();
        String verifiedMetricName = VERIFIED_METRIC_NAMES.get(requestName);
        String metricName = (verifiedMetricName != null) ? verifiedMetricName : requestName;
        try {//from w ww.  java2  s .c  o m
            Serializable value = null;
            boolean foundProperty = false;
            try {
                value = getMetric(managementView, metricName);
                foundProperty = true;
            } catch (ManagedComponentUtils.PropertyNotFoundException e) {
                // ignore
            }

            if (value == null) {
                metricName = ALTERNATE_METRIC_NAMES.get(metricName);
                if (metricName != null) {
                    try {
                        value = getMetric(managementView, metricName);
                        foundProperty = true;
                    } catch (ManagedComponentUtils.PropertyNotFoundException e) {
                        // ignore
                    }
                }
            }

            if (!foundProperty) {
                List<String> propertyNames = new ArrayList<String>(2);
                propertyNames.add(requestName);
                if (ALTERNATE_METRIC_NAMES.containsKey(requestName)) {
                    propertyNames.add(ALTERNATE_METRIC_NAMES.get(requestName));
                }
                throw new IllegalStateException(
                        "A property was not found with any of the following names: " + propertyNames);
            }

            if (value != null) {
                VERIFIED_METRIC_NAMES.put(requestName, metricName);
            } else {
                log.debug("Null value returned for metric '" + metricName + "'.");
                continue;
            }

            if (request.getDataType() == DataType.MEASUREMENT) {
                Number number = (Number) value;
                report.addData(new MeasurementDataNumeric(request, number.doubleValue()));
            } else if (request.getDataType() == DataType.TRAIT) {
                report.addData(new MeasurementDataTrait(request, value.toString()));
            }
        } catch (RuntimeException e) {
            log.error("Failed to obtain metric '" + requestName + "'.", e);
        }
    }
}

From source file:org.egov.services.budget.BudgetDetailService.java

@Transactional
public Budget setBudgetState(final Budget budget) {
    State budgetState;/*from   w w w  . j  a  v  a2s .c o m*/
    Serializable sequenceNumber = null;
    Long stateId;
    try {
        sequenceNumber = databaseSequenceProvider.getNextSequence("seq_eg_wf_states");
        stateId = Long.valueOf(sequenceNumber.toString());
    } catch (final SQLGrammarException e) {
        throw new ValidationException(Arrays.asList(new ValidationError(e.getMessage(), e.getMessage())));
    }
    persistenceService.getSession().createSQLQuery(BUDGET_STATES_INSERT).setLong("stateId", stateId)
            .executeUpdate();
    budgetState = (State) persistenceService.find("from State where id = ?", stateId);
    budget.setWfState(budgetState);
    return budget;
}

From source file:com.bluexml.side.Integration.alfresco.xforms.webscript.XFormsWork.java

/**
 * Builds some information about the content of a node.
 * //w w  w  . j  av  a2 s .c  om
 * @param nodeId
 *            complete (store + workspace) id
 * @return an empty string if any problem or the comma-separated string
 *         containing the
 *         information built. Currently, {full node id},{content size in
 *         bytes}.
 */
private String contentInfo(String nodeId) {
    try {
        String result;
        NodeRef nodeRef = new NodeRef(nodeId);
        Serializable name = this.serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME);
        Serializable content = this.serviceRegistry.getNodeService().getProperty(nodeRef,
                ContentModel.PROP_CONTENT);
        if (content == null) {
            return "";
        }
        ContentData contentData = (ContentData) content;

        long size = contentData.getSize();

        result = name.toString() + "," + size;
        return result;

    } catch (Exception e) {
        logger.error("Failed to provide info for node id: " + nodeId + ". An error occurred.");
    }
    return "";
}

From source file:org.egov.services.budget.BudgetDetailService.java

@Transactional
public BudgetDetail setBudgetDetailStatus(final BudgetDetail budgetDetail) {
    Long stateId;/*from  w ww.j  a v  a 2  s . c  om*/
    Serializable sequenceNumber = null;
    try {
        sequenceNumber = databaseSequenceProvider.getNextSequence("seq_eg_wf_states");
    } catch (final SQLGrammarException e) {
    }
    stateId = Long.valueOf(sequenceNumber.toString());

    persistenceService.getSession().createSQLQuery(BUDGETDETAIL_STATES_INSERT).setLong("stateId", stateId)
            .executeUpdate();

    budgetDetail.setWfState((State) persistenceService.find("from State where id = ?", stateId));
    return budgetDetail;
}

From source file:org.egov.services.budget.BudgetDetailService.java

@Transactional
public BudgetGroup createBudgetGroup(CChartOfAccounts coa) {
    BudgetGroup budgetGroup = budgetGroupService.getBudgetGroup(coa.getId());
    try {//from w ww. ja  v a 2s. c o m
        Serializable sequenceNumber = null;
        try {
            sequenceNumber = databaseSequenceProvider.getNextSequence("seq_egf_budgetgroup");
        } catch (final SQLGrammarException e) {
        }

        Long.valueOf(sequenceNumber.toString());

        if (budgetGroup == null) {
            budgetGroup = new BudgetGroup();
            budgetGroup.setName(coa.getGlcode() + "-" + coa.getName());
            budgetGroup.setDescription(coa.getName());
            budgetGroup.setIsActive(true);
            if (coa.getType().compareTo('E') == 0) {
                budgetGroup.setAccountType(BudgetAccountType.REVENUE_EXPENDITURE);
                budgetGroup.setBudgetingType(BudgetingType.DEBIT);
            } else if (coa.getType().compareTo('A') == 0) {
                budgetGroup.setAccountType(BudgetAccountType.CAPITAL_EXPENDITURE);
                budgetGroup.setBudgetingType(BudgetingType.DEBIT);
            } else if (coa.getType().compareTo('L') == 0) {
                budgetGroup.setAccountType(BudgetAccountType.CAPITAL_RECEIPTS);
                budgetGroup.setBudgetingType(BudgetingType.CREDIT);
            } else if (coa.getType().compareTo('I') == 0) {
                budgetGroup.setAccountType(BudgetAccountType.REVENUE_RECEIPTS);
                budgetGroup.setBudgetingType(BudgetingType.CREDIT);
            }
            if (coa.getClassification().compareTo(1l) == 0 || coa.getClassification().compareTo(2l) == 0
                    || coa.getClassification().compareTo(4l) == 0) {
                budgetGroup.setMinCode(coa);
                budgetGroup.setMaxCode(coa);
            }
            budgetGroup.setMajorCode(null);
            budgetGroupService.applyAuditing(budgetGroup);
            budgetGroup = budgetGroupService.persist(budgetGroup);
            if (coa.getType().compareTo('E') == 0 || coa.getType().compareTo('A') == 0) {
                coa.setBudgetCheckReq(true);
                coa = chartOfAccountsService.update(coa);
            }
        }

    } catch (final ValidationException e) {
        throw new ValidationException(Arrays.asList(
                new ValidationError(e.getErrors().get(0).getMessage(), e.getErrors().get(0).getMessage())));
    } catch (final Exception e) {
        throw new ValidationException(Arrays.asList(new ValidationError(e.getMessage(), e.getMessage())));
    }
    return budgetGroup;
}

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

private void internalCopyOrMove(final Serializable fileId, final String destRelPath,
        final String versionMessage, final boolean copy) {
    if (isKioskEnabled()) {
        throw new RuntimeException(
                Messages.getInstance().getString("JcrRepositoryFileDao.ERROR_0006_ACCESS_DENIED")); //$NON-NLS-1$
    }//from  w  w  w  . ja  v  a2s.c o m

    Assert.notNull(fileId);
    jcrTemplate.execute(new JcrCallback() {
        @Override
        public Object doInJcr(final Session session) throws RepositoryException, IOException {
            RepositoryFile file = getFileById(fileId);
            RepositoryFileAcl acl = aclDao.getAcl(fileId);
            if (!accessVoterManager.hasAccess(file, RepositoryFilePermission.WRITE, acl,
                    PentahoSessionHolder.getSession())) {
                return null;
            }

            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(fileId.toString());
            Serializable srcParentFolderId = JcrRepositoryFileUtils.getParentId(session, fileId);
            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();
            return null;
        }
    });
}

From source file:org.alfresco.repo.version.VersionServiceImplTest.java

/**
 * Check that the version type property is actually set when creating a new version.
 * //from   w  w w . j av a 2 s. com
 * @see https://issues.alfresco.com/jira/browse/MNT-14681
 */
public void testVersionTypeIsSet() {
    ChildAssociationRef childAssociation = nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CHILDREN,
            QName.createQName("http://www.alfresco.org/test/versiontypeissettest/1.0", "versionTypeIsSetTest"),
            TEST_TYPE_QNAME);

    NodeRef newNode = childAssociation.getChildRef();
    assertNull(nodeService.getProperty(newNode, ContentModel.PROP_VERSION_TYPE));

    Map<String, Serializable> versionProps = new HashMap<String, Serializable>(1);
    versionProps.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);

    versionService.createVersion(newNode, versionProps);

    Serializable versionTypeProperty = nodeService.getProperty(newNode, ContentModel.PROP_VERSION_TYPE);
    assertNotNull(versionTypeProperty);
    assertTrue(versionTypeProperty.toString().equals(VersionType.MINOR.toString()));
}

From source file:org.alfresco.rest.api.impl.NodesImpl.java

protected PathInfo lookupPathInfo(NodeRef nodeRefIn, ChildAssociationRef archivedParentAssoc) {

    List<ElementInfo> pathElements = new ArrayList<>();
    Boolean isComplete = Boolean.TRUE;
    final Path nodePath;
    final int pathIndex;

    if (archivedParentAssoc != null) {
        if (permissionService.hasPermission(archivedParentAssoc.getParentRef(), PermissionService.READ)
                .equals(AccessStatus.ALLOWED) && nodeService.exists(archivedParentAssoc.getParentRef())) {
            nodePath = nodeService.getPath(archivedParentAssoc.getParentRef());
            pathIndex = 1;// 1 => we want to include the given node in the path as well.
        } else {/*from   www  .  j  a va  2s .co m*/
            //We can't return a valid path
            return null;
        }
    } else {
        nodePath = nodeService.getPath(nodeRefIn);
        pathIndex = 2; // 2 => as we don't want to include the given node in the path as well.
    }

    for (int i = nodePath.size() - pathIndex; i >= 0; i--) {
        Element element = nodePath.get(i);
        if (element instanceof Path.ChildAssocElement) {
            ChildAssociationRef elementRef = ((Path.ChildAssocElement) element).getRef();
            if (elementRef.getParentRef() != null) {
                NodeRef childNodeRef = elementRef.getChildRef();
                if (permissionService.hasPermission(childNodeRef,
                        PermissionService.READ) == AccessStatus.ALLOWED) {
                    Serializable nameProp = nodeService.getProperty(childNodeRef, ContentModel.PROP_NAME);
                    pathElements.add(0, new ElementInfo(childNodeRef.getId(), nameProp.toString()));
                } else {
                    // Just return the pathInfo up to the location where the user has access
                    isComplete = Boolean.FALSE;
                    break;
                }
            }
        }
    }

    String pathStr = null;
    if (pathElements.size() > 0) {
        StringBuilder sb = new StringBuilder(120);
        for (PathInfo.ElementInfo e : pathElements) {
            sb.append("/").append(e.getName());
        }
        pathStr = sb.toString();
    } else {
        // There is no path element, so set it to null in order to be
        // ignored by Jackson during serialisation
        isComplete = null;
    }
    return new PathInfo(pathStr, isComplete, pathElements);
}

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

public RepositoryFile internalCreateFile(Session session, final Serializable parentFolderId,
        final RepositoryFile file, final IRepositoryFileData content, final RepositoryFileAcl acl,
        final String versionMessage) throws RepositoryException {
    if (!hasAccess(session, parentFolderId, RepositoryFilePermission.WRITE)) {
        return null;
    }/*w  w  w  . j  a va 2s  .  c  o m*/
    // Assert.notNull(content);
    DataNode emptyDataNode = new DataNode(file.getName());
    emptyDataNode.setProperty(" ", "content"); //$NON-NLS-1$ //$NON-NLS-2$
    final IRepositoryFileData emptyContent = new NodeRepositoryFileData(emptyDataNode);

    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:com.amalto.core.storage.hibernate.HibernateStorage.java

@Override
public void delete(DataRecord record) {
    Session session = this.getCurrentSession();
    try {/*  w  w w.j  a v  a  2 s  . c  o  m*/
        storageClassLoader.bind(Thread.currentThread());
        // Session session = factory.getCurrentSession();
        ComplexTypeMetadata currentType = record.getType();
        TypeMapping mapping = mappingRepository.getMappingFromUser(currentType);
        if (mapping == null) {
            throw new IllegalArgumentException(
                    "Type '" + currentType.getName() + "' does not have a database mapping."); //$NON-NLS-1$ //$NON-NLS-2$
        }
        Class<?> clazz = storageClassLoader.getClassFromType(mapping.getDatabase());

        Serializable idValue;
        Collection<FieldMetadata> keyFields = currentType.getKeyFields();
        if (keyFields.size() == 1) {
            idValue = (Serializable) record.get(keyFields.iterator().next());
        } else {
            List<Object> compositeIdValues = new LinkedList<Object>();
            for (FieldMetadata keyField : keyFields) {
                compositeIdValues.add(record.get(keyField));
            }
            idValue = ObjectDataRecordConverter.createCompositeId(storageClassLoader, clazz, compositeIdValues);
        }

        Wrapper object = (Wrapper) session.get(clazz, idValue, LockOptions.READ);
        if (object != null) {
            session.delete(object);
        } else {
            LOGGER.warn("Instance of type '" + currentType.getName() + "' and ID '" + idValue.toString() //$NON-NLS-1$ //$NON-NLS-2$
                    + "' has already been deleted within same transaction."); //$NON-NLS-1$
        }
    } catch (ConstraintViolationException e) {
        throw new com.amalto.core.storage.exception.ConstraintViolationException(e);
    } catch (HibernateException e) {
        throw new RuntimeException(e);
    } finally {
        this.releaseSession();
        storageClassLoader.unbind(Thread.currentThread());
    }
}