Added sqlite support and fixed some issues

This commit is contained in:
Ziver Koc 2014-07-01 19:54:30 +00:00
parent 78205d97af
commit fcbaef3e76
26 changed files with 348 additions and 371 deletions

View file

@ -7,18 +7,10 @@
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/> <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry exported="true" kind="lib" path="libs/commons-fileupload-1.2.1.jar" sourcepath="C:/Users/Ziver/Documents/Programmering/Java/libs/commons/commons-fileupload-1.2.1-sources.jar"/> <classpathentry exported="true" kind="lib" path="libs/commons-fileupload-1.2.1.jar" sourcepath="C:/Users/Ziver/Documents/Programmering/Java/libs/commons/commons-fileupload-1.2.1-sources.jar"/>
<classpathentry exported="true" kind="lib" path="libs/commons-io-1.4.jar"/> <classpathentry exported="true" kind="lib" path="libs/commons-io-1.4.jar"/>
<classpathentry exported="true" kind="lib" path="libs/mysql-connector-java-5.1.14-bin.jar"/> <classpathentry kind="lib" path="libs/mysql-connector-java-5.1.14-bin.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
<classpathentry kind="con" path="at.bestsolution.efxclipse.tooling.jdt.core.JAVAFX_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v7.0"/>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v7.0"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<attributes> <classpathentry kind="lib" path="libs/sqlite-jdbc-3.7.2.jar"/>
<attribute name="owner.project.facets" value="jst.utility"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre7">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin"/> <classpathentry kind="output" path="bin"/>
</classpath> </classpath>

1
.idea/.name generated
View file

@ -1 +0,0 @@
ZUtil

7
.idea/ant.xml generated
View file

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AntConfiguration">
<defaultAnt bundledAnt="true" />
</component>
</project>

27
.idea/compiler.xml generated
View file

@ -1,27 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<option name="DEFAULT_COMPILER" value="Javac" />
<excludeFromCompile>
<file url="file://$PROJECT_DIR$/src/zutil/jee/upload/AjaxFileUpload.java" />
<file url="file://$PROJECT_DIR$/src/zutil/net/http/multipart/MultipartParser.java" />
</excludeFromCompile>
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
</project>

View file

@ -1,9 +0,0 @@
<component name="CopyrightManager">
<copyright>
<option name="notice" value="Copyright (c) &amp;#36;today.year &amp;#36;username&#10;&#10;Permission is hereby granted, free of charge, to any person obtaining a copy&#10;of this software and associated documentation files (the &quot;Software&quot;), to deal&#10;in the Software without restriction, including without limitation the rights&#10;to use, copy, modify, merge, publish, distribute, sublicense, and/or sell&#10;copies of the Software, and to permit persons to whom the Software is&#10;furnished to do so, subject to the following conditions:&#10;&#10;The above copyright notice and this permission notice shall be included in&#10;all copies or substantial portions of the Software.&#10;&#10;THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR&#10;IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,&#10;FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE&#10;AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER&#10;LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,&#10;OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN&#10;THE SOFTWARE." />
<option name="keyword" value="Copyright" />
<option name="allowReplaceKeyword" value="" />
<option name="myName" value="MIT" />
<option name="myLocal" value="true" />
</copyright>
</component>

View file

@ -1,7 +0,0 @@
<component name="CopyrightManager">
<settings default="">
<module2copyright>
<element module="All" copyright="MIT" />
</module2copyright>
</settings>
</component>

View file

@ -1,3 +0,0 @@
<component name="ProjectDictionaryState">
<dictionary name="ezivkoc" />
</component>

5
.idea/encodings.xml generated
View file

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
</project>

45
.idea/misc.xml generated
View file

@ -1,45 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
<list size="1">
<item index="0" class="java.lang.String" itemvalue="zutil.net.ws.WSReturnObject.WSValueName" />
</list>
</component>
<component name="JavadocGenerationManager">
<option name="OUTPUT_DIRECTORY" />
<option name="OPTION_SCOPE" value="protected" />
<option name="OPTION_HIERARCHY" value="true" />
<option name="OPTION_NAVIGATOR" value="true" />
<option name="OPTION_INDEX" value="true" />
<option name="OPTION_SEPARATE_INDEX" value="true" />
<option name="OPTION_DOCUMENT_TAG_USE" value="false" />
<option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" />
<option name="OPTION_DOCUMENT_TAG_VERSION" value="false" />
<option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" />
<option name="OPTION_DEPRECATED_LIST" value="true" />
<option name="OTHER_OPTIONS" value="" />
<option name="HEAP_SIZE" />
<option name="LOCALE" />
<option name="OPEN_IN_BROWSER" value="true" />
<option name="OPTION_INCLUDE_LIBS" value="false" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/bin" />
</component>
<component name="SvnBranchConfigurationManager">
<option name="myConfigurationMap">
<map>
<entry key="$PROJECT_DIR$">
<value>
<SvnBranchConfiguration>
<option name="trunkUrl" value="" />
</SvnBranchConfiguration>
</value>
</entry>
</map>
</option>
<option name="mySupportsUserInfoFilter" value="true" />
</component>
</project>

9
.idea/modules.xml generated
View file

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/ZUtil.iml" filepath="$PROJECT_DIR$/ZUtil.iml" />
</modules>
</component>
</project>

View file

@ -1,5 +0,0 @@
<component name="DependencyValidationManager">
<state>
<option name="SKIP_IMPORT_STATEMENTS" value="false" />
</state>
</component>

125
.idea/uiDesigner.xml generated
View file

@ -1,125 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

7
.idea/vcs.xml generated
View file

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="svn" />
</component>
</project>

View file

@ -1,8 +0,0 @@
#Mon Aug 16 22:05:56 CEST 2010
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.5

View file

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<faceted-project> <faceted-project>
<runtime name="Apache Tomcat v7.0"/>
<fixed facet="java"/> <fixed facet="java"/>
<fixed facet="jst.utility"/> <fixed facet="jst.utility"/>
<installed facet="java" version="1.5"/> <installed facet="java" version="1.5"/>

BIN
libs/sqlite-jdbc-3.7.2.jar Normal file

Binary file not shown.

View file

@ -44,7 +44,8 @@ public class DBConnection implements Closeable{
private static final Logger logger = LogUtil.getLogger(); private static final Logger logger = LogUtil.getLogger();
public enum DBMS{ public enum DBMS{
MySQL MySQL,
SQLite
} }
// The connection // The connection
private Connection conn = null; private Connection conn = null;
@ -88,6 +89,17 @@ public class DBConnection implements Closeable{
String dbms_name = initDriver(dbms); String dbms_name = initDriver(dbms);
conn = DriverManager.getConnection ("jdbc:"+dbms_name+"://"+url+"/"+db, user, password); conn = DriverManager.getConnection ("jdbc:"+dbms_name+"://"+url+"/"+db, user, password);
} }
/**
* Creates an Connection to a DB file
*
* @param dbms is the DB type
* @param db is the database to connect to
*/
public DBConnection(DBMS dbms, String db) throws Exception{
String dbms_name = initDriver(dbms);
conn = DriverManager.getConnection ("jdbc:"+dbms_name+":"+db);
}
/** /**
* @return the underlying connection * @return the underlying connection
@ -105,11 +117,15 @@ public class DBConnection implements Closeable{
public String initDriver(DBMS db) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ public String initDriver(DBMS db) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
switch(db){ switch(db){
case MySQL: case MySQL:
Class.forName ("com.mysql.jdbc.Driver").newInstance(); Class.forName("com.mysql.jdbc.Driver").newInstance();
DriverManager.setLoginTimeout(10); DriverManager.setLoginTimeout(10);
return "mysql"; return "mysql";
case SQLite:
Class.forName("org.sqlite.JDBC");
return "sqlite";
default:
return null;
} }
return null;
} }
/** /**
@ -162,16 +178,23 @@ public class DBConnection implements Closeable{
* @return update count or -1 if the query is not an update query * @return update count or -1 if the query is not an update query
*/ */
public static int exec(PreparedStatement stmt) throws SQLException { public static int exec(PreparedStatement stmt) throws SQLException {
return exec(stmt, new SQLResultHandler<Integer>(){ Integer ret = exec(stmt, new SQLResultHandler<Integer>(){
public Integer handleQueryResult(Statement stmt, ResultSet result) { public Integer handleQueryResult(Statement stmt, ResultSet result) {
try { try {
return stmt.getUpdateCount(); if(stmt != null)
return stmt.getUpdateCount();
else
return -1;
} catch (SQLException e) { } catch (SQLException e) {
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
} }
return -1; return -1;
} }
}); });
if(ret != null)
return ret;
return -1;
} }
/** /**
@ -203,23 +226,35 @@ public class DBConnection implements Closeable{
if( handler != null ){ if( handler != null ){
ResultSet result = null; ResultSet result = null;
try{ try{
result = stmt.getResultSet(); if(stmt.getMoreResults()){
return handler.handleQueryResult(stmt, result); result = stmt.getResultSet();
return handler.handleQueryResult(stmt, result);
}
else
return null;
}catch(SQLException sqlex){
logger.throwing(null, null, sqlex);
}finally{ }finally{
if(result != null){ if(result != null){
try { try {
result.close(); result.close();
} catch (SQLException e) { } } catch (SQLException sqlex) {
logger.throwing(null, null, sqlex);
}
result = null; result = null;
} }
} }
} }
}catch(SQLException sqlex){
logger.throwing(null, null, sqlex);
// Cleanup // Cleanup
} finally { } finally {
if (stmt != null) { if (stmt != null) {
try { try {
stmt.close(); stmt.close();
} catch (SQLException sqlex) { } } catch (SQLException sqlex) {
logger.throwing(null, null, sqlex);
}
stmt = null; stmt = null;
} }
} }

View file

@ -43,12 +43,13 @@ import java.util.logging.Logger;
import zutil.db.DBConnection; import zutil.db.DBConnection;
import zutil.log.LogUtil; import zutil.log.LogUtil;
/** /**
* <XMP> * The class that extends this will be able to save its state to a database.
* The class that extends this will be able to save its state to a DB.
* Fields that are transient will be ignored, and fields that extend * Fields that are transient will be ignored, and fields that extend
* DBBean will be replaced with the id field of that class in the database. * DBBean will be replaced with the an id which corresponds to the field
* of that object.
* *
* <XMP>
* Supported fields: * Supported fields:
* *Boolean * *Boolean
* *Integer * *Integer
@ -59,8 +60,7 @@ import zutil.log.LogUtil;
* *Character * *Character
* *DBBean * *DBBean
* *java.sql.Timestamp * *java.sql.Timestamp
* *List<DBBean> * *List<DBBean>
*
* </XMP> * </XMP>
* @author Ziver * @author Ziver
*/ */
@ -340,11 +340,11 @@ public abstract class DBBean {
} }
/** /**
* Loads all the rows in the table into a LinkedList * Loads all rows from the table into a LinkedList
* *
* @param <T> is the class of the bean * @param <T> is the class of the bean
* @param c is the class of the bean * @param c is the class of the bean
* @return a LinkedList with all the Beans in the DB * @return a LinkedList with all the beans in the DB
*/ */
public static <T extends DBBean> List<T> load(DBConnection db, Class<T> c) throws SQLException { public static <T extends DBBean> List<T> load(DBConnection db, Class<T> c) throws SQLException {
// Initiate a BeanConfig if there is non // Initiate a BeanConfig if there is non
@ -359,12 +359,12 @@ public abstract class DBBean {
} }
/** /**
* Loads all the rows in the table into a LinkedList * Loads a specific instance of the bean from the table with the specific id
* *
* @param <T> is the class of the bean * @param <T> is the class of the bean
* @param c is the class of the bean * @param c is the class of the bean
* @param id is the id value of the bean * @param id is the id value of the bean
* @return a DBBean Object with the specific id or null * @return a DBBean Object with the specific id or null if the id was not found
*/ */
public static <T extends DBBean> T load(DBConnection db, Class<T> c, long id) throws SQLException { public static <T extends DBBean> T load(DBConnection db, Class<T> c, long id) throws SQLException {
// Initiate a BeanConfig if there is non // Initiate a BeanConfig if there is non

View file

@ -29,24 +29,25 @@ import java.util.ArrayList;
public class DynamicByteArrayStream extends InputStream{ public class DynamicByteArrayStream extends InputStream{
/** The byte array container */ /** The byte array container */
private ArrayList<byte[]> bytes; private ArrayList<byte[]> bytes;
/** Current virtual size of the stream */
private int size;
/** Points the current byte array index */
private int arrayIndex;
/** Points to a local index in the current byte array */
private int arrayLocalIndex;
/** Current virtual position of the stream */ /** Current virtual position of the stream */
private int pos; private int globalPos;
/** Current virtual size of the stream */
private int globalSize;
/** Points the current byte array index */
private int globalArrayIndex;
/** Points to a local index in the current byte array */
private int localArrayOffset;
/** /**
* Create a new instance of DynamicByteArrayStream * Create a new instance of DynamicByteArrayStream
*/ */
public DynamicByteArrayStream(){ public DynamicByteArrayStream(){
bytes = new ArrayList<byte[]>(); bytes = new ArrayList<byte[]>();
size = 0; globalPos = 0;
arrayIndex = 0; globalSize = 0;
arrayLocalIndex = 0; globalArrayIndex = 0;
pos = 0; localArrayOffset = 0;
} }
/** /**
@ -56,7 +57,7 @@ public class DynamicByteArrayStream extends InputStream{
*/ */
public synchronized void append(byte[] b){ public synchronized void append(byte[] b){
bytes.add(b); bytes.add(b);
size += b.length; globalSize += b.length;
} }
/** /**
@ -71,70 +72,70 @@ public class DynamicByteArrayStream extends InputStream{
byte[] new_b = new byte[length]; byte[] new_b = new byte[length];
System.arraycopy(b, offset, new_b, 0, length); System.arraycopy(b, offset, new_b, 0, length);
bytes.add(new_b); bytes.add(new_b);
size += length; globalSize += length;
} }
@Override @Override
public synchronized int read() throws IOException { public synchronized int read() throws IOException {
if(pos >= size) return -1; if(globalPos >= globalSize) return -1;
int ret = bytes.get(arrayIndex)[arrayLocalIndex] & 0xff; int ret = bytes.get(globalArrayIndex)[localArrayOffset] & 0xff;
pos++; globalPos++;
arrayLocalIndex++; localArrayOffset++;
if(arrayLocalIndex >= bytes.get(arrayIndex).length){ if(localArrayOffset >= bytes.get(globalArrayIndex).length){
arrayIndex++; globalArrayIndex++;
arrayLocalIndex = 0; localArrayOffset = 0;
} }
return ret; return ret;
} }
public synchronized int read(byte b[], int off, int len) { public synchronized int read(byte b[], int off, int len) {
if(len <= 0) return 0; if(len <= 0) return 0;
if(pos >= size) return -1; if(globalPos >= globalSize) return -1;
int bytes_read=0; int bytes_read=0;
if(pos+len >= size) len = size - pos; if(globalPos+len >= globalSize) len = globalSize - globalPos;
for(; bytes_read<len ;bytes_read++){ while(bytes_read<len){
byte[] src = bytes.get(arrayIndex); byte[] src = bytes.get(globalArrayIndex);
// Read length is LONGER than local array // Read length is LONGER than local array
if(arrayLocalIndex +len-bytes_read >= src.length){ if(localArrayOffset +len-bytes_read > src.length){
int length = src.length- arrayLocalIndex; int length = src.length- localArrayOffset;
System.arraycopy(src, arrayLocalIndex, b, off+bytes_read, length); System.arraycopy(src, localArrayOffset, b, off+bytes_read, length);
arrayLocalIndex = 0; localArrayOffset = 0;
arrayIndex++; globalArrayIndex++;
bytes_read += length; bytes_read += length;
} }
// Read length is SHORTER than local array // Read length is SHORTER than local array
else{ else{
int length = len-bytes_read; int length = len-bytes_read;
System.arraycopy(src, arrayLocalIndex, b, off+bytes_read, length); System.arraycopy(src, localArrayOffset, b, off+bytes_read, length);
arrayLocalIndex += length; localArrayOffset += length;
bytes_read += length; bytes_read += length;
} }
} }
pos += len; globalPos += len;
return bytes_read; return bytes_read;
} }
public synchronized int available() { public synchronized int available() {
return size - pos; return globalSize - globalPos;
} }
/** /**
* Clears this stream from the byte arrays * Clears this stream from the byte arrays
*/ */
public synchronized void clear(){ public synchronized void clear(){
size = 0; globalSize = 0;
reset(); reset();
bytes.clear(); bytes.clear();
} }
public synchronized void reset() { public synchronized void reset() {
arrayIndex = 0; globalArrayIndex = 0;
arrayLocalIndex = 0; localArrayOffset = 0;
pos = 0; globalPos = 0;
} }
public void close() throws IOException { public void close() throws IOException {
@ -145,8 +146,8 @@ public class DynamicByteArrayStream extends InputStream{
* @return all of the buffers content as a byte array. * @return all of the buffers content as a byte array.
*/ */
public byte[] getBytes(){ public byte[] getBytes(){
byte[] data = new byte[size]; byte[] data = new byte[globalSize];
this.read(data, 0, size); this.read(data, 0, globalSize);
return data; return data;
} }

View file

@ -0,0 +1,59 @@
/*******************************************************************************
* Copyright (c) 2013 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package zutil.io;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
/**
* A simple Class that mirrors a InputStream but
* also has an additional Closeable object that
* will be closed with the InputStream
*
* @author Ziver
*/
public class InputStreamCloser extends InputStream{
private Closeable c;
private InputStream in;
public InputStreamCloser(InputStream in, Closeable c){
this.c = c;
this.in = in;
}
public void close() throws IOException {
in.close();
c.close();
}
// Mirror functions
public int read() throws IOException { return in.read(); }
public int read(byte b[]) throws IOException { return in.read(b); }
public int read(byte b[], int off, int len) throws IOException { return in.read(b, off, len); }
public long skip(long n) throws IOException { return in.skip(n); }
public int available() throws IOException { return in.available(); }
public synchronized void mark(int readlimit) { in.mark(readlimit); }
public synchronized void reset() throws IOException { in.reset(); }
public boolean markSupported() { return in.markSupported(); }
}

View file

@ -23,49 +23,68 @@
package zutil.io.file; package zutil.io.file;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class FileSearch implements Iterable<File>{ import zutil.io.InputStreamCloser;
public class FileSearch implements Iterable<FileSearchItem>{
// Constants
private static final List<String> compressedFileExtensions = Arrays.asList(new String[]{
"jar", "zip"
});
// Constructor params
private File root; private File root;
// Search parameters // Search parameters
private String fileName; private String fileName;
private String extension; private String extension;
private boolean recursive; private boolean recursive;
//private int depth; //private int depth;
private boolean searchFiles; private boolean searchFiles;
private boolean searchCompressedFiles;
private boolean searchFolders; private boolean searchFolders;
public FileSearch(File root){ public FileSearch(File root){
this.root = root; this.root = root;
searchFiles = true; searchFiles = true;
searchFolders = true; searchFolders = true;
} }
/** /**
* @param file Sets the exact file name to search for (includes extension) * @param file Sets the exact file name to search for (includes extension)
*/ */
public void setFileName(String file){ public void setFileName(String file){
fileName = file; fileName = file;
} }
/** /**
* Sets the file extensions to search for (should not include . at the beggining) * Sets the file extensions to search for (should not include . at the beggining)
*/ */
public void setExtension(String ext){ public void setExtension(String ext){
} }
/** /**
* Sets if the search should go into sub-folders * Sets if the search should go into sub-folders
*/ */
public void setRecursive(boolean recursive){ public void setRecursive(boolean recursive){
this.recursive = recursive; this.recursive = recursive;
} }
/** /**
* Sets how deep into folders the search should go * Sets how deep into folders the search should go
* (Recursion needs to be enabled for this attribute to be used) * (Recursion needs to be enabled for this attribute to be used)
@ -73,75 +92,153 @@ public class FileSearch implements Iterable<File>{
//public void setDepth(int depth){ //public void setDepth(int depth){
// this.depth = depth; // this.depth = depth;
//} //}
public void searchFiles(boolean searchFiles){ public void searchFiles(boolean searchFiles){
this.searchFiles = searchFiles; this.searchFiles = searchFiles;
} }
public void searchCompressedFiles(boolean searchCompressedFiles){
this.searchCompressedFiles = searchCompressedFiles;
}
public void searchFolders(boolean searchFolders){ public void searchFolders(boolean searchFolders){
this.searchFolders = searchFolders; this.searchFolders = searchFolders;
} }
@Override @Override
public Iterator<File> iterator() { public Iterator<FileSearchItem> iterator() {
return new FileSearchIterator(); return new FileSearchIterator();
} }
protected class FileSearchIterator implements Iterator<File>{ protected class FileSearchIterator implements Iterator<FileSearchItem>{
private ArrayList<File> fileList; private ArrayList<FileSearchItem> fileList;
private int currentIndex; private int currentIndex;
public FileSearchIterator(){ public FileSearchIterator(){
fileList = new ArrayList<File>(); fileList = new ArrayList<FileSearchItem>();
currentIndex = 0; currentIndex = 0;
addToFileList(root.listFiles()); addFiles(root.list());
next(); next();
} }
@Override @Override
public boolean hasNext() { public boolean hasNext() {
return currentIndex != fileList.size(); return currentIndex != fileList.size();
} }
@Override @Override
public void remove() { public void remove() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public File next() { public FileSearchItem next() {
if(currentIndex < 0) if(currentIndex < 0)
return null; return null;
// Temporarily save the current file // Temporarily save the current file
File ret = fileList.get(currentIndex); FileSearchItem ret = fileList.get(currentIndex);
// Find the next file // Find the next file
for(; currentIndex<fileList.size(); currentIndex++){ for(; currentIndex<fileList.size(); currentIndex++){
File file = fileList.get(currentIndex); FileSearchItem file = fileList.get(currentIndex);
if(recursive && file.isDirectory()){ if(recursive && file.isDirectory()){
addToFileList(file.listFiles()); addFiles(file.listFiles());
if(searchFolders && file.getName().equalsIgnoreCase(fileName)) if(searchFolders && file.getName().equalsIgnoreCase(fileName))
break; break;
}
else if(searchCompressedFiles && file.isFile() &&
compressedFileExtensions.contains(FileUtil.getFileExtension(file.getName()).toLowerCase())){
try {
String url = file.getUrl().getFile();
ZipFile zipFile = new ZipFile(url);
Enumeration<? extends ZipEntry> e = zipFile.entries();
while(e.hasMoreElements()){
ZipEntry entry = e.nextElement();
fileList.add(new FileSearchZipItem(url, entry));
}
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
else if(searchFiles && file.isFile()){ else if(searchFiles && file.isFile()){
if(extension != null && FileUtil.getFileExtension(file).equalsIgnoreCase(extension)) if(extension != null && FileUtil.getFileExtension(file.getName()).equalsIgnoreCase(extension))
break; break;
else if(fileName != null && file.getName().equalsIgnoreCase(fileName)) else if(fileName != null && file.getName().equalsIgnoreCase(fileName))
break; break;
} }
} }
return ret; return ret;
} }
private void addToFileList(File[] list){ private void addFiles(String[] list){
for(File file : list){ for(String file : list){
fileList.add(file); fileList.add(new FileSearchFileItem(new File(file)));
} }
} }
} }
} }
interface FileSearchItem{
/** @return a file or folder name **/
public String getName();
/** @return a URL to the file or folder, in case of a compressed file the URL to the package will be returned **/
public URL getUrl() throws MalformedURLException ;
public boolean isCompressed();
public boolean isFile();
public boolean isDirectory();
/** @return an InputStream if this is a file otherwise null **/
public InputStream getInputStream() throws IOException;
/** @return an String array with all files if this is a folder otherwise null **/
public String[] listFiles();
}
class FileSearchFileItem implements FileSearchItem{
private File file;
protected FileSearchFileItem(File file){
this.file = file;
}
public String getName() { return file.getName(); }
public URL getUrl() throws MalformedURLException { return new URL(file.getAbsolutePath()); }
public boolean isCompressed() { return false; }
public boolean isFile() { return file.isFile(); }
public boolean isDirectory() { return file.isDirectory(); }
public InputStream getInputStream() throws IOException { return new FileInputStream(file); }
public String[] listFiles() { return file.list(); }
}
class FileSearchZipItem implements FileSearchItem{
private String file;
private ZipEntry entry;
protected FileSearchZipItem(String file, ZipEntry entry){
this.file = file;
this.entry = entry;
}
public String getName() { return entry.getName(); }
public URL getUrl() throws MalformedURLException { return new URL(file); }
public boolean isCompressed() { return true; }
public boolean isFile() { return !entry.isDirectory(); }
public boolean isDirectory() { return entry.isDirectory(); }
public InputStream getInputStream() throws IOException {
ZipFile zip = new ZipFile(file);
return new InputStreamCloser(zip.getInputStream(entry), zip);
}
public String[] listFiles() { return null; }
}

View file

@ -23,8 +23,12 @@
package zutil.io.file; package zutil.io.file;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URISyntaxException; import java.net.URISyntaxException;
@ -310,4 +314,43 @@ public class FileUtil {
return file.substring(0, file.lastIndexOf(".")+1)+ext; return file.substring(0, file.lastIndexOf(".")+1)+ext;
} }
/**
* This function will replace some data between two boundaries.
* If the boundary is not found it will be added to the end of the file.
*
* @param file is the file to modify
* @param boundary is the start and end boundary to put the data between, this is a full line boundary.
* @param data is the data that will be written to the file
*/
public static void writeBetweenBoundary(File file, String boundary, String data) throws IOException{
BufferedReader in = new BufferedReader(new FileReader(file));
StringBuilder output = new StringBuilder();
String line;
while((line = in.readLine()) != null){
// Found starting boundary
if(line.equals(boundary)){
while((line = in.readLine()) != null)
// Find ending boundary
if(line.equals(boundary)) break;
// EOF and no ending boundary found
if(line == null){
in.close();
throw new EOFException("No ending boundary found");
}
// Write the new data
output.append(boundary).append('\n');
output.append(data).append('\n');
output.append(boundary).append('\n');
}
else
output.append(line).append('\n');
}
in.close();
// Save changes
FileWriter out = new FileWriter(file);
out.write(output.toString());
out.close();
}
} }

View file

@ -123,6 +123,8 @@ public class HttpServer extends ThreadedTCPNetworkServer{
* @param page The page itself * @param page The page itself
*/ */
public void setPage(String name, HttpPage page){ public void setPage(String name, HttpPage page){
if(name.charAt(0) != '/')
name = "/"+name;
pages.put(name, page); pages.put(name, page);
} }
@ -268,9 +270,12 @@ public class HttpServer extends ThreadedTCPNetworkServer{
} catch (Exception e1) {} } catch (Exception e1) {}
if(e.getMessage() != null) if(e.getMessage() != null)
out.println( "500 Internal Server Error: "+e.getMessage() ); out.println( "500 Internal Server Error: "+e.getMessage() );
else{ else if(e.getCause() != null){
out.println( "500 Internal Server Error: "+e.getCause().getMessage() ); out.println( "500 Internal Server Error: "+e.getCause().getMessage() );
} }
else{
out.println( "500 Internal Server Error: "+e);
}
} }
try{ try{

View file

@ -39,13 +39,13 @@ public abstract class OSAbstractionLayer {
// Variables // Variables
private static OSAbstractionLayer instance; private static OSAbstractionLayer instance;
public OSAbstractionLayer getInstance(){ public static OSAbstractionLayer getInstance(){
if(instance == null) if(instance == null)
instance = getAbstractionLayer(); instance = getAbstractionLayer();
return instance; return instance;
} }
private OSAbstractionLayer getAbstractionLayer(){ private static OSAbstractionLayer getAbstractionLayer(){
String os = System.getProperty("os.name"); String os = System.getProperty("os.name");
if (os.contains("Linux")) return new OsalLinuxImpl(); if (os.contains("Linux")) return new OsalLinuxImpl();
else if(os.contains("Windows")) return new OsalWindowsImpl(); else if(os.contains("Windows")) return new OsalWindowsImpl();

View file

@ -54,7 +54,8 @@ public class PluginData<T> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T getObject() throws InstantiationException, IllegalAccessException, ClassNotFoundException{ public T getObject() throws InstantiationException, IllegalAccessException, ClassNotFoundException{
if(obj == null) if(obj == null)
obj = (T) Class.forName(pluginClass).newInstance(); new URLClassLoader(urls);
//obj = (T) Class.forName(pluginClass).newInstance();
return obj; return obj;
} }

View file

@ -48,6 +48,9 @@ public class DynamicByteArrayStreamTest {
DynamicByteArrayStream out = new DynamicByteArrayStream(); DynamicByteArrayStream out = new DynamicByteArrayStream();
out.append(b); out.append(b);
assertEquals(b, out.getBytes()); byte[] result = out.getBytes();
for(int i=0; i<b.length; i++){
assertEquals(b[i], result[i]);
}
} }
} }