Subversion Repositories XServices

Compare Revisions

Problem with comparison.

Ignore whitespace Rev HEAD → Rev 99

/xservices/trunk/src/java/net/brutex/xservices/util/CVSRoot.java
0,0 → 1,67
package net.brutex.xservices.util;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
 
/**
* A struct containing the various bits of information in a CVS root string,
* allowing easy retrieval of individual items of information
*/
public class CVSRoot {
public String connectionType;
public String user;
public String host;
public String repository;
 
public CVSRoot(String root) throws IllegalArgumentException {
if (!root.startsWith(":"))
throw new IllegalArgumentException();
 
int oldColonPosition = 0;
int colonPosition = root.indexOf(':', 1);
if (colonPosition == -1)
throw new IllegalArgumentException();
connectionType = root.substring(oldColonPosition + 1, colonPosition);
oldColonPosition = colonPosition;
colonPosition = root.indexOf('@', colonPosition + 1);
if (colonPosition == -1)
throw new IllegalArgumentException();
user = root.substring(oldColonPosition + 1, colonPosition);
oldColonPosition = colonPosition;
colonPosition = root.indexOf(':', colonPosition + 1);
if (colonPosition == -1)
throw new IllegalArgumentException();
host = root.substring(oldColonPosition + 1, colonPosition);
repository = root.substring(colonPosition + 1);
if (connectionType == null || user == null || host == null
|| repository == null)
throw new IllegalArgumentException();
}
 
public String getCVSRoot(File directory) {
String root = null;
BufferedReader r = null;
try {
File rootFile = new File(directory, "CVS/Root");
if (rootFile.exists()) {
r = new BufferedReader(new FileReader(rootFile));
root = r.readLine();
}
} catch (IOException e) {
// ignore
} finally {
try {
if (r != null)
r.close();
} catch (IOException e) {
System.err.println("Warning: could not close CVS/Root file!");
}
}
if (root == null) {
root = System.getProperty("cvs.root");
}
return root;
}
}
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/xservices/trunk/src/java/net/brutex/xservices/util/BasicCVSListener.java
0,0 → 1,104
package net.brutex.xservices.util;
 
import java.io.PrintStream;
 
import org.netbeans.lib.cvsclient.command.FileInfoContainer;
import org.netbeans.lib.cvsclient.command.log.LogInformation;
import org.netbeans.lib.cvsclient.event.BinaryMessageEvent;
import org.netbeans.lib.cvsclient.event.CVSAdapter;
import org.netbeans.lib.cvsclient.event.CVSListener;
import org.netbeans.lib.cvsclient.event.FileAddedEvent;
import org.netbeans.lib.cvsclient.event.FileInfoEvent;
import org.netbeans.lib.cvsclient.event.FileRemovedEvent;
import org.netbeans.lib.cvsclient.event.FileToRemoveEvent;
import org.netbeans.lib.cvsclient.event.FileUpdatedEvent;
import org.netbeans.lib.cvsclient.event.MessageEvent;
import org.netbeans.lib.cvsclient.event.ModuleExpansionEvent;
import org.netbeans.lib.cvsclient.event.TerminationEvent;
 
public abstract class BasicCVSListener implements CVSListener
{
/**
* Stores a tagged line
*/
private final StringBuffer taggedLine = new StringBuffer();
 
/**
* Called when the server wants to send a message to be displayed to
* the user. The message is only for information purposes and clients
* can choose to ignore these messages if they wish.
* @param e the event
*/
public void messageSent(MessageEvent e)
{
String line = e.getMessage();
PrintStream stream = e.isError() ? System.err
: System.out;
 
if (e.isTagged())
{
String message = e.parseTaggedMessage(taggedLine, line);
// if we get back a non-null line, we have something
// to output. Otherwise, there is more to come and we
// should do nothing yet.
if (message != null)
{
//stream.println("Message: " + message);
}
}
else
{
//stream.println("Message: " + line);
}
}
 
@Override
public void commandTerminated(TerminationEvent arg0) {
}
 
@Override
public void fileAdded(FileAddedEvent arg0) {
}
 
@Override
public void fileInfoGenerated(FileInfoEvent arg0) {
FileInfoContainer info = arg0.getInfoContainer();
LogInformation info2 = (LogInformation) info;
System.out.println(info2.getRepositoryFilename());
System.out.println(info2.getDescription());
}
 
@Override
public void fileRemoved(FileRemovedEvent arg0) {
// TODO Auto-generated method stub
}
 
@Override
public void fileToRemove(FileToRemoveEvent arg0) {
// TODO Auto-generated method stub
}
 
@Override
public void fileUpdated(FileUpdatedEvent arg0) {
// TODO Auto-generated method stub
}
 
@Override
public void messageSent(BinaryMessageEvent arg0) {
// TODO Auto-generated method stub
}
 
@Override
public void moduleExpanded(ModuleExpansionEvent arg0) {
// TODO Auto-generated method stub
}
}
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/xservices/trunk/src/java/net/brutex/xservices/util/CVSClient.java
0,0 → 1,94
/*
* Copyright 2012 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
package net.brutex.xservices.util;
 
import java.io.File;
 
 
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.netbeans.lib.cvsclient.Client;
import org.netbeans.lib.cvsclient.admin.StandardAdminHandler;
import org.netbeans.lib.cvsclient.command.CommandAbortedException;
import org.netbeans.lib.cvsclient.command.GlobalOptions;
import org.netbeans.lib.cvsclient.connection.AuthenticationException;
import org.netbeans.lib.cvsclient.connection.PServerConnection;
 
public class CVSClient {
private final File configfile;
private final PServerConnection connection;
private final CVSRoot root;
private final GlobalOptions globalOptions;
public final Client client;
public CVSClient(File config) throws CommandAbortedException, AuthenticationException, ConfigurationException {
 
if (config == null || !config.exists() || config.isDirectory())
throw new ConfigurationException("Config file not found");
this.configfile = config;
Configuration configuration = new PropertiesConfiguration(configfile);
 
String cvsroot = configuration.getString("CVSROOT");
String workdir = configuration.getString("WORKDIR");
String password = configuration.getString("PASSWORD");
this.root = new CVSRoot(cvsroot);
this.globalOptions = new GlobalOptions();
globalOptions.setCVSRoot(cvsroot);
this.connection = new PServerConnection();
connection.setUserName(root.user);
if (password != null) {
connection.setEncodedPassword(CvsPassword.encode(password));
} else {
connection.setEncodedPassword(password);
}
 
connection.setHostName(root.host);
connection.setRepository(root.repository);
connection.open();
 
this.client = new Client(connection, new StandardAdminHandler());
client.setLocalPath(workdir);
}
/**
* @return
*/
public File getConfigFile() {
return this.configfile;
}
public GlobalOptions getGlobalOptions() {
return this.globalOptions;
}
/**
* @return the connection
*/
public PServerConnection getConnection() {
return connection;
}
/**
* @return the root
*/
public CVSRoot getRoot() {
return root;
}
}
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/xservices/trunk/src/java/net/brutex/xservices/util/CvsPassword.java
0,0 → 1,125
/*
* Copyright 2012 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
package net.brutex.xservices.util;
/*
* Copyright 2010 Andrew Kroh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
 
 
/**
* A simple class for encoding and decoding passwords for CVS pserver protocol.
* Can be used to recover forgotten passwords.
*
* <p>
* Adapted from: http://blog.zmeeagain.com/2005/01/recover-cvs-pserver-passwords.html
*/
public class CvsPassword
{
private static final char[] LOOKUP_TABLE =
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 114, 120, 53,
79, 0, 109, 72, 108, 70, 64, 76, 67, 116, 74, 68, 87, 111, 52, 75,
119, 49, 34, 82, 81, 95, 65, 112, 86, 118, 110, 122, 105, 41, 57,
83, 43, 46, 102, 40, 89, 38, 103, 45, 50, 42, 123, 91, 35, 125, 55,
54, 66, 124, 126, 59, 47, 92, 71, 115, 78, 88, 107, 106, 56, 0,
121, 117, 104, 101, 100, 69, 73, 99, 63, 94, 93, 39, 37, 61, 48,
58, 113, 32, 90, 44, 98, 60, 51, 33, 97, 62, 77, 84, 80, 85};
 
/**
* Encodes a CVS password to be used in .cvspass file. Throws an exception
* if clearText is null, if a character is found outside the 0 - 126 range, or
* if within the range, one of the non-allowed characters.
*
* @param clearText
* the password in clear to be encoded
*
* @return the encoded cvs password
*/
public static String encode(String clearText)
{
// First character of encoded version is A:
char[] encoded = new char[clearText.length() + 1];
encoded[0] = 'A';
// Skip the first character:
int counter = 1;
for (char c : clearText.toCharArray())
{
if (c == '`' || c == '$' || c < 32)
{
throw new IllegalArgumentException(
"Illegal character was found in clear password.");
}
encoded[counter++] = LOOKUP_TABLE[c];
}
 
return String.valueOf(encoded);
}
 
/**
* Recovers an encoded via pserver protocol CVS password.
*
* @param encodedPassword
* the encoded password to be decoded
*
* @return the decoded password or null if the input was
* null or empty
*/
public static String decode(String encodedPassword)
{
String rtn = null;
if (encodedPassword != null && encodedPassword.length() > 0)
{
if (encodedPassword.startsWith("A"))
{
rtn = encode(encodedPassword.substring(1)).substring(1);
}
else
{
rtn = encode(encodedPassword).substring(1);
}
}
return rtn;
}
public static void main(String[] sArgs)
{
final String TEST_WORD = "i07w91";
String encoded = CvsPassword.encode(TEST_WORD);
System.out.println("Encoded: <" + encoded + ">");
String decoded = CvsPassword.decode(encoded);
System.out.println("Decoded: <" + decoded + ">");
System.out.println(decoded.equals(TEST_WORD) ? "Test Passed" : "Test Failed");
}
}
 
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/xservices/trunk/src/java/net/brutex/xservices/util/XServicesDocumentation.java
0,0 → 1,73
/*
* Copyright 2011 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
package net.brutex.xservices.util;
 
/**
* Holds static documentation.
*
*
* @author Brian Rosenberger, bru@brutex.de
*/
public class XServicesDocumentation {
 
public static final String BRUTEX_COPYRIGHT = "" +
"/*\n" +
"* Copyright 2010 Brian Rosenberger (Brutex Network)\n" +
"*\n" +
"* Licensed under the Apache License, Version 2.0 (the \"License\")\n" +
"* you may not use this file except in compliance with the License.\n" +
"* You may obtain a copy of the License at\n" +
"*\n" +
"* http://www.apache.org/licenses/LICENSE-2.0\n" +
"*\n" +
"* Unless required by applicable law or agreed to in writing, software\n" +
"* distributed under the License is distributed on an \"AS IS\" BASIS,\n" +
"* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +
"* See the License for the specific language governing permissions and\n" +
"* limitations under the License.\n" +
"*/";
 
 
public static final String SERVICE_OPERATION_DOWNLOADFILE = "Download a file from the maschine where the service is running in order " +
"to process it with the client. The file is either downloaded as a MTOM attachment or " +
"as inline base64 encoded block. Keep in mind that unless you are using MTOM, a lot of " +
"java heap memory is used.";
public static final String SERVICE_OPERATION_ENCODEFILE = "Encodes a file.";
public static final String SERVICE_OPERATION_UPLOADFILE = "Send a file from client to web service server using either " +
"MTOM attachment or base64 inline attachment.";
public static final String SERVICE_OPERATION_COPY = "Copies a fileset locally on the server.";
public static final String SERVICE_OPERATION_COPYFILE = "Copies a single file locally on the server";
public static final String SERVICE_OPERATION_LOADRESOURCE = "Load the content of a resource";
public static final String SERVICE_OPERATION_LOADRESOURCEFROMARCHIVE = "Load the content of a resource";
public static final String SERVICE_OPERATION_ECHOTOFILE = "Write or append a string to a file";
public static final String SERVICE_OPERATION_REPLACEINFILE = "Replaces every <pattern> with a string in an ascii file";
public static final String SERVICE_OPERATION_REPLACEINFILE2 = "Replaces every <pattern> with a string in an ascii file";
public static final String SERVICE_OPERATION_REPLACEINFILEREGEX = "Replaces every <regex pattern> with a string in an ascii file";
private XServicesDocumentation() {};
}
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/xservices/trunk/src/java/net/brutex/xservices/util/RunTask.java
0,0 → 1,101
/*
* Copyright 2010 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.brutex.xservices.util;
 
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import net.brutex.xservices.types.ReturnCode;
import net.brutex.xservices.types.ant.AntProperty;
 
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.listener.TimestampedLogger;
import org.apache.tools.ant.taskdefs.Echo;
 
/**
*
* @author Brian Rosenberger, bru@brutex.de
*/
public class RunTask {
 
Project antproject;
Target anttarget;
Task anttask;
ByteArrayOutputStream myout = new ByteArrayOutputStream();
ByteArrayOutputStream myerr = new ByteArrayOutputStream();
PrintStream out = new PrintStream(myout);
PrintStream err = new PrintStream(myerr);
TimestampedLogger log = null;
 
public RunTask(Task anttask) {
 
antproject = new Project();
antproject.init();
antproject.setBasedir(System.getProperty("java.io.tmpdir"));
log = new TimestampedLogger();
log.setOutputPrintStream(out);
log.setErrorPrintStream(err);
log.setMessageOutputLevel(Echo.EchoLevel.WARN.getLevel());
 
antproject.addBuildListener(log);
 
anttarget = new Target();
anttarget.setName("XBridgeNGDynamicTarget");
anttarget.setProject(antproject);
antproject.addTarget(anttarget);
 
this.anttask = anttask;
prepareTask();
}
 
private void prepareTask()
throws BuildException {
anttask.init();
anttask.setProject(antproject);
anttask.setOwningTarget(anttarget);
anttarget.addTask(anttask);
antproject.addOrReplaceTarget(anttarget);
}
 
/**
* @return ReturnCode type {@link ReturnCode}
* @throws BuildException
*/
public ReturnCode postTask() throws BuildException {
int returnCode = 0;
Map<String, String> origMap = new HashMap<String, String>();
Map<String, String> newMap = null;
origMap.putAll(antproject.getProperties());
antproject.executeTarget(anttarget.getName());
newMap = antproject.getProperties();
newMap.putAll(antproject.getUserProperties());
for (Map.Entry<String, String> e : origMap.entrySet()) {
newMap.remove(e.getKey());
}
 
//anttask.execute();
return new ReturnCode(returnCode,
myout.toString(),
myerr.toString(),
AntProperty.createAntPropertyList(newMap));
 
}
}
/xservices/trunk/src/java/net/brutex/xservices/util/BrutexHSQLQuartzConnectionProvider.java
0,0 → 1,181
/*
* Copyright 2011 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
package net.brutex.xservices.util;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.quartz.utils.ConnectionProvider;
 
/**
* @author Brian Rosenberger
*
*/
public class BrutexHSQLQuartzConnectionProvider implements ConnectionProvider {
private Connection conn = null;
private final Logger logger = Logger.getLogger(this.getClass().getCanonicalName());
 
public Connection getConnection() throws SQLException {
if( conn!= null && conn.isValid(5)) {
logger.debug("Checking tables on pre-exisiting database connection.");
checkTables();
return conn;
}
try {
// Class.forName("org.hsqldb.jdbc.JDBCDriver" );
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch (Exception e) {
logger.fatal("Failed to load Derby JDBC driver.");
e.printStackTrace();
return null;
}
 
if(isConnected(false)) {
checkTables();
} else {
return null;
}
return conn;
}
 
public void shutdown() throws SQLException {
try {
// Class.forName("org.hsqldb.jdbc.JDBCDriver" );
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch (Exception e) {
System.err.println("ERROR: failed to load Derby JDBC driver.");
e.printStackTrace();
return;
}
String t = this.getClass().getClassLoader().getResource("/").toString()
.substring(6);
t += "../data/db";
System.out.println("Shut down embedded database now.");
Connection c = DriverManager.getConnection("jdbc:derby:" + t
+ ";shutdown=true;");
 
}
 
private synchronized void recursiveDelete(File dbDir) {
File[] files = dbDir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
files[i].delete();
} else {
recursiveDelete(files[i]);
files[i].delete();
}
}
dbDir.delete();
}
private synchronized void checkTables() throws SQLException {
logger.debug("Checking QUARTZ database schema.");
if(!isConnected(false)) {
logger.error("Failed to validate QUARTZ database schema.");
return;
}
List<String> ddl_list = new ArrayList<String>(11);
ddl_list.add("QRTZ_JOB_DETAILS");
ddl_list.add("QRTZ_TRIGGERS");
ddl_list.add("QRTZ_SIMPLE_TRIGGERS");
ddl_list.add("QRTZ_CRON_TRIGGERS");
ddl_list.add("QRTZ_SIMPROP_TRIGGERS");
ddl_list.add("QRTZ_BLOB_TRIGGERS");
ddl_list.add("QRTZ_CALENDARS");
ddl_list.add("QRTZ_PAUSED_TRIGGER_GRPS");
ddl_list.add("QRTZ_FIRED_TRIGGERS");
ddl_list.add("QRTZ_SCHEDULER_STATE");
ddl_list.add("QRTZ_LOCKS");
String ddl = this.getClass().getClassLoader().getResource("/").toString()
.substring(6)+ "../data/";
 
DatabaseMetaData dmd = conn.getMetaData();
for (String tbl : ddl_list) {
ResultSet rs = dmd.getTables(null, "APP", tbl, null);
if (!rs.next()) {
logger.log(Level.INFO, "Adding DDL for table "+ tbl);
Statement st = conn.createStatement();
File ddlFile = new File(ddl + tbl + ".ddl");
String create = "";
try {
BufferedReader r = new BufferedReader(new FileReader(ddlFile));
while (r.ready()) {
create += r.readLine() + "\n";
}
create.trim();
if( st.execute(create)) {
logger.log(Level.INFO, "Table " + tbl + " created.");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
logger.log(Level.ERROR, "Error executing statement "+ create );
System.out.println(ex.getMessage());
}
} else {
logger.trace("Table "+tbl+" exists.");
}
}
}
private synchronized boolean isConnected(boolean fail) throws SQLException {
if(conn!=null && conn.isValid(5)) {
return true;
} else {
String t = this.getClass().getClassLoader().getResource("/").toString().substring(6); // WEB-INF/classes
t += "../data/db";
logger.debug("Database directory is set to '" + t + "'");
try {
this.conn = DriverManager.getConnection("jdbc:derby:" + t + ";create=true;");
} catch (SQLException ex) {
logger.error(ex.getMessage(), ex);
if(!fail) {
logger.warn("Deleting database directory.");
recursiveDelete(new File(t));
logger.warn("Retrying to connect to database.");
return isConnected(true);
} else {
return false;
}
}
}
return false;
}
}
 
 
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/xservices/trunk/src/java/net/brutex/xservices/util/BrutexQuartzConnectionProvider.java
0,0 → 1,181
/*
* Copyright 2011 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
package net.brutex.xservices.util;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.quartz.utils.ConnectionProvider;
 
/**
* @author Brian Rosenberger
*
*/
public class BrutexQuartzConnectionProvider implements ConnectionProvider {
private Connection conn = null;
private final Logger logger = Logger.getLogger(this.getClass().getCanonicalName());
 
public Connection getConnection() throws SQLException {
if( conn!= null && conn.isValid(5)) {
logger.debug("Checking tables on pre-exisiting database connection.");
checkTables();
return conn;
}
try {
// Class.forName("org.hsqldb.jdbc.JDBCDriver" );
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch (Exception e) {
logger.fatal("Failed to load Derby JDBC driver.");
e.printStackTrace();
return null;
}
 
if(isConnected(false)) {
checkTables();
} else {
return null;
}
return conn;
}
 
public void shutdown() throws SQLException {
try {
// Class.forName("org.hsqldb.jdbc.JDBCDriver" );
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch (Exception e) {
System.err.println("ERROR: failed to load Derby JDBC driver.");
e.printStackTrace();
return;
}
String t = this.getClass().getClassLoader().getResource("/").toString()
.substring(6);
t += "../data/db";
System.out.println("Shut down embedded database now.");
Connection c = DriverManager.getConnection("jdbc:derby:" + t
+ ";shutdown=true;");
 
}
 
private synchronized void recursiveDelete(File dbDir) {
File[] files = dbDir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
files[i].delete();
} else {
recursiveDelete(files[i]);
files[i].delete();
}
}
dbDir.delete();
}
private synchronized void checkTables() throws SQLException {
logger.debug("Checking QUARTZ database schema.");
if(!isConnected(false)) {
logger.error("Failed to validate QUARTZ database schema.");
return;
}
List<String> ddl_list = new ArrayList<String>(11);
ddl_list.add("QRTZ_JOB_DETAILS");
ddl_list.add("QRTZ_TRIGGERS");
ddl_list.add("QRTZ_SIMPLE_TRIGGERS");
ddl_list.add("QRTZ_CRON_TRIGGERS");
ddl_list.add("QRTZ_SIMPROP_TRIGGERS");
ddl_list.add("QRTZ_BLOB_TRIGGERS");
ddl_list.add("QRTZ_CALENDARS");
ddl_list.add("QRTZ_PAUSED_TRIGGER_GRPS");
ddl_list.add("QRTZ_FIRED_TRIGGERS");
ddl_list.add("QRTZ_SCHEDULER_STATE");
ddl_list.add("QRTZ_LOCKS");
String ddl = this.getClass().getClassLoader().getResource("/").toString()
.substring(6)+ "../data/";
 
DatabaseMetaData dmd = conn.getMetaData();
for (String tbl : ddl_list) {
ResultSet rs = dmd.getTables(null, "APP", tbl, null);
if (!rs.next()) {
logger.log(Level.INFO, "Adding DDL for table "+ tbl);
Statement st = conn.createStatement();
File ddlFile = new File(ddl + tbl + ".ddl");
String create = "";
try {
BufferedReader r = new BufferedReader(new FileReader(ddlFile));
while (r.ready()) {
create += r.readLine() + "\n";
}
create.trim();
if( st.execute(create)) {
logger.log(Level.INFO, "Table " + tbl + " created.");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
logger.log(Level.ERROR, "Error executing statement "+ create );
System.out.println(ex.getMessage());
}
} else {
logger.trace("Table "+tbl+" exists.");
}
}
}
private synchronized boolean isConnected(boolean fail) throws SQLException {
if(conn!=null && conn.isValid(5)) {
return true;
} else {
String t = this.getClass().getClassLoader().getResource("/").toString().substring(6); // WEB-INF/classes
t += "../data/db";
logger.debug("Database directory is set to '" + t + "'");
try {
this.conn = DriverManager.getConnection("jdbc:derby:" + t + ";create=true;");
} catch (SQLException ex) {
logger.error(ex.getMessage(), ex);
if(!fail) {
logger.warn("Deleting database directory.");
recursiveDelete(new File(t));
logger.warn("Retrying to connect to database.");
return isConnected(true);
} else {
return false;
}
}
}
return false;
}
}
 
 
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/xservices/trunk/src/java/net/brutex/xservices/util/JobWrapper.java
0,0 → 1,96
/*
* Copyright 2011 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
package net.brutex.xservices.util;
 
import java.io.Serializable;
import java.util.Date;
 
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
 
/**
* Wrapper for jobs that can be executed through quartz scheduler.
*
* @author Brian Rosenberger, bru@brutex.de
* @since 0.5.0
*
*/
public class JobWrapper implements Job, Serializable {
 
public void execute(JobExecutionContext jcontext)
throws JobExecutionException {
try {
 
System.out.println("Executing scheduled job '"+jcontext.getJobDetail().getKey().getName()+"' at " + new Date());
 
JobDataMap jdMap = jcontext.getJobDetail().getJobDataMap();
String script = jdMap.getString("script");
 
// Create and enter a Context. A Context stores information about
// the execution environment of a script.
Context cx = Context.enter();
cx.setOptimizationLevel(0);
cx.setLanguageVersion(Context.VERSION_1_7);
// cx is the Context instance you're using to run scripts
/*
* cx.setClassShutter(new ClassShutter() { public boolean
* visibleToScripts(String className) {
* if(className.startsWith("adapter")) return true;
* if(className.startsWith("java.lang.System") ||
* className.startsWith
* ("org.apache.tomcat.util.log.SystemLogHandler")) return true;
* System.out.println(className + " is blocked."); return false; }
* });
*/
 
// Initialise the standard objects (Object, Function, etc.). This
// must be done before scripts can be
// executed. The null parameter tells initStandardObjects
// to create and return a scope object that we use
// in later calls.
Scriptable scope = cx.initStandardObjects();
//Object wrappedOut = Context.javaToJS(System.out, scope);
//Object wrappedOut2 = Context.javaToJS(this, scope);
//scope.put("out", scope, wrappedOut);
//scope.put("exe", scope, wrappedOut2);
 
// Execute the script
// cx.evaluateString(scope, "importClass('java.lang.System');\n",
// "head", 1, null);
// cx.evaluateString(scope, "importPackage('java.util');\n", "head",
// 2, null);
Object obj = cx
.evaluateString(scope, script, "TestScript", 1, null);
 
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
// Exit the Context. This removes the association between the
// Context and the current thread and is an
// essential cleanup action. There should be a call to exit for
// every call to enter.
Context.exit();
}
 
}
}
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/xservices/trunk/src/java/net/brutex/xservices/util/BrutexNamespaces.java
0,0 → 1,54
/*
* Copyright 2010 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
package net.brutex.xservices.util;
 
/**
* Holds static namespace information.
*
*
* @author Brian Rosenberger, bru@brutex.de
*/
public class BrutexNamespaces {
 
/**
* Brutex Network XServices web service name space declaration
*/
public static final String WS_XSERVICES = "http://ws.xservices.brutex.net";
/**
* Copyright and license agreement statement.
*/
public static final String BRUTEX_COPYRIGHT = "" +
"/*\n" +
"* Copyright 2010 Brian Rosenberger (Brutex Network)\n" +
"*\n" +
"* Licensed under the Apache License, Version 2.0 (the \"License\")\n" +
"* you may not use this file except in compliance with the License.\n" +
"* You may obtain a copy of the License at\n" +
"*\n" +
"* http://www.apache.org/licenses/LICENSE-2.0\n" +
"*\n" +
"* Unless required by applicable law or agreed to in writing, software\n" +
"* distributed under the License is distributed on an \"AS IS\" BASIS,\n" +
"* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +
"* See the License for the specific language governing permissions and\n" +
"* limitations under the License.\n" +
"*/";
 
 
private BrutexNamespaces() {};
}
/xservices/trunk/src/java/net/brutex/xservices/util/UnRarTask.java
0,0 → 1,74
/*
* Copyright 2010 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
package net.brutex.xservices.util;
 
import de.innosystec.unrar.Archive;
import de.innosystec.unrar.exception.RarException;
import de.innosystec.unrar.rarfile.FileHeader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
 
/**
*
* @author Brian Rosenberger, bru@brutex.de
*/
public class UnRarTask extends Task {
 
private File dst = null;
private File src = null;
 
public File getDst() {
return dst;
}
 
public void setDst(File dst) {
this.dst = dst;
}
 
public File getSrc() {
return src;
}
 
public void setSrc(File src) {
this.src = src;
}
 
 
@Override
public void execute() {
if(src==null ) throw new BuildException("Please supply a source archive file.");
if(!src.exists()) throw new BuildException("Archive '"+src.getName()+"' does not exist.");
 
try {
if(dst==null) dst = new File(src.getParent());
Archive ar = new Archive(src);
List<FileHeader> list = ar.getFileHeaders();
for(FileHeader h : list) {
ar.extractFile(h, new FileOutputStream(new File(dst.getAbsolutePath()+"/"+h.getFileNameString())));
}
} catch (RarException ex) {
throw new BuildException(ex.getMessage(), ex);
} catch (IOException ex) {
throw new BuildException(ex.getMessage(), ex);
}
}
 
}