November 2, 2015

Extending OutputStream

It was very helpful when using: ((ChannelExec) channel).setErrStream(new Log4JOutputStream());

Review JSch - Examples - Exec.java

Example 1

package sawalha.poc.sch;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4JOutputStream extends OutputStream {

    static Logger log = LogManager.getLogger(ExecCli.class.getName());
    StringBuffer str = new StringBuffer();

    @Override
    public void write(int b) throws IOException {
        char current = (char) b;
        if (current == '\n') {
            log.error(str.toString());
            // Reset it
            str.setLength(0);
        } else {
            str.append(current);
        }
    }
}

Example 2

package sawalha.poc.sch;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4JOutputStream extends OutputStream {

    static Logger log = LogManager.getLogger(ExecCli.class.getName());
    StringBuffer str = new StringBuffer();

    @Override
    public void close() throws IOException {
        super.close();
        log.error(str.toString());
    }

    @Override
    public void write(int b) throws IOException {
        int[] bytes = { b };
        write(bytes, 0, bytes.length);
    }

    public void write(int[] bytes, int offset, int length) {
        String s = new String(bytes, offset, length);
        str.append(s);
    }

}

Copy Files between Linux & Windows using Java

Maven Dependency

print 'hello w<!-- www.jcraft.com/jsch/ -->
<dependency>
 <groupId>com.jcraft</groupId>
 <artifactId>jsch</artifactId>
 <version>0.1.53</version>
</dependency>orld!'

FileCopierOverNetwork example class

package sawalha.poc.sch.trans;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

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;
import com.jcraft.jsch.SftpProgressMonitor;

public class FileCopierOverNetwork {

    static Logger log = LogManager.getLogger(FileCopierOverNetwork.class.getName());

    final static SftpProgressMonitor monitor = new SftpProgressMonitor() {
        public void init(final int op, final String source, final String target, final long max) {
            log.info("sftp start uploading file from:" + source + " to:" + target);
        }

        public boolean count(final long count) {
            log.debug("sftp sending bytes: " + count);
            return true;
        }

        public void end() {
            log.info("sftp uploading is done.");
        }
    };

    public static void main(String args[]) {
        String hostname = "10.100.102.37";
        String username = "thin";
        String password = "thin123";
        String copyWinFrom = createTestFile("fromWindows.del").getAbsolutePath();
        // String copyWinFrom = "d:/fromWindows.del";
        String copyWinTo = "/home/thin/ibrahim-scripts/fromWindows.del";

        String copyLinuxFrom = "/home/thin/ibrahim-scripts/fromLinux.del";
        String copyLinuxTo = "fromLinux.del";

        try {
            putFile(hostname, username, password, copyWinFrom, copyWinTo);
            getFile(hostname, username, password, copyLinuxFrom, copyLinuxTo);
        } catch (JSchException e1) {
            e1.printStackTrace();
        } catch (SftpException e1) {
            e1.printStackTrace();
        }
        log.info("Done !!");
    }

    public static void putFile(String hostname, String username, String password, String copyFrom, String copyTo)
            throws JSchException, SftpException {
        log.info("Initiate sending file to Linux Server...");
        JSch jsch = new JSch();
        Session session = null;
        log.info("Trying to connect.....");
        session = jsch.getSession(username, hostname, 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();
        log.info("is server connected? " + session.isConnected());

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        log.info("Server's home directory: " + sftpChannel.getHome());
        try {
            sftpChannel.put(copyFrom, copyTo, monitor, ChannelSftp.OVERWRITE);
        } catch (SftpException e) {
            log.error("file was not found: " + copyFrom);
        }

        sftpChannel.exit();
        session.disconnect();
        log.info("Finished sending file to Linux Server...");
    }

    public static void getFile(String hostname, String username, String password, String copyFrom, String copyTo)
            throws JSchException {
        log.info("Initiate getting file from Linux Server...");
        JSch jsch = new JSch();
        Session session = null;
        log.info("Trying to connect.....");
        session = jsch.getSession(username, hostname, 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();
        log.info("is server connected? " + session.isConnected());

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        try {
            log.info(sftpChannel.getHome());
        } catch (SftpException e1) {
            e1.printStackTrace();
        }
        try {
            sftpChannel.get(copyFrom, copyTo, monitor, ChannelSftp.OVERWRITE);
        } catch (SftpException e) {
            log.error("file was not found: " + copyFrom);
        }

        sftpChannel.exit();
        session.disconnect();
        log.info("Finished getting file from Linux Server...");
    }

    public static File createTestFile(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            return file;
        }
        try {
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("This is ");
            fileWriter.write("a test");
            fileWriter.write("\n");
            fileWriter.write("Ibrahim Sawalha.");
            fileWriter.flush();
            fileWriter.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Example on Log4j2 with RollingFile

pom.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>log4j2-example</groupId>
 <artifactId>log4j2-example</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <dependencies>
  <!-- Log4J 2 : required -->
  <dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-core</artifactId>
   <version>2.3</version>
  </dependency>
 </dependencies>
</project>

log4j2.xml file

Note: the log4j2.xml file is located under PORJECT_HOME\src\main\resources\log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
 <Properties>
  <Property name="log-path">logs</Property>
 </Properties>
 <Appenders>
  <Console name="console-log" target="SYSTEM_OUT">
   <PatternLayout pattern="[%-5level][%t] %c{1}:%L- %msg%n" />
  </Console>
  <RollingFile name="trace-log" fileName="${log-path}/myexample.log"
   filePattern="${log-path}/myexample-%d{yyyy-MM-dd}-%i.log">
   <PatternLayout>
    <pattern>[%-5level] %d [%t] %c{1}:%L- %msg%n</pattern>
   </PatternLayout>
   <Policies>
    <SizeBasedTriggeringPolicy size="1 KB" />
   </Policies>
   <DefaultRolloverStrategy max="4" />
  </RollingFile>
  <RollingFile name="error-log" fileName="${log-path}/myexample-error.log"
   filePattern="${log-path}/ics-print-info-error-%d{yyyy-MM-dd}.log">
   <PatternLayout>
    <!-- %-5level %d [%t] %c:%M(%L): %m%n -->
    <pattern>[%-5level] %d [%t] %c:%M:%L- %m%n</pattern>
   </PatternLayout>
   <Policies>
    <SizeBasedTriggeringPolicy size="1 KB" />
   </Policies>
   <DefaultRolloverStrategy max="4" />
  </RollingFile>
 </Appenders>
 <Loggers>
  <Logger name="sawalha" level="debug" additivity="false"
   includeLocation="true">
   <appender-ref ref="trace-log" level="debug" />
   <appender-ref ref="error-log" level="error" />
   <appender-ref ref="console-log" level="info" />
  </Logger>
  <Root level="debug" additivity="false">
   <AppenderRef ref="console-log" />
  </Root>
 </Loggers>
</Configuration>

Log4j2Example class file

package sawalha.log4j2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4j2Example {
    static Logger log = LogManager.getLogger(Log4j2Example.class.getName());

    public static void main(String[] args) throws IOException {
        System.out.println("===> Please enter a number:\n===>");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int number = Integer.valueOf(br.readLine());
        log.info("Info : number is " + number);
        log.warn("Warning : number is " + number);
        log.debug("Debug : number is " + number);
        log.error("Error : number is " + number);
        log.fatal("Fatal : number is " + number);

        if (number > 100) {
            log.info("Info : You chose a number > 100 ");
            log.warn("Warning : You chose a number > 100 ");
            log.debug("Debug : You chose a number > 100 ");
            log.error("Error : You chose a number > 100 ");
            log.fatal("Fatal : You chose a number > 100 ");

        } else {
            log.info("Info : You chose a number < 100 ");
            log.warn("Warning : You chose a number < 100 ");
            log.debug("Debug : You chose a number < 100 ");
            log.error("Error : You chose a number < 100 ");
            log.fatal("Fatal : You chose a number < 100 ");
        }
        String numberStr = String.valueOf(number);
        for (int i = 0; i <= 10; i++) {
            if (numberStr.contains(String.valueOf(i))) {
                log.info("Info : Your number has the digit " + i);
                log.warn("Warning : Your number has the digit " + i);
                log.debug("Debug : Your number has the digit " + i);
                log.error("Error : Your number has the digit " + i);
                log.fatal("Fatal : Your number has the digit " + i);
            }
        }
    }
}