NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

package com.ge.treasury.mypayments.sftp;

import com.ge.treasury.mypayments.constants.SFTPConstants;
import com.ge.treasury.mypayments.service.SftpServiceImpl;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
public class SftpServiceImplTest {

@Mock
private SFTPConstants sftpTRAX;

@InjectMocks
private SftpServiceImpl sftpService;

private byte[] contents;
private String fileName;
private String paymentSystem;

@BeforeEach
public void setUp() {
contents = "test contents".getBytes(StandardCharsets.UTF_8);
fileName = "testFile";
paymentSystem = "TRAX";
}

@Test
public void testSendMultipleFiles() throws Exception {
// Mocking the necessary objects
Session mockSession = mock(Session.class);
Channel mockChannel = mock(Channel.class);
ChannelSftp mockChannelSftp = mock(ChannelSftp.class);

// Mock behaviors for SFTP constants and session
when(sftpTRAX.getPrivateKeyPath()).thenReturn("privateKeyPath");
when(sftpTRAX.getUser()).thenReturn("user");
when(sftpTRAX.getHost()).thenReturn("host");
when(sftpTRAX.getPort()).thenReturn(22);
when(sftpTRAX.getRemoteOutboundDir()).thenReturn("/remote/dir");

// Mocking the session and channel interaction
when(mockSession.openChannel("sftp")).thenReturn(mockChannel);
doNothing().when(mockChannel).connect();
when(mockChannelSftp.isConnected()).thenReturn(true);
when(mockChannel.getSession()).thenReturn(mockSession);
doNothing().when(mockChannelSftp).exit();
doNothing().when(mockChannel).disconnect();
doNothing().when(mockSession).disconnect();

// Mock the JSch behavior to return the mock session
JSch mockJSch = mock(JSch.class);
when(mockJSch.getSession(anyString(), anyString(), anyInt())).thenReturn(mockSession);

// Simulate the file send operation for 10 files
for (int i = 0; i < 10; i++) {
String currentFileName = fileName + "_" + i + ".txt";
boolean result = sftpService.send(contents, currentFileName, paymentSystem);
assertTrue(result, "File send failed: " + currentFileName);
}

// Verifying that the 'put' method was called 10 times for each file
verify(mockChannelSftp, times(10)).put(any(InputStream.class), anyString());
}
}


---------------------------------------------------------------------------------------------------------------------


package com.ge.treasury.mypayments.service;

import java.util.Properties;
import java.util.UUID;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.nio.charset.StandardCharsets;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

import com.ge.treasury.mypayments.OutBoundGateway;
import com.ge.treasury.mypayments.constants.ExceptionConstants;
import com.ge.treasury.mypayments.constants.PaymentRequestConstants;
import com.ge.treasury.mypayments.constants.SFTPConstants;
import com.ge.treasury.mypayments.constants.WorkflowConstants;
import com.ge.treasury.mypayments.dao.PaymentRequestDao;
import com.ge.treasury.mypayments.domain.AutopayFileDetails;
import com.ge.treasury.mypayments.domain.PaymentFile;
import com.ge.treasury.mypayments.domain.User;
import com.ge.treasury.mypayments.exceptions.BusinessException;
import com.ge.treasury.mypayments.utils.service.CryptographicService;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

@Service
public class SftpServiceImpl implements SftpService {

private static final Logger LOGGER = LogManager.getLogger(SftpServiceImpl.class);

@Value("${sftp.maxRetry}")
private int maxRetry;

@Autowired
private OutBoundGateway outBoundGateway;

@Autowired
private PaymentRequestDao paymentDao;

@Autowired
CryptographicService cryptographicService;

@Autowired
PaymentRequestManagerService paymentService;

//TRAX SFTP
@Autowired
@Qualifier("sftpTRAX")
private SFTPConstants sftpTRAX;



@Override
public boolean send(byte[] contents, String fileName, String paymentSystem) {
for (int tryCount = 0; tryCount < maxRetry; tryCount++) {
try {
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;

UUID uuid = UUID.randomUUID();
String uniqueString = uuid.toString();
try (InputStream stream = new ByteArrayInputStream("contents".getBytes(StandardCharsets.UTF_8));) {
JSch jsch = new JSch();
jsch.addIdentity(sftpTRAX.getPrivateKeyPath());
session = jsch.getSession(sftpTRAX.getUser(), sftpTRAX.getHost(), sftpTRAX.getPort());
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(sftpTRAX.getRemoteOutboundDir());
channelSftp.put(stream, uniqueString);

} catch (Exception e) {
throw new BusinessException(e.getMessage());
} finally {
if (channelSftp != null) {
channelSftp.exit();
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}

return true;
} catch (Exception e) {
LOGGER.error(WorkflowConstants.TRNSFR_ERROR + fileName + WorkflowConstants.REM_DIR_LOC, e);
}

}
return false;
}
@Override
public boolean sentPaymentRequestToWebCash(PaymentFile paymentFile, User user) {
return retrieveClobAndSend(paymentFile, user, PaymentRequestConstants.SYSTEM_WEBCASH);
}

@Override
public boolean sentPaymentRequestToTrax(PaymentFile paymentFile, User user) {
return retrieveClobAndSend(paymentFile, user, PaymentRequestConstants.TRAX_PAYMENT);
}

private boolean retrieveClobAndSend(PaymentFile paymentFile, User user, String paymentSystem) {
AutopayFileDetails autopayFileDetails = paymentDao.getFileDetailsById(paymentFile.getFileDetailId());
byte[] encryptedFileContent = retrieveAndEncryptClob(paymentFile, paymentSystem, user,autopayFileDetails);
boolean isSuccessful = send(encryptedFileContent, autopayFileDetails.getFileName().concat(".pgp"), paymentSystem);
updateFileStatus(paymentFile, isSuccessful, ExceptionConstants.SFTP_TRANSFER_ERROR, user, paymentSystem);
if (isSuccessful) {
paymentService.insertWorkflowActivity(paymentFile.getPaymentRequestId(), user, WorkflowConstants.WRKFLW_STS_DLVRY_SUCCESS,
"File Name :".concat(StringUtils.defaultString(autopayFileDetails.getFileName())));
} else {
paymentService.insertWorkflowActivity(paymentFile.getPaymentRequestId(), user, WorkflowConstants.WRKFLW_STS_DLVRY_FAILED,
ExceptionConstants.SFTP_TRANSFER_ERROR.concat(". File Name :".concat(StringUtils.defaultString(autopayFileDetails.getFileName()))));
}

return isSuccessful;
}

private void updateFileStatus(PaymentFile paymentFile, boolean isSuccessful, String exceptionMessage, User user, String paymentSystem) {
if (isSuccessful) {
paymentFile.setTransmissionStatusCode(
paymentDao.getMypayLookUpByExample("DELIVERED_STATUS", null, null).getLookupCode());
paymentFile.setTransmissionComments(
PaymentRequestConstants.FILE_TRANSFER_MESSAGE.concat(paymentSystem));
} else {
paymentFile.setTransmissionStatusCode(
paymentDao.getMypayLookUpByExample("ERROR_STATUS", null, null).getLookupCode());
paymentFile.setTransmissionComments(exceptionMessage);
}

paymentDao.updateFileTransferStatus(paymentFile, user);
}

@PostConstruct
public void postConstruct() {
Assert.isTrue(maxRetry > 0, "sftp.maxRetry must be greater than 0; is : " + maxRetry);
}

@Override
public byte[] retrieveAndEncryptClob(PaymentFile paymentFile, String paymentSystem, User user, AutopayFileDetails autopayFileDetails) {
byte[] fileContent = null;
if (null != autopayFileDetails && null != autopayFileDetails.getFileContent() && null != autopayFileDetails.getFileName()) {
try {
fileContent = cryptographicService.getEncryptSignContent(paymentFile, paymentSystem,autopayFileDetails);
} catch (Exception e) {
LOGGER.error("Error in retrieve encrypt and sign clob content ", e);

paymentService.insertWorkflowActivity(paymentFile.getPaymentRequestId(), user,
WorkflowConstants.WRKFLW_STS_DLVRY_FAILED, ExceptionConstants.ENCRYPTION_ERROR);
updateFileStatus(paymentFile, false, ExceptionConstants.ENCRYPTION_ERROR, user, paymentSystem);
}
}
return fileContent;
}

}
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.