⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 decryptpanel.java

📁 Java version of ABC/HR comparator v0.5. by schnofler. Runs on Sun JRE 1.5 or later
💻 JAVA
字号:
package abchr.gui;

import abchr.ResultIO;
import abchr.ScrambledResultIO;
import abchr.TxtResultIO;
import abchr.XMLResultIO;
import guiutils.*;
import org.jdom.Document;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class DecryptPanel extends JPanel {
	private JTextField keyFileTextField;
	private FileList resultFileList;
	private JTextField outputMaskField;
	private JCheckBox recurseCheckBox;
	private JCheckBox overwriteCheckBox;
	private JCheckBox translateCheckBox;

	public DecryptPanel() {
		super(new BorderLayout());

		JPanel centerPanel=new JPanel(new BorderLayout());
		centerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
		SimpleFileChooser fileChooser=new SimpleFileChooser(new OrFileFilter(new FileFilter[] {
			new SimpleFileFilter(".erf","Encrypted Result Files"),
			new SimpleFileFilter(".arf","ABC/HR XML Result Files"),
			new SimpleFileFilter(".xml","ABC/HR XML Result Files"),
			new SimpleFileFilter(".txt","Plain Text Result Files")
		},"Result Files (*.erf, *.arf, *.xml, *.txt)"));
		fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		resultFileList=new FileList(fileChooser);
		centerPanel.add(resultFileList,BorderLayout.CENTER);

		JPanel controlPanel=new JPanel(new FlexibleGridLayout(5,1,5,5,true));
		controlPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

		JPanel p=new JPanel(new BorderLayout(5,5));
		p.add(new JLabel("Key File: "),BorderLayout.WEST);
		keyFileTextField=new JTextField(25);
		p.add(keyFileTextField,BorderLayout.CENTER);
		fileChooser=new SimpleFileChooser(new SimpleFileFilter(".key","Key files (*.key)"));
		p.add(new TextFieldBrowseButton(this,fileChooser,keyFileTextField,false),BorderLayout.EAST);
		controlPanel.add(p);

		recurseCheckBox=new JCheckBox("Recurse subdirectories",true);
		overwriteCheckBox=new JCheckBox("Ask before overwriting",true);
		translateCheckBox=new JCheckBox("Translate XML to txt",true);
		controlPanel.add(recurseCheckBox);
		controlPanel.add(overwriteCheckBox);
		controlPanel.add(translateCheckBox);

		p=new JPanel(new BorderLayout(5,0));
		p.add(new JLabel("Output file mask: "),BorderLayout.WEST);
		outputMaskField=new JTextField("$FILENAME$",25);
		p.add(outputMaskField,BorderLayout.CENTER);
		controlPanel.add(p);

		JTextArea descriptionPane=new JTextArea();
		descriptionPane.setWrapStyleWord(true);
		descriptionPane.setLineWrap(true);
		descriptionPane.setText(
			"Use slashes/backslashes in output file mask " +
			"to create directory structures.\n\n" +
			"The following variables are available:\n" +
			"$FILENAME$ = The original filename sans extension.\n" +
			"     results05.erf -> results05\n" +
			"$DIRECTORY$ = The name of the parent directory.\n" +
			"     c:\\results\\sample01\\results.txt -> sample01\n" +
			"$TESTNAME$ = The test name as mentioned in the\n" +
			"     result file.\n" +
			"$TESTER$ = The tester's name if mentioned in the \n" +
			"     results file.\n" +
			"     If no name is mentioned, this field is omitted.\n\n" +
			"Example: c:\\results\\$TESTNAME$\\$FILENAME$\n" +
			"     keeps filenames and sorts files by sample."
		);
		descriptionPane.setBackground(UIManager.getColor("Panel.background"));
		controlPanel.add(descriptionPane);

		p=new JPanel(new LineLayout(LineLayout.CENTER));
		JButton processButton=new JButton("Process");
		processButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e){process();}
		});
		p.add(processButton);
		controlPanel.add(p);

		this.add(controlPanel,BorderLayout.WEST);
		this.add(centerPanel,BorderLayout.CENTER);
	}

	private java.util.List fileList=new ArrayList();
	private boolean overwrite;

	private void process() {
		String s=validateFileMask();
		if(s!=null) {
			JOptionPane.showMessageDialog(this,"Invalid file mask: "+s,"Error",JOptionPane.ERROR_MESSAGE);
			return;
		}
		keyLoaded=false;
		errorList.clear();
		fileList.clear();
		overwrite=!overwriteCheckBox.isSelected();
		File[] files=resultFileList.getFiles();
		for(int i=0;i<files.length;i++) {
			gatherFiles(files[i]);
		}
		try {
			for(int i=0;i<fileList.size();i++) {
				process((File)fileList.get(i));
			}
		} catch(IOException e) {
			JOptionPane.showMessageDialog(this,"I/O error: "+e.getMessage(),"I/O error",JOptionPane.ERROR_MESSAGE);
		} catch(CancelledException e){}
		if(!errorList.isEmpty()) {
			StringBuffer errors=new StringBuffer();
			ProcessingError e;
			for(int i=0;i<errorList.size();i++) {
				e=(ProcessingError)errorList.get(i);
				errors.append(e.f+": "+e.e.getMessage()+'\n');
			}
			JOptionPane.showMessageDialog(this,"These files caused errors: \n"+errors,"Processing errors",JOptionPane.ERROR_MESSAGE);
		}
	}

	private String validateFileMask() {
		String s=outputMaskField.getText();
		if(s.equals("")){return "Output file mask must not be empty.";}
		if(s.indexOf("\\\\")!=-1 || s.indexOf("//")!=-1){return "Something's wrong with the path separators.";}
		if(s.indexOf("\\")!=-1 && s.indexOf("/")!=-1){return "Use either slashes or backslashes.";}
		int i=-1;
		int n=0;
		while((i=s.indexOf('$',i+1))!=-1){n++;}
		if(n%2!=0){return "Unmatched variable delimiter ($).";}
		return null;
	}

	private void gatherFiles(File f) {
		if(f.isDirectory()) {
			File[] files=f.listFiles();
			for(int i=0;i<files.length;i++) {
				if(recurseCheckBox.isSelected() || !files[i].isDirectory()) {
					gatherFiles(files[i]);
				}
			}
		} else {
			fileList.add(f);
		}
	}

	private boolean keyLoaded=false;
	private ScrambledResultIO srio=new ScrambledResultIO();

	private static class ProcessingError {
		public File f;
		public Exception e;

		public ProcessingError(File f,Exception e) {
			this.e=e;
			this.f=f;
		}

		public Exception getException(){return e;}
		public File getFile(){return f;}
	}
	private java.util.List errorList=new ArrayList();

	private static String readFile(File f) throws IOException {
		BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(f)));
		StringBuffer buffer=new StringBuffer();
		char[] buf=new char[512];
		int n=reader.read(buf);
		while(n!=-1) {
			buffer.append(buf,0,n);
			n=reader.read(buf);
		}
		return buffer.toString();
	}

	private static class CancelledException extends RuntimeException {}

	private void process(File f) throws IOException {
		Map fieldsMap=new HashMap();
		String name=f.getName();
		if(name.indexOf('.')!=-1){name=name.substring(0,name.lastIndexOf('.'));}
		fieldsMap.put("FILENAME",name);
		fieldsMap.put("DIRECTORY",f.getParentFile().getName());
		if(f.getName().endsWith(".erf") || f.getName().endsWith(".arf") || f.getName().endsWith(".xml")) {
			ResultIO inRIO;
			if(f.getName().endsWith(".erf")) {
				if(!keyLoaded) {
					try {
						srio.readKey(new File(keyFileTextField.getText()));
						keyLoaded=true;
					} catch(IOException e) {
						throw new IOException("Key file could not be opened.");
					}
				}
				inRIO=srio;
			} else {
				inRIO=new XMLResultIO();
			}
			try {
				FileInputStream fis=new FileInputStream(f);
				Document doc=inRIO.readConfig(fis);
				fis.close();
				getFieldsXML(doc,fieldsMap);
				ResultIO rio;
				if(translateCheckBox.isSelected()) {
					rio=new TxtResultIO();
				} else {
					rio=new XMLResultIO();
				}
				String filename=getFilename(fieldsMap)+(translateCheckBox.isSelected()?".txt":".arf");
				File outFile=makeOutFile(f,filename);
				if(validateFile(outFile)==OVERWRITE) {
//					System.out.println(outFile);
					if(outFile.exists()){outFile.delete();}
					FileOutputStream out=new FileOutputStream(outFile);
					rio.writeConfig(out,doc);
					out.close();
				}
			} catch(IOException e) {
				errorList.add(new ProcessingError(f,e));
			}
		} else if(f.getName().endsWith(".txt")) {
			String s=readFile(f);
			if(s.startsWith("ABC/HR")) {
				getFieldsPlainText(s,fieldsMap);
				String filename=getFilename(fieldsMap)+".txt";
				File outFile=makeOutFile(f,filename);
				if(validateFile(outFile)==OVERWRITE) {
					//System.out.println(outFile);
					if(outFile.exists()){outFile.delete();}
					try {
						copy(f,outFile);
					} catch(IOException e) {
						errorList.add(new ProcessingError(f,new IOException("Could not copy file to "+outFile)));
					}
				}
			} else {
				errorList.add(new ProcessingError(f,new IOException("Not an ABC/HR results file.")));
			}
		}
	}

	private static File makeOutFile(File f,String filename) {
		File outFile=new File(filename);
		if(!outFile.isAbsolute()) {
			outFile=new File(f.getParent(),outFile.toString());
		}
		if(!outFile.getParentFile().exists()){outFile.getParentFile().mkdirs();}
		return outFile;
	}

	private static void copy(File f,File outFile) throws IOException {
		BufferedOutputStream outStream=new BufferedOutputStream(new FileOutputStream(outFile));
		BufferedInputStream inStream=new BufferedInputStream(new FileInputStream(f));
		byte[] buffer=new byte[1024];
		int n=inStream.read(buffer);
		while(n!=-1) {
			outStream.write(buffer,0,n);
			n=inStream.read(buffer);
		}
		inStream.close();
		outStream.close();
	}

	private static final int OVERWRITE=0;
	private static final int SKIP=1;
	private static final int CANCEL=2;

	private int validateFile(File outFile) throws CancelledException {
		if(overwrite || !outFile.exists()){return OVERWRITE;}
		Object[] options=new Object[] {
			"Overwrite","Skip","Cancel"
		};
		int n=JOptionPane.showOptionDialog(this,
			"File "+outFile+" already exists.\nIt's up to you:",
			"File exists",
			JOptionPane.YES_NO_CANCEL_OPTION,
			JOptionPane.WARNING_MESSAGE,
			null,
			options,
			options[0]
		);
		switch(n) {
			case JOptionPane.YES_OPTION:return OVERWRITE;
			case JOptionPane.NO_OPTION:return SKIP;
			case JOptionPane.CANCEL_OPTION:
			case JOptionPane.CLOSED_OPTION:throw new CancelledException();
		}
		return CANCEL;
	}

	private static void getFieldsPlainText(String s,Map m) {
		BufferedReader reader=new BufferedReader(new StringReader(s));
		try {
			for(int i=0;i<5;i++) {
				String line=reader.readLine();
				if(line.startsWith("Testname")) {
					m.put("TESTNAME",line.substring(10).trim());
				} else if(line.startsWith("Tester")) {
					m.put("TESTER",line.substring(7).trim());
				}
			}
		} catch(IOException e) {
			e.printStackTrace();
		}
	}

	private static void getFieldsXML(Document doc,Map m) {
		m.put("TESTNAME",doc.getRootElement().getChildText("TestName"));
		String s=doc.getRootElement().getChildText("TesterName");
		if(s!=null){m.put("TESTER",s);}
	}

	private String getFilename(Map fieldMap) {
		String mask=outputMaskField.getText();
		StringBuffer filename=new StringBuffer();
		int i=0;
		int j=-1;
		while((i=mask.indexOf('$',j+1))!=-1) {
			filename.append(mask.substring(j+1,i));
			j=mask.indexOf('$',i+1);
			String var=mask.substring(i+1,j);
			String val=(String)fieldMap.get(var);
			if(val!=null){filename.append(val);}
		}
		filename.append(mask.substring(j+1,mask.length()));
		return filename.toString();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -