use of java.io.IOException in project camel by apache.
the class SftpOperations method createSession.
protected Session createSession(final RemoteFileConfiguration configuration) throws JSchException {
final JSch jsch = new JSch();
JSch.setLogger(new JSchLogger(endpoint.getConfiguration().getJschLoggingLevel()));
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(), 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 known hosts uri: {}", sftpConfig.getKnownHostsUri());
try {
InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(endpoint.getCamelContext(), sftpConfig.getKnownHostsUri());
jsch.setKnownHosts(is);
} catch (IOException e) {
throw new JSchException("Cannot read resource: " + sftpConfig.getKnownHostsUri(), e);
}
}
if (sftpConfig.getKnownHosts() != null) {
LOG.debug("Using known hosts information from byte array");
jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));
}
String knownHostsFile = sftpConfig.getKnownHostsFile();
if (knownHostsFile == null && sftpConfig.isUseUserKnownHostsFile()) {
knownHostsFile = System.getProperty("user.home") + "/.ssh/known_hosts";
LOG.info("Known host file not configured, using user known host file: {}", knownHostsFile);
}
if (ObjectHelper.isNotEmpty(knownHostsFile)) {
LOG.debug("Using known hosts information from file: {}", knownHostsFile);
jsch.setKnownHosts(knownHostsFile);
}
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", "zlib@openssh.com,zlib,none");
session.setConfig("compression.c2s", "zlib@openssh.com,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;
}
use of java.io.IOException in project camel by apache.
the class FtpOperations method doChangeDirectory.
private void doChangeDirectory(String path) {
if (path == null || ".".equals(path) || ObjectHelper.isEmpty(path)) {
return;
}
log.trace("Changing directory: {}", path);
boolean success;
try {
if ("..".equals(path)) {
changeToParentDirectory();
success = true;
} else {
success = client.changeWorkingDirectory(path);
}
} catch (IOException e) {
throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);
}
if (!success) {
throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), "Cannot change directory to: " + path);
}
}
use of java.io.IOException in project camel by apache.
the class FtpOperations method doStoreFile.
private boolean doStoreFile(String name, String targetName, Exchange exchange) throws GenericFileOperationFailedException {
log.trace("doStoreFile({})", targetName);
// if an existing file already exists what should we do?
if (endpoint.getFileExist() == GenericFileExist.Ignore || endpoint.getFileExist() == GenericFileExist.Fail || endpoint.getFileExist() == GenericFileExist.Move) {
boolean existFile = existsFile(targetName);
if (existFile && endpoint.getFileExist() == GenericFileExist.Ignore) {
// ignore but indicate that the file was written
log.trace("An existing file already exists: {}. Ignore and do not override it.", name);
return true;
} else if (existFile && endpoint.getFileExist() == GenericFileExist.Fail) {
throw new GenericFileOperationFailedException("File already exist: " + name + ". Cannot write new file.");
} else if (existFile && endpoint.getFileExist() == GenericFileExist.Move) {
// move any existing file first
doMoveExistingFile(name, targetName);
}
}
InputStream is = null;
if (exchange.getIn().getBody() == null) {
// Do an explicit test for a null body and decide what to do
if (endpoint.isAllowNullBody()) {
log.trace("Writing empty file.");
is = new ByteArrayInputStream(new byte[] {});
} else {
throw new GenericFileOperationFailedException("Cannot write null body to file: " + name);
}
}
try {
if (is == null) {
String charset = endpoint.getCharset();
if (charset != null) {
// charset configured so we must convert to the desired
// charset so we can write with encoding
is = new ByteArrayInputStream(exchange.getIn().getMandatoryBody(String.class).getBytes(charset));
log.trace("Using InputStream {} with charset {}.", is, charset);
} else {
is = exchange.getIn().getMandatoryBody(InputStream.class);
}
}
final StopWatch watch = new StopWatch();
boolean answer;
log.debug("About to store file: {} using stream: {}", targetName, is);
if (endpoint.getFileExist() == GenericFileExist.Append) {
log.trace("Client appendFile: {}", targetName);
answer = client.appendFile(targetName, is);
} else {
log.trace("Client storeFile: {}", targetName);
answer = client.storeFile(targetName, is);
}
watch.stop();
if (log.isDebugEnabled()) {
log.debug("Took {} ({} millis) to store file: {} and FTP client returned: {}", new Object[] { TimeUtils.printDuration(watch.taken()), watch.taken(), targetName, answer });
}
// store client reply information after the operation
exchange.getIn().setHeader(FtpConstants.FTP_REPLY_CODE, client.getReplyCode());
exchange.getIn().setHeader(FtpConstants.FTP_REPLY_STRING, client.getReplyString());
// after storing file, we may set chmod on the file
String chmod = ((FtpConfiguration) endpoint.getConfiguration()).getChmod();
if (ObjectHelper.isNotEmpty(chmod)) {
log.debug("Setting chmod: {} on file: {}", chmod, targetName);
String command = "chmod " + chmod + " " + targetName;
log.trace("Client sendSiteCommand: {}", command);
boolean success = client.sendSiteCommand(command);
log.trace("Client sendSiteCommand successful: {}", success);
}
return answer;
} catch (IOException e) {
throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);
} catch (InvalidPayloadException e) {
throw new GenericFileOperationFailedException("Cannot store file: " + name, e);
} finally {
IOHelper.close(is, "store: " + name, log);
}
}
use of java.io.IOException in project camel by apache.
the class FlinkProducerTest method shouldExecuteVoidDataStreamCallback.
@Test
public void shouldExecuteVoidDataStreamCallback() throws IOException {
final File output = File.createTempFile("camel", "flink");
output.delete();
template.sendBodyAndHeader(flinkDataStreamUri, null, FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() {
@Override
public void doOnDataStream(DataStream ds, Object... payloads) throws Exception {
ds.writeAsText(output.getAbsolutePath());
}
});
Truth.assertThat(output.length()).isAtLeast(0L);
}
use of java.io.IOException in project camel by apache.
the class DefaultPropertiesResolver method loadPropertiesFromRegistry.
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Properties loadPropertiesFromRegistry(CamelContext context, boolean ignoreMissingLocation, PropertiesLocation location) throws IOException {
String path = location.getPath();
Properties answer;
try {
answer = context.getRegistry().lookupByNameAndType(path, Properties.class);
} catch (Exception ex) {
// just look up the Map as a fault back
Map map = context.getRegistry().lookupByNameAndType(path, Map.class);
answer = new Properties();
answer.putAll(map);
}
if (answer == null && (!ignoreMissingLocation && !location.isOptional())) {
throw new FileNotFoundException("Properties " + path + " not found in registry");
}
return answer != null ? answer : new Properties();
}
Aggregations