Search in sources :

Example 51 with Transformer

use of org.mule.runtime.core.api.transformer.Transformer in project mule by mulesoft.

the class DefaultTransformationService method getPayload.

/**
 * Attempts to obtain the payload of this message with the desired Class type. This will try and resolve a transformer that can
 * do this transformation. If a transformer cannot be found an exception is thrown. Any transformers added to the registry will
 * be checked for compatibility.
 *
 * @param resultType the desired return type
 * @param encoding the encoding to use if required
 * @return The converted payload of this message. Note that this method will not alter the payload of this message <b>unless</b>
 *         the payload is an {@link InputStream} in which case the stream will be read and the payload will become the fully
 *         read stream.
 * @throws MessageTransformerException if a transformer cannot be found or there is an error during transformation of the payload.
 */
@SuppressWarnings("unchecked")
protected <T> T getPayload(Message message, DataType resultType, Charset encoding) throws MessageTransformerException {
    // Handle null by ignoring the request
    if (resultType == null) {
        throw new IllegalArgumentException(objectIsNull("resultType").getMessage());
    }
    DataType dataType = DataType.builder(resultType).type(message.getPayload().getDataType().getType()).build();
    // If no conversion is necessary, just return the payload as-is
    if (resultType.isCompatibleWith(dataType)) {
        return (T) message.getPayload().getValue();
    }
    // The transformer to execute on this message
    Transformer transformer = null;
    try {
        transformer = ((MuleContextWithRegistries) muleContext).getRegistry().lookupTransformer(dataType, resultType);
        if (transformer == null) {
            throw new MessageTransformerException(noTransformerFoundForMessage(dataType, resultType), null, message);
        }
        // Pass in the message itself
        Object result = transformer.transform(message, encoding);
        // Unless we disallow Object.class as a valid return type we need to do this extra check
        checkResultDataType(message, resultType, result);
        return (T) result;
    } catch (MessageTransformerException e) {
        throw e;
    } catch (TransformerException e) {
        throw new MessageTransformerException(transformer, e, message);
    }
}
Also used : Transformer(org.mule.runtime.core.api.transformer.Transformer) MuleContextWithRegistries(org.mule.runtime.core.internal.context.MuleContextWithRegistries) DataType(org.mule.runtime.api.metadata.DataType) MessageTransformerException(org.mule.runtime.core.api.transformer.MessageTransformerException) MessageTransformerException(org.mule.runtime.core.api.transformer.MessageTransformerException) TransformerException(org.mule.runtime.core.api.transformer.TransformerException)

Example 52 with Transformer

use of org.mule.runtime.core.api.transformer.Transformer in project mule by mulesoft.

the class SimpleRegistryBootstrap method doRegisterTransformer.

@Override
protected void doRegisterTransformer(TransformerBootstrapProperty bootstrapProperty, Class<?> returnClass, Class<? extends Transformer> transformerClass) throws Exception {
    Transformer trans = ClassUtils.instantiateClass(transformerClass);
    if (!(trans instanceof DiscoverableTransformer)) {
        throw new RegistrationException(CoreMessages.transformerNotImplementDiscoverable(trans));
    }
    if (returnClass != null) {
        DataTypeParamsBuilder builder = DataType.builder().type(returnClass);
        if (isNotEmpty(bootstrapProperty.getMimeType())) {
            builder = builder.mediaType(bootstrapProperty.getMimeType());
        }
        trans.setReturnDataType(builder.build());
    }
    if (bootstrapProperty.getName() != null) {
        trans.setName(bootstrapProperty.getName());
    } else {
        // Prefixes the generated default name to ensure there is less chance of conflict if the user registers
        // the transformer with the same name
        trans.setName("_" + trans.getName());
    }
    ((MuleContextWithRegistries) muleContext).getRegistry().registerTransformer(trans);
}
Also used : RegistrationException(org.mule.runtime.core.privileged.registry.RegistrationException) DataTypeParamsBuilder(org.mule.runtime.api.metadata.DataTypeParamsBuilder) Transformer(org.mule.runtime.core.api.transformer.Transformer) DiscoverableTransformer(org.mule.runtime.core.api.transformer.DiscoverableTransformer) DiscoverableTransformer(org.mule.runtime.core.api.transformer.DiscoverableTransformer)

Example 53 with Transformer

use of org.mule.runtime.core.api.transformer.Transformer in project mule by mulesoft.

the class MuleRegistryHelper method resolveTransformer.

protected Transformer resolveTransformer(DataType source, DataType result) throws TransformerException {
    Lock readLock = transformerResolversLock.readLock();
    readLock.lock();
    try {
        for (TransformerResolver resolver : transformerResolvers) {
            try {
                Transformer trans = resolver.resolve(source, result);
                if (trans != null) {
                    return trans;
                }
            } catch (ResolverException e) {
                throw new TransformerException(CoreMessages.noTransformerFoundForMessage(source, result), e);
            }
        }
    } finally {
        readLock.unlock();
    }
    return null;
}
Also used : Transformer(org.mule.runtime.core.api.transformer.Transformer) ResolverException(org.mule.runtime.core.internal.transformer.ResolverException) TransformerException(org.mule.runtime.core.api.transformer.TransformerException) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Lock(java.util.concurrent.locks.Lock)

Example 54 with Transformer

use of org.mule.runtime.core.api.transformer.Transformer in project mule by mulesoft.

the class MuleRegistryHelper method lookupTransformer.

/**
 * {@inheritDoc}
 */
@Override
public Transformer lookupTransformer(DataType source, DataType result) throws TransformerException {
    // To maintain the previous behaviour, we don't want to consider the result mimeType when resolving a transformer
    // and only find transformers with a targetType the same as or a super class of the expected one.
    // The same could be done for the source but since if the source expected by the transformer is more generic that
    // the provided, it will be found.
    result = builder(result).mediaType(ANY).charset((Charset) null).build();
    final String dataTypePairHash = getDataTypeSourceResultPairHash(source, result);
    Transformer cachedTransformer = (Transformer) exactTransformerCache.get(dataTypePairHash);
    if (cachedTransformer != null) {
        return cachedTransformer;
    }
    Transformer trans = resolveTransformer(source, result);
    if (trans != null) {
        Transformer concurrentlyAddedTransformer = (Transformer) exactTransformerCache.putIfAbsent(dataTypePairHash, trans);
        if (concurrentlyAddedTransformer != null) {
            return concurrentlyAddedTransformer;
        } else {
            return trans;
        }
    } else {
        throw new TransformerException(CoreMessages.noTransformerFoundForMessage(source, result));
    }
}
Also used : Transformer(org.mule.runtime.core.api.transformer.Transformer) TransformerException(org.mule.runtime.core.api.transformer.TransformerException)

Example 55 with Transformer

use of org.mule.runtime.core.api.transformer.Transformer in project mule by mulesoft.

the class MuleRegistryHelper method lookupTransformers.

/**
 * {@inheritDoc}
 */
@Override
public List<Transformer> lookupTransformers(DataType source, DataType result) {
    // To maintain the previous behaviour, we don't want to consider the result mimeType when resolving a transformer
    // and only find transformers with a targetType the same as or a super class of the expected one.
    // The same could be done for the source but since if the source expected by the transformer is more generic that
    // the provided, it will be found.
    result = builder(result).mediaType(ANY).charset((Charset) null).build();
    final String dataTypePairHash = getDataTypeSourceResultPairHash(source, result);
    List<Transformer> results = (List<Transformer>) transformerListCache.get(dataTypePairHash);
    if (results != null) {
        return results;
    }
    results = new ArrayList<>(2);
    Lock readLock = transformersLock.readLock();
    readLock.lock();
    try {
        for (Transformer transformer : transformers) {
            // going to find it here
            if (!(transformer instanceof Converter)) {
                continue;
            }
            if (result.isCompatibleWith(transformer.getReturnDataType()) && transformer.isSourceDataTypeSupported(source)) {
                results.add(transformer);
            }
        }
    } finally {
        readLock.unlock();
    }
    List<Transformer> concurrentlyAddedTransformers = (List<Transformer>) transformerListCache.putIfAbsent(dataTypePairHash, results);
    if (concurrentlyAddedTransformers != null) {
        return concurrentlyAddedTransformers;
    } else {
        return results;
    }
}
Also used : Transformer(org.mule.runtime.core.api.transformer.Transformer) Converter(org.mule.runtime.core.api.transformer.Converter) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Lock(java.util.concurrent.locks.Lock)

Aggregations

Transformer (org.mule.runtime.core.api.transformer.Transformer)87 Test (org.junit.Test)65 SmallTest (org.mule.tck.size.SmallTest)54 MockConverterBuilder (org.mule.runtime.core.internal.transformer.builder.MockConverterBuilder)37 Message (org.mule.runtime.api.message.Message)35 MockTransformerBuilder (org.mule.runtime.core.internal.transformer.builder.MockTransformerBuilder)19 DataType (org.mule.runtime.api.metadata.DataType)14 Converter (org.mule.runtime.core.api.transformer.Converter)12 ArrayList (java.util.ArrayList)10 TransformerException (org.mule.runtime.core.api.transformer.TransformerException)10 AbstractTransformer (org.mule.runtime.core.api.transformer.AbstractTransformer)9 CompositeConverter (org.mule.runtime.core.privileged.transformer.CompositeConverter)9 Serializable (java.io.Serializable)6 MuleContextWithRegistries (org.mule.runtime.core.internal.context.MuleContextWithRegistries)6 TransformerWeighting (org.mule.runtime.core.internal.registry.TransformerWeighting)6 CoreEvent (org.mule.runtime.core.api.event.CoreEvent)4 MessageTransformerException (org.mule.runtime.core.api.transformer.MessageTransformerException)4 IOException (java.io.IOException)3 LinkedList (java.util.LinkedList)3 List (java.util.List)3