Java tutorial
/******************************************************************************* * Educational Online Test Delivery System * Copyright (c) 2013 American Institutes for Research * * Distributed under the AIR Open Source License, Version 1.0 * See accompanying file AIR-License-1_0.txt or at * http://www.smarterapp.org/documents/American_Institutes_for_Research_Open_Source_Software_License.pdf ******************************************************************************/ package org.opentestsystem.delivery.testreg.service.impl; import com.jcraft.jsch.ChannelSftp; import org.apache.commons.lang.StringUtils; import org.opentestsystem.delivery.testreg.domain.MnaAlertType; import org.opentestsystem.delivery.testreg.service.FileTransferService; import org.opentestsystem.shared.mna.client.domain.MnaSeverity; import org.opentestsystem.shared.mna.client.service.AlertBeacon; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.integration.file.remote.session.Session; import org.springframework.integration.sftp.session.DefaultSftpSessionFactory; import org.springframework.stereotype.Service; import java.io.ByteArrayInputStream; @Service public class UserChangeEventFileTransferServiceImpl implements FileTransferService { private static final Logger LOGGER = LoggerFactory.getLogger(UserChangeEventFileTransferServiceImpl.class); @Autowired private AlertBeacon alertBeacon; @Value(value = "${testreg.sftp.dir:}") private String sftpDir; @Value(value = "${testreg.sftp.host:}") private String sftpHost; @Value(value = "${testreg.sftp.port:22}") private int sftpPort; @Value(value = "${testreg.sftp.user:}") private String sftpUser; @Autowired private DefaultSftpSessionFactory defaultSftpSessionFactory; @Override public final void writeFile(final String fileName, final String fileBody) { Session<ChannelSftp.LsEntry> sftpSession = null; String destinationPath = (StringUtils.isBlank(sftpDir)) ? fileName : sftpDir + "/" + fileName; String humanReadableConnectionInfo = "sftp://" + sftpUser + "@" + sftpHost + ":" + sftpPort + "/" + destinationPath; try { LOGGER.debug("attempting to transfer file: " + humanReadableConnectionInfo); sftpSession = defaultSftpSessionFactory.getSession(); sftpSession.write(new ByteArrayInputStream(fileBody.getBytes("UTF-8")), destinationPath); alertBeacon.sendAlert(MnaSeverity.INFO, MnaAlertType.SSO_USER_EXPORT.name(), "file transferred: " + humanReadableConnectionInfo); } catch (Exception e) { String errorMessage = "unable to transfer file: " + humanReadableConnectionInfo; LOGGER.error(errorMessage); alertBeacon.sendAlert(MnaSeverity.ERROR, MnaAlertType.SSO_USER_EXPORT.name(), errorMessage); throw new RuntimeException(e); } finally { if (sftpSession != null && sftpSession.isOpen()) { sftpSession.close(); } } } }