Example usage for java.io Serializable getClass

List of usage examples for java.io Serializable getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.haulmont.cuba.core.app.ClusterManager.java

protected void internalSend(Serializable message, boolean sync) {
    StopWatch sw = new Slf4JStopWatch(
            String.format("sendClusterMessage(%s)", message.getClass().getSimpleName()));
    try {/*from w ww. ja v  a 2 s. c o  m*/
        byte[] bytes = SerializationSupport.serialize(message);
        log.debug("Sending message: {}: {} ({} bytes)", message.getClass(), message, bytes.length);
        MessageStat stat = messagesStat.get(message.getClass().getName());
        if (stat != null) {
            stat.updateSent(bytes.length);
        }
        Message msg = new Message(null, null, bytes);
        if (sync) {
            msg.setFlag(Message.Flag.RSVP);
        }
        try {
            channel.send(msg);
        } catch (Exception e) {
            log.error("Error sending message", e);
        }
    } finally {
        sw.stop();
    }
}

From source file:org.ambraproject.testutils.DummyHibernateDataStore.java

@Override
public String store(Object object) {
    try {//from   ww  w. jav  a2s .co m
        return hibernateTemplate.save(object).toString();
    } catch (Exception e) {
        //for constraint violation exceptions, just check if the object already exists in the db,
        // so we can reuse data providers and call store() multiple times
        Serializable storedId = getStoredId(object);
        if (storedId != null) {
            String idPropertyName = allClassMetadata.get(object.getClass().getName())
                    .getIdentifierPropertyName();
            String idSetterName = "set" + idPropertyName.substring(0, 1).toUpperCase()
                    + idPropertyName.substring(1);
            //set the id on the object
            try {
                object.getClass().getMethod(idSetterName, storedId.getClass()).invoke(object, storedId);
            } catch (Exception e1) {
                //do nothing
            }
            return storedId.toString();
        } else {
            return null;
        }
    }
}

From source file:org.alfresco.repo.transfer.RepoRequisiteManifestProcessorImpl.java

protected void processNode(TransferManifestNormalNode node) {

    if (log.isDebugEnabled()) {
        log.debug("Processing node with incoming noderef of " + node.getNodeRef());
    }//from   w w w .  j a  va 2s .c om
    logComment("Requisite Processing incoming node: " + node.getNodeRef() + " --  Source path = "
            + node.getParentPath() + "/" + node.getPrimaryParentAssoc().getQName());

    ChildAssociationRef primaryParentAssoc = node.getPrimaryParentAssoc();

    CorrespondingNodeResolver.ResolvedParentChildPair resolvedNodes = nodeResolver
            .resolveCorrespondingNode(node.getNodeRef(), primaryParentAssoc, node.getParentPath());

    // Does a corresponding node exist in this repo?
    if (resolvedNodes.resolvedChild != null) {
        /**
         * there is a corresponding node so we need to check whether we already 
         * have the part for each content item
         */
        NodeRef destinationNode = resolvedNodes.resolvedChild;

        Map<QName, Serializable> destinationProps = nodeService.getProperties(destinationNode);
        /**
         * For each property on the source node
         */
        for (Map.Entry<QName, Serializable> propEntry : node.getProperties().entrySet()) {
            Serializable value = propEntry.getValue();
            QName propName = propEntry.getKey();

            if (log.isDebugEnabled()) {
                if (value == null) {
                    log.debug("Received a null value for property " + propName);
                }
            }
            if ((value != null) && ContentData.class.isAssignableFrom(value.getClass())) {
                /**
                 * Got a content property from source node.
                 */
                ContentData srcContent = (ContentData) value;

                if (srcContent.getContentUrl() != null && !srcContent.getContentUrl().isEmpty()) {
                    /**
                     * Source Content is not empty
                     */
                    String partName = TransferCommons.URLToPartName(srcContent.getContentUrl());

                    Serializable destSer = destinationProps.get(propName);
                    if (destSer != null && ContentData.class.isAssignableFrom(destSer.getClass())) {
                        /**
                         * Content property not empty and content property already exists on destination
                         */
                        ContentData destContent = (ContentData) destSer;

                        Serializable destFromContents = destinationProps.get(TransferModel.PROP_FROM_CONTENT);

                        if (destFromContents != null
                                && Collection.class.isAssignableFrom(destFromContents.getClass())) {
                            Collection<String> contents = (Collection<String>) destFromContents;
                            /**
                             * Content property not empty and content property already exists on destination
                             */
                            if (contents.contains(partName)) {
                                if (log.isDebugEnabled()) {
                                    log.debug("part already transferred, no need to send it again, partName:"
                                            + partName + ", nodeRef:" + node.getNodeRef());
                                }
                            } else {
                                if (log.isDebugEnabled()) {
                                    log.debug("part name not transferred, requesting new content item partName:"
                                            + partName + ", nodeRef:" + node.getNodeRef());
                                }
                                out.missingContent(node.getNodeRef(), propEntry.getKey(),
                                        TransferCommons.URLToPartName(srcContent.getContentUrl()));
                            }
                        } else {
                            // dest from contents is null
                            if (log.isDebugEnabled()) {
                                log.debug("from contents is null, requesting new content item partName:"
                                        + partName + ", nodeRef:" + node.getNodeRef());
                            }
                            out.missingContent(node.getNodeRef(), propEntry.getKey(),
                                    TransferCommons.URLToPartName(srcContent.getContentUrl()));
                        }
                    } else {
                        /**
                         * Content property not empty and does not exist on destination
                         */
                        if (log.isDebugEnabled()) {
                            log.debug("no content on destination, all content is required" + propEntry.getKey()
                                    + srcContent.getContentUrl());
                        }
                        //  We don't have the property on the destination node 
                        out.missingContent(node.getNodeRef(), propEntry.getKey(),
                                TransferCommons.URLToPartName(srcContent.getContentUrl()));
                    }
                }
            } // src content url not null
        } // value is content data
    } else {
        log.debug("Node does not exist on destination nodeRef:" + node.getNodeRef());

        /**
         * there is no corresponding node so all content properties are "missing."
         */
        for (Map.Entry<QName, Serializable> propEntry : node.getProperties().entrySet()) {
            Serializable value = propEntry.getValue();
            if (log.isDebugEnabled()) {
                if (value == null) {
                    log.debug("Received a null value for property " + propEntry.getKey());
                }
            }
            if ((value != null) && ContentData.class.isAssignableFrom(value.getClass())) {
                ContentData srcContent = (ContentData) value;
                if (srcContent.getContentUrl() != null && !srcContent.getContentUrl().isEmpty()) {
                    if (log.isDebugEnabled()) {
                        log.debug("no node on destination, content is required" + propEntry.getKey()
                                + srcContent.getContentUrl());
                    }
                    out.missingContent(node.getNodeRef(), propEntry.getKey(),
                            TransferCommons.URLToPartName(srcContent.getContentUrl()));
                }
            }
        }
    }
}

From source file:net.sf.jasperreports.components.table.fill.FillTable.java

protected JRReportCompileData createTableReportCompileData(JasperReport parentReport,
        JRDataset reportSubdataset) throws JRException {
    Serializable reportCompileDataObj = parentReport.getCompileData();
    if (!(reportCompileDataObj instanceof JRReportCompileData)) {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_UNSUPPORTED_REPORT_DATA_TYPE,
                new Object[] { reportCompileDataObj.getClass().getName() });
    }// w  w w. j ava  2s. c o m

    JRReportCompileData reportCompileData = (JRReportCompileData) reportCompileDataObj;
    Serializable datasetCompileData = reportCompileData.getDatasetCompileData(reportSubdataset);

    TableReportCompileData tableReportCompileData = new TableReportCompileData(parentReport);
    tableReportCompileData.setMainDatasetCompileData(datasetCompileData);

    JRDataset[] datasets = parentReport.getDatasets();
    if (datasets != null) {
        for (JRDataset dataset : datasets) {
            Serializable compileData = reportCompileData.getDatasetCompileData(dataset);
            tableReportCompileData.setDatasetCompileData(dataset, compileData);
        }
    }
    tableReportCompileData.copyCrosstabCompileData(reportCompileData);
    return tableReportCompileData;
}

From source file:org.spout.api.datatable.SerializableData.java

@Override
public byte[] compress() {
    Serializable value = super.get();
    if (value instanceof ByteArrayWrapper) {
        return ((ByteArrayWrapper) value).getArray();
    }//from w  w w .j av  a 2 s . c o m

    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();

    try {
        ObjectOutputStream objOut = new ObjectOutputStream(byteOut);

        objOut.writeObject(super.get());
        objOut.flush();
        objOut.close();
    } catch (IOException e) {
        if (Spout.debugMode()) {
            Spout.getLogger().log(Level.SEVERE, "Unable to serialize " + value + " (type: "
                    + (value != null ? value.getClass().getSimpleName() : "null") + ")", e);
        }
        return null;
    }

    return byteOut.toByteArray();
}

From source file:org.apache.axis2.clustering.tribes.RpcMessagingHandler.java

public Serializable replyRequest(Serializable msg, Member invoker) {
    if (log.isDebugEnabled()) {
        log.debug("RPC request received by RpcMessagingHandler");
    }//from w  w w .  j a  v  a2s .co  m
    if (msg instanceof ClusteringMessage) {
        ClusteringMessage clusteringMsg = (ClusteringMessage) msg;
        try {
            clusteringMsg.execute(configurationContext);
        } catch (ClusteringFault e) {
            String errMsg = "Cannot handle RPC message";
            log.error(errMsg, e);
            throw new RemoteProcessException(errMsg, e);
        }
        return clusteringMsg.getResponse();
    } else {
        throw new IllegalArgumentException("Invalid RPC message of type " + msg.getClass() + " received");
    }
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.MediaFieldPersistenceProvider.java

@Override
public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance)
        throws PersistenceException {
    if (!canHandlePersistence(populateValueRequest, instance)) {
        return FieldProviderResponse.NOT_HANDLED;
    }/*  ww w.  j a v  a 2s .c  om*/
    String prop = populateValueRequest.getProperty().getName();
    if (prop.contains(FieldManager.MAPFIELDSEPARATOR)) {
        Field field = populateValueRequest.getFieldManager().getField(instance.getClass(),
                prop.substring(0, prop.indexOf(FieldManager.MAPFIELDSEPARATOR)));
        if (field.getAnnotation(OneToMany.class) == null) {
            throw new UnsupportedOperationException(
                    "MediaFieldPersistenceProvider is currently only compatible with map fields when modelled using @OneToMany");
        }
    }
    FieldProviderResponse response = FieldProviderResponse.HANDLED;
    boolean dirty;
    try {
        setNonDisplayableValues(populateValueRequest);
        Class<?> valueType = getStartingValueType(populateValueRequest);

        if (Media.class.isAssignableFrom(valueType)) {
            Media newMedia = mediaBuilderService
                    .convertJsonToMedia(populateValueRequest.getProperty().getUnHtmlEncodedValue(), valueType);
            boolean persist = false;
            Media media;
            try {
                media = (Media) populateValueRequest.getFieldManager().getFieldValue(instance,
                        populateValueRequest.getProperty().getName());
                if (media == null) {
                    media = (Media) valueType.newInstance();

                    Object parent = extractParent(populateValueRequest, instance);

                    populateValueRequest.getFieldManager().setFieldValue(media,
                            populateValueRequest.getMetadata().getToOneParentProperty(), parent);
                    populateValueRequest.getFieldManager().setFieldValue(media,
                            populateValueRequest.getMetadata().getMapKeyValueProperty(),
                            prop.substring(prop.indexOf(FieldManager.MAPFIELDSEPARATOR)
                                    + FieldManager.MAPFIELDSEPARATOR.length(), prop.length()));
                    persist = true;
                }
            } catch (FieldNotAvailableException e) {
                throw new IllegalArgumentException(e);
            }
            populateValueRequest.getProperty().setOriginalValue(convertMediaToJson(media));
            dirty = establishDirtyState(newMedia, media);
            if (dirty) {
                updateMedia(populateValueRequest, newMedia, persist, media);
                response = FieldProviderResponse.HANDLED_BREAK;
            }
        } else {
            throw new UnsupportedOperationException("MediaFields only work with Media types.");
        }
    } catch (Exception e) {
        throw ExceptionHelper.refineException(PersistenceException.class, PersistenceException.class, e);
    }
    populateValueRequest.getProperty().setIsDirty(dirty);

    return response;
}

From source file:org.sparkcommerce.openadmin.server.service.persistence.validation.EntityValidatorServiceImpl.java

@Override
public void validate(Entity submittedEntity, @Nullable Serializable instance,
        Map<String, FieldMetadata> propertiesMetadata, RecordHelper recordHelper,
        boolean validateUnsubmittedProperties) {
    Object idValue = null;//from  w  ww  .j  a  v  a 2s .com
    if (instance != null) {
        String idField = (String) ((BasicPersistenceModule) recordHelper
                .getCompatibleModule(OperationType.BASIC)).getPersistenceManager().getDynamicEntityDao()
                        .getIdMetadata(instance.getClass()).get("name");
        try {
            idValue = recordHelper.getFieldManager().getFieldValue(instance, idField);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (FieldNotAvailableException e) {
            throw new RuntimeException(e);
        }
    }
    Entity entity;
    boolean isUpdateRequest;
    if (idValue == null) {
        //This is for an add, or if the instance variable is null (e.g. PageTemplateCustomPersistenceHandler)
        entity = submittedEntity;
        isUpdateRequest = false;
    } else {
        //This is for an update, as the submittedEntity instance will likely only contain the dirty properties
        entity = recordHelper.getRecord(propertiesMetadata, instance, null, null);
        //acquire any missing properties not harvested from the instance and add to the entity. A use case for this
        //would be the confirmation field for a password validation
        for (Map.Entry<String, FieldMetadata> entry : propertiesMetadata.entrySet()) {
            if (entity.findProperty(entry.getKey()) == null) {
                Property myProperty = submittedEntity.findProperty(entry.getKey());
                if (myProperty != null) {
                    entity.addProperty(myProperty);
                }
            } else if (submittedEntity.findProperty(entry.getKey()) != null) {
                // Set the dirty state of the property
                entity.findProperty(entry.getKey())
                        .setIsDirty(submittedEntity.findProperty(entry.getKey()).getIsDirty());
            }
        }
        isUpdateRequest = true;
    }

    List<String> types = getTypeHierarchy(entity);
    //validate each individual property according to their validation configuration
    for (Entry<String, FieldMetadata> metadataEntry : propertiesMetadata.entrySet()) {
        FieldMetadata metadata = metadataEntry.getValue();

        //Don't test this field if it was not inherited from our polymorphic type (or supertype)
        if (types.contains(metadata.getInheritedFromType()) || (instance != null
                && instance.getClass().getName().equals(metadata.getInheritedFromType()))) {

            Property property = entity.getPMap().get(metadataEntry.getKey());

            // This property should be set to false only in the case where we are adding a member to a collection
            // that has type of lookup. In this case, we don't have the properties from the target in our entity,
            // and we don't need to validate them.
            if (!validateUnsubmittedProperties && property == null) {
                continue;
            }

            //for radio buttons, it's possible that the entity property was never populated in the first place from the POST
            //and so it will be null
            String propertyName = metadataEntry.getKey();
            String propertyValue = (property == null) ? null : property.getValue();

            if (metadata instanceof BasicFieldMetadata) {
                //First execute the global field validators
                if (CollectionUtils.isNotEmpty(globalEntityValidators)) {
                    for (GlobalPropertyValidator validator : globalEntityValidators) {
                        PropertyValidationResult result = validator.validate(entity, instance,
                                propertiesMetadata, (BasicFieldMetadata) metadata, propertyName, propertyValue);
                        if (!result.isValid()) {
                            submittedEntity.addValidationError(propertyName, result.getErrorMessage());
                        }
                    }
                }

                //Now execute the validators configured for this particular field
                Map<String, Map<String, String>> validations = ((BasicFieldMetadata) metadata)
                        .getValidationConfigurations();
                for (Map.Entry<String, Map<String, String>> validation : validations.entrySet()) {
                    String validationImplementation = validation.getKey();
                    Map<String, String> configuration = validation.getValue();

                    PropertyValidator validator = null;

                    //attempt bean resolution to find the validator
                    if (applicationContext.containsBean(validationImplementation)) {
                        validator = applicationContext.getBean(validationImplementation,
                                PropertyValidator.class);
                    }

                    //not a bean, attempt to instantiate the class
                    if (validator == null) {
                        try {
                            validator = (PropertyValidator) Class.forName(validationImplementation)
                                    .newInstance();
                        } catch (Exception e) {
                            //do nothing
                        }
                    }

                    if (validator == null) {
                        throw new PersistenceException("Could not find validator: " + validationImplementation
                                + " for property: " + propertyName);
                    }

                    PropertyValidationResult result = validator.validate(entity, instance, propertiesMetadata,
                            configuration, (BasicFieldMetadata) metadata, propertyName, propertyValue);
                    if (!result.isValid()) {
                        for (String message : result.getErrorMessages()) {
                            submittedEntity.addValidationError(propertyName, message);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.CswRecordConverterTest.java

private void assertDateConversion(Serializable ser, Calendar expectedDate) {
    assertThat(ser, notNullValue());//from w  w w  .  jav a 2 s.  com
    assertThat(Date.class.isAssignableFrom(ser.getClass()), is(true));
    Date date = (Date) ser;
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    assertThat(cal.get(Calendar.MONTH), is(expectedDate.get(Calendar.MONTH)));
    assertThat(cal.get(Calendar.YEAR), is(expectedDate.get(Calendar.YEAR)));
    assertThat(cal.get(Calendar.DAY_OF_MONTH), is(expectedDate.get(Calendar.DAY_OF_MONTH)));
}

From source file:org.bremersee.common.jms.DefaultJmsConverter.java

private Message createSerializedMessage(Serializable object, Session session) throws JMSException {
    try {/*from w  w  w. j  a v  a 2 s.  c  o  m*/
        BytesMessage msg = session.createBytesMessage();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        msg.writeBytes(outputStream.toByteArray());
        msg.setJMSType(object.getClass().getName());
        return msg;

    } catch (Throwable t) { // NOSONAR
        log.info("Creating Serialized JMS from object of type ["
                + (object == null ? "null" : object.getClass().getName()) + "] failed.");
        return null;
    }
}