|
From: <dav...@us...> - 2011-12-28 18:00:50
|
Revision: 1298
http://cishell.svn.sourceforge.net/cishell/?rev=1298&view=rev
Author: david-coe
Date: 2011-12-28 18:00:43 +0000 (Wed, 28 Dec 2011)
Log Message:
-----------
Initial import.
This is a prototype for using a webservice interface to interact with CIShell services.
Added Paths:
-----------
trunk/testing/org.cishell.testing.webapp/.classpath
trunk/testing/org.cishell.testing.webapp/.project
trunk/testing/org.cishell.testing.webapp/.settings/
trunk/testing/org.cishell.testing.webapp/.settings/org.eclipse.jdt.core.prefs
trunk/testing/org.cishell.testing.webapp/.settings/org.eclipse.pde.core.prefs
trunk/testing/org.cishell.testing.webapp/META-INF/
trunk/testing/org.cishell.testing.webapp/META-INF/MANIFEST.MF
trunk/testing/org.cishell.testing.webapp/README.html
trunk/testing/org.cishell.testing.webapp/README.txt
trunk/testing/org.cishell.testing.webapp/bin/
trunk/testing/org.cishell.testing.webapp/build.properties
trunk/testing/org.cishell.testing.webapp/libs/
trunk/testing/org.cishell.testing.webapp/libs/CIShell.war
trunk/testing/org.cishell.testing.webapp/libs/bridge.war
trunk/testing/org.cishell.testing.webapp/src/
trunk/testing/org.cishell.testing.webapp/src/org/
trunk/testing/org.cishell.testing.webapp/src/org/cishell/
trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/
trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/
trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/Activator.java
trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ConvertServlet.java
trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ListFiles.java
trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ReturnFile.java
trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/UploadFile.java
trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/utilities/
trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/utilities/WebAppLogger.java
Added: trunk/testing/org.cishell.testing.webapp/.classpath
===================================================================
--- trunk/testing/org.cishell.testing.webapp/.classpath (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/.classpath 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
Added: trunk/testing/org.cishell.testing.webapp/.project
===================================================================
--- trunk/testing/org.cishell.testing.webapp/.project (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/.project 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.cishell.testing.webapp</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
+ </natures>
+</projectDescription>
Added: trunk/testing/org.cishell.testing.webapp/.settings/org.eclipse.jdt.core.prefs
===================================================================
--- trunk/testing/org.cishell.testing.webapp/.settings/org.eclipse.jdt.core.prefs (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/.settings/org.eclipse.jdt.core.prefs 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,8 @@
+#Fri Dec 16 10:50:57 EST 2011
+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
Added: trunk/testing/org.cishell.testing.webapp/.settings/org.eclipse.pde.core.prefs
===================================================================
--- trunk/testing/org.cishell.testing.webapp/.settings/org.eclipse.pde.core.prefs (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/.settings/org.eclipse.pde.core.prefs 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,5 @@
+#Fri Dec 16 10:50:57 EST 2011
+eclipse.preferences.version=1
+pluginProject.equinox=false
+pluginProject.extensions=false
+resolve.requirebundle=false
Added: trunk/testing/org.cishell.testing.webapp/META-INF/MANIFEST.MF
===================================================================
--- trunk/testing/org.cishell.testing.webapp/META-INF/MANIFEST.MF (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/META-INF/MANIFEST.MF 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,22 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: WebBundle
+Bundle-SymbolicName: org.cishell.testing.webapp
+Bundle-Version: 1.0.0
+Bundle-Activator: org.cishell.testing.webapp.Activator
+Import-Package: javax.servlet;version="2.5.0",
+ javax.servlet.http;version="2.5.0",
+ org.apache.commons.fileupload;version="1.2.2",
+ org.apache.commons.fileupload.disk;version="1.2.2",
+ org.apache.commons.fileupload.servlet;version="1.2.2",
+ org.cishell.framework;version="1.0.0",
+ org.cishell.framework.algorithm;version="1.0.0",
+ org.cishell.framework.data;version="1.0.0",
+ org.cishell.service.conversion;version="1.0.0",
+ org.cishell.utilities,
+ org.osgi.framework;version="1.3.0",
+ org.osgi.service.http;version="1.2.0",
+ org.osgi.service.log;version="1.3.0",
+ org.osgi.util.tracker;version="1.3.3"
+Bundle-RequiredExecutionEnvironment: J2SE-1.5
+X-AutoStart: true
Added: trunk/testing/org.cishell.testing.webapp/README.html
===================================================================
--- trunk/testing/org.cishell.testing.webapp/README.html (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/README.html 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,23 @@
+To get the demo running on your own machine:<br>
+<ul>
+ <li>Basic Test Setup<br></li>
+ <ul><li>Get the war file called bridge.war from <a href="http://www.eclipse.org/equinox/server/http_in_container.php" target="_blank">here</a>.</li>
+ <li>Extract it into webapps in Tomcat or whatever you choose to use<br></li>
+ <li>Test it by visiting <a href="http://localhost/bridge/sp_test" target="_blank">http://localhost/bridge/sp_<wbr>test</a></li></ul><li>Real Setup</li>
+ <ul><li>Use the cishell.war file found in the libs and launch your servlet container (e.g. Tomcat)</li>
+ <li> Export the org.cishell.testing.webapp as a "deployable plugin or fragment" to the /cishell/WEB-INF/eclipse/plugins folder</li><li>Change the config.ini file in /CIShell/WEB-INF/eclipse/<wbr>configuration/ to include:</li>
+ <ul><li>osgi.bundles=org.eclipse.<wbr>equinox.common@2:start,
+ org.eclipse.update.<wbr>configurator@start,
+ org.eclipse.equinox.http.<wbr>servletbridge@start,
+ org.eclipse.equinox.http.<wbr>registry@start, org.cishell.testing.webapp@start,
+ edu.iu.nwb.converter.nwb@start<wbr>, org.eclipse.equinox.ds@start,
+ org.eclipse.osgi.services@<wbr>start, org.eclipse.equinox.metatype@<wbr>start,
+ org.eclipse.equinox.log@start, org.cishell.reference.<wbr>services@start,
+ edu.iu.nwb.converter.<wbr>nwbgraphml@start</li></ul>
+ <li>Edit /CIShell/WEB-INF/web.xml to remove the console if you desire.</li>
+ <li>To apply the changes:</li>
+ <ul>
+ <li>visit <a href="http://localhost/CIShell/sp_stop" target="_blank">http://localhost/CIShell/sp_<wbr>stop</a>, then <a href="http://localhost/CIShell/sp_undeploy" target="_blank">http://localhost/CIShell/sp_<wbr>undeploy</a> to stop and remove the old stuff</li>
+ <li>visit <a href="http://localhost/CIShell/sp_deploy" target="_blank">http://localhost/CIShell/sp_<wbr>deploy</a>, then <a href="http://localhost/CIShell/sp_start" target="_blank">http://localhost/CIShell/sp_<wbr>start</a> to copy from the new eclipse and start again.</li>
+ </ul>
+ <li>visit <a href="http://localhost/CIShell/upload" target="_blank">http://localhost/CIShell/upload</a> to verify everything works.</li>
\ No newline at end of file
Added: trunk/testing/org.cishell.testing.webapp/README.txt
===================================================================
--- trunk/testing/org.cishell.testing.webapp/README.txt (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/README.txt 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,16 @@
+To get the demo running on your own machine:
+
+ Basic Test Setup
+ Get the war file called bridge.war from http://www.eclipse.org/equinox/server/http_in_container.php.
+ Extract it into webapps in Tomcat or whatever you choose to use
+ Test it by visiting http://localhost/bridge/sp_test
+ Real Setup
+ Use the cishell.war file found in the libs and launch your servlet container (e.g. Tomcat)
+ Export the org.cishell.testing.webapp as a "deployable plugin or fragment" to the /CIShell/WEB-INF/eclipse/plugins folder
+ Change the config.ini file in /CIShell/WEB-INF/eclipse/configuration/ to include:
+ osgi.bundles=org.eclipse.equinox.common@2:start, org.eclipse.update.configurator@start, org.eclipse.equinox.http.servletbridge@start, org.eclipse.equinox.http.registry@start, org.cishell.testing.webapp@start, edu.iu.nwb.converter.nwb@start, org.eclipse.equinox.ds@start, org.eclipse.osgi.services@start, org.eclipse.equinox.metatype@start, org.eclipse.equinox.log@start, org.cishell.reference.services@start, edu.iu.nwb.converter.nwbgraphml@start
+ Edit /CIShell/WEB-INF/web.xml to remove the console if you desire.
+ To apply the changes:
+ visit http://localhost/CIShell/sp_stop, then http://localhost/CIShell/sp_undeploy to stop and remove the old stuff
+ visit http://localhost/CIShell/sp_deploy, then http://localhost/CIShell/sp_start to copy from the new eclipse and start again.
+ visit http://localhost/CIShell/upload to verify everything works.
\ No newline at end of file
Added: trunk/testing/org.cishell.testing.webapp/build.properties
===================================================================
--- trunk/testing/org.cishell.testing.webapp/build.properties (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/build.properties 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,4 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .
Added: trunk/testing/org.cishell.testing.webapp/libs/CIShell.war
===================================================================
(Binary files differ)
Property changes on: trunk/testing/org.cishell.testing.webapp/libs/CIShell.war
___________________________________________________________________
Added: svn:mime-type
+ application/octet-stream
Added: trunk/testing/org.cishell.testing.webapp/libs/bridge.war
===================================================================
(Binary files differ)
Property changes on: trunk/testing/org.cishell.testing.webapp/libs/bridge.war
___________________________________________________________________
Added: svn:mime-type
+ application/octet-stream
Added: trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/Activator.java
===================================================================
--- trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/Activator.java (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/Activator.java 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,83 @@
+package org.cishell.testing.webapp;
+
+import org.cishell.testing.webapp.utilities.WebAppLogger;
+import org.cishell.utilities.FileUtilities;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.http.HttpService;
+import org.osgi.service.log.LogService;
+import org.osgi.util.tracker.ServiceTracker;
+
+/**
+ * This bundle activates several servlets that then are bound to html links on
+ * the server. The can be accessed in the general form [host]/CIShell/...
+ *
+ * @author dmcoe
+ *
+ */
+public class Activator implements BundleActivator {
+ public static final String WEBAPP_ROOT_URL = "/CIShell";
+ public static final String FILE_DIRECTORY = FileUtilities.getDefaultTemporaryDirectory();
+
+ private HttpServiceTracker httpServiceTracker;
+
+ public void start(BundleContext bundleContext) throws Exception {
+
+ httpServiceTracker = new HttpServiceTracker(bundleContext);
+ httpServiceTracker.open();
+
+ WebAppLogger logger = WebAppLogger.getInstance(bundleContext);
+ logger.writeToLog("Webservice interface has been started.",
+ LogService.LOG_INFO);
+
+ }
+
+ public void stop(BundleContext bundleContext) throws Exception {
+
+ httpServiceTracker.close();
+ httpServiceTracker = null;
+ }
+
+ public class HttpServiceTracker extends ServiceTracker<HttpService, HttpService> {
+
+ public HttpServiceTracker(BundleContext context) {
+ super(context, HttpService.class.getName(), null);
+ }
+
+ public HttpService addingService(ServiceReference<HttpService> reference) {
+ HttpService httpService = super.addingService(reference);
+ if (httpService == null) {
+ return null;
+ }
+
+ try {
+ httpService.registerServlet(ConvertServlet.CONVERT_FILE_URL,
+ new ConvertServlet(context), null, null);
+ httpService.registerServlet(UploadFile.UPLOAD_FILE_URL,
+ new UploadFile(context), null, null);
+ httpService.registerServlet(ListFiles.LIST_FILES_URL,
+ new ListFiles(), null, null);
+ httpService.registerServlet(ReturnFile.RETURN_FILE_URL,
+ new ReturnFile(), null, null);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return httpService;
+ }
+
+ public void removedService(ServiceReference<HttpService> reference,
+ HttpService service) {
+ HttpService httpService = service;
+ httpService.unregister(ConvertServlet.CONVERT_FILE_URL);
+ httpService.unregister(UploadFile.UPLOAD_FILE_URL);
+ httpService.unregister(ListFiles.LIST_FILES_URL);
+ httpService.unregister(ReturnFile.RETURN_FILE_URL);
+ super.removedService(reference, service);
+ }
+
+ }
+
+}
Added: trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ConvertServlet.java
===================================================================
--- trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ConvertServlet.java (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ConvertServlet.java 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,324 @@
+package org.cishell.testing.webapp;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Writer;
+import java.text.ParseException;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.cishell.framework.algorithm.Algorithm;
+import org.cishell.framework.algorithm.AlgorithmExecutionException;
+import org.cishell.framework.algorithm.AlgorithmFactory;
+import org.cishell.framework.data.BasicData;
+import org.cishell.framework.data.Data;
+import org.cishell.service.conversion.ConversionException;
+import org.cishell.service.conversion.DataConversionService;
+import org.cishell.testing.webapp.utilities.WebAppLogger;
+import org.cishell.utilities.AlgorithmNotFoundException;
+import org.cishell.utilities.AlgorithmUtilities;
+import org.cishell.utilities.FileCopyingException;
+import org.cishell.utilities.FileUtilities;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.log.LogService;
+import org.osgi.util.tracker.ServiceTracker;
+
+/**
+ * A servlet for converting files uploaded to the server to a different type.
+ * Currently it is hard coded to convert to GraphML. The path for accessing
+ * should be something like [host]/cishell/convert?filename=FILENAME.nwb
+ *
+ * @author dmcoe
+ *
+ */
+public class ConvertServlet extends HttpServlet {
+ private BundleContext context;
+
+ public static final String RETURN_FILE_DIRECTORY = Activator.FILE_DIRECTORY;
+ public static final String CONVERT_FILE_URL = "/convert";
+ public static final String CONVERT_FILE_URL_GET_PARAMETER = "filename";
+ private File fileDir;
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Construct a ConvertServlet.
+ *
+ * @param context
+ * The bundlecontext for the servelet.
+ */
+ public ConvertServlet(BundleContext context) {
+ this.context = context;
+ }
+
+ /**
+ * This will build a paragraph element with a link in HTML that links to the
+ * conversion service for the given filename.
+ *
+ * @param filename
+ * The file's name that will be converted.
+ * @return An html
+ * <p>
+ * with a link to the conversion service.
+ */
+ public static String conversionParagraphLink(String filename) {
+ String html = "<p><a href=\"" + Activator.WEBAPP_ROOT_URL
+ + CONVERT_FILE_URL + "?" + CONVERT_FILE_URL_GET_PARAMETER + "="
+ + filename + "\">Convert this to GraphML</a></p>";
+ return html;
+ }
+
+ public void init(ServletConfig config) throws ServletException {
+
+ fileDir = new File(RETURN_FILE_DIRECTORY);
+ if (!fileDir.isDirectory()) {
+ throw new ServletException(RETURN_FILE_DIRECTORY
+ + " is not a directory");
+ }
+
+ }
+
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
+ throws ServletException, IOException {
+ WebAppLogger logger = WebAppLogger.getInstance(context);
+
+ resp.setContentType("text/html");
+ Writer out = resp.getWriter();
+ out.write("<html><head></head><body>");
+ String errors = "";
+ String outHTML = "";
+ String filename = req.getParameter("filename");
+ File file = openFile(filename);
+ if (file.exists()) {
+ try {
+ Data[] data = validateFile(file);
+ Data datum = data[0];
+ outHTML += "<p>Your file is of type " + datum.getFormat()
+ + ".</p>";
+
+ // TODO get this information from the user
+ String fileFormat = "file:text/graphml+xml";
+
+ try {
+ Data convertedData = convertData(datum, fileFormat);
+ if (convertedData != null) {
+ outHTML += "<p>Your data was successfully converted to "
+ + convertedData.getFormat() + "</p>";
+ File savedConvertedFile = saveData(convertedData);
+ if (savedConvertedFile != null) {
+ outHTML += "<p>Your converted data was saved.</p>";
+
+ outHTML += "<p>"
+ + ReturnFile
+ .returnFileLink(savedConvertedFile
+ .getName()) + "</p>";
+ }
+ } else {
+ errors += "<p>The Conversion Service is not running. "
+ + "Your file could not be converted.</p>";
+ }
+ } catch (ConversionException e) {
+ logger.writeToLog(
+ "The conversion failed: " + e.getMessage(),
+ LogService.LOG_ERROR);
+ errors += "<p>Conversion to " + fileFormat
+ + " failed because " + e.getMessage() + "</p>";
+ }
+
+ } catch (AlgorithmExecutionException e) {
+ logger.writeToLog("Your file was not of a valid type",
+ LogService.LOG_ERROR);
+ errors += "<p>Your file was not of a valid type.</p>";
+ }
+ } else {
+ logger.writeToLog("The file \"" + file.getAbsolutePath()
+ + "\" does not exist", LogService.LOG_ERROR);
+ errors += "<p>Your file could not be located.</p>";
+ }
+
+ if (errors == "") {
+ out.write(outHTML);
+ } else {
+ out.write(errors);
+ }
+ out.write("</body></html>");
+ }
+
+ /**
+ * Write the data out to a file.
+ *
+ * @param data
+ * The data to be written to disk.
+ * @return The file object of the written data.
+ * @throws IOException
+ */
+ private File saveData(Data data) throws IOException {
+ File dataFile = (File) data.getData();
+
+ File targetFile = new File(RETURN_FILE_DIRECTORY, dataFile.getName());
+
+ try {
+ FileUtilities.copyFile(dataFile, targetFile);
+ } catch (FileCopyingException e) {
+ throw new IOException(e.getMessage());
+ }
+
+ return targetFile;
+ }
+
+ /**
+ * Convert the data from one format to another.
+ *
+ * @param data
+ * The data you would like converted
+ * @param fileFormat
+ * The string file format of the target data
+ * @return The converted data or null if no conversion service was running.
+ * @throws ConversionException
+ */
+ private Data convertData(Data data, String fileFormat)
+ throws ConversionException {
+
+ if (data.getFormat() == fileFormat) {
+ return data;
+ }
+
+ WebAppLogger logger = WebAppLogger.getInstance(context);
+
+ ServiceTracker<DataConversionService, DataConversionService> conversionServiceTracker =
+ new ServiceTracker<DataConversionService, DataConversionService>(
+ context, DataConversionService.class.getName(), null);
+
+ conversionServiceTracker.open();
+
+ DataConversionService conversionService = conversionServiceTracker
+ .getService();
+
+ if (conversionService == null) {
+ logger.writeToLog("The Conversion Service is not running.",
+ LogService.LOG_ERROR);
+ throw new ConversionException(
+ "The Conversion Service is not running.");
+ }
+
+ Data convertedData = conversionService.convert(data, fileFormat);
+
+ /**
+ * FIXME this can be removed when the conversion service's convert bug
+ * is fixed. There is an issue where if a converter cannot be found, the
+ * input data will be returned. This is no acceptable.
+ */
+ if (convertedData.getFormat() == data.getFormat()) {
+ logger.writeToLog("No conversion chain was found to sastisfy converting from "
+ + data.getFormat() + " to " + fileFormat,
+ LogService.LOG_ERROR);
+ throw new ConversionException(
+ "No conversion chain was found to sastisfy converting from "
+ + data.getFormat() + " to " + fileFormat);
+ }
+
+ conversionServiceTracker.close();
+ return convertedData;
+ }
+
+ /**
+ * This will return a query string that will return validators that can
+ * validate the file extension.
+ *
+ * @param fileExtension
+ * The file extension of the file you wish to be validated.
+ * @return A query that will find validators.
+ */
+ private String buildValidatorQuery(String fileExtension) {
+ String validatorsQuery = "(& (type=validator)" + "(|"
+ + "(in_data=file-ext:" + fileExtension + ")"
+ + "(also_validates=" + fileExtension + ")" + "))";
+ return validatorsQuery;
+ }
+
+ /**
+ * Using a file object, this looks for a validator based on the file
+ * extension.
+ *
+ * @param file
+ * The file to be validated.
+ * @return A data[] representing the data the file contained.
+ * @throws AlgorithmExecutionException
+ */
+ private Data[] validateFile(File file) throws AlgorithmExecutionException {
+ WebAppLogger logger = WebAppLogger.getInstance(context);
+
+ // A dummy data[] must be setup for the validator to work.
+ Data[] validationData = new Data[] { new BasicData(file.getPath(),
+ String.class.getName()) };
+
+ try {
+ String fileExtension = getFileExtension(file.getPath());
+
+ String validatorsQuery = buildValidatorQuery(fileExtension);
+
+ try {
+ // Get the validator based on the file extension
+ AlgorithmFactory validatorFactory = AlgorithmUtilities
+ .getAlgorithmFactoryByFilter(validatorsQuery, context);
+
+ Algorithm validator = validatorFactory.createAlgorithm(
+ validationData, null, null);
+
+ Data[] validatedData = validator.execute();
+ logger.writeToLog("Loaded: " + file.getPath(),
+ LogService.LOG_INFO);
+ return validatedData;
+ } catch (AlgorithmExecutionException e) {
+ logger.writeToLog(
+ "Your data could not be validated: " + e.getMessage(),
+ LogService.LOG_ERROR);
+ throw e;
+ } catch (AlgorithmNotFoundException e) {
+ logger.writeToLog(e.getMessage(), LogService.LOG_ERROR);
+ throw new AlgorithmExecutionException(e.getMessage());
+ }
+ } catch (ParseException e) {
+ logger.writeToLog(e.getMessage(), LogService.LOG_ERROR);
+ throw new AlgorithmExecutionException(e.getMessage());
+ }
+
+ }
+
+ public File openFile(String filename) {
+ File file = new File(fileDir.getPath() + File.separator + filename);
+
+ return file;
+ }
+
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ doGet(request, response);
+ }
+
+ /**
+ * Get the file extension from the file represented as filePath.
+ *
+ * e.g. C:/temp/thisIsAFile.xml -> xml
+ *
+ * @param filePath
+ * The file path.
+ * @return The extension of the file.
+ * @throws ParseException
+ */
+ private static String getFileExtension(String filePath) throws ParseException {
+ int periodPosition = filePath.lastIndexOf(".");
+ int extensionStart = periodPosition + 1;
+ if ((periodPosition != -1) && ((extensionStart) < filePath.length())) {
+ return filePath.substring(extensionStart);
+ } else {
+
+ throw new ParseException("There is no file extension for " + filePath, periodPosition);
+ }
+ }
+}
Added: trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ListFiles.java
===================================================================
--- trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ListFiles.java (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ListFiles.java 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,53 @@
+package org.cishell.testing.webapp;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Writer;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * A servlet for listing all the files in the directory. Clicking on them will
+ * allow the files to be downloaded. The path for accessing should be something
+ * like [host]/cishell/files
+ *
+ * @author dmcoe
+ *
+ */
+public class ListFiles extends HttpServlet {
+
+ private static final String DIRECTORY_PATH = Activator.FILE_DIRECTORY;
+ public static final String LIST_FILES_URL = "/files";
+ private File destinationDirectory;
+
+ private static final long serialVersionUID = 1L;
+
+ public void init(ServletConfig config) throws ServletException {
+ super.init(config);
+
+ destinationDirectory = new File(DIRECTORY_PATH);
+ if (!destinationDirectory.isDirectory()) {
+ throw new ServletException(DIRECTORY_PATH + " is not a directory");
+ }
+ }
+
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+ response.setContentType("text/html");
+ Writer outHtml = response.getWriter();
+ outHtml.write("<html><body><h1>Files</h1>");
+
+ // Write out the html for downloading all the files found
+ for (String filename : destinationDirectory.list()) {
+ outHtml.write("<p>" + ReturnFile.returnFileLink(filename) + "</p>");
+ }
+
+ outHtml.write("</body></html>");
+
+ }
+
+}
Added: trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ReturnFile.java
===================================================================
--- trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ReturnFile.java (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/ReturnFile.java 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,112 @@
+package org.cishell.testing.webapp;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.Writer;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * A servlet for downloading files from the server. The path for accessing
+ * should be something like [host]/cishell/download_file?filename=FILENAME
+ *
+ * @author dmcoe
+ *
+ */
+public class ReturnFile extends HttpServlet {
+
+ private static final long serialVersionUID = 1L;
+ public static final String RETURN_FILE_URL = "/download_file";
+ private static final String RETURN_FILE_URL_GET_PARAMETER = "filename";
+ private static final String DIRECTORY_PATH = Activator.FILE_DIRECTORY;
+
+ private File directory;
+
+ public void init(ServletConfig config) throws ServletException {
+ super.init(config);
+
+ // This would be cool, save it at {server root}/DIR_PATH
+ // TODO Use once tomcat is working
+ // String realPath = getServletContext().getRealPath(DIR_PATH);
+
+ directory = new File(DIRECTORY_PATH);
+ if (!directory.isDirectory()) {
+ throw new ServletException(DIRECTORY_PATH + " is not a directory");
+ }
+ }
+
+ public void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ String filename = request.getParameter(RETURN_FILE_URL_GET_PARAMETER);
+
+ File file = new File(directory.getPath() + File.separatorChar
+ + filename);
+
+ if (file.exists() && !file.isDirectory()) {
+ PrintWriter out = null;
+ BufferedInputStream buf = null;
+
+ response.setContentLength((int) file.length());
+ response.setHeader("Content-Disposition", "attachment; filename=\""
+ + filename + "\"");
+
+ try {
+ out = response.getWriter();
+
+ // Read the file in and output it
+ buf = new BufferedInputStream(new FileInputStream(file));
+ int readBytes = 0;
+ while ((readBytes = buf.read()) != -1) {
+ out.write(readBytes);
+ }
+ } catch (IOException e) {
+ throw new ServletException(e.getMessage());
+ } finally {
+ if (out != null) {
+ out.close();
+ }
+ if (buf != null) {
+ buf.close();
+ }
+ }
+ } else {
+ response.setContentType("text/html");
+ Writer outHtml = response.getWriter();
+ outHtml.write("<html><body>");
+ outHtml.write("<p>There is no such file as " + filename);
+ outHtml.write("</body></html>");
+ }
+
+ }
+
+ public void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ doGet(request, response);
+ }
+
+ /**
+ * An html link that would download the given filename.
+ *
+ * @param filename
+ * The filename of the file to be downloaded
+ *
+ * @return Return an html link in string form
+ */
+ public static String returnFileLink(String filename) {
+ String html = "<a href=\"" + Activator.WEBAPP_ROOT_URL
+ + RETURN_FILE_URL + "?" + RETURN_FILE_URL_GET_PARAMETER + "="
+ + filename + "\">" + filename + "</a>";
+ return html;
+ }
+
+
+}
Added: trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/UploadFile.java
===================================================================
--- trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/UploadFile.java (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/UploadFile.java 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,156 @@
+package org.cishell.testing.webapp;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.Writer;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileUploadException;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.cishell.testing.webapp.utilities.WebAppLogger;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.log.LogService;
+
+/**
+ * A servlet that allows files to be uploaded to the server. The path for
+ * accessing should be something like [host]/cishell/upload
+ *
+ * @author dmcoe
+ *
+ */
+public class UploadFile extends HttpServlet {
+ public static final int MAX_SIZE_UNTIL_DISK = 1 * 1024 * 1024; // 1MB
+ private BundleContext context;
+
+ private static final String FINAL_DIRECTORY_PATH = Activator.FILE_DIRECTORY;
+ private static final String TEMP_DIRECTORY_PATH = FINAL_DIRECTORY_PATH
+ + File.separator + "tmp";
+ public static final String UPLOAD_FILE_URL = "/upload";
+ private File tempDir;
+ private File destinationDir;
+
+ private static final long serialVersionUID = 1L;
+
+ public UploadFile(BundleContext context) {
+ this.context = context;
+ }
+
+ public void init(ServletConfig config) throws ServletException {
+ super.init(config);
+
+ tempDir = new File(TEMP_DIRECTORY_PATH);
+
+ if (tempDir.exists() && !tempDir.isDirectory()) {
+ throw new ServletException(TEMP_DIRECTORY_PATH
+ + " is not a directory");
+ } else if (!tempDir.exists()) {
+ tempDir.mkdir();
+ }
+
+ // This would be cool, save it at {server root}/DESTINATION_DIR_PATH
+ // String realPath =
+ // getServletContext().getRealPath(DESTINATION_DIR_PATH);
+
+ destinationDir = new File(FINAL_DIRECTORY_PATH);
+ if (!destinationDir.isDirectory()) {
+ throw new ServletException(FINAL_DIRECTORY_PATH
+ + " is not a directory");
+ }
+
+ }
+
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
+ throws ServletException, IOException {
+ resp.setContentType("text/html");
+ Writer outHTML = resp.getWriter();
+
+ // Create the upload form
+ outHTML.write("<html><head></head> <body>"
+ + "<p>Commons File Upload Example</p>"
+ + "<form action=\"\" enctype=\"multipart/form-data\" method=\"POST\">"
+ + "<select name=\"converter\"> <option value=\"nwb\">anytoall</option></select>"
+ + "<input type=\"file\" name=\"file1\"><br>"
+ + "<input type=\"Submit\" value=\"Upload File\"><br>"
+ + "</form>" + "</body></html>");
+ outHTML.close();
+
+ }
+
+ protected void doPost(HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ WebAppLogger logger = WebAppLogger.getInstance(context);
+
+ response.setContentType("text/html");
+ PrintWriter outHTML = response.getWriter();
+ outHTML.println("<h1>Your Data</h1>");
+
+ DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
+ /*
+ * Set the size threshold, above which content will be stored on disk.
+ */
+ fileItemFactory.setSizeThreshold(MAX_SIZE_UNTIL_DISK);
+ /*
+ * Set the temporary directory to store the uploaded files of size above
+ * threshold.
+ */
+ fileItemFactory.setRepository(tempDir);
+ ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
+ try {
+ /*
+ * Parse the request
+ */
+ List<?> items = uploadHandler.parseRequest(request);
+ Iterator<?> iterator = items.iterator();
+ while (iterator.hasNext()) {
+ FileItem item = (FileItem) iterator.next();
+ /*
+ * Handle Form Fields.
+ */
+ if (item.isFormField()) {
+ outHTML.println("File Name = " + item.getFieldName()
+ + ", Value = " + item.getString());
+ } else {
+ // Handle Uploaded files.
+ outHTML.println("Field Name = " + item.getFieldName()
+ + ", File Name = " + item.getName()
+ + ", Content type = " + item.getContentType()
+ + ", File Size = " + item.getSize());
+ /*
+ * Write file to the ultimate location.
+ */
+ File file = new File(destinationDir, item.getName());
+ item.write(file);
+
+ outHTML.println("<p>"
+ + ReturnFile.returnFileLink(file.getName())
+ + "</p>");
+
+ outHTML.println(ConvertServlet.conversionParagraphLink(file
+ .getName()));
+ }
+ }
+
+ } catch (FileUploadException ex) {
+ logger.writeToLog("Error encountered while parsing the request",
+ LogService.LOG_ERROR);
+ log("Error encountered while parsing the request", ex);
+ } catch (Exception ex) {
+ logger.writeToLog(
+ "Error encountered while uploading file: "
+ + ex.getMessage(), LogService.LOG_ERROR);
+ log("Error encountered while uploading file", ex);
+ }
+
+ outHTML.close();
+ }
+}
\ No newline at end of file
Added: trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/utilities/WebAppLogger.java
===================================================================
--- trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/utilities/WebAppLogger.java (rev 0)
+++ trunk/testing/org.cishell.testing.webapp/src/org/cishell/testing/webapp/utilities/WebAppLogger.java 2011-12-28 18:00:43 UTC (rev 1298)
@@ -0,0 +1,53 @@
+package org.cishell.testing.webapp.utilities;
+
+import org.osgi.framework.BundleContext;
+import org.osgi.service.log.LogService;
+import org.osgi.util.tracker.ServiceTracker;
+
+public final class WebAppLogger {
+ private static WebAppLogger instance;
+ private ServiceTracker<LogService, LogService> logServiceTracker;
+
+ private WebAppLogger(BundleContext context) {
+ logServiceTracker = new ServiceTracker<LogService, LogService>(
+ context, LogService.class.getName(), null);
+ logServiceTracker.open();
+ }
+
+ public static WebAppLogger getInstance(BundleContext context) {
+ if (instance == null) {
+ instance = new WebAppLogger(context);
+ }
+
+ return instance;
+ }
+
+ protected void finalize() throws Throwable {
+ super.finalize();
+ logServiceTracker.close();
+ logServiceTracker = null;
+ }
+
+ /**
+ * Write the message out to the log at the specified level. It will either
+ * use the log service if it is found or system out for debugging.
+ *
+ * @param message
+ * Human readable string describing the condition or null.
+ * @param logLevel
+ * The severity of the message. This should be one of the defined
+ * log levels but may be any integer that is interpreted in a
+ * user defined way.
+ */
+ public void writeToLog(String message, int logLevel) {
+ LogService log = logServiceTracker.getService();
+ if (log != null) {
+ log.log(logLevel, message);
+ } else {
+ System.out
+ .println("Error: No log service running.\n\tLog message: ["
+ + logLevel + "] " + message);
+ }
+ }
+
+}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|