[jboss-cvs] jboss-seam/examples/wiki/src/main/org/jboss/seam/wiki/util ...
Christian Bauer
christian at hibernate.org
Tue Dec 18 23:29:20 EST 2007
User: cbauer
Date: 07/12/18 23:29:20
Modified: examples/wiki/src/main/org/jboss/seam/wiki/util Hash.java
WikiUtil.java
Added: examples/wiki/src/main/org/jboss/seam/wiki/util
DBUnitImporter.java
Log:
Major rewrite of the most of the application
Revision Changes Path
1.4 +3 -4 jboss-seam/examples/wiki/src/main/org/jboss/seam/wiki/util/Hash.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: Hash.java
===================================================================
RCS file: /cvsroot/jboss/jboss-seam/examples/wiki/src/main/org/jboss/seam/wiki/util/Hash.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -b -r1.3 -r1.4
--- Hash.java 21 Jun 2007 11:05:49 -0000 1.3
+++ Hash.java 19 Dec 2007 04:29:20 -0000 1.4
@@ -6,12 +6,11 @@
import org.jboss.seam.annotations.AutoCreate;
/**
- * Not really safe, should use a random salt, prepended later on the digest.
+ * Not super safe, should use a random salt, prepended later on the digest.
* Should also iterate the hashing a few thousand times to make brute force
- * attacks more difficult. Basically, implement user password encryption with
- * the same technique as on a typical Linux distribution.
+ * attacks more difficult. Oh well, probably good enough for storing things
+ * in an internal database.
* <p/>
- * TODO: Make this more secure - before releasing to public and breaking all stored passwords!
*/
@Name("hashUtil")
@AutoCreate
1.21 +20 -110 jboss-seam/examples/wiki/src/main/org/jboss/seam/wiki/util/WikiUtil.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: WikiUtil.java
===================================================================
RCS file: /cvsroot/jboss/jboss-seam/examples/wiki/src/main/org/jboss/seam/wiki/util/WikiUtil.java,v
retrieving revision 1.20
retrieving revision 1.21
diff -u -b -r1.20 -r1.21
--- WikiUtil.java 13 Nov 2007 07:58:09 -0000 1.20
+++ WikiUtil.java 19 Dec 2007 04:29:20 -0000 1.21
@@ -7,14 +7,13 @@
package org.jboss.seam.wiki.util;
import org.jboss.seam.Component;
-import org.jboss.seam.ui.validator.FormattedTextValidator;
-import org.jboss.seam.international.Messages;
import org.jboss.seam.core.Conversation;
import org.jboss.seam.wiki.core.action.prefs.WikiPreferences;
import org.jboss.seam.wiki.core.model.*;
import org.jboss.seam.wiki.core.engine.WikiTextParser;
import org.jboss.seam.wiki.core.engine.WikiLinkResolver;
import org.jboss.seam.wiki.core.engine.NullWikiTextRenderer;
+import org.jboss.seam.wiki.core.engine.MacroWikiTextRenderer;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
@@ -45,6 +44,11 @@
*/
public class WikiUtil {
+ // Disable caching of imags (e.g. captcha) by appending this as a random URL parameter
+ public static int generateRandomNumber() {
+ return (int) Math.round(1 + (Math.random()*1000000));
+ }
+
// Creates clean alphanumeric UpperCaseCamelCase
public static String convertToWikiName(String realName) {
StringBuilder wikiName = new StringBuilder();
@@ -62,27 +66,6 @@
return wikiName.toString();
}
- // Replacement for missing instaceOf in EL (can't use string comparison, might be proxy)
- public static boolean isDirectory(Node node) {
- return node != null && Directory.class.isAssignableFrom(node.getClass());
- }
-
- public static boolean isDocument(Node node) {
- return node != null && Document.class.isAssignableFrom(node.getClass());
- }
-
- public static boolean isFile(Node node) {
- return node != null && File.class.isAssignableFrom(node.getClass());
- }
-
- public static String getType(Node node) {
- if (isDirectory(node)) return "Directory";
- if (isDocument(node)) return "Document";
- if (isFile(node)) return "File";
- return "UNKNOWN TYPE";
- }
-
- // EL is weak
public static String truncateString(String string, int length, String appendString) {
if (string.length() <= length) return string;
return string.substring(0, length-1) + appendString;
@@ -101,16 +84,16 @@
}
// Rendering made easy
- public static String renderPlainURL(Node node) {
- if (isFile(node)) return renderFileLink((File)node);
+ public static String renderPlainURL(WikiNode node) {
+// TODO: Fixme if (node.isInstance(File.class) return renderFileLink((File)node);
WikiPreferences prefs = (WikiPreferences) Component.getInstance("wikiPreferences");
String url = "";
- if (isDocument(node)) {
+ if (node.isInstance(WikiDocument.class)) {
url = prefs.getBaseUrl() + "/docDisplayPlain.seam?documentId=" + node.getId();
- } else if (isDirectory(node)) {
- Directory dir = (Directory)node;
- if (dir.getDefaultDocument() != null) {
- url = prefs.getBaseUrl() + "/docDisplayPlain.seam?documentId=" + dir.getDefaultDocument().getId();
+ } else if (node.isInstance(WikiDirectory.class)) {
+ WikiDirectory dir = (WikiDirectory)node;
+ if (dir.getDefaultFile() != null) {
+ url = prefs.getBaseUrl() + "/docDisplayPlain.seam?documentId=" + dir.getDefaultFile().getId();
} else {
url = prefs.getBaseUrl() + "/dirDisplayPlain.seam?directoryId=" + node.getId();
}
@@ -119,68 +102,22 @@
return url;
}
- public static String renderURL(Node node) {
- return renderURL(node, null);
- }
-
- public static String renderURL(Node node, Comment comment) {
- if (isFile(node)) return renderFileLink((File)node);
+ public static String renderURL(WikiNode node) {
+ if (node == null || node.getId() == null) return "";
WikiPreferences wikiPrefs = (WikiPreferences) Component.getInstance("wikiPreferences");
- if (wikiPrefs.isRenderPermlinks()) {
- return renderPermLink(node, comment);
- } else {
- return renderWikiLink(node, comment);
- }
+ return wikiPrefs.isRenderPermlinks() ? renderPermURL(node) : renderWikiURL(node);
}
- public static String renderPermLink(Node node) {
- return renderPermLink(node, null);
- }
-
- public static String renderPermLink(Node node, Comment comment) {
+ public static String renderPermURL(WikiNode node) {
if (node == null || node.getId() == null) return "";
- if (isFile(node)) return renderFileLink((File)node);
WikiPreferences prefs = (WikiPreferences)Component.getInstance("wikiPreferences");
- StringBuilder url = new StringBuilder();
- url.append(prefs.getBaseUrl());
- if (!prefs.getBaseUrl().endsWith("/")) url.append("/");
- url.append(node.getId());
- url.append(prefs.getPermlinkSuffix());
- if (comment != null) url.append("#comment").append(comment.getId());
- return url.toString();
- }
-
- public static String renderWikiLink(Node node) {
- return renderWikiLink(node, null);
+ return prefs.getBaseUrl() + node.getPermURL(prefs.getPermlinkSuffix());
}
- public static String renderWikiLink(Node node, Comment comment) {
+ public static String renderWikiURL(WikiNode node) {
if (node == null || node.getId() == null) return "";
WikiPreferences prefs = (WikiPreferences)Component.getInstance("wikiPreferences");
- StringBuilder url = new StringBuilder();
- url.append(prefs.getBaseUrl());
- if (!prefs.getBaseUrl().endsWith("/")) url.append("/");
- if (node.getArea().getWikiname().equals(node.getWikiname())) {
- url.append(node.getArea().getWikiname());
- } else {
- url.append(node.getArea().getWikiname()).append("/").append(node.getWikiname());
- }
- if (comment != null) url.append("#comment").append(comment.getId());
- return url.toString();
- }
-
- private static String renderFileLink(File file) {
- if (file == null || file.getId() == null) return "";
- WikiPreferences prefs = (WikiPreferences)Component.getInstance("wikiPreferences");
- return prefs.getBaseUrl() + "/servlets/files/download.seam?fileId=" + file.getId();
- }
-
- public static String renderHomeURL(User user) {
- if (user == null) return "";
- if (user.getMemberHome() == null) throw new IllegalArgumentException("User does not have a home directory");
- WikiPreferences prefs = (WikiPreferences)Component.getInstance("wikiPreferences");
- return prefs.getBaseUrl() + "/" + user.getMemberHome().getParent().getWikiname() + "/" + user.getMemberHome().getWikiname();
-
+ return prefs.getBaseUrl() + node.getWikiURL();
}
public static String displayFilesize(int fileSizeInBytes) {
@@ -248,33 +185,6 @@
}
- public static String findMacros(Document currentDocument, Directory currentDirectory, String wikitext) {
- if (wikitext == null) return null;
- final StringBuilder usedMacros = new StringBuilder();
- WikiTextParser parser = new WikiTextParser(wikitext, false, false);
- parser.setCurrentDocument(currentDocument);
- parser.setCurrentDirectory(currentDirectory);
- parser.setResolver((WikiLinkResolver)Component.getInstance("wikiLinkResolver"));
-
- try {
- class MacroRenderer extends NullWikiTextRenderer {
- public String renderMacro(String macroName) {
- usedMacros.append(macroName).append(" ");
- return null;
- }
- }
- parser.setRenderer( new MacroRenderer() ).parse(false);
-
- } catch (RecognitionException rex) {
- // Swallowing, we don't really care if there was a parse error
- } catch (ANTLRException ex) {
- // All other errors are fatal;
- throw new RuntimeException(ex);
- }
-
- return usedMacros.toString();
- }
-
// TODO: This would be the job of a more flexible seam text parser...
public static String disableFloats(String string) {
return string.replaceAll("float:\\s?(right)|(left)", "float:none")
1.1 date: 2007/12/19 04:29:20; author: cbauer; state: Exp;jboss-seam/examples/wiki/src/main/org/jboss/seam/wiki/util/DBUnitImporter.java
Index: DBUnitImporter.java
===================================================================
package org.jboss.seam.wiki.util;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ReplacementDataSet;
import org.dbunit.dataset.datatype.DataType;
import org.dbunit.dataset.datatype.DataTypeException;
import org.dbunit.dataset.datatype.DefaultDataTypeFactory;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
/**
* Imports some data into the database with the help of DBUnit. This allows us to
* use the same dataset files as in unit testing, but in the regular application startup during
* development. Also helps to avoid maintaining the crude Hibernate import.sql file.
*
* @author Christian Bauer
*/
public class DBUnitImporter {
public enum Database {
hsql, mysql
}
protected Database database;
private String datasourceJndiName;
String binaryDir;
List<String> datasets = new ArrayList<String>();
public void setDatabase(String database) {
this.database = Database.valueOf(database);
}
public String getDatasourceJndiName() {
return datasourceJndiName;
}
public void setDatasourceJndiName(String datasourceJndiName) {
this.datasourceJndiName = datasourceJndiName;
}
public String getBinaryDir() {
return binaryDir;
}
public void setBinaryDir(String binaryDir) {
this.binaryDir = binaryDir;
}
public List<String> getDatasets() {
return datasets;
}
public void setDatasets(List<String> datasets) {
this.datasets = datasets;
}
public void importDatasets() throws Exception {
List<DataSetOperation> dataSetOperations = new ArrayList<DataSetOperation>();
for (String dataset : datasets) {
dataSetOperations.add(new DataSetOperation(dataset));
}
IDatabaseConnection con = null;
try {
con = getConnection();
disableReferentialIntegrity(con);
for (DataSetOperation op : dataSetOperations) {
op.execute(con);
}
enableReferentialIntegrity(con);
} finally {
if (con != null) {
try {
con.close();
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
}
}
/**
* Override this method if you want to provide your own DBUnit <tt>IDatabaseConnection</tt> instance.
* <p/>
* If you do not override this, default behavior is to use the * configured datasource name and
* to obtain a connection with a JNDI lookup.
*
* @return a DBUnit database connection (wrapped)
*/
protected IDatabaseConnection getConnection() {
try {
DataSource datasource = ((DataSource)new InitialContext().lookup(datasourceJndiName));
// Get a JDBC connection from JNDI datasource
Connection con = datasource.getConnection();
IDatabaseConnection dbUnitCon = new DatabaseConnection(con);
editConfig(dbUnitCon.getConfig());
return dbUnitCon;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Override this method if you aren't using HSQL DB.
* <p/>
* Execute whatever statement is necessary to either defer or disable foreign
* key constraint checking on the given database connection, which is used by
* DBUnit to import datasets.
*
* @param con A DBUnit connection wrapper, which is used afterwards for dataset operations
*/
protected void disableReferentialIntegrity(IDatabaseConnection con) {
try {
if (database.equals(Database.hsql)) {
con.getConnection().prepareStatement("set referential_integrity FALSE").execute(); // HSQL DB
} else if (database.equals(Database.mysql)) {
con.getConnection().prepareStatement("set foreign_key_checks=0").execute(); // MySQL > 4.1.1
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Override this method if you aren't using HSQL DB.
* <p/>
* Execute whatever statement is necessary to enable integrity constraint checks after
* dataset operations.
*
* @param con A DBUnit connection wrapper, before it is used by the application again
*/
protected void enableReferentialIntegrity(IDatabaseConnection con) {
try {
if (database.equals(Database.hsql)) {
con.getConnection().prepareStatement("set referential_integrity TRUE").execute(); // HSQL DB
} else if (database.equals(Database.mysql)) {
con.getConnection().prepareStatement("set foreign_key_checks=1").execute(); // MySQL > 4.1.1
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Override this method if you require DBUnit configuration features or additional properties.
* <p>
* Called after a connection has been obtaind and before the connection is used. Can be a
* NOOP method if no additional settings are necessary for your DBUnit/DBMS setup.
*
* @param config A DBUnit <tt>DatabaseConfig</tt> object for setting properties and features
*/
protected void editConfig(DatabaseConfig config) {
if (database.equals(Database.hsql)) {
// DBUnit/HSQL bugfix
// http://www.carbonfive.com/community/archives/2005/07/dbunit_hsql_and.html
config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new DefaultDataTypeFactory() {
public DataType createDataType(int sqlType, String sqlTypeName)
throws DataTypeException {
if (sqlType == Types.BOOLEAN) {
return DataType.BOOLEAN;
}
return super.createDataType(sqlType, sqlTypeName);
}
});
}
}
/**
* Resolves the binary dir location with the help of the classloader, we need the
* absolute full path of that directory.
*
* @return String full absolute path of the binary directory
*/
protected String getBinaryDirFullpath() {
if (binaryDir == null) {
throw new RuntimeException("Please set binaryDir property to location of binary test files");
}
URL url = Thread.currentThread().getContextClassLoader().getResource(getBinaryDir());
if (url == null) {
throw new RuntimeException("Could not find full path with classloader of binaryDir: " + getBinaryDir());
}
return url.toString();
}
protected class DataSetOperation {
String dataSetLocation;
ReplacementDataSet dataSet;
DatabaseOperation operation;
/**
* Defaults to <tt>DatabaseOperation.CLEAN_INSERT</tt>
*/
public DataSetOperation(String dataSetLocation){
this(dataSetLocation, DatabaseOperation.INSERT);
}
public DataSetOperation(String dataSetLocation, DatabaseOperation operation) {
// Load the base dataset file
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(dataSetLocation);
try {
this.dataSet = new ReplacementDataSet( new FlatXmlDataSet(input) );
} catch (Exception ex) {
throw new RuntimeException("Could not load dataset for import: " + dataSetLocation, ex);
}
this.dataSet.addReplacementObject("[NULL]", null);
this.dataSet.addReplacementSubstring("[BINARY_DIR]", getBinaryDirFullpath());
this.operation = operation;
this.dataSetLocation = dataSetLocation;
}
public IDataSet getDataSet() {
return dataSet;
}
public DatabaseOperation getOperation() {
return operation;
}
public void execute(IDatabaseConnection connection) {
try {
this.operation.execute(connection, dataSet);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public String toString() {
// TODO: This is not pretty because DBUnit's DatabaseOperation doesn't implement toString() properly
return operation.getClass() + " with dataset: " + dataSetLocation;
}
}
}
More information about the jboss-cvs-commits
mailing list