--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="lib" path="lib/commons-logging-1.1.1-javadoc.jar"/>
+ <classpathentry kind="lib" path="lib/commons-logging-1.1.1-sources.jar"/>
+ <classpathentry kind="lib" path="lib/commons-logging-1.1.1.jar"/>
+ <classpathentry kind="lib" path="lib/commons-logging-adapters-1.1.1.jar"/>
+ <classpathentry kind="lib" path="lib/commons-logging-api-1.1.1.jar"/>
+ <classpathentry kind="lib" path="lib/commons-logging-tests.jar"/>
+ <classpathentry kind="lib" path="lib/log4j-1.2.16.jar"/>
+ <classpathentry kind="lib" path="lib/junit-4.5.jar"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>kona</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
--- /dev/null
+#Tue Feb 07 11:35:37 EST 2012
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
--- /dev/null
+# don't limit by the logging level, and use two appenders.\r
+log4j.rootCategory=, TTY, LOGFILE\r
+\r
+# TTY is set to be a ConsoleAppender using a PatternLayout.\r
+log4j.appender.TTY=org.apache.log4j.ConsoleAppender\r
+log4j.appender.TTY.Threshold=DEBUG\r
+log4j.appender.TTY.layout=org.apache.log4j.PatternLayout\r
+log4j.appender.TTY.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%-28c{2}] - %m%n\r
+\r
+# LOGFILE is set to be a RollingFileAppender using a PatternLayout.\r
+log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender\r
+log4j.appender.LOGFILE.File=dragdrop_test.log\r
+log4j.appender.LOGFILE.MaxFileSize=10MB\r
+log4j.appender.LOGFILE.MaxBackupIndex=10\r
+log4j.appender.LOGFILE.Threshold=DEBUG\r
+log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout\r
+log4j.appender.LOGFILE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%-28c{2}] - %m%n\r
+\r
--- /dev/null
+package org.feistymeow.dragdrop;
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.util.List;
+
+import javax.swing.JComponent;
+import javax.swing.TransferHandler;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * A transfer handler that can be extended and used to inter-operate with DragonDropManager. This
+ * object is not strictly necessary to use, but it can help if one has not already implemented one's
+ * own transfer handler.
+ *
+ * @author Chris Koeritz
+ * @copyright Copyright (c) 2012-$now By University of Virginia
+ * @license This file is free software; you can modify and redistribute it under the terms of the
+ * Apache License v2.0: http://www.apache.org/licenses/LICENSE-2.0
+ */
+@SuppressWarnings("serial")
+public class DragonTransferHandler extends TransferHandler
+{
+ static private Log logger = LogFactory.getLog(DragonTransferHandler.class);
+ IDragonDropDataProvider c_provider;
+
+ public DragonTransferHandler(IDragonDropDataProvider provider)
+ {
+ c_provider = provider;
+ }
+
+ @Override
+ public boolean canImport(TransferSupport support)
+ {
+ if (support == null) return false;
+ if (!support.isDrop())
+ return false; // we don't support cut&paste here.
+ logger.debug("canImport: base just saying okay.");
+ return true;
+ }
+
+ @Override
+ protected Transferable createTransferable(JComponent c)
+ {
+ logger.debug("createTransferable: at base, returning ListTransferable.");
+ return new ListTransferable(c_provider.provideDragList());
+ }
+
+ @Override
+ protected void exportDone(JComponent source, Transferable data, int action)
+ {
+ logger.debug("exportDone: base got event for component " + source.toString());
+ }
+
+ @Override
+ public int getSourceActions(JComponent c)
+ {
+ return COPY;
+ }
+
+ @Override
+ public boolean importData(TransferSupport support)
+ {
+ if (support == null) return false;
+ logger.debug("importData: at base...");
+
+ if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
+ logger.debug("importing data with java files flavor");
+ List<Object> files = ListTransferable.extractData(support.getTransferable());
+ if ((files != null) && (files.size() != 0)) {
+ c_provider.consumeDropList(files, support.getDropLocation().getDropPoint());
+ return true;
+ }
+ } else if (support.isDataFlavorSupported(ListTransferable.getURIListFlavor1())
+ || support.isDataFlavorSupported(ListTransferable.getURIListFlavor2())) {
+ logger.debug("importing data with uri list flavor");
+ List<Object> files = ListTransferable.extractData(support.getTransferable());
+ if ((files != null) && (files.size() != 0)) {
+ c_provider.consumeDropList(files, support.getDropLocation().getDropPoint());
+ return true;
+ }
+ }
+ logger.warn("passing importData request to superclass, which will probably fail.");
+ return super.importData(support);
+ }
+}
--- /dev/null
+package org.feistymeow.dragdrop;
+
+import java.util.List;
+import java.awt.Point;
+
+/**
+ * An interface for any object that can interact with a DragonTransferSupport to receive files (or
+ * other things) that are dropped on it and that can provide files (or other things) for dragging to
+ * another location. Note that the details of finding a selected node or determining what objects
+ * are relevant there is entirely up to the component. You probably do not need this interface if
+ * you have implemented your own TransferHandler.
+ *
+ * @author Chris Koeritz
+ * @copyright Copyright (c) 2012-$now By University of Virginia
+ * @license This file is free software; you can modify and redistribute it under the terms of the
+ * Apache License v2.0: http://www.apache.org/licenses/LICENSE-2.0
+ */
+public interface IDragonDropDataProvider
+{
+ /**
+ * A function that is invoked by the handler when some files or other objects are being dragged
+ * out of the parent. The handler expects the real provider to come up with a useful set of
+ * things to deliver at the drag target.
+ */
+ public List<Object> provideDragList();
+
+ /**
+ * A function that is invoked by the d&d manager when a passel of objects have been dropped on
+ * the parent object.
+ */
+ public boolean consumeDropList(List<Object> dropSet, Point cursor);
+}
--- /dev/null
+package org.feistymeow.dragdrop;
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Vector;
+import java.util.StringTokenizer;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Implements a transferable object that understands URI lists as well as java file lists. This is
+ * useful for implementing file drag and drop that will work across different platforms (such as
+ * Gnome on Linux).
+ *
+ * @author Chris Koeritz
+ * @copyright Copyright (c) 2012-$now By University of Virginia
+ * @license This file is free software; you can modify and redistribute it under the terms of the
+ * Apache License v2.0: http://www.apache.org/licenses/LICENSE-2.0
+ */
+@SuppressWarnings("serial")
+public class ListTransferable extends Vector<Object> implements Transferable
+{
+ static private Log logger = LogFactory.getLog(ListTransferable.class);
+
+ public ListTransferable()
+ {
+ }
+
+ public ListTransferable(Object initial)
+ {
+ if (initial != null) add(initial);
+ }
+
+ public ListTransferable(List<Object> initial)
+ {
+ if (initial != null) addAll(initial);
+ }
+
+ /**
+ * create a new flavor. this one understands URI lists, such as: file:///home/fred/arf.txt\r\n
+ * file:///etc/inputrc\r\n http://gruntose.com\r\n ...
+ */
+ private static DataFlavor URIListFlavor;
+ static {
+ try {
+ URIListFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
+ } catch (ClassNotFoundException e) {
+ logger.error("should never happen", e);
+ }
+ }
+ private static DataFlavor AltURIListFlavor;
+ static {
+ try {
+ AltURIListFlavor = new DataFlavor("text/uri-list;representationclass=java.lang.String");
+ } catch (ClassNotFoundException e) {
+ logger.error("should never happen", e);
+ }
+ }
+
+ /**
+ * accessors for our special featured flavors of URI lists.
+ */
+ public static DataFlavor getURIListFlavor1()
+ {
+ return URIListFlavor;
+ }
+
+ public static DataFlavor getURIListFlavor2()
+ {
+ return AltURIListFlavor;
+ }
+
+ /**
+ * register the types of transfers that we understand. this is really only the normal java file
+ * list and our new URI list.
+ */
+ protected ArrayList<DataFlavor> FLAVORS = new ArrayList<DataFlavor>(Arrays.asList(
+ DataFlavor.javaFileListFlavor, URIListFlavor, AltURIListFlavor));
+
+ /**
+ * a function that must be overridden by derived classes if they are not initially seeding the
+ * vector of objects that we hold. the caller of this function expects it will populate the
+ * vector held here with usable objects.
+ */
+ public boolean loadDataJustInTime(DataFlavor flavor)
+ {
+ logger.warn("base loadDataJustInTime. derived class should have implemented this.");
+ return false;
+ }
+
+ /**
+ * using the set of files that we've been handed, we can do transfers using our two supported
+ * flavors.
+ */
+ public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException,
+ java.io.IOException
+ {
+ if (flavor == null) return null;
+ if (size() == 0) {
+ logger.debug("size was zero, so loading data just in time");
+ boolean worked = loadDataJustInTime(flavor);
+ if (!worked || (size() == 0)) {
+ logger.warn("failed to retrieve data just in time for getTransferData.");
+ return null;
+ }
+ }
+ // help from workaround at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4899516
+ logger.debug("responding to flavor: " + flavor.toString());
+ if (flavor.equals(DataFlavor.javaFileListFlavor)) {
+ logger.debug("java file list flavor...");
+ List<Object> data = new java.util.ArrayList<Object>();
+ data.addAll(this);
+ return data;
+ } else if (flavor.equals(URIListFlavor) || flavor.equals(AltURIListFlavor)) {
+ logger.debug("uri list flavor...");
+ StringBuilder data = new StringBuilder();
+ Iterator<Object> iter = iterator();
+ while (iter.hasNext()) {
+ Object x = iter.next();
+ if (x instanceof File) {
+ File elem = (File) x;
+ data.append(elem.toURI() + "\r\n");
+ } else if (x instanceof String) {
+ data.append((String) x + "\r\n");
+ } else {
+ logger.debug("did not know how to handle type in transfer: " + x.toString());
+ }
+ }
+ logger.debug("returning URI string: " + data.toString());
+ return data.toString();
+ } else {
+ logger.debug("getTransferData: didn't know how to handle the requested flavor.");
+ throw new UnsupportedFlavorException(flavor);
+ }
+ }
+
+ /**
+ * returns the list of all transfer flavors we understand.
+ */
+ public DataFlavor[] getTransferDataFlavors()
+ {
+ return (DataFlavor[]) FLAVORS.toArray(new DataFlavor[FLAVORS.size()]);
+ }
+
+ /**
+ * reports if a particular flavor is handled here.
+ */
+ public boolean isDataFlavorSupported(DataFlavor flavor)
+ {
+ if (flavor == null) return false;
+ for (int i = 0; i < FLAVORS.size(); i++) {
+ if (flavor.equals((DataFlavor) FLAVORS.get(i))) {
+ return true;
+ }
+ }
+ logger.debug("failed to find flavor: " + flavor.toString());
+ return false;
+ }
+
+ /**
+ * a helper method that can process transfer data from either a java file list or a URI list.
+ */
+ @SuppressWarnings("unchecked")
+ static public List<Object> extractData(Transferable tran) {
+ if (tran == null) return null;
+ if (tran.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
+ logger.debug("extractData seeing java files flavor.");
+ try {
+ return (List<Object>) tran.getTransferData(DataFlavor.javaFileListFlavor);
+ } catch (Throwable cause) {
+ logger.error("extractData caught exception for java file list.", cause);
+ return null;
+ }
+ } else if (tran.isDataFlavorSupported(ListTransferable.getURIListFlavor1())
+ || tran.isDataFlavorSupported(ListTransferable.getURIListFlavor2())) {
+ logger.debug("extractData seeing uri list flavor.");
+ try {
+ return textURIListToFileList((String) tran.getTransferData(getURIListFlavor1()));
+ } catch (Throwable cause) {
+ logger.error("extractData caught exception for URI list.", cause);
+ return null;
+ }
+ }
+ logger.error("extractData: Transferable did not support known data flavor.");
+ return null;
+ }
+
+ /**
+ * translates the string in "data" into a list of Files.
+ *
+ * @param data
+ * a string formatted with possibly multiple URIs separated by CRLF.
+ * @return a list of the files as java File objects. many thanks to
+ * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4899516
+ */
+ public static List<Object> textURIListToFileList(String data)
+ {
+ if (data == null) return null;
+ List<Object> list = new ArrayList<Object>(0);
+ for (StringTokenizer st = new StringTokenizer(data, "\r\n"); st.hasMoreTokens();) {
+ String s = st.nextToken();
+ if (s.startsWith("#")) {
+ // the line is a comment (as per the RFC 2483)
+ continue;
+ }
+ try {
+ java.net.URI uri = new java.net.URI(s);
+ java.io.File file = new java.io.File(uri);
+ list.add(file);
+ } catch (java.net.URISyntaxException e) {
+ // this is a malformed URI.
+ logger.error("Found a malformed URI of: " + data);
+ } catch (IllegalArgumentException e) {
+ // the URI is not a valid 'file:' URI
+ logger.error("Found invalid 'file:' URI of: " + data);
+ }
+ }
+ return list;
+ }
+
+ /**
+ * This function will retrieve the file list from a standard file list flavor.
+ */
+ @SuppressWarnings("unchecked")
+ public static List<Object> processStandardFileList(Transferable tran)
+ {
+ if (tran == null) return null;
+ logger.debug("trying java file list flavor.");
+ try {
+ return (List<Object>) tran.getTransferData(DataFlavor.javaFileListFlavor);
+ } catch (Throwable cause) {
+ logger.debug("failed to retrieve transfer data for standard java file list flavor.",
+ cause);
+ }
+ return new ArrayList<Object>();
+ }
+
+ /**
+ * checks if the transferable is appropriate to try to use as a java Reader.
+ */
+ public static boolean checkReaderFlavor(Transferable tran)
+ {
+ if (tran == null) return false;
+ DataFlavor[] flavors = tran.getTransferDataFlavors();
+ for (int i = 0; i < flavors.length; i++) {
+ if (flavors[i].isRepresentationClassReader())
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Use a Reader to handle an incoming transferable.
+ */
+ public static List<Object> processReaderFlavor(Transferable tran)
+ {
+ if (tran == null) return null;
+ logger.debug("trying URI list flavor.");
+ DataFlavor[] flavors = tran.getTransferDataFlavors();
+ for (int i = 0; i < flavors.length; i++) {
+ if (flavors[i].isRepresentationClassReader()) {
+ // it looks like we can work with this flavor just fine.
+ logger.debug("found a reader flavor.");
+ try {
+ Reader reader = flavors[i].getReaderForText(tran);
+ BufferedReader br = new BufferedReader(reader);
+ return createFileArray(br);
+ } catch (Throwable cause) {
+ logger.debug("failed to scan reader for file list.");
+ }
+ }
+ }
+ return new ArrayList<Object>();
+ }
+
+ private static String ZERO_CHAR_STRING = "" + (char) 0;
+
+ public static List<Object> createFileArray(BufferedReader bReader) {
+ if (bReader == null) return null;
+ try {
+ List<Object> list = new ArrayList<Object>();
+ String line = null;
+ while ((line = bReader.readLine()) != null) {
+ try {
+ // kde seems to append a 0 char to the end of the reader
+ if (ZERO_CHAR_STRING.equals(line))
+ continue;
+ File file = new java.io.File(new java.net.URI(line));
+ list.add(file);
+ } catch (Exception ex) {
+ logger.error("Error with " + line + ": " + ex.getMessage());
+ }
+ }
+
+ return list;
+ } catch (IOException ex) {
+ logger.error("IOException while working on file list");
+ }
+ return new ArrayList<Object>();
+ }
+
+}
--- /dev/null
+package org.feistymeow.dragdrop;
+
+import java.awt.*;
+import java.io.*;
+import java.util.*;
+import java.util.List;
+import java.awt.event.*;
+import javax.swing.*;
+import javax.swing.event.*;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.log4j.PropertyConfigurator;
+
+/**
+ * A demo of the DragonDropHandler being used with a JList. Much love to the internet for lots of
+ * examples.
+ *
+ * @author Chris Koeritz
+ * @copyright Copyright (c) 2012-$now By University of Virginia
+ * @license This file is free software; you can modify and redistribute it under the terms of the
+ * Apache License v2.0: http://www.apache.org/licenses/LICENSE-2.0
+ */
+@SuppressWarnings("serial")
+public class dragdrop_list_test extends JFrame implements ListSelectionListener
+{
+ private DraggableDroppableList list;
+ private JTextField fileName;
+ static private Log logger = LogFactory.getLog(dragdrop_list_test.DraggableDroppableList.class);
+
+ public dragdrop_list_test(String startPath)
+ {
+ super("dragdrop_test");
+
+ // Create the list and put it in a scroll pane
+ list = new DraggableDroppableList();
+ DefaultListModel listModel = (DefaultListModel) list.getModel();
+ list.setCellRenderer(new CustomCellRenderer());
+ list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ list.setSelectedIndex(0);
+ list.addListSelectionListener(this);
+ JScrollPane listScrollPane = new JScrollPane(list);
+
+ String dirName = startPath + "/"; // make sure we think of it as a directory.
+ String filelist[] = new File(dirName).list();
+ for (int i = 0; i < filelist.length; i++) {
+ String thisFileSt = dirName + filelist[i];
+ File thisFile = new File(thisFileSt);
+ // skip directories for now.
+ if (thisFile.isDirectory())
+ continue;
+ // skip dot files.
+ if (filelist[i].startsWith("."))
+ continue;
+ try {
+ listModel.addElement(makeNode(thisFile.getName(), thisFile.toURI().toURL()
+ .toString(), thisFile.getAbsolutePath()));
+ } catch (java.net.MalformedURLException e) {
+ }
+ }
+
+ fileName = new JTextField(50);
+ list.setSelectedIndex(0);
+ int sel_index = list.getSelectedIndex();
+ Object obj_at_index = listModel.getElementAt(sel_index);
+ String name = obj_at_index.toString();
+ fileName.setText(name);
+
+ // Create a panel that uses FlowLayout (the default).
+ JPanel buttonPane = new JPanel();
+ buttonPane.add(fileName);
+
+ Container contentPane = getContentPane();
+ contentPane.add(listScrollPane, BorderLayout.CENTER);
+ contentPane.add(buttonPane, BorderLayout.NORTH);
+ }
+
+ public void valueChanged(ListSelectionEvent e)
+ {
+ if (e.getValueIsAdjusting() == false) {
+ fileName.setText("");
+ if (list.getSelectedIndex() != -1) {
+ String name = list.getSelectedValue().toString();
+ fileName.setText(name);
+ }
+ }
+ }
+
+ private static Hashtable<String, String> makeNode(String name, String url, String strPath)
+ {
+ Hashtable<String, String> hashtable = new Hashtable<String, String>();
+ hashtable.put("name", name);
+ hashtable.put("url", url);
+ hashtable.put("path", strPath);
+ return hashtable;
+ }
+
+ public class DraggableDroppableList extends JList implements IDragonDropDataProvider
+ {
+ public DraggableDroppableList()
+ {
+ setModel(new DefaultListModel());
+ setTransferHandler(new DragonTransferHandler(this));
+ setDragEnabled(true);
+ }
+
+ @Override
+ public boolean consumeDropList(List<Object> fileSet, Point location)
+ {
+ logger.debug("into consume dropped files, file set is:");
+ for (int i = 0; i < fileSet.size(); i++) {
+ logger.debug(" " + ((File) fileSet.get(i)).getPath());
+ }
+ return true;
+ }
+
+ @Override
+ public List<Object> provideDragList()
+ {
+ ArrayList<Object> toReturn = new ArrayList<Object>();
+ if (getSelectedIndex() == -1)
+ return toReturn;
+ Object obj = getSelectedValue();
+ if (obj != null) {
+ @SuppressWarnings("unchecked")
+ Hashtable<String, String> table = (Hashtable<String, String>) obj;
+ toReturn.add(new File((String) table.get("path")));
+ }
+ return toReturn;
+ }
+ }
+
+ public class CustomCellRenderer implements ListCellRenderer
+ {
+ DefaultListCellRenderer listCellRenderer = new DefaultListCellRenderer();
+
+ public Component getListCellRendererComponent(JList list, Object value, int index,
+ boolean selected, boolean hasFocus)
+ {
+ listCellRenderer.getListCellRendererComponent(list, value, index, selected, hasFocus);
+ listCellRenderer.setText(getValueString(value));
+ return listCellRenderer;
+ }
+
+ private String getValueString(Object value)
+ {
+ String returnString = "null";
+ if (value != null) {
+ if (value instanceof Hashtable<?, ?>) {
+ @SuppressWarnings("unchecked")
+ Hashtable<String, String> h = (Hashtable<String, String>) value;
+ String name = (String) h.get("name");
+ String url = (String) h.get("url");
+ returnString = name + " ==> " + url;
+ } else {
+ returnString = "X: " + value.toString();
+ }
+ }
+ return returnString;
+ }
+ }
+
+ public static void main(String s[])
+ {
+ PropertyConfigurator.configure("log4j.properties");
+ // starting with user's personal area.
+ String homedir = System.getenv("HOME");
+ if ((homedir == null) || (homedir.length() == 0)) {
+ // fall back to the root if no home directory.
+ homedir = "/";
+ }
+ JFrame frame = new dragdrop_list_test(homedir);
+ frame.addWindowListener(new WindowAdapter()
+ {
+ public void windowClosing(WindowEvent e)
+ {
+ System.exit(0);
+ }
+ });
+ frame.pack();
+ frame.setVisible(true);
+ }
+}
--- /dev/null
+package org.feistymeow.dragdrop;
+
+import java.awt.*;
+import java.io.*;
+import java.util.*;
+import java.util.List;
+import java.awt.event.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeCellRenderer;
+import javax.swing.tree.DefaultTreeModel;
+import javax.swing.tree.DefaultTreeSelectionModel;
+import javax.swing.tree.MutableTreeNode;
+import javax.swing.tree.TreeCellRenderer;
+import javax.swing.tree.TreePath;
+import javax.swing.tree.TreeSelectionModel;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.log4j.PropertyConfigurator;
+
+/**
+ * A demo of the DragonDropHandler being used with a JTree.
+ *
+ * @author Chris Koeritz
+ * @copyright Copyright (c) 2012-$now By University of Virginia
+ * @license This file is free software; you can modify and redistribute it under the terms of the
+ * Apache License v2.0: http://www.apache.org/licenses/LICENSE-2.0
+ */
+@SuppressWarnings("serial")
+public class dragdrop_tree_test extends JFrame implements TreeSelectionListener
+{
+ private DraggableDroppableTree larch;
+ private JTextField fileName;
+ static private Log logger = LogFactory.getLog(dragdrop_tree_test.DraggableDroppableTree.class);
+
+ public dragdrop_tree_test(String startPath)
+ {
+ super("dragdrop_test");
+
+ // create the tree, configure it to show our hashtable nodes, and put it in
+ // a scroll pane.
+ larch = new DraggableDroppableTree(startPath);
+ DefaultTreeModel treeModel = (DefaultTreeModel) larch.getModel();
+ larch.setCellRenderer(new CustomCellRenderer());
+ TreeSelectionModel selmod = new DefaultTreeSelectionModel();
+ selmod.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
+ larch.setSelectionModel(selmod);
+ larch.addTreeSelectionListener(this);
+ JScrollPane listScrollPane = new JScrollPane(larch);
+ // get the files that live in the specified directory.
+ String dirName = startPath + "/"; // make sure we think of it as a
+ // directory.
+ String filelist[] = new File(dirName).list();
+ MutableTreeNode root_node = (MutableTreeNode) treeModel.getRoot();
+ if (root_node == null) {
+ logger.error("something is not right about tree. has null root.");
+ System.exit(1);
+ }
+ // load up the tree with the files in the directory they passed.
+ for (int i = 0; i < filelist.length; i++) {
+ String thisFileSt = dirName + filelist[i];
+ File thisFile = new File(thisFileSt);
+ // skip directories for now.
+ if (thisFile.isDirectory())
+ continue;
+ // skip dot files.
+ if (filelist[i].startsWith("."))
+ continue;
+ try {
+ // need to trap exceptions from the URI/URL functions.
+ DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(makeNode(
+ thisFile.getName(), thisFile.toURI().toURL().toString(),
+ thisFile.getAbsolutePath()));
+ treeModel.insertNodeInto(newNode, root_node, root_node.getChildCount());
+ } catch (java.net.MalformedURLException e) {
+ logger.warn("caught an exception while trying to process path: "
+ + thisFile.getAbsolutePath());
+ }
+ }
+
+ // set our status bar to have the current path info.
+ fileName = new JTextField(50);
+ // select the root.
+ larch.setSelectionPath(larch.getPathForRow(0));
+
+ // pop out all the nodes.
+ larch.expandAll();
+
+ // Create a panel that uses FlowLayout (the default).
+ JPanel buttonPane = new JPanel();
+ buttonPane.add(fileName);
+
+ Container contentPane = getContentPane();
+ contentPane.add(listScrollPane, BorderLayout.CENTER);
+ contentPane.add(buttonPane, BorderLayout.NORTH);
+ }
+
+ @SuppressWarnings("unchecked")
+ // given a mutable tree node, this will fetch out the embedded hash table.
+ Hashtable<String, String> NodeToTable(Object node)
+ {
+ if (!(node instanceof DefaultMutableTreeNode))
+ return null;
+ Object content = ((DefaultMutableTreeNode) node).getUserObject();
+ if (content != null) {
+ if (content instanceof Hashtable<?, ?>) {
+ try {
+ return (Hashtable<String, String>) content;
+ } catch (Throwable cause) {
+ logger.error("failed to cast our tree node to a hashtable.");
+ }
+ }
+ }
+ return null;
+ }
+
+ public void valueChanged(TreeSelectionEvent e)
+ {
+ fileName.setText("");
+ TreePath sel_path = larch.getSelectionPath();
+ if (sel_path != null) {
+ Hashtable<String, String> table = NodeToTable(sel_path.getLastPathComponent());
+ if (table != null) {
+ String name = (String) table.get("name");
+ fileName.setText(name);
+ }
+ }
+ }
+
+ private static Hashtable<String, String> makeNode(String name, String url, String strPath)
+ {
+ Hashtable<String, String> hashtable = new Hashtable<String, String>();
+ hashtable.put("name", name);
+ hashtable.put("url", url);
+ hashtable.put("path", strPath);
+ return hashtable;
+ }
+
+ public class DraggableDroppableTree extends JTree implements IDragonDropDataProvider
+ {
+ public DraggableDroppableTree(String startPath)
+ {
+ String url = "";
+ try {
+ url = new File(startPath).toURI().toURL().toString();
+ } catch (Throwable cause) {
+ logger.warn("failed to calculate URL for " + startPath);
+ }
+ setModel(new DefaultTreeModel(new DefaultMutableTreeNode(
+ makeNode("top", url, startPath))));
+ setTransferHandler(new DragonTransferHandler(this));
+ setDragEnabled(true);
+ }
+
+ @Override
+ public boolean consumeDropList(List<Object> fileSet, Point location)
+ {
+ logger.debug("into consume dropped files, file set is:");
+ for (int i = 0; i < fileSet.size(); i++) {
+ logger.debug(" " + ((File) fileSet.get(i)).getPath());
+ }
+ return true;
+ }
+
+ @Override
+ public List<Object> provideDragList()
+ {
+ ArrayList<Object> toReturn = new ArrayList<Object>();
+ TreePath tsp = getSelectionPath();
+ if (tsp == null)
+ return toReturn;
+ logger.debug("got the path...");
+ Hashtable<String, String> table = NodeToTable(tsp.getLastPathComponent());
+ if (table != null) {
+ toReturn.add(new File(table.get("path")));
+ }
+ return toReturn;
+ }
+
+ public void expandAll()
+ {
+ int row = 0;
+ while (row < getRowCount()) {
+ expandRow(row);
+ row++;
+ }
+ }
+
+ }
+
+ public class CustomCellRenderer implements TreeCellRenderer
+ {
+ DefaultTreeCellRenderer defRend = new DefaultTreeCellRenderer();
+
+ private String getValueString(Object value)
+ {
+ String returnString = "empty";
+ Hashtable<String, String> table = NodeToTable(value);
+ if (table != null) {
+ returnString = table.get("name") + " -> " + table.get("url");
+ } else {
+ returnString = "??: " + value.toString();
+ }
+ return returnString;
+ }
+
+ @Override
+ public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
+ boolean expanded, boolean leaf, int row, boolean hasFocus)
+ {
+ defRend.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row,
+ hasFocus);
+ defRend.setText(getValueString(value));
+ return defRend;
+ }
+ }
+
+ public static void main(String s[])
+ {
+ PropertyConfigurator.configure("log4j.properties");
+ // starting with user's personal area.
+ String homedir = System.getenv("HOME");
+ if ((homedir == null) || (homedir.length() == 0)) {
+ // fall back to the root if no home directory.
+ homedir = "/";
+ }
+ JFrame frame = new dragdrop_tree_test(homedir);
+ frame.addWindowListener(new WindowAdapter()
+ {
+ public void windowClosing(WindowEvent e)
+ {
+ System.exit(0);
+ }
+ });
+ frame.pack();
+ frame.setVisible(true);
+ }
+
+}
--- /dev/null
+package org.feistymeow.encryption;\r
+\r
+import java.util.ArrayList;\r
+\r
+/****************************************************************************\r
+ * Java-based implementation of the unix UnixCrypt(3) command\r
+ *\r
+ * Based upon C source code written by Eric Young, eay@psych.uq.oz.au\r
+ * Java conversion by John F. Dumas, jdumas@zgs.com\r
+ *\r
+ * Found at http://locutus.kingwoodcable.com/jfd/UnixCrypt.html\r
+ * Minor optimizations by Wes Biggs, wes@cacas.org\r
+ *\r
+ * Eric's original code is licensed under the BSD license. As this is\r
+ * derivative, the same license applies.\r
+ *\r
+ * Note: UnixCrypt.class is much smaller when compiled with javac -O\r
+ ****************************************************************************/\r
+\r
+public class UnixCrypt \r
+{\r
+ private UnixCrypt() {} // defined so class can't be instantiated.\r
+\r
+ private static final int ITERATIONS = 16;\r
+\r
+ private static final boolean shifts2[] = {\r
+ false, false, true, true, true, true, true, true,\r
+ false, true, true, true, true, true, true, false\r
+ };\r
+\r
+ private static final int skb[][] = {\r
+ {\r
+ /* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */\r
+ 0x00000000, 0x00000010, 0x20000000, 0x20000010, \r
+ 0x00010000, 0x00010010, 0x20010000, 0x20010010, \r
+ 0x00000800, 0x00000810, 0x20000800, 0x20000810, \r
+ 0x00010800, 0x00010810, 0x20010800, 0x20010810, \r
+ 0x00000020, 0x00000030, 0x20000020, 0x20000030, \r
+ 0x00010020, 0x00010030, 0x20010020, 0x20010030, \r
+ 0x00000820, 0x00000830, 0x20000820, 0x20000830, \r
+ 0x00010820, 0x00010830, 0x20010820, 0x20010830, \r
+ 0x00080000, 0x00080010, 0x20080000, 0x20080010, \r
+ 0x00090000, 0x00090010, 0x20090000, 0x20090010, \r
+ 0x00080800, 0x00080810, 0x20080800, 0x20080810, \r
+ 0x00090800, 0x00090810, 0x20090800, 0x20090810, \r
+ 0x00080020, 0x00080030, 0x20080020, 0x20080030, \r
+ 0x00090020, 0x00090030, 0x20090020, 0x20090030, \r
+ 0x00080820, 0x00080830, 0x20080820, 0x20080830, \r
+ 0x00090820, 0x00090830, 0x20090820, 0x20090830, \r
+ },\r
+ {\r
+ /* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */\r
+ 0x00000000, 0x02000000, 0x00002000, 0x02002000, \r
+ 0x00200000, 0x02200000, 0x00202000, 0x02202000, \r
+ 0x00000004, 0x02000004, 0x00002004, 0x02002004, \r
+ 0x00200004, 0x02200004, 0x00202004, 0x02202004, \r
+ 0x00000400, 0x02000400, 0x00002400, 0x02002400, \r
+ 0x00200400, 0x02200400, 0x00202400, 0x02202400, \r
+ 0x00000404, 0x02000404, 0x00002404, 0x02002404, \r
+ 0x00200404, 0x02200404, 0x00202404, 0x02202404, \r
+ 0x10000000, 0x12000000, 0x10002000, 0x12002000, \r
+ 0x10200000, 0x12200000, 0x10202000, 0x12202000, \r
+ 0x10000004, 0x12000004, 0x10002004, 0x12002004, \r
+ 0x10200004, 0x12200004, 0x10202004, 0x12202004, \r
+ 0x10000400, 0x12000400, 0x10002400, 0x12002400, \r
+ 0x10200400, 0x12200400, 0x10202400, 0x12202400, \r
+ 0x10000404, 0x12000404, 0x10002404, 0x12002404, \r
+ 0x10200404, 0x12200404, 0x10202404, 0x12202404, \r
+ },\r
+ {\r
+ /* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */\r
+ 0x00000000, 0x00000001, 0x00040000, 0x00040001, \r
+ 0x01000000, 0x01000001, 0x01040000, 0x01040001, \r
+ 0x00000002, 0x00000003, 0x00040002, 0x00040003, \r
+ 0x01000002, 0x01000003, 0x01040002, 0x01040003, \r
+ 0x00000200, 0x00000201, 0x00040200, 0x00040201, \r
+ 0x01000200, 0x01000201, 0x01040200, 0x01040201, \r
+ 0x00000202, 0x00000203, 0x00040202, 0x00040203, \r
+ 0x01000202, 0x01000203, 0x01040202, 0x01040203, \r
+ 0x08000000, 0x08000001, 0x08040000, 0x08040001, \r
+ 0x09000000, 0x09000001, 0x09040000, 0x09040001, \r
+ 0x08000002, 0x08000003, 0x08040002, 0x08040003, \r
+ 0x09000002, 0x09000003, 0x09040002, 0x09040003, \r
+ 0x08000200, 0x08000201, 0x08040200, 0x08040201, \r
+ 0x09000200, 0x09000201, 0x09040200, 0x09040201, \r
+ 0x08000202, 0x08000203, 0x08040202, 0x08040203, \r
+ 0x09000202, 0x09000203, 0x09040202, 0x09040203, \r
+ },\r
+ {\r
+ /* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */\r
+ 0x00000000, 0x00100000, 0x00000100, 0x00100100, \r
+ 0x00000008, 0x00100008, 0x00000108, 0x00100108, \r
+ 0x00001000, 0x00101000, 0x00001100, 0x00101100, \r
+ 0x00001008, 0x00101008, 0x00001108, 0x00101108, \r
+ 0x04000000, 0x04100000, 0x04000100, 0x04100100, \r
+ 0x04000008, 0x04100008, 0x04000108, 0x04100108, \r
+ 0x04001000, 0x04101000, 0x04001100, 0x04101100, \r
+ 0x04001008, 0x04101008, 0x04001108, 0x04101108, \r
+ 0x00020000, 0x00120000, 0x00020100, 0x00120100, \r
+ 0x00020008, 0x00120008, 0x00020108, 0x00120108, \r
+ 0x00021000, 0x00121000, 0x00021100, 0x00121100, \r
+ 0x00021008, 0x00121008, 0x00021108, 0x00121108, \r
+ 0x04020000, 0x04120000, 0x04020100, 0x04120100, \r
+ 0x04020008, 0x04120008, 0x04020108, 0x04120108, \r
+ 0x04021000, 0x04121000, 0x04021100, 0x04121100, \r
+ 0x04021008, 0x04121008, 0x04021108, 0x04121108, \r
+ },\r
+ {\r
+ /* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */\r
+ 0x00000000, 0x10000000, 0x00010000, 0x10010000, \r
+ 0x00000004, 0x10000004, 0x00010004, 0x10010004, \r
+ 0x20000000, 0x30000000, 0x20010000, 0x30010000, \r
+ 0x20000004, 0x30000004, 0x20010004, 0x30010004, \r
+ 0x00100000, 0x10100000, 0x00110000, 0x10110000, \r
+ 0x00100004, 0x10100004, 0x00110004, 0x10110004, \r
+ 0x20100000, 0x30100000, 0x20110000, 0x30110000, \r
+ 0x20100004, 0x30100004, 0x20110004, 0x30110004, \r
+ 0x00001000, 0x10001000, 0x00011000, 0x10011000, \r
+ 0x00001004, 0x10001004, 0x00011004, 0x10011004, \r
+ 0x20001000, 0x30001000, 0x20011000, 0x30011000, \r
+ 0x20001004, 0x30001004, 0x20011004, 0x30011004, \r
+ 0x00101000, 0x10101000, 0x00111000, 0x10111000, \r
+ 0x00101004, 0x10101004, 0x00111004, 0x10111004, \r
+ 0x20101000, 0x30101000, 0x20111000, 0x30111000, \r
+ 0x20101004, 0x30101004, 0x20111004, 0x30111004, \r
+ },\r
+ {\r
+ /* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */\r
+ 0x00000000, 0x08000000, 0x00000008, 0x08000008, \r
+ 0x00000400, 0x08000400, 0x00000408, 0x08000408, \r
+ 0x00020000, 0x08020000, 0x00020008, 0x08020008, \r
+ 0x00020400, 0x08020400, 0x00020408, 0x08020408, \r
+ 0x00000001, 0x08000001, 0x00000009, 0x08000009, \r
+ 0x00000401, 0x08000401, 0x00000409, 0x08000409, \r
+ 0x00020001, 0x08020001, 0x00020009, 0x08020009, \r
+ 0x00020401, 0x08020401, 0x00020409, 0x08020409, \r
+ 0x02000000, 0x0A000000, 0x02000008, 0x0A000008, \r
+ 0x02000400, 0x0A000400, 0x02000408, 0x0A000408, \r
+ 0x02020000, 0x0A020000, 0x02020008, 0x0A020008, \r
+ 0x02020400, 0x0A020400, 0x02020408, 0x0A020408, \r
+ 0x02000001, 0x0A000001, 0x02000009, 0x0A000009, \r
+ 0x02000401, 0x0A000401, 0x02000409, 0x0A000409, \r
+ 0x02020001, 0x0A020001, 0x02020009, 0x0A020009, \r
+ 0x02020401, 0x0A020401, 0x02020409, 0x0A020409, \r
+ },\r
+ {\r
+ /* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */\r
+ 0x00000000, 0x00000100, 0x00080000, 0x00080100, \r
+ 0x01000000, 0x01000100, 0x01080000, 0x01080100, \r
+ 0x00000010, 0x00000110, 0x00080010, 0x00080110, \r
+ 0x01000010, 0x01000110, 0x01080010, 0x01080110, \r
+ 0x00200000, 0x00200100, 0x00280000, 0x00280100, \r
+ 0x01200000, 0x01200100, 0x01280000, 0x01280100, \r
+ 0x00200010, 0x00200110, 0x00280010, 0x00280110, \r
+ 0x01200010, 0x01200110, 0x01280010, 0x01280110, \r
+ 0x00000200, 0x00000300, 0x00080200, 0x00080300, \r
+ 0x01000200, 0x01000300, 0x01080200, 0x01080300, \r
+ 0x00000210, 0x00000310, 0x00080210, 0x00080310, \r
+ 0x01000210, 0x01000310, 0x01080210, 0x01080310, \r
+ 0x00200200, 0x00200300, 0x00280200, 0x00280300, \r
+ 0x01200200, 0x01200300, 0x01280200, 0x01280300, \r
+ 0x00200210, 0x00200310, 0x00280210, 0x00280310, \r
+ 0x01200210, 0x01200310, 0x01280210, 0x01280310, \r
+ },\r
+ {\r
+ /* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */\r
+ 0x00000000, 0x04000000, 0x00040000, 0x04040000, \r
+ 0x00000002, 0x04000002, 0x00040002, 0x04040002, \r
+ 0x00002000, 0x04002000, 0x00042000, 0x04042000, \r
+ 0x00002002, 0x04002002, 0x00042002, 0x04042002, \r
+ 0x00000020, 0x04000020, 0x00040020, 0x04040020, \r
+ 0x00000022, 0x04000022, 0x00040022, 0x04040022, \r
+ 0x00002020, 0x04002020, 0x00042020, 0x04042020, \r
+ 0x00002022, 0x04002022, 0x00042022, 0x04042022, \r
+ 0x00000800, 0x04000800, 0x00040800, 0x04040800, \r
+ 0x00000802, 0x04000802, 0x00040802, 0x04040802, \r
+ 0x00002800, 0x04002800, 0x00042800, 0x04042800, \r
+ 0x00002802, 0x04002802, 0x00042802, 0x04042802, \r
+ 0x00000820, 0x04000820, 0x00040820, 0x04040820, \r
+ 0x00000822, 0x04000822, 0x00040822, 0x04040822, \r
+ 0x00002820, 0x04002820, 0x00042820, 0x04042820, \r
+ 0x00002822, 0x04002822, 0x00042822, 0x04042822, \r
+ }\r
+ };\r
+ \r
+ private static final int SPtrans[][] = {\r
+ {\r
+ /* nibble 0 */\r
+ 0x00820200, 0x00020000, 0x80800000, 0x80820200,\r
+ 0x00800000, 0x80020200, 0x80020000, 0x80800000,\r
+ 0x80020200, 0x00820200, 0x00820000, 0x80000200,\r
+ 0x80800200, 0x00800000, 0x00000000, 0x80020000,\r
+ 0x00020000, 0x80000000, 0x00800200, 0x00020200,\r
+ 0x80820200, 0x00820000, 0x80000200, 0x00800200,\r
+ 0x80000000, 0x00000200, 0x00020200, 0x80820000,\r
+ 0x00000200, 0x80800200, 0x80820000, 0x00000000,\r
+ 0x00000000, 0x80820200, 0x00800200, 0x80020000,\r
+ 0x00820200, 0x00020000, 0x80000200, 0x00800200,\r
+ 0x80820000, 0x00000200, 0x00020200, 0x80800000,\r
+ 0x80020200, 0x80000000, 0x80800000, 0x00820000,\r
+ 0x80820200, 0x00020200, 0x00820000, 0x80800200,\r
+ 0x00800000, 0x80000200, 0x80020000, 0x00000000,\r
+ 0x00020000, 0x00800000, 0x80800200, 0x00820200,\r
+ 0x80000000, 0x80820000, 0x00000200, 0x80020200,\r
+ },\r
+ {\r
+ /* nibble 1 */\r
+ 0x10042004, 0x00000000, 0x00042000, 0x10040000,\r
+ 0x10000004, 0x00002004, 0x10002000, 0x00042000,\r
+ 0x00002000, 0x10040004, 0x00000004, 0x10002000,\r
+ 0x00040004, 0x10042000, 0x10040000, 0x00000004,\r
+ 0x00040000, 0x10002004, 0x10040004, 0x00002000,\r
+ 0x00042004, 0x10000000, 0x00000000, 0x00040004,\r
+ 0x10002004, 0x00042004, 0x10042000, 0x10000004,\r
+ 0x10000000, 0x00040000, 0x00002004, 0x10042004,\r
+ 0x00040004, 0x10042000, 0x10002000, 0x00042004,\r
+ 0x10042004, 0x00040004, 0x10000004, 0x00000000,\r
+ 0x10000000, 0x00002004, 0x00040000, 0x10040004,\r
+ 0x00002000, 0x10000000, 0x00042004, 0x10002004,\r
+ 0x10042000, 0x00002000, 0x00000000, 0x10000004,\r
+ 0x00000004, 0x10042004, 0x00042000, 0x10040000,\r
+ 0x10040004, 0x00040000, 0x00002004, 0x10002000,\r
+ 0x10002004, 0x00000004, 0x10040000, 0x00042000,\r
+ },\r
+ {\r
+ /* nibble 2 */\r
+ 0x41000000, 0x01010040, 0x00000040, 0x41000040,\r
+ 0x40010000, 0x01000000, 0x41000040, 0x00010040,\r
+ 0x01000040, 0x00010000, 0x01010000, 0x40000000,\r
+ 0x41010040, 0x40000040, 0x40000000, 0x41010000,\r
+ 0x00000000, 0x40010000, 0x01010040, 0x00000040,\r
+ 0x40000040, 0x41010040, 0x00010000, 0x41000000,\r
+ 0x41010000, 0x01000040, 0x40010040, 0x01010000,\r
+ 0x00010040, 0x00000000, 0x01000000, 0x40010040,\r
+ 0x01010040, 0x00000040, 0x40000000, 0x00010000,\r
+ 0x40000040, 0x40010000, 0x01010000, 0x41000040,\r
+ 0x00000000, 0x01010040, 0x00010040, 0x41010000,\r
+ 0x40010000, 0x01000000, 0x41010040, 0x40000000,\r
+ 0x40010040, 0x41000000, 0x01000000, 0x41010040,\r
+ 0x00010000, 0x01000040, 0x41000040, 0x00010040,\r
+ 0x01000040, 0x00000000, 0x41010000, 0x40000040,\r
+ 0x41000000, 0x40010040, 0x00000040, 0x01010000,\r
+ },\r
+ {\r
+ /* nibble 3 */\r
+ 0x00100402, 0x04000400, 0x00000002, 0x04100402,\r
+ 0x00000000, 0x04100000, 0x04000402, 0x00100002,\r
+ 0x04100400, 0x04000002, 0x04000000, 0x00000402,\r
+ 0x04000002, 0x00100402, 0x00100000, 0x04000000,\r
+ 0x04100002, 0x00100400, 0x00000400, 0x00000002,\r
+ 0x00100400, 0x04000402, 0x04100000, 0x00000400,\r
+ 0x00000402, 0x00000000, 0x00100002, 0x04100400,\r
+ 0x04000400, 0x04100002, 0x04100402, 0x00100000,\r
+ 0x04100002, 0x00000402, 0x00100000, 0x04000002,\r
+ 0x00100400, 0x04000400, 0x00000002, 0x04100000,\r
+ 0x04000402, 0x00000000, 0x00000400, 0x00100002,\r
+ 0x00000000, 0x04100002, 0x04100400, 0x00000400,\r
+ 0x04000000, 0x04100402, 0x00100402, 0x00100000,\r
+ 0x04100402, 0x00000002, 0x04000400, 0x00100402,\r
+ 0x00100002, 0x00100400, 0x04100000, 0x04000402,\r
+ 0x00000402, 0x04000000, 0x04000002, 0x04100400,\r
+ },\r
+ {\r
+ /* nibble 4 */\r
+ 0x02000000, 0x00004000, 0x00000100, 0x02004108,\r
+ 0x02004008, 0x02000100, 0x00004108, 0x02004000,\r
+ 0x00004000, 0x00000008, 0x02000008, 0x00004100,\r
+ 0x02000108, 0x02004008, 0x02004100, 0x00000000,\r
+ 0x00004100, 0x02000000, 0x00004008, 0x00000108,\r
+ 0x02000100, 0x00004108, 0x00000000, 0x02000008,\r
+ 0x00000008, 0x02000108, 0x02004108, 0x00004008,\r
+ 0x02004000, 0x00000100, 0x00000108, 0x02004100,\r
+ 0x02004100, 0x02000108, 0x00004008, 0x02004000,\r
+ 0x00004000, 0x00000008, 0x02000008, 0x02000100,\r
+ 0x02000000, 0x00004100, 0x02004108, 0x00000000,\r
+ 0x00004108, 0x02000000, 0x00000100, 0x00004008,\r
+ 0x02000108, 0x00000100, 0x00000000, 0x02004108,\r
+ 0x02004008, 0x02004100, 0x00000108, 0x00004000,\r
+ 0x00004100, 0x02004008, 0x02000100, 0x00000108,\r
+ 0x00000008, 0x00004108, 0x02004000, 0x02000008,\r
+ },\r
+ {\r
+ /* nibble 5 */\r
+ 0x20000010, 0x00080010, 0x00000000, 0x20080800,\r
+ 0x00080010, 0x00000800, 0x20000810, 0x00080000,\r
+ 0x00000810, 0x20080810, 0x00080800, 0x20000000,\r
+ 0x20000800, 0x20000010, 0x20080000, 0x00080810,\r
+ 0x00080000, 0x20000810, 0x20080010, 0x00000000,\r
+ 0x00000800, 0x00000010, 0x20080800, 0x20080010,\r
+ 0x20080810, 0x20080000, 0x20000000, 0x00000810,\r
+ 0x00000010, 0x00080800, 0x00080810, 0x20000800,\r
+ 0x00000810, 0x20000000, 0x20000800, 0x00080810,\r
+ 0x20080800, 0x00080010, 0x00000000, 0x20000800,\r
+ 0x20000000, 0x00000800, 0x20080010, 0x00080000,\r
+ 0x00080010, 0x20080810, 0x00080800, 0x00000010,\r
+ 0x20080810, 0x00080800, 0x00080000, 0x20000810,\r
+ 0x20000010, 0x20080000, 0x00080810, 0x00000000,\r
+ 0x00000800, 0x20000010, 0x20000810, 0x20080800,\r
+ 0x20080000, 0x00000810, 0x00000010, 0x20080010,\r
+ },\r
+ {\r
+ /* nibble 6 */\r
+ 0x00001000, 0x00000080, 0x00400080, 0x00400001,\r
+ 0x00401081, 0x00001001, 0x00001080, 0x00000000,\r
+ 0x00400000, 0x00400081, 0x00000081, 0x00401000,\r
+ 0x00000001, 0x00401080, 0x00401000, 0x00000081,\r
+ 0x00400081, 0x00001000, 0x00001001, 0x00401081,\r
+ 0x00000000, 0x00400080, 0x00400001, 0x00001080,\r
+ 0x00401001, 0x00001081, 0x00401080, 0x00000001,\r
+ 0x00001081, 0x00401001, 0x00000080, 0x00400000,\r
+ 0x00001081, 0x00401000, 0x00401001, 0x00000081,\r
+ 0x00001000, 0x00000080, 0x00400000, 0x00401001,\r
+ 0x00400081, 0x00001081, 0x00001080, 0x00000000,\r
+ 0x00000080, 0x00400001, 0x00000001, 0x00400080,\r
+ 0x00000000, 0x00400081, 0x00400080, 0x00001080,\r
+ 0x00000081, 0x00001000, 0x00401081, 0x00400000,\r
+ 0x00401080, 0x00000001, 0x00001001, 0x00401081,\r
+ 0x00400001, 0x00401080, 0x00401000, 0x00001001,\r
+ },\r
+ {\r
+ /* nibble 7 */\r
+ 0x08200020, 0x08208000, 0x00008020, 0x00000000,\r
+ 0x08008000, 0x00200020, 0x08200000, 0x08208020,\r
+ 0x00000020, 0x08000000, 0x00208000, 0x00008020,\r
+ 0x00208020, 0x08008020, 0x08000020, 0x08200000,\r
+ 0x00008000, 0x00208020, 0x00200020, 0x08008000,\r
+ 0x08208020, 0x08000020, 0x00000000, 0x00208000,\r
+ 0x08000000, 0x00200000, 0x08008020, 0x08200020,\r
+ 0x00200000, 0x00008000, 0x08208000, 0x00000020,\r
+ 0x00200000, 0x00008000, 0x08000020, 0x08208020,\r
+ 0x00008020, 0x08000000, 0x00000000, 0x00208000,\r
+ 0x08200020, 0x08008020, 0x08008000, 0x00200020,\r
+ 0x08208000, 0x00000020, 0x00200020, 0x08008000,\r
+ 0x08208020, 0x00200000, 0x08200000, 0x08000020,\r
+ 0x00208000, 0x00008020, 0x08008020, 0x08200000,\r
+ 0x00000020, 0x08208000, 0x00208020, 0x00000000,\r
+ 0x08000000, 0x08200020, 0x00008000, 0x00208020\r
+ }\r
+ };\r
+ \r
+ private static final int byteToUnsigned(byte b) {\r
+ int value = (int) b;\r
+ return (value >= 0) ? value : value + 256;\r
+ }\r
+\r
+ private static int fourBytesToInt(byte b[], int offset) {\r
+ return byteToUnsigned(b[offset++]) \r
+ | (byteToUnsigned(b[offset++]) << 8) \r
+ | (byteToUnsigned(b[offset++]) << 16) \r
+ | (byteToUnsigned(b[offset]) << 24);\r
+ }\r
+\r
+ private static final void intToFourBytes(int iValue, byte b[], int offset) {\r
+ b[offset++] = (byte)((iValue) & 0xff);\r
+ b[offset++] = (byte)((iValue >>> 8 ) & 0xff);\r
+ b[offset++] = (byte)((iValue >>> 16) & 0xff);\r
+ b[offset] = (byte)((iValue >>> 24) & 0xff);\r
+ }\r
+ \r
+ private static final void PERM_OP(int a, int b, int n, int m, int results[]) {\r
+ int t;\r
+\r
+ t = ((a >>> n) ^ b) & m;\r
+ a ^= t << n;\r
+ b ^= t;\r
+\r
+ results[0] = a;\r
+ results[1] = b;\r
+ }\r
+\r
+ private static final int HPERM_OP(int a, int n, int m) {\r
+ int t;\r
+ \r
+ t = ((a << (16 - n)) ^ a) & m;\r
+ a = a ^ t ^ (t >>> (16 - n));\r
+ \r
+ return a;\r
+ }\r
+\r
+ private static int [] des_set_key(byte key[]) {\r
+ int schedule[] = new int [ITERATIONS * 2];\r
+ \r
+ int c = fourBytesToInt(key, 0);\r
+ int d = fourBytesToInt(key, 4);\r
+ \r
+ int results[] = new int[2];\r
+\r
+ PERM_OP(d, c, 4, 0x0f0f0f0f, results);\r
+ d = results[0]; c = results[1];\r
+ \r
+ c = HPERM_OP(c, -2, 0xcccc0000);\r
+ d = HPERM_OP(d, -2, 0xcccc0000);\r
+ \r
+ PERM_OP(d, c, 1, 0x55555555, results);\r
+ d = results[0]; c = results[1];\r
+ \r
+ PERM_OP(c, d, 8, 0x00ff00ff, results);\r
+ c = results[0]; d = results[1];\r
+ \r
+ PERM_OP(d, c, 1, 0x55555555, results);\r
+ d = results[0]; c = results[1];\r
+ \r
+ d = (((d & 0x000000ff) << 16) | (d & 0x0000ff00) |\r
+ ((d & 0x00ff0000) >>> 16) | ((c & 0xf0000000) >>> 4));\r
+ c &= 0x0fffffff;\r
+ \r
+ int s, t;\r
+ int j = 0;\r
+ \r
+ for(int i = 0; i < ITERATIONS; i ++) {\r
+ if(shifts2[i]) {\r
+ c = (c >>> 2) | (c << 26);\r
+ d = (d >>> 2) | (d << 26);\r
+ } else {\r
+ c = (c >>> 1) | (c << 27);\r
+ d = (d >>> 1) | (d << 27);\r
+ }\r
+ \r
+ c &= 0x0fffffff;\r
+ d &= 0x0fffffff;\r
+ \r
+ s = skb[0][ (c ) & 0x3f ]|\r
+ skb[1][((c >>> 6) & 0x03) | ((c >>> 7) & 0x3c)]|\r
+ skb[2][((c >>> 13) & 0x0f) | ((c >>> 14) & 0x30)]|\r
+ skb[3][((c >>> 20) & 0x01) | ((c >>> 21) & 0x06) |\r
+ ((c >>> 22) & 0x38)];\r
+\r
+ t = skb[4][ (d ) & 0x3f ]|\r
+ skb[5][((d >>> 7) & 0x03) | ((d >>> 8) & 0x3c)]|\r
+ skb[6][ (d >>>15) & 0x3f ]|\r
+ skb[7][((d >>>21) & 0x0f) | ((d >>> 22) & 0x30)];\r
+ \r
+ schedule[j++] = ((t << 16) | (s & 0x0000ffff)) & 0xffffffff;\r
+ s = ((s >>> 16) | (t & 0xffff0000));\r
+ \r
+ s = (s << 4) | (s >>> 28);\r
+ schedule[j++] = s & 0xffffffff;\r
+ }\r
+ return schedule;\r
+ }\r
+\r
+ private static final int D_ENUnixCrypt(int L, int R, int S, int E0, int E1, int s[]) {\r
+ int t, u, v;\r
+ \r
+ v = R ^ (R >>> 16);\r
+ u = v & E0;\r
+ v = v & E1;\r
+ u = (u ^ (u << 16)) ^ R ^ s[S];\r
+ t = (v ^ (v << 16)) ^ R ^ s[S + 1];\r
+ t = (t >>> 4) | (t << 28);\r
+ \r
+ L ^= SPtrans[1][(t ) & 0x3f] |\r
+ SPtrans[3][(t >>> 8) & 0x3f] |\r
+ SPtrans[5][(t >>> 16) & 0x3f] |\r
+ SPtrans[7][(t >>> 24) & 0x3f] |\r
+ SPtrans[0][(u ) & 0x3f] |\r
+ SPtrans[2][(u >>> 8) & 0x3f] |\r
+ SPtrans[4][(u >>> 16) & 0x3f] |\r
+ SPtrans[6][(u >>> 24) & 0x3f];\r
+\r
+ return L;\r
+ }\r
+ \r
+ private static final int [] body(int schedule[], int Eswap0, int Eswap1) \r
+ {\r
+ int left = 0;\r
+ int right = 0;\r
+ int t = 0;\r
+\r
+ for (int j = 0; j < 25; j ++) {\r
+ for (int i = 0; i < ITERATIONS * 2; i += 4) {\r
+ left = D_ENUnixCrypt(left, right, i, Eswap0, Eswap1, schedule);\r
+ right = D_ENUnixCrypt(right, left, i + 2, Eswap0, Eswap1, schedule);\r
+ }\r
+ t = left; \r
+ left = right; \r
+ right = t;\r
+ }\r
+ \r
+ t = right;\r
+\r
+ right = (left >>> 1) | (left << 31);\r
+ left = (t >>> 1) | (t << 31);\r
+ \r
+ left &= 0xffffffff;\r
+ right &= 0xffffffff;\r
+\r
+ int results[] = new int[2];\r
+\r
+ PERM_OP(right, left, 1, 0x55555555, results); \r
+ right = results[0]; left = results[1];\r
+ \r
+ PERM_OP(left, right, 8, 0x00ff00ff, results); \r
+ left = results[0]; right = results[1];\r
+\r
+ PERM_OP(right, left, 2, 0x33333333, results); \r
+ right = results[0]; left = results[1];\r
+ \r
+ PERM_OP(left, right, 16, 0x0000ffff, results);\r
+ left = results[0]; right = results[1];\r
+ \r
+ PERM_OP(right, left, 4, 0x0f0f0f0f, results);\r
+ right = results[0]; left = results[1];\r
+ \r
+ int out[] = new int[2];\r
+ \r
+ out[0] = left; \r
+ out[1] = right;\r
+ \r
+ return out;\r
+ }\r
+\r
+ public static final String alphabet = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";\r
+\r
+ public static final String encrypt(String salt, String original) \r
+ {\r
+ // wwb -- Should do some sanity checks: salt needs to be 2 chars, in alpha.\r
+ while(salt.length() < 2)\r
+ salt += "A";\r
+\r
+ char[] buffer = new char [13];\r
+\r
+ char charZero = salt.charAt(0);\r
+ char charOne = salt.charAt(1);\r
+ \r
+ buffer[0] = charZero;\r
+ buffer[1] = charOne;\r
+\r
+ int Eswap0 = alphabet.indexOf(charZero);\r
+ int Eswap1 = alphabet.indexOf(charOne) << 4;\r
+ byte key[] = new byte[8];\r
+ \r
+ for(int i = 0; i < key.length; i ++)\r
+ key[i] = (byte)0;\r
+ \r
+ for(int i = 0; i < key.length && i < original.length(); i ++)\r
+ key[i] = (byte) (((int) original.charAt(i)) << 1);\r
+\r
+ int schedule[] = des_set_key(key);\r
+ int out[] = body(schedule, Eswap0, Eswap1);\r
+ \r
+ byte b[] = new byte[9];\r
+ \r
+ intToFourBytes(out[0], b, 0);\r
+ intToFourBytes(out[1], b, 4);\r
+ b[8] = 0;\r
+\r
+ for(int i = 2, y = 0, u = 0x80; i < 13; i ++) {\r
+ for(int j = 0, c = 0; j < 6; j ++) {\r
+ c <<= 1;\r
+\r
+ if(((int)b[y] & u) != 0)\r
+ c |= 1;\r
+\r
+ u >>>= 1;\r
+ \r
+ if (u == 0) {\r
+ y++;\r
+ u = 0x80;\r
+ }\r
+ buffer[i] = alphabet.charAt(c);\r
+ }\r
+ }\r
+ return new String(buffer);\r
+ }\r
+ \r
+ public static void main(String [] args)\r
+ {\r
+ if ( (1 == args.length) && ("list".equalsIgnoreCase(args[0])) )\r
+ {\r
+ StringBuffer listChars = new StringBuffer(alphabet);\r
+ final String password = "italianroast";\r
+ int salt = 1;\r
+ ArrayList<String []> pws = new ArrayList<String []>();\r
+ while( listChars.length() > 0 )\r
+ {\r
+ int startLen = listChars.length();\r
+ String pw = UnixCrypt.encrypt(Integer.toString(salt), password);\r
+ for( int i = 0; i < pw.length(); ++i )\r
+ {\r
+ int pos = listChars.indexOf(pw.substring(i, i+1));\r
+ if( pos >= 0 )\r
+ listChars.deleteCharAt(pos); \r
+ }\r
+ if( listChars.length() == startLen )\r
+ ++salt;\r
+ else\r
+ pws.add(new String [] { password, pw });\r
+ }\r
+ for( String [] pw : pws )\r
+ System.out.println(pw[0] + " : " + pw[1]);\r
+ }\r
+ else if ( 2 == args.length )\r
+ {\r
+ System.out.println(UnixCrypt.encrypt(args[0], args[1]));\r
+ }\r
+ else\r
+ {\r
+ System.out.println("usage: UnixCrypt <salt> <password>");\r
+ System.out.println("or: \"UnixCrypt list\" to generate a list of password with all possible characters.");\r
+ }\r
+ }\r
+ \r
+}\r
--- /dev/null
+package org.feistymeow.filesystem;\r
+\r
+import java.net.URLDecoder;\r
+\r
+import org.apache.commons.logging.Log;\r
+import org.apache.commons.logging.LogFactory;\r
+\r
+/*\r
+ * Provides access to the relevant paths for a Java application.\r
+ * This class cannot provide static members due to runtime constraints.\r
+ * \r
+ * @author Chris Koeritz\r
+ */\r
+public class PathHelper {\r
+ private static Log c_logger = LogFactory.getLog(PathHelper.class);\r
+ \r
+ // locates the home directory where *this* application is installed.\r
+ // this can be used as a root path for finding configuration files\r
+ // needed by the application.\r
+ public String findHome() {\r
+ String path = ".";\r
+ try {\r
+ path = URLDecoder.decode(getClass().getProtectionDomain().getCodeSource().getLocation().getPath(), "x-www-form-urlencoded");\r
+ // we remove the leading slash that is sometimes present, but only if the path looks.\r
+ // like a dos path.\r
+ if ( (path.length() >=3) && (path.charAt(0) == '/') && (path.charAt(2) == ':') )\r
+ path = path.substring(1);\r
+ // we chop the last component off, because we want an actual path.\r
+ int lastSlash = path.lastIndexOf('/');\r
+ path = path.substring(0, lastSlash);\r
+ } catch (Exception ex) {\r
+ c_logger.error("caught exception during path calculation: " + ex.toString());\r
+ // unknown what we should say here, so we return the default.\r
+ }\r
+ return path;\r
+ } \r
+};\r
+\r
--- /dev/null
+package org.feistymeow.networking;
+
+import java.util.*;
+import java.io.*;
+import java.net.*;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.feistymeow.dragdrop.ListTransferable;
+
+/**
+ * Provides a lightweight way for RNS structures to be accessible over http.
+ *
+ * @Author Chris Koeritz
+ */
+
+/*
+ * original example thanks to Matt Mahoney, at
+ * http://cs.fit.edu/~mmahoney/cse3103/java/Webserver.java
+ */
+
+public class BasicWebServer {
+ static private Log logger = LogFactory.getLog(BasicWebServer.class);
+
+ private int port;
+ private boolean leaving = false; // turns to true when should stop serving.
+ servingThread socketThread;
+ private ServerSocket realSocket;
+
+ BasicWebServer(int portIn) {
+ port = portIn;
+ }
+
+ public void shutDown() {
+ leaving = true;
+ if (realSocket != null) {
+ try {
+ realSocket.close();
+ } catch (IOException e) {
+ }
+ }
+ if (socketThread != null) {
+ // stop it?
+ }
+ }
+
+ public class servingThread implements Runnable {
+ private Thread thread;
+ private ServerSocket serverSocket;
+
+ servingThread(ServerSocket socket) {
+ serverSocket = socket;
+ thread = new Thread(this);
+ thread.start();
+ }
+
+ @Override
+ public void run() {
+ while (!leaving) {
+ try {
+ logger.debug("about to accept on server socket.");
+ Socket s = serverSocket.accept(); // Wait for a client to
+ // connect
+ logger.debug("accepted client, spawning handler.");
+ new ClientHandler(s); // Handle the client in a separate
+ // thread
+ } catch (Throwable cause) {
+ logger.error(
+ "exception raised while handling accepted socket",
+ cause);
+ }
+ }
+ }
+ }
+
+ // enums for outcomes? really need better reporting.
+ public int startServing() {
+ if (socketThread != null)
+ return 1; // already running outcome.
+ try {
+ realSocket = new ServerSocket(port);
+ } catch (Throwable cause) {
+ logger.error("failure to start server on port " + port, cause);
+ return 1;
+ // socket failure outcome.
+ }
+ socketThread = new servingThread(realSocket);
+ return 0;
+ }
+
+ public String predictMimeType(String filename) {
+
+ // kludge to try one type:
+ return "text/plain;charset=utf-8";
+
+ /*
+ *
+ * if (filename.endsWith(".html") || filename.endsWith(".htm")) return
+ * "text/html"; if (filename.endsWith(".jpg") ||
+ * filename.endsWith(".jpeg")) return "image/jpeg"; if
+ * (filename.endsWith(".gif")) return "image/gif"; if
+ * (filename.endsWith(".class")) return "application/octet-stream";
+ * return "text/plain";
+ */
+ }
+
+ // A ClientHandler reads an HTTP request and responds
+ class ClientHandler extends Thread {
+ private Socket socket; // The accepted socket from the Webserver
+
+ // Start the thread in the constructor
+ public ClientHandler(Socket s) {
+ socket = s;
+ start();
+ }
+
+ // Read the HTTP request, respond, and close the connection
+ public void run() {
+ try {
+ logger.debug("into client run(): listening for gets.");
+
+ // Open connections to the socket
+ BufferedReader in = new BufferedReader(new InputStreamReader(
+ socket.getInputStream()));
+ PrintStream out = new PrintStream(new BufferedOutputStream(
+ socket.getOutputStream()));
+
+ // Read filename from first input line "GET /filename.html ..."
+ // or if not in this format, treat as a file not found.
+ String s = in.readLine();
+ logger.debug("request is: " + s); // Log the request
+
+ // Attempt to serve the file. Catch FileNotFoundException and
+ // return an HTTP error "404 Not Found". Treat invalid requests
+ // the same way.
+ String filename = "";
+ StringTokenizer st = new StringTokenizer(s);
+ try {
+
+ boolean transferFile = true;
+ // get the command first.
+ String command = st.nextToken();
+ // Parse the filename from the command.
+ if (st.hasMoreElements() && command.equalsIgnoreCase("GET")
+ && st.hasMoreElements()) {
+ filename = st.nextToken();
+ } else if (st.hasMoreElements()
+ && command.equalsIgnoreCase("HEAD")
+ && st.hasMoreElements()) {
+ filename = st.nextToken();
+ transferFile = false; // don't need to do that, just the
+ // header.
+ } else {
+ logger.error("going to blow file not found exception now.");
+ throw new FileNotFoundException(); // Bad request
+ }
+ logger.info("filename to handle is now: " + filename);
+
+ // Append trailing "/" with "index.html"
+ // /hmmm: may want to make this assume directory.
+ if (filename.endsWith("/"))
+ logger.error("unhandled attempt to get item ending in slash");
+ // if (filename.endsWith("/"))
+ // filename += "index.html";
+
+ // Remove leading / from filename
+ // / while (filename.indexOf("/") == 0)
+ // / filename = filename.substring(1);
+
+ // Replace "/" with "\" in path for PC-based servers
+ filename = filename.replace('/', File.separator.charAt(0));
+
+ logger.info("asking for rns path of " + filename);
+
+ // Check for illegal characters to prevent access to
+ // superdirectories
+ if (filename.indexOf("..") >= 0
+ || filename.indexOf(':') >= 0
+ || filename.indexOf('|') >= 0)
+ throw new FileNotFoundException();
+
+ logger.info("got past filename checks for: " + filename);
+
+ /*
+ * this doesn't actually check that trailing slash is
+ * missing! // If a directory is requested and the trailing
+ * / is missing, // send the client an HTTP request to
+ * append it. (This is // necessary for relative links to
+ * work correctly in the client). if ((new
+ * GeniiPath(filename)).isDirectory()) {
+ * out.print("HTTP/1.0 301 Moved Permanently\r\n" +
+ * "Location: /" + filename + "/\r\n\r\n"); out.close();
+ * return; }
+ */
+
+ // trying to get around worrying about mime types by saying
+ // "just get this there".
+ String mimeType = predictMimeType(filename);
+ // //"application/octet-stream";
+
+ File source = new File(filename);
+ if (!source.exists()) {
+ logger.error("source does not exist for serving: "
+ + filename);
+ // do something!
+ // hmmm: below could be abstracted to more general
+ // denial method.
+ out.println("HTTP/1.1 404 Not Found\r\n"
+ + "Content-type: text/html\r\n\r\n"
+ + "<html><head></head><body>" + filename
+ + " not found</body></html>\n");
+ out.close();
+
+ }
+ out.print("HTTP/1.1 200 OK\r\n" + "Content-type: "
+ + mimeType + "\r\n" + "Connection: close" + "\r\n"
+ // // + "\r\nContent-Length: " + source.size? +
+ // "\r\n"
+ + "\r\n");
+ if (!transferFile) {
+ logger.debug("closing stream for finished HEAD request.");
+ out.close();
+ return;
+ }
+ logger.debug("moving to handle GET request.");
+ InputStream f = source.openInputStream();
+ logger.debug("opened stream on source");
+ // Send file contents to client, then close the connection.
+ byte[] a = new byte[4096];
+ int n;
+ while ((n = f.read(a)) > 0)
+ out.write(a, 0, n);
+ logger.debug("wrote file back for request, closing stream.");
+ out.close();
+ } catch (FileNotFoundException x) {
+ logger.error("failed to find requested file: " + filename);
+ out.println("HTTP/1.1 404 Not Found\r\n"
+ + "Content-type: text/html\r\n\r\n"
+ + "<html><head></head><body>" + filename
+ + " not found</body></html>\n");
+ out.close();
+ }
+ } catch (IOException x) {
+ logger.error("exception blew out in outer area of web server",
+ x);
+ // / System.out.println(x);
+ }
+ }
+ }
+}
--- /dev/null
+package org.feistymeow.process;
+
+//////////////
+//Name : ThreadSpawnerAndWatcher
+//Author : Chris Koeritz
+//Rights : Copyright (c) 2012-$now By University of Virginia
+//////////////
+//This file is free software; you can modify/redistribute it under the terms
+//of the Apache License v2.0: http://www.apache.org/licenses/LICENSE-2.0
+//Feel free to send updates to: [ koeritz@virginia.edu ]
+//////////////
+
+
+// test app by Chris Koeritz.
+
+import java.io.IOException;
+import java.lang.ProcessBuilder;
+import java.lang.Process;
+import java.util.Vector;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.log4j.PropertyConfigurator;
+
+class Defaults
+{
+ public static int CONCURRENT_LAUNCHES = 1000;
+};
+
+// will be spawned multiply and each one will check its one process.
+class ThreadSpawnerAndWatcher implements Runnable
+{
+ private static Log c_logger = LogFactory.getLog(ThreadSpawnerAndWatcher.class);
+
+ private volatile Thread myThread;
+
+ private Vector<String> cmdline;
+
+ private ProcessBuilder procbuild;
+
+ @SuppressWarnings("unchecked")
+ public ThreadSpawnerAndWatcher(Vector<String> command_line)
+ {
+ cmdline = (Vector<String>) command_line.clone();
+ procbuild = new ProcessBuilder(cmdline);
+ }
+
+ /**
+ * Launches the thread and waits for its results.
+ */
+ public void start()
+ {
+ if (null == this.myThread) {
+ this.myThread = new Thread(this);
+ this.myThread.start();
+ }
+ }
+
+ /**
+ * Stops the execution of the ProcessWatchingThread - or tries to.
+ */
+ public void stop()
+ {
+ Thread goAway = myThread;
+ myThread = null;
+ if (null != goAway) {
+ goAway.interrupt();
+ }
+ }
+
+ /**
+ * Returns true if the thread isn't null, i.e. it is still running.
+ */
+ public boolean threadRunning()
+ {
+ return (null != this.myThread);
+ }
+
+ public void run()
+ {
+ if (false == threadRunning()) {
+ return; // stopped before it ever started
+ }
+
+ try {
+ // c_logger.info("about to start process: " + cmdline);
+ Process p = procbuild.start();
+ p.waitFor();
+ // c_logger.info("returned from awaiting process: " + cmdline);
+ } catch (IOException e) {
+ c_logger.debug("thread caught io exception on: " + cmdline);
+ } catch (InterruptedException ie) {
+ c_logger.debug("thread interrupted for: " + cmdline);
+ } finally {
+ this.myThread = null; // thread is exiting
+ }
+ }
+
+ static public void main(String[] args) throws Throwable
+ {
+ PropertyConfigurator.configure("log4j.properties"); // hard-coded for
+ // eclipse based run.
+
+ Vector<String> cmds = new Vector<String>();
+
+ cmds.add("/bin/echo");
+ cmds.add("hello jupiter");
+
+ // cmds.add("/bin/sleep");
+ // cmds.add("10");
+
+ Vector<ThreadSpawnerAndWatcher> watchers = new Vector<ThreadSpawnerAndWatcher>();
+
+ c_logger.info("revving up the process launching test.");
+
+ // create all the threads and get them ready to go.
+ for (int i = 0; i < Defaults.CONCURRENT_LAUNCHES; i++) {
+ ThreadSpawnerAndWatcher newby = new ThreadSpawnerAndWatcher(cmds);
+ watchers.add(newby);
+ }
+
+ // randomize start order?
+ // now start all the threads, which will cause all our process launches.
+ for (int i = 0; i < Defaults.CONCURRENT_LAUNCHES; i++) {
+ ThreadSpawnerAndWatcher curr = watchers.get(i);
+ curr.start();
+ }
+
+ // now wait for them all to finish. if we never get out, then there's a bug
+ // someplace.
+ for (int i = 0; i < Defaults.CONCURRENT_LAUNCHES; i++) {
+ ThreadSpawnerAndWatcher curr = watchers.get(i);
+ while (curr.threadRunning()) {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ // ignore for now.
+ }
+ }
+ }
+
+ // currently test will never come back out to finish, if there's a failure
+ // seen.
+ c_logger.info("Test Succeeded: all spawned processes came back as expected.");
+ System.exit(0);
+ }
+}
--- /dev/null
+\r
+package org.feistymeow.system;\r
+\r
+import java.io.*;\r
+\r
+/*\r
+ * this class supports reading and setting values in the Windows registry.\r
+ * \r
+ * some example code came from http://www.rgagnon.com/javadetails/java-0480.html\r
+ * @author Chris Koeritz\r
+ */\r
+public class RegistryEditor {\r
+\r
+ // the values below can be used for the expected type in the registry calls.\r
+ public static final String STRING_TYPE = "REG_SZ";\r
+ public static final String DOUBLEWORD_TYPE = "REG_DWORD"; \r
+\r
+ // looks up the key provided in the registry and returns true if the key seems to exist.\r
+ // this is just a check for presence; it could have no subkeys or values under it, but it at\r
+ // least seems to be there.\r
+ public static boolean checkKey(String keyName) {\r
+ try {\r
+ // make a command to run in windows that will query the value.\r
+ StringBuilder command = new StringBuilder(QUERY_COMMAND);\r
+ command.append("\"");\r
+ command.append(keyName);\r
+ command.append("\"");\r
+ // start the command running and trap its output.\r
+ Process process = Runtime.getRuntime().exec(command.toString());\r
+ StreamReader reader = new StreamReader(process.getInputStream());\r
+ reader.start();\r
+ process.waitFor(); // let the system call finish up.\r
+ reader.join(); // let the stream reader finish also.\r
+ return process.exitValue() == 0;\r
+ } catch (Exception e) {\r
+ return false;\r
+ }\r
+ }\r
+\r
+ // retrieves the key provided from the registry and selects out the value requested.\r
+ // it is necessary to know the expected type, such as REG_SZ or REG_DWORD.\r
+ // the value is always returned as a string and needs to be cast to different types as appropriate.\r
+ public static String getValue(String keyName, String valueName, String typeExpected) {\r
+ try {\r
+ // make a command to run in windows that will query the value.\r
+ StringBuilder command = new StringBuilder(QUERY_COMMAND);\r
+ command.append("\"");\r
+ command.append(keyName);\r
+ command.append("\"");\r
+ command.append(VALUE_FLAG); \r
+ command.append(valueName);\r
+ // start the command running and trap its output.\r
+ Process process = Runtime.getRuntime().exec(command.toString());\r
+ StreamReader reader = new StreamReader(process.getInputStream());\r
+ reader.start();\r
+ process.waitFor(); // let the system call finish up.\r
+ reader.join(); // let the stream reader finish also.\r
+ // now grab the results from running the command and extract the answer.\r
+ String result = reader.getResult();\r
+ int p = result.indexOf(typeExpected);\r
+ if (p == -1) return null;\r
+ // return the result with the stuff before the type chopped off.\r
+ return result.substring(p + typeExpected.length()).trim();\r
+ } catch (Exception e) {\r
+ return null;\r
+ }\r
+ }\r
+\r
+ // makes a change to the specified "keyName" value called "valueName". the old value will be replaced\r
+ // with the "newValue" provided. the key and the value do not have to exist prior to the call, but if\r
+ // they already did exist, they'll be updated.\r
+ public static boolean setValue(String keyName, String valueName, String typeExpected, String newValue) {\r
+ try {\r
+ // make a command to run in windows that will set the value.\r
+ StringBuilder command = new StringBuilder(SET_COMMAND);\r
+ command.append("\"");\r
+ command.append(keyName);\r
+ command.append("\"");\r
+ command.append(VALUE_FLAG); \r
+ command.append(valueName);\r
+ command.append(TYPE_FLAG);\r
+ command.append(typeExpected);\r
+ command.append(FORCE_FLAG);\r
+ command.append(DATA_FLAG);\r
+ command.append(newValue);\r
+ //System.out.println("command to run: " + command);\r
+ // start the command running and trap its output.\r
+ Process process = Runtime.getRuntime().exec(command.toString());\r
+ StreamReader reader = new StreamReader(process.getInputStream());\r
+ reader.start();\r
+ process.waitFor(); // let the system call finish up.\r
+ reader.join(); // let the stream reader finish also.\r
+ return (process.exitValue() == 0); // zero exit is a success.\r
+ } catch (Exception e) {\r
+ return false;\r
+ }\r
+ }\r
+\r
+ // removes the "valueName" value from the key "keyName". true is returned on success.\r
+ public static boolean deleteValue(String keyName, String valueName) {\r
+ try {\r
+ // make a command to run in windows that will set the value.\r
+ StringBuilder command = new StringBuilder(DELETE_COMMAND);\r
+ command.append("\"");\r
+ command.append(keyName);\r
+ command.append("\"");\r
+ command.append(VALUE_FLAG);\r
+ command.append(valueName);\r
+ command.append(FORCE_FLAG);\r
+ //System.out.println("command to run: " + command);\r
+ // start the command running and trap its output.\r
+ Process process = Runtime.getRuntime().exec(command.toString());\r
+ StreamReader reader = new StreamReader(process.getInputStream());\r
+ reader.start();\r
+ process.waitFor(); // let the system call finish up.\r
+ reader.join(); // let the stream reader finish also.\r
+ return (process.exitValue() == 0); // zero exit is a success.\r
+ } catch (Exception e) {\r
+ return false;\r
+ }\r
+ } \r
+\r
+ // removes the entire key "keyName" from the registry. true is returned on success.\r
+ public static boolean deleteKey(String keyName) {\r
+ try {\r
+ // make a command to run in windows that will set the value.\r
+ StringBuilder command = new StringBuilder(DELETE_COMMAND);\r
+ command.append("\"");\r
+ command.append(keyName);\r
+ command.append("\"");\r
+ command.append(FORCE_FLAG);\r
+ //System.out.println("command to run: " + command);\r
+ // start the command running and trap its output.\r
+ Process process = Runtime.getRuntime().exec(command.toString());\r
+ StreamReader reader = new StreamReader(process.getInputStream());\r
+ reader.start();\r
+ process.waitFor(); // let the system call finish up.\r
+ reader.join(); // let the stream reader finish also.\r
+ return (process.exitValue() == 0); // zero exit is a success.\r
+ } catch (Exception e) {\r
+ return false;\r
+ }\r
+ }\r
+\r
+ // constants used in the registry code for talking to windows' reg application.\r
+ private static final String QUERY_COMMAND = "reg query ";\r
+ private static final String VALUE_FLAG = " /v ";\r
+\r
+ private static final String SET_COMMAND = "reg add ";\r
+ private static final String TYPE_FLAG = " /t ";\r
+ private static final String DATA_FLAG = " /d ";\r
+ private static final String FORCE_FLAG = " /f ";\r
+\r
+ private static final String DELETE_COMMAND = "reg delete ";\r
+\r
+ // wrapper class for stream reading came from web example mentioned above. \r
+ static class StreamReader extends Thread {\r
+ private InputStream is;\r
+ private StringWriter sw;\r
+\r
+ StreamReader(InputStream is) {\r
+ this.is = is;\r
+ sw = new StringWriter();\r
+ }\r
+\r
+ public void run() {\r
+ int c;\r
+ try {\r
+ while ((c = is.read()) != -1) sw.write(c);\r
+ } catch (IOException e) { /*nothing*/ }\r
+ }\r
+\r
+ String getResult() { return sw.toString(); }\r
+ }\r
+}\r
--- /dev/null
+package org.feistymeow.system;\r
+\r
+import static org.junit.Assert.*;\r
+import org.junit.*;\r
+\r
+import org.feistymeow.system.RegistryEditor;\r
+\r
+/**\r
+ * RegistryEditor junit tests.\r
+ * \r
+ * @author Chris Koeritz\r
+ *\r
+ */\r
+public class RegistryEditorTestCase \r
+{ \r
+ @Before\r
+ public void setUp() throws Exception \r
+ {\r
+ }\r
+\r
+ @After\r
+ public void tearDown() throws Exception \r
+ {\r
+ }\r
+\r
+ @Test\r
+ public void testCheckKey_missing() {\r
+ // this key cannot exist, since we're not allowed to write at that\r
+ // top level hive (as far as we know).\r
+ assertFalse(RegistryEditor.checkKey("HKLM\\flaubert\\maximus"));\r
+ }\r
+\r
+ @Test\r
+ public void testCheckKey_present() {\r
+ // this key must always exist as far as we know.\r
+ assertTrue(RegistryEditor.checkKey("HKLM\\Software"));\r
+ }\r
+\r
+ @Test\r
+ public void testCheckKey_bad() {\r
+ assertFalse(RegistryEditor.checkKey(null));\r
+ }\r
+\r
+ @Test\r
+ public void testGetValue_present() {\r
+ String PERSONAL_FOLDER_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";\r
+ String PERSONAL_FOLDER_VALUE = "Personal";\r
+ assertNotNull(RegistryEditor.getValue(PERSONAL_FOLDER_KEY, PERSONAL_FOLDER_VALUE,\r
+ RegistryEditor.STRING_TYPE)); \r
+ }\r
+\r
+ @Test\r
+ public void testGetValue_missing() {\r
+ String PERSONAL_FOLDER_KEY = "HKCU\\Flombix\\Gruntnork";\r
+ String PERSONAL_FOLDER_VALUE = "Personalish";\r
+ assertNull(RegistryEditor.getValue(PERSONAL_FOLDER_KEY, PERSONAL_FOLDER_VALUE,\r
+ RegistryEditor.STRING_TYPE)); \r
+ }\r
+\r
+ @Test\r
+ public void testSetValueAndRemove_AllWork()\r
+ {\r
+ String EXAMPLE_KEY_ROOT = "HKCU\\Software\\SpunkMaster5000";\r
+ String EXAMPLE_KEY = EXAMPLE_KEY_ROOT + "\\traumix";\r
+ String EXAMPLE_VALUE = "glonkish";\r
+ String EXAMPLE_CONTENTS1 = "ralphWiggum!";\r
+ String EXAMPLE_CONTENTS2 = "moeSzyslak?";\r
+\r
+ // first try deleting the value. this should fail to start with.\r
+ assertFalse(RegistryEditor.deleteValue(EXAMPLE_KEY, EXAMPLE_VALUE));\r
+ // remove the entire key if present.\r
+ assertFalse(RegistryEditor.deleteKey(EXAMPLE_KEY_ROOT));\r
+ // now test that it really doesn't seem to be there.\r
+ assertFalse(RegistryEditor.checkKey(EXAMPLE_KEY));\r
+//System.out.println("now setting key [" + EXAMPLE_KEY + "] value [" + EXAMPLE_VALUE + "] to '" + EXAMPLE_CONTENTS1 + "'");\r
+ // now try adding the example value.\r
+ assertTrue(RegistryEditor.setValue(EXAMPLE_KEY, EXAMPLE_VALUE, RegistryEditor.STRING_TYPE, EXAMPLE_CONTENTS1));\r
+ // check that the contents are what we expect.\r
+ assertEquals(RegistryEditor.getValue(EXAMPLE_KEY, EXAMPLE_VALUE, RegistryEditor.STRING_TYPE),\r
+ EXAMPLE_CONTENTS1);\r
+ // now change the value's contents to a new setting.\r
+ assertTrue(RegistryEditor.setValue(EXAMPLE_KEY, EXAMPLE_VALUE, RegistryEditor.STRING_TYPE, EXAMPLE_CONTENTS2));\r
+ // make sure the update has succeeded.\r
+ assertEquals(RegistryEditor.getValue(EXAMPLE_KEY, EXAMPLE_VALUE, RegistryEditor.STRING_TYPE),\r
+ EXAMPLE_CONTENTS2);\r
+ // now whack the value we had added.\r
+ assertTrue(RegistryEditor.deleteValue(EXAMPLE_KEY, EXAMPLE_VALUE));\r
+ // now remove the entire key we added.\r
+ assertTrue(RegistryEditor.deleteKey(EXAMPLE_KEY_ROOT));\r
+ }\r
+\r
+}\r
+\r
--- /dev/null
+package org.feistymeow.utility;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+//////////////
+// Name : Extemporizer
+// Author : Chris Koeritz
+// Rights : Copyright (c) 2012-$now By University of Virginia
+//////////////
+// This file is free software; you can modify/redistribute it under the terms
+// of the Apache License v2.0: http://www.apache.org/licenses/LICENSE-2.0
+// Feel free to send updates to: [ koeritz@virginia.edu ]
+//////////////
+
+/**
+ * A set of useful utilities for dealing with temporary items.
+ */
+public class Extemporizer
+{
+ static private Log _logger = LogFactory.getLog(Extemporizer.class);
+
+ /**
+ * creates a uniquely named temporary directory. thanks for guidance to article at:
+ * http://stackoverflow.com/questions/617414/create-a-temporary-directory-in-java
+ *
+ * @return a File object pointing at the new temporary directory.
+ * @throws IOException
+ */
+ public static File createTempDirectory(String prefix, String suffix)
+ {
+ if ((prefix == null) || (suffix == null))
+ return null;
+ try {
+ final File temp = File.createTempFile(prefix, suffix);
+ if (!temp.delete())
+ throw new IOException("failed to delete temporary file: " + temp.getAbsolutePath());
+ if (!temp.mkdir())
+ throw new IOException("failed to create temporary directory: "
+ + temp.getAbsolutePath());
+ temp.deleteOnExit(); // set for cleanup.
+ return temp;
+ } catch (Throwable cause) {
+ _logger.error("caught exception while creating temporary directory", cause);
+ return null;
+ }
+ }
+}
--- /dev/null
+package org.feistymeow.utility;\r
+\r
+/*\r
+ * Some helper methods that retrieve the function and class names where code is executing.\r
+ * This can be helpful for doing very specific logging, and will work even if the log4j\r
+ * settings have turned off the function names and such (given that you really want to\r
+ * see those in a log entry). \r
+ * \r
+ * @author Chris Koeritz\r
+ */\r
+public class Naming {\r
+\r
+ // returns the name of the function invoking this method.\r
+ public static String thisFunctionName() {\r
+ Throwable ex = new Throwable();\r
+ StackTraceElement[] trace = ex.getStackTrace();\r
+ // StackTrace trace = new StackTrace(0, true);\r
+ String meth = trace[0].getMethodName(); // this should be *this*\r
+ // function.\r
+ for (int i = 1; i < trace.length; i++) {\r
+ if ((trace[i].getMethodName() != meth)\r
+ && (!trace[i].getMethodName().contains("formatted_names"))) {\r
+ // we've gone back far enough.\r
+ return trace[i].getMethodName();\r
+ }\r
+ }\r
+ return "unknown";\r
+ }\r
+\r
+ // provides a method to get the current class name and function name without\r
+ // needing to embed a lot of code into individual functions.\r
+ public static String thisClassName() {\r
+ Throwable ex = new Throwable();\r
+ StackTraceElement[] trace = ex.getStackTrace();\r
+ // StackTrace trace = new StackTrace(0, true);\r
+\r
+ String meth = trace[0].getMethodName(); // this should be *this*\r
+ // function.\r
+ for (int i = 1; i < trace.length; i++) {\r
+ String currClass = trace[i].getClassName();\r
+ if ((trace[i].getMethodName() != meth)\r
+ && (!trace[i].getMethodName().contains("formatted_names"))) {\r
+ // we've gone back far enough.\r
+ String simpleClassName = extractSimpleClassName(currClass);\r
+ return simpleClassName;\r
+ }\r
+ }\r
+ return "unknown";\r
+ }\r
+\r
+ public String thisPackageName() {\r
+ Throwable ex = new Throwable();\r
+ StackTraceElement[] trace = ex.getStackTrace();\r
+ // StackTrace trace = new StackTrace(0, true);\r
+\r
+ String meth = trace[0].getMethodName(); // this should be *this*\r
+ // function.\r
+ for (int i = 1; i < trace.length; i++) {\r
+ String currClass = trace[i].getClassName();\r
+ if ((trace[i].getMethodName() != meth)\r
+ && (!trace[i].getMethodName().contains("formatted_names"))) {\r
+ // we've gone back far enough.\r
+ String packageName = extractPackageName(currClass);\r
+ return packageName;\r
+ }\r
+ }\r
+ return "unknown";\r
+ }\r
+\r
+ public static String extractPackageName(String fullClassName) {\r
+ if ((null == fullClassName) || ("".equals(fullClassName)))\r
+ return "";\r
+\r
+ // The package name is everything preceding the last dot.\r
+ // Is there a dot in the name?\r
+ int lastDot = fullClassName.lastIndexOf('.');\r
+\r
+ // Note that by fiat, I declare that any class name that has been\r
+ // passed in which starts with a dot doesn't have a package name.\r
+ if (0 >= lastDot)\r
+ return "";\r
+\r
+ // Otherwise, extract the package name.\r
+ return fullClassName.substring(0, lastDot);\r
+ }\r
+\r
+ public static String extractSimpleClassName(String fullClassName) {\r
+ if ((null == fullClassName) || ("".equals(fullClassName)))\r
+ return "";\r
+\r
+ // The simple class name is everything after the last dot.\r
+ // If there's no dot then the whole thing is the class name.\r
+ int lastDot = fullClassName.lastIndexOf('.');\r
+ if (0 > lastDot)\r
+ return fullClassName;\r
+\r
+ // Otherwise, extract the class name.\r
+ return fullClassName.substring(++lastDot);\r
+ }\r
+\r
+ // returns a nicely formatted string containing the class and function name.\r
+ // the string also contains a colon and space on the end so other text\r
+ // can be concatenated right up against it while still being readable.\r
+ public static String formatted_names() {\r
+ String class_name = thisClassName();\r
+ String function_name = thisFunctionName();\r
+ return class_name + "." + function_name + ": ";\r
+ }\r
+};\r
--- /dev/null
+package org.feistymeow.windowing;\r
+\r
+import java.awt.*;\r
+import java.awt.event.*;\r
+\r
+/** A listener that you attach to the top-level Frame or JFrame of\r
+ * your application, so quitting the frame exits the application.\r
+ * 1998-99 Marty Hall, http://www.apl.jhu.edu/~hall/java/\r
+ */\r
+\r
+public class ExitListener extends WindowAdapter {\r
+ public void windowClosing(WindowEvent event) {\r
+ System.exit(0);\r
+ }\r
+}\r
--- /dev/null
+package org.feistymeow.windowing;\r
+\r
+import javax.swing.*;\r
+import java.awt.*;\r
+\r
+/** A few utilities that simplify using windows in Swing.\r
+ * 1998-99 Marty Hall, http://www.apl.jhu.edu/~hall/java/\r
+ */\r
+\r
+public class WindowUtilities {\r
+\r
+ /** Tell system to use native look and feel, as in previous\r
+ * releases. Metal (Java) LAF is the default otherwise.\r
+ */\r
+\r
+ public static void setNativeLookAndFeel() {\r
+ try {\r
+ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\r
+ } catch(Exception e) {\r
+ System.out.println("Error setting native LAF: " + e);\r
+ }\r
+ }\r
+\r
+ public static void setJavaLookAndFeel() {\r
+ try {\r
+ UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());\r
+ } catch(Exception e) {\r
+ System.out.println("Error setting Java LAF: " + e);\r
+ }\r
+ }\r
+\r
+ public static void setMotifLookAndFeel() {\r
+ try {\r
+ UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");\r
+ } catch(Exception e) {\r
+ System.out.println("Error setting Motif LAF: " + e);\r
+ }\r
+ }\r
+\r
+ /** A simplified way to see a JPanel or other Container.\r
+ * Pops up a JFrame with specified Container as the content pane.\r
+ */\r
+\r
+ public static JFrame openInJFrame(Container content,\r
+ int width,\r
+ int height,\r
+ String title,\r
+ Color bgColor) {\r
+ JFrame frame = new JFrame(title);\r
+ frame.setBackground(bgColor);\r
+ content.setBackground(bgColor);\r
+ frame.setSize(width, height);\r
+ frame.setContentPane(content);\r
+ frame.addWindowListener(new ExitListener());\r
+ frame.setVisible(true);\r
+ return(frame);\r
+ }\r
+\r
+ /** Uses Color.white as the background color. */\r
+\r
+ public static JFrame openInJFrame(Container content,\r
+ int width,\r
+ int height,\r
+ String title) {\r
+ return(openInJFrame(content, width, height, title, Color.white));\r
+ }\r
+\r
+ /** Uses Color.white as the background color, and the\r
+ * name of the Container's class as the JFrame title.\r
+ */\r
+\r
+ public static JFrame openInJFrame(Container content,\r
+ int width,\r
+ int height) {\r
+ return(openInJFrame(content, width, height,\r
+ content.getClass().getName(),\r
+ Color.white));\r
+ }\r
+}\r
--- /dev/null
+
+
+package test.java.semantics;
+
+import java.util.List;
+
+class instance_of
+{
+ public instance_of() {}
+
+ public Object cogitate() {
+ return null;
+ }
+
+ public static void main(String s[]) throws Exception
+ {
+ // we are just asserting that it is safe to do instanceof on an object that is null.
+ // let's test that theory.
+ instance_of tony = new instance_of();
+ Object fred = tony.cogitate(); // will produce null.
+ if (fred instanceof List<?>) {
+ throw new Exception("that should not have happened!");
+ } else {
+ System.out.println("told us null is not an instance of List, which is correct.");
+ }
+
+ }
+
+}
\ No newline at end of file