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

📄 ch12.txt

📁 精通Java网络编程代码全部
💻 TXT
📖 第 1 页 / 共 2 页
字号:
/* 代码12-1
 * Created on 2005-5-22
 */

import java.util.*;
import java.io.*;
import java.lang.reflect.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
此程序用来演示类装载器的作用
*/
public class ClassLoaderTest
{
	public static void main(String[] args)
	{
        JFrame frame = new ClassLoaderFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.show();
	}
}

/**
窗口中的两个部分各自为类名,和密钥
*/
class ClassLoaderFrame extends JFrame
{
    public ClassLoaderFrame()
	{
		setTitle("ClassLoaderTest");
		setSize(WIDTH, HEIGHT);
		getContentPane().setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
		gbc.weightx = 0;
		gbc.weighty = 100;
		gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.EAST;
		add(new JLabel("Class"), gbc, 0, 0, 1, 1);
        add(new JLabel("Key"), gbc, 0, 1, 1, 1);
        gbc.weightx = 100;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;
		add(nameField, gbc, 1, 0, 1, 1);
        add(keyField, gbc, 1, 1, 1, 1);
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.CENTER;
        JButton loadButton = new JButton("Load");//添加下载按钮
		add(loadButton, gbc, 0, 2, 2, 1);
        loadButton.addActionListener(new
            ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
                runClass(nameField.getText(), keyField.getText());
			}
		});
    }
	
	/**
	向窗口中添加组件
	@param c the component to add
	@param gbc the grid bag constraints to use
	@param x the x grid position
	@param y the y grid position
	@param w the grid width
	@param h the grid height
	*/
	public void add(Component c, GridBagConstraints gbc,
        int x, int y, int w, int h)
    {
		gbc.gridx = x;
		gbc.gridy = y;
		gbc.gridwidth = w;
        gbc.gridheight = h;
		getContentPane().add(c, gbc);
	}
	
	/**
	运行主程序
	@param name the class name
	@param key the decryption key for the class files
	*/
	public void runClass(String name, String key)
	{
        try
        {
			ClassLoader loader
				= new CryptoClassLoader(Integer.parseInt(key));//设置类装载器
			Class c = loader.loadClass(name);
			String[] args = new String[] {};
			
			Method m = c.getMethod("main",
				new Class[] { args.getClass() });
			m.invoke(null, new Object[] { args });
        }
		catch (Throwable e)
        {
			JOptionPane.showMessageDialog(this, e);
		}
    }
	
    private JTextField keyField = new JTextField("3", 4);//设置文本区
	private JTextField nameField = new JTextField(30);
	private static final int WIDTH = 300;//设置宽度
	private static final int HEIGHT = 200;//设置高度
}

/**
载入加密的类
*/
class CryptoClassLoader extends ClassLoader
{
/**
Constructs a crypto class loader.
@param k the decryption key
    */
    public CryptoClassLoader(int k)
	{
		key = k;
    }
	
    protected Class findClass(String name)
		throws ClassNotFoundException
    {
		byte[] classBytes = null;
		try
		{
			classBytes = loadClassBytes(name);
		}
		catch (IOException exception)
        {
			throw new ClassNotFoundException(name);
		}
		
		Class cl = defineClass(name, classBytes,
			0, classBytes.length);
		if (cl == null)
			throw new ClassNotFoundException(name);
        return cl;
    }
	
    /**
	解析加密的类
	@param name the class name
	@return an array with the class file bytes
    */
	private byte[] loadClassBytes(String name)
		throws IOException
    {
        String cname = name.replace('.', '/') + ".caesar";
		FileInputStream in = null;//文件输入流
        try
		{
			in = new FileInputStream(cname);
			ByteArrayOutputStream buffer
				= new ByteArrayOutputStream();
			int ch;
			while ((ch = in.read()) != -1)
			{
				byte b = (byte)(ch - key);
				buffer.write(b);
			}
			in.close();//关闭输入流
			return buffer.toByteArray();
		}
		finally
		{
			if (in != null)
				in.close();
		}
	}
	
	private Map classes = new HashMap();
	private int key;//设置密钥
}

/* 代码12-2
 * Created on 2005-5-22
 */

import java.io.*;

/**
用恺撒加密方法来加密文件
*/
public class Caesar
{
    public static void main(String[] args)
    {
		if (args.length != 3)
		{
			System.out.println("USAGE: java Caesar in out key");
			return;
		}
		
		try
		{
			FileInputStream in = new FileInputStream(args[0]);//设置输入流
			FileOutputStream out = new FileOutputStream(args[1]);
			int key = Integer.parseInt(args[2]);
			int ch;
			while ((ch = in.read()) != -1)
			{
				byte c = (byte)(ch + key);
				out.write(c);
			}
			in.close();
			out.close();
		}
		catch(IOException exception)
		{
			exception.printStackTrace();
		}
	}
}

/* 代码12-3
 * Created on 2005-5-22
 */

//PermissionTest.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;
import javax.swing.*;

/**
此类证明了经典的WordCheckPermission.
*/
public class PermissionTest
{
    public static void main(String[] args)
    {
		System.setSecurityManager(new SecurityManager());//设置系统安全管理器
		JFrame frame = new PermissionTestFrame();//设置界面
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.show();//显示界面
	}
}

/**
*窗口中的文本框用来检测插入的文字是否合适
*/
class PermissionTestFrame extends JFrame
{
	public PermissionTestFrame()
	{
		setTitle("PermissionTest");//设置标题
		setSize(WIDTH, HEIGHT);//设置大小
		
		textField = new JTextField(20);//设置文本框
		JPanel panel = new JPanel();
		panel.add(textField);
		JButton openButton = new JButton("Insert");
		panel.add(openButton);
		openButton.addActionListener(new
			ActionListener()
		{
            public void actionPerformed(ActionEvent event)
			{
				insertWords(textField.getText());
            }
        });
		
		Container contentPane = getContentPane();
		contentPane.add(panel, BorderLayout.NORTH);//添加组见
		
		textArea = new WordCheckTextArea();//设置新的文本区域
		contentPane.add(new JScrollPane(textArea),
			BorderLayout.CENTER);
	}
	
	/**
    	尝试将文字插入到文本框中
	如果失败跳出对话框
	@param words the words to insert
    */
    public void insertWords(String words)
	{
		try
		{
			textArea.append(words + "\n");//在文本框中添加信息
		}
		catch (SecurityException e)
		{
			JOptionPane.showMessageDialog(this,
				"I am sorry, but I cannot do that.");
		}
	}
	
	private JTextField textField;
    private WordCheckTextArea textArea;
    private static final int WIDTH = 400;//设置宽度
    private static final int HEIGHT = 300;//设置高度
}

/* 代码12-4
 * Created on 2005-5-22
 */

import java.security.*;
import java.util.*;

/**
对于检测“坏句”的权限
*/
public class WordCheckPermission extends Permission
{
	String action;
/**
构建检测权限
@param target a comma separated word list
@param anAction "insert" or "avoid"
	*/
	public WordCheckPermission(String target, String anAction)
	{
		super(target);
		action = anAction;
	}
	
    public String getActions() { return action; }
	
    public boolean equals(Object other)
    {
		if (other == null) return false;
		if (!getClass().equals(other.getClass())) return false;//返回错误情况
		WordCheckPermission b = (WordCheckPermission)other;
		if (!action.equals(b.action)) return false;
		//以下为处理各种情况
		if (action.equals("insert"))
			return getName().equals(b.getName());
		else if (action.equals("avoid"))
			return badWordSet().equals(b.badWordSet());
		else return false;
	}
	
	public int hashCode()
	{
        return getName().hashCode() + action.hashCode();
	}
	//设置权限
	public boolean implies(Permission other)
	{
        if (!(other instanceof WordCheckPermission)) return false;
		WordCheckPermission b = (WordCheckPermission)other;
		if (action.equals("insert"))
		{
			return b.action.equals("insert") &&
				getName().indexOf(b.getName()) >= 0;
		}
        else if (action.equals("avoid"))
        {
			if (b.action.equals("avoid"))
				return b.badWordSet().containsAll(badWordSet());
			else if (b.action.equals("insert"))
			{
				Iterator iter = badWordSet().iterator();
				while (iter.hasNext())
				{
					String badWord = (String)iter.next();
					if (b.getName().indexOf(badWord) >= 0)
						return false;
				}
				return true;
			}
			else return false;
		}
        else return false;
	}



class WordCheckTextArea extends JTextArea
{
    public void append(String text)
    {
		WordCheckPermission p
			= new WordCheckPermission(text, "insert");
		SecurityManager manager = System.getSecurityManager();
		if (manager != null) manager.checkPermission(p);
		super.append(text);
	}
}

/* 代码12-5
 * Created on 2005-5-22
 */

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
//权限管理器检测
public class SecurityManagerTest
{
	public static void main(String[] args)
	{
        System.setSecurityManager(new WordCheckSecurityManager());
		JFrame frame = new SecurityManagerFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.show();
	}
}

/**
此窗口拥有一个文本框来输入文件名以及表示被下载文件的内容
*/
class SecurityManagerFrame extends JFrame
{

⌨️ 快捷键说明

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