private static byte[] getKeyRing(String fileName) throws IOException { InputStream is = PGPDataFormatTest.class.getClassLoader().getResourceAsStream(fileName); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(is, output); output.close(); return output.toByteArray(); }
@SuppressWarnings("unchecked") private boolean retrieveFileToStreamInBody(String name, Exchange exchange) throws GenericFileOperationFailedException { OutputStream os = null; String currentDir = null; try { GenericFile<ChannelSftp.LsEntry> target = (GenericFile<ChannelSftp.LsEntry>) exchange.getProperty(FileComponent.FILE_EXCHANGE_FILE); ObjectHelper.notNull( target, "Exchange should have the " + FileComponent.FILE_EXCHANGE_FILE + " set"); String remoteName = name; if (endpoint.getConfiguration().isStepwise()) { // remember current directory currentDir = getCurrentDirectory(); // change directory to path where the file is to be retrieved // (must do this as some FTP servers cannot retrieve using absolute path) String path = FileUtil.onlyPath(name); if (path != null) { changeCurrentDirectory(path); } // remote name is now only the file name as we just changed directory remoteName = FileUtil.stripPath(name); } // use input stream which works with Apache SSHD used for testing InputStream is = channel.get(remoteName); if (endpoint.getConfiguration().isStreamDownload()) { target.setBody(is); exchange.getIn().setHeader(RemoteFileComponent.REMOTE_FILE_INPUT_STREAM, is); } else { os = new ByteArrayOutputStream(); target.setBody(os); IOHelper.copyAndCloseInput(is, os); } return true; } catch (IOException e) { throw new GenericFileOperationFailedException("Cannot retrieve file: " + name, e); } catch (SftpException e) { throw new GenericFileOperationFailedException("Cannot retrieve file: " + name, e); } finally { IOHelper.close(os, "retrieve: " + name, LOG); // change back to current directory if we changed directory if (currentDir != null) { changeCurrentDirectory(currentDir); } } }
/** * Reads the response body from the given input stream. * * @param is the input stream * @param exchange the exchange * @return the response body, can be <tt>null</tt> if no body * @throws IOException is thrown if error reading response body */ public static Object readResponseBodyFromInputStream(InputStream is, Exchange exchange) throws IOException { if (is == null) { return null; } // convert the input stream to StreamCache if the stream cache is not disabled if (exchange.getProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.FALSE, Boolean.class)) { return is; } else { CachedOutputStream cos = new CachedOutputStream(exchange); IOHelper.copyAndCloseInput(is, cos); return cos.newStreamCache(); } }
@Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws NoTypeConversionAvailableException, MessagingException, IOException { if (multipartWithoutAttachment || headersInline || exchange.getIn().hasAttachments()) { ContentType contentType = getContentType(exchange); // remove the Content-Type header. This will be wrong afterwards... exchange.getOut().removeHeader(Exchange.CONTENT_TYPE); byte[] bodyContent = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph); Session session = Session.getInstance(System.getProperties()); MimeMessage mm = new MimeMessage(session); MimeMultipart mp = new MimeMultipart(multipartSubType); BodyPart part = new MimeBodyPart(); writeBodyPart(bodyContent, part, contentType); mp.addBodyPart(part); for (Map.Entry<String, Attachment> entry : exchange.getIn().getAttachmentObjects().entrySet()) { String attachmentFilename = entry.getKey(); Attachment attachment = entry.getValue(); part = new MimeBodyPart(); part.setDataHandler(attachment.getDataHandler()); part.setFileName(MimeUtility.encodeText(attachmentFilename, "UTF-8", null)); String ct = attachment.getDataHandler().getContentType(); contentType = new ContentType(ct); part.setHeader(CONTENT_TYPE, ct); if (!contentType.match("text/*") && binaryContent) { part.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); } // Set headers to the attachment for (String headerName : attachment.getHeaderNames()) { List<String> values = attachment.getHeaderAsList(headerName); for (String value : values) { part.setHeader(headerName, value); } } mp.addBodyPart(part); exchange.getOut().removeAttachment(attachmentFilename); } mm.setContent(mp); // copy headers if required and if the content can be converted into // a String if (headersInline && includeHeaders != null) { for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) { if (includeHeaders.matcher(entry.getKey()).matches()) { String headerStr = ExchangeHelper.convertToType(exchange, String.class, entry.getValue()); if (headerStr != null) { mm.setHeader(entry.getKey(), headerStr); } } } } mm.saveChanges(); Enumeration<?> hl = mm.getAllHeaders(); List<String> headers = new ArrayList<String>(); if (!headersInline) { while (hl.hasMoreElements()) { Object ho = hl.nextElement(); if (ho instanceof Header) { Header h = (Header) ho; exchange.getOut().setHeader(h.getName(), h.getValue()); headers.add(h.getName()); } } mm.saveChanges(); } mm.writeTo(stream, headers.toArray(new String[0])); } else { // keep the original data InputStream is = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph); IOHelper.copyAndCloseInput(is, stream); } }
@Override public Object unmarshal(Exchange exchange, InputStream stream) throws IOException, MessagingException { MimeBodyPart mimeMessage; String contentType; Message camelMessage; Object content = null; if (headersInline) { mimeMessage = new MimeBodyPart(stream); camelMessage = exchange.getOut(); MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true); contentType = mimeMessage.getHeader(CONTENT_TYPE, null); // write the MIME headers not generated by javamail as Camel headers Enumeration<?> headersEnum = mimeMessage.getNonMatchingHeaders(STANDARD_HEADERS); while (headersEnum.hasMoreElements()) { Object ho = headersEnum.nextElement(); if (ho instanceof Header) { Header header = (Header) ho; camelMessage.setHeader(header.getName(), header.getValue()); } } } else { // check if this a multipart at all. Otherwise do nothing contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class); if (contentType == null) { return stream; } try { ContentType ct = new ContentType(contentType); if (!ct.match("multipart/*")) { return stream; } } catch (ParseException e) { LOG.warn("Invalid Content-Type " + contentType + " ignored"); return stream; } camelMessage = exchange.getOut(); MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(stream, bos); InternetHeaders headers = new InternetHeaders(); extractHeader(CONTENT_TYPE, camelMessage, headers); extractHeader(MIME_VERSION, camelMessage, headers); mimeMessage = new MimeBodyPart(headers, bos.toByteArray()); bos.close(); } DataHandler dh; try { dh = mimeMessage.getDataHandler(); if (dh != null) { content = dh.getContent(); contentType = dh.getContentType(); } } catch (MessagingException e) { LOG.warn("cannot parse message, no unmarshalling done"); } if (content instanceof MimeMultipart) { MimeMultipart mp = (MimeMultipart) content; content = mp.getBodyPart(0); for (int i = 1; i < mp.getCount(); i++) { BodyPart bp = mp.getBodyPart(i); DefaultAttachment camelAttachment = new DefaultAttachment(bp.getDataHandler()); @SuppressWarnings("unchecked") Enumeration<Header> headers = bp.getAllHeaders(); while (headers.hasMoreElements()) { Header header = headers.nextElement(); camelAttachment.addHeader(header.getName(), header.getValue()); } camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment); } } if (content instanceof BodyPart) { BodyPart bp = (BodyPart) content; camelMessage.setBody(bp.getInputStream()); contentType = bp.getContentType(); if (contentType != null && !DEFAULT_CONTENT_TYPE.equals(contentType)) { camelMessage.setHeader(CONTENT_TYPE, contentType); ContentType ct = new ContentType(contentType); String charset = ct.getParameter("charset"); if (charset != null) { camelMessage.setHeader(Exchange.CONTENT_ENCODING, MimeUtility.javaCharset(charset)); } } } else { // If we find no body part, try to leave the message alone LOG.info("no MIME part found"); } return camelMessage; }
protected Session createSession(final RemoteFileConfiguration configuration) throws JSchException { final JSch jsch = new JSch(); JSch.setLogger(new JSchLogger()); SftpConfiguration sftpConfig = (SftpConfiguration) configuration; if (isNotEmpty(sftpConfig.getCiphers())) { LOG.debug("Using ciphers: {}", sftpConfig.getCiphers()); Hashtable<String, String> ciphers = new Hashtable<String, String>(); ciphers.put("cipher.s2c", sftpConfig.getCiphers()); ciphers.put("cipher.c2s", sftpConfig.getCiphers()); JSch.setConfig(ciphers); } if (isNotEmpty(sftpConfig.getPrivateKeyFile())) { LOG.debug("Using private keyfile: {}", sftpConfig.getPrivateKeyFile()); if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) { jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyPassphrase()); } else { jsch.addIdentity(sftpConfig.getPrivateKeyFile()); } } if (sftpConfig.getPrivateKey() != null) { LOG.debug("Using private key information from byte array"); byte[] passphrase = null; if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) { try { passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new JSchException("Cannot transform passphrase to byte[]", e); } } jsch.addIdentity("ID", sftpConfig.getPrivateKey(), null, passphrase); } if (sftpConfig.getPrivateKeyUri() != null) { LOG.debug("Using private key uri : {}", sftpConfig.getPrivateKeyUri()); byte[] passphrase = null; if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) { try { passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new JSchException("Cannot transform passphrase to byte[]", e); } } try { InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream( endpoint.getCamelContext().getClassResolver(), sftpConfig.getPrivateKeyUri()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(is, bos); jsch.addIdentity("ID", bos.toByteArray(), null, passphrase); } catch (IOException e) { throw new JSchException("Cannot read resource: " + sftpConfig.getPrivateKeyUri(), e); } } if (sftpConfig.getKeyPair() != null) { LOG.debug("Using private key information from key pair"); KeyPair keyPair = sftpConfig.getKeyPair(); if (keyPair.getPrivate() != null && keyPair.getPublic() != null) { if (keyPair.getPrivate() instanceof RSAPrivateKey && keyPair.getPublic() instanceof RSAPublicKey) { jsch.addIdentity(new RSAKeyPairIdentity("ID", keyPair), null); } else if (keyPair.getPrivate() instanceof DSAPrivateKey && keyPair.getPublic() instanceof DSAPublicKey) { jsch.addIdentity(new DSAKeyPairIdentity("ID", keyPair), null); } else { LOG.warn("Only RSA and DSA key pairs are supported"); } } else { LOG.warn("PrivateKey and PublicKey in the KeyPair must be filled"); } } if (isNotEmpty(sftpConfig.getKnownHostsFile())) { LOG.debug("Using knownhosts file: {}", sftpConfig.getKnownHostsFile()); jsch.setKnownHosts(sftpConfig.getKnownHostsFile()); } if (isNotEmpty(sftpConfig.getKnownHostsUri())) { LOG.debug("Using knownhosts uri: {}", sftpConfig.getKnownHostsUri()); try { InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream( endpoint.getCamelContext().getClassResolver(), sftpConfig.getKnownHostsUri()); jsch.setKnownHosts(is); } catch (IOException e) { throw new JSchException("Cannot read resource: " + sftpConfig.getKnownHostsUri(), e); } } if (sftpConfig.getKnownHosts() != null) { LOG.debug("Using knownhosts information from byte array"); jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts())); } final Session session = jsch.getSession( configuration.getUsername(), configuration.getHost(), configuration.getPort()); if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) { LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking()); session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking()); } session.setServerAliveInterval(sftpConfig.getServerAliveInterval()); session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax()); // compression if (sftpConfig.getCompression() > 0) { LOG.debug("Using compression: {}", sftpConfig.getCompression()); session.setConfig("compression.s2c", "[email protected],zlib,none"); session.setConfig("compression.c2s", "[email protected],zlib,none"); session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression())); } // set the PreferredAuthentications if (sftpConfig.getPreferredAuthentications() != null) { LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications()); session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications()); } // set user information session.setUserInfo( new ExtendedUserInfo() { public String getPassphrase() { return null; } public String getPassword() { return configuration.getPassword(); } public boolean promptPassword(String s) { return true; } public boolean promptPassphrase(String s) { return true; } public boolean promptYesNo(String s) { LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no."); // Return 'false' indicating modification of the hosts file is disabled. return false; } public void showMessage(String s) { LOG.trace("Message received from Server: " + s); } public String[] promptKeyboardInteractive( String destination, String name, String instruction, String[] prompt, boolean[] echo) { // must return an empty array if password is null if (configuration.getPassword() == null) { return new String[0]; } else { return new String[] {configuration.getPassword()}; } } }); // set the SO_TIMEOUT for the time after the connect phase if (configuration.getSoTimeout() > 0) { session.setTimeout(configuration.getSoTimeout()); } // set proxy if configured if (proxy != null) { session.setProxy(proxy); } return session; }
public void writeTo(OutputStream os) throws IOException { IOHelper.copyAndCloseInput(in, os); }