Java 类org.apache.camel.Converter 实例源码

项目:Camel    文件:GenericFileConverter.java   
@Converter
public static InputStream genericFileToInputStream(GenericFile<?> file, Exchange exchange) throws IOException, NoTypeConversionAvailableException {
    if (file.getFile() instanceof File) {
        // prefer to use a file input stream if its a java.io.File
        File f = (File) file.getFile();
        // the file must exists
        if (f.exists()) {
            // read the file using the specified charset
            String charset = file.getCharset();
            if (charset != null) {
                LOG.debug("Read file {} with charset {}", f, file.getCharset());
            } else {
                LOG.debug("Read file {} (no charset)", f);
            }
            return IOConverter.toInputStream(f, charset);
        }
    }
    if (exchange != null) {
        // otherwise ensure the body is loaded as we want the input stream of the body
        file.getBinding().loadContent(exchange, file);
        return exchange.getContext().getTypeConverter().convertTo(InputStream.class, exchange, file.getBody());
    } else {
        // should revert to fallback converter if we don't have an exchange
        return null;
    }
}
项目:Camel    文件:ObjectConverter.java   
/**
 * Returns the converted value, or null if the value is null
 */
@Converter
public static Class<?> toClass(Object value, Exchange exchange) {
    if (value instanceof Class) {
        return (Class<?>) value;
    } else if (value instanceof String) {
        // prefer to use class resolver API
        if (exchange != null) {
            return exchange.getContext().getClassResolver().resolveClass((String) value);
        } else {
            return ObjectHelper.loadClass((String) value);
        }
    } else {
        return null;
    }
}
项目:Camel    文件:NIOConverter.java   
@Converter
public static ByteBuffer toByteBuffer(File file) throws IOException {
    InputStream in = null;
    try {
        byte[] buf = new byte[(int)file.length()];
        in = IOHelper.buffered(new FileInputStream(file));
        int sizeLeft = (int)file.length();
        int offset = 0;
        while (sizeLeft > 0) {
            int readSize = in.read(buf, offset, sizeLeft);
            sizeLeft -= readSize;
            offset += readSize;
        }
        return ByteBuffer.wrap(buf);
    } finally {
        IOHelper.close(in, "Failed to close file stream: " + file.getPath(), LOG);
    }
}
项目:Camel    文件:FlatpackConverter.java   
@Converter
public static List<Map<String, Object>> toList(DataSet dataSet) {
    List<Map<String, Object>> answer = new ArrayList<Map<String, Object>>();
    dataSet.goTop();

    while (dataSet.next()) {
        Map<String, Object> map = new HashMap<String, Object>();
        putValues(map, dataSet);
        answer.add(map);
    }

    return answer;
}
项目:Camel    文件:MinaConverter.java   
@Converter
public static byte[] toByteArray(ByteBuffer buffer) {
    buffer.mark();
    try {
        byte[] answer = new byte[buffer.remaining()];
        buffer.get(answer);
        return answer;
    } finally {
        buffer.reset();
    }
}
项目:Camel    文件:CxfPayloadConverter.java   
@Converter
public static <T> CxfPayload<T> sourceToCxfPayload(Source src, Exchange exchange) {
    List<T> headers = new ArrayList<T>();
    List<Source> body = new ArrayList<Source>();
    body.add(src);
    return new CxfPayload<T>(headers, body, null);
}
项目:Camel    文件:CollectionConverter.java   
/**
 * Converts an {@link Iterator} to a {@link ArrayList}
 */
@Converter
public static <T> ArrayList<T> toArrayList(Iterator<T> it) {
    ArrayList<T> list = new ArrayList<T>();
    while (it.hasNext()) {
        list.add(it.next());
    }
    return list;
}
项目:Camel    文件:MailConverters.java   
/**
 * Converts the given JavaMail multipart to a String body, where the content-type of the multipart
 * must be text based (ie start with text). Can return null.
 */
@Converter
public static String toString(Multipart multipart) throws MessagingException, IOException {
    int size = multipart.getCount();
    for (int i = 0; i < size; i++) {
        BodyPart part = multipart.getBodyPart(i);
        if (part.getContentType().toLowerCase().startsWith("text")) {
            return part.getContent().toString();
        }
    }
    return null;
}
项目:Camel    文件:JcloudsPayloadConverter.java   
@Converter
public static Payload toPayload(final StreamSourceCache cache, Exchange exchange) throws IOException {
    long contentLength = ByteStreams.length(new InputSupplier<InputStream>() {
        @Override
        public InputStream getInput() throws IOException {
            return cache.getInputStream();
        }
    });
    cache.reset();
    InputStreamPayload payload = new InputStreamPayload(cache.getInputStream());
    payload.getContentMetadata().setContentLength(contentLength);
    setContentMetadata(payload, exchange);
    return payload;
}
项目:Camel    文件:TelegramConverter.java   
@Converter
public static OutgoingMessage toOutgoingMessage(String message, Exchange exchange) {
    if (message == null) {
        // fail fast
        return null;
    }

    Object typeObj = exchange.getIn().getHeader(TelegramConstants.TELEGRAM_MEDIA_TYPE);
    TelegramMediaType type;
    if (typeObj instanceof String) {
        type = TelegramMediaType.valueOf((String) typeObj);
    } else {
        type = (TelegramMediaType) typeObj;
    }

    // If the message is a string, it will be converted to a OutgoingTextMessage
    if (type == null) {
        type = TelegramMediaType.TEXT;
    }

    OutgoingMessage result;

    switch (type) {
    case TEXT: {
        OutgoingTextMessage txt = new OutgoingTextMessage();
        txt.setText(message);
        result = txt;
        break;
    }
    default: {
        throw new IllegalArgumentException("Unsupported conversion from String to media type " + type);
    }
    }


    return result;
}
项目:Camel    文件:ElasticsearchActionRequestConverter.java   
@Converter
public static DeleteRequest toDeleteRequest(String id, Exchange exchange) {
    return new DeleteRequest()
            .index(exchange.getIn().getHeader(
                    ElasticsearchConstants.PARAM_INDEX_NAME,
                    String.class))
            .type(exchange.getIn().getHeader(
                    ElasticsearchConstants.PARAM_INDEX_TYPE,
                    String.class)).id(id);
}
项目:Camel    文件:XmlConverter.java   
/**
 * Create a DOM document from the given Node.
 *
 * If the node is an document, just cast it, if the node is an root element, retrieve its
 * owner element or create a new document and import the node.
 */
@Converter
public Document toDOMDocument(final Node node) throws ParserConfigurationException, TransformerException {
    ObjectHelper.notNull(node, "node");

    // If the node is the document, just cast it
    if (node instanceof Document) {
        return (Document) node;
        // If the node is an element
    } else if (node instanceof Element) {
        Element elem = (Element) node;
        // If this is the root element, return its owner document
        if (elem.getOwnerDocument().getDocumentElement() == elem) {
            return elem.getOwnerDocument();
            // else, create a new doc and copy the element inside it
        } else {
            Document doc = createDocument();
            // import node must not occur concurrent on the same node (must be its owner)
            // so we need to synchronize on it
            synchronized (node.getOwnerDocument()) {
                doc.appendChild(doc.importNode(node, true));
            }
            return doc;
        }
        // other element types are not handled
    } else {
        throw new TransformerException("Unable to convert DOM node to a Document: " + node);
    }
}
项目:Camel    文件:IOConverter.java   
@Converter
public static byte[] toByteArray(File file) throws IOException {
    InputStream is = toInputStream(file);
    try {
        return toBytes(is);
    } finally {
        IOHelper.close(is, "file", LOG);
    }
}
项目:Camel    文件:CxfPayloadConverter.java   
@Converter
public static <T> CxfPayload<T> elementToCxfPayload(Element element, Exchange exchange) {
    List<T> headers = new ArrayList<T>();
    List<Element> body = new ArrayList<Element>();
    body.add(element);
    return new CxfPayload<T>(headers, body);
}
项目:Camel    文件:NIOConverter.java   
@Converter
public static ByteBuffer toByteBuffer(Integer value) {
    ByteBuffer buf = ByteBuffer.allocate(4);
    buf.putInt(value);
    buf.flip();
    return buf;
}
项目:Camel    文件:NIOConverter.java   
@Converter
public static ByteBuffer toByteBuffer(Long value) {
    ByteBuffer buf = ByteBuffer.allocate(8);
    buf.putLong(value);
    buf.flip();
    return buf;
}
项目:Camel    文件:ExecResultConverter.java   
@Converter
public static String convertToString(ExecResult result, Exchange exchange) throws FileNotFoundException {
    // special for string, as we want an empty string if no output from stdin / stderr
    InputStream is = toInputStream(result);
    if (is != null) {
        return exchange.getContext().getTypeConverter().convertTo(String.class, exchange, is);
    } else {
        // no stdin/stdout, so return an empty string
        return "";
    }
}
项目:Camel    文件:RestletConverter.java   
@Converter
public static Method[] toMethods(String name) {
    String[] strings = name.split(",");
    List<Method> methods = new ArrayList<Method>();
    for (String string : strings) {
        methods.add(toMethod(string));
    }

    return methods.toArray(new Method[methods.size()]);
}
项目:Camel    文件:TwitterConverter.java   
@Converter
public static String toString(Status status) throws ParseException {
    return new StringBuilder()
        .append(status.getCreatedAt()).append(" (").append(status.getUser().getScreenName()).append(") ")
        .append(status.getText())
        .toString();
}
项目:Camel    文件:MongoDbBasicConverters.java   
@Converter
public static DBObject fromAnyObjectToDBObject(Object value) {
    BasicDBObject answer;
    try {
        Map<?, ?> m = OBJECT_MAPPER.convertValue(value, Map.class);
        answer = new BasicDBObject(m);
    } catch (Exception e) {
        LOG.warn("Conversion has fallen back to generic Object -> DBObject, but unable to convert type {}. Returning null.", 
                value.getClass().getCanonicalName());
        return null;
    }
    return answer;
}
项目:Camel    文件:ExecResultConverter.java   
@Converter
public static byte[] convertToByteArray(ExecResult result, Exchange exchange) throws FileNotFoundException, IOException {
    InputStream stream = toInputStream(result);
    try {
        return IOUtils.toByteArray(stream);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}
项目:Camel    文件:StaxConverter.java   
@Converter
public XMLStreamReader createXMLStreamReader(Reader reader) throws XMLStreamException {
    XMLInputFactory factory = getInputFactory();
    try {
        return factory.createXMLStreamReader(IOHelper.buffered(reader));
    } finally {
        returnXMLInputFactory(factory);
    }
}
项目:Camel    文件:StaxConverter.java   
@Converter
public XMLStreamReader createXMLStreamReader(Source in) throws XMLStreamException {
    XMLInputFactory factory = getInputFactory();
    try {
        return factory.createXMLStreamReader(in);
    } finally {
        returnXMLInputFactory(factory);
    }
}
项目:Camel    文件:StaxConverter.java   
@Converter
public XMLEventReader createXMLEventReader(InputStream in, Exchange exchange) throws XMLStreamException {
    XMLInputFactory factory = getInputFactory();
    try {
        String charsetName = IOHelper.getCharsetName(exchange, false);
        if (charsetName == null) {
            return factory.createXMLEventReader(IOHelper.buffered(in));
        } else {
            return factory.createXMLEventReader(IOHelper.buffered(in), charsetName);
        }
    } finally {
        returnXMLInputFactory(factory);
    }
}
项目:Camel    文件:ElasticsearchActionRequestConverter.java   
@Converter
public static MultiGetRequest toMultiGetRequest(Object document, Exchange exchange) {
    List<Item> items = (List<Item>) document;
    MultiGetRequest multiGetRequest = new MultiGetRequest();
    Iterator<Item> it = items.iterator();
    while (it.hasNext()) {
        MultiGetRequest.Item item = it.next();
        multiGetRequest.add(item);
    }
    return multiGetRequest;
}
项目:Camel    文件:MyConverters.java   
@Converter
public Country toCountry(String iso) {
    Country answer = new Country();
    answer.setIso("en");
    answer.setName("England");
    return answer;
}
项目:Camel    文件:NettyConverter.java   
@Converter
public static String toString(ChannelBuffer buffer, Exchange exchange) throws UnsupportedEncodingException {
    byte[] bytes = toByteArray(buffer, exchange);
    // use type converter as it can handle encoding set on the Exchange
    if (exchange != null) {
        return exchange.getContext().getTypeConverter().convertTo(String.class, exchange, bytes);
    }
    return new String(bytes, "UTF-8");
}
项目:Camel    文件:MyTypeConverter.java   
/**
 * Converts the given value to a boolean, handling strings or Boolean
 * objects; otherwise returning false if the value could not be converted to
 * a boolean
 */
@Converter
public static boolean toBool(Object value) {
    Boolean answer = null;    
    if (value instanceof String) {
        answer = Boolean.valueOf((String)value);
    } 
    if (value instanceof Boolean) {
        answer = (Boolean) value;
    }
    if (answer != null) {
        return answer.booleanValue();
    }
    return false;
}
项目:Camel    文件:XmlConverter.java   
/**
 * Converts the source instance to a {@link DOMSource} or returns null if the conversion is not
 * supported (making it easy to derive from this class to add new kinds of conversion).
 */
@Converter
public DOMSource toDOMSource(Source source, Exchange exchange) throws ParserConfigurationException, IOException, SAXException, TransformerException {
    if (source instanceof DOMSource) {
        return (DOMSource) source;
    } else if (source instanceof SAXSource) {
        return toDOMSourceFromSAX((SAXSource) source);
    } else if (source instanceof StreamSource) {
        return toDOMSourceFromStream((StreamSource) source, exchange);
    } else if (source instanceof StAXSource) {
        return toDOMSourceFromStAX((StAXSource)source);
    } else {
        return null;
    }
}
项目:Camel    文件:IOConverter.java   
@Converter
public static byte[] toBytes(InputStream stream) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOHelper.copy(IOHelper.buffered(stream), bos);

    // no need to close the ByteArrayOutputStream as it's close()
    // implementation is noop
    return bos.toByteArray();
}
项目:Camel    文件:DomConverter.java   
@Converter
public static List<?> toList(NodeList nodeList) {
    List<Object> answer = new ArrayList<Object>();
    Iterator<Object> it = ObjectHelper.createIterator(nodeList);
    while (it.hasNext()) {
        answer.add(it.next());
    }
    return answer;
}
项目:Camel    文件:CxfConverter.java   
@Converter
public static MessageContentsList toMessageContentsList(final Object[] array) {
    if (array != null) {
        return new MessageContentsList(array);
    } else {
        return new MessageContentsList();
    }
}
项目:Camel    文件:ElasticsearchActionRequestConverter.java   
@Converter
public static BulkRequest toBulkRequest(List<Object> documents,
                                        Exchange exchange) {
    BulkRequest request = new BulkRequest();
    for (Object document : documents) {
        request.add(createIndexRequest(document, exchange));
    }
    return request;
}
项目:Camel    文件:XmlConverter.java   
@Converter
public StreamSource toStreamSourceFromSAX(SAXSource source, Exchange exchange) throws TransformerException {
    InputSource inputSource = source.getInputSource();
    if (inputSource != null) {
        if (inputSource.getCharacterStream() != null) {
            return new StreamSource(inputSource.getCharacterStream());
        }
        if (inputSource.getByteStream() != null) {
            return new StreamSource(inputSource.getByteStream());
        }
    }
    String result = toString(source, exchange);
    return new StringSource(result);
}
项目:de.dentrassi.camel.unide    文件:PpmpTypeConverter.java   
@Converter
public static MeasurementsWrapper parseMeasurements(final String json) throws IOException {
    return PACKAGER.getMeasurementsBean(json);
}
项目:de.dentrassi.camel.unide    文件:PpmpTypeConverter.java   
@Converter
public static ProcessWrapper parseProcesses(final String json) throws IOException {
    return PACKAGER.getProcessesBean(json);
}
项目:de.dentrassi.camel.unide    文件:PpmpTypeConverter.java   
@Converter
public static MessagesWrapper parseMessages(final String json) throws IOException {
    return PACKAGER.getMessagesBean(json);
}
项目:de.dentrassi.camel.unide    文件:PpmpTypeConverter.java   
@Converter
public static String toStringMeasurements(final MeasurementsWrapper measurements) throws IOException {
    return PACKAGER.getMessage(measurements);
}
项目:de.dentrassi.camel.unide    文件:PpmpTypeConverter.java   
@Converter
public static String toStringProcess(final ProcessWrapper process) throws IOException {
    return PACKAGER.getMessage(process);
}
项目:de.dentrassi.camel.unide    文件:PpmpTypeConverter.java   
@Converter
public static String toStringMessages(final MessagesWrapper messages) throws IOException {
    return PACKAGER.getMessage(messages);
}