@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; } }
/** * 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; } }
@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); } }
@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; }
@Converter public static byte[] toByteArray(ByteBuffer buffer) { buffer.mark(); try { byte[] answer = new byte[buffer.remaining()]; buffer.get(answer); return answer; } finally { buffer.reset(); } }
@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); }
/** * 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; }
/** * 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; }
@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; }
@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; }
@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); }
/** * 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); } }
@Converter public static byte[] toByteArray(File file) throws IOException { InputStream is = toInputStream(file); try { return toBytes(is); } finally { IOHelper.close(is, "file", LOG); } }
@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); }
@Converter public static ByteBuffer toByteBuffer(Integer value) { ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(value); buf.flip(); return buf; }
@Converter public static ByteBuffer toByteBuffer(Long value) { ByteBuffer buf = ByteBuffer.allocate(8); buf.putLong(value); buf.flip(); return buf; }
@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 ""; } }
@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()]); }
@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(); }
@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; }
@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); } }
@Converter public XMLStreamReader createXMLStreamReader(Reader reader) throws XMLStreamException { XMLInputFactory factory = getInputFactory(); try { return factory.createXMLStreamReader(IOHelper.buffered(reader)); } finally { returnXMLInputFactory(factory); } }
@Converter public XMLStreamReader createXMLStreamReader(Source in) throws XMLStreamException { XMLInputFactory factory = getInputFactory(); try { return factory.createXMLStreamReader(in); } finally { returnXMLInputFactory(factory); } }
@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); } }
@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; }
@Converter public Country toCountry(String iso) { Country answer = new Country(); answer.setIso("en"); answer.setName("England"); return answer; }
@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"); }
/** * 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; }
/** * 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; } }
@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(); }
@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; }
@Converter public static MessageContentsList toMessageContentsList(final Object[] array) { if (array != null) { return new MessageContentsList(array); } else { return new MessageContentsList(); } }
@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; }
@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); }
@Converter public static MeasurementsWrapper parseMeasurements(final String json) throws IOException { return PACKAGER.getMeasurementsBean(json); }
@Converter public static ProcessWrapper parseProcesses(final String json) throws IOException { return PACKAGER.getProcessesBean(json); }
@Converter public static MessagesWrapper parseMessages(final String json) throws IOException { return PACKAGER.getMessagesBean(json); }
@Converter public static String toStringMeasurements(final MeasurementsWrapper measurements) throws IOException { return PACKAGER.getMessage(measurements); }
@Converter public static String toStringProcess(final ProcessWrapper process) throws IOException { return PACKAGER.getMessage(process); }
@Converter public static String toStringMessages(final MessagesWrapper messages) throws IOException { return PACKAGER.getMessage(messages); }