Compare commits

...

1 Commits

  1. 4
      src/de/memtext/baseobjects/ActivatableItem.java
  2. 1
      src/de/memtext/baseobjects/ActivatableItemI.java
  3. 13
      src/de/memtext/baseobjects/ComparableObject.java
  4. 2
      src/de/memtext/baseobjects/DataList.java
  5. 3
      src/de/memtext/baseobjects/DoubleClickMouseListener.java
  6. 11
      src/de/memtext/baseobjects/IdObject.java
  7. 2
      src/de/memtext/baseobjects/IdObjectI.java
  8. 9
      src/de/memtext/baseobjects/NameDecorator.java
  9. 27
      src/de/memtext/baseobjects/NamedIdObject.java
  10. 37
      src/de/memtext/baseobjects/NamedIdObjectWithParent.java
  11. 1
      src/de/memtext/baseobjects/NamedIdObjectWithParentI.java
  12. 8
      src/de/memtext/baseobjects/NamedObject.java
  13. 2
      src/de/memtext/baseobjects/NamedObjectI.java
  14. 2
      src/de/memtext/baseobjects/SearchReplaceTextHolder.java
  15. 20
      src/de/memtext/baseobjects/User.java
  16. 66
      src/de/memtext/baseobjects/coll/ActivatableItemList.java
  17. 16
      src/de/memtext/baseobjects/coll/BaseObjectCollection.java
  18. 27
      src/de/memtext/baseobjects/coll/IdObjectCollection.java
  19. 21
      src/de/memtext/baseobjects/coll/IdObjectList.java
  20. 2
      src/de/memtext/baseobjects/coll/IdObjectSet.java
  21. 25
      src/de/memtext/baseobjects/coll/NamedIdObjectCollection.java
  22. 15
      src/de/memtext/baseobjects/coll/NamedIdObjectList.java
  23. 3
      src/de/memtext/baseobjects/coll/NamedIdObjectSet.java
  24. 33
      src/de/memtext/baseobjects/coll/NamedIdObjectWithParentCollection.java
  25. 19
      src/de/memtext/baseobjects/coll/NamedIdObjectWithParentList.java
  26. 2
      src/de/memtext/baseobjects/coll/NamedIdObjectWithParentSet.java
  27. 31
      src/de/memtext/baseobjects/coll/NamedObjectCollection.java
  28. 17
      src/de/memtext/baseobjects/coll/NamedObjectList.java
  29. 2
      src/de/memtext/baseobjects/coll/NamedObjectSet.java
  30. 25
      src/de/memtext/buttons/ButtonGroupPanel.java
  31. 7
      src/de/memtext/buttons/Standard.java
  32. 1
      src/de/memtext/db/AbstractHsqlStandaloneMgrResources.java
  33. 52
      src/de/memtext/db/AddProc.java
  34. 14
      src/de/memtext/db/Comparison.java
  35. 5
      src/de/memtext/db/ComparisonUnit.java
  36. 59
      src/de/memtext/db/ConnectionCreator.java
  37. 10
      src/de/memtext/db/DB.java
  38. 913
      src/de/memtext/db/DBAccess.java
  39. 50
      src/de/memtext/db/DBComparison.java
  40. 11
      src/de/memtext/db/DBServletException.java
  41. 69
      src/de/memtext/db/DBTimer.java
  42. 13
      src/de/memtext/db/DataSource.java
  43. 35
      src/de/memtext/db/DataSourceEditPanel.java
  44. 34
      src/de/memtext/db/DbRequest.java
  45. 10
      src/de/memtext/db/DbRequestType.java
  46. 11
      src/de/memtext/db/DbResponse.java
  47. 31
      src/de/memtext/db/DbRmiClient.java
  48. 3
      src/de/memtext/db/DbServerI.java
  49. 23
      src/de/memtext/db/DbServerImpl.java
  50. 122
      src/de/memtext/db/DbUtils.java
  51. 88
      src/de/memtext/db/HsqlProcedures.java
  52. 107
      src/de/memtext/db/HsqlStandaloneMgr.java
  53. 24
      src/de/memtext/db/HsqlStandaloneMgrResources.java
  54. 27
      src/de/memtext/db/HsqlStandaloneMgrResources_de.java
  55. 22
      src/de/memtext/db/Library2.java
  56. 262
      src/de/memtext/db/MemtextPool.java
  57. 197
      src/de/memtext/db/MemtextPools.java
  58. 1
      src/de/memtext/db/NichtAngemeldetException.java
  59. 33
      src/de/memtext/db/ProcedureSql.java
  60. 10
      src/de/memtext/db/PropDescriptor.java
  61. 46
      src/de/memtext/db/PropsReader.java
  62. 35
      src/de/memtext/db/RestrictionCollector.java
  63. 21
      src/de/memtext/db/SampleApp.java
  64. 7
      src/de/memtext/db/SchemaReader.java
  65. 133
      src/de/memtext/db/ValueRandomizer.java
  66. 38
      src/de/memtext/db/dataexchange/MyRequest.java
  67. 12
      src/de/memtext/db/dataexchange/MyServletResponse.java
  68. 11
      src/de/memtext/dlg/AboutDialog.java
  69. 23
      src/de/memtext/dlg/DialogWithExit.java
  70. 12
      src/de/memtext/dlg/EnterDateDlg.java
  71. 13
      src/de/memtext/dlg/ImportDlg.java
  72. 10
      src/de/memtext/dlg/InputDialog.java
  73. 19
      src/de/memtext/dlg/LoginDlg.java
  74. 35
      src/de/memtext/dlg/NodeSelectionDlg.java
  75. 12
      src/de/memtext/dlg/ObjectCheckBoxDlg.java
  76. 18
      src/de/memtext/dlg/OkCancelClearDlg.java
  77. 39
      src/de/memtext/dlg/OkCancelDlg.java
  78. 5
      src/de/memtext/dlg/OkCancelPanel.java
  79. 23
      src/de/memtext/dlg/OkDlg.java
  80. 28
      src/de/memtext/dlg/OkDoneDlg.java
  81. 8
      src/de/memtext/dlg/OkDonePanel.java
  82. 58
      src/de/memtext/dlg/PasswdChangeDlg.java
  83. 122
      src/de/memtext/hbt/AbstractAriel.java
  84. 96
      src/de/memtext/hbt/Checker.java
  85. 293
      src/de/memtext/hbt/NewHeartBeatAriel.java
  86. 1
      src/de/memtext/icons/ArrowDownIcon.java
  87. 1
      src/de/memtext/icons/ArrowRight.java
  88. 1
      src/de/memtext/icons/ArrowUpIcon.java
  89. 14
      src/de/memtext/icons/BasicIcon.java
  90. 4
      src/de/memtext/icons/DoubleArrowDownIcon.java
  91. 4
      src/de/memtext/icons/DoubleArrowDownLineIcon.java
  92. 4
      src/de/memtext/icons/DoubleArrowUpIcon.java
  93. 4
      src/de/memtext/icons/DoubleArrowUpLineIcon.java
  94. 38
      src/de/memtext/icons/MBStandardIcons.java
  95. 28
      src/de/memtext/lang/SingOrPluralWord.java
  96. 5
      src/de/memtext/observ/DocumentListenerObserver.java
  97. 39
      src/de/memtext/rights/AllowableHierarchyUtil.java
  98. 30
      src/de/memtext/rights/NewPasswordChecker.java
  99. 116
      src/de/memtext/rights/Rights.java
  100. 23
      src/de/memtext/rights/RightsKeyEntry.java
  101. Some files were not shown because too many files have changed in this diff Show More

4
src/de/memtext/baseobjects/ActivatableItem.java

@ -6,7 +6,9 @@ package de.memtext.baseobjects; @@ -6,7 +6,9 @@ package de.memtext.baseobjects;
* */
public class ActivatableItem implements ActivatableItemI {
private static final long serialVersionUID = 1;
private boolean isActive;
/**
*
*/
@ -17,6 +19,7 @@ private boolean isActive; @@ -17,6 +19,7 @@ private boolean isActive;
/* (non-Javadoc)
* @see de.memtext.baseobjects.ActivatableItemI#isActive()
*/
@Override
public boolean isActive() {
return isActive;
}
@ -24,6 +27,7 @@ private boolean isActive; @@ -24,6 +27,7 @@ private boolean isActive;
/* (non-Javadoc)
* @see de.memtext.baseobjects.ActivatableItemI#setActive(boolean)
*/
@Override
public void setActive(boolean isActive) {
this.isActive = isActive;
}

1
src/de/memtext/baseobjects/ActivatableItemI.java

@ -6,5 +6,6 @@ package de.memtext.baseobjects; @@ -6,5 +6,6 @@ package de.memtext.baseobjects;
* */
public interface ActivatableItemI {
boolean isActive();
void setActive(boolean isActive);
}

13
src/de/memtext/baseobjects/ComparableObject.java

@ -2,6 +2,7 @@ package de.memtext.baseobjects; @@ -2,6 +2,7 @@ package de.memtext.baseobjects;
public class ComparableObject extends NamedObject implements Comparable {
private int sortNr;
private static final long serialVersionUID = 1;
public ComparableObject(String name, int sortNr) {
@ -9,12 +10,11 @@ public class ComparableObject extends NamedObject implements Comparable { @@ -9,12 +10,11 @@ public class ComparableObject extends NamedObject implements Comparable {
this.sortNr = sortNr;
}
@Override
public int compareTo(Object o) {
int result = 0;
if (getSortNr() < ((ComparableObject) o).getSortNr())
result = -1;
if (getSortNr() > ((ComparableObject) o).getSortNr())
result = 1;
if (getSortNr() < ((ComparableObject) o).getSortNr()) result = -1;
if (getSortNr() > ((ComparableObject) o).getSortNr()) result = 1;
return result;
}
@ -22,12 +22,11 @@ public class ComparableObject extends NamedObject implements Comparable { @@ -22,12 +22,11 @@ public class ComparableObject extends NamedObject implements Comparable {
return sortNr;
}
@Override
public boolean equals(Object o) {
boolean result = false;
ComparableObject comp = (ComparableObject) o;
if (this.getName().equals(comp.getName())
&& this.getSortNr() == comp.getSortNr())
result = true;
if (this.getName().equals(comp.getName()) && this.getSortNr() == comp.getSortNr()) result = true;
return result;
}

2
src/de/memtext/baseobjects/DataList.java

@ -33,11 +33,13 @@ public class DataList extends LinkedList { @@ -33,11 +33,13 @@ public class DataList extends LinkedList {
super(c);
}
/**
* If for example a value for column 5 is to be stored, but the data List only
* contains values for column 1 and 2, for column 3 and 4 null values are stored.
*/
@Override
public Object set(int index, Object o) {
while (index > this.size() - 1) {
this.add(null);

3
src/de/memtext/baseobjects/DoubleClickMouseListener.java

@ -8,9 +8,12 @@ public abstract class DoubleClickMouseListener extends MouseAdapter { @@ -8,9 +8,12 @@ public abstract class DoubleClickMouseListener extends MouseAdapter {
public DoubleClickMouseListener() {
super();
}
@Override
public final void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) doubleClickOccured();
}
protected abstract void doubleClickOccured();

11
src/de/memtext/baseobjects/IdObject.java

@ -8,10 +8,13 @@ import java.io.Serializable; @@ -8,10 +8,13 @@ import java.io.Serializable;
* */
public class IdObject implements IdObjectI, Serializable {
private Object id;
private static final long serialVersionUID = 1;
public IdObject() {
}
public IdObject(Object id) {
setId(id);
@ -20,6 +23,7 @@ public class IdObject implements IdObjectI,Serializable { @@ -20,6 +23,7 @@ public class IdObject implements IdObjectI,Serializable {
/**
* @return
*/
@Override
public Object getId() {
return id;
}
@ -29,17 +33,20 @@ public class IdObject implements IdObjectI,Serializable { @@ -29,17 +33,20 @@ public class IdObject implements IdObjectI,Serializable {
/**
* @param object
*/
@Override
public void setId(Object object) {
id = object;
}
public String toString()
{
@Override
public String toString() {
return "id:" + getId();
}
/**
* Provides a deep copy
*/
@Override
public Object clone() throws CloneNotSupportedException {
if (id != null && !(id instanceof String) && !(id instanceof Integer))
throw new CloneNotSupportedException(" You have to check in IdObject.clone if deep copying is necessary for class " + id.getClass());

2
src/de/memtext/baseobjects/IdObjectI.java

@ -1,9 +1,11 @@ @@ -1,9 +1,11 @@
package de.memtext.baseobjects;
/**
* @see de.memtext.util.TreeUtils for a method creating key list (1,2,4) from nodes
*/
public interface IdObjectI {
public Object getId();
public void setId(Object id);
}

9
src/de/memtext/baseobjects/NameDecorator.java

@ -7,20 +7,25 @@ package de.memtext.baseobjects; @@ -7,20 +7,25 @@ package de.memtext.baseobjects;
*/
public final class NameDecorator implements NamedObjectI {
private Object object;
private String name;
public NameDecorator(String name, Object object) {
this.name = name;
this.object = object;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
public Object getObject()
{
public Object getObject() {
return object;
}
}

27
src/de/memtext/baseobjects/NamedIdObject.java

@ -9,10 +9,11 @@ import de.memtext.util.HashCodeUtil; @@ -9,10 +9,11 @@ import de.memtext.util.HashCodeUtil;
*
* @author MB
*/
public class NamedIdObject extends NamedObject implements NamedIdObjectI,
Serializable {
public class NamedIdObject extends NamedObject implements NamedIdObjectI, Serializable {
private Object id;
private static final long serialVersionUID = 1;
public NamedIdObject() {
}
@ -28,6 +29,7 @@ public class NamedIdObject extends NamedObject implements NamedIdObjectI, @@ -28,6 +29,7 @@ public class NamedIdObject extends NamedObject implements NamedIdObjectI,
/**
* @return
*/
@Override
public Object getId() {
return id;
}
@ -35,18 +37,20 @@ public class NamedIdObject extends NamedObject implements NamedIdObjectI, @@ -35,18 +37,20 @@ public class NamedIdObject extends NamedObject implements NamedIdObjectI,
/**
* @param object
*/
@Override
public void setId(Object id) {
this.id = id;
}
@Override
public String toString() {
return getId() + " - " + getName();
}
public boolean equals(Object o)
{
@Override
public boolean equals(Object o) {
boolean result = false;
if (o instanceof NamedIdObject)
{
if (o instanceof NamedIdObject) {
NamedIdObject o2 = (NamedIdObject) o;
result = EqualsUtil.areEqual(this.getId(), o2.getId()) && EqualsUtil.areEqual(this.getName(), o2.getName());
@ -54,6 +58,8 @@ public boolean equals(Object o) @@ -54,6 +58,8 @@ public boolean equals(Object o)
}
return result;
}
@Override
public int hashCode() {
int result = HashCodeUtil.SEED;
//collect the contributions of various fields
@ -62,20 +68,19 @@ public int hashCode(){ @@ -62,20 +68,19 @@ public int hashCode(){
return result;
}
/**
* Provides a deep copy
*/
@Override
public Object clone() throws CloneNotSupportedException {
NamedIdObject cl = new NamedIdObject((NamedObject) super.clone());
if (id != null && !(id instanceof String) && !(id instanceof Integer))
throw new CloneNotSupportedException(
" You have to check in NamedIdObject.clone if deep copying is necessary for class "
+ id.getClass());
throw new CloneNotSupportedException(" You have to check in NamedIdObject.clone if deep copying is necessary for class " + id.getClass());
if (this.id != null)
cl.setId(id);
if (this.id != null) cl.setId(id);
return cl;
}

37
src/de/memtext/baseobjects/NamedIdObjectWithParent.java

@ -6,10 +6,11 @@ import de.memtext.tree.KeyParentEqualException; @@ -6,10 +6,11 @@ import de.memtext.tree.KeyParentEqualException;
import de.memtext.util.EqualsUtil;
import de.memtext.util.HashCodeUtil;
public class NamedIdObjectWithParent extends NamedIdObject implements
NamedIdObjectWithParentI, Serializable {
public class NamedIdObjectWithParent extends NamedIdObject implements NamedIdObjectWithParentI, Serializable {
private Object parentKey;
private static final long serialVersionUID = 1;
public NamedIdObjectWithParent() {
super();
}
@ -23,33 +24,31 @@ public class NamedIdObjectWithParent extends NamedIdObject implements @@ -23,33 +24,31 @@ public class NamedIdObjectWithParent extends NamedIdObject implements
super(id, name);
}
public NamedIdObjectWithParent(Object id, String name, Object parentKey)
throws KeyParentEqualException {
public NamedIdObjectWithParent(Object id, String name, Object parentKey) throws KeyParentEqualException {
super(id, name);
setParentKey(parentKey);
}
@Override
public Object getParentKey() {
return parentKey;
}
@Override
public void setParentKey(Object parentKey) throws KeyParentEqualException {
this.parentKey = parentKey;
if ((getId() == null && getParentKey() == null)
|| (getId() != null && getId().equals(getParentKey())))
throw new KeyParentEqualException((NamedIdObjectWithParentI) this);
if ((getId() == null && getParentKey() == null) || (getId() != null && getId().equals(getParentKey()))) throw new KeyParentEqualException((NamedIdObjectWithParentI) this);
}
//TODO aufteilen auf übergeordnete Objekte
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
NamedIdObjectWithParent i2 = (NamedIdObjectWithParent) obj;
return
EqualsUtil.areEqual(this.getId(), i2.getId()) &&
EqualsUtil.areEqual(this.getName(), i2.getName()) &&
EqualsUtil.areEqual(this.getParentKey(), i2.getParentKey());
return EqualsUtil.areEqual(this.getId(), i2.getId()) && EqualsUtil.areEqual(this.getName(), i2.getName()) && EqualsUtil.areEqual(this.getParentKey(), i2.getParentKey());
}
@ -57,6 +56,7 @@ public class NamedIdObjectWithParent extends NamedIdObject implements @@ -57,6 +56,7 @@ public class NamedIdObjectWithParent extends NamedIdObject implements
/*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int result = HashCodeUtil.SEED;
result = HashCodeUtil.hash(result, getId());
@ -64,22 +64,19 @@ public class NamedIdObjectWithParent extends NamedIdObject implements @@ -64,22 +64,19 @@ public class NamedIdObjectWithParent extends NamedIdObject implements
result = HashCodeUtil.hash(result, getParentKey());
return result;
}
/**
* Provides a deep copy
*/
@Override
public Object clone() throws CloneNotSupportedException {
NamedIdObjectWithParent cl = new NamedIdObjectWithParent(
(NamedIdObject) super.clone());
NamedIdObjectWithParent cl = new NamedIdObjectWithParent((NamedIdObject) super.clone());
if (parentKey != null && !(parentKey instanceof String)
&& !(parentKey instanceof Integer))
throw new CloneNotSupportedException(
" You have to check in NamedIdObjectWithParent.clone if deep copying is necessary for class "
+ parentKey.getClass());
if (parentKey != null && !(parentKey instanceof String) && !(parentKey instanceof Integer))
throw new CloneNotSupportedException(" You have to check in NamedIdObjectWithParent.clone if deep copying is necessary for class " + parentKey.getClass());
if (this.parentKey != null)
try {
if (this.parentKey != null) try {
cl.setParentKey(this.parentKey);
} catch (KeyParentEqualException e) {
throw new CloneNotSupportedException("Cloning didn't work" + e);

1
src/de/memtext/baseobjects/NamedIdObjectWithParentI.java

@ -4,6 +4,7 @@ import de.memtext.tree.KeyParentEqualException; @@ -4,6 +4,7 @@ import de.memtext.tree.KeyParentEqualException;
public interface NamedIdObjectWithParentI extends NamedIdObjectI {
public Object getParentKey();
public void setParentKey(Object parentKey) throws KeyParentEqualException;
}
//Created on 18.11.2003

8
src/de/memtext/baseobjects/NamedObject.java

@ -8,7 +8,9 @@ import java.io.Serializable; @@ -8,7 +8,9 @@ import java.io.Serializable;
* */
public class NamedObject implements NamedObjectI, Serializable {
private String name;
private static final long serialVersionUID = 1;
/**
*
*/
@ -16,6 +18,7 @@ public class NamedObject implements NamedObjectI,Serializable { @@ -16,6 +18,7 @@ public class NamedObject implements NamedObjectI,Serializable {
public NamedObject() {
}
public NamedObject(String name) {
setName(name);
}
@ -24,6 +27,7 @@ public class NamedObject implements NamedObjectI,Serializable { @@ -24,6 +27,7 @@ public class NamedObject implements NamedObjectI,Serializable {
/**
* @return
*/
@Override
public String getName() {
return name;
}
@ -33,9 +37,12 @@ public class NamedObject implements NamedObjectI,Serializable { @@ -33,9 +37,12 @@ public class NamedObject implements NamedObjectI,Serializable {
/**
* @param string
*/
@Override
public void setName(String string) {
name = string;
}
@Override
public String toString() {
return name;
}
@ -43,6 +50,7 @@ public class NamedObject implements NamedObjectI,Serializable { @@ -43,6 +50,7 @@ public class NamedObject implements NamedObjectI,Serializable {
/**
* Provides a deep copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
return new NamedObject(this.getName());
}

2
src/de/memtext/baseobjects/NamedObjectI.java

@ -9,5 +9,7 @@ public interface NamedObjectI { @@ -9,5 +9,7 @@ public interface NamedObjectI {
public String getName();
public void setName(String name);
@Override
public String toString();
}

2
src/de/memtext/baseobjects/SearchReplaceTextHolder.java

@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@
package de.memtext.baseobjects;
/**
* This class holds information about a string that is to be
* searched for and another string that the former is to be
@ -7,6 +8,7 @@ package de.memtext.baseobjects; @@ -7,6 +8,7 @@ package de.memtext.baseobjects;
*/
public class SearchReplaceTextHolder {
private String searchText = "", replaceText = "";
public SearchReplaceTextHolder() {
super();
}

20
src/de/memtext/baseobjects/User.java

@ -14,15 +14,20 @@ import de.memtext.rights.Rights; @@ -14,15 +14,20 @@ import de.memtext.rights.Rights;
* */
public class User extends NamedIdObject implements Serializable {
private List groupMembershipIds = new ArrayList(5);
private String passwd;
private Rights rights;
private boolean isAdmin = false;
private static final long serialVersionUID = 1;
public User() {
setName("");
setPasswd("");
}
public User(String username, String passwd) {
setName(username);
setPasswd(passwd);
@ -31,18 +36,20 @@ public class User extends NamedIdObject implements Serializable { @@ -31,18 +36,20 @@ public class User extends NamedIdObject implements Serializable {
public User(String username, Integer userid) {
super(userid, username);
if (userid == null)
throw new IllegalArgumentException("No user without userid allowed");
if (userid == null) throw new IllegalArgumentException("No user without userid allowed");
}
public User(String username) {
setName(username);
}
/**
* @param groupmemberships
*/
public void addAllGroupmembershipsById(List groupmemberships) {
groupMembershipIds.addAll(groupmemberships);
}
public void addGroupMembershipById(Integer groupid) {
groupMembershipIds.add(groupid);
}
@ -56,6 +63,7 @@ public class User extends NamedIdObject implements Serializable { @@ -56,6 +63,7 @@ public class User extends NamedIdObject implements Serializable {
public Iterator groupmembershipIdIterator() {
return groupMembershipIds.iterator();
}
public void removeGroupMembershipById(Integer groupid) {
groupMembershipIds.remove(groupid);
}
@ -65,20 +73,24 @@ public class User extends NamedIdObject implements Serializable { @@ -65,20 +73,24 @@ public class User extends NamedIdObject implements Serializable {
}
public String toString()
{
@Override
public String toString() {
return getName();
}
public Rights getRights() {
return rights;
}
public void setRights(Rights rights) {
this.rights = rights;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}

66
src/de/memtext/baseobjects/coll/ActivatableItemList.java

@ -15,7 +15,9 @@ import de.memtext.baseobjects.ActivatableItemI; @@ -15,7 +15,9 @@ import de.memtext.baseobjects.ActivatableItemI;
* */
public class ActivatableItemList implements List, Serializable {
private List collect = new LinkedList();
private static final long serialVersionUID = 1;
/**
*
*/
@ -31,17 +33,18 @@ public class ActivatableItemList implements List,Serializable { @@ -31,17 +33,18 @@ public class ActivatableItemList implements List,Serializable {
Collection result = new LinkedList();
for (Iterator iter = this.iterator(); iter.hasNext();) {
ActivatableItemI element = (ActivatableItemI) iter.next();
if (element.isActive())
result.add(element);
if (element.isActive()) result.add(element);
}
return result;
}
public void setAllActive(boolean active) {
for (Iterator iter = this.iterator(); iter.hasNext();) {
ActivatableItemI element = (ActivatableItemI) iter.next();
element.setActive(active);
}
}
public boolean isAllActive() {
boolean result = true;
for (Iterator iter = this.iterator(); iter.hasNext();) {
@ -53,6 +56,7 @@ public class ActivatableItemList implements List,Serializable { @@ -53,6 +56,7 @@ public class ActivatableItemList implements List,Serializable {
}
return result;
}
public boolean isAllDeactivated() {
boolean result = true;
for (Iterator iter = this.iterator(); iter.hasNext();) {
@ -64,26 +68,27 @@ public class ActivatableItemList implements List,Serializable { @@ -64,26 +68,27 @@ public class ActivatableItemList implements List,Serializable {
}
return result;
}
public int activeCount() {
int count = 0;
for (Iterator iter = this.iterator(); iter.hasNext();) {
ActivatableItemI element = (ActivatableItemI) iter.next();
if (element.isActive())
count++;
if (element.isActive()) count++;
}
return count;
}
public int deactivatedCount() {
int count = 0;
for (Iterator iter = this.iterator(); iter.hasNext();) {
ActivatableItemI element = (ActivatableItemI) iter.next();
if (!element.isActive())
count++;
if (!element.isActive()) count++;
}
return count;
}
public ActivatableItemI getActiveItem(int pos) {
ActivatableItemI result = null;
int i = 0;
@ -96,11 +101,11 @@ public class ActivatableItemList implements List,Serializable { @@ -96,11 +101,11 @@ public class ActivatableItemList implements List,Serializable {
}
i++;
}
if (result == null)
throw new RuntimeException("not found");
if (result == null) throw new RuntimeException("not found");
return result;
}
/**
*
* @return null if all deactivated
@ -116,6 +121,7 @@ public class ActivatableItemList implements List,Serializable { @@ -116,6 +121,7 @@ public class ActivatableItemList implements List,Serializable {
}
return result;
}
/**
*
* @return null if all active
@ -131,9 +137,11 @@ public class ActivatableItemList implements List,Serializable { @@ -131,9 +137,11 @@ public class ActivatableItemList implements List,Serializable {
}
return result;
}
/* (non-Javadoc)
* @see java.util.Collection#size()
*/
@Override
public int size() {
return collect.size();
}
@ -141,6 +149,7 @@ public class ActivatableItemList implements List,Serializable { @@ -141,6 +149,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#isEmpty()
*/
@Override
public boolean isEmpty() {
return collect.isEmpty();
}
@ -148,6 +157,7 @@ public class ActivatableItemList implements List,Serializable { @@ -148,6 +157,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#contains(java.lang.Object)
*/
@Override
public boolean contains(Object o) {
return collect.contains(o);
}
@ -155,6 +165,7 @@ public class ActivatableItemList implements List,Serializable { @@ -155,6 +165,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#iterator()
*/
@Override
public Iterator iterator() {
return collect.iterator();
}
@ -162,6 +173,7 @@ public class ActivatableItemList implements List,Serializable { @@ -162,6 +173,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#toArray()
*/
@Override
public Object[] toArray() {
return collect.toArray();
}
@ -169,6 +181,7 @@ public class ActivatableItemList implements List,Serializable { @@ -169,6 +181,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#toArray(java.lang.Object[])
*/
@Override
public Object[] toArray(Object[] a) {
return collect.toArray(a);
}
@ -176,6 +189,7 @@ public class ActivatableItemList implements List,Serializable { @@ -176,6 +189,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#containsAll(java.util.Collection)
*/
@Override
public boolean containsAll(Collection c) {
return collect.containsAll(c);
}
@ -183,11 +197,11 @@ public class ActivatableItemList implements List,Serializable { @@ -183,11 +197,11 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#addAll(java.util.Collection)
*/
@Override
public boolean addAll(Collection c) {
for (Iterator iter = c.iterator(); iter.hasNext();) {
Object element = iter.next();
if (!(element instanceof ActivatableItemI))
throw new IllegalArgumentException("only Activatable items");
if (!(element instanceof ActivatableItemI)) throw new IllegalArgumentException("only Activatable items");
}
return collect.addAll(c);
@ -196,6 +210,7 @@ public class ActivatableItemList implements List,Serializable { @@ -196,6 +210,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#removeAll(java.util.Collection)
*/
@Override
public boolean removeAll(Collection c) {
return collect.removeAll(c);
}
@ -203,11 +218,11 @@ public class ActivatableItemList implements List,Serializable { @@ -203,11 +218,11 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#retainAll(java.util.Collection)
*/
@Override
public boolean retainAll(Collection c) {
for (Iterator iter = c.iterator(); iter.hasNext();) {
Object element = iter.next();
if (!(element instanceof ActivatableItemI))
throw new IllegalArgumentException("only Activatable items");
if (!(element instanceof ActivatableItemI)) throw new IllegalArgumentException("only Activatable items");
}
return collect.retainAll(c);
@ -216,6 +231,7 @@ public class ActivatableItemList implements List,Serializable { @@ -216,6 +231,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#clear()
*/
@Override
public void clear() {
collect.clear();
}
@ -223,15 +239,16 @@ public class ActivatableItemList implements List,Serializable { @@ -223,15 +239,16 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#add(java.lang.Object)
*/
@Override
public boolean add(Object o) {
if (!(o instanceof ActivatableItemI))
throw new IllegalArgumentException("only Activatable items");
if (!(o instanceof ActivatableItemI)) throw new IllegalArgumentException("only Activatable items");
return collect.add(o);
}
/* (non-Javadoc)
* @see java.util.Collection#remove(java.lang.Object)
*/
@Override
public boolean remove(Object o) {
return collect.remove(o);
}
@ -239,11 +256,11 @@ public class ActivatableItemList implements List,Serializable { @@ -239,11 +256,11 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.List#addAll(int, java.util.Collection)
*/
@Override
public boolean addAll(int index, Collection c) {
for (Iterator iter = c.iterator(); iter.hasNext();) {
Object element = iter.next();
if (!(element instanceof ActivatableItemI))
throw new IllegalArgumentException("only Activatable items");
if (!(element instanceof ActivatableItemI)) throw new IllegalArgumentException("only Activatable items");
}
return collect.addAll(c);
@ -252,6 +269,7 @@ public class ActivatableItemList implements List,Serializable { @@ -252,6 +269,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.List#get(int)
*/
@Override
public Object get(int index) {
return collect.get(index);
}
@ -259,24 +277,25 @@ public class ActivatableItemList implements List,Serializable { @@ -259,24 +277,25 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.List#set(int, java.lang.Object)
*/
@Override
public Object set(int index, Object element) {
if (!(element instanceof ActivatableItemI))
throw new IllegalArgumentException("only Activatable items");
if (!(element instanceof ActivatableItemI)) throw new IllegalArgumentException("only Activatable items");
return collect.set(index, element);
}
/* (non-Javadoc)
* @see java.util.List#add(int, java.lang.Object)
*/
@Override
public void add(int index, Object element) {
if (!(element instanceof ActivatableItemI))
throw new IllegalArgumentException("only Activatable items");
if (!(element instanceof ActivatableItemI)) throw new IllegalArgumentException("only Activatable items");
collect.add(index, element);
}
/* (non-Javadoc)
* @see java.util.List#remove(int)
*/
@Override
public Object remove(int index) {
return collect.remove(index);
}
@ -284,6 +303,7 @@ public class ActivatableItemList implements List,Serializable { @@ -284,6 +303,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.List#indexOf(java.lang.Object)
*/
@Override
public int indexOf(Object o) {
return collect.indexOf(o);
}
@ -291,6 +311,7 @@ public class ActivatableItemList implements List,Serializable { @@ -291,6 +311,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.List#lastIndexOf(java.lang.Object)
*/
@Override
public int lastIndexOf(Object o) {
return collect.lastIndexOf(o);
}
@ -298,6 +319,7 @@ public class ActivatableItemList implements List,Serializable { @@ -298,6 +319,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.List#listIterator()
*/
@Override
public ListIterator listIterator() {
return collect.listIterator();
}
@ -305,6 +327,7 @@ public class ActivatableItemList implements List,Serializable { @@ -305,6 +327,7 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.List#listIterator(int)
*/
@Override
public ListIterator listIterator(int index) {
return collect.listIterator(index);
}
@ -312,9 +335,12 @@ public class ActivatableItemList implements List,Serializable { @@ -312,9 +335,12 @@ public class ActivatableItemList implements List,Serializable {
/* (non-Javadoc)
* @see java.util.List#subList(int, int)
*/
@Override
public List subList(int fromIndex, int toIndex) {
return collect.subList(fromIndex, toIndex);
}
@Override
public String toString() {
return "ActivatableItemsList " + size() + " items";
}

16
src/de/memtext/baseobjects/coll/BaseObjectCollection.java

@ -12,7 +12,9 @@ import java.util.LinkedList; @@ -12,7 +12,9 @@ import java.util.LinkedList;
* */
public class BaseObjectCollection implements Collection, Serializable {
protected Collection collect;
private static final long serialVersionUID = 1;
public BaseObjectCollection() {
super();
collect = new LinkedList();
@ -20,6 +22,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -20,6 +22,7 @@ public class BaseObjectCollection implements Collection,Serializable {
@Override
public int size() {
return collect.size();
}
@ -27,6 +30,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -27,6 +30,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#isEmpty()
*/
@Override
public boolean isEmpty() {
return collect.isEmpty();
}
@ -34,6 +38,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -34,6 +38,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#contains(java.lang.Object)
*/
@Override
public boolean contains(Object o) {
return collect.contains(o);
}
@ -41,6 +46,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -41,6 +46,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#iterator()
*/
@Override
public Iterator iterator() {
return collect.iterator();
}
@ -48,6 +54,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -48,6 +54,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#toArray()
*/
@Override
public Object[] toArray() {
return collect.toArray();
}
@ -55,6 +62,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -55,6 +62,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#toArray(java.lang.Object[])
*/
@Override
public Object[] toArray(Object[] a) {
return collect.toArray(a);
}
@ -65,6 +73,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -65,6 +73,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#containsAll(java.util.Collection)
*/
@Override
public boolean containsAll(Collection c) {
return collect.containsAll(c);
}
@ -72,6 +81,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -72,6 +81,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#addAll(java.util.Collection)
*/
@Override
public boolean addAll(Collection c) {
return collect.addAll(c);
}
@ -79,6 +89,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -79,6 +89,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#removeAll(java.util.Collection)
*/
@Override
public boolean removeAll(Collection c) {
return collect.removeAll(c);
}
@ -86,6 +97,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -86,6 +97,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#retainAll(java.util.Collection)
*/
@Override
public boolean retainAll(Collection c) {
return collect.retainAll(c);
}
@ -93,6 +105,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -93,6 +105,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#clear()
*/
@Override
public void clear() {
collect.clear();
}
@ -100,6 +113,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -100,6 +113,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#add(java.lang.Object)
*/
@Override
public boolean add(Object o) {
if (o == null) throw new IllegalArgumentException("can't add null value");
return collect.add(o);
@ -108,6 +122,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -108,6 +122,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/* (non-Javadoc)
* @see java.util.Collection#remove(java.lang.Object)
*/
@Override
public boolean remove(Object o) {
return collect.remove(o);
}
@ -116,6 +131,7 @@ public class BaseObjectCollection implements Collection,Serializable { @@ -116,6 +131,7 @@ public class BaseObjectCollection implements Collection,Serializable {
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
BaseObjectCollection c = new BaseObjectCollection();
c.addAll(this);

27
src/de/memtext/baseobjects/coll/IdObjectCollection.java

@ -11,13 +11,13 @@ import de.memtext.util.StringUtils; @@ -11,13 +11,13 @@ import de.memtext.util.StringUtils;
*
* @author MB
* */
public class IdObjectCollection
extends BaseObjectCollection
implements Collection ,Serializable{
public class IdObjectCollection extends BaseObjectCollection implements Collection, Serializable {
private static final long serialVersionUID = 1;
public IdObjectCollection() {
super();
}
/**
*
* @param id
@ -28,17 +28,15 @@ public class IdObjectCollection @@ -28,17 +28,15 @@ public class IdObjectCollection
IdObjectI test, result = null;
for (Iterator it = collect.iterator(); it.hasNext();) {
test = (IdObjectI) it.next();
if ((id == null && test.getId() == null)
|| (test.getId() != null && test.getId().equals(id))) {
if ((id == null && test.getId() == null) || (test.getId() != null && test.getId().equals(id))) {
result = test;
break;
}
}
if (result == null)
throw new IllegalArgumentException(
"No element with id " + id + " found!");
if (result == null) throw new IllegalArgumentException("No element with id " + id + " found!");
return result;
}
/**
* like '12','34','343'
* useful for creating sqls like where x in (...)
@ -54,6 +52,7 @@ public class IdObjectCollection @@ -54,6 +52,7 @@ public class IdObjectCollection
StringUtils.deleteLastChar(result);
return result.toString();
}
public boolean containsItemWithId(Object id) {
boolean result = false;
IdObjectI test;
@ -66,6 +65,7 @@ public class IdObjectCollection @@ -66,6 +65,7 @@ public class IdObjectCollection
}
return result;
}
/**
* Checks if the collection contains only the ids given in the param collection ids
* @param Collection ids
@ -73,8 +73,7 @@ public class IdObjectCollection @@ -73,8 +73,7 @@ public class IdObjectCollection
*/
public boolean consistsOfIds(Collection ids) {
if (this.size() != ids.size())
return false;
if (this.size() != ids.size()) return false;
boolean result = true;
for (Iterator it = ids.iterator(); it.hasNext();) {
Object id = it.next();
@ -88,17 +87,17 @@ public class IdObjectCollection @@ -88,17 +87,17 @@ public class IdObjectCollection
return result;
}
@Override
public boolean add(Object o) {
if (o == null)
throw new IllegalArgumentException("can't add null value");
if (!(o instanceof IdObjectI))
throw new IllegalArgumentException("only named IdObjects allowed");
if (o == null) throw new IllegalArgumentException("can't add null value");
if (!(o instanceof IdObjectI)) throw new IllegalArgumentException("only named IdObjects allowed");
return collect.add(o);
}
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
IdObjectCollection c = new IdObjectCollection();
c.addAll(this);

21
src/de/memtext/baseobjects/coll/IdObjectList.java

@ -15,55 +15,66 @@ import de.memtext.util.StringUtils; @@ -15,55 +15,66 @@ import de.memtext.util.StringUtils;
* */
public class IdObjectList extends IdObjectCollection implements List {
private static final long serialVersionUID = 1;
public IdObjectList() {
super();
collect = new LinkedList();
}
public Object get(int pos)
{
@Override
public Object get(int pos) {
return ((List) collect).get(pos);
}
@Override
public boolean addAll(int arg0, Collection arg1) {
return ((List) collect).addAll(arg0, arg1);
}
@Override
public Object set(int arg0, Object arg1) {
return ((List) collect).set(arg0, arg1);
}
@Override
public void add(int pos, Object arg1) {
((List) collect).add(pos, arg1);
}
@Override
public Object remove(int arg0) {
return ((List) collect).remove(arg0);
}
@Override
public ListIterator listIterator(int arg0) {
return ((List) collect).listIterator(arg0);
}
@Override
public List subList(int arg0, int arg1) {
return ((List) collect).subList(arg0, arg1);
}
@Override
public int indexOf(Object arg0) {
return ((List) collect).indexOf(arg0);
}
@Override
public int lastIndexOf(Object arg0) {
return ((List) collect).lastIndexOf(arg0);
}
@Override
public ListIterator listIterator() {
return ((List) collect).listIterator();
}
public String toString()
{
@Override
public String toString() {
StringBuffer result = new StringBuffer("idobject list:");
for (Iterator it = this.iterator(); it.hasNext();) {
IdObjectI element = (IdObjectI) it.next();
@ -72,9 +83,11 @@ public class IdObjectList extends IdObjectCollection implements List { @@ -72,9 +83,11 @@ public class IdObjectList extends IdObjectCollection implements List {
StringUtils.getLastChar(result);
return result.toString();
}
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
IdObjectList c = new IdObjectList();
c.addAll(this);

2
src/de/memtext/baseobjects/coll/IdObjectSet.java

@ -5,6 +5,7 @@ import java.util.Set; @@ -5,6 +5,7 @@ import java.util.Set;
public class IdObjectSet extends IdObjectCollection implements Set {
private static final long serialVersionUID = 1;
public IdObjectSet() {
super();
collect = new HashSet();
@ -14,6 +15,7 @@ public class IdObjectSet extends IdObjectCollection implements Set { @@ -14,6 +15,7 @@ public class IdObjectSet extends IdObjectCollection implements Set {
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
IdObjectSet c = new IdObjectSet();
c.addAll(this);

25
src/de/memtext/baseobjects/coll/NamedIdObjectCollection.java

@ -4,7 +4,6 @@ import java.io.Serializable; @@ -4,7 +4,6 @@ import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import de.memtext.baseobjects.NamedIdObject;
import de.memtext.baseobjects.NamedIdObjectI;
import de.memtext.util.EqualsUtil;
import de.memtext.util.StringUtils;
@ -13,9 +12,9 @@ import de.memtext.util.StringUtils; @@ -13,9 +12,9 @@ import de.memtext.util.StringUtils;
*
* @author MB
*/
public class NamedIdObjectCollection extends NamedObjectCollection implements
Collection, Serializable {
public class NamedIdObjectCollection extends NamedObjectCollection implements Collection, Serializable {
private static final long serialVersionUID = 1;
public NamedIdObjectCollection() {
super();
}
@ -31,15 +30,12 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements @@ -31,15 +30,12 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements
NamedIdObjectI test, result = null;
for (Iterator it = collect.iterator(); it.hasNext();) {
test = (NamedIdObjectI) it.next();
if ((id == null && test.getId() == null)
|| (test.getId() != null && test.getId().equals(id))) {
if ((id == null && test.getId() == null) || (test.getId() != null && test.getId().equals(id))) {
result = test;
break;
}
}
if (result == null)
throw new IllegalArgumentException("No element with id " + id
+ " found!");
if (result == null) throw new IllegalArgumentException("No element with id " + id + " found!");
return result;
}
@ -59,6 +55,7 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements @@ -59,6 +55,7 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements
return result.toString();
}
@Override
public boolean containsItemWithName(String name) {
boolean result = false;
NamedIdObjectI test;
@ -95,8 +92,7 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements @@ -95,8 +92,7 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements
*/
public boolean consistsOfIds(Collection ids) {
if (this.size() != ids.size())
return false;
if (this.size() != ids.size()) return false;
boolean result = true;
for (Iterator it = ids.iterator(); it.hasNext();) {
Object id = it.next();
@ -110,14 +106,14 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements @@ -110,14 +106,14 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements
return result;
}
@Override
public boolean add(Object o) {
if (o == null)
throw new IllegalArgumentException("can't add null value");
if (!(o instanceof NamedIdObjectI))
throw new IllegalArgumentException("only named IdObjects allowed");
if (o == null) throw new IllegalArgumentException("can't add null value");
if (!(o instanceof NamedIdObjectI)) throw new IllegalArgumentException("only named IdObjects allowed");
return collect.add(o);
}
@Override
public String toString() {
StringBuffer result = new StringBuffer(size() + " NamedIdObjects: ");
for (Iterator it = this.iterator(); it.hasNext();) {
@ -130,6 +126,7 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements @@ -130,6 +126,7 @@ public class NamedIdObjectCollection extends NamedObjectCollection implements
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
NamedIdObjectCollection c = new NamedIdObjectCollection();
c.addAll(this);

15
src/de/memtext/baseobjects/coll/NamedIdObjectList.java

@ -11,50 +11,60 @@ import java.util.ListIterator; @@ -11,50 +11,60 @@ import java.util.ListIterator;
* */
public class NamedIdObjectList extends NamedIdObjectCollection implements List {
private static final long serialVersionUID = 1;
public NamedIdObjectList() {
super();
collect = new LinkedList();
}
public Object get(int pos)
{
@Override
public Object get(int pos) {
return ((List) collect).get(pos);
}
@Override
public boolean addAll(int arg0, Collection arg1) {
return ((List) collect).addAll(arg0, arg1);
}
@Override
public Object set(int arg0, Object arg1) {
return ((List) collect).set(arg0, arg1);
}
@Override
public void add(int pos, Object arg1) {
((List) collect).add(pos, arg1);
}
@Override
public Object remove(int arg0) {
return ((List) collect).remove(arg0);
}
@Override
public ListIterator listIterator(int arg0) {
return ((List) collect).listIterator(arg0);
}
@Override
public List subList(int arg0, int arg1) {
return ((List) collect).subList(arg0, arg1);
}
@Override
public int indexOf(Object arg0) {
return ((List) collect).indexOf(arg0);
}
@Override
public int lastIndexOf(Object arg0) {
return ((List) collect).lastIndexOf(arg0);
}
@Override
public ListIterator listIterator() {
return ((List) collect).listIterator();
}
@ -62,6 +72,7 @@ public class NamedIdObjectList extends NamedIdObjectCollection implements List { @@ -62,6 +72,7 @@ public class NamedIdObjectList extends NamedIdObjectCollection implements List {
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
NamedIdObjectList c = new NamedIdObjectList();
c.addAll(this);

3
src/de/memtext/baseobjects/coll/NamedIdObjectSet.java

@ -5,6 +5,7 @@ import java.util.Set; @@ -5,6 +5,7 @@ import java.util.Set;
public class NamedIdObjectSet extends NamedIdObjectCollection implements Set {
private static final long serialVersionUID = 1;
/**
* Default uses a HashSet internally;
*
@ -13,6 +14,7 @@ public class NamedIdObjectSet extends NamedIdObjectCollection implements Set { @@ -13,6 +14,7 @@ public class NamedIdObjectSet extends NamedIdObjectCollection implements Set {
super();
collect = new HashSet();
}
/**
*
* @param set the implementation of Set interface to use internally
@ -25,6 +27,7 @@ public class NamedIdObjectSet extends NamedIdObjectCollection implements Set { @@ -25,6 +27,7 @@ public class NamedIdObjectSet extends NamedIdObjectCollection implements Set {
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
NamedIdObjectSet c = new NamedIdObjectSet();
c.addAll(this);

33
src/de/memtext/baseobjects/coll/NamedIdObjectWithParentCollection.java

@ -3,16 +3,12 @@ package de.memtext.baseobjects.coll; @@ -3,16 +3,12 @@ package de.memtext.baseobjects.coll;
import java.util.Collection;
import java.util.Iterator;
import de.memtext.baseobjects.NamedIdObject;
import de.memtext.baseobjects.NamedIdObjectI;
import de.memtext.baseobjects.NamedIdObjectWithParent;
import de.memtext.baseobjects.NamedIdObjectWithParentI;
import de.memtext.util.EqualsUtil;
public class NamedIdObjectWithParentCollection
extends NamedIdObjectCollection
implements Collection {
public class NamedIdObjectWithParentCollection extends NamedIdObjectCollection implements Collection {
private static final long serialVersionUID = 1;
public NamedIdObjectWithParentCollection() {
super();
}
@ -29,6 +25,7 @@ public class NamedIdObjectWithParentCollection @@ -29,6 +25,7 @@ public class NamedIdObjectWithParentCollection
}
return result;
}
/**
* get a collection with all objects in the collection that have a
* given parentKey
@ -38,29 +35,24 @@ public class NamedIdObjectWithParentCollection @@ -38,29 +35,24 @@ public class NamedIdObjectWithParentCollection
* makes casting possible
*/
public NamedIdObjectWithParentCollection getByParent(Object parentKey) {
NamedIdObjectWithParentCollection result =
new NamedIdObjectWithParentCollection();
if (this instanceof NamedIdObjectWithParentList)
result = new NamedIdObjectWithParentList();
if (this instanceof NamedIdObjectWithParentSet)
result = new NamedIdObjectWithParentSet();
NamedIdObjectWithParentCollection result = new NamedIdObjectWithParentCollection();
if (this instanceof NamedIdObjectWithParentList) result = new NamedIdObjectWithParentList();
if (this instanceof NamedIdObjectWithParentSet) result = new NamedIdObjectWithParentSet();
for (Iterator it = this.iterator(); it.hasNext();) {
NamedIdObjectWithParentI element =
(NamedIdObjectWithParentI) it.next();
if (EqualsUtil.areEqual(element.getParentKey(),parentKey))
result.add(element);
NamedIdObjectWithParentI element = (NamedIdObjectWithParentI) it.next();
if (EqualsUtil.areEqual(element.getParentKey(), parentKey)) result.add(element);
}
return result;
}
public int countItemsWithParent(Object parent)
{
public int countItemsWithParent(Object parent) {
return getByParent(parent).size();
}
public String toString()
{
@Override
public String toString() {
StringBuffer result = new StringBuffer(size() + " NamedIdObjectsWithParent: ");
for (Iterator it = this.iterator(); it.hasNext();) {
NamedIdObjectWithParentI element = (NamedIdObjectWithParentI) it.next();
@ -72,6 +64,7 @@ public class NamedIdObjectWithParentCollection @@ -72,6 +64,7 @@ public class NamedIdObjectWithParentCollection
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
NamedIdObjectWithParentCollection c = new NamedIdObjectWithParentCollection();
c.addAll(this);

19
src/de/memtext/baseobjects/coll/NamedIdObjectWithParentList.java

@ -7,54 +7,65 @@ import java.util.ListIterator; @@ -7,54 +7,65 @@ import java.util.ListIterator;
public class NamedIdObjectWithParentList extends NamedIdObjectWithParentCollection implements List {
private static final long serialVersionUID = 1;
public NamedIdObjectWithParentList() {
super();
collect = new LinkedList();
}
public Object get(int pos)
{
@Override
public Object get(int pos) {
return ((List) collect).get(pos);
}
@Override
public boolean addAll(int arg0, Collection arg1) {
return ((List) collect).addAll(arg0, arg1);
}
@Override
public Object set(int arg0, Object arg1) {
return ((List) collect).set(arg0, arg1);
}
@Override
public void add(int pos, Object arg1) {
((List) collect).add(pos, arg1);
}
@Override
public Object remove(int arg0) {
return ((List) collect).remove(arg0);
}
@Override
public ListIterator listIterator(int arg0) {
return ((List) collect).listIterator(arg0);
}
@Override
public List subList(int arg0, int arg1) {
return ((List) collect).subList(arg0, arg1);
}
@Override
public int indexOf(Object arg0) {
return ((List) collect).indexOf(arg0);
}
@Override
public int lastIndexOf(Object arg0) {
return ((List) collect).lastIndexOf(arg0);
}
@Override
public ListIterator listIterator() {
return ((List) collect).listIterator();
}
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
NamedIdObjectWithParentList c = new NamedIdObjectWithParentList();
c.addAll(this);

2
src/de/memtext/baseobjects/coll/NamedIdObjectWithParentSet.java

@ -5,6 +5,7 @@ import java.util.Set; @@ -5,6 +5,7 @@ import java.util.Set;
public class NamedIdObjectWithParentSet extends NamedIdObjectWithParentCollection implements Set {
private static final long serialVersionUID = 1;
public NamedIdObjectWithParentSet() {
super();
collect = new HashSet();
@ -14,6 +15,7 @@ public class NamedIdObjectWithParentSet extends NamedIdObjectWithParentCollectio @@ -14,6 +15,7 @@ public class NamedIdObjectWithParentSet extends NamedIdObjectWithParentCollectio
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
NamedIdObjectWithParentCollection c = new NamedIdObjectWithParentSet();
c.addAll(this);

31
src/de/memtext/baseobjects/coll/NamedObjectCollection.java

@ -12,9 +12,7 @@ import de.memtext.util.StringUtils; @@ -12,9 +12,7 @@ import de.memtext.util.StringUtils;
*
* @author MB
* */
public class NamedObjectCollection
extends BaseObjectCollection
implements Collection,Serializable {
public class NamedObjectCollection extends BaseObjectCollection implements Collection, Serializable {
private static final long serialVersionUID = 1;
public NamedObjectCollection() {
@ -27,7 +25,8 @@ public class NamedObjectCollection @@ -27,7 +25,8 @@ public class NamedObjectCollection
* @param name
* @return first element with given name
* @throws IllegalArgumentException if nothing found
*/public NamedObjectI getByName(String name) {
*/
public NamedObjectI getByName(String name) {
NamedObjectI test, result = null;
for (Iterator it = collect.iterator(); it.hasNext();) {
test = (NamedObjectI) it.next();
@ -36,11 +35,10 @@ public class NamedObjectCollection @@ -36,11 +35,10 @@ public class NamedObjectCollection
break;
}
}
if (result == null)
throw new IllegalArgumentException(
"No element with name " + name + " found.");
if (result == null) throw new IllegalArgumentException("No element with name " + name + " found.");
return result;
}
/**
* like '12','34','343'
* useful for creating sqls like where x in (...)
@ -55,8 +53,7 @@ public class NamedObjectCollection @@ -55,8 +53,7 @@ public class NamedObjectCollection
result.append("'" + test.getName() + "',");
}
StringUtils.deleteLastChar(result);
if (result.length() == 0)
result.append("''");
if (result.length() == 0) result.append("''");
return result.toString();
}
@ -65,8 +62,7 @@ public class NamedObjectCollection @@ -65,8 +62,7 @@ public class NamedObjectCollection
NamedObjectI test;
for (Iterator it = collect.iterator(); it.hasNext();) {
test = (NamedObjectI) it.next();
if (EqualsUtil.areEqual(test.getName(),name))
{
if (EqualsUtil.areEqual(test.getName(), name)) {
result = true;
break;
}
@ -74,15 +70,15 @@ public class NamedObjectCollection @@ -74,15 +70,15 @@ public class NamedObjectCollection
return result;
}
@Override
public boolean add(Object o) {
if (o == null)
throw new IllegalArgumentException("can't add null value");
if (!(o instanceof NamedObjectI))
throw new IllegalArgumentException("only named Objects allowed");
if (o == null) throw new IllegalArgumentException("can't add null value");
if (!(o instanceof NamedObjectI)) throw new IllegalArgumentException("only named Objects allowed");
return collect.add(o);
}
public String toString()
{
@Override
public String toString() {
StringBuffer result = new StringBuffer(size() + " NamedObjects: ");
for (Iterator it = this.iterator(); it.hasNext();) {
NamedObjectI element = (NamedObjectI) it.next();
@ -94,6 +90,7 @@ public class NamedObjectCollection @@ -94,6 +90,7 @@ public class NamedObjectCollection
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
NamedObjectCollection c = new NamedObjectCollection();
c.addAll(this);

17
src/de/memtext/baseobjects/coll/NamedObjectList.java

@ -12,49 +12,57 @@ import java.util.ListIterator; @@ -12,49 +12,57 @@ import java.util.ListIterator;
* */
public class NamedObjectList extends NamedObjectCollection implements List {
private static final long serialVersionUID = 1;
public NamedObjectList() {
super();
collect = new LinkedList();
}
public Object get(int pos)
{
@Override
public Object get(int pos) {
return ((List) collect).get(pos);
}
@Override
public boolean addAll(int arg0, Collection arg1) {
return ((List) collect).addAll(arg0, arg1);
}
@Override
public Object set(int arg0, Object arg1) {
return ((List) collect).set(arg0, arg1);
}
@Override
public void add(int pos, Object arg1) {
((List) collect).add(pos, arg1);
}
@Override
public Object remove(int arg0) {
return ((List) collect).remove(arg0);
}
@Override
public ListIterator listIterator(int arg0) {
return ((List) collect).listIterator(arg0);
}
@Override
public List subList(int arg0, int arg1) {
return ((List) collect).subList(arg0, arg1);
}
@Override
public int indexOf(Object arg0) {
return ((List) collect).indexOf(arg0);
}
@Override
public int lastIndexOf(Object arg0) {
return ((List) collect).lastIndexOf(arg0);
}
@Override
public ListIterator listIterator() {
return ((List) collect).listIterator();
}
@ -62,6 +70,7 @@ public class NamedObjectList extends NamedObjectCollection implements List { @@ -62,6 +70,7 @@ public class NamedObjectList extends NamedObjectCollection implements List {
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
NamedObjectCollection c = new NamedObjectList();
c.addAll(this);

2
src/de/memtext/baseobjects/coll/NamedObjectSet.java

@ -5,6 +5,7 @@ import java.util.Set; @@ -5,6 +5,7 @@ import java.util.Set;
public class NamedObjectSet extends NamedObjectCollection implements Set {
private static final long serialVersionUID = 1;
public NamedObjectSet() {
super();
collect = new HashSet();
@ -19,6 +20,7 @@ public class NamedObjectSet extends NamedObjectCollection implements Set { @@ -19,6 +20,7 @@ public class NamedObjectSet extends NamedObjectCollection implements Set {
/**
* Only shallow copy
*/
@Override
protected Object clone() throws CloneNotSupportedException {
NamedObjectCollection c = new NamedObjectSet();
c.addAll(this);

25
src/de/memtext/buttons/ButtonGroupPanel.java

@ -3,43 +3,47 @@ package de.memtext.buttons; @@ -3,43 +3,47 @@ package de.memtext.buttons;
import java.util.Enumeration;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class ButtonGroupPanel extends JPanel {
ButtonGroup group = new ButtonGroup();
ButtonWithValue hiddenNoSelectionButton = new ButtonWithValue("", null);
public ButtonGroupPanel() {
this(null);
}
public ButtonGroupPanel(String header) {
super();
if (header != null)
this.add(new JLabel(header));
if (header != null) this.add(new JLabel(header));
hiddenNoSelectionButton.setVisible(false);
hiddenNoSelectionButton.setSelected(true);
group.add(hiddenNoSelectionButton);
}
public void addCategory(String label, Object value, boolean isSelected) {
ButtonWithValue b = new ButtonWithValue(label, value);
this.add(b);
group.add(b);
b.setSelected(isSelected);
}
public void addCategory(String label, Object value) {
addCategory(label, value, false);
}
public void addCategory(String label, int i) {
addCategory(label, new Integer(i));
addCategory(label, Integer.valueOf(i));
}
public void addCategory(String label, int i, boolean isSelected) {
addCategory(label, new Integer(i),isSelected);
addCategory(label, Integer.valueOf(i), isSelected);
}
/**
* If you pass null as an argument no element will be selected
* @param label
@ -48,9 +52,7 @@ public class ButtonGroupPanel extends JPanel { @@ -48,9 +52,7 @@ public class ButtonGroupPanel extends JPanel {
if (label == null)
hiddenNoSelectionButton.setSelected(true);
else
for (Enumeration en = group.getElements();
en.hasMoreElements();
) {
for (Enumeration en = group.getElements(); en.hasMoreElements();) {
ButtonWithValue b = (ButtonWithValue) en.nextElement();
if (b.getText().equals(label)) {
b.doClick();
@ -61,9 +63,7 @@ public class ButtonGroupPanel extends JPanel { @@ -61,9 +63,7 @@ public class ButtonGroupPanel extends JPanel {
public Object getSelectedValue() {
ButtonWithValue selectedButton = null;
for (Enumeration en = group.getElements();
en.hasMoreElements();
) {
for (Enumeration en = group.getElements(); en.hasMoreElements();) {
ButtonWithValue b = (ButtonWithValue) en.nextElement();
if (b.isSelected()) {
selectedButton = b;
@ -72,12 +72,15 @@ public class ButtonGroupPanel extends JPanel { @@ -72,12 +72,15 @@ public class ButtonGroupPanel extends JPanel {
}
return selectedButton.getValue();
}
class ButtonWithValue extends JRadioButton {
private Object value;
ButtonWithValue(String label, Object value) {
super(label);
this.value = value;
}
Object getValue() {
return value;
}

7
src/de/memtext/buttons/Standard.java

@ -17,8 +17,7 @@ public class Standard { @@ -17,8 +17,7 @@ public class Standard {
super();
}
public static JButton getCopy()
{
public static JButton getCopy() {
JButton copy = new JButton(de.memtext.icons.MBStandardIcons.getCopy());
copy.setToolTipText("Kopieren");
@ -26,8 +25,8 @@ public class Standard { @@ -26,8 +25,8 @@ public class Standard {
return copy;
}
public static JButton getCopyWithText()
{
public static JButton getCopyWithText() {
JButton copy = new JButton("Kopieren", de.memtext.icons.MBStandardIcons.getCopy());
copy.setToolTipText("Kopieren");

1
src/de/memtext/db/AbstractHsqlStandaloneMgrResources.java

@ -31,6 +31,7 @@ @@ -31,6 +31,7 @@
package de.memtext.db;
import java.util.ListResourceBundle;
/**
* Resources for HsqlStandaloneMgr.
* For other locales extend AbstractHsqlStandloneMgrResources, i.e.

52
src/de/memtext/db/AddProc.java

@ -10,6 +10,7 @@ import java.text.DateFormat; @@ -10,6 +10,7 @@ import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Additional procedures for HSQLDB
* make sure that this class in the classpath.
@ -32,6 +33,7 @@ public class AddProc { @@ -32,6 +33,7 @@ public class AddProc {
private AddProc() {
super();
}
/**
* Fills regular tables with values from a CSV-file.
* Similar to Postgres COPY FROM command.
@ -65,20 +67,11 @@ public class AddProc { @@ -65,20 +67,11 @@ public class AddProc {
* encoding=UTF-8 if you don't have ASCII<br>
* @throws SQLException
*/
public static String copyFrom(
Connection con,
String table,
String file,
String options)
throws SQLException {
if (table == null || table.equals(""))
throw new IllegalArgumentException("Table must not be null or empty");
if (file == null || file.equals(""))
throw new IllegalArgumentException("File must not be null or empty");
public static String copyFrom(Connection con, String table, String file, String options) throws SQLException {
if (table == null || table.equals("")) throw new IllegalArgumentException("Table must not be null or empty");
if (file == null || file.equals("")) throw new IllegalArgumentException("File must not be null or empty");
File f = new File(file);
if (!f.exists())
throw new IllegalArgumentException(
"source file " + file + " doesn't exist");
if (!f.exists()) throw new IllegalArgumentException("source file " + file + " doesn't exist");
//normally created tables are in UPPERCASE in the metadata,
//but tables in inverted commas (create table "myData")
@ -88,11 +81,9 @@ public class AddProc { @@ -88,11 +81,9 @@ public class AddProc {
tableNameInMetaData = table.substring(1, table.length() - 1);
else
tableNameInMetaData = table.toUpperCase();
StringBuffer buf =
new StringBuffer("create temp text table TMP_COPYFROM(");
StringBuffer buf = new StringBuffer("create temp text table TMP_COPYFROM(");
ResultSet rs =
con.getMetaData().getColumns(null, null, tableNameInMetaData, null);
ResultSet rs = con.getMetaData().getColumns(null, null, tableNameInMetaData, null);
String colname, coltype;
boolean tableFound = false;
while (rs.next()) {
@ -102,15 +93,10 @@ public class AddProc { @@ -102,15 +93,10 @@ public class AddProc {
buf.append(colname + " " + coltype + ",");
}
rs.close();
if (!tableFound)
throw new SQLException(
"Copy from failed - table "
+ table
+ " not found");
if (!tableFound) throw new SQLException("Copy from failed - table " + table + " not found");
buf.deleteCharAt(buf.lastIndexOf(","));
buf.append("); SET TABLE TMP_COPYFROM SOURCE \"" + file);
if (options != null)
buf.append(";" + options);
if (options != null) buf.append(";" + options);
buf.append("\";");
buf.append("insert into " + table + " select * from TMP_COPYFROM");
System.out.println(buf);
@ -127,31 +113,29 @@ public class AddProc { @@ -127,31 +113,29 @@ public class AddProc {
}
public static String toDate(String year, String month, String day)
throws ParseException {
public static String toDate(String year, String month, String day) throws ParseException {
String result;
Date d =
dfUS.parse(year.trim() + "-" + month.trim() + "-" + day.trim());
Date d = dfUS.parse(year.trim() + "-" + month.trim() + "-" + day.trim());
result = dfUS.format(d);
return result;
}
public static String toDate(String year, int month, int day)
throws ParseException {
public static String toDate(String year, int month, int day) throws ParseException {
return toDate(year + "", month + "", day + "");
}
public static String toDate(int year, int month, int day)
throws ParseException {
public static String toDate(int year, int month, int day) throws ParseException {
return toDate(year + "", month + "", day + "");
}
public static void main(String a[]) {
Connection conn = null;
try {
Class.forName("org.hsqldb.jdbcDriver");
conn = DriverManager.getConnection("jdbc:hsqldb:test", "sa", "");
java.sql.Statement stmt = conn.createStatement();
stmt.execute(
"drop table \"test\" if exists;create table \"test\" (col1 integer,col2 varchar, col3 double,col4 date)");
stmt.execute("drop table \"test\" if exists;create table \"test\" (col1 integer,col2 varchar, col3 double,col4 date)");
copyFrom(conn, "\"test\"", "test.csv", "fs=;");
System.out.println("2");
copyFrom(conn, "\"test\"", "test.csv", "fs=;");

14
src/de/memtext/db/Comparison.java

@ -18,25 +18,31 @@ import java.util.LinkedList; @@ -18,25 +18,31 @@ import java.util.LinkedList;
*/
public class Comparison {
private String name;
private Collection units = new LinkedList();
public Comparison(String name) {
this.name = name;
}
public void addUnit(ComparisonUnit unit) {
units.add(unit);
}
public Iterator iterator()
{
public Iterator iterator() {
return units.iterator();
}
public int getUnitCount()
{
public int getUnitCount() {
return units.size();
}
public void removeUnit(ComparisonUnit unit) {
units.remove(unit);
}
@Override
public String toString() {
return name;
}

5
src/de/memtext/db/ComparisonUnit.java

@ -14,11 +14,12 @@ package de.memtext.db; @@ -14,11 +14,12 @@ package de.memtext.db;
*/
public class ComparisonUnit {
private String name, sql;
public ComparisonUnit(String name,String sql)
{
public ComparisonUnit(String name, String sql) {
this.name = name;
this.sql = sql;
}
/**
* @return
*/

59
src/de/memtext/db/ConnectionCreator.java

@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@
package de.memtext.db;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
@ -7,6 +8,7 @@ import java.util.Properties; @@ -7,6 +8,7 @@ import java.util.Properties;
import de.memtext.util.CryptUtils;
import de.memtext.util.PropUtils;
/**
* This class is a utility that makes the creation of database connections
* easier. If necessary, one can use loadClass("jdbdcDriver-class") and then
@ -25,49 +27,30 @@ public class ConnectionCreator { @@ -25,49 +27,30 @@ public class ConnectionCreator {
System.exit(0);
}
}
public static Connection getConnection(
String url,
String username,
String passwd) throws SQLException
{
public static Connection getConnection(String url, String username, String passwd) throws SQLException {
return DriverManager.getConnection(url, username, passwd);
}
public static Connection getConnection(
String driver,
String url,
String username,
String passwd)
throws SQLException, ClassNotFoundException {
public static Connection getConnection(String driver, String url, String username, String passwd) throws SQLException, ClassNotFoundException {
Class.forName(driver);
return getConnection(url, username, passwd);
}
public static Connection getConnectionQuitOnException(
String driver,
String url,
String username,
String passwd) {
public static Connection getConnectionQuitOnException(String driver, String url, String username, String passwd) {
Connection con = null;
try {
con = getConnection(driver, url, username, passwd);
} catch (Exception e) {
System.out.println(
"Couldn't create connection to database "
+ url
+ "\n"
+ e.toString());
System.out.println("Couldn't create connection to database " + url + "\n" + e.toString());
System.exit(-1);
}
return con;
}
public static Connection getConnection(
String propfilename,
String driverkey,
String urlkey,
String usernamekey,
String passwordkey) throws IOException, SQLException, ClassNotFoundException
{
public static Connection getConnection(String propfilename, String driverkey, String urlkey, String usernamekey, String passwordkey)
throws IOException, SQLException, ClassNotFoundException {
Properties props = PropUtils.getProps(propfilename);
String driver = PropUtils.getProperty(props, driverkey);
String url = PropUtils.getProperty(props, urlkey);
@ -76,14 +59,9 @@ public class ConnectionCreator { @@ -76,14 +59,9 @@ public class ConnectionCreator {
return getConnection(driver, url, username, passwd);
}
public static Connection getConnection(String propfilename) throws IOException, SQLException, ClassNotFoundException
{
return getConnection(
propfilename,
"driver",
"url",
"username",
"password");
public static Connection getConnection(String propfilename) throws IOException, SQLException, ClassNotFoundException {
return getConnection(propfilename, "driver", "url", "username", "password");
}
/**
@ -99,13 +77,8 @@ public class ConnectionCreator { @@ -99,13 +77,8 @@ public class ConnectionCreator {
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnectionCryptPassword(
String propfilename,
String driverkey,
String urlkey,
String usernamekey,
String passwordkey) throws IOException, SQLException, ClassNotFoundException
{
public static Connection getConnectionCryptPassword(String propfilename, String driverkey, String urlkey, String usernamekey, String passwordkey)
throws IOException, SQLException, ClassNotFoundException {
Properties props = PropUtils.getProps(propfilename);
String driver = PropUtils.getProperty(props, driverkey);
String url = PropUtils.getProperty(props, urlkey);

10
src/de/memtext/db/DB.java

@ -1,14 +1,19 @@ @@ -1,14 +1,19 @@
package de.memtext.db;
import de.memtext.baseobjects.NamedObject;
/**
* This class represents a Database system like Informix or Postgres
*/
public class DB extends NamedObject {
private String version;
static public final DB INFORMIX = new DB("Informix", "7.3");
static public final DB POSTGRES = new DB("Postgres", "7.3");
static public final DB ACCESS = new DB("Access", "2000");
/**
* The public constructors are needed because the DB class is
* a java bean which is cool for XMLEncoding
@ -17,6 +22,7 @@ public class DB extends NamedObject { @@ -17,6 +22,7 @@ public class DB extends NamedObject {
public DB() {
this("Unbekannte Datenbank", "");
}
public DB(String name) {
this(name, "");
}
@ -26,9 +32,9 @@ public class DB extends NamedObject { @@ -26,9 +32,9 @@ public class DB extends NamedObject {
this.version = version;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof DB))
return false;
if (!(o instanceof DB)) return false;
DB db = (DB) o;
return this.getName().equals(db.getName());
}

913
src/de/memtext/db/DBAccess.java

File diff suppressed because it is too large Load Diff

50
src/de/memtext/db/DBComparison.java

@ -12,21 +12,14 @@ public class DBComparison { @@ -12,21 +12,14 @@ public class DBComparison {
private DBComparison() {
super();
}
public static void main(String a[]) {
try {
Class.forName("org.hsqldb.jdbcDriver");
java.sql.Connection con =
DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost:9000",
"sa",
"");
java.sql.Connection con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost:9000", "sa", "");
DBAccess.addConnection("ssc", con);
java.sql.Connection con2 =
DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost:9500",
"sa",
"");
java.sql.Connection con2 = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost:9500", "sa", "");
DBAccess.addConnection("ssc-test", con2);
compare("ssc", "ssc-test");
@ -39,10 +32,10 @@ public class DBComparison { @@ -39,10 +32,10 @@ public class DBComparison {
}
}
private static void compare(String db1, String db2) {
private static void compare(String db1, String db2) throws SQLException {
System.out.println("Start comparing...");
StringBuffer fineTables =
new StringBuffer("The following tables are fine: ");
StringBuffer fineTables = new StringBuffer("The following tables are fine: ");
List tableList = DBAccess.get(db1).getTableList();
boolean isOk = false;
for (Iterator it = tableList.iterator(); it.hasNext();) {
@ -50,45 +43,26 @@ public class DBComparison { @@ -50,45 +43,26 @@ public class DBComparison {
if (DBAccess.get(db2).hasTable(table)) {
isOk = true;
if (DBAccess.get(db1).getColumnCount(table)
!= DBAccess.get(db2).getColumnCount(table)) {
System.out.println(
"Table "
+ table
+ " has a different number of columns");
if (DBAccess.get(db1).getColumnCount(table) != DBAccess.get(db2).getColumnCount(table)) {
System.out.println("Table " + table + " has a different number of columns");
isOk = false;
} else {
List colList = DBAccess.get(db1).getColumnNames(table);
for (Iterator it2 = colList.iterator(); it2.hasNext();) {
String colname = (String) it2.next();
if (!DBAccess.get(db2).hasColumn(table, colname)) {
System.out.println(
"Table "
+ table
+ " in "
+ db2
+ " doesn't have column:"
+ colname);
System.out.println("Table " + table + " in " + db2 + " doesn't have column:" + colname);
isOk = false;
} else {
if (DBAccess.get(db1).getColumnType(table, colname)
!= DBAccess.get(db2).getColumnType(
table,
colname)) {
System.out.println(
"Table "
+ table
+ " column:"
+ colname
+ " are of different types");
if (DBAccess.get(db1).getColumnType(table, colname) != DBAccess.get(db2).getColumnType(table, colname)) {
System.out.println("Table " + table + " column:" + colname + " are of different types");
isOk = false;
}
}
}
if (isOk)
fineTables.append(table + ",");
if (isOk) fineTables.append(table + ",");
}
} else {

11
src/de/memtext/db/DBServletException.java

@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@
package de.memtext.db;
/**
* Eine spezielle Exception im Servlet.
* Wird zwar im Applet eigentlich nicht gebraucht, aber trotzdem
@ -7,14 +8,12 @@ package de.memtext.db; @@ -7,14 +8,12 @@ package de.memtext.db;
* @author Marlies Winterstein
* @version 2.0, 18.2.2002
*/
public class DBServletException extends Exception
{
public DBServletException()
{
public class DBServletException extends Exception {
public DBServletException() {
super();
}
public DBServletException(String msg)
{
public DBServletException(String msg) {
super(msg);
}
}

69
src/de/memtext/db/DBTimer.java

@ -7,79 +7,46 @@ import de.memtext.util.TimeUtils; @@ -7,79 +7,46 @@ import de.memtext.util.TimeUtils;
public class DBTimer {
private static int runCount = 200;
private static boolean logEachRun = false;
//private static String driver="org.hsqldb.jdbcDriver";
private static String driver = "com.informix.jdbc.IfxDriver";
//private static String url="jdbc:hsqldb:hsql://localhost:9001";
private static String url = "jdbc:informix-sqli://jupiter:50000:informixserver=superx_host;database=superx";
private static String user = "superx";
private static String passwd = "anfang12";
private static String sql = "execute procedure sp_cob_keychild('1',0);";
//wenn ein zweiter Sql folgen soll - drop table tmp_xx muss z.B. in eigenem Aufruf sein.
private static String sql2 = null;//"select sum(betrag) from cob_busa,tmp_children T where fikrkey=T.key";
//"select sum(betrag) from cob_busa where fikrkey in (select key from tmp_children)";
private static String sql3 = null;//"drop table tmp_children;";
public static void main(String[] args) {
//sql="select sum(betrag) from cob_busa C, tmp_children T where fikrkey=T.key and T.parent='1'";
sql = "select sum(betrag) from cob_busa where fikrkey in ('1', \n" +
" '11 ', \n" +
" '111 ', \n" +
" '1111 ', \n" +
" '1112 ', \n" +
" '112 ', \n" +
" '1121 ', \n" +
" '1122 ', \n" +
" '113 ', \n" +
" '1131 ', \n" +
" '1132 ', \n" +
" '12 ', \n" +
" '121 ', \n" +
" '1211 ', \n" +
" '1212 ', \n" +
" '1213 ', \n" +
" '122 ', \n" +
" '123 ', \n" +
" '124 ', \n" +
" '125 ', \n" +
" '126 ', \n" +
" '13 ', \n" +
" '131 ', \n" +
" '1311 ', \n" +
" '1312 ', \n" +
" '1313 ', \n" +
" '132 ', \n" +
" '1321 ', \n" +
" '1322 ', \n" +
" '1323 ', \n" +
" '133 ', \n" +
" '1331 ', \n" +
" '1332 ', \n" +
" '1333 ', \n" +
" '1334 ', \n" +
" '134 ', \n" +
" '135 ', \n" +
" '136 ', \n" +
" '137 ', \n" +
" '138 ')";
sql = "select sum(betrag) from cob_busa where fikrkey in ('1', \n" + " '11 ', \n" + " '111 ', \n" + " '1111 ', \n" + " '1112 ', \n" + " '112 ', \n"
+ " '1121 ', \n" + " '1122 ', \n" + " '113 ', \n" + " '1131 ', \n" + " '1132 ', \n" + " '12 ', \n" + " '121 ', \n" + " '1211 ', \n"
+ " '1212 ', \n" + " '1213 ', \n" + " '122 ', \n" + " '123 ', \n" + " '124 ', \n" + " '125 ', \n" + " '126 ', \n" + " '13 ', \n"
+ " '131 ', \n" + " '1311 ', \n" + " '1312 ', \n" + " '1313 ', \n" + " '132 ', \n" + " '1321 ', \n" + " '1322 ', \n" + " '1323 ', \n"
+ " '133 ', \n" + " '1331 ', \n" + " '1332 ', \n" + " '1333 ', \n" + " '1334 ', \n" + " '134 ', \n" + " '135 ', \n" + " '136 ', \n"
+ " '137 ', \n" + " '138 ')";
try {
Class.forName(driver);
Connection conn =
java.sql.DriverManager.getConnection(
url,
user,
passwd);
Connection conn = java.sql.DriverManager.getConnection(url, user, passwd);
Statement stmt = conn.createStatement();
TimeUtils t = new TimeUtils();
System.out.println("start " + sql);
for (int i=1;i<=runCount;i++)
{
for (int i = 1; i <= runCount; i++) {
if (logEachRun) System.out.println(i);
stmt.execute(sql);
if (sql2!=null)
stmt.execute(sql2);
if (sql3!=null)
stmt.execute(sql3);
if (sql2 != null) stmt.execute(sql2);
if (sql3 != null) stmt.execute(sql3);
}
t.print(runCount + " times");
stmt.close();

13
src/de/memtext/db/DataSource.java

@ -5,16 +5,20 @@ import java.sql.DriverManager; @@ -5,16 +5,20 @@ import java.sql.DriverManager;
import java.sql.SQLException;
import de.memtext.baseobjects.NamedObject;
import de.memtext.util.CryptUtils;
/**
* wonder what this is
*/
public class DataSource extends NamedObject {
private static final String CRYPT_PREFIX = "^^@@@";
private String url, username, cryptPassword, driver;
private transient String password;
private DB db;
public DataSource() {
}
@ -30,6 +34,7 @@ public class DataSource extends NamedObject { @@ -30,6 +34,7 @@ public class DataSource extends NamedObject {
setPassword("");
this.db = DB.INFORMIX;
}
public void setAccessSampleValues() {
setUrl("jdbc:odbc:jdbcodbc:");
setUsername("informix");
@ -91,14 +96,12 @@ public class DataSource extends NamedObject { @@ -91,14 +96,12 @@ public class DataSource extends NamedObject {
}
public void setCryptPassword(String aPwd) {
if (!isEncrypted(aPwd))
{
if (!isEncrypted(aPwd)) {
//cryptPassword =CRYPT_PREFIX + CryptUtils.encryptStringDES(aPwd);
}
}
public boolean isEncrypted(String aPwd)
{
public boolean isEncrypted(String aPwd) {
return aPwd.startsWith(CRYPT_PREFIX);
}
}

35
src/de/memtext/db/DataSourceEditPanel.java

@ -16,15 +16,19 @@ import de.memtext.widgets.WarningMessage; @@ -16,15 +16,19 @@ import de.memtext.widgets.WarningMessage;
public class DataSourceEditPanel extends MultilineEditPanel {
private DataSource ds;
private LabeledTextField hostField = new LabeledTextField("Host", 10);
private LabeledTextField serverField = new LabeledTextField("Server", 10);
private LabeledTextField serviceField = new LabeledTextField("Service", 10);
private LabeledTextField odbcSourceField =
new LabeledTextField("Odbc-DSN", 10);
private LabeledTextField usernameField =
new LabeledTextField("Kennung", 10);
private LabeledTextField passwordField =
new LabeledPasswordField("Password", 10);
private LabeledTextField odbcSourceField = new LabeledTextField("Odbc-DSN", 10);
private LabeledTextField usernameField = new LabeledTextField("Kennung", 10);
private LabeledTextField passwordField = new LabeledPasswordField("Password", 10);
private JPanel pButtons = new JPanel();
public DataSourceEditPanel() {
@ -45,6 +49,8 @@ public class DataSourceEditPanel extends MultilineEditPanel { @@ -45,6 +49,8 @@ public class DataSourceEditPanel extends MultilineEditPanel {
btnTesten.setBackground(null);
pButtons.setBackground(null);
btnTesten.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
test();
}
@ -53,13 +59,16 @@ public class DataSourceEditPanel extends MultilineEditPanel { @@ -53,13 +59,16 @@ public class DataSourceEditPanel extends MultilineEditPanel {
//this.addGlue();
this.add(pButtons);
}
public void setDataSource(DataSource ds) {
this.ds = ds;
setMode(ds.getDb());
}
public void addButton(JButton btn) {
pButtons.add(btn);
}
private void setMode(DB db) {
if (db.equals(DB.ACCESS)) {
odbcSourceField.setVisible(true);
@ -74,6 +83,7 @@ public class DataSourceEditPanel extends MultilineEditPanel { @@ -74,6 +83,7 @@ public class DataSourceEditPanel extends MultilineEditPanel {
serviceField.setVisible(true);
}
}
protected void test() {
updateDataSource();
try {
@ -81,19 +91,13 @@ public class DataSourceEditPanel extends MultilineEditPanel { @@ -81,19 +91,13 @@ public class DataSourceEditPanel extends MultilineEditPanel {
InfoMessage.show(this, "Verbindung erfolgreich aufgebaut", "Erfolg");
} catch (SQLException e) {
if (ds.getDb().equals(DB.ACCESS)) {
WarningMessage.show(this,
"Verbindung zur ODBC-Quelle "
+ odbcSourceField.getValue()
+ " konnte nicht aufgebaut werden.\n"
+ e,
"Achtung");
WarningMessage.show(this, "Verbindung zur ODBC-Quelle " + odbcSourceField.getValue() + " konnte nicht aufgebaut werden.\n" + e, "Achtung");
}
} catch (ClassNotFoundException e) {
WarningMessage.show(this,
"Benötigte Treiber-Klase nicht gefunden ",
"Achtung");
WarningMessage.show(this, "Benötigte Treiber-Klase nicht gefunden ", "Achtung");
}
}
public void updateDataSource() {
if (ds.getDb() == DB.ACCESS) {
ds.setUrl("jdbc:odbc:" + odbcSourceField.getValue());
@ -101,6 +105,7 @@ public class DataSourceEditPanel extends MultilineEditPanel { @@ -101,6 +105,7 @@ public class DataSourceEditPanel extends MultilineEditPanel {
ds.setUsername(usernameField.getValue().toString());
ds.setPassword("");
}
public void addDocumentListener(DocumentListenerObserver listener) {
hostField.addDocumentListener(listener);
serverField.addDocumentListener(listener);

34
src/de/memtext/db/DbRequest.java

@ -19,18 +19,23 @@ public class DbRequest @@ -19,18 +19,23 @@ public class DbRequest
private String sql;
private String name;
private Object[] params;
private int type;
private DbRequestType dbRequestType;
public DbRequest(String sql)
{
public DbRequest(String sql) {
this(null, sql, null, null);
}
public DbRequest(String name,String sql,Object[] params)
{
public DbRequest(String name, String sql, Object[] params) {
this(name, sql, params, null);
}
/**
* Request type used by servlet
* @param name
@ -38,41 +43,34 @@ public class DbRequest @@ -38,41 +43,34 @@ public class DbRequest
* @param params
* @param dbRequestType
*/
public DbRequest(String name,String sql,Object[] params,DbRequestType dbRequestType)
{
public DbRequest(String name, String sql, Object[] params, DbRequestType dbRequestType) {
setName(name);
setSql(sql);
setParams(params);
this.dbRequestType = dbRequestType;
}
public String getName()
{
public String getName() {
return name;
}
public void setName(String name)
{
public void setName(String name) {
this.name = name;
}
public Object[] getParams()
{
public Object[] getParams() {
return params;
}
public void setParams(Object[] params)
{
public void setParams(Object[] params) {
this.params = params;
}
public String getSql()
{
public String getSql() {
return sql;
}
public void setSql(String sql)
{
public void setSql(String sql) {
this.sql = sql;
}

10
src/de/memtext/db/DbRequestType.java

@ -17,11 +17,15 @@ public class DbRequestType { @@ -17,11 +17,15 @@ public class DbRequestType {
private final String name;
public static final DbRequestType QUERY = new DbRequestType("QUERY");
public static final DbRequestType UPDATE = new DbRequestType("UPDATE");
private DbRequestType(String name)
{
private DbRequestType(String name) {
this.name = name;
}
public String toString() {return name;
@Override
public String toString() {
return name;
}
}

11
src/de/memtext/db/DbResponse.java

@ -16,9 +16,13 @@ import java.util.Collection; @@ -16,9 +16,13 @@ import java.util.Collection;
*/
public class DbResponse implements java.io.Serializable {
static final long serialVersionUID = -3L;
private Collection result;
private boolean OK;
private Exception exception;
private int updatedRowsCount;
/**
@ -29,24 +33,31 @@ public DbResponse(Collection result, boolean OK, Exception exception) { @@ -29,24 +33,31 @@ public DbResponse(Collection result, boolean OK, Exception exception) {
this.OK = OK;
this.exception = exception;
}
public Exception getException() {
return exception;
}
public Collection getResult() {
return result;
}
public boolean isOK() {
return OK;
}
public void setException(Exception exception) {
this.exception = exception;
}
public void setOK(boolean OK) {
this.OK = OK;
}
public void setResult(Collection result) {
this.result = result;
}
public int getUpdatedRowsCount() {
return updatedRowsCount;
}

31
src/de/memtext/db/DbRmiClient.java

@ -22,9 +22,10 @@ import java.util.List; @@ -22,9 +22,10 @@ import java.util.List;
*/
public class DbRmiClient {
private DbServerI dbServerI = null;
String name = "DbServer"; //"//localhost/DbServer"
public DbRmiClient()
{
public DbRmiClient() {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
@ -38,22 +39,20 @@ public DbRmiClient() @@ -38,22 +39,20 @@ public DbRmiClient()
e.printStackTrace();
}
}
public void test()
{
public void test() {
testUpdate();
testQuery();
}
private void testUpdate() {
try {
DbRequest dbRequest = new DbRequest("update dummy set col2=99");
DbResponse dbResponse = dbServerI.execute(dbRequest);
if (dbResponse.isOK())
{
if (dbResponse.isOK()) {
System.out.println("OK - updated rows :" + dbResponse.getUpdatedRowsCount());
}
else
{
} else {
System.out.println("failed :" + dbResponse.getException());
}
@ -69,28 +68,23 @@ private void testQuery() { @@ -69,28 +68,23 @@ private void testQuery() {
DbRequest dbRequest = new DbRequest("select * from dummy");
DbResponse dbResponse = dbServerI.executeQuery("select * from dummy");
if (dbResponse.isOK())
{
if (dbResponse.isOK()) {
System.out.println("OK");
List result = (List) dbResponse.getResult();
System.out.println("rows:" + result.size());
int i = 0;
for (Iterator it=result.iterator();it.hasNext();)
{
for (Iterator it = result.iterator(); it.hasNext();) {
List row = (List) it.next();
i++;
System.out.print("row " + i + " ");
for (Iterator it2=row.iterator();it2.hasNext();)
{
for (Iterator it2 = row.iterator(); it2.hasNext();) {
Object o = it2.next();
System.out.print(" - " + o);
}
System.out.println("");
}
}
else
{
} else {
System.out.println("failed :" + dbResponse.getException());
}
@ -100,6 +94,7 @@ private void testQuery() { @@ -100,6 +94,7 @@ private void testQuery() {
e.printStackTrace();
}
}
public static void main(String a[]) {
DbRmiClient c = new DbRmiClient();
c.test();

3
src/de/memtext/db/DbServerI.java

@ -17,7 +17,10 @@ import java.rmi.RemoteException; @@ -17,7 +17,10 @@ import java.rmi.RemoteException;
*/
public interface DbServerI extends Remote {
public DbResponse execute(String sql) throws RemoteException;
public DbResponse executeQuery(String sql) throws RemoteException;
public DbResponse execute(DbRequest dbRequest) throws RemoteException;
public DbResponse executeQuery(DbRequest dbRequest) throws RemoteException;
}

23
src/de/memtext/db/DbServerImpl.java

@ -22,16 +22,21 @@ import java.util.List; @@ -22,16 +22,21 @@ import java.util.List;
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class DbServerImpl
extends UnicastRemoteObject
implements de.memtext.db.DbServerI {
public class DbServerImpl extends UnicastRemoteObject implements de.memtext.db.DbServerI {
private String dbDriver = "org.hsqldb.jdbcDriver";
private String dbURL = "jdbc:hsqldb:hsql://localhost:9000";
private String userid = "SA";
private String passwd = "";
private int updateRowCount;
private Connection con;
private Statement stmt;
public DbServerImpl() throws RemoteException {
super();
ConnectionCreator.loadClass(dbDriver);
@ -43,6 +48,8 @@ public class DbServerImpl @@ -43,6 +48,8 @@ public class DbServerImpl
throw new RemoteException("Couldn't connect to DB" + e.toString());
}
}
@Override
public DbResponse execute(String sql) throws RemoteException {
DbResponse result = new DbResponse(null, true, null);
try {
@ -60,14 +67,15 @@ public class DbServerImpl @@ -60,14 +67,15 @@ public class DbServerImpl
/* (non-Javadoc)
* @see de.mbisping.db.DbServerI#execute(de.mbisping.db.DbRequest)
*/
@Override
public DbResponse execute(DbRequest dbRequest) throws RemoteException {
DbResponse result = new DbResponse(null, true, null);
if (dbRequest.getSql() != null)
result = execute(dbRequest.getSql());
if (dbRequest.getSql() != null) result = execute(dbRequest.getSql());
return result;
}
@Override
public DbResponse executeQuery(String sql) throws RemoteException {
DbResponse result = new DbResponse(null, true, null);
try {
@ -82,11 +90,12 @@ public class DbServerImpl @@ -82,11 +90,12 @@ public class DbServerImpl
}
return result;
}
/* (non-Javadoc)
* @see de.mbisping.db.DbServerI#executeQuery(de.mbisping.db.DbRequest)
*/
public DbResponse executeQuery(DbRequest dbRequest)
throws RemoteException {
@Override
public DbResponse executeQuery(DbRequest dbRequest) throws RemoteException {
DbResponse result = new DbResponse(null, true, null);
result.setUpdatedRowsCount(20);
return result;

122
src/de/memtext/db/DbUtils.java

@ -1,12 +1,9 @@ @@ -1,12 +1,9 @@
package de.memtext.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
@ -22,17 +19,24 @@ public class DbUtils { @@ -22,17 +19,24 @@ public class DbUtils {
private DbUtils() {
}
/*
* private Vector toResultVector(ResultSet rs) throws SQLException { Vector help
* = new Vector(); ResultSetMetaData rsmd = rs.getMetaData(); int
* numberOfColumns = rsmd.getColumnCount();
*
* Vector row = null; while (rs.next()) { row = new Vector(); for (int i = 1; i
* <= numberOfColumns; i++) { row.add(rs.getObject(i)); } help.add(row); }
* rs.close(); return help;
*
* }
*/
/* private Vector toResultVector(ResultSet rs) throws SQLException
{
Vector help = new Vector();
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
Vector row = null;
while (rs.next()) {
row = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
row.add(rs.getObject(i));
}
help.add(row);
}
rs.close();
return help;
}*/
public static List toResultList(ResultSet rs) throws SQLException {
List help = new LinkedList();
ResultSetMetaData rsmd = rs.getMetaData();
@ -50,7 +54,7 @@ public class DbUtils { @@ -50,7 +54,7 @@ public class DbUtils {
return help;
}
public static void grantRightToAllTables() {
public static void grantRightToAllTables() throws SQLException {
String url = "jdbc:hsqldb:hsql://localhost:9999";
String user = "";
String right = "select";
@ -76,102 +80,20 @@ public class DbUtils { @@ -76,102 +80,20 @@ public class DbUtils {
}
DBAccess.get("dbConn").execute(buf.toString());
DBAccess.closeConnection("dbConn");
}
/**
* Places Object in inverted single commas if it isn't null
*
* @param val
* @return either "null" if val is null or "'val'"
*/
public static String placeInInvertedCommas(Object val) {
if (val == null)
return "null";
if (val == null) return "null";
return "'" + val + "'";
}
public static int getInt(Statement stm, String query) throws SQLException {
int result = -1;
ResultSet rs = stm.executeQuery(query);
while (rs.next()) {
result = rs.getInt(1);
}
rs.close();
return result;
}
public static String getString(Statement stm, String query) throws SQLException {
String result = null;
ResultSet rs = stm.executeQuery(query);
while (rs.next()) {
result = rs.getString(1);
}
rs.close();
return result;
}
/**
*
* @param query
* @return -1 wenn nichts gefunden
* @throws SQLException
*/
public static int getInt(Connection con, String query,int param) throws SQLException {
int result = -1;
PreparedStatement pst=con.prepareStatement(query);
pst.setInt(1, param);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
result = rs.getInt(1);
}
rs.close();
pst.close();
return result;
}
/**
*
* @param query
* @return -1 wenn nichts gefunden
* @throws SQLException
*/
public static int getInt(Connection con, String query,String param) throws SQLException {
int result = -1;
PreparedStatement pst=con.prepareStatement(query);
pst.setString(1, param);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
result = rs.getInt(1);
}
rs.close();
pst.close();
return result;
}
/**
*
* @param con
* @param query
* @param param
* @return null if nothing found
* @throws SQLException
*/
public static String getString(Connection con,String query,String param) throws SQLException
{
String result=null;
PreparedStatement pst=con.prepareStatement(query);
pst.setString(1, param);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
result = rs.getString(1);
}
rs.close();
pst.close();
return result;
}
}
//Created on 21.06.2003

88
src/de/memtext/db/HsqlProcedures.java

@ -19,101 +19,47 @@ public class HsqlProcedures { @@ -19,101 +19,47 @@ public class HsqlProcedures {
super();
}
public static Integer get1()
{
return new Integer(1);
public static Integer get1() {
return Integer.valueOf(1);
}
public static void alterTableColumnIntegerToVarchar(
java.sql.Connection con,
String tablename,
String columnname) {
public static void alterTableColumnIntegerToVarchar(java.sql.Connection con, String tablename, String columnname) {
try {
Statement stmt = con.createStatement();
// add new tmp varchar col
stmt.execute(
"alter table "
+ tablename
+ " add column tmp"
+ columnname
+ " varchar");
stmt.execute("alter table " + tablename + " add column tmp" + columnname + " varchar");
//update value of tmp
stmt.execute(
"update "
+ tablename
+ " set tmp"
+ columnname
+ "= "
+ columnname);
stmt.execute("update " + tablename + " set tmp" + columnname + "= " + columnname);
//drop original
stmt.execute(
"alter table " + tablename + " drop column " + columnname);
stmt.execute("alter table " + tablename + " drop column " + columnname);
//add col with original name and of varchar type
stmt.execute(
"alter table "
+ tablename
+ " add column "
+ columnname
+ " varchar");
stmt.execute("alter table " + tablename + " add column " + columnname + " varchar");
//update values
stmt.execute(
"update "
+ tablename
+ " set "
+ columnname
+ "= tmp"
+ columnname);
stmt.execute("update " + tablename + " set " + columnname + "= tmp" + columnname);
//drop tmp
stmt.execute(
"alter table " + tablename + " drop column tmp" + columnname);
stmt.execute("alter table " + tablename + " drop column tmp" + columnname);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void alterTableColumnVarcharToInteger(
java.sql.Connection con,
String tablename,
String columnname) {
public static void alterTableColumnVarcharToInteger(java.sql.Connection con, String tablename, String columnname) {
try {
Statement stmt = con.createStatement();
// add new tmp varchar col
stmt.execute(
"alter table "
+ tablename
+ " add column tmp"
+ columnname
+ " integer");
stmt.execute("alter table " + tablename + " add column tmp" + columnname + " integer");
//update value of tmp
stmt.execute(
"update "
+ tablename
+ " set tmp"
+ columnname
+ "= "
+ columnname);
stmt.execute("update " + tablename + " set tmp" + columnname + "= " + columnname);
//drop original
stmt.execute(
"alter table " + tablename + " drop column " + columnname);
stmt.execute("alter table " + tablename + " drop column " + columnname);
//add col with original name and of varchar type
stmt.execute(
"alter table "
+ tablename
+ " add column "
+ columnname
+ " integer");
stmt.execute("alter table " + tablename + " add column " + columnname + " integer");
//update values
stmt.execute(
"update "
+ tablename
+ " set "
+ columnname
+ "= tmp"
+ columnname);
stmt.execute("update " + tablename + " set " + columnname + "= tmp" + columnname);
//drop tmp
stmt.execute(
"alter table " + tablename + " drop column tmp" + columnname);
stmt.execute("alter table " + tablename + " drop column tmp" + columnname);
} catch (Exception e) {
e.printStackTrace();
}

107
src/de/memtext/db/HsqlStandaloneMgr.java

@ -66,8 +66,7 @@ public class HsqlStandaloneMgr { @@ -66,8 +66,7 @@ public class HsqlStandaloneMgr {
String mypackage = "";
//if you place the Resources classes in some package, define it like this
mypackage = "de.memtext.db.";
resources = (AbstractHsqlStandaloneMgrResources) ResourceBundle
.getBundle(mypackage + "HsqlStandaloneMgrResources");
resources = (AbstractHsqlStandaloneMgrResources) ResourceBundle.getBundle(mypackage + "HsqlStandaloneMgrResources");
}
@ -98,26 +97,21 @@ public class HsqlStandaloneMgr { @@ -98,26 +97,21 @@ public class HsqlStandaloneMgr {
* @param String
* databasename - of the original database, no _TMP_COPY appendix
*/
public static void deleteTmpFiles(String url, String path,
String databasename) {
if (databasename.indexOf("_TMP_COPY") > -1)
throw new IllegalArgumentException(
"Please specifiy the name of the original database without _TMP_COPY");
public static void deleteTmpFiles(String url, String path, String databasename) {
if (databasename.indexOf("_TMP_COPY") > -1) throw new IllegalArgumentException("Please specifiy the name of the original database without _TMP_COPY");
path = getAdaptedPath(path);
int tmpPos = url.indexOf("_TMP_COPY");
if (tmpPos == -1) {
//if the main connection is closed delete info about the user
File f = new File(path + databasename + "_user.properties");
if (f.exists())
f.delete();
if (f.exists()) f.delete();
} else {
//delete files for temp. connection
String tmp = url.substring(tmpPos);
if (path == null || path.equals("")) path = ".";
File fpath = new File(path);
File tmpFiles[] = fpath.listFiles(new TmpFileFilter(databasename
+ tmp));
File tmpFiles[] = fpath.listFiles(new TmpFileFilter(databasename + tmp));
for (int i = 0; i < tmpFiles.length; i++) {
tmpFiles[i].delete();
}
@ -141,8 +135,7 @@ public class HsqlStandaloneMgr { @@ -141,8 +135,7 @@ public class HsqlStandaloneMgr {
public static int askUser(Component parentComponent, String path,
String databasename, boolean isReadOnlyCopyWanted) {
if (resources == null)
initResources();
if (resources == null) initResources();
String username = null;
File f = new File(getAdaptedPath(path) + databasename + "_user.properties");
@ -155,25 +148,18 @@ public class HsqlStandaloneMgr { @@ -155,25 +148,18 @@ public class HsqlStandaloneMgr {
username = p.getProperty("user");
fis.close();
} catch (Exception e) {
System.err.println(resources
.getString("Couldn't read user name"));
System.err.println(resources.getString("Couldn't read user name"));
e.printStackTrace();
}
}
StringBuffer msg = new StringBuffer(resources.getDbInUseBy(
databasename, username));
StringBuffer msg = new StringBuffer(resources.getDbInUseBy(databasename, username));
if (isReadOnlyCopyWanted)
msg
.append(resources
.getString("Would you like to open a temporary copy in read-only mode?"));
msg.append(resources.getString("Would you like to open a temporary copy in read-only mode?"));
else
msg
.append(resources
.getString("Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!"));
return JOptionPane.showConfirmDialog(parentComponent, msg, "HSQLDB",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
msg.append(resources.getString("Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!"));
return JOptionPane.showConfirmDialog(parentComponent, msg, "HSQLDB", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
}
@ -200,12 +186,9 @@ public class HsqlStandaloneMgr { @@ -200,12 +186,9 @@ public class HsqlStandaloneMgr {
* @throws SQLException
* @throws IOException
*/
public static Connection getTmpConnection(Component parentComponent,
String path, String databasename, String username, String password,
boolean isReadOnlyCopyWanted) throws ClassNotFoundException,
SQLException, IOException {
if (resources == null)
initResources();
public static Connection getTmpConnection(Component parentComponent, String path, String databasename, String username, String password, boolean isReadOnlyCopyWanted)
throws ClassNotFoundException, SQLException, IOException {
if (resources == null) initResources();
Class.forName("org.hsqldb.jdbcDriver");
path = getAdaptedPath(path);
@ -214,46 +197,33 @@ public class HsqlStandaloneMgr { @@ -214,46 +197,33 @@ public class HsqlStandaloneMgr {
try {
copyDatabaseFiles(path, databasename, tmpInstanceNumber);
} catch (IOException e) {
JOptionPane.showMessageDialog(parentComponent, resources
.getString("Could not create temporary copy of database.)")
+ "\n" + e, "HSQLDB", JOptionPane.WARNING_MESSAGE);
JOptionPane.showMessageDialog(parentComponent, resources.getString("Could not create temporary copy of database.)") + "\n" + e, "HSQLDB", JOptionPane.WARNING_MESSAGE);
throw e;
}
if (isReadOnlyCopyWanted) {
try {
setReadonly(path + databasename + "_TMP_COPY"
+ tmpInstanceNumber + ".properties");
setReadonly(path + databasename + "_TMP_COPY" + tmpInstanceNumber + ".properties");
} catch (IOException e) {
JOptionPane
.showMessageDialog(
parentComponent,
resources
.getString("Could not set temporary copy of database to readonly mode.")
+ "\n" + e, "HSQLDB",
JOptionPane.showMessageDialog(parentComponent, resources.getString("Could not set temporary copy of database to readonly mode.") + "\n" + e, "HSQLDB",
JOptionPane.WARNING_MESSAGE);
throw e;
}
}
String url = "jdbc:hsqldb:file:" + path + databasename
+ "_TMP_COPY" + tmpInstanceNumber;
String url = "jdbc:hsqldb:file:" + path + databasename + "_TMP_COPY" + tmpInstanceNumber;
Connection con = java.sql.DriverManager.getConnection(url, username,
password);
Connection con = java.sql.DriverManager.getConnection(url, username, password);
if (!isReadOnlyCopyWanted) {
Statement stmt = con.createStatement();
ResultSet rs = stmt
.executeQuery("select count(*) from system_tables where hsqldb_type='TEXT'");
ResultSet rs = stmt.executeQuery("select count(*) from system_tables where hsqldb_type='TEXT'");
rs.next();
if (rs.getInt(1) > 0) {
stmt.execute("shutdown");
stmt.close();
con.close();
deleteTmpFiles(url, path, databasename);
throw new SQLException(
resources
.getString("Handling non read-only temporary database with text tables is not supported"));
throw new SQLException(resources.getString("Handling non read-only temporary database with text tables is not supported"));
}
rs.close();
stmt.close();
@ -263,8 +233,7 @@ public class HsqlStandaloneMgr { @@ -263,8 +233,7 @@ public class HsqlStandaloneMgr {
private static int checkNumber(String path, String databasename) {
int result = 1;
while (new File(path + databasename + "_TMP_COPY" + result
+ ".script").exists())
while (new File(path + databasename + "_TMP_COPY" + result + ".script").exists())
result++;
return result;
}
@ -287,9 +256,7 @@ public class HsqlStandaloneMgr { @@ -287,9 +256,7 @@ public class HsqlStandaloneMgr {
* @throws SQLException
* @throws IOException
*/
public static Connection getConnection(String path, String databasename,
String username, String password) throws ClassNotFoundException,
SQLException, IOException {
public static Connection getConnection(String path, String databasename, String username, String password) throws ClassNotFoundException, SQLException, IOException {
Class.forName("org.hsqldb.jdbcDriver");
String url = null;
if (path == null)
@ -297,8 +264,7 @@ public class HsqlStandaloneMgr { @@ -297,8 +264,7 @@ public class HsqlStandaloneMgr {
else
url = "jdbc:hsqldb:file:" + getAdaptedPath(path) + databasename;
Connection con = java.sql.DriverManager.getConnection(url, username,
password);
Connection con = java.sql.DriverManager.getConnection(url, username, password);
Properties p = new Properties();
p.put("user", System.getProperty("user.name"));
@ -319,8 +285,7 @@ public class HsqlStandaloneMgr { @@ -319,8 +285,7 @@ public class HsqlStandaloneMgr {
*/
private static String getAdaptedPath(String path) {
if (path == null) path = "";
if ((path.equals(".")||path.length()>1)&&!(path.endsWith("/")||path.endsWith("\\")))
path+=File.separator;
if ((path.equals(".") || path.length() > 1) && !(path.endsWith("/") || path.endsWith("\\"))) path += File.separator;
return path;
}
@ -350,20 +315,15 @@ public class HsqlStandaloneMgr { @@ -350,20 +315,15 @@ public class HsqlStandaloneMgr {
* databasename
* @throws IOException
*/
private static void copyDatabaseFiles(String path, String databasename,
int number) throws IOException {
private static void copyDatabaseFiles(String path, String databasename, int number) throws IOException {
String s = path + databasename;
copyFile(s + ".script", s + "_TMP_COPY" + number + ".script");
copyFile(s + ".properties", s + "_TMP_COPY" + number + ".properties");
if (new File(s + ".log").exists())
copyFile(s + ".log", s + "_TMP_COPY" + number + ".log");
if (new File(s + ".data").exists())
copyFile(s + ".data", s + "_TMP_COPY" + number + ".data");
if (new File(s + ".backup").exists())
copyFile(s + ".backup", s + "_TMP_COPY" + number + ".backup");
if (new File(s + ".nio").exists())
copyFile(s + ".nio", s + "_TMP_COPY" + number + ".nio");
if (new File(s + ".log").exists()) copyFile(s + ".log", s + "_TMP_COPY" + number + ".log");
if (new File(s + ".data").exists()) copyFile(s + ".data", s + "_TMP_COPY" + number + ".data");
if (new File(s + ".backup").exists()) copyFile(s + ".backup", s + "_TMP_COPY" + number + ".backup");
if (new File(s + ".nio").exists()) copyFile(s + ".nio", s + "_TMP_COPY" + number + ".nio");
}
/**
@ -375,8 +335,7 @@ public class HsqlStandaloneMgr { @@ -375,8 +335,7 @@ public class HsqlStandaloneMgr {
* target - target file name (incl. path if necessary)
* @throws IOException
*/
static public void copyFile(String source, String target)
throws IOException {
static public void copyFile(String source, String target) throws IOException {
try {
FileInputStream is = new FileInputStream(source);
@ -399,8 +358,7 @@ public class HsqlStandaloneMgr { @@ -399,8 +358,7 @@ public class HsqlStandaloneMgr {
os.close();
} catch (IOException e) {
throw new IOException("Couldn't copy file " + source + ": "
+ e.toString());
throw new IOException("Couldn't copy file " + source + ": " + e.toString());
}
}
@ -411,6 +369,7 @@ public class HsqlStandaloneMgr { @@ -411,6 +369,7 @@ public class HsqlStandaloneMgr {
this.tmpName = tmpName;
}
@Override
public boolean accept(File dir, String name) {
return name.indexOf(tmpName) > -1;
}

24
src/de/memtext/db/HsqlStandaloneMgrResources.java

@ -29,14 +29,15 @@ @@ -29,14 +29,15 @@
*/
package de.memtext.db;
/**
* Resources for HsqlStandaloneMgr.
* For other locales extend AbstractHsqlStandloneMgrResources, i.e.
* by copying HsqlStandaloneMgrResources_de to your locale
*/
public class HsqlStandaloneMgrResources extends
AbstractHsqlStandaloneMgrResources {
public class HsqlStandaloneMgrResources extends AbstractHsqlStandaloneMgrResources {
@Override
public Object[][] getContents() {
return contents;
}
@ -44,25 +45,20 @@ public class HsqlStandaloneMgrResources extends @@ -44,25 +45,20 @@ public class HsqlStandaloneMgrResources extends
static final Object[][] contents = {
{ "Couldn't read user name", "Couldn't read user name" },
{ "Would you like to open a temporary copy in read-only mode?",
"Would you like to open a temporary copy in read-only mode?" },
{
"Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!",
{ "Would you like to open a temporary copy in read-only mode?", "Would you like to open a temporary copy in read-only mode?" },
{ "Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!",
"Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!" },
{ "Could not create temporary copy of database.",
"Could not create temporary copy of database." },
{ "Could not set temporary copy of database to readonly mode.",
"Could not set temporary copy of database to readonly mode." },
{
"Handling non read-only temporary database with text tables is not supported",
{ "Could not create temporary copy of database.", "Could not create temporary copy of database." },
{ "Could not set temporary copy of database to readonly mode.", "Could not set temporary copy of database to readonly mode." },
{ "Handling non read-only temporary database with text tables is not supported",
"Handling non read-only temporary database with text tables is not supported" }
};
@Override
public String getDbInUseBy(String dbname, String user) {
String result = "The database " + dbname + " is already in use";
if (user != null)
result += " by user " + user;
if (user != null) result += " by user " + user;
result += ".\n";
return result;
}

27
src/de/memtext/db/HsqlStandaloneMgrResources_de.java

@ -29,38 +29,33 @@ @@ -29,38 +29,33 @@
*/
package de.memtext.db;
/**
* Resources for HsqlStandaloneMgr.
* For other locales extend AbstractHsqlStandloneMgrResources, i.e.
* by copying this class to your locale
*/
public class HsqlStandaloneMgrResources_de extends
AbstractHsqlStandaloneMgrResources {
public class HsqlStandaloneMgrResources_de extends AbstractHsqlStandaloneMgrResources {
@Override
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{ "Couldn't read user name", "Konnte Usernamen nicht lesen" },
{ "Would you like to open a temporary copy in read-only mode?",
"Möchten Sie eine schreibgeschützte Kopie öffnen?" },
{
"Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!",
static final Object[][] contents = { { "Couldn't read user name", "Konnte Usernamen nicht lesen" },
{ "Would you like to open a temporary copy in read-only mode?", "Möchten Sie eine schreibgeschützte Kopie öffnen?" },
{ "Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!",
"Möchten Sie eine temporäre Kopie öffnen?\nAchtung, wenn Sie das Programm beenden, gehen alle Änderungen, die Sie vorgenommen haben, verloren!" },
{ "Could not create temporary copy of database.",
"Konnte keine temporäre Kopie der Datenbank anlegen." },
{ "Could not set temporary copy of database to readonly mode.",
"Konnte die temp. Kopie nicht auf schreibgeschützt setzen" },
{
"Handling non read-only temporary database with text tables is not supported",
{ "Could not create temporary copy of database.", "Konnte keine temporäre Kopie der Datenbank anlegen." },
{ "Could not set temporary copy of database to readonly mode.", "Konnte die temp. Kopie nicht auf schreibgeschützt setzen" },
{ "Handling non read-only temporary database with text tables is not supported",
"Nicht schreibgeschützte Datenbanken mit Text-Tables werden nicht unterstützt" }
};
@Override
public String getDbInUseBy(String dbname, String user) {
String result = "Die Datenbank " + dbname + " wird schon benutzt ";
if (user != null)
result += " vom User " + user;
if (user != null) result += " vom User " + user;
result += ".\n";
return result;
}

22
src/de/memtext/db/Library2.java

@ -4,6 +4,7 @@ import java.sql.Connection; @@ -4,6 +4,7 @@ import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Additional procedures for HSQLDB
* make sure that this class in the classpath.
@ -21,6 +22,7 @@ public class Library2 { @@ -21,6 +22,7 @@ public class Library2 {
private Library2() {
super();
}
/**
* Fills regular tables with values from a CSV-file.
* Similar to Postgres COPY FROM command.
@ -52,14 +54,8 @@ public class Library2 { @@ -52,14 +54,8 @@ public class Library2 {
* encoding=UTF-8 if you don't have ASCII
* @throws SQLException
*/
public static void copyFrom(
Connection con,
String table,
String file,
String options)
throws SQLException {
StringBuffer buf =
new StringBuffer("create text table TMP_SOURCE_" + table + " (");
public static void copyFrom(Connection con, String table, String file, String options) throws SQLException {
StringBuffer buf = new StringBuffer("create text table TMP_SOURCE_" + table + " (");
ResultSet rs = con.getMetaData().getColumns(null, null, table, null);
String colname, coltype;
@ -71,16 +67,12 @@ public class Library2 { @@ -71,16 +67,12 @@ public class Library2 {
buf.append(colname + " " + coltype + ",");
}
rs.close();
if (!tableFound)
throw new IllegalArgumentException(
"Copy from failed - table " + table + " not found");
if (!tableFound) throw new IllegalArgumentException("Copy from failed - table " + table + " not found");
buf.deleteCharAt(buf.lastIndexOf(","));
buf.append("); SET TABLE TMP_SOURCE_" + table + " SOURCE \"" + file);
if (options != null)
buf.append(";" + options);
if (options != null) buf.append(";" + options);
buf.append("\";");
buf.append(
"insert into " + table + " select * from TMP_SOURCE_" + table);
buf.append("insert into " + table + " select * from TMP_SOURCE_" + table);
Statement stmt = con.createStatement();
try {
stmt.execute(buf.toString());

262
src/de/memtext/db/MemtextPool.java

@ -1,262 +0,0 @@ @@ -1,262 +0,0 @@
package de.memtext.db;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.xml.transform.TransformerConfigurationException;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.impl.GenericObjectPool;
import de.memtext.baseobjects.NamedObjectI;
import de.memtext.tree.KeyParentEqualException;
import de.memtext.util.DSAHandler;
/**
* A new Connection pool making use of Jakarta Commons dbcp.
*/
public class MemtextPool extends GenericObjectPool implements NamedObjectI {
private String name, subpath;
private String nameNoAppendix;
private Properties props = new Properties();
private String privateKeyEncoded = null;
private String publicKeyEncoded = null;
private DSAHandler dsaHandler;
public MemtextPool(String name, String nameAppendix, String subpath)
throws SQLException, IOException, DBServletException {
this.subpath = subpath;
nameNoAppendix = name;
this.setName(name + nameAppendix);
try {
readPropertiesAndUrl();
System.out
.print(" (" + props.getProperty("connectionURL") + ") ..");
} catch (Exception e) {
System.out
.println("Konnte properties / Passwort nicht lesen. " + e);
e.printStackTrace();
throw new DBServletException(
"Konnte properties / Passwort nicht lesen. " + e);
}
try {
Class.forName(props.getProperty("driverName"));
} catch (ClassNotFoundException e1) {
throw new DBServletException("Treiber "
+ props.getProperty("driverName")
+ " nicht gefunden. Ggfs. nach tomcat/common/lib kopieren.");
}
initLogging();
this.setTestOnBorrow(true);
int minIdle = 5;
if (props.getProperty("minIdle") != null
&& !props.getProperty("minIdle").trim().equals("")) {
minIdle = Integer.parseInt(props.getProperty("minIdle"));
}
this.setMinIdle(minIdle);
int maxIdle = -1;
if (props.getProperty("maxIdle") != null
&& !props.getProperty("maxIdle").trim().equals("")) {
maxIdle = Integer.parseInt(props.getProperty("maxIdle"));
}
if (maxIdle != -1)
setMaxIdle(maxIdle);
int maxActive = -1;
if (props.getProperty("maxActive") != null
&& !props.getProperty("maxActive").trim().equals("")) {
maxActive = Integer.parseInt(props.getProperty("maxActive"));
}
if (maxActive != -1)
setMaxActive(maxActive);
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
props.getProperty("connectionURL"), props);
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
connectionFactory, this, null, "select count(*) from xdummy;" //validationQuery
, false, true);
int i = 1;
try {
// PoolingDriver driver = new PoolingDriver();
Class.forName("org.apache.commons.dbcp.PoolingDriver");
} catch (ClassNotFoundException e2) {
throw new DBServletException(
"ConnectionPool Klasse org.apache.commons.dbcp.PoolingDriver nicht gefunden.\ncommons-dbcp nach tomcat/common/lib stellen.");
}
PoolingDriver driver = (PoolingDriver) DriverManager
.getDriver("jdbc:apache:commons:dbcp:");
driver.registerPool(this.getName(), this);
Object x = driver.getConnectionPool(this.getName());
try {
Connection con = this.getConnection();
Statement st = con.createStatement();
ResultSet rs = st
.executeQuery("select value from properties where name='privatekey'");
while (rs.next()) {
privateKeyEncoded = rs.getString(1);
}
rs.close();
rs = st
.executeQuery("select value from properties where name='publickey'");
while (rs.next()) {
publicKeyEncoded = rs.getString(1);
}
rs.close();
st.close();
con.close();
} catch (SQLException e) {
String msg = "Fehler beim Aufbau des ConnectionPools ";
if (!getName().startsWith("default"))
msg += " für Mandant: " + getName();
msg += "\nKonnte keine Connection aus dem Pool holen.\n" + e;
throw new SQLException(msg);
}
if (privateKeyEncoded != null)
initDSAHandler();
}
protected void initLogging() throws IOException {
/*
* LogUtils.initRawFile("superx_" + getName(), getLogDir() + "/superx_" +
* name + ".log", 2000, 1, false, true); LogUtils.initRawFile("superx_" +
* getName() + "_xml", getLogDir() + "/superx_" + name + "_xml.log",
* 2000, 1, false, true);
*
* Level lev = Level.SEVERE;
*
* try { if (props.getProperty("logLevelSQL") != null) lev =
* Level.parse(props.getProperty("logLevelSQL")); } catch
* (IllegalArgumentException e) { String msg = "Ungültiger Level für
* sqlLogger "; if (!this.getName().equals("default")) msg += "(Mandant :" +
* getName() + ") "; msg += " :" + props.getProperty("logLevelSQL");
* System.out.println(msg); } Logger.getLogger("superx_" +
* getName()).setLevel(lev); lev = Level.SEVERE;
*
* try { if (props.getProperty("logLevelXML") != null) lev =
* Level.parse(props.getProperty("logLevelXML")); } catch
* (IllegalArgumentException e) { String msg = "Ungültiger Level für
* XMLLogger "; if (!this.getName().equals("default")) msg += "(Mandant :" +
* getName() + ") "; msg += " :" + props.getProperty("logLevelXML");
* System.out.println(msg); } Logger.getLogger("superx_" + getName() +
* "_xml").setLevel(lev);
*/
}
public static String getLogDir() {
String tomcat_home = System.getProperty("catalina.home"); //tomcat 4
// and 5
if (tomcat_home == null)
tomcat_home = System.getProperty("tomcat.home"); //tomcat 3.x
if (tomcat_home == null)
tomcat_home = "/home/superx/webserver/tomcat";
return tomcat_home + "/logs";
}
public Properties getProperties() {
return props;
}
private void readPropertiesAndUrl() throws Exception {
String propname = "db_" + nameNoAppendix + ".properties";
if (nameNoAppendix.equals("default"))
propname = "db.properties";
java.net.URL url = MemtextPool.class.getProtectionDomain()
.getCodeSource().getLocation();
File myJar = new File(url.getFile());
File myPath = new File(myJar.getParent());
String pfad = myPath.getParent() + System.getProperty("file.separator");
if (subpath != null)
pfad += subpath + System.getProperty("file.separator");
props = PropsReader.prepareProps(new File(pfad + propname));
int i = 1;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void close() throws SQLException {
PoolingDriver driver = (PoolingDriver) DriverManager
.getDriver("jdbc:apache:commons:dbcp:");
driver.closePool(this.getName());
}
public Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:apache:commons:dbcp:"
+ this.getName());
}
public void init() throws TransformerConfigurationException,
KeyParentEqualException, SQLException, DBServletException {
}
public void clearLogFiles() throws IOException {
}
private void initDSAHandler() throws DBServletException {
//privateKey wird ggfs. im Konstruktur bei Connection-Test, public key
// aus properties eingelesen
if (privateKeyEncoded == null)
throw new IllegalStateException(
"privatekey war null - properties-table auf Eintrag überprüfen");
if (publicKeyEncoded == null)
throw new IllegalStateException(
"publickey war null - properties-table prüfen");
try {
dsaHandler = new DSAHandler(privateKeyEncoded, publicKeyEncoded);
} catch (Exception e) {
throw new DBServletException(e.toString());
}
}
public boolean hasDSAHandler() {
return dsaHandler != null;
}
public boolean verifiy(String data, String signature)
throws InvalidKeyException, NoSuchAlgorithmException,
InvalidKeySpecException, SignatureException {
if (dsaHandler == null)
throw new IllegalStateException(
"DSAHandler ist null, public und private key definition prüfen");
return dsaHandler.verify(data, signature);
}
public String getPrivateKey() {
return privateKeyEncoded;
}
}
//Created on 04.11.2004 at 20:18:11 as SxPool

197
src/de/memtext/db/MemtextPools.java

@ -1,197 +0,0 @@ @@ -1,197 +0,0 @@
package de.memtext.db;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
import javax.xml.transform.TransformerConfigurationException;
import org.apache.commons.dbcp.PoolingDriver;
import de.memtext.baseobjects.coll.NamedObjectSet;
import de.memtext.tree.KeyParentEqualException;
public class MemtextPools extends NamedObjectSet {
private NamedObjectSet pools = new NamedObjectSet();
public MemtextPools() {
super();
}
public synchronized Connection getConnection(String poolname)
throws SQLException {
if (pools.size() == 0)
throw new IllegalStateException("Kein ConnectionPool gefunden.");
if (!pools.containsItemWithName(poolname))
throw new SQLException("Kein ConnectionPool für Mandant:"
+ poolname + " gefunden");
String pooldrv = "jdbc:apache:commons:dbcp:" + poolname;
if (DriverManager.getDriver(pooldrv) == null) {
String msg = "Kein ConnectionPool gefunden ";
if (!poolname.equals("default"))
msg += " für Mandant " + poolname;
throw new SQLException(msg);
}
return DriverManager.getConnection(pooldrv);
}
public MemtextPool get(String poolname) {
if (!pools.containsItemWithName(poolname))
throw new IllegalStateException("Kein ConnectionPool (" + poolname
+ ") vorhanden");
return (MemtextPool) pools.getByName(poolname);
}
/* void initDefaultOnly() throws SQLException, IOException,
DBServletException {
pools.add(new MemtextPool("default"));
}
*/
/**
* wenn mehrfach benutzt wird (ConnectionPools für SuperX und Joolap)
* mind ein sollte namensappendix haben, damit unterscheidbar -
* sonst wird z.B. Pool für joolap "default" von später erzeugten Pool für superx "default"
* überschrieben!
*/
public void init(String subpath,Class poolclass, String nameAppendix) throws SQLException, IOException,
DBServletException {
if (nameAppendix==null) nameAppendix="";
Class[] params = new Class[2];
params[0] = String.class;
params[1] = String.class;
Constructor constructor;
try {
constructor = poolclass.getConstructor(params);
String db_extfile = "mandanten.cfg";
if (db_extfile.indexOf(File.separator) == -1) {
java.net.URL url = MemtextPools.class.getProtectionDomain()
.getCodeSource().getLocation();
File myJar = new File(url.getFile());
File myPath = new File(myJar.getParent());
String pfad = myPath.getParent();
if (subpath!=null) pfad+=File.separator+subpath;
db_extfile = pfad + File.separator+db_extfile; ;
}
File f = new File(db_extfile);
if (!f.exists()) {
//einfach nur normale db.properties (default)
System.out.print("Aufbau Datenbank-ConnectionPool");
Object[] args = new Object[2];
args[0] = "default";//Appendix hängt JoolapPool an
args[1] = subpath;
MemtextPool connectionPool = (MemtextPool) constructor.newInstance(args);
System.out.println(" OK");
System.out.println(" public/private key "+(connectionPool.hasDSAHandler()?" aktiv ":" nicht aktiv"));
pools.add(connectionPool);
} else { //mehrereMandanten
FileReader fr = new FileReader(f);
BufferedReader bfr = new BufferedReader(fr);
String line;
while ((line = bfr.readLine()) != null) {
System.out.print("Aufbau Datenbank-ConnectionPool für "
+ line);
Object[] args = new Object[2];
args[0] = line;//Appendix hängt JoolapPool an
args[1] = subpath;
MemtextPool connectionPool = (MemtextPool) constructor.newInstance(args);
System.out.println("OK");
System.out.println(" public/private key"+(connectionPool.hasDSAHandler()?" aktiv ":" nicht aktiv"));
pools.add(connectionPool);
}
bfr.close();
fr.close();
}
} catch (SecurityException e) {
e.printStackTrace();
throw new DBServletException(e.toString());
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new DBServletException(e.toString());
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw new DBServletException(e.toString());
} catch (InstantiationException e) {
e.printStackTrace();
throw new DBServletException(e.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new DBServletException(e.toString());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new DBServletException(e.toString());
}
}
/**
* Destroys all ConnectionPools
*
* @throws Exception
*/
public void closeAll() throws Exception {
for (Iterator it = pools.iterator(); it.hasNext();) {
MemtextPool pool = (MemtextPool) it.next();
pool.close();
}
}
public void main(String args[]) {
try {
init("xx",MemtextPool.class, null);
} catch (Exception e) {
e.printStackTrace();
}
int i = 1;
}
public void invalidate(String poolname, Connection con)
throws DBServletException {
if (!pools.containsItemWithName(poolname))
throw new DBServletException(
"Kann Connection nicht invalidieren - kein ConnectionPool "
+ poolname + " gefunden.");
try {
PoolingDriver driver = (PoolingDriver) DriverManager
.getDriver("jdbc:apache:commons:dbcp:");
//driver.invalidateConnection(con);
driver.getConnectionPool(poolname).invalidateObject(con);
} catch (Exception e) {
e.printStackTrace();
throw new DBServletException("Invalidating connection failed -" + e);
}
}
public void resetAllPools()
throws TransformerConfigurationException, KeyParentEqualException,
SQLException, DBServletException {
for (Iterator it = pools.iterator(); it.hasNext();) {
MemtextPool aPool = (MemtextPool) it.next();
aPool.init();
}
}
public void clearLogFiles() throws IOException {
for (Iterator it = pools.iterator(); it.hasNext();) {
MemtextPool aPool = (MemtextPool) it.next();
aPool.clearLogFiles();
}
}
}
//Created on 04.11.2004 at 20:18:11 als SxPools

1
src/de/memtext/db/NichtAngemeldetException.java

@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@
package de.memtext.db;
public class NichtAngemeldetException extends Exception {
public NichtAngemeldetException() {

33
src/de/memtext/db/ProcedureSql.java

@ -1,6 +1,7 @@ @@ -1,6 +1,7 @@
package de.memtext.db;
import de.memtext.util.StringUtils;
/**
* Hilfsklasse zum Erstellen von Prozeduraufrüfen für verschd.
* Datenbanken.
@ -15,17 +16,17 @@ import de.memtext.util.StringUtils; @@ -15,17 +16,17 @@ import de.memtext.util.StringUtils;
public class ProcedureSql {
private DB dbsystem;
private boolean isAddPossible = true, isNameSet, isFinished;
private String finalSelect = "";
private StringBuffer result = new StringBuffer();
public ProcedureSql(DB db) {
this.dbsystem = db;
if (dbsystem.equals(DB.INFORMIX))
result.append("execute procedure ");
if (dbsystem.equals(DB.POSTGRES))
result.append("select ");
if (dbsystem.equals(DB.INFORMIX)) result.append("execute procedure ");
if (dbsystem.equals(DB.POSTGRES)) result.append("select ");
}
@ -34,33 +35,32 @@ public class ProcedureSql { @@ -34,33 +35,32 @@ public class ProcedureSql {
result.append(procname + ("("));
isNameSet = true;
}
public void setName(String procName) {
if (isNameSet) throw new IllegalStateException("Name wurde schon gesetzt");
result.append(procName + ("("));
isNameSet = true;
}
public void addParam(String param) {
if (!isAddPossible)
throw new IllegalStateException("kann keine Parameter hinzufügen, vielleicht wurde getFinishedCall schon aufgerufen");
if (!isAddPossible) throw new IllegalStateException("kann keine Parameter hinzufügen, vielleicht wurde getFinishedCall schon aufgerufen");
result.append(param + ",");
}
public void addDateParam(String param) {
if (!isAddPossible)
throw new IllegalStateException("kann keine Parameter hinzufügen, vielleicht wurde getFinishedCall schon aufgerufen");
if (!isAddPossible) throw new IllegalStateException("kann keine Parameter hinzufügen, vielleicht wurde getFinishedCall schon aufgerufen");
if (dbsystem.equals(DB.INFORMIX))
result.append("date");
if (dbsystem.equals(DB.POSTGRES))
result.append("date_val");
if (dbsystem.equals(DB.INFORMIX)) result.append("date");
if (dbsystem.equals(DB.POSTGRES)) result.append("date_val");
result.append("('" + param + "'),");
}
public void setFinalSelect(String sel) {
finalSelect = sel;
}
public String getFinishedCall() {
if (!isFinished)
finish();
if (!isFinished) finish();
return result.toString();
}
@ -73,8 +73,7 @@ public class ProcedureSql { @@ -73,8 +73,7 @@ public class ProcedureSql {
private void addClosingBracket() {
char lc = result.charAt(result.length() - 1);// StringUtils.getLastChar(result);
if (lc==',')
StringUtils.deleteLastChar(result);
if (lc == ',') StringUtils.deleteLastChar(result);
result.append(");");
}
@ -83,7 +82,7 @@ public class ProcedureSql { @@ -83,7 +82,7 @@ public class ProcedureSql {
}
public void addParam(int in) {
addParam(new Integer(in).toString());
addParam(Integer.valueOf(in).toString());
}
public void addParam(Object param) {

10
src/de/memtext/db/PropDescriptor.java

@ -1,6 +1,7 @@ @@ -1,6 +1,7 @@
package de.memtext.db;
import de.memtext.baseobjects.NamedIdObject;
/**
* Beschreibt eine (zusätzliche) in der Datenbank hinterlegt Eigenschaft.
* (z.B. Accident meister)
@ -8,12 +9,15 @@ import de.memtext.baseobjects.NamedIdObject; @@ -8,12 +9,15 @@ import de.memtext.baseobjects.NamedIdObject;
public class PropDescriptor extends NamedIdObject {
//wie heißt die Spalte in der DB
private String colname;
//bei Combobox sql für quelle select key,name from xx
private String quelle;
//soll auf dem Bildschirm sichtbar sein
private boolean isVisible;
private String defaultkey;
private int sortnr;
@ -60,11 +64,13 @@ public class PropDescriptor extends NamedIdObject { @@ -60,11 +64,13 @@ public class PropDescriptor extends NamedIdObject {
public int getSortnr() {
return sortnr;
}
public void setSortnr(int sortnr) {
this.sortnr = sortnr;
}
public String toString()
{
@Override
public String toString() {
return getName();
}
}

46
src/de/memtext/db/PropsReader.java

@ -1,79 +1,49 @@ @@ -1,79 +1,49 @@
package de.memtext.db;
import static de.superx.servlet.SxSQL_Server.DEFAULT_MANDANTEN_ID;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.memtext.util.CryptUtils;
public class PropsReader {
private static byte key[] = { (byte) 255, (byte) 221, (byte) 127,
(byte) 109, (byte) 129 };
private static int keyLength = key.length;
private static byte key[] = { (byte) 255, (byte) 221, (byte) 127, (byte) 109, (byte) 129 };
/*
*
* 28.10.08 EInfache Verschlüsselungsmethode wird nicht mehr unterstützt
*/
public static String check(String mandantenID, String d) throws Exception {
String result = "";
// Logger.getLogger("superx_" + mandantenID).log(Level.FINEST,
// "Verschlüsseltes Passwort " + d);
if (d.startsWith("sx_des")) {
result = CryptUtils.decryptStringDES(d.substring(6));
}
else {
} else {
result = d;
/* try {
byte[] tmp;
tmp = d.getBytes();
int size = (byte) (tmp[0] ^ key[0 % keyLength]);
int index = (byte) (tmp[1] ^ key[1 % keyLength]);
byte de[] = new byte[size];
for (int i = index; i < (size + index); i++) {
de[i - index] = (byte) (tmp[i] ^ key[i % keyLength]);
}
result = new String(de);
} catch (Exception e) {
throw new DBServletException(
"Konnte Passwort nicht entschlüsseln (altes Verfahren). Bitte mit propadmin.x prüfen.\n"
+ e);
}*/
}
return result;
}
public static Properties prepareProps(File propfile) throws IOException,
FileNotFoundException, Exception {
public static Properties prepareProps(File propfile) throws IOException, FileNotFoundException, Exception {
Properties props = new Properties();
if (!propfile.exists()) {
throw new IOException("Datei nicht gefunden: " + propfile);
}
InputStream is = new FileInputStream(propfile);
if (is != null) {
props.load(is);
is.close();
} else {
throw new IOException("cannot open " + propfile);
}
String mandantenID = props.getProperty("MandantenID");
if (mandantenID == null)
mandantenID = "default";
if (mandantenID == null) mandantenID = DEFAULT_MANDANTEN_ID;
props.put("user", props.getProperty("connectionName"));
props.put("password", check(mandantenID, props
.getProperty("connectionPassword")));
props.put("password", check(mandantenID, props.getProperty("connectionPassword")));
if (props.getProperty("driverName").indexOf("postgres") > -1) {
props.put("charSet", "Latin-1");
props.put("DateStyle", "German, DMY");
// props.put("DateStyle", "ISO, DMY");
}
if (props.getProperty("driverName").indexOf("informix") > -1)

35
src/de/memtext/db/RestrictionCollector.java

@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@
package de.memtext.db;
/**
* collects restrictions for sql-clauses, manages where and
* and what to delete
@ -8,28 +9,30 @@ public class RestrictionCollector { @@ -8,28 +9,30 @@ public class RestrictionCollector {
private StringBuffer restrict = new StringBuffer();
private int count = 0;
public RestrictionCollector() {
}
public RestrictionCollector(String restriction) {
restrict.append(restriction);
count = 1;
}
public boolean isSomethingAdded()
{
public boolean isSomethingAdded() {
return count > 0;
}
public void addAndRestriction(StringBuffer restriction) {
addAndRestriction(restriction.toString());
}
public void addAndRestriction(String restriction) {
if (restriction==null||restriction.length()<3)
throw new IllegalArgumentException("Not OK:"+restriction);
if (restriction == null || restriction.length() < 3) throw new IllegalArgumentException("Not OK:" + restriction);
boolean isNewlineAtStart = restriction.startsWith("\n");
restriction = restriction.trim();
if (isNewlineAtStart) restriction = "\n" + restriction;
if (restriction.substring(0, 3).equalsIgnoreCase("and"))
restriction = restriction.substring(3);
if (restriction.substring(0, 3).equalsIgnoreCase("and")) restriction = restriction.substring(3);
if (count > 0)
restrict.append(" and " + restriction + " ");
else
@ -40,13 +43,12 @@ public class RestrictionCollector { @@ -40,13 +43,12 @@ public class RestrictionCollector {
public void addOrRestriction(StringBuffer restriction) {
addOrRestriction(restriction.toString());
}
public void addOrRestriction(String restriction) {
if (restriction==null||restriction.length()<3)
throw new IllegalArgumentException("Not OK:"+restriction);
if (restriction == null || restriction.length() < 3) throw new IllegalArgumentException("Not OK:" + restriction);
restriction = restriction.trim();
if (restriction.substring(0, 3).equalsIgnoreCase("or "))
restriction = restriction.substring(3);
if (restriction.substring(0, 3).equalsIgnoreCase("or ")) restriction = restriction.substring(3);
if (count > 0)
restrict.append(" or " + restriction + " ");
@ -54,32 +56,37 @@ public class RestrictionCollector { @@ -54,32 +56,37 @@ public class RestrictionCollector {
restrict.append(restriction + " ");
count++;
}
public void addOrRestriction(RestrictionCollector collector) {
addOrRestriction(collector.toString());
}
@Override
public String toString() {
if (count > 0)
return restrict.toString();
else
return "";
}
public String toStringInclusiveWhere()
{
public String toStringInclusiveWhere() {
if (count > 0)
return " where " + restrict;
else
return "";
}
public int getArgumentCount()
{
public int getArgumentCount() {
return count;
}
public void addAndRestriction(RestrictionCollector collector) {
if (collector.getArgumentCount() > 1)
addAndRestriction(collector.toString());
else
addAndRestriction(collector.toString());
}
public static void main(String[] args) {
RestrictionCollector r = new RestrictionCollector();
r.addAndRestriction(" AND 1=1");

21
src/de/memtext/db/SampleApp.java

@ -43,19 +43,21 @@ import javax.swing.JOptionPane; @@ -43,19 +43,21 @@ import javax.swing.JOptionPane;
public class SampleApp extends JFrame {
private Connection con = null;
private String path = ""; // null , "" or "." for current directory
private String dbname = "testing";
public SampleApp() throws ClassNotFoundException, SQLException, IOException {
super("SampleApp");
initDb();
JLabel lbl = new JLabel("got a connection to "
+ con.getMetaData().getURL());
JLabel lbl = new JLabel("got a connection to " + con.getMetaData().getURL());
this.getContentPane().add(lbl);
this.setSize(600, 400);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
try {
String url = con.getMetaData().getURL();
@ -74,16 +76,14 @@ public class SampleApp extends JFrame { @@ -74,16 +76,14 @@ public class SampleApp extends JFrame {
}
private void initDb() throws ClassNotFoundException, SQLException,
IOException {
private void initDb() throws ClassNotFoundException, SQLException, IOException {
if (!HsqlStandaloneMgr.isDatabaseOpen(path, dbname)) {
//if the database isn't open yet, we just open a regular connection
//the system username is written to a special properties file
con = HsqlStandaloneMgr.getConnection(path, dbname, "sa", "");
Statement stmt = con.createStatement();
stmt
.execute("drop table test if exists;create table test( col1 integer);insert into test values(1);checkpoint;");
stmt.execute("drop table test if exists;create table test( col1 integer);insert into test values(1);checkpoint;");
stmt.close();
} else
// the database is already open
@ -92,13 +92,10 @@ public class SampleApp extends JFrame { @@ -92,13 +92,10 @@ public class SampleApp extends JFrame {
//if not, all changes to the database will be lost after closing
// the connection
boolean isReadOnlyModeWanted = true;
int result = HsqlStandaloneMgr.askUser(this, path, dbname,
isReadOnlyModeWanted);
int result = HsqlStandaloneMgr.askUser(this, path, dbname, isReadOnlyModeWanted);
if (result == JOptionPane.YES_OPTION) {
con = HsqlStandaloneMgr.getTmpConnection(this, path, dbname,
"sa", "", isReadOnlyModeWanted);
} else
{
con = HsqlStandaloneMgr.getTmpConnection(this, path, dbname, "sa", "", isReadOnlyModeWanted);
} else {
// opening of temp. copy not wanted
System.exit(0);
}

7
src/de/memtext/db/SchemaReader.java

@ -7,7 +7,7 @@ import java.sql.DatabaseMetaData; @@ -7,7 +7,7 @@ import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import de.memtext.util.StringUtils;
import org.apache.commons.io.FileUtils;
public class SchemaReader {
@ -27,13 +27,12 @@ public class SchemaReader { @@ -27,13 +27,12 @@ public class SchemaReader {
result.append("TABLE " + tabname + "\n");
ResultSet cols = md.getColumns(null, null, tabname, null);
while (cols.next()) {
result.append(cols.getString(4) + ":"
+ cols.getObject(5) + "\n");
result.append(cols.getString(4) + ":" + cols.getObject(5) + "\n");
}
result.append("----\n");
}
}
StringUtils.write(new File("schema.txt"),result.toString());
FileUtils.writeStringToFile(new File("schema.txt"), result.toString());
} catch (IOException e) {
e.printStackTrace();

133
src/de/memtext/db/ValueRandomizer.java

@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@
package de.memtext.db;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.sql.Connection;
@ -9,6 +10,7 @@ import java.sql.Statement; @@ -9,6 +10,7 @@ import java.sql.Statement;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
/**
* Randomizes values in a database.
* Reads all values of a given table column (select distinct x from..) and
@ -21,20 +23,30 @@ import java.util.Vector; @@ -21,20 +23,30 @@ import java.util.Vector;
public class ValueRandomizer {
//private static String driver = "org.hsqldb.jdbcDriver";
private static String driver = "org.postgresql.Driver";
//private static String dbUrl = "jdbc:hsqldb:hsql://localhost:9999";
private static String dbUrl = "jdbc:postgresql://localhost:5432/superx";
private static String username = "superx"; //"joolap";
private static String password = ""; //"loopja3000";
private static String tablename = "cob_busa";
private static String colname = "betrag"; //"value";
private static String datenart = "DOUBLE"; //or "INTEGER";
private static double minFactor = 0.6;
private static double maxFactor = 1.8;
private static boolean printOutOnly = false;
private static Statement stat;
private static Random r = new Random();
public static void main(String args[]) {
try {
@ -67,6 +79,7 @@ public class ValueRandomizer { @@ -67,6 +79,7 @@ public class ValueRandomizer {
}
}
/**
* randomizes in categories of values
* only for double
@ -78,50 +91,20 @@ public class ValueRandomizer { @@ -78,50 +91,20 @@ public class ValueRandomizer {
StringBuffer updates = new StringBuffer();
float limit = 0, limit2;
for (int i = 1; i < categories; i++) {
limit =
(float) ((Double) werte.get(i * valuesPerCategory))
.doubleValue();
updates.append(
"update "
+ tablename
+ " set "
+ colname
+ "="
+ colname
+ "*"
+ getRndFactor()
+ " where "
+ colname
+ ">"
+ limit);
limit = (float) ((Double) werte.get(i * valuesPerCategory)).doubleValue();
updates.append("update " + tablename + " set " + colname + "=" + colname + "*" + getRndFactor() + " where " + colname + ">" + limit);
if (i > 1) {
limit2 =
(float) ((Double) werte.get((i - 1) * valuesPerCategory))
.doubleValue();
limit2 = (float) ((Double) werte.get((i - 1) * valuesPerCategory)).doubleValue();
updates.append(" and " + colname + "<" + limit2);
}
updates.append(";\n");
}
limit =
(float) ((Double) werte.get((categories - 1) * valuesPerCategory))
.doubleValue();
updates.append(
"update "
+ tablename
+ " set "
+ colname
+ "="
+ colname
+ "*"
+ getRndFactor()
+ " where "
+ colname
+ "<"
+ limit
+ ";");
limit = (float) ((Double) werte.get((categories - 1) * valuesPerCategory)).doubleValue();
updates.append("update " + tablename + " set " + colname + "=" + colname + "*" + getRndFactor() + " where " + colname + "<" + limit + ";");
System.out.println(updates);
}
/**
* * multiplies all occurences of a single value (e.g. 150) with a factor between
* minFactor and maxFactor (e.g. 150*1.1 -> all entries with 150 become 165)
@ -129,25 +112,13 @@ public class ValueRandomizer { @@ -129,25 +112,13 @@ public class ValueRandomizer {
* @param werte
* @throws SQLException
*/
private static void massiveRandomizeInteger(Vector werte)
throws SQLException {
private static void massiveRandomizeInteger(Vector werte) throws SQLException {
Integer einWert;
String upd = null;
for (Enumeration en = werte.elements(); en.hasMoreElements();) {
einWert = (Integer) en.nextElement();
int neuerwert = (int) (einWert.intValue() * getRndFactor());
upd =
"update "
+ tablename
+ " set "
+ colname
+ "="
+ neuerwert
+ " where "
+ colname
+ "="
+ einWert.toString()
+ ";";
upd = "update " + tablename + " set " + colname + "=" + neuerwert + " where " + colname + "=" + einWert.toString() + ";";
if (printOutOnly)
System.out.println(upd);
@ -156,6 +127,7 @@ public class ValueRandomizer { @@ -156,6 +127,7 @@ public class ValueRandomizer {
}
}
/**
* * multiplies all occurences of a single value (e.g. 150) with a factor between
* minFactor and maxFactor (e.g. 150*1.1 -> all entries with 150 become 165)
@ -163,8 +135,7 @@ public class ValueRandomizer { @@ -163,8 +135,7 @@ public class ValueRandomizer {
* @param werte
* @throws SQLException
*/
private static void massiveRandomizeDouble(Vector werte)
throws SQLException {
private static void massiveRandomizeDouble(Vector werte) throws SQLException {
Double einWert;
double zufallswert;
String upd;
@ -174,28 +145,17 @@ public class ValueRandomizer { @@ -174,28 +145,17 @@ public class ValueRandomizer {
einWert = (Double) en.nextElement();
i++;
zufallswert = einWert.doubleValue() * getRndFactor();
upd =
"update "
+ tablename
+ " set "
+ colname
+ "="
+ zufallswert
+ " where "
+ colname
+ "="
+ einWert
+ ";";
upd = "update " + tablename + " set " + colname + "=" + zufallswert + " where " + colname + "=" + einWert + ";";
if (printOutOnly)
System.out.println(upd);
else {
stat.executeUpdate(upd);
if (i % 20 == 0)
System.out.println("Done " + i + " updates of " + count);
if (i % 20 == 0) System.out.println("Done " + i + " updates of " + count);
}
}
}
private static float getRndFactor() {
double rnd = Math.abs(r.nextDouble());
while (rnd < minFactor)
@ -204,27 +164,14 @@ public class ValueRandomizer { @@ -204,27 +164,14 @@ public class ValueRandomizer {
rnd -= 0.05;
return (float) rnd;
}
private static Vector readDistinctValues() throws SQLException {
Vector werte = new Vector();
ResultSet rs = null;
Object item;
System.out.println(
"Alle werte einlesen:"
+ "select distinct "
+ colname
+ " from "
+ tablename
+ " order by 1 DESC");
rs =
stat.executeQuery(
"select distinct "
+ colname
+ " from "
+ tablename
+ " order by "
+ colname
+ " DESC");
System.out.println("Alle werte einlesen:" + "select distinct " + colname + " from " + tablename + " order by 1 DESC");
rs = stat.executeQuery("select distinct " + colname + " from " + tablename + " order by " + colname + " DESC");
while (rs.next()) {
item = rs.getObject(1);
werte.add(item);
@ -235,21 +182,25 @@ public class ValueRandomizer { @@ -235,21 +182,25 @@ public class ValueRandomizer {
private static void out() {
try {
FileWriter fw =
new FileWriter("c:\\cygwin\\home\\superx\\cob_busa.unl");
FileWriter fw = new FileWriter("c:\\cygwin\\home\\superx\\cob_busa.unl");
BufferedWriter bw = new BufferedWriter(fw);
StringBuffer buf = new StringBuffer();
ResultSet rs = stat.executeQuery("select * from cob_busa");
int cols = 20;String s;Object o;
int cols = 20;
String s;
Object o;
while (rs.next()) {
for (int i = 1; i <= cols; i++)
{o=rs.getObject(i);
if (o==null) s="";
else s=o.toString();
for (int i = 1; i <= cols; i++) {
o = rs.getObject(i);
if (o == null)
s = "";
else
s = o.toString();
buf.append(s.trim() + "^");}
buf.append(s.trim() + "^");
}
buf.append("^\n");
}

38
src/de/memtext/db/dataexchange/MyRequest.java

@ -7,61 +7,59 @@ package de.memtext.db.dataexchange; @@ -7,61 +7,59 @@ package de.memtext.db.dataexchange;
*/
public class MyRequest implements java.io.Serializable {
static final long serialVersionUID = -2L;
static final int NORMAL = 1;
static final int EXPECT_ONE_UPDATE = 2;
private String sql;
private String name;
private Object[] params;
private int type;
public MyRequest(String name,String sql,Object[] params)
{
public MyRequest(String name, String sql, Object[] params) {
this(name, sql, params, NORMAL);
}
public MyRequest(String name,String sql,Object[] params,int type)
{
public MyRequest(String name, String sql, Object[] params, int type) {
setName(name);
setSql(sql);
setParams(params);
setType(type);
}
public int getType()
{
public int getType() {
return type;
}
public void setType(int type)
{
public void setType(int type) {
this.type = type;
}
public String getName()
{
public String getName() {
return name;
}
public void setName(String name)
{
public void setName(String name) {
this.name = name;
}
public Object[] getParams()
{
public Object[] getParams() {
return params;
}
public void setParams(Object[] params)
{
public void setParams(Object[] params) {
this.params = params;
}
public String getSql()
{
public String getSql() {
return sql;
}
public void setSql(String sql)
{
public void setSql(String sql) {
this.sql = sql;
}

12
src/de/memtext/db/dataexchange/MyServletResponse.java

@ -1,6 +1,7 @@ @@ -1,6 +1,7 @@
package de.memtext.db.dataexchange;
import java.util.Vector;
/**
* Insert the type's description here.
* Creation date: (28.11.2002 19:25:34)
@ -8,9 +9,13 @@ import java.util.Vector; @@ -8,9 +9,13 @@ import java.util.Vector;
*/
public class MyServletResponse implements java.io.Serializable {
static final long serialVersionUID = -3L;
private Vector result;
private boolean OK;
private Exception exception;
private int updatedRowsCount;
/**
@ -21,24 +26,31 @@ public class MyServletResponse implements java.io.Serializable { @@ -21,24 +26,31 @@ public class MyServletResponse implements java.io.Serializable {
this.OK = OK;
this.exception = exception;
}
public Exception getException() {
return exception;
}
public Vector getResult() {
return result;
}
public boolean isOK() {
return OK;
}
public void setException(Exception exception) {
this.exception = exception;
}
public void setOK(boolean OK) {
this.OK = OK;
}
public void setResult(Vector result) {
this.result = result;
}
public int getUpdatedRowsCount() {
return updatedRowsCount;
}

11
src/de/memtext/dlg/AboutDialog.java

@ -13,17 +13,14 @@ import de.memtext.widgets.VerticalBox; @@ -13,17 +13,14 @@ import de.memtext.widgets.VerticalBox;
public class AboutDialog extends OkDlg {
private JLabel infoLbl, homepageLabel;
public AboutDialog(
Frame parent,
String title,
String infoText,
String homePageLink,
final String homepageUrl)
throws HeadlessException {
public AboutDialog(Frame parent, String title, String infoText, String homePageLink, final String homepageUrl) throws HeadlessException {
super(parent, title);
infoLbl = new JLabel(infoText);
homepageLabel = new JLabel("<html><u>" + homePageLink);
homepageLabel.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
try {

23
src/de/memtext/dlg/DialogWithExit.java

@ -33,17 +33,12 @@ public class DialogWithExit extends JDialog { @@ -33,17 +33,12 @@ public class DialogWithExit extends JDialog {
initMe();
}
public DialogWithExit(Frame owner, String arg1, boolean arg2)
throws HeadlessException {
public DialogWithExit(Frame owner, String arg1, boolean arg2) throws HeadlessException {
super(owner, arg1, arg2);
initMe();
}
public DialogWithExit(
Frame owner,
String arg1,
boolean arg2,
GraphicsConfiguration arg3) {
public DialogWithExit(Frame owner, String arg1, boolean arg2, GraphicsConfiguration arg3) {
super(owner, arg1, arg2, arg3);
initMe();
}
@ -63,27 +58,24 @@ public class DialogWithExit extends JDialog { @@ -63,27 +58,24 @@ public class DialogWithExit extends JDialog {
initMe();
}
public DialogWithExit(Dialog owner, String arg1, boolean arg2)
throws HeadlessException {
public DialogWithExit(Dialog owner, String arg1, boolean arg2) throws HeadlessException {
super(owner, arg1, arg2);
}
public DialogWithExit(
Dialog owner,
String arg1,
boolean arg2,
GraphicsConfiguration arg3)
throws HeadlessException {
public DialogWithExit(Dialog owner, String arg1, boolean arg2, GraphicsConfiguration arg3) throws HeadlessException {
super(owner, arg1, arg2, arg3);
initMe();
}
private void initMe() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
exit();
}
});
}
/**
* called if window is closed, does nothing by default,
* subclasses can override
@ -101,6 +93,7 @@ protected void exit() { @@ -101,6 +93,7 @@ protected void exit() {
public void setCenter(JComponent comp) {
this.getContentPane().add(comp, BorderLayout.CENTER);
}
/**
* installs a component in the notrh of the dialog
* @param comp

12
src/de/memtext/dlg/EnterDateDlg.java

@ -10,7 +10,9 @@ import de.memtext.widgets.WarningMessage; @@ -10,7 +10,9 @@ import de.memtext.widgets.WarningMessage;
public class EnterDateDlg {
private java.util.Date date;
private Component parentComp;
private String title, text;
public EnterDateDlg(Component parentComp, String text, String title) {
@ -19,17 +21,16 @@ public class EnterDateDlg { @@ -19,17 +21,16 @@ public class EnterDateDlg {
this.text = text;
}
public boolean wasOkSelected()
{
public boolean wasOkSelected() {
return date != null;
}
public void show() {
date = null;
String in;
boolean ok = false;
while (!ok) {
in = JOptionPane.showInputDialog(parentComp, text, title,
JOptionPane.QUESTION_MESSAGE);
in = JOptionPane.showInputDialog(parentComp, text, title, JOptionPane.QUESTION_MESSAGE);
if (in == null) {
date = null;
ok = true;
@ -38,8 +39,7 @@ public class EnterDateDlg { @@ -38,8 +39,7 @@ public class EnterDateDlg {
date = DateUtils.parse(in);
ok = true;
} catch (ParseException e) {
WarningMessage.show(parentComp, "Ungültige Datumseingabe",
title);
WarningMessage.show(parentComp, "Ungültige Datumseingabe", title);
}
}
}

13
src/de/memtext/dlg/ImportDlg.java

@ -12,6 +12,7 @@ import de.memtext.widgets.VerticalBox; @@ -12,6 +12,7 @@ import de.memtext.widgets.VerticalBox;
public class ImportDlg extends OkCancelDlg {
private JLabel lblTop = new JLabel();
private FileSelectionPanel fsp = new FileSelectionPanel("Datei");
public ImportDlg(Frame owner, String title, String infoTxt) {
@ -26,10 +27,10 @@ public class ImportDlg extends OkCancelDlg { @@ -26,10 +27,10 @@ public class ImportDlg extends OkCancelDlg {
}
public void setCurrentDir(File defaultdir)
{
public void setCurrentDir(File defaultdir) {
fsp.setCurrentDir(defaultdir);
}
/**
* @param endings
@ -38,10 +39,12 @@ public class ImportDlg extends OkCancelDlg { @@ -38,10 +39,12 @@ public class ImportDlg extends OkCancelDlg {
fsp.setFileFilter(new FilenamesFilter("CSV oder XML Dateien", endings));
}
@Override
protected void performOk() {
this.dispose();
}
@Override
protected void performCancel() {
this.dispose();
}
@ -51,11 +54,7 @@ public class ImportDlg extends OkCancelDlg { @@ -51,11 +54,7 @@ public class ImportDlg extends OkCancelDlg {
}
public static void main(String[] args) {
ImportDlg d =
new ImportDlg(
null,
"titl",
"Unfälle importieren aus CSV- oder XML-Datei (z.B. Universum Unfallanzeige 3.0)");
ImportDlg d = new ImportDlg(null, "titl", "Unfälle importieren aus CSV- oder XML-Datei (z.B. Universum Unfallanzeige 3.0)");
d.setFileFilter(".xml|.csv");
d.show();
}

10
src/de/memtext/dlg/InputDialog.java

@ -12,6 +12,7 @@ import javax.swing.JOptionPane; @@ -12,6 +12,7 @@ import javax.swing.JOptionPane;
*/
public class InputDialog {
private String title, txt;
private ArrayList list;
public InputDialog(Collection col, String title, String txt) {
@ -26,14 +27,7 @@ public class InputDialog { @@ -26,14 +27,7 @@ public class InputDialog {
}
public Object show() {
return JOptionPane.showInputDialog(
null,
txt,
title,
JOptionPane.QUESTION_MESSAGE,
null,
list.toArray(),
null);
return JOptionPane.showInputDialog(null, txt, title, JOptionPane.QUESTION_MESSAGE, null, list.toArray(), null);
}
}

19
src/de/memtext/dlg/LoginDlg.java

@ -11,8 +11,9 @@ import de.memtext.widgets.MultilineEditPanel; @@ -11,8 +11,9 @@ import de.memtext.widgets.MultilineEditPanel;
*/
public class LoginDlg extends OkCancelDlg {
private LabeledTextField lUser = new LabeledTextField("Kennung", 15);
private LabeledPasswordField lPass =
new LabeledPasswordField("Passwort", 15);
private LabeledPasswordField lPass = new LabeledPasswordField("Passwort", 15);
public LoginDlg(JFrame frame, String title) {
super(frame, title, true);
initdlg();
@ -26,23 +27,28 @@ public class LoginDlg extends OkCancelDlg { @@ -26,23 +27,28 @@ public class LoginDlg extends OkCancelDlg {
this.pack();
}
@Override
protected void performOk() {
this.hide();
}
public void setUsername(String username)
{
public void setUsername(String username) {
lUser.setValue(username);
}
public void setPassword(String password)
{
public void setPassword(String password) {
lPass.setValue(password);
}
@Override
protected void performCancel() {
this.hide();
}
public String getUsername() {
return lUser.getValue().toString();
}
/**
* can be returned only once, cleared for security reasons
* afterwards
@ -58,6 +64,7 @@ public class LoginDlg extends OkCancelDlg { @@ -58,6 +64,7 @@ public class LoginDlg extends OkCancelDlg {
*/
return lPass.getValue().toString();
}
public static void main(String args[]) {
LoginDlg d = new LoginDlg(null, "asdf");
d.show();

35
src/de/memtext/dlg/NodeSelectionDlg.java

@ -19,75 +19,89 @@ import de.memtext.util.WindowUtils; @@ -19,75 +19,89 @@ import de.memtext.util.WindowUtils;
*/
public class NodeSelectionDlg extends OkCancelClearDlg {
private JTree tree;
private Object selectedNode = null;
private String title;
public NodeSelectionDlg(Frame owner, String title, JTree tree) {
super(owner, title);
this.tree = tree;
this.title = title;
this.setCenter(new JScrollPane(tree));
selectedNode = null;
if (tree.getLastSelectedPathComponent() != null)
selectedNode = (TreeNode) tree.getLastSelectedPathComponent();
if (tree.getLastSelectedPathComponent() != null) selectedNode = (TreeNode) tree.getLastSelectedPathComponent();
this.pack();
WindowUtils.center(this);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
exit();
}
});
}
/**
* called if window is closed, does nothing by default,
* subclasses can override
*
*/
@Override
protected void exit() {
}
public NodeSelectionDlg(
Frame owner,
String title,
DefaultTreeModel treeModel) {
public NodeSelectionDlg(Frame owner, String title, DefaultTreeModel treeModel) {
this(owner, title, new JTree(treeModel));
}
public NodeSelectionDlg(Frame owner, String title, TreeNode node) {
this(owner, title, new JTree(node));
}
/**
* can be overriden by subclasses to perform a check if
* the selected node is OK
* @return
*/
protected boolean isSelectedNodeOk(TreeNode testme)
{
protected boolean isSelectedNodeOk(TreeNode testme) {
return true;
}
@Override
protected void performOk() {
if (!isSelectedNodeOk((TreeNode) tree.getLastSelectedPathComponent())) return;
selectedNode = tree.getLastSelectedPathComponent();
this.setVisible(false);
}
@Override
protected void performCancel() {
this.setVisible(false);
}
public TreeNode getSelectedNode() {
return selectedNode == null ? null : (TreeNode) selectedNode;
}
@Override
protected void performClear() {
selectedNode = null;
tree.clearSelection();
this.setVisible(false);
}
@Override
public void setSize(Dimension dim) {
super.setSize(dim);
WindowUtils.center(this);
}
@Override
public void setSize(int x, int y) {
super.setSize(x, y);
WindowUtils.center(this);
}
public static void main(String a[]) {
NodeSelectionDlg t = new NodeSelectionDlg(null, "adsf", new JTree());
t.pack();
@ -96,16 +110,21 @@ public class NodeSelectionDlg extends OkCancelClearDlg { @@ -96,16 +110,21 @@ public class NodeSelectionDlg extends OkCancelClearDlg {
t.show();
System.out.println(t.getSelectedNode());
}
public void setNode(TreeNode node) {
tree.setModel(new DefaultTreeModel(node));
selectedNode = null;
}
public void setCellRenderer(TreeCellRenderer renderer) {
tree.setCellRenderer(renderer);
}
@Override
public String getTitle() {
return title;
}
public String getInfoText() {
return title;
}

12
src/de/memtext/dlg/ObjectCheckBoxDlg.java

@ -8,15 +8,16 @@ import java.util.List; @@ -8,15 +8,16 @@ import java.util.List;
import javax.swing.JScrollPane;
import de.memtext.util.WindowUtils;
import de.memtext.widgets.ObjectCheckBox;
import de.memtext.widgets.VerticalBox;
import de.memtext.util.WindowUtils;
public class ObjectCheckBoxDlg extends OkCancelDlg {
private List boxList = new LinkedList();
private List selectedObjectsList;
public ObjectCheckBoxDlg(Frame frame, String title, List itemList,boolean selected)
throws HeadlessException {
public ObjectCheckBoxDlg(Frame frame, String title, List itemList, boolean selected) throws HeadlessException {
super(frame, title);
VerticalBox vbox = new VerticalBox();
for (Iterator it = itemList.iterator(); it.hasNext();) {
@ -30,16 +31,17 @@ public class ObjectCheckBoxDlg extends OkCancelDlg { @@ -30,16 +31,17 @@ public class ObjectCheckBoxDlg extends OkCancelDlg {
WindowUtils.center(this);
}
@Override
protected void performOk() {
selectedObjectsList = new LinkedList();
for (Iterator it = boxList.iterator(); it.hasNext();) {
ObjectCheckBox element = (ObjectCheckBox) it.next();
if (element.isSelected())
selectedObjectsList.add(element.getObject());
if (element.isSelected()) selectedObjectsList.add(element.getObject());
}
this.hide();
}
@Override
protected void performCancel() {
selectedObjectsList = new LinkedList();
this.hide();

18
src/de/memtext/dlg/OkCancelClearDlg.java

@ -18,19 +18,18 @@ import javax.swing.JLabel; @@ -18,19 +18,18 @@ import javax.swing.JLabel;
getContentPane().setLayout(new BorderLayout()) or something like that,
because that will cause southPanel to disappear
*/
public abstract class OkCancelClearDlg
extends OkCancelDlg
{
public abstract class OkCancelClearDlg extends OkCancelDlg {
private boolean wasClearSelected;
protected JButton btnClear = new JButton("Leeren");
/**
* Constructor for OkCancelClearDlg.
* @param arg0
* @param arg1
* @throws HeadlessException
*/
public OkCancelClearDlg(Frame arg0, String title)
throws HeadlessException {
public OkCancelClearDlg(Frame arg0, String title) throws HeadlessException {
super(arg0, title, true);
initOkCancelClearDlg();
}
@ -39,6 +38,8 @@ public abstract class OkCancelClearDlg @@ -39,6 +38,8 @@ public abstract class OkCancelClearDlg
btnClear.setActionCommand("Clear");
btnClear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
wasOkSelected = false;
wasClearSelected = true;
@ -47,19 +48,26 @@ public abstract class OkCancelClearDlg @@ -47,19 +48,26 @@ public abstract class OkCancelClearDlg
});
addAfterCancel(btnClear);
}
public boolean wasClearSelected() {
return wasClearSelected;
}
protected abstract void performClear();
public static void main(String[] args) {
OkCancelClearDlg dlg = new OkCancelClearDlg(new JFrame(), "test") {
@Override
protected void performOk() {
}
@Override
protected void performCancel() {
}
@Override
protected void performClear() {
}
};

39
src/de/memtext/dlg/OkCancelDlg.java

@ -23,12 +23,13 @@ import de.memtext.widgets.VerticalBox; @@ -23,12 +23,13 @@ import de.memtext.widgets.VerticalBox;
getContentPane().setLayout(new BorderLayout()) or something like that,
because that will cause southPanel to disappear
*/
public abstract class OkCancelDlg
extends DialogWithExit
{
public abstract class OkCancelDlg extends DialogWithExit {
private OkCancelPanel pOkCancel;
private HorizontalBox boxAboverOkCancel = new HorizontalBox();
protected boolean wasOkSelected, wasCancelSelected;
public OkCancelDlg(Frame owner, String title, boolean isModal) {
super(owner, title, isModal);
initOkCancelDlg();
@ -76,8 +77,9 @@ public abstract class OkCancelDlg @@ -76,8 +77,9 @@ public abstract class OkCancelDlg
this.getContentPane().add(pSouth, BorderLayout.SOUTH);
pOkCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
@Override
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if (cmd.equals("OK")) {
wasOkSelected = true;
@ -94,6 +96,7 @@ public abstract class OkCancelDlg @@ -94,6 +96,7 @@ public abstract class OkCancelDlg
});
this.getRootPane().setDefaultButton(pOkCancel.getBtnOk());
}
public void addAboveOK(JComponent comp) {
boxAboverOkCancel.add(comp);
}
@ -101,51 +104,48 @@ public abstract class OkCancelDlg @@ -101,51 +104,48 @@ public abstract class OkCancelDlg
public boolean wasOkSelected() {
return wasOkSelected;
}
public boolean wasCancelSelected() {
return wasCancelSelected;
}
/**
* subclasses must implement this method and specify commands
* to be executed when OK was clicked
*/
protected abstract void performOk();
/**
* subclasses must implement this method and specify commands
* to be executed when Cancel was clicked
*
*/
protected abstract void performCancel();
/**
* Adds a Component before the OK button
* @param comp
*/
public void addBeforeOK(JComponent comp) {
int pos =
de.memtext.util.ComponentUtils.getPositionOnComponent(
pOkCancel.getBtnOk(),
pOkCancel);
int pos = de.memtext.util.ComponentUtils.getPositionOnComponent(pOkCancel.getBtnOk(), pOkCancel);
pOkCancel.add(comp, pos);
}
/**
* Adds a component right of the OK Button
* @param comp
*/
public void addAfterOK(JComponent comp) {
int pos =
de.memtext.util.ComponentUtils.getPositionOnComponent(
pOkCancel.getBtnOk(),
pOkCancel);
int pos = de.memtext.util.ComponentUtils.getPositionOnComponent(pOkCancel.getBtnOk(), pOkCancel);
pOkCancel.add(comp, pos + 1);
}
/**
* Adds a component right of the Cancel Button
* @param comp
*/
public void addAfterCancel(JComponent comp) {
int pos =
de.memtext.util.ComponentUtils.getPositionOnComponent(
pOkCancel.getBtnCancel(),
pOkCancel);
int pos = de.memtext.util.ComponentUtils.getPositionOnComponent(pOkCancel.getBtnCancel(), pOkCancel);
pOkCancel.add(comp, pos + 1);
}
/* class OneTimeInitContentPane extends Container {
@ -167,12 +167,15 @@ public abstract class OkCancelDlg @@ -167,12 +167,15 @@ public abstract class OkCancelDlg
public void setOkVisible(boolean b) {
pOkCancel.setOkVisible(b);
}
public void setCancelVisible(boolean b) {
pOkCancel.setCancelVisible(b);
}
public boolean requestFocusForOK() {
return pOkCancel.getBtnOk().requestFocusInWindow();
}
public void setOkBold(boolean b) {
pOkCancel.setOkBold(b);
}
@ -184,9 +187,11 @@ public abstract class OkCancelDlg @@ -184,9 +187,11 @@ public abstract class OkCancelDlg
public static void main(String[] args) {
OkCancelDlg dlg = new OkCancelDlg(new JFrame(), "test") {
@Override
protected void performOk() {
}
@Override
protected void performCancel() {
}
};

5
src/de/memtext/dlg/OkCancelPanel.java

@ -11,6 +11,7 @@ A Panel with an OK and a Cancel button. @@ -11,6 +11,7 @@ A Panel with an OK and a Cancel button.
*/
public class OkCancelPanel extends JPanel {
protected JButton btnOk, btnCancel;
public OkCancelPanel() {
btnOk = new JButton("OK");
btnCancel = new JButton("Abbrechen");
@ -19,6 +20,7 @@ public class OkCancelPanel extends JPanel { @@ -19,6 +20,7 @@ public class OkCancelPanel extends JPanel {
add(btnCancel);
}
public void addActionListener(ActionListener al) {
btnOk.addActionListener(al);
btnCancel.addActionListener(al);
@ -39,12 +41,15 @@ public class OkCancelPanel extends JPanel { @@ -39,12 +41,15 @@ public class OkCancelPanel extends JPanel {
public JButton getBtnOk() {
return btnOk;
}
public void setOkVisible(boolean b) {
btnOk.setVisible(b);
}
public void setCancelVisible(boolean b) {
btnCancel.setVisible(b);
}
public void setOkBold(boolean b) {
Font f = btnOk.getFont();
if (b)

23
src/de/memtext/dlg/OkDlg.java

@ -11,6 +11,7 @@ import java.awt.event.ActionListener; @@ -11,6 +11,7 @@ import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
/**
* Dialog which can only be closed by clicking OK.
*
@ -22,6 +23,7 @@ import javax.swing.JPanel; @@ -22,6 +23,7 @@ import javax.swing.JPanel;
public class OkDlg extends DialogWithExit {
private JPanel psouth = new JPanel();
protected JButton ok = new JButton("OK");
/**
@ -33,6 +35,7 @@ public class OkDlg extends DialogWithExit { @@ -33,6 +35,7 @@ public class OkDlg extends DialogWithExit {
super(owner, true);
initSouth();
}
public OkDlg(Frame owner, String title, boolean isModal) {
super(owner, title, isModal);
initSouth();
@ -45,8 +48,7 @@ public class OkDlg extends DialogWithExit { @@ -45,8 +48,7 @@ public class OkDlg extends DialogWithExit {
}
public JButton getOkBtn()
{
public JButton getOkBtn() {
return ok;
}
@ -65,8 +67,9 @@ public class OkDlg extends DialogWithExit { @@ -65,8 +67,9 @@ public class OkDlg extends DialogWithExit {
private void initSouth() {
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
@Override
public void actionPerformed(ActionEvent ae) {
performOk();
}
});
@ -82,23 +85,23 @@ public class OkDlg extends DialogWithExit { @@ -82,23 +85,23 @@ public class OkDlg extends DialogWithExit {
public void addBeforeOK(JComponent comp) {
int pos =
de.memtext.util.ComponentUtils.getPositionOnComponent(ok, psouth);
int pos = de.memtext.util.ComponentUtils.getPositionOnComponent(ok, psouth);
psouth.add(comp, pos);
}
public void addAfterOK(JComponent comp) {
int pos =
de.memtext.util.ComponentUtils.getPositionOnComponent(ok, psouth);
int pos = de.memtext.util.ComponentUtils.getPositionOnComponent(ok, psouth);
psouth.add(comp, pos + 1);
}
/**
* subclasses can override this method and specify commands
* to be executed when OK was clicked
*/
protected void performOk()
{
protected void performOk() {
this.hide();
}
public static void main(String args[]) {
OkDlg d = new OkDlg(new javax.swing.JFrame());
d.show();

28
src/de/memtext/dlg/OkDoneDlg.java

@ -66,8 +66,7 @@ public abstract class OkDoneDlg extends DialogWithExit { @@ -66,8 +66,7 @@ public abstract class OkDoneDlg extends DialogWithExit {
* @param arg2
* @throws HeadlessException
*/
public OkDoneDlg(Frame arg0, String arg1, boolean arg2)
throws HeadlessException {
public OkDoneDlg(Frame arg0, String arg1, boolean arg2) throws HeadlessException {
super(arg0, arg1, arg2);
initSouth();
}
@ -79,11 +78,7 @@ public abstract class OkDoneDlg extends DialogWithExit { @@ -79,11 +78,7 @@ public abstract class OkDoneDlg extends DialogWithExit {
* @param arg2
* @param arg3
*/
public OkDoneDlg(
Frame arg0,
String arg1,
boolean arg2,
GraphicsConfiguration arg3) {
public OkDoneDlg(Frame arg0, String arg1, boolean arg2, GraphicsConfiguration arg3) {
super(arg0, arg1, arg2, arg3);
initSouth();
}
@ -127,8 +122,7 @@ public abstract class OkDoneDlg extends DialogWithExit { @@ -127,8 +122,7 @@ public abstract class OkDoneDlg extends DialogWithExit {
* @param arg2
* @throws HeadlessException
*/
public OkDoneDlg(Dialog arg0, String arg1, boolean arg2)
throws HeadlessException {
public OkDoneDlg(Dialog arg0, String arg1, boolean arg2) throws HeadlessException {
super(arg0, arg1, arg2);
initSouth();
}
@ -141,12 +135,7 @@ public abstract class OkDoneDlg extends DialogWithExit { @@ -141,12 +135,7 @@ public abstract class OkDoneDlg extends DialogWithExit {
* @param arg3
* @throws HeadlessException
*/
public OkDoneDlg(
Dialog arg0,
String arg1,
boolean arg2,
GraphicsConfiguration arg3)
throws HeadlessException {
public OkDoneDlg(Dialog arg0, String arg1, boolean arg2, GraphicsConfiguration arg3) throws HeadlessException {
super(arg0, arg1, arg2, arg3);
initSouth();
}
@ -156,8 +145,9 @@ public abstract class OkDoneDlg extends DialogWithExit { @@ -156,8 +145,9 @@ public abstract class OkDoneDlg extends DialogWithExit {
Container cp = this.getContentPane();
cp.add(ocp, BorderLayout.SOUTH);
ocp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
@Override
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if (cmd.equals("OK")) {
performOk();
@ -167,7 +157,8 @@ public abstract class OkDoneDlg extends DialogWithExit { @@ -167,7 +157,8 @@ public abstract class OkDoneDlg extends DialogWithExit {
performDone();
}
}
});;
});
;
}
@ -176,6 +167,7 @@ public abstract class OkDoneDlg extends DialogWithExit { @@ -176,6 +167,7 @@ public abstract class OkDoneDlg extends DialogWithExit {
* to be executed when OK was clicked
*/
protected abstract void performOk();
/**
* subclasses must implement this method and specify commands
* to be executed when DONE was clicked

8
src/de/memtext/dlg/OkDonePanel.java

@ -15,15 +15,15 @@ import javax.swing.JPanel; @@ -15,15 +15,15 @@ import javax.swing.JPanel;
*/
public class OkDonePanel extends JPanel {
JButton btnOk, btnDone;
public OkDonePanel()
{
public OkDonePanel() {
btnOk = new JButton("OK");
btnDone = new JButton("Fertig");
add(btnOk);
add(btnDone);
}
public void addActionListener(ActionListener al)
{
public void addActionListener(ActionListener al) {
btnOk.addActionListener(al);
btnDone.addActionListener(al);
}

58
src/de/memtext/dlg/PasswdChangeDlg.java

@ -19,17 +19,29 @@ import de.memtext.widgets.WarningMessage; @@ -19,17 +19,29 @@ import de.memtext.widgets.WarningMessage;
public abstract class PasswdChangeDlg extends OkCancelDlg {
private JLabel lblInfoDummy = new JLabel();
private NewPasswordChecker newPasswordChecker;
private boolean isCheckOldPasswdWanted = true, isNewPasswordRequired = true;
private JTextField usernameField = new JTextField(20);
private KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
private JLabel lblInfo = new JLabel();
private JLabel lbl0 = new JLabel("Username:", JLabel.RIGHT);
private JLabel lbl1 = new JLabel("altes Passwort:", JLabel.RIGHT);
private JPasswordField oldpasswField = new JPasswordField(30);
private JLabel lbl2 = new JLabel("neues Passwort:", JLabel.RIGHT);
private JPasswordField newpasswField = new JPasswordField(30);
private JLabel lbl3 = new JLabel("wiederholen:", JLabel.RIGHT);
private JPasswordField newpasswField2 = new JPasswordField(30);
public PasswdChangeDlg(Frame frame, String title) {
@ -65,68 +77,63 @@ public abstract class PasswdChangeDlg extends OkCancelDlg { @@ -65,68 +77,63 @@ public abstract class PasswdChangeDlg extends OkCancelDlg {
this.pack();
WindowUtils.center(this);
}
public void setNewPasswordChecker(NewPasswordChecker newPasswordChecker)
{
public void setNewPasswordChecker(NewPasswordChecker newPasswordChecker) {
this.newPasswordChecker = newPasswordChecker;
}
public void setUsername(String username) {
usernameField.setText(username);
}
public void clear() {
usernameField.setText("");
oldpasswField.setText("");
newpasswField.setText("");
newpasswField2.setText("");
}
protected abstract boolean isOldPasswordOK(String username, String passwd);
/**
* wenn OK geklickt wird wird automatisch geprüft ob die Länge des neuen
* Passwort passt und beide gleich sind
*/
@Override
protected final void performOk() {
String new1 = new String(newpasswField.getPassword());
if (new1==null||new1.length()<4 )
{
WarningMessage.show(this,
"Das neue Passwort ist zu kurz.",
"Achtung");
if (new1 == null || new1.length() < 4) {
WarningMessage.show(this, "Das neue Passwort ist zu kurz.", "Achtung");
return;
}
String new2 = new String(newpasswField2.getPassword());
String oldPassword = new String(oldpasswField.getPassword());
if (!new1.equals(new2)) {
WarningMessage.show(this,
"Die beiden neuen Passwörter stimmen nicht überein",
"Achtung");
WarningMessage.show(this, "Die beiden neuen Passwörter stimmen nicht überein", "Achtung");
return;
}
String faults = null;
if (newPasswordChecker != null) faults = newPasswordChecker.checkForFaults(getUsername(), new String(newpasswField.getPassword()));
if (faults != null) {
WarningMessage.show(this,
faults,
"Achtung");
WarningMessage.show(this, faults, "Achtung");
return;
}
if (isNewPasswordRequired&&new1.equals(oldPassword))
{
if (isNewPasswordRequired && new1.equals(oldPassword)) {
WarningMessage.show(this, "Sie müssen ein neues Passwort eingeben", "Achtung");
return;
}
if (isCheckOldPasswdWanted
&& !isOldPasswordOK(usernameField.getText(),
oldPassword)) {
if (isCheckOldPasswdWanted && !isOldPasswordOK(usernameField.getText(), oldPassword)) {
WarningMessage.show(this, "Das alte Passwort stimmt nicht", "Achtung");
return;
}
this.hide();
}
@Override
protected void performCancel() {
this.hide();
}
@ -135,18 +142,23 @@ public abstract class PasswdChangeDlg extends OkCancelDlg { @@ -135,18 +142,23 @@ public abstract class PasswdChangeDlg extends OkCancelDlg {
public void setUsernameFieldEnabled(boolean b) {
usernameField.setEnabled(b);
}
public void setOldPassword(String passw) {
oldpasswField.setText(passw);
}
public String getUsername() {
return usernameField.getText();
}
public String getOldPasswd() {
return new String(oldpasswField.getPassword());
}
public String getNewPasswd() {
return new String(newpasswField.getPassword());
}
public boolean isCheckOldPasswdWanted() {
return isCheckOldPasswdWanted;
}
@ -156,6 +168,7 @@ public abstract class PasswdChangeDlg extends OkCancelDlg { @@ -156,6 +168,7 @@ public abstract class PasswdChangeDlg extends OkCancelDlg {
lbl1.setVisible(b);
oldpasswField.setVisible(b);
}
public void setInfoLabel(String txt) {
lblInfo.setVisible(true);
lblInfo.setText(txt);
@ -169,14 +182,15 @@ public abstract class PasswdChangeDlg extends OkCancelDlg { @@ -169,14 +182,15 @@ public abstract class PasswdChangeDlg extends OkCancelDlg {
public void setNewPasswordRequired(boolean b) {
isNewPasswordRequired = b;
}
public static void main(String a[])
{
public static void main(String a[]) {
PasswdChangeDlg dlg = new PasswdChangeDlg(null, "dummy") {
@Override
protected boolean isOldPasswordOK(String username, String passwd) {
return false;
}}
;
}
};
dlg.setInfoLabel("bitte ändern");
dlg.show();
}

122
src/de/memtext/hbt/AbstractAriel.java

@ -1,122 +0,0 @@ @@ -1,122 +0,0 @@
package de.memtext.hbt;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.search.FlagTerm;
import de.memtext.util.LogUtils;
import de.superx.servlet.SxMail;
import de.superx.servlet.SxPool;
public abstract class AbstractAriel extends Thread {
// this is defined as private static method to use as little memory as possible,
// it would be neglectable in moder computers to create it every time the method
// runs, GarbargeCollection would easily do the job
// yet I define it that way out of respect for the programmers of beginning in
// the 50ies/60ies or whenever
// private static FlagTerm flagUnseen = new FlagTerm(new Flags(Flags.Flag.SEEN), true); // ja ich weiß, flagUnseen
Flags seen = new Flags(Flags.Flag.RECENT);
private static FlagTerm flagUnseen = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
static Flags flagsContainingOnlySeen=new Flags(Flags.Flag.SEEN);
protected Logger logger=null;
// wird bisher nicht
// benötigt, aber ist doch
// klar, dass ich das gleich
// nutzen will, dass nervt,
// dass die Meldung jetzt
// kommt
private boolean isActive = true;
private int interval = 10;
protected SxMail sxmail;
public AbstractAriel() {
super();
}
public AbstractAriel(Runnable target) {
super(target);
}
public AbstractAriel(String name) {
super(name);
}
public AbstractAriel(ThreadGroup group, Runnable target) {
super(group, target);
}
public AbstractAriel(ThreadGroup group, String name) {
super(group, name);
}
public AbstractAriel(Runnable target, String name) {
super(target, name);
}
public AbstractAriel(ThreadGroup group, Runnable target, String name) {
super(group, target, name);
}
public AbstractAriel(ThreadGroup group, Runnable target, String name, long stackSize) {
super(group, target, name, stackSize);
}
public void initLogging()throws IOException
{
String filename=SxPool.getLogDir() + "/superx_"
+ getArielName() + ".log";
LogUtils.initRawFile("superx_" + getArielName(), filename, 20000, 1, true, true);
System.out.println("Superx Mail logging in "+filename);
logger=Logger.getLogger("superx_" + getArielName());
Level lev = Level.SEVERE;
logger.setLevel(lev);
}
public String getArielName()
{
return "mail";
}
public void run() {
while (isActive) {
try {
Thread.sleep(interval * 1000);
} catch (InterruptedException e) {
// e.printStackTrace();
}
try {
logger.log(Level.INFO,"SuperX is checking mails for new heartbeats...");
Folder inbox=sxmail.getInbox();
//if (inbox.hasNewMessages())
processNewMessages(inbox.getMessages()); // processed messages will be deleted -> don#t need inbox.search(flagUnseen)); // former first attempt was : processNewMessages(inbox.getMessages()); // should be in differnt colour (<- British English)
sxmail.closeInbox(); //deletes marked mails
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
abstract void processNewMessages(Message[] messages) throws MessagingException, IOException, SQLException;
public void setActive(boolean isActive) {
this.isActive=isActive;
}
}

96
src/de/memtext/hbt/Checker.java

@ -1,96 +0,0 @@ @@ -1,96 +0,0 @@
package de.memtext.hbt;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Checker {
public static void check(Session emailSession, String user, String password)
throws MessagingException, IOException {
// create the POP3 store object and connect with the pop server
// pop3s wichtig -> vermutlich secure
Store store = emailSession.getStore("pop3s");
store.connect(emailSession.getProperty("mail.pop3.host"), user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// messages werden geholt, können nur ausgelesen werden, wenn Folder noch open
// ist!
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
// close the store and folder objects
emailFolder.close(false);
store.close();
}
private static void send(Session emailSession, String user, String recipient, String subject, String text,
String password) throws AddressException, MessagingException {
MimeMessage replyMessage = new MimeMessage(emailSession);
// replyMessage = (MimeMessage) message.reply(false);
replyMessage.setFrom(new InternetAddress(user));
replyMessage.setRecipients(Message.RecipientType.TO, recipient);
replyMessage.setSubject(subject);
replyMessage.setText(text);
Transport t = emailSession.getTransport("smtp");
t.connect(user, password);
t.sendMessage(replyMessage, replyMessage.getAllRecipients());
System.out.println("Message sent...");
}
private static Session initSession(String pophost, String smtphost) {
Properties properties = new Properties();
properties.put("mail.pop3.host", pophost);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", smtphost);
properties.put("mail.smtp.port", "25");
return Session.getDefaultInstance(properties);
}
public static void main(String[] args) {
Session session = initSession("pop3.strato.de", "smtp.strato.de");
String username = "heartbeat@mbisping.de";
String password = "$Anfang1200";
try {
check(session, username, password);
send(session, username, "danielq@memtext.de", "From Düsseldorf with fun...", "This is the memtext's first digitial 'heartbeat' :-)\n send via java mail - \nThanks and see you around :-)",
password);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

293
src/de/memtext/hbt/NewHeartBeatAriel.java

@ -1,293 +0,0 @@ @@ -1,293 +0,0 @@
package de.memtext.hbt;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.AddressException;
import javax.mail.internet.MimeMessage;
import clover.com.atlassian.extras.common.org.springframework.util.StringUtils;
import de.memtext.db.DbUtils;
import de.memtext.util.FileUtils;
import de.memtext.util.MailUtils;
import de.superx.servlet.SuperXManager;
import de.superx.servlet.SxMail;
import de.superx.servlet.SxPools;
public class NewHeartBeatAriel extends AbstractAriel {
private static final Pattern pHbtId = Pattern.compile("@hbt:\\d*@");
public NewHeartBeatAriel(SxMail sxmail) throws IOException {
this.sxmail = sxmail;
initLogging();
}
void processNewMessages(Message newMessages[]) throws MessagingException, IOException, SQLException {
logger.log(Level.INFO," found " + newMessages.length + " new messages");
for (int i = 0, n = newMessages.length; i < n; i++) {
Message aNewMessage = newMessages[i];
String content = MailUtils.getContent(aNewMessage);
if (content.indexOf("@hbt:") == -1)
createNewHeartBeat(aNewMessage, content);
else
appendToHeartBeat(aNewMessage, content);
// had thought setting via inbox nessary, but that's only the preferred way to
// set flags for group of messages since some mail implementations by have
// optimized support for groups of messages
// inbox.setFlags(new Message[] {message}, , true);
// message.setFlags(flagsContainingOnlySeen, true);
// unseen wäre schöner, mailapi.jar aktualisieren bei HIS Antrag
// nötig,vielleicht klappt mit delete
aNewMessage.setFlag(Flags.Flag.DELETED, true); // AbstractAriel.run ruft sxmail.closeInbox() auf mit
// Anweisung zu löschen
// sorry to bother you, Garbage collector , need message only to times, hey or
// doesn't that matter anyway since only a simple reference (like in good old
// C), but clearer/easier to read if line Message message=.. was superfolous
}
}
private void appendToHeartBeat(Message message, String content)
throws SQLException, IOException, MessagingException {
StringBuffer result = new StringBuffer();
int hbtTid = -1;
Connection con = SxPools.getConnection(sxmail.getMandantenID());
Statement stm = con.createStatement();
boolean isHbtFoundInDb = false;
String feedbackSubject = "";
Matcher m = pHbtId.matcher(content);
boolean foundHbtTag=m.find();
if (foundHbtTag) {
String hbtIdString = content.substring(m.start() + 5, m.end() - 1);
content=content.replaceAll("@hbt:\\d*@", "");
try {
hbtTid = Integer.parseInt(hbtIdString);
if (DbUtils.getInt(con, "select count(*) from hbt_heartbeat where tid=?", hbtTid) > 0)
isHbtFoundInDb = true;
} catch (NumberFormatException e) {
result.append(" hbt:" + hbtIdString
+ " konnte nicht in integer transformiert werden, Nachricht wird zwischengespeichert");
isHbtFoundInDb = false;
}
if (isHbtFoundInDb) {
// TODO ggfs. mehrer Topics
int maxTopic = DbUtils.getInt(con, "select max(tid) from hbt_topic where hbt_id=?", hbtTid);
// int maxNote = DbUtils.getInt(stm, "select max(tid) from hbt_note where
// hbt_id=" + hbtTid + " hbt_topic_id=" + maxTopic);
int newNoteId = createNote(con, stm, hbtTid, maxTopic, message, content);
feedbackSubject = "Your new note was added to Heartbeat " + hbtTid;
result.append("Feel free to view this HeartBeat by visiting " + sxmail.getWTFAI()
+ "/edit/hbt/hbt_viewer.jsp?tid=" + hbtTid + " \n\n" + "Always at your service: \n"
+ " your HeartBeatAriel @ SuperX");
}
}
if (!foundHbtTag || !isHbtFoundInDb) {
feedbackSubject = "Sorry, target hbt found found ...";
PreparedStatement pst=con.prepareStatement("insert into hbt_tmp_note (note) values (?)");
pst.setString(1,content);
pst.execute();
pst.close();
int newNoteId=DbUtils.getInt(stm, "select max(tid) from hbt_tmp_note");
result.append("you can select the right hbt_id by visiting " + sxmail.getWTFAI()+"/servlet/SuperXmlMaske?tid=60040?note_id="+newNoteId);
}
stm.close();
con.close();
sendFeedbackEmail(feedbackSubject, result.toString(), message);
}
private void createNewHeartBeat(Message inMessage, String content)
throws SQLException, MessagingException, IOException {
int newHbtTid = performHbtInsert(inMessage, content);
String text = "Feel free to complete this heartbeat's details by visiting " + sxmail.getWTFAI()
+ "/edit/hbt/hbt_edit.jsp?tid=" + newHbtTid + " \n\n" + "Always at your service: \n"
+ " your HeartBeatAriel @ SuperX";
sendFeedbackEmail("Your new digital heartbeat has been created ...", text, inMessage);
}
/**
* Performs the creation of a new HeartBeat in the database
*
* @param message
* @return newHbtTid
* @throws SQLException
* @throws MessagingException
* @throws IOException
*/
private int performHbtInsert(Message m, String content) throws SQLException, IOException, MessagingException {
Connection con = SxPools.getConnection(sxmail.getMandantenID());
Statement stm = con.createStatement();
int newHbtTid = createHbt(con, stm, content, m.getSubject());
int newTopicId = createTopic(stm, newHbtTid);
createNote(con, stm, newHbtTid, newTopicId, m, content);
con.close();
return newHbtTid;
}
private int createHbt(Connection dbConnection, Statement stm, String content, String subject)
throws IOException, MessagingException, SQLException {
String primary_customer_id = identifyPrimaryCustomerId(dbConnection, stm, content);
String name = StringUtils.replace(subject, "'", "''");// for SQL insert
// Sql insert - fuck prepared statements, nobody hacks this, I don't give a
// shit, not worth my extra time or effort, I want to get things done now while
// having fun :-)
stm.execute("select sp_update_sequence('hbt_heartbeat')");
String insertSql = "INSERT INTO hbt_heartbeat \n" + "( primary_customer_id,name," + " created_at, \n"
+ " status \n" + ") \n" + "VALUES \n" + "( " + primary_customer_id + ",'" + name + "', "
+ " today(), \n" + " 1 \n" + ") " + "";
stm.execute(insertSql);
int newHbtTid = DbUtils.getInt(stm, "select max(tid) from hbt_heartbeat");
return newHbtTid;
}
/**
*
* Wenn im Text der weitergeleiteten Email der Absender mit @@ markiert ist,
* z.B. @@hiber@his.de@@, diesen auslesen zugehörige Organisation auslesen
*
* @param m
* @return String null oder key_apnr z.B. '1001'
* @throws IOException
* @throws MessagingException
* @throws SQLException
*/
private String identifyPrimaryCustomerId(Connection con, Statement stm, String content)
throws IOException, MessagingException, SQLException {
String result = "null";
int pos1 = content.indexOf("@@");
int pos2 = content.substring(pos1 + 2).indexOf("@@");
if (pos1 > -1 && pos2 > -1) {
String absender = content.substring(pos1 + 2);
absender = absender.substring(0, absender.lastIndexOf("@@"));
logger.log(Level.INFO," checking customer " + absender);
int userinfo_id = DbUtils.getInt(con, "select tid from userinfo where email=?", absender);
result = DbUtils.getString(stm,
"select min(ch110_institut) from user_institution where userid=" + userinfo_id);
if (result == null)
result = "null";
else
result = "'" + result + "'";
}
return result;
}
private int createTopic(Statement stm, int newHbtTid) throws SQLException {
stm.execute("select sp_update_sequence('hbt_topic')");
String insertSql = "INSERT INTO hbt_topic \n" + "( hbt_id,name, created_at)" + "VALUES (" + newHbtTid
+ ",'Start',now() )";
stm.execute(insertSql);
int newTopicId = DbUtils.getInt(stm, "select max(tid) from hbt_topic");
return newTopicId;
}
private int createNote(Connection con, Statement stm, int hbtId, int topicId, Message m, String content)
throws IOException, MessagingException, SQLException {
stm.execute("select sp_update_sequence('hbt_note')");
PreparedStatement pst = con
.prepareStatement(" INSERT INTO hbt_note (hbt_id,hbt_topic_id,note, created_at) VALUES (?,?,?,now());");
pst.setInt(1, hbtId);
pst.setInt(2, topicId);
pst.setString(3, content);
pst.execute();
pst.close();
int newNoteId = DbUtils.getInt(stm, "select max(tid) from hbt_note");
saveAttachments(stm, hbtId, topicId, newNoteId, m);
return newNoteId;
}
private void saveAttachments(Statement stm, int newHbtTid, int newTopicId, int newNoteId, Message m)
throws IOException, MessagingException, SQLException {
// List<String> attachments = new ArrayList<String>();
Object content = m.getContent();
// if (content instanceof String) return null;
if (content instanceof Multipart) {
Multipart multipart = (Multipart) content;
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart part = multipart.getBodyPart(i);
logger.log(Level.INFO,part.getFileName() + " " + part.getContentType() + " " + part.getDisposition());
if (part.getDisposition() != null && part.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
// result.addAll(getAttachments(multipart.getBodyPart(i)));
String filename = SuperXManager.getWEB_INFPfad()+"/downloads/hbt_"+newHbtTid+"_" +newNoteId+"_"+FileUtils.removeProblemChars(part.getFileName());
sxDownloadsInsert(stm, newHbtTid, newTopicId, newNoteId, filename, part.getContentType());
// javaxmail >1.4 bodyPart.saveFile(filename);
// old version
InputStream is = part.getInputStream();
File f = new File(filename);
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.close();
logger.log(Level.INFO," saving attachment " + (i++) + " as " + filename);
}
}
}
}
private void sxDownloadsInsert(Statement stm, int newHbtTid, int newTopicId, int newNoteId, String filename,
String contenttype) throws SQLException {
stm.execute("select sp_update_sequence('sx_downloads')");
String filenameShort = filename.substring(filename.indexOf(File.separator + "hbt") + 1);
String insertSQLSxDownloads = "INSERT INTO sx_downloads \n" + "( \n" + " name, \n" + " importdatum, \n"
+ " kommentar, \n" + " kommentar_url, \n" + " contenttype, \n" + " datei, \n" + " gueltig_seit, \n"
+ " gueltig_bis \n" + ") \n" + "VALUES \n" + "( \n" + " '" + filenameShort + "', \n" + " today(), \n"
+ " 'kommentar_value', \n" + " 'kommentar_url_value', \n" + " '" + contenttype + "', \n" + " '"
+ filenameShort + "', \n" + " today(), \n" + " date_val('1.1.3000') \n" + ") \n" + "";
stm.execute(insertSQLSxDownloads);
int newDownloadTid = DbUtils.getInt(stm, "select max(tid) from sx_downloads");
stm.executeUpdate("insert into hbt_attachment (hbt_id,topic_id,note_id,download_id) values (" + newHbtTid + ","
+ newTopicId + "," + newNoteId + "," + newDownloadTid + ")");
}
/**
* sendFeedBackEmail -- hier hätte ich gern automatisch newline in Zeile 60
* direkt unter createNewHeartBeat automatisch erzeugt, dann nach weiter unten
* im Quelltext verlagert, damit von der Reihenfolge in
* createNewHeartBeat(Message message) her passt
*
* @param newHbtTid : tid von neuem HeartBeat in der Datenbank
* @param inMessage
* @throws MessagingException
* @throws AddressException
*/
private void sendFeedbackEmail(String subject, String text, Message inMessage)
throws AddressException, MessagingException {
MimeMessage reply = sxmail.createMessage();
reply.setRecipients(Message.RecipientType.TO, inMessage.getFrom());
reply.setSubject(subject);
reply.setText(text);
sxmail.setMessage(reply);
logger.log(Level.INFO,"Reply message happily sent...");
}
}

1
src/de/memtext/icons/ArrowDownIcon.java

@ -3,6 +3,7 @@ package de.memtext.icons; @@ -3,6 +3,7 @@ package de.memtext.icons;
import java.awt.Graphics;
public class ArrowDownIcon extends BasicIcon {
@Override
public void myPaint(Graphics g) {
drawArrowDown(g, 6);
}

1
src/de/memtext/icons/ArrowRight.java

@ -4,6 +4,7 @@ import java.awt.Graphics; @@ -4,6 +4,7 @@ import java.awt.Graphics;
public class ArrowRight extends BasicIcon {
@Override
void myPaint(Graphics g) {
drawArrowRight(g);
}

1
src/de/memtext/icons/ArrowUpIcon.java

@ -6,6 +6,7 @@ import javax.swing.Icon; @@ -6,6 +6,7 @@ import javax.swing.Icon;
public class ArrowUpIcon extends BasicIcon implements Icon {
@Override
public void myPaint(Graphics g) {
drawArrowUp(g, 4);

14
src/de/memtext/icons/BasicIcon.java

@ -9,10 +9,13 @@ import javax.swing.JButton; @@ -9,10 +9,13 @@ import javax.swing.JButton;
public abstract class BasicIcon implements Icon {
private int iconWidth = 16, iconHeight = 16;
private Color color = Color.black;
/**
* @see javax.swing.Icon#getIconWidth()
*/
@Override
public int getIconWidth() {
return iconWidth;
}
@ -20,9 +23,12 @@ public abstract class BasicIcon implements Icon { @@ -20,9 +23,12 @@ public abstract class BasicIcon implements Icon {
/**
* @see javax.swing.Icon#getIconHeight()
*/
@Override
public int getIconHeight() {
return iconHeight;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.translate(x, y);
if (c.isEnabled())
@ -32,10 +38,11 @@ public abstract class BasicIcon implements Icon { @@ -32,10 +38,11 @@ public abstract class BasicIcon implements Icon {
myPaint(g);
g.translate(-x, -y);
}
abstract void myPaint(Graphics g);
void drawDoubleLine(Graphics g, int y) {
if (y > getIconHeight() - 2)
throw new IllegalArgumentException("can't draw that low");
if (y > getIconHeight() - 2) throw new IllegalArgumentException("can't draw that low");
g.drawLine(0, y, getIconWidth(), y);
g.drawLine(0, y + 1, getIconWidth(), y + 1);
}
@ -65,6 +72,7 @@ public abstract class BasicIcon implements Icon { @@ -65,6 +72,7 @@ public abstract class BasicIcon implements Icon {
g.drawLine(midx, y + 1, getIconWidth(), y + midy + 1);
}
void drawArrowDown(Graphics g, int y) {
int midx = (int) Math.floor(getIconWidth() / 2);
int midy = (int) Math.floor(getIconHeight() / 2);
@ -74,12 +82,14 @@ public abstract class BasicIcon implements Icon { @@ -74,12 +82,14 @@ public abstract class BasicIcon implements Icon {
g.drawLine(midx, y + midy + 1, getIconWidth(), y + 1);
}
public static void main(String[] args) {
de.memtext.widgets.MBFrame f = new de.memtext.widgets.MBFrame("test");
f.setCenter(new JButton("test", new ArrowRight()));
f.pack();
f.show();
}
public void setIconHeight(int i) {
iconHeight = i;
}

4
src/de/memtext/icons/DoubleArrowDownIcon.java

@ -4,8 +4,8 @@ import java.awt.Graphics; @@ -4,8 +4,8 @@ import java.awt.Graphics;
public class DoubleArrowDownIcon extends BasicIcon {
public void myPaint(Graphics g)
{
@Override
public void myPaint(Graphics g) {
drawArrowDown(g, 2);
drawArrowDown(g, 6);

4
src/de/memtext/icons/DoubleArrowDownLineIcon.java

@ -11,8 +11,8 @@ import java.awt.Graphics; @@ -11,8 +11,8 @@ import java.awt.Graphics;
* Window>Preferences>Java>Code Generation.
*/
public class DoubleArrowDownLineIcon extends BasicIcon {
public void myPaint(Graphics g)
{
@Override
public void myPaint(Graphics g) {
drawArrowDown(g, 0);
drawArrowDown(g, 4);
drawDoubleLine(g, getIconHeight() - 2);

4
src/de/memtext/icons/DoubleArrowUpIcon.java

@ -11,8 +11,8 @@ import java.awt.Graphics; @@ -11,8 +11,8 @@ import java.awt.Graphics;
* Window>Preferences>Java>Code Generation.
*/
public class DoubleArrowUpIcon extends BasicIcon {
public void myPaint(Graphics g)
{
@Override
public void myPaint(Graphics g) {
drawArrowUp(g, 0);
drawArrowUp(g, 4);

4
src/de/memtext/icons/DoubleArrowUpLineIcon.java

@ -11,8 +11,8 @@ import java.awt.Graphics; @@ -11,8 +11,8 @@ import java.awt.Graphics;
* Window>Preferences>Java>Code Generation.
*/
public class DoubleArrowUpLineIcon extends BasicIcon {
public void myPaint(Graphics g)
{
@Override
public void myPaint(Graphics g) {
drawDoubleLine(g, 0);
drawArrowUp(g, 2);
drawArrowUp(g, 6);

38
src/de/memtext/icons/MBStandardIcons.java

@ -10,62 +10,60 @@ import de.memtext.util.IconUtils; @@ -10,62 +10,60 @@ import de.memtext.util.IconUtils;
changed xxx
*/
public class MBStandardIcons {
private static ImageIcon indexBox,
newDoc,
copyWin,
searchWin,
viewingGlass,
table,
delete,
properties;
private static ImageIcon indexBox, newDoc, copyWin, searchWin, viewingGlass, table, delete, properties;
private static ClassLoader cl;
/**
* Constructor for StandardIcons.
*/
private MBStandardIcons() {
}
public static ImageIcon get(String name) {
return IconUtils.get("de/memtext/icons/" + name);
}
static {
MBStandardIcons s = new MBStandardIcons();
cl = s.getClass().getClassLoader();
copyWin =
new ImageIcon(cl.getResource("de/memtext/icons/copyWindows.gif"));
searchWin =
new ImageIcon(cl.getResource("de/memtext/icons/searchWindows.gif"));
viewingGlass =
new ImageIcon(cl.getResource("de/memtext/icons/viewingGlass.gif"));
copyWin = new ImageIcon(cl.getResource("de/memtext/icons/copyWindows.gif"));
searchWin = new ImageIcon(cl.getResource("de/memtext/icons/searchWindows.gif"));
viewingGlass = new ImageIcon(cl.getResource("de/memtext/icons/viewingGlass.gif"));
table = new ImageIcon(cl.getResource("de/memtext/icons/table.gif"));
newDoc = new ImageIcon(cl.getResource("de/memtext/icons/newDoc.gif"));
delete = new ImageIcon(cl.getResource("de/memtext/icons/delete.gif"));
properties =
new ImageIcon(cl.getResource("de/memtext/icons/properties.gif"));
indexBox =
new ImageIcon(cl.getResource("de/memtext/icons/indexBox.gif"));
properties = new ImageIcon(cl.getResource("de/memtext/icons/properties.gif"));
indexBox = new ImageIcon(cl.getResource("de/memtext/icons/indexBox.gif"));
}
public static ImageIcon getEntry() {
return new ImageIcon(cl.getResource("de/memtext/icons/entry.gif"));
}
public static ImageIcon getCopy() {
return copyWin;
}
public static ImageIcon getSearch() {
return searchWin;
}
public static ImageIcon getDelete() {
return delete;
}
public static ImageIcon getPrint()
{
public static ImageIcon getPrint() {
return new ImageIcon(cl.getResource("de/memtext/icons/print.gif"));
}
public static ImageIcon getProperties() {
return properties;
}
/**
* Returns the table.
* @return ImageIcon

28
src/de/memtext/lang/SingOrPluralWord.java

@ -1,28 +0,0 @@ @@ -1,28 +0,0 @@
package de.memtext.lang;
public class SingOrPluralWord {
public final static SingOrPluralWord SEIN=new SingOrPluralWord("ist","sind");
private int count;
private String singular,plural;
public SingOrPluralWord(String singular,String plural) {
this.singular=singular;
this.plural=plural;
}
public static String format(int count,String sing,String plural)
{
if (count==1) return count+" "+sing;
else
return count+" "+plural;
}
public String say(int count)
{
if (count==1) return singular;
else
return plural;
}
}
//Created on 12.12.2003 at 15:53:43

5
src/de/memtext/observ/DocumentListenerObserver.java

@ -2,26 +2,31 @@ package de.memtext.observ; @@ -2,26 +2,31 @@ package de.memtext.observ;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
/**
* A document listener that will inform an observable about changes
* in the document
*/
public class DocumentListenerObserver implements DocumentListener {
private MyObservable observable;
public DocumentListenerObserver(MyObservable observable) {
this.observable = observable;
}
@Override
public void insertUpdate(DocumentEvent e) {
observable.markChanged();
observable.notifyObservers();
}
@Override
public void removeUpdate(DocumentEvent e) {
observable.markChanged();
observable.notifyObservers();
}
@Override
public void changedUpdate(DocumentEvent e) {
observable.markChanged();
observable.notifyObservers();

39
src/de/memtext/rights/AllowableHierarchyUtil.java

@ -19,18 +19,15 @@ public class AllowableHierarchyUtil { @@ -19,18 +19,15 @@ public class AllowableHierarchyUtil {
* must also extend DefaultMutableTreeNode
*/
public static void removeUnallowedNodes(AllowableHierarchy root) {
if (!(root instanceof DefaultMutableTreeNode))
throw new IllegalArgumentException(" must be a node!");
if (!(root instanceof DefaultMutableTreeNode)) throw new IllegalArgumentException(" must be a node!");
DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) root;
boolean needAnotherRound = true, killedOne = false;
while (needAnotherRound) {
killedOne = false;
for (Enumeration en = rootNode.breadthFirstEnumeration(); en
.hasMoreElements();) {
for (Enumeration en = rootNode.breadthFirstEnumeration(); en.hasMoreElements();) {
Object o = en.nextElement();
if (o == root)
continue;
if (o == root) continue;
AllowableHierarchy ah = (AllowableHierarchy) o;
if (!ah.isAnyDescendantAllowed()) {
@ -43,8 +40,7 @@ public class AllowableHierarchyUtil { @@ -43,8 +40,7 @@ public class AllowableHierarchyUtil {
break;
}
}
if (killedOne == false)
needAnotherRound = false;
if (killedOne == false) needAnotherRound = false;
}
}
@ -52,12 +48,10 @@ public class AllowableHierarchyUtil { @@ -52,12 +48,10 @@ public class AllowableHierarchyUtil {
private static void markParentsAsNotAllowed(DefaultMutableTreeNode node) {
if (!node.isRoot() && node instanceof Allowable) {
Allowable al = null;
if (node.getParent() instanceof Allowable)
al = (Allowable) node.getParent();
if (node.getParent() instanceof Allowable) al = (Allowable) node.getParent();
al.setAllowed(false);
markParentsAsNotAllowed((DefaultMutableTreeNode) node
.getParent());
markParentsAsNotAllowed((DefaultMutableTreeNode) node.getParent());
}
}
@ -71,8 +65,7 @@ public class AllowableHierarchyUtil { @@ -71,8 +65,7 @@ public class AllowableHierarchyUtil {
* @param root
*/
public static void reorg(AllowableHierarchy root) {
if (!(root instanceof DefaultMutableTreeNode))
throw new IllegalArgumentException(" must be a node!");
if (!(root instanceof DefaultMutableTreeNode)) throw new IllegalArgumentException(" must be a node!");
DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) root;
boolean needAnotherRound = true;
List nodeList = new LinkedList();
@ -80,15 +73,12 @@ public class AllowableHierarchyUtil { @@ -80,15 +73,12 @@ public class AllowableHierarchyUtil {
nodeList.clear();
needAnotherRound = false;
for (int i = 0; i < rootNode.getChildCount(); i++) {
AllowableHierarchy ah = (AllowableHierarchy) rootNode
.getChildAt(i);
AllowableHierarchy ah = (AllowableHierarchy) rootNode.getChildAt(i);
if (!ah.isAllowed()) {
needAnotherRound = true;
((DefaultMutableTreeNode) ah).removeFromParent();
for (int i2 = 0; i2 < ((DefaultMutableTreeNode) ah)
.getChildCount(); i2++)
nodeList.add(((DefaultMutableTreeNode) ah)
.getChildAt(i2));
for (int i2 = 0; i2 < ((DefaultMutableTreeNode) ah).getChildCount(); i2++)
nodeList.add(((DefaultMutableTreeNode) ah).getChildAt(i2));
}
}
for (Iterator it = nodeList.iterator(); it.hasNext();) {
@ -98,17 +88,14 @@ public class AllowableHierarchyUtil { @@ -98,17 +88,14 @@ public class AllowableHierarchyUtil {
}
public static void markNotAllowedNodes(AllowableHierarchy root, String mark) {
if (!(root instanceof DefaultMutableTreeNode))
throw new IllegalArgumentException(" must be a node!");
if (!(root instanceof DefaultMutableTreeNode)) throw new IllegalArgumentException(" must be a node!");
DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) root;
int i = 0;
for (Enumeration en = rootNode.breadthFirstEnumeration(); en
.hasMoreElements();) {
for (Enumeration en = rootNode.breadthFirstEnumeration(); en.hasMoreElements();) {
AllowableHierarchy ah = (AllowableHierarchy) en.nextElement();
if (!ah.isAllowed()) {
TreeEntryI te = (TreeEntryI) ah;
if (!te.getName().endsWith(mark))
te.setName(te.getName() + mark);
if (!te.getName().endsWith(mark)) te.setName(te.getName() + mark);
}
}
}

30
src/de/memtext/rights/NewPasswordChecker.java

@ -6,12 +6,13 @@ import de.memtext.util.PWChecker; @@ -6,12 +6,13 @@ import de.memtext.util.PWChecker;
public class NewPasswordChecker implements Serializable {
private int minimumLength = 0;
private boolean isLowerAndUpperCaseNeeded = false;
private boolean isNumberNeeded = false;
public NewPasswordChecker(int minLaenge, int grossklein,int ziffernoetig)
{
public NewPasswordChecker(int minLaenge, int grossklein, int ziffernoetig) {
this.minimumLength = minLaenge;
isLowerAndUpperCaseNeeded = grossklein == 1;
isNumberNeeded = ziffernoetig == 1;
@ -22,27 +23,20 @@ public NewPasswordChecker(int minLaenge, int grossklein,int ziffernoetig) @@ -22,27 +23,20 @@ public NewPasswordChecker(int minLaenge, int grossklein,int ziffernoetig)
* @param check
* @return null wenn alles OK
*/
public String checkForFaults(String username,String check)
{
public String checkForFaults(String username, String check) {
StringBuffer result = new StringBuffer();
if (check==null)
{
if (check == null) {
result.append("Es wurde kein Passwort übermittelt.");
}
else
{
if (check.equals(username))
result.append("Passwort darf nicht gleich Benutzername sein");
if (minimumLength>0&&check.length()<minimumLength)
result.append("Passwort ist zu kurz (min. "+minimumLength+" Zeichen).");
if (isLowerAndUpperCaseNeeded&!PWChecker.hasLowerAndUpperCase(check))
result.append("\nPasswort muss Groß- und Kleinbuchstaben enthalten.");
if (isNumberNeeded&&!PWChecker.hasNumbers(check))
result.append("\nPasswort muss mindestens eine Ziffer enthalten.");
} else {
if (check.equals(username)) result.append("Passwort darf nicht gleich Benutzername sein");
if (minimumLength > 0 && check.length() < minimumLength) result.append("Passwort ist zu kurz (min. " + minimumLength + " Zeichen).");
if (isLowerAndUpperCaseNeeded & !PWChecker.hasLowerAndUpperCase(check)) result.append("\nPasswort muss Groß- und Kleinbuchstaben enthalten.");
if (isNumberNeeded && !PWChecker.hasNumbers(check)) result.append("\nPasswort muss mindestens eine Ziffer enthalten.");
// if (oldShas.contains(CryptUtils.encodeSHA(check+CryptUtils.geheimnis1)))
// result.append("Das Password wurde schon zuvor verwendet, bitte neues Password benutzen.");
}
if (result.length()>1) return result.toString();
if (result.length() > 1)
return result.toString();
else
return null;
}

116
src/de/memtext/rights/Rights.java

@ -1,21 +1,28 @@ @@ -1,21 +1,28 @@
package de.memtext.rights;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import de.memtext.util.EqualsUtil;
import de.superx.common.OrgUnit;
import de.superx.common.OrgUnitMapping;
import de.superx.servlet.SxPools;
/**
* A class for managing rights. In particular c
* A class for managing rights.
*/
public class Rights implements Serializable {
private static final long serialVersionUID = 1;
private static final long serialVersionUID = 2;
private boolean isAdmin = false;
private boolean hasAllRights;
private Collection keyColl = new TreeSet();
private Set<RightsKeyEntry> allowedRightKeyEntries = new TreeSet<RightsKeyEntry>();
public Rights() {
@ -35,49 +42,38 @@ public class Rights implements Serializable { @@ -35,49 +42,38 @@ public class Rights implements Serializable {
}
public void addAllowed(RightsKeyEntry rke) {
keyColl.add(rke);
allowedRightKeyEntries.add(rke);
}
public void clear() {
keyColl.clear();
this.isAdmin = false;
hasAllRights = false;
allowedRightKeyEntries.clear();
}
public boolean isEmpty() {
return keyColl.isEmpty();
return allowedRightKeyEntries.isEmpty();
}
public boolean hasNoRights() {
return !isAdmin && !hasAllRights && isEmpty();
}
public Iterator iterator() {
return keyColl.iterator();
}
/**
* @return
*/
public boolean hasAllRights() {
return hasAllRights;
}
/**
* @param b
*/
public void setHasAllRights(boolean b) {
hasAllRights = b;
}
/**
* @param dn
* @return
*/
public boolean isAllowed(Object id) {
boolean result = false;
if (isAdmin || hasAllRights()) {
result = true;
} else {
for (Iterator it = keyColl.iterator(); it.hasNext();) {
for (Iterator it = allowedRightKeyEntries.iterator(); it.hasNext();) {
RightsKeyEntry entry = (RightsKeyEntry) it.next();
if (EqualsUtil.areEqual(entry.getKey(), id)) {
result = true;
@ -94,7 +90,7 @@ public class Rights implements Serializable { @@ -94,7 +90,7 @@ public class Rights implements Serializable {
if (isAdmin || hasAllRights()) {
result = true;
} else {
for (Iterator it = keyColl.iterator(); it.hasNext();) {
for (Iterator it = allowedRightKeyEntries.iterator(); it.hasNext();) {
RightsKeyEntry entry = (RightsKeyEntry) it.next();
if (EqualsUtil.areEqual(entry.getKey(), key)) {
result = entry.isSubordinatesAllowed();
@ -105,24 +101,90 @@ public class Rights implements Serializable { @@ -105,24 +101,90 @@ public class Rights implements Serializable {
return result;
}
@Override
public Object clone() throws CloneNotSupportedException {
Rights cl = new Rights(isAdmin, hasAllRights);
for (Iterator it = keyColl.iterator(); it.hasNext();) {
for (Iterator it = allowedRightKeyEntries.iterator(); it.hasNext();) {
RightsKeyEntry key = (RightsKeyEntry) it.next();
cl.keyColl.add(key.clone());
cl.allowedRightKeyEntries.add((RightsKeyEntry) key.clone());
}
return cl;
}
@Override
public String toString() {
StringBuffer result = new StringBuffer("Rechte: ");
for (Iterator it = keyColl.iterator(); it.hasNext();) {
RightsKeyEntry entry = (RightsKeyEntry) it.next();
for (RightsKeyEntry entry : allowedRightKeyEntries) {
result.append(entry.toString() + ",");
}
de.memtext.util.StringUtils.removeLastChar(result);
return result.toString();
}
public void add(Set<String> allowedKeys) {
for (String aKey : allowedKeys) {
allowedRightKeyEntries.add(new RightsKeyEntry(aKey, true));
}
}
public void add(String allowedKey) {
allowedRightKeyEntries.add(new RightsKeyEntry(allowedKey, true));
}
public void addOrgUnitRights(StringBuffer msg, Set<OrgUnit> orgUnits) {
for (OrgUnit ou : orgUnits) {
this.add(ou.getApnr());
msg.append(ou.getApnr() + ",");
}
}
public void addLiveMappingRights(StringBuffer msg, String mandantenID) {
msg.append(
" via LifeMapping :");
Set<String> lifeMappingApnrs = new TreeSet<String>();
Set<String> keysBefore=new HashSet<String>();
for (RightsKeyEntry re:allowedRightKeyEntries)
{
keysBefore.add((String)re.getKey());
OrgUnitMapping oum = SxPools.get(mandantenID).getOrgUnitMappings().get(re.getKey().toString());
if (oum != null) {
lifeMappingApnrs.add(oum.getUniquename());
for (String mappedId : oum.getMappedIds()) {
lifeMappingApnrs.add(mappedId);
}
}
}
lifeMappingApnrs.removeAll(keysBefore);
for (String mappedId : lifeMappingApnrs) {
this.add(mappedId);
msg.append(mappedId + ",");
}
}
/**
* Alle Rechte inkl. LiveMapping und implizierten Rechten wenn Methoden vorher aufgerufen
* @return
*/
public Set<String> getAllRightKeys()
{
Set<String> keys=new TreeSet<String>();
for (RightsKeyEntry re : allowedRightKeyEntries) {
keys.add(re.getKey().toString());
}
return keys;
}
public Iterator<RightsKeyEntry> iterator()
{
return allowedRightKeyEntries.iterator();
}
}
// Created on 07.09.2004 at 11:10:06

23
src/de/memtext/rights/RightsKeyEntry.java

@ -2,11 +2,13 @@ package de.memtext.rights; @@ -2,11 +2,13 @@ package de.memtext.rights;
import java.io.Serializable;
public class RightsKeyEntry implements Comparable,Serializable {
public class RightsKeyEntry implements Comparable<RightsKeyEntry>, Serializable {
private static final long serialVersionUID = 1L;
private final Object key;
private final boolean isSubordinatesAllowed;
public RightsKeyEntry(Object key, boolean isSubordinatesAllowed) {
@ -33,9 +35,9 @@ public class RightsKeyEntry implements Comparable,Serializable { @@ -33,9 +35,9 @@ public class RightsKeyEntry implements Comparable,Serializable {
return key;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof RightsKeyEntry))
return false;
if (!(o instanceof RightsKeyEntry)) return false;
Object otherKey = ((RightsKeyEntry) o).getKey();
boolean result = false;
@ -48,13 +50,15 @@ public class RightsKeyEntry implements Comparable,Serializable { @@ -48,13 +50,15 @@ public class RightsKeyEntry implements Comparable,Serializable {
}
@Override
public int hashCode() {
int result = 37 + key.hashCode() + (isSubordinatesAllowed ? 0 : 1);
return result;
}
public int compareTo(Object o) {
Object otherKey = ((RightsKeyEntry) o).getKey();
@Override
public int compareTo(RightsKeyEntry o) {
Object otherKey = o.getKey();
int result = 0;
if (key instanceof Integer) {
result = ((Integer) key).compareTo((Integer) otherKey);
@ -65,16 +69,17 @@ public class RightsKeyEntry implements Comparable,Serializable { @@ -65,16 +69,17 @@ public class RightsKeyEntry implements Comparable,Serializable {
return result;
}
@Override
public Object clone() throws CloneNotSupportedException {
if (key != null && !(key instanceof String || key instanceof Integer))
throw new CloneNotSupportedException("Prüfen, ob " + key.getClass()
+ " problemlos geclont werden kann");
throw new CloneNotSupportedException("Prüfen, ob " + key.getClass() + " problemlos geclont werden kann");
RightsKeyEntry cl = new RightsKeyEntry(key, isSubordinatesAllowed);
return cl;
}
public String toString()
{
@Override
public String toString() {
return key.toString();
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save