`
vortexchoo
  • 浏览: 67087 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

compare local files and remote files.

    博客分类:
  • java
 
阅读更多

最近发生了一件怪事,项目在本地run的时候会报一个jar包下找不到某个class的错误,然而同样的project promote到远程服务器上 是ok的,于是就怀疑会不会是远程服务器上的jar包 跟本地的有差别,于是乎写下了这个东西。

 

只是一个basic的版本,可以再加点内容完善的。

 

需要的jar包 

 

连接linux remote server要用的:

ganymed-ssh2.jar

因为我是导出了excel 所以用了POI

poi.jar

 

 

Utils 类

写道
package org.vic.util;

import java.util.Collection;
import java.util.Collections;

public class Utils {

public static <T> Collection<T> ifNullReturnEmpty(Collection<T> collection) {
return collection == null ? Collections.emptyList() : collection;
}

}

 DTO: 数据行结构

 

package org.vic.dto;

public class Row {
	
	private String fileName;
	
	private int fileAmount;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public int getFileAmount() {
		return fileAmount;
	}

	public void setFileAmount(int fileAmount) {
		this.fileAmount = fileAmount;
	}
	
}

 主功能类:

package org.vic.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import org.vic.dto.Row;
import org.vic.util.Utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class Comparator {
	
	/**
	 * 
	 * @param remoteFolderPath 远程服务目标文件夹路径
	 * @param remoteIp         远程服务器IP
	 * @param remoteUsername   远程服务器登陆用户名
	 * @param remotePassword   远程服务器登陆密码
	 * @param localFolderPath  本地目标文件夹路径
	 * @param excelFilePath    导出结果excel文件路径
	 * @throws Exception       抛出一场
	 */
	public void getDifferentFiles(String remoteFolderPath, String remoteIp, String remoteUsername, String remotePassword, String localFolderPath, String excelFilePath) throws Exception {
		System.out.println("start searching local files");
		List<String> localFileNames = getLocalFileNames(localFolderPath);
		System.out.println("start searching remote files");
		List<String> remoteFileNames = getRemoteFileNames(remoteFolderPath, remoteIp, remoteUsername, remotePassword);
		System.out.println("merging data");
		Set<String> totalSet = new HashSet<String>();
		totalSet.addAll(localFileNames);
		totalSet.addAll(remoteFileNames);
		List<Row> localFileInfo = new ArrayList<Row>();
		List<Row> remoteFileInfo = new ArrayList<Row>();
		System.out.println("creating rows");
		for(String fileName : Utils.ifNullReturnEmpty(localFileNames)){
			Row row = fileInfoProcesser(fileName, localFileNames);
			localFileInfo.add(row);
		}
		for(String fileName : Utils.ifNullReturnEmpty(remoteFileNames)){
			Row row = fileInfoProcesser(fileName, remoteFileNames);
			remoteFileInfo.add(row);
		}
		System.out.println("generating excel file...");
		excelCreater(localFileInfo, remoteFileInfo, excelFilePath, totalSet);
		System.out.println("generating finished, please read the file in : " + excelFilePath);
	}
	
	private void excelCreater(List<Row> localList, List<Row> remoteList, String exportFilePath, Set<String> totalSet) {
		HSSFWorkbook wb = new HSSFWorkbook();  
        HSSFSheet sheet = wb.createSheet("comparator"); 
        sheet.setColumnWidth(0, 100 * 180);
        sheet.setColumnWidth(1, 100 * 50);
        sheet.setColumnWidth(2, 100 * 180);
        sheet.setColumnWidth(3, 100 * 50);
        HSSFRow row = sheet.createRow((int) 0);  
        HSSFCellStyle style = wb.createCellStyle();  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font titleFont = wb.createFont();
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);
        HSSFCellStyle differentStyle = wb.createCellStyle();
        differentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font font = wb.createFont();
        font.setColor(Font.COLOR_RED);
        differentStyle.setFont(font);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("localFileName");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("localFileAmount");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("remoteFileName");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("remoteFileAmount");
        cell.setCellStyle(style);
        HSSFCellStyle dataStyle = wb.createCellStyle();  
        dataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font dataFont = wb.createFont();
        dataFont.setColor(HSSFColor.BLUE.index);
        dataStyle.setFont(dataFont);
        List<String> archList = new ArrayList<String>();
        archList.addAll(totalSet);
        for(int i = 0; i < archList.size(); i ++) {
        	row = sheet.createRow(i + 1);  
        	String fileName = archList.get(i);
        	Row localRowData = findRowByFileName(fileName, localList);
        	Row remoteRowData = findRowByFileName(fileName, remoteList);
        	HSSFCell cell0 = row.createCell(0);
        	cell0.setCellStyle(dataStyle);
        	cell0.setCellValue(localRowData.getFileName());
        	HSSFCell cell1 = row.createCell(1);
        	cell1.setCellStyle(dataStyle);
        	cell1.setCellValue(localRowData.getFileAmount());
        	HSSFCell cell2 = row.createCell(2);
        	cell2.setCellStyle(dataStyle);
        	cell2.setCellValue(remoteRowData.getFileName());
        	HSSFCell cell3 = row.createCell(3);
        	cell3.setCellStyle(dataStyle);
        	cell3.setCellValue(remoteRowData.getFileAmount());
            if(!localRowData.getFileName().equals(remoteRowData.getFileName()) || localRowData.getFileAmount() != remoteRowData.getFileAmount()) {
            	cell0.setCellStyle(differentStyle);
            	cell1.setCellStyle(differentStyle);
            	cell2.setCellStyle(differentStyle);
            	cell3.setCellStyle(differentStyle);
            	
            }
        }
        
        try {
        	File file = new File(exportFilePath);
        	if(!file.exists()) {
        		file.createNewFile();
        	}
			FileOutputStream fos = new FileOutputStream(exportFilePath);
			wb.write(fos);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private Row findRowByFileName(String fileName, List<Row> fileList) {
		for(Row row : fileList) {
			if(fileName.equals(row.getFileName())){
				return row;
			}
		}
		Row empty = new Row();
		empty.setFileName("--");
		empty.setFileAmount(0);
		return empty;
	}
	
	private Row fileInfoProcesser(String fileName, List<String> fileList) {
		Row row = new Row();
		int count = 0;
		for(String file : Utils.ifNullReturnEmpty(fileList)) {
			if(file.equals(fileName)) {
				count ++;
			}
		}
		row.setFileName(fileName);
		row.setFileAmount(count);
		return row;
	}
	
	private List<String> getLocalFileNames(String localFolderPath) throws Exception {
		List<String> result = new ArrayList<String>();
		File file = new File(localFolderPath);
		if(file.exists()) {
			if(file.isDirectory()) {
				File[] files = file.listFiles();
				if(file != null && file.length() > 0) {
					for (File subFile : files) {
						String fileName = subFile.getName();
						result.add(fileName);
					}
				}
			} else {
				throw new Exception("path is a file, not a directory!");
			}
		} else {
			throw new Exception("folder is not existing!");
		}
		return result;
	}
	
	private List<String> getRemoteFileNames(String remoteFolderPath, String remoteIp, String remoteUsername, String remotePassword) throws IOException {
		List<String> result = new ArrayList<String>();
		Connection conn = new Connection(remoteIp);
		conn.connect();
        boolean isAuthenticated = conn.authenticateWithPassword(remoteUsername, remotePassword);
        if (isAuthenticated == false) throw new IOException("Authentication failed.");
        Session session = conn.openSession();
        String commands = "cd " + remoteFolderPath + "&&ls";
        session.execCommand(commands);
        InputStream stdout = new StreamGobbler(session.getStdout());
		@SuppressWarnings("resource")
		BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
		String tmp = null;
		while ((tmp = br.readLine()) != null) {
			String fileName = tmp;
			fileName = fileName.replace("Shell Message : ", "");
			result.add(fileName);
		}
        session.close();
        conn.close();
		return result;
	}
	
	/**
	 * Execution Entrance
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		Comparator c = new Comparator();
		
		c.getDifferentFiles("/remoteServer/project/lib", "xx.xx.xx.xx", "username", "password", "local/project/lib", "excel/result.xls");
	}
}

 

 

分享到:
评论

相关推荐

    UE(官方下载)

    UEStudio and UltraEdit provide a way for you to search and delete found lines from your files. This short tutorial provides the steps for searching for and deleting lines by writing a simple script. ...

    PrimalScript.2012.v6.5.144.Cracked.by.yoza[

    And of course the remote debugger is just as multi-platform as the local version. PrimalSense Unsurpassed code-completion and instant help features guide you through developing more complex ...

    Cornerstone_2.7.18 破解补丁(Mac)

    • Displays local and remote file status • Quick Look working copy files • Powerful filtering by modification and lock status as well as by file name • Configure which application to open files ...

    Manning.Git.in.Practice.2014.9.pdf

    The `git fetch` command retrieves changes from a remote repository, and `git checkout -b &lt;branch-name&gt; origin/&lt;remote-branch&gt;` creates a local branch from a remote branch. - **Remote Collaboration**:...

    ZendFramework中文文档

    14.5.3. Retrieving Validated Fields and other Reports 14.5.3.1. Querying if the input is valid 14.5.3.2. Getting Invalid, Missing, or Unknown Fields 14.5.3.3. Getting Valid Fields 14.5.4. Using ...

    Linux for Developers: Jumpstart Your Linux Programming Skills

    Linux for Developers: Jumpstart Your Linux Programming Skills ...Manage local and remote GIT repositories This guide’s modular coverage helps you quickly access whatever information you need right now.

    gun tar for windows

    GNU `tar' saves many files together into a single tape or disk archive, and can restore individual files from the archive. Usage: tar [OPTION]... [FILE]... If a long option shows an argument as ...

    雷达技术知识

    measure local water surface slopes within the active channel. Much of the reason that researchers have not attempted to measure water surface slopes with LiDAR is because most LiDAR pulses are ...

    MS-DOS 5.0

    Name the files DMDRVR.BIN and XBIOS.OVL. 3. Run Setup with the /u switch, as follows: setup /u 2.5 SpeedStor and Volume Expansion ---------------------------------- To upgrade Storage Dimensions'...

    svn学习手册,版本控制教程

    - **Compare 2 Files**: 比较两个文件之间的差异。 - **Change Report**: 生成变更报告。 - **Log**: 查看文件或目录的历史记录。 - **Annotate**: 显示文件中每行的版本信息和作者。 - **Create Patch**: 生成补丁...

Global site tag (gtag.js) - Google Analytics