Various changes to support compatibility with Java 9 and code cleanups.

This commit is contained in:
Norberto Lopez
2018-03-27 22:48:07 +00:00
parent ed4a00ab8b
commit 9d153c83aa
33 changed files with 424 additions and 581 deletions

View File

@@ -1,9 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="lib/miglayout-3.7.2-swing.jar" sourcepath="lib/miglayout-3.7.2-sources.jar"/>
<classpathentry kind="lib" path="lib/dockingFramesCore.jar" sourcepath="lib/dockingFramesCore-src.jar"/>
<classpathentry kind="lib" path="lib/guava-12.0.jar" sourcepath="lib/guava-12.0-sources.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jdk1.8.0_31">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="lib/guava-18.0.jar" sourcepath="lib/guava-18.0-sources.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="lib/dockingFramesCore.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="lib/miglayout-3.7.2-swing.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -4,15 +4,8 @@
<options buildIfNeeded="true" compress="true" descriptionLocation="/glum/buildGlumBin.jardesc" exportErrors="false" exportWarnings="true" includeDirectoryEntries="false" overwrite="true" saveDescription="false" storeRefactorings="false" useSourceFolders="false"/>
<storedRefactorings deprecationInfo="true" structuralOnly="false"/>
<selectedProjects/>
<manifest generateManifest="false" manifestLocation="/glum/src/Manifest.txt" manifestVersion="1.0" reuseManifest="false" saveManifest="false" usesManifest="true">
<sealing sealJar="false">
<packagesToSeal/>
<packagesToUnSeal/>
</sealing>
</manifest>
<selectedElements exportClassFiles="true" exportJavaFiles="false" exportOutputFolder="false">
<javaElement handleIdentifier="=glum/src"/>
<folder path="/glum/build/doc"/>
<folder path="/glum/build/classes"/>
</selectedElements>
</jardesc>

View File

@@ -4,15 +4,7 @@
<options buildIfNeeded="true" compress="true" descriptionLocation="/glum/buildGlumSrc.jardesc" exportErrors="false" exportWarnings="true" includeDirectoryEntries="false" overwrite="true" saveDescription="false" storeRefactorings="false" useSourceFolders="false"/>
<storedRefactorings deprecationInfo="true" structuralOnly="false"/>
<selectedProjects/>
<manifest generateManifest="false" manifestLocation="/glum/src/Manifest.txt" manifestVersion="1.0" reuseManifest="false" saveManifest="false" usesManifest="false">
<sealing sealJar="false">
<packagesToSeal/>
<packagesToUnSeal/>
</sealing>
</manifest>
<selectedElements exportClassFiles="false" exportJavaFiles="true" exportOutputFolder="false">
<javaElement handleIdentifier="=glum/src"/>
<folder path="/glum/build/doc"/>
<folder path="/glum/build/classes"/>
</selectedElements>
</jardesc>

Binary file not shown.

Binary file not shown.

BIN
lib/guava-18.0-sources.jar Normal file

Binary file not shown.

BIN
lib/guava-18.0.jar Normal file

Binary file not shown.

View File

@@ -1 +0,0 @@
Class-Path: lib/guava-12.0.jar lib/miglayout-3.7.2-sources.jar

View File

@@ -1,16 +1,16 @@
package glum.gui;
import glum.gui.icon.IconUtil;
import glum.reflect.Function;
import glum.reflect.FunctionRunnable;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Collection;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.event.ChangeListener;
import glum.gui.icon.IconUtil;
import glum.reflect.Function;
public class GuiUtil
{
/**
@@ -144,12 +144,12 @@ public class GuiUtil
/**
* Creates a JComboBox with the specified settings
*/
public static JComboBox createJComboBox(ActionListener aListener, Font aFont, Object... itemArr)
public static <G1> JComboBox<G1> createJComboBox(ActionListener aListener, Font aFont, Collection<G1> aItemL)
{
JComboBox tmpBox;
JComboBox<G1> tmpBox;
tmpBox = new JComboBox();
for (Object aItem : itemArr)
tmpBox = new JComboBox<G1>();
for (G1 aItem : aItemL)
tmpBox.addItem(aItem);
if (aFont != null)
@@ -209,7 +209,7 @@ public class GuiUtil
/**
* Utility method for creating a visual thin divider
*
* <P>
* Typically added to MigLayout (or like manager) with: add(aComp, "growx,h 4!,span,wrap");
*/
public static JPanel createDivider()
@@ -652,7 +652,7 @@ public class GuiUtil
/**
* Utility method that checks to ensure the current thread is running on the ATW thread. If it is NOT then the
* specified function will be posted so that it is called on the AWT thread. If it is running on the AWT thread then
* specified Runnable will be posted so that it is called on the AWT thread. If it is running on the AWT thread then
* nothing will happen and this method will return false.
* <P>
* Typically this utility method is called at the start of a function to ensure it is on the AWT thread, and if not
@@ -665,6 +665,7 @@ public class GuiUtil
* public void actionPerformed(aEvent)
* {
* // Ensure this method is run on the AWT thread
* Runnable tmpRunnable = ()-> actionPerformed(aEvent);
* if (redispatchOnAwtIfNeeded(this, "actionPerformed", aEvent) = true)
* return;
*
@@ -672,16 +673,13 @@ public class GuiUtil
* }
* </PRE>
*/
public static boolean redispatchOnAwtIfNeeded(Object aObj, String methodName, Object... aArgArr)
public static boolean redispatchOnAwtIfNeeded(Runnable aRunnable)
{
FunctionRunnable aFunctionRunnable;
// Do nothing if this is the AWT thread
if (SwingUtilities.isEventDispatchThread() == true)
return false;
aFunctionRunnable = new FunctionRunnable(aObj, methodName, aArgArr);
SwingUtilities.invokeLater(aFunctionRunnable);
SwingUtilities.invokeLater(aRunnable);
return true;
}

View File

@@ -18,7 +18,7 @@ public class GComboBox<G1> extends JComboBox<G1>
setModel(itemModel);
}
public GComboBox(ActionListener aListener, ListCellRenderer aRenderer)
public GComboBox(ActionListener aListener, ListCellRenderer<? super G1> aRenderer)
{
this();
@@ -158,7 +158,7 @@ public class GComboBox<G1> extends JComboBox<G1>
for (ActionListener aListener : listenerArr)
addActionListener(aListener);
}
// Note you cannot do the below as internal methods within JComboBox make calls to
// the methods below.
// @Override

View File

@@ -20,9 +20,9 @@ import com.google.common.collect.Lists;
public class GList<G1> extends JComponent implements GenericCodes, ListSelectionListener
{
// Gui vars
private JList refList;
private JList<G1> refList;
private GListModel<G1> refModel;
// State vars
private ActionListener refActionListener;
private ListSelectionListener refListSelectionListener;
@@ -31,36 +31,36 @@ public class GList<G1> extends JComponent implements GenericCodes, ListSelection
{
refActionListener = null;
refListSelectionListener = null;
refModel = new GListModel<G1>(aItemList);
refList = new JList(refModel);
refModel = new GListModel<>(aItemList);
refList = new JList<>(refModel);
buildGui(aListener);
}
public GList(Object aListener, G1... aItemArr)
{
refActionListener = null;
refListSelectionListener = null;
refModel = new GListModel<G1>(aItemArr);
refList = new JList(refModel);
buildGui(aListener);
}
// public GList(Object aListener, G1... aItemArr)
// {
// refActionListener = null;
// refListSelectionListener = null;
//
// refModel = new GListModel<G1>(aItemArr);
// refList = new JList<>(refModel);
// buildGui(aListener);
// }
//
/**
* Returns the (first) selected item
*/
public G1 getSelectedItem()
{
int selectedIndex;
selectedIndex = refList.getSelectedIndex();
if (selectedIndex == -1)
return null;
return refModel.getElementAt(selectedIndex);
}
/**
* Returns all of the selected items
*/
@@ -68,17 +68,17 @@ public class GList<G1> extends JComponent implements GenericCodes, ListSelection
{
ArrayList<G1> retList;
int[] indexArr;
indexArr = refList.getSelectedIndices();
retList = Lists.newArrayList();
for (int aIndex : indexArr)
retList.add(refModel.getElementAt(aIndex));
retList.trimToSize();
return retList;
}
/**
* Replaces all of the items in the list with aItemList.
*/
@@ -88,7 +88,7 @@ public class GList<G1> extends JComponent implements GenericCodes, ListSelection
refList.setModel(new GListModel<G1>(aItemList));
refList.addListSelectionListener(this);
}
/**
* Sets aItem as the selected item.
*/
@@ -106,13 +106,13 @@ public class GList<G1> extends JComponent implements GenericCodes, ListSelection
{
int[] idArr;
int c1;
// Ensure we are executed only on the proper thread
if (SwingUtilities.isEventDispatchThread() == false)
throw new RuntimeException("GList.selectItems() not executed on the AWT event dispatch thread.");
refList.removeListSelectionListener(this);
c1 = 0;
idArr = new int[aItemList.size()];
for (G1 aItem : aItemList)
@@ -122,10 +122,10 @@ public class GList<G1> extends JComponent implements GenericCodes, ListSelection
}
refList.setSelectedIndices(idArr);
refList.addListSelectionListener(this);
}
@Override
public void setEnabled(boolean aBool)
{
@@ -137,7 +137,7 @@ public class GList<G1> extends JComponent implements GenericCodes, ListSelection
{
if (refListSelectionListener != null)
refListSelectionListener.valueChanged(new ListSelectionEvent(this, aEvent.getFirstIndex(), aEvent.getLastIndex(), aEvent.getValueIsAdjusting()));
if (refActionListener != null)
refActionListener.actionPerformed(new ActionEvent(this, ID_UPDATE, "update"));
}
@@ -151,9 +151,9 @@ public class GList<G1> extends JComponent implements GenericCodes, ListSelection
refActionListener = (ActionListener)aListener;
if (aListener instanceof ListSelectionListener)
refListSelectionListener = (ListSelectionListener)aListener;
setLayout(new BorderLayout());
add(refList);
}
}

View File

@@ -5,7 +5,7 @@ import javax.swing.ComboBoxModel;
import com.google.common.collect.Lists;
public class GComboBoxModel<G1> extends GListModel<G1> implements ComboBoxModel
public class GComboBoxModel<G1> extends GListModel<G1> implements ComboBoxModel<G1>
{
protected G1 chosenItem;
@@ -13,11 +13,11 @@ public class GComboBoxModel<G1> extends GListModel<G1> implements ComboBoxModel
{
this(Lists.newArrayList(aItemArr));
}
public GComboBoxModel(Collection<G1> aItemList)
{
super(aItemList);
chosenItem = null;
if (itemList.size() > 0)
chosenItem = itemList.get(0);
@@ -28,20 +28,20 @@ public class GComboBoxModel<G1> extends GListModel<G1> implements ComboBoxModel
{
if (chosenItem == null)
chosenItem = aItem;
super.addItem(aItem);
}
@Override
public void removeItem(G1 aItem)
{
super.removeItem(aItem);
chosenItem = null;
if (itemList.size() > 0)
chosenItem = itemList.get(0);
}
/**
* Note aItem must be of the Generified type
*/

View File

@@ -11,7 +11,7 @@ import com.google.common.collect.Lists;
/**
* Generified mutable ListModel
*/
public class GListModel<G1> extends AbstractListModel
public class GListModel<G1> extends AbstractListModel<G1>
{
protected List<G1> itemList;
@@ -20,11 +20,11 @@ public class GListModel<G1> extends AbstractListModel
itemList = Lists.newArrayList(aItemList);
}
public GListModel(G1... aItemArr)
{
itemList = Lists.newArrayList(aItemArr);
}
// public GListModel(G1... aItemArr)
// {
// itemList = Lists.newArrayList(aItemArr);
// }
//
/**
* Adds aItem to this model
*/

View File

@@ -170,7 +170,7 @@ public class PrimDockFactory implements DockFactory<PrimDock, DefaultDockablePer
if (spawnConstructor != null)
rDockable = spawnConstructor.newInstance(parmValues);
else
rDockable = spawnClass.newInstance();
rDockable = spawnClass.getDeclaredConstructor().newInstance();
}
catch (Exception aExp)
{

View File

@@ -99,7 +99,7 @@ public class NumberDocument extends BaseNumberDocument
// Ensure that the number is in range
if (aVal > maxVal)
throw new BadLocationException("Out of numerical range.", offs);
else if (aVal < minVal)
else if (aVal < minVal && resultStr.length() >= ("" + maxVal).length())
throw new BadLocationException("Out of numerical range.", offs);
// Insert the string

View File

@@ -1,19 +1,20 @@
package glum.gui.panel;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import glum.gui.component.GNumberField;
import glum.unit.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.miginfocom.swing.MigLayout;
import glum.gui.component.GNumberField;
import glum.unit.ConstUnitProvider;
import glum.unit.NumberUnit;
import glum.unit.UnitProvider;
public class ColorInputPanel extends JPanel implements ActionListener, ChangeListener
public class ColorInputPanel extends GPanel implements ActionListener, ChangeListener
{
// Constants
private static final Font miniFont = new Font("Serif", Font.PLAIN, 10);
@@ -24,54 +25,22 @@ public class ColorInputPanel extends JPanel implements ActionListener, ChangeLis
private JSlider redS, greenS, blueS;
private GNumberField redNF, greenNF, blueNF;
// State vars
private Collection<ActionListener> myActionListeners;
/**
* Constructor
*/
public ColorInputPanel(boolean isHorizontal, boolean showTF)
{
super();
// Init internal vars
myActionListeners = new LinkedHashSet<ActionListener>();
// Build the gui areas
buildGuiArea(isHorizontal, showTF);
// Set in the default color
setColor(Color.BLACK);
}
/**
* addActionListener
*/
public synchronized void addActionListener(ActionListener aActionListener)
{
// Insanity check
if (aActionListener == null)
return;
myActionListeners.add(aActionListener);
}
/**
* removeActionListener
*/
public synchronized void removeActionListener(ActionListener aActionListener)
{
// Insanity check
if (aActionListener == null)
return;
myActionListeners.remove(aActionListener);
setColorConfig(Color.BLACK);
}
/**
* Returns the selected color
*/
public Color getColor()
public Color getColorConfig()
{
int redVal, greenVal, blueVal;
@@ -82,9 +51,9 @@ public class ColorInputPanel extends JPanel implements ActionListener, ChangeLis
}
/**
* Sets in the current selected color
* Sets in the current selected color.
*/
public void setColor(Color aColor)
public void setColorConfig(Color aColor)
{
// Insanity check
if (aColor == null)
@@ -103,7 +72,7 @@ public class ColorInputPanel extends JPanel implements ActionListener, ChangeLis
updateGui(source);
// Notify the listeners
fireActionEvent(false);
notifyListeners(source, ID_UPDATE);
}
@Override
@@ -138,9 +107,9 @@ public class ColorInputPanel extends JPanel implements ActionListener, ChangeLis
// Fire off an event only if not being updated
aSlider = (JSlider)source;
if (aSlider.getValueIsAdjusting() == false)
fireActionEvent(false);
notifyListeners(source, ID_UPDATE);
else
fireActionEvent(true);
notifyListeners(source, ID_UPDATING);
}
}
@@ -244,33 +213,6 @@ public class ColorInputPanel extends JPanel implements ActionListener, ChangeLis
return aPanel;
}
/**
* Notifies all listeners of color change
*/
private void fireActionEvent(boolean isChanging)
{
Collection<ActionListener> currListeners;
ActionEvent aEvent;
// Get a copy of the current set of listeners
synchronized(this)
{
currListeners = new LinkedHashSet<ActionListener>(myActionListeners);
}
// Construct the event
if (isChanging == false)
aEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Color changed.");
else
aEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Color changing.");
// Notify our listeners
for (ActionListener aListener : currListeners)
{
aListener.actionPerformed(aEvent);
}
}
/**
* Syncs the GUI to match aColor
*/

View File

@@ -4,47 +4,68 @@ import glum.gui.panel.generic.GenericCodes;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.*;
import javax.swing.JPanel;
import com.google.common.collect.Lists;
/**
* JPanel that supports registration of ActionListeners. Derived classes will be responsible for determining when an ActionEvent should be fired.
*/
public class GPanel extends JPanel implements GenericCodes
{
// State vars
protected List<ActionListener> myListeners;
protected Set<ActionListener> myListeners;
public GPanel()
{
super();
myListeners = Lists.newLinkedList();
myListeners = new LinkedHashSet<>();
}
/**
* Add an ActionListener to this GPanel
*/
public void addActionListener(ActionListener aListener)
public synchronized void addActionListener(ActionListener aListener)
{
// Insanity check
if (aListener == null)
throw new RuntimeException("Listener should not be null.");
myListeners.add(aListener);
}
/**
* Remove an ActionListener to this GPanel
*/
public void removeActionListener(ActionListener aListener)
public synchronized void removeActionListener(ActionListener aListener)
{
myListeners.remove(aListener);
}
/**
* Send out notification to all of the ActionListeners
*/
public void notifyListeners(Object aSource, int aId, String aCommand)
{
for (ActionListener aListener : myListeners)
Set<ActionListener> tmpListeners;
// Get a copy of the current set of listeners
synchronized (this)
{
tmpListeners = new LinkedHashSet<>(myListeners);
}
// Notify our listeners
for (ActionListener aListener : tmpListeners)
aListener.actionPerformed(new ActionEvent(aSource, aId, aCommand));
}
/**
* Send out notification to all of the ActionListeners
*/
public void notifyListeners(Object aSource, int aId)
{
notifyListeners(aSource, aId, "");
}
}

View File

@@ -4,8 +4,10 @@ public interface GenericCodes
{
// Constants
public static final int ID_UNDEFINED = 0;
public static final int ID_UPDATE = 10;
public static final int ID_ACCEPT = 11;
public static final int ID_CANCEL = 12;
public static final int ID_ACCEPT = 10;
public static final int ID_CANCEL = 11;
public static final int ID_UPDATE = 20;
public static final int ID_UPDATING = 21;
}

View File

@@ -15,7 +15,7 @@ public class SearchBoxRenderer extends DefaultListCellRenderer
}
@Override
public Component getListCellRendererComponent(JList list, Object aObj, int index, boolean isSelected, boolean hasFocus)
public Component getListCellRendererComponent(JList<?> list, Object aObj, int index, boolean isSelected, boolean hasFocus)
{
JLabel retL;
String aStr;

View File

@@ -1,11 +1,13 @@
package glum.gui.panel.itemList.query;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import com.google.common.base.Preconditions;
import com.google.common.collect.*;
import glum.unit.UnitProvider;
@@ -14,24 +16,24 @@ public class QueryComposer<G1 extends Enum<?>>
// State vars
protected ArrayList<QueryAttribute> itemList;
// protected Map<G1, QueryAttribute> itemMap;
public QueryComposer()
{
itemList = Lists.newArrayList();
itemList = new ArrayList<>();
// itemMap = Maps.newLinkedHashMap();
}
/**
* Return the QueryAttribute located at aIndex
*/
* Return the QueryAttribute located at aIndex
*/
public QueryAttribute get(int aIndex)
{
return itemList.get(aIndex);
}
/**
* Return the QueryAttribute associated with aRefKey
*/
* Return the QueryAttribute associated with aRefKey
*/
public QueryAttribute getItem(G1 aRefKey)
{
for (QueryAttribute aItem : itemList)
@@ -39,49 +41,35 @@ public class QueryComposer<G1 extends Enum<?>>
if (aItem.refKey == aRefKey)
return aItem;
}
return null;
}
/**
* Returns a listing of all the QueryAttributes that were composed
*/
* Returns a listing of all the QueryAttributes that were composed
*/
public Collection<QueryAttribute> getItems()
{
return Lists.newArrayList(itemList);
return new ArrayList<>(itemList);
}
/**
* Returns a listing of the items found in the keyArr
*/
public Collection<QueryAttribute> getItems(G1... keyArr)
* Returns a listing of the items found between sIndex, eIndex (inclusive)
*/
public Collection<QueryAttribute> getItemsFrom(int sIndex, int eIndex)
{
List<QueryAttribute> rList;
rList = Lists.newArrayListWithCapacity(keyArr.length);
for (G1 aEnum : keyArr)
rList.add(getItem(aEnum));
rList = new ArrayList<>((eIndex - sIndex) + 1);
for (int c1 = sIndex; c1 <= eIndex; c1++)
rList.add(itemList.get(c1));
return rList;
}
/**
* Returns a listing of the items found between sIndex, eIndex (inclusive)
*/
public Collection<QueryAttribute> getItemsFrom(int sIndex, int eIndex)
{
List<QueryAttribute> rList;
rList = Lists.newArrayListWithCapacity((eIndex - sIndex) + 1);
for (int c1 = sIndex; c1 <= eIndex; c1++)
rList.add(itemList.get(c1));
return rList;
}
/**
* Returns a listing of the items found between sKey, eKey (inclusive)
*/
* Returns a listing of the items found between sKey, eKey (inclusive)
*/
public Collection<QueryAttribute> getItemsFrom(G1 sKey, G1 eKey)
{
int sIndex, eIndex;
@@ -95,7 +83,7 @@ public class QueryComposer<G1 extends Enum<?>>
if (itemList.get(c1).refKey == eKey)
eIndex = c1;
}
// Insanity checks
if (sIndex == -1)
throw new RuntimeException("Failure. Key is not in composer: sKey: " + sKey);
@@ -103,21 +91,21 @@ public class QueryComposer<G1 extends Enum<?>>
throw new RuntimeException("Failure. Key is not in composer: eKey: " + eKey);
if (sIndex > eIndex)
throw new RuntimeException("Failure: eKey: (" + eKey + ") appears before for sKey: (" + sKey + ")");
return getItemsFrom(sIndex, eIndex);
}
/**
* Returns the num of items in the composition
*/
* Returns the num of items in the composition
*/
public int size()
{
return itemList.size();
}
/**
* Method to add a QueryAttribute to this container
*/
* Method to add a QueryAttribute to this container
*/
public QueryAttribute addAttribute(G1 aRefKey, UnitProvider aUnitProvider, String aName, String maxValue)
{
return addAttribute(aRefKey, aUnitProvider, aName, maxValue, true);
@@ -126,7 +114,7 @@ public class QueryComposer<G1 extends Enum<?>>
public QueryAttribute addAttribute(G1 aRefKey, UnitProvider aUnitProvider, String aName, String maxValue, boolean isVisible)
{
QueryAttribute aAttribute;
// Insanity check
Preconditions.checkNotNull(aUnitProvider);
@@ -143,12 +131,12 @@ public class QueryComposer<G1 extends Enum<?>>
public QueryAttribute addAttribute(G1 aRefKey, Class<?> aClass, String aName, String maxValue, boolean isVisible)
{
int maxSize;
// Compute the maxSize
maxSize = Integer.MAX_VALUE;
if (maxValue != null)
maxSize = computeStringWidth(maxValue) + 15;
return addAttribute(aRefKey, aClass, aName, maxSize, isVisible);
}
@@ -161,12 +149,12 @@ public class QueryComposer<G1 extends Enum<?>>
{
QueryAttribute aAttribute;
int defaultSize, minSize, maxSize;
// Get the defaultSize
defaultSize = 15;
if (aLabel != null)
defaultSize = computeStringWidth(aLabel);
minSize = 15;
maxSize = aMaxSize;
if (defaultSize < minSize)
@@ -177,7 +165,7 @@ public class QueryComposer<G1 extends Enum<?>>
// Set the defaultSize to be maxSize (unless it is ~infinite)
if (maxSize != Integer.MAX_VALUE)
defaultSize = maxSize;
// Form the attribute
aAttribute = new QueryAttribute(itemList.size());
aAttribute.refKey = aRefKey;
@@ -227,10 +215,10 @@ public class QueryComposer<G1 extends Enum<?>>
itemList.add(aAttribute);
return aAttribute;
}
/**
* Method to set in a custom Editor for the QueryAttribute associated with aRefKey
*/
* Method to set in a custom Editor for the QueryAttribute associated with aRefKey
*/
public void setEditor(G1 aRefKey, TableCellEditor aEditor)
{
for (QueryAttribute aItem : itemList)
@@ -241,13 +229,13 @@ public class QueryComposer<G1 extends Enum<?>>
return;
}
}
throw new RuntimeException("No item found with the key:" + aRefKey);
}
/**
* Method to set in a custom Renderer for the QueryAttribute associated with aRefKey
*/
* Method to set in a custom Renderer for the QueryAttribute associated with aRefKey
*/
public void setRenderer(G1 aRefKey, TableCellRenderer aRenderer)
{
for (QueryAttribute aItem : itemList)
@@ -258,20 +246,20 @@ public class QueryComposer<G1 extends Enum<?>>
return;
}
}
throw new RuntimeException("No item found with the key:" + aRefKey);
}
/**
* Utility method to compute the width of a string with the standard font
*/
* Utility method to compute the width of a string with the standard font
*/
protected int computeStringWidth(String aStr)
{
JLabel tmpL;
tmpL = new JLabel(aStr);
tmpL.setFont((new JTextField()).getFont());
return tmpL.getPreferredSize().width + 5;
}

View File

@@ -1,21 +1,17 @@
package glum.gui.panel.task;
import glum.gui.component.GLabel;
import glum.gui.panel.GlassPanel;
import glum.reflect.FunctionRunnable;
import glum.task.Task;
import glum.util.WallTimer;
import java.awt.Component;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.*;
import glum.gui.component.GLabel;
import glum.gui.panel.GlassPanel;
import glum.task.Task;
import glum.util.WallTimer;
/**
* Abstract TaskPanel that handles all of the state vars used to maintain
* the Task interface.
* Abstract TaskPanel that handles all of the state vars used to maintain the Task interface.
*/
public abstract class BaseTaskPanel extends GlassPanel implements Task
{
@@ -28,17 +24,17 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
protected long oldTimeMs;
protected long refreshRateMs;
protected int maxLC;
// Gui vars
protected JLabel titleL;
protected GLabel progressL, timerL;
protected GLabel progressL, timerL;
protected GLabel statusL;
protected JTextArea infoTA;
public BaseTaskPanel(Component aParent)
{
super(aParent);
isActive = true;
infoMsgFrag = null;
mProgress = 0;
@@ -48,7 +44,7 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
refreshRateMs = 47;
maxLC = -1;
}
/**
* Method to set the font of the infoTA
*/
@@ -65,15 +61,16 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
{
maxLC = aMaxLC;
}
@Override
public void abort()
{
mTimer.stop();
isActive = false;
SwingUtilities.invokeLater(new FunctionRunnable(this, "updateGui"));
Runnable tmpRunnable = () -> updateGui();
SwingUtilities.invokeLater(tmpRunnable);
}
@Override
public void infoAppend(String aMsg)
{
@@ -115,30 +112,32 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
mStatus = "";
mTimer.start();
oldTimeMs = Long.MIN_VALUE;
// Clear out all the text in the infoTA
if (infoTA != null)
infoTA.setText("");
SwingUtilities.invokeLater(new FunctionRunnable(this, "updateGui"));
Runnable tmpRunnable = () -> updateGui();
SwingUtilities.invokeLater(tmpRunnable);
}
@Override
public void setProgress(double aProgress)
{
mProgress = aProgress;
// Bail if it is not time to update our UI
if (isTimeForUpdate() == false && aProgress < 1.0)
return;
SwingUtilities.invokeLater(new FunctionRunnable(this, "updateGui"));
Runnable tmpRunnable = () -> updateGui();
SwingUtilities.invokeLater(tmpRunnable);
}
@Override
public void setProgress(int currVal, int maxVal)
{
setProgress((currVal + 0.0)/ maxVal);
setProgress((currVal + 0.0) / maxVal);
}
@Override
@@ -164,12 +163,13 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
public void setStatus(String aMsg)
{
mStatus = aMsg;
// Bail if it is not time to update our UI
if (isTimeForUpdate() == false)
return;
SwingUtilities.invokeLater(new FunctionRunnable(this, "updateGui"));
Runnable tmpRunnable = () -> updateGui();
SwingUtilities.invokeLater(tmpRunnable);
}
@Override
@@ -177,11 +177,10 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
{
return isActive;
}
/**
* Utility method that checks the update rate and returns true if the task
* UI can be updated. Note this method keeps track of the timer vars to
* honor refreshRateMs
* Utility method that checks the update rate and returns true if the task UI can be updated. Note this method keeps
* track of the timer vars to honor refreshRateMs
*/
protected boolean isTimeForUpdate()
{
@@ -194,11 +193,11 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
totalTimeMs = currTimeMs - oldTimeMs;
if (totalTimeMs < refreshRateMs && totalTimeMs > 0)
return false;
oldTimeMs = currTimeMs;
return true;
}
return true;
}
/**
* Utility method that does the actual updating of the previous info text with aMsg
*/
@@ -218,11 +217,11 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
start = end = 0;
try
{
end = infoTA.getLineEndOffset(infoTA.getLineCount()-1);
end = infoTA.getLineEndOffset(infoTA.getLineCount() - 1);
start = end - infoMsgFrag.length();
infoTA.replaceRange(aMsg, start, end);
}
catch (Exception aExp)
catch(Exception aExp)
{
System.out.println("infoMsgFrag:" + infoMsgFrag.length() + " start: " + start + " end:" + end);
throw new RuntimeException(aExp);
@@ -232,7 +231,7 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
else
{
infoTA.append(aMsg);
// Trim the buffer if we exceed our maxLC
if (maxLC > 0)
{
@@ -246,7 +245,7 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
end = infoTA.getLineEndOffset(currLC - maxLC);
infoTA.replaceRange("", start, end);
}
catch (Exception aExp)
catch(Exception aExp)
{
System.out.println("currLC:" + currLC + " maxLC:" + maxLC + " start: " + start + " end:" + end);
throw new RuntimeException(aExp);
@@ -257,14 +256,14 @@ public abstract class BaseTaskPanel extends GlassPanel implements Task
// Save off the new dynamic message fragment
infoMsgFrag = aMsg;
// timerL.setValue(mTimer.getTotal());
// SwingUtilities.invokeLater(new FunctionRunnable(timerL, "updateGui"));
// Update our internal time
oldTimeMs = System.nanoTime() / 1000000;
}
/**
* Utility method to update the GUI
*/

View File

@@ -15,7 +15,7 @@ public class TimeZoneCellRenderer extends DefaultListCellRenderer
}
@Override
public Component getListCellRendererComponent(JList list, Object aObj, int index, boolean isSelected, boolean hasFocus)
public Component getListCellRendererComponent(JList<?> list, Object aObj, int index, boolean isSelected, boolean hasFocus)
{
JLabel retL;
String aStr;

View File

@@ -1,27 +1,24 @@
package glum.gui.unit;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import net.miginfocom.swing.MigLayout;
import glum.gui.FocusUtil;
import glum.gui.GuiUtil;
import glum.gui.action.ClickAction;
import glum.gui.panel.CardPanel;
import glum.gui.panel.itemList.BasicItemHandler;
import glum.gui.panel.itemList.ItemHandler;
import glum.gui.panel.itemList.ItemListPanel;
import glum.gui.panel.itemList.StaticItemProcessor;
import glum.gui.panel.itemList.*;
import glum.gui.panel.itemList.query.QueryComposer;
import glum.reflect.FunctionRunnable;
import glum.unit.UnitListener;
import glum.unit.UnitProvider;
import net.miginfocom.swing.MigLayout;
public class UnitConfigurationDialog extends JDialog implements ActionListener, ListSelectionListener, UnitListener
{
@@ -34,16 +31,16 @@ public class UnitConfigurationDialog extends JDialog implements ActionListener,
// State vars
private StaticItemProcessor<UnitProvider> itemProcessor;
public UnitConfigurationDialog(JFrame parentFrame)
public UnitConfigurationDialog(JFrame aParentFrame)
{
// Make sure we call the parent
super(parentFrame);
super(aParentFrame);
// Set the characteristics for this dialog
setTitle("Edit Unit");
setDefaultCloseOperation(HIDE_ON_CLOSE);
setLocationRelativeTo(parentFrame);
setLocationRelativeTo(aParentFrame);
setModal(false);
// Build the actual GUI
@@ -109,11 +106,11 @@ public class UnitConfigurationDialog extends JDialog implements ActionListener,
}
@Override
public void actionPerformed(ActionEvent e)
public void actionPerformed(ActionEvent aEvent)
{
Object source;
source = e.getSource();
source = aEvent.getSource();
if (source == closeB)
{
setVisible(false);
@@ -210,10 +207,12 @@ public class UnitConfigurationDialog extends JDialog implements ActionListener,
editorPanel.setMaximumSize(new Dimension(5000, aDim.height));
// Hack to get the editorPanel resize properly. Not sure why invalidate(), validate() do not work
int aHeight = getHeight();
SwingUtilities.invokeLater(new FunctionRunnable(this, "setSize", getWidth(), aHeight - 1));
SwingUtilities.invokeLater(new FunctionRunnable(this, "setSize", getWidth(), aHeight));
// SwingUtilities.invokeLater(new FunctionRunnable(editorPanel, "invalidate"));
// SwingUtilities.invokeLater(new FunctionRunnable(editorPanel, "validate"));
Runnable tmpRunnable1 = () -> setSize(getWidth(), aHeight - 1);
Runnable tmpRunnable2 = () -> setSize(getWidth(), aHeight);
SwingUtilities.invokeLater(tmpRunnable1);
SwingUtilities.invokeLater(tmpRunnable2);
// Runnable tmpRunnable1 = () -> editorPanel.invalidate();
// Runnable tmpRunnable2 = () -> editorPanel.validate();
// invalidate();
// validate();
}
@@ -257,7 +256,8 @@ public class UnitConfigurationDialog extends JDialog implements ActionListener,
*/
enum Lookup
{
Key, Value,
Key,
Value,
};
public class UnitProviderHandler extends BasicItemHandler<UnitProvider>
@@ -268,25 +268,25 @@ public class UnitConfigurationDialog extends JDialog implements ActionListener,
}
@Override
public Object getColumnValue(UnitProvider aItem, int colNum)
public Object getColumnValue(UnitProvider aItem, int aColNum)
{
Enum<?> refKey;
// Insanity check
if (colNum < 0 && colNum >= fullAttributeList.size())
if (aColNum < 0 && aColNum >= fullAttributeList.size())
return null;
refKey = fullAttributeList.get(colNum).refKey;
refKey = fullAttributeList.get(aColNum).refKey;
switch ((Lookup)refKey)
{
case Key:
return aItem.getDisplayName();
return aItem.getDisplayName();
case Value:
return aItem.getConfigName();
return aItem.getConfigName();
default:
break;
break;
}
return null;

View File

@@ -13,7 +13,7 @@ public class UnitLabelRenderer extends DefaultListCellRenderer
}
@Override
public Component getListCellRendererComponent(JList list, Object aObj, int index, boolean isSelected, boolean hasFocus)
public Component getListCellRendererComponent(JList<?> list, Object aObj, int index, boolean isSelected, boolean hasFocus)
{
JLabel retL;
String aStr;

View File

@@ -7,10 +7,9 @@ import glum.zio.ZoutStream;
import java.io.*;
import java.net.*;
import java.nio.channels.Channel;
import java.util.Base64;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
import com.google.common.collect.Maps;
public class IoUtil
@@ -20,18 +19,18 @@ public class IoUtil
*/
public static URL createURL(String aUrlStr)
{
URL aURL;
URL retURL;
try
{
aURL = new URL(aUrlStr);
retURL = new URL(aUrlStr);
}
catch (MalformedURLException e)
catch(MalformedURLException e)
{
aURL = null;
retURL = null;
}
return aURL;
return retURL;
}
/**
@@ -55,7 +54,7 @@ public class IoUtil
{
aChannel.close();
}
catch (Exception aExp)
catch(Exception aExp)
{
aExp.printStackTrace();
}
@@ -73,7 +72,7 @@ public class IoUtil
{
aStream.close();
}
catch (Exception aExp)
catch(Exception aExp)
{
aExp.printStackTrace();
}
@@ -91,7 +90,7 @@ public class IoUtil
{
aStream.close();
}
catch (Exception aExp)
catch(Exception aExp)
{
aExp.printStackTrace();
}
@@ -109,7 +108,7 @@ public class IoUtil
{
aReader.close();
}
catch (Exception aExp)
catch(Exception aExp)
{
aExp.printStackTrace();
}
@@ -127,7 +126,7 @@ public class IoUtil
{
aWriter.close();
}
catch (Exception aExp)
catch(Exception aExp)
{
aExp.printStackTrace();
}
@@ -146,7 +145,7 @@ public class IoUtil
{
aStream.close();
}
catch (Exception aExp)
catch(Exception aExp)
{
aExp.printStackTrace();
}
@@ -164,7 +163,7 @@ public class IoUtil
{
aStream.close();
}
catch (Exception aExp)
catch(Exception aExp)
{
aExp.printStackTrace();
}
@@ -176,26 +175,20 @@ public class IoUtil
*/
public static boolean copyUrlToFile(Task aTask, URL aUrl, File aFile, Map<String, String> aPropertyMap)
{
URLConnection aConnection;
InputStream inStream;
OutputStream outStream;
byte[] byteArr;
int numBytes;
// Ensure we have a valid aTask
if (aTask == null)
aTask = new ConsoleTask();
// Allocate space for the byte buffer
byteArr = new byte[10000];
byte[] byteArr = new byte[10000];
// Perform the actual copying
inStream = null;
outStream = null;
InputStream inStream = null;
OutputStream outStream = null;
try
{
// Open the src stream (with a 30 sec connect timeout)
aConnection = aUrl.openConnection();
URLConnection aConnection = aUrl.openConnection();
aConnection.setConnectTimeout(30 * 1000);
aConnection.setReadTimeout(90 * 1000);
@@ -213,13 +206,13 @@ public class IoUtil
outStream = new FileOutputStream(aFile);
// Copy the bytes from the instream to the outstream
numBytes = 0;
int numBytes = 0;
while (numBytes != -1)
{
numBytes = inStream.read(byteArr);
if (numBytes > 0)
outStream.write(byteArr, 0, numBytes);
// Bail if aTask is aborted
if (aTask.isActive() == false)
{
@@ -228,7 +221,7 @@ public class IoUtil
}
}
}
catch (Exception aExp)
catch(Exception aExp)
{
aTask.infoAppendln("Exception:" + aExp);
aTask.infoAppendln(" URL:" + aUrl);
@@ -268,13 +261,10 @@ public class IoUtil
*/
public static boolean copyUrlToFile(Task aTask, URL aUrl, File aFile, String aUsername, String aPassword)
{
Map<String, String> plainMap;
String authStr;
String authStr = aUsername + ":" + aPassword;
authStr = Base64.getEncoder().encodeToString(authStr.getBytes());
authStr = aUsername + ":" + aPassword;
authStr = DatatypeConverter.printBase64Binary(authStr.getBytes());
plainMap = Maps.newHashMap();
Map<String, String> plainMap = Maps.newHashMap();
plainMap.put("Authorization", "Basic " + authStr);
return copyUrlToFile(aTask, aUrl, aFile, plainMap);
@@ -294,20 +284,19 @@ public class IoUtil
*/
public static boolean copyFileToFile(File aFile1, File aFile2)
{
URL aUrl;
URL tmpUrl;
try
{
aUrl = aFile1.toURI().toURL();
tmpUrl = aFile1.toURI().toURL();
}
catch (Exception aExp)
catch(Exception aExp)
{
System.out.println("Exception:" + aExp);
aExp.printStackTrace();
return false;
}
return copyUrlToFile(aUrl, aFile2);
return copyUrlToFile(tmpUrl, aFile2);
}
/**
@@ -344,16 +333,13 @@ public class IoUtil
*/
public static String readString(DataInputStream aStream) throws IOException
{
byte[] data;
int size;
size = aStream.readShort() & 0x00FFFF;
int size = aStream.readShort() & 0x00FFFF;
if (size == 0x00FFFF)
return null;
if (size == 0)
return "";
data = new byte[size];
byte[] data = new byte[size];
aStream.readFully(data);
return new String(data, "UTF-8");
}
@@ -363,9 +349,6 @@ public class IoUtil
*/
public static void writeString(DataOutputStream aStream, String aStr) throws IOException
{
byte[] data;
int size;
// Null strings are handled in special fashion
if (aStr == null)
{
@@ -380,8 +363,8 @@ public class IoUtil
return;
}
data = aStr.getBytes("UTF-8");
size = data.length;
byte[] data = aStr.getBytes("UTF-8");
int size = data.length;
// Ensure the string size is less than 0x00FFFF
if (size >= 0x00FFFF)
@@ -397,18 +380,17 @@ public class IoUtil
*/
public static short sizeOnDisk(String aStr)
{
byte[] data;
int size;
if (aStr == null || aStr.equals("") == true)
return 2;
byte[] data;
int size;
try
{
data = aStr.getBytes("UTF-8");
size = data.length;
}
catch (Exception aExp)
catch(Exception aExp)
{
throw new RuntimeException("UTF-8 Transform error.", aExp);
}

View File

@@ -21,7 +21,7 @@ public class LogicChunkEngine implements ActionListener
private JMenuBar menuBar;
private Map<Object, LogicChunk> menuMap;
private ShutdownHook shutdownHook;
public LogicChunkEngine(Registry aRegistry, URL aURL, String aAppName)
{
boolean isHeadless;
@@ -32,7 +32,7 @@ public class LogicChunkEngine implements ActionListener
// Are we headless
isHeadless = GraphicsEnvironment.isHeadless();
// Install our custom shutdown logic
shutdownHook = new ShutdownHook(this, aAppName);
Runtime.getRuntime().addShutdownHook(shutdownHook);
@@ -53,7 +53,7 @@ public class LogicChunkEngine implements ActionListener
if (aLogicChunk != null)
aLogicChunk.dispose();
}
catch (Exception aExp)
catch(Exception aExp)
{
System.out.println("Failed to dispose LogicChunk. Exception:");
aExp.printStackTrace();
@@ -79,7 +79,7 @@ public class LogicChunkEngine implements ActionListener
{
return menuMap.values();
}
/**
* Configures the shutdown hook to exit quickly by not waiting for daemon threads.
*/
@@ -98,7 +98,7 @@ public class LogicChunkEngine implements ActionListener
return;
// Find the associated LogicChunk
aLogicChunk = (LogicChunk)menuMap.get( aEvent.getSource() );
aLogicChunk = (LogicChunk)menuMap.get(aEvent.getSource());
// Activate the MenuItem
if (aLogicChunk != null)
@@ -144,7 +144,7 @@ public class LogicChunkEngine implements ActionListener
try
{
inStream = aURL.openStream();
br = new BufferedReader( new InputStreamReader(inStream) );
br = new BufferedReader(new InputStreamReader(inStream));
// Read the lines
while (true)
@@ -159,18 +159,16 @@ public class LogicChunkEngine implements ActionListener
// Get the tokens out of strLine
tokenList = aTokenizer.getTokens(strLine);
tokens = tokenList.toArray(new String[0]);
numTokens = tokens.length;
// Process the tokens
if (numTokens == 0)
{
; // Empty line
}
else if ( (isHeadless == true)
&& (tokens[0].equals("Menu") == true || tokens[0].equals("MenuItem") == true
|| tokens[0].equals("SubMenu") || tokens[0].equals("EndSubMenu")) )
else if ((isHeadless == true) && (tokens[0].equals("Menu") == true || tokens[0].equals("MenuItem") == true || tokens[0].equals("SubMenu") || tokens[0].equals("EndSubMenu")))
{
System.out.println("Ignoring:" + tokens[0] + " command. Running in headless environment.");
System.out.println("\tTokens: " + tokens);
@@ -256,7 +254,7 @@ public class LogicChunkEngine implements ActionListener
{
// Try to build the LogicChunk and load it into our MenuMap
logicChunk = loadLogicChunkInstance(refRegistry, tokens[2], tokens[1], aLoc);
// Form the MenuItem or Menu
if (logicChunk instanceof SubMenuChunk)
aMenuItem = new JMenu(tokens[1]);
@@ -264,7 +262,6 @@ public class LogicChunkEngine implements ActionListener
aMenuItem = new JMenuItem(tokens[1]);
aMenuItem.addActionListener(this);
// Associate the MenuItem with the LogicChunk
if (logicChunk != null)
menuMap.put(aMenuItem, logicChunk);
@@ -286,12 +283,12 @@ public class LogicChunkEngine implements ActionListener
}
}
catch (FileNotFoundException e)
catch(FileNotFoundException e)
{
System.out.println("File not found: " + aLoc);
return;
}
catch (IOException e)
catch(IOException e)
{
System.out.println("Ioexception occured in: LogicChunkEngine.loadLogicChunks()");
return;
@@ -301,8 +298,8 @@ public class LogicChunkEngine implements ActionListener
}
/**
* Attempts to load up the logicChunk with the specified aLabel. If that fails then will attempt to
* construct the LogicChunk using the default constructor.
* Attempts to load up the logicChunk with the specified aLabel. If that fails then will attempt to construct the
* LogicChunk using the default constructor.
*/
private static LogicChunk loadLogicChunkInstance(Registry aRegistry, String aFullClassPath, String aLabel, String aLoc)
{
@@ -326,7 +323,7 @@ public class LogicChunkEngine implements ActionListener
System.out.println("\tLocation: " + aLoc + "\n");
return null;
}
// Try the 1st preferred constructor
rawConstructor = ReflectUtil.getConstructorSafe(rawClass, parmTypes1);
if (rawConstructor != null)
@@ -334,32 +331,32 @@ public class LogicChunkEngine implements ActionListener
parmValues = new Object[2];
parmValues[0] = aRegistry;
parmValues[1] = aLabel;
return (LogicChunk)rawConstructor.newInstance(parmValues);
}
// Try the 2nd preferred constructor
rawConstructor = ReflectUtil.getConstructorSafe(rawClass, parmTypes2);
if (rawConstructor != null)
{
parmValues = new Object[1];
parmValues[0] = aLabel;
return (LogicChunk)rawConstructor.newInstance(parmValues);
}
// Just use the default constructor
else
{
return (LogicChunk)rawClass.newInstance();
return (LogicChunk)rawClass.getDeclaredConstructor().newInstance();
}
}
catch (ClassNotFoundException aExp)
catch(ClassNotFoundException aExp)
{
System.out.println("Failure: " + aFullClassPath + " not found.");
System.out.println("\tLocation: " + aLoc + "\n");
}
catch (Exception aExp)
catch(Exception aExp)
{
// Unknown Exception
aExp.printStackTrace();

View File

@@ -8,8 +8,7 @@ import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import javax.xml.bind.DatatypeConverter;
import java.util.Base64;
public class NetUtil
{
@@ -22,32 +21,31 @@ public class NetUtil
{
return aConnection.getResponseCode();
}
catch (IOException aExp)
catch(IOException aExp)
{
return -1;
}
}
/**
* Utility method to return the input stream associated with a URL
*/
public static InputStream getInputStream(URLConnection aConnection, Credential aCredential) throws IOException
{
InputStream inStream;
String authStr;
// Properly setup the credentials
if (aCredential != null)
{
authStr = aCredential.getUsername() + ":" + aCredential.getPasswordAsString();
authStr = DatatypeConverter.printBase64Binary(authStr.getBytes());
String username = aCredential.getUsername();
String password = aCredential.getPasswordAsString();
String authStr = username + ":" + password;
authStr = Base64.getEncoder().encodeToString(authStr.getBytes());
aConnection.setRequestProperty("Authorization", "Basic " + authStr);
}
// Retrieve the InputStream
aConnection.connect();
inStream = aConnection.getInputStream();
InputStream inStream = aConnection.getInputStream();
return inStream;
}
@@ -64,44 +62,40 @@ public class NetUtil
*/
public static Result getResult(Exception aExp, URLConnection aConnection)
{
Throwable aCause;
// See if there was a problem with the HTTP Connection
if (aConnection instanceof HttpURLConnection)
{
int responseCode;
responseCode = getResponseCode((HttpURLConnection)aConnection);
int responseCode = getResponseCode((HttpURLConnection)aConnection);
switch (responseCode)
{
case HttpURLConnection.HTTP_UNAUTHORIZED:
return Result.BadCredentials;
return Result.BadCredentials;
case HttpURLConnection.HTTP_UNSUPPORTED_TYPE:
return Result.UnsupportedConnection;
return Result.UnsupportedConnection;
case HttpURLConnection.HTTP_NOT_FOUND:
case HttpURLConnection.HTTP_NO_CONTENT:
return Result.InvalidResource;
return Result.InvalidResource;
// case HttpURLConnection.HTTP_UNAVAILABLE:
// return Result.UnreachableHost;
// return Result.UnreachableHost;
default:
break;
break;
}
}
// Evaluate the Exception
aCause = aExp;
while (aCause != null)
Throwable tmpCause = aExp;
while (tmpCause != null)
{
if (aCause instanceof UnknownHostException)
if (tmpCause instanceof UnknownHostException)
return Result.UnreachableHost;
else if (aCause instanceof ConnectException)
else if (tmpCause instanceof ConnectException)
return Result.ConnectFailure;
aCause = aCause.getCause();
tmpCause = tmpCause.getCause();
}
return Result.Undefined;
@@ -115,24 +109,16 @@ public class NetUtil
*/
public static Result checkCredentials(String uriRoot, Credential aCredential)
{
URLConnection aConnection;
InputStream inStream;
String username, password;
String authStr;
URL srcURL;
// int fullLen;
aConnection = null;
inStream = null;
URLConnection aConnection = null;
InputStream inStream = null;
try
{
srcURL = new URL(uriRoot);
URL srcURL = new URL(uriRoot);
username = aCredential.getUsername();
password = aCredential.getPasswordAsString();
authStr = username + ":" + password;
authStr = DatatypeConverter.printBase64Binary(authStr.getBytes());
// authStr = new sun.misc.BASE64Encoder().encode((username + ":" + password).getBytes());
String username = aCredential.getUsername();
String password = aCredential.getPasswordAsString();
String authStr = username + ":" + password;
authStr = Base64.getEncoder().encodeToString(authStr.getBytes());
aConnection = srcURL.openConnection();
aConnection.setRequestProperty("Authorization", "Basic " + authStr);
aConnection.connect();
@@ -143,7 +129,7 @@ public class NetUtil
inStream.close();
return Result.Success;
}
catch (Exception aExp)
catch(Exception aExp)
{
// aExp.printStackTrace();
return getResult(aExp, aConnection);

View File

@@ -1,67 +0,0 @@
package glum.reflect;
/**
* Class that wraps the provided function in a Runnable
*/
public class FunctionRunnable implements Runnable
{
protected Function refFunc;
protected Object[] argArr;
public FunctionRunnable(Object aObj, String methodName, Object... aArgArr)
{
Class<?>[] typeArr;
argArr = aArgArr;
typeArr = new Class[0];
if (argArr.length > 0)
{
// Determine the types of the specified arguments
typeArr = new Class[argArr.length];
for (int c1 = 0; c1 < typeArr.length; c1++)
{
typeArr[c1] = null;
if (argArr[c1] != null)
typeArr[c1] = argArr[c1].getClass();
}
}
try
{
if (aObj instanceof Class)
refFunc = new Function((Class<?>)aObj, methodName, typeArr);
else
refFunc = new Function(aObj, methodName, typeArr);
}
catch (Exception aExp)
{
String aMsg;
aMsg = "Failed to locate valid function. Method:" + methodName;
aMsg += "\n Class:" + aObj.getClass();
throw new RuntimeException(aMsg, aExp);
}
}
@Override
public void run()
{
try
{
refFunc.invoke(argArr);
}
catch (Exception aExp)
{
Throwable aCause;
// Retrieve the root cause
aCause = aExp;
while (aCause.getCause() != null)
aCause = aCause.getCause();
throw new RuntimeException("Failed to invoke method.", aCause);
}
}
}

View File

@@ -79,7 +79,7 @@ public class ReflectUtil
{
aConstructor = aClass.getConstructor(parmTypes);
}
catch (Exception aExp)
catch(Exception aExp)
{
return null;
}
@@ -129,14 +129,14 @@ public class ReflectUtil
if (retType.isAssignableFrom(aClass) == false)
return null;
aObject = aClass.newInstance();
aObject = aClass.getDeclaredConstructor().newInstance();
return retType.cast(aObject);
}
catch (ClassNotFoundException aExp)
catch(ClassNotFoundException aExp)
{
System.out.println("Failure: " + aFullClassPath + " not found.");
}
catch (Exception aExp)
catch(Exception aExp)
{
// Unknown Exception
aExp.printStackTrace();
@@ -175,11 +175,11 @@ public class ReflectUtil
aObject = aConstructor.newInstance(parmValues);
return retType.cast(aObject);
}
catch (ClassNotFoundException aExp)
catch(ClassNotFoundException aExp)
{
System.out.println("Failure: " + aFullClassPath + " not found.");
}
catch (Exception aExp)
catch(Exception aExp)
{
// Unknown Exception
aExp.printStackTrace();
@@ -206,14 +206,14 @@ public class ReflectUtil
dataPath = aUrl.toURI().toString();
dataPath = URLDecoder.decode(dataPath, "UTF-8");
}
catch (Exception aExp)
catch(Exception aExp)
{
dataPath = aUrl.getPath();
try
{
dataPath = URLDecoder.decode(dataPath, "UTF-8");
}
catch (Exception aExp2)
catch(Exception aExp2)
{
;
}

View File

@@ -1,18 +1,10 @@
package glum.registry;
import glum.reflect.FunctionRunnable;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
import javax.swing.SwingUtilities;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.collect.*;
/**
* Class that support arbitrary item selection. All valid types of selected items must be registered in the Constructor.
@@ -60,7 +52,7 @@ public class SelectionManager
/**
* Adds to the list of selected items and notifies all listeners but the specified skipListener
*/
public <G1 extends Object> void addItem(Class<G1> aClass, G1 aItem, SelectionListener skipListener)
public <G1 extends Object> void addItem(Class<G1> aClass, G1 aItem, SelectionListener aSkipListener)
{
if (registerSet.contains(aClass) == false)
throw new RuntimeException("Unregistered selection class: " + aClass);
@@ -71,21 +63,21 @@ public class SelectionManager
selectionMap.put(aClass, aItem);
}
notifyListeners(aClass, skipListener);
notifyListeners(aClass, aSkipListener);
}
/**
* Add to the list of selected items associated with aClass
*/
public <G1 extends Object> void addItems(Class<G1> aClass, List<G1> itemList)
public <G1 extends Object> void addItems(Class<G1> aClass, List<G1> aItemList)
{
addItems(aClass, itemList, null);
addItems(aClass, aItemList, null);
}
/**
* Adds to the list of selected items and notifies all listeners but the specified skipListener
*/
public <G1 extends Object> void addItems(Class<G1> aClass, List<G1> itemList, SelectionListener skipListener)
public <G1 extends Object> void addItems(Class<G1> aClass, List<G1> aItemList, SelectionListener aSkipListener)
{
if (registerSet.contains(aClass) == false)
throw new RuntimeException("Unregistered selection class: " + aClass);
@@ -93,10 +85,10 @@ public class SelectionManager
// Replace the old selections with the new item list
synchronized(this)
{
selectionMap.putAll(aClass, itemList);
selectionMap.putAll(aClass, aItemList);
}
notifyListeners(aClass, skipListener);
notifyListeners(aClass, aSkipListener);
}
/**
@@ -114,15 +106,15 @@ public class SelectionManager
/**
* Removes from the list of selected items associated with aClass
*/
public <G1 extends Object> void removeItems(Class<G1> aClass, List<G1> itemList)
public <G1 extends Object> void removeItems(Class<G1> aClass, List<G1> aItemList)
{
removeItems(aClass, itemList, null);
removeItems(aClass, aItemList, null);
}
/**
* Removes from the list of selected items and notifies all listeners but the specified skipListener
*/
public <G1 extends Object> void removeItems(Class<G1> aClass, List<G1> itemList, SelectionListener skipListener)
public <G1 extends Object> void removeItems(Class<G1> aClass, List<G1> aItemList, SelectionListener skipListener)
{
if (registerSet.contains(aClass) == false)
throw new RuntimeException("Unregistered selection class: " + aClass);
@@ -133,7 +125,7 @@ public class SelectionManager
Set<G1> replaceSet;
replaceSet = new LinkedHashSet<G1>(getSelectedItems(aClass));
replaceSet.removeAll(itemList);
replaceSet.removeAll(aItemList);
selectionMap.replaceValues(aClass, replaceSet);
}
@@ -143,15 +135,15 @@ public class SelectionManager
/**
* Sets in the selected items and notifies all listeners
*/
public <G1 extends Object> void setItems(Class<G1> aClass, List<G1> itemList)
public <G1 extends Object> void setItems(Class<G1> aClass, List<G1> aItemList)
{
setItems(aClass, itemList, null);
setItems(aClass, aItemList, null);
}
/**
* Sets in the selected items and notifies all listeners but the specified skipListener
*/
public <G1 extends Object> void setItems(Class<G1> aClass, List<G1> itemList, SelectionListener skipListener)
public <G1 extends Object> void setItems(Class<G1> aClass, List<G1> aItemList, SelectionListener aSkipListener)
{
if (registerSet.contains(aClass) == false)
throw new RuntimeException("Unregistered selection class: " + aClass);
@@ -159,10 +151,10 @@ public class SelectionManager
// Replace the old selections with the new item list
synchronized(this)
{
selectionMap.replaceValues(aClass, itemList);
selectionMap.replaceValues(aClass, aItemList);
}
notifyListeners(aClass, skipListener);
notifyListeners(aClass, aSkipListener);
}
/**
@@ -177,21 +169,21 @@ public class SelectionManager
/**
* Helper method to notify the listeners associated with the specified class.
*/
private void notifyListeners(Class<?> aClass, SelectionListener skipListener)
private void notifyListeners(Class<?> aClass, SelectionListener aSkipListener)
{
List<SelectionListener> listenerList;
// Ensure this logic is always executed on the AWT thread (if notifyViaAwtThread == true)
if (notifyViaAwtThread == true && SwingUtilities.isEventDispatchThread() == false)
{
SwingUtilities.invokeLater(new FunctionRunnable(this, "notifyListeners", aClass, skipListener));
Runnable tmpRunnable = () -> notifyListeners(aClass, aSkipListener);
SwingUtilities.invokeLater(tmpRunnable);
return;
}
List<SelectionListener> listenerList;
synchronized(this)
{
listenerList = Lists.newArrayList(listenerMap.get(aClass));
listenerList.remove(skipListener);
listenerList = new ArrayList<>(listenerMap.get(aClass));
listenerList.remove(aSkipListener);
}
for (SelectionListener aListener : listenerList)

View File

@@ -25,7 +25,7 @@ public class ZioObjUtil
// Serialize the class
try
{
G1 aItem = aClass.newInstance();
G1 aItem = aClass.getDeclaredConstructor().newInstance();
aItem.zioRead(aStream);
itemList.add(aItem);
}
@@ -39,8 +39,8 @@ public class ZioObjUtil
}
/**
* Utility method to read a preloaded list of ZioObj items. The passed in list must contain the exact number of items as that stored on disk and in the
* correct order.
* Utility method to read a preloaded list of ZioObj items. The passed in list must contain the exact number of items
* as that stored on disk and in the correct order.
* <P>
* Format: <numItems> (<ZioObj>)*
*/
@@ -97,8 +97,9 @@ public class ZioObjUtil
}
/**
* Utility method to read a map of ZioObj items. The items are assumed to be preloaded. Thus the passed in map must contain as many items (and in the order)
* as that which will be read in from the disk. It is therefore advisable that only LinkedHashMaps be used with this method.
* Utility method to read a map of ZioObj items. The items are assumed to be preloaded. Thus the passed in map must
* contain as many items (and in the order) as that which will be read in from the disk. It is therefore advisable
* that only LinkedHashMaps be used with this method.
*/
public static void readMap(ZinStream aStream, Map<String, ? extends ZioObj> aItemMap) throws IOException
{
@@ -146,12 +147,11 @@ public class ZioObjUtil
public static <G1 extends ZioObj> G1 read(ZinStream aStream, Class<G1> aClass) throws IOException
{
G1 aItem;
// Serialize the class
G1 aItem;
try
{
aItem = aClass.newInstance();
aItem = aClass.getDeclaredConstructor().newInstance();
aItem.zioRead(aStream);
}
catch(Exception aException)
@@ -172,7 +172,7 @@ public class ZioObjUtil
G1 aItem;
try
{
aItem = aClass.newInstance();
aItem = aClass.getDeclaredConstructor().newInstance();
aItem.zioRead(aStream);
}
catch(Exception aException)

View File

@@ -1,9 +1,5 @@
package glum.zio.stream;
import glum.util.WallTimer;
import glum.zio.ZinStream;
import glum.zio.util.ZioUtil;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
@@ -14,6 +10,10 @@ import java.util.Arrays;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import glum.util.WallTimer;
import glum.zio.ZinStream;
import glum.zio.util.ZioUtil;
public abstract class BaseZinStream implements ZinStream
{
// Work vars
@@ -27,10 +27,11 @@ public abstract class BaseZinStream implements ZinStream
/**
* @param computeCheckSum
* True if a checksum (md5sum) is desired to be computed as the stream is written
* True if a checksum (md5sum) is desired to be computed as the stream is written
* @param streamSizeHint
* A hint which indicates the final size of the source stream. This hint will be used to determine if a direct buffer should be allocated. If the
* hint size is greater than 25 MB then a direct buffer will be allocated. A value of 0 implies that a direct buffer should not be allocated.
* A hint which indicates the final size of the source stream. This hint will be used to determine if a direct
* buffer should be allocated. If the hint size is greater than 25 MB then a direct buffer will be allocated.
* A value of 0 implies that a direct buffer should not be allocated.
*/
public BaseZinStream(boolean computeCheckSum, long streamSizeHint) throws IOException
{
@@ -58,9 +59,9 @@ public abstract class BaseZinStream implements ZinStream
/**
* @param aWorkBuffer
* This ByteBuffer will be used as the workBuffer. No workBuffer will be allocated for this BaseZinStream.
* This ByteBuffer will be used as the workBuffer. No workBuffer will be allocated for this BaseZinStream.
* @param computeCheckSum
* True if a checksum (md5sum) is desired to be computed as the stream is written
* True if a checksum (md5sum) is desired to be computed as the stream is written
*/
public BaseZinStream(ByteBuffer aWorkBuffer, boolean computeCheckSum) throws IOException
{
@@ -348,21 +349,23 @@ public abstract class BaseZinStream implements ZinStream
}
/**
* Helper method to refresh the workBuffer with new data from the stream. This method ensures that workBuffer will always have enough data to support
* reading.
* Helper method to refresh the workBuffer with new data from the stream. This method ensures that workBuffer will
* always have enough data to support reading.
* <P>
* If there is no more data on the stream then this method should throw an IOException
*/
protected abstract void refreshWorkBuffer() throws IOException;
/**
* Helper method to release any stream related vars. This method will only be called once, the very first time the method {@link #close()} is called.
* Helper method to release any stream related vars. This method will only be called once, the very first time the
* method {@link #close()} is called.
*/
protected abstract void releaseStreamVars() throws IOException;
/**
* Helper method that ensures the digest has been updated with any data that has been "read" thus far. The definition of "read" is any data returned from the
* stream via one of the read methods. The digest shall not be updated with any buffered data - only data that has been read from the stream.
* Helper method that ensures the digest has been updated with any data that has been "read" thus far. The definition
* of "read" is any data returned from the stream via one of the read methods. The digest shall not be updated with
* any buffered data - only data that has been read from the stream.
*/
protected void updateDigest() throws IOException
{

View File

@@ -11,16 +11,16 @@ public class FileZinStream extends BaseZinStream
// Stream vars
private FileChannel fileCh;
private byte[] staleArr;
public FileZinStream(File aFile, boolean computeCheckSum) throws IOException
{
super(computeCheckSum, aFile.length());
// Set up the stream vars
fileCh = new FileInputStream(aFile).getChannel();
staleArr = new byte[256];
}
public FileZinStream(File aFile) throws IOException
{
this(aFile, false);
@@ -31,48 +31,48 @@ public class FileZinStream extends BaseZinStream
{
if (workBuffer == null)
return 0;
return fileCh.size() - (fileCh.position() - workBuffer.remaining());
}
@Override
public long getPosition() throws IOException
{
// There is no virtual position if the stream has been closed
if (workBuffer == null)
throw new IOException("Stream has been closed.");
return fileCh.position() - workBuffer.remaining();
}
@Override
protected void refreshWorkBuffer() throws IOException
{
int numReadBytes, numStaleBytes;
// Ensure the digest has been updated before refreshing the buffer
updateDigest();
// Copies the remaining data from workBuffer to a byte (stale) array
// Copies the remaining data from workBuffer to a byte (stale) array
numStaleBytes = workBuffer.remaining();
if (numStaleBytes > 0)
workBuffer.get(staleArr, 0, numStaleBytes);
// Clear the buffer and copy the (stale) bytes from the byte array to the start of workBuffer
workBuffer.clear();
if (numStaleBytes > 0)
workBuffer.put(staleArr, 0, numStaleBytes);
// Fill the remaining workBuffer with data from the "stream"
numReadBytes = fileCh.read(workBuffer);
if (numReadBytes == 0)
System.out.println("Failed to read any buffer bytes!!! Bytes formerly read: " + numReadBytes);
if (numReadBytes == -1)
throw new EOFException("EOF reached on stream.");
// Mark the buffer as fully prepared and ready for processing
workBuffer.flip();
// Mark the current digestPos to the start of the workBuffer
digestPos = 0;
}
@@ -81,9 +81,9 @@ public class FileZinStream extends BaseZinStream
protected void releaseStreamVars() throws IOException
{
fileCh.close();
fileCh = null;
staleArr = null;
}
}
}