-
Notifications
You must be signed in to change notification settings - Fork 1
SFTP
Transferring data wireless over local network isn't something new, people have been doing that for a long time. You may be aware of what I'm talking about: an FTP connection. With an FTP client you can connect one device to another to transfer your data over a network.
Example using com.jcraft.jsch.0.1.54 maven
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class SFTP_RemoteFileTransfer {
private static final Log log = LogFactory.getLog(SFTP_RemoteFileTransfer.class);
static String sftpHost, sftpUsername, sftpPassword;
static int sftpPort;
public static void main(String[] args) throws Exception {
String NewFilePath = "C:/Yash/Reports.sql";
File newFile = new File(NewFilePath);
InputStream fileContent = new FileInputStream(newFile);
String newFileName = newFile.getName();
String destinationDir = "C:/Yash/Workplace SVN Branches/NeonDashboard/RemoteFile",
archivalDir = "C:/Yash/Workplace SVN Branches/NeonDashboard/RemoteFile/BackUP";
copyReportToDestination(fileContent, newFileName, destinationDir, archivalDir);
}
public static void copyReportToDestination(InputStream fileContent, String fileName, String destinationDir,
String archivalDir)
throws Exception{
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(sftpUsername, sftpHost, sftpPort);
session.setPassword(sftpPassword);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(destinationDir);
// Move old reports to archive location
if(archivalDir != null)
moveExistingFilesToArchive(channelSftp, destinationDir, archivalDir);
// copy new report to destination directory
copyReportsToDestination(channelSftp, fileContent, fileName, destinationDir);
channel.disconnect();
session.disconnect();
if (session.isConnected()) {
session.disconnect();
}
} catch (JSchException|SftpException e) {
throw new Exception("Failed while transfering file and caught Exception!:"+ e);
}
}
public static void moveExistingFilesToArchive(ChannelSftp channelSftp, String sftpWorkingDir, String destinationDir) throws Exception {
try {
Vector<ChannelSftp.LsEntry> filesList = channelSftp.ls("*.*");
log.info("filesList size:" + filesList.size());
if (!filesList.isEmpty()) {
for (ChannelSftp.LsEntry entry : filesList) {
String filename = entry.getFilename();
log.info("Filename::" + filename);
String localFile = sftpWorkingDir + "/" + filename;
String archivalFilename = filename;
String[] parts = null;
if (filename.contains(".")) { // filename.matches("\\*.\\*")
log.info("File name change");
parts = filename.split("\\.");
// ArchivalTimestamp to be appended to filename
String timeStamp = new SimpleDateFormat("yyyyMMdd_HH_mm_ss").format(new Date());
archivalFilename = parts[0] + "_" + timeStamp + "." + parts[1];
}
String remoteDir = destinationDir + "/" + archivalFilename;
log.info("Ready for transfer" + remoteDir + "\n" + localFile);
channelSftp.cd(destinationDir);
channelSftp.rename(localFile, remoteDir);
channelSftp.cd(sftpWorkingDir);
}
}
} catch (SftpException e) {
throw new Exception("Failed while transfering file and caught SftpException!:"+ e);
}
}
public static void copyReportsToDestination(ChannelSftp channelSftp, InputStream fileContent, String fileName, String destinationDir) throws Exception {
try {
channelSftp.cd(destinationDir);
log.info("Report upload to Remote directory Starts");
channelSftp.put(fileContent, destinationDir+"/"+fileName);
fileContent.close();
log.info("File uploaded successfully - "+ destinationDir);
} catch(SftpException|IOException e) {
throw new Exception("Failed while transfering file and caught Exception!:"+ e);
}
}
}
In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior.
Method signature: It consists of method name and parameter list (number/type/order of the parameters). methodName(parametersList y)
. An instance method in a subclass with the same signature
and return type
as an instance method in the super-class overrides the super-class's method.
Java OOP concepts
Class - Collection of a common features of a group of object [static/instance Fields, blocks and Methods]
Object - Instance of a class (instance fields)
Abstraction - Process of hiding complex info and providing required info like API, Marker Interfaces ...
Encapsulation(Security) - Class Binding up with data members(fields) and member functions.
Inheritance (Reusability by placing common code in single class)
1. Multilevel - {A -> B -> C} 2. Multiple - Diamond problem {A <- (B) -> C} [Java not supports] 3. Cyclic {A <-> B} [Java not supports]
* Is-A Relation - Class A extends B
* Hash-A Relation - Class A { B obj = new B(); } - (Composition/Aggregation)
Polymorphism (Flexibility) 1. Compile-Time Overloading 2. Runtime Overriding [Greek - "many forms"]
int[] arr = {1,2,3}; int arrLength = arr.length; // Fixed length of sequential blocks to hold same data type
String str = "Yash"; int strLength = str.length(); // Immutable Object value can't be changed.
List<?> collections = new ArrayList<String>(); int collectionGroupSize = collections.size();
Map<?, ?> mapEntry = new HashMap<String, String>();
Set<?> keySet = mapEntry.keySet(); // Set of Key's
Set<?> entrySet = mapEntry.entrySet(); // Set of Entries [Key, Value]
// Immutable Objects once created they can't be modified. final class Integer/String/Employee
Integer val = Integer.valueOf("100"); String str2 = String.valueOf(100); // Immutable classes
final class Employee { // All Wrapper classes, java.util.UUID, java.io.File ...
private final String empName; // Field as Final(values can be assigned only once) Only getter functions.
public Employee(String name) { this.empName = name; }
}
Native Java Code for Hashtable.h
, Hashtable.cpp
SQL API
.
You can check your current JDK and JRE versions on your command prompt respectively,
- JDK
javac -version [C:\Program Files\Java\jdk1.8.0_121\bin]
o/p:javac 1.8.0_121
- JRE
java -version
[C:\Program Files\Java\jdk1.8.0_121\bin]
o/P:java version "1.8.0_102"
JAVA_HOME - Must be set to JDK otherwise maven projects leads to compilation error. [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
C:\Softwares\OpenJDK\
, 7-zip
Fatal error compiling: invalid target release: JRE and JDK must be of same version
1.8.0.XXX
Disable TLS 1.0 and 1.1
security-libs/javax.net.ssl
: TLS 1.0 and 1.1 are versions of the TLS protocol that are no longer considered secure and have been superseded by more secure and modern versions (TLS 1.2 and 1.3).
Core Java
-
Java Programming Language Basics
- Object, Class, Encapsulation, Interface, Inheritance, Polymorphism (Method Overloading, Overriding)
- JVM Architecture, Memory Areas
- JVM Class Loader SubSystem
- Core Java Interview Questions & Programs
- Interview Concepts
Stack Posts
- Comparable vs Comparator
- Collections and Arrays
-
String, StringBuffer, and StringBuilder
- String reverse
- Remove single char
- File data to String
- Unicode equality check Spacing entities
- split(String regex, int limit)
- Longest String of an array
-
Object Serialization
- Interface's Serializable vs Externalizable
- Transient Keyword
-
implements Runnable
vsextends Thread
- JSON
- Files,
Logging API
- Append text to Existing file
- Counting number of words in a file
- Properties
- Properties with reference key