Modified: lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/TaskManager.java
URL: http://svn.apache.org/viewvc/lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/TaskManager.java?rev=617035&r1=617034&r2=617035&view=diff
==============================================================================
--- lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/TaskManager.java (original)
+++ lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/TaskManager.java Wed Jan 30 23:44:03 2008
@@ -14,130 +14,102 @@
* limitations under the License.
*
*/
-
/* $Id$ */
-
package org.apache.lenya.cms.task;
-
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
-import org.apache.log4j.Category;
+import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
-
public class TaskManager implements Configurable {
- private static Category log = Category.getInstance(TaskManager.class);
- public static final String TASK_ELEMENT = "task";
- public static final String TASK_ID_ATTRIBUTE = "id";
- public static final String CONFIGURATION_FILE =
- File.separator
- + "config"
- + File.separator
- + "tasks"
- + File.separator
- + "tasks.xconf";
-
- // maps task-ids to tasks
- private Map tasks = new HashMap();
-
- /**
- * Creates a new TaskManager object.
- */
- public TaskManager() {
- }
-
- /**
- * Creates a new instance of TaskManager
- *
- * @param publicationPath path to publication
- * @throws ConfigurationException if the configuration failed.
- * @throws SAXException when parsing the config file failed.
- * @throws IOException when an I/O error occured.
- */
- public TaskManager(String publicationPath)
- throws ConfigurationException, SAXException, IOException {
- String configurationFilePath = publicationPath + CONFIGURATION_FILE;
- log.debug("Loading tasks: " + configurationFilePath);
-
- File configurationFile = new File(configurationFilePath);
-
- if (configurationFile.isFile()) {
- DefaultConfigurationBuilder builder =
- new DefaultConfigurationBuilder();
- Configuration configuration =
- builder.buildFromFile(configurationFile);
- configure(configuration);
-
- } else {
- log.info(
- "Task configuration not loaded - file ["
- + configurationFile.getAbsolutePath()
- + "] does not exist.");
- }
- tasks.put(EMTPY_TASK, new EmptyTask());
- tasks.put(ANT_TASK, new AntTask());
- }
-
- public static final String EMTPY_TASK = "empty";
- public static final String ANT_TASK = "ant";
-
- /**
- * DOCUMENT ME!
- *
- * @param configuration DOCUMENT ME!
- *
- * @throws ConfigurationException DOCUMENT ME!
- */
- public void configure(Configuration configuration)
- throws ConfigurationException {
- log.debug("Creating tasks:");
-
- // create task list
- Configuration[] taskConfigurations =
- configuration.getChildren(TASK_ELEMENT);
-
- // set task IDs
- for (int i = 0; i < taskConfigurations.length; i++) {
- String taskId =
- taskConfigurations[i].getAttribute(TASK_ID_ATTRIBUTE);
- log.debug("Creating task '" + taskId + "'");
-
- Task task =
- TaskFactory.getInstance().createTask(taskConfigurations[i]);
- tasks.put(taskId, task);
- }
- }
-
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
- public String[] getTaskIds() {
- return (String[]) tasks.keySet().toArray(new String[tasks.size()]);
- }
-
- /**
- * Get the task with a given task-id
- *
- * @param taskId the task-id of the requested task
- *
- * @return the task
- *
- * @throws ExecutionException if there is no task with the given task-id.
- */
- public Task getTask(String taskId) throws ExecutionException {
- if (!tasks.containsKey(taskId)) {
- throw new ExecutionException(
- "Task with ID '" + taskId + "' not found!");
- }
-
- return (Task) tasks.get(taskId);
- }
+ private static Logger log = Logger.getLogger(TaskManager.class);
+ public static final String TASK_ELEMENT = "task";
+ public static final String TASK_ID_ATTRIBUTE = "id";
+ public static final String CONFIGURATION_FILE = File.separator + "config" + File.separator + "tasks" + File.separator + "tasks.xconf";
+ // maps task-ids to tasks
+ private Map tasks = new HashMap();
+ /**
+ * Creates a new TaskManager object.
+ */
+ public TaskManager() {
+ }
+ /**
+ * Creates a new instance of TaskManager
+ *
+ * @param publicationPath
+ * path to publication
+ * @throws ConfigurationException
+ * if the configuration failed.
+ * @throws SAXException
+ * when parsing the config file failed.
+ * @throws IOException
+ * when an I/O error occured.
+ */
+ public TaskManager(String publicationPath) throws ConfigurationException, SAXException, IOException {
+ String configurationFilePath = publicationPath + CONFIGURATION_FILE;
+ log.debug("Loading tasks: " + configurationFilePath);
+ File configurationFile = new File(configurationFilePath);
+ if(configurationFile.isFile()){
+ DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
+ Configuration configuration = builder.buildFromFile(configurationFile);
+ configure(configuration);
+ }else{
+ log.info("Task configuration not loaded - file [" + configurationFile.getAbsolutePath() + "] does not exist.");
+ }
+ tasks.put(EMTPY_TASK, new EmptyTask());
+ tasks.put(ANT_TASK, new AntTask());
+ }
+ public static final String EMTPY_TASK = "empty";
+ public static final String ANT_TASK = "ant";
+ /**
+ * DOCUMENT ME!
+ *
+ * @param configuration
+ * DOCUMENT ME!
+ *
+ * @throws ConfigurationException
+ * DOCUMENT ME!
+ */
+ public void configure(Configuration configuration) throws ConfigurationException {
+ log.debug("Creating tasks:");
+ // create task list
+ Configuration[] taskConfigurations = configuration.getChildren(TASK_ELEMENT);
+ // set task IDs
+ for(int i = 0; i < taskConfigurations.length; i++){
+ String taskId = taskConfigurations[i].getAttribute(TASK_ID_ATTRIBUTE);
+ log.debug("Creating task '" + taskId + "'");
+ Task task = TaskFactory.getInstance().createTask(taskConfigurations[i]);
+ tasks.put(taskId, task);
+ }
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String[] getTaskIds() {
+ return (String[]) tasks.keySet().toArray(new String[tasks.size()]);
+ }
+ /**
+ * Get the task with a given task-id
+ *
+ * @param taskId
+ * the task-id of the requested task
+ *
+ * @return the task
+ *
+ * @throws ExecutionException
+ * if there is no task with the given task-id.
+ */
+ public Task getTask(String taskId) throws ExecutionException {
+ if(!tasks.containsKey(taskId)){
+ throw new ExecutionException("Task with ID '" + taskId + "' not found!");
+ }
+ return (Task) tasks.get(taskId);
+ }
}
Modified: lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/TaskSequence.java
URL: http://svn.apache.org/viewvc/lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/TaskSequence.java?rev=617035&r1=617034&r2=617035&view=diff
==============================================================================
--- lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/TaskSequence.java (original)
+++ lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/TaskSequence.java Wed Jan 30 23:44:03 2008
@@ -14,130 +14,114 @@
* limitations under the License.
*
*/
-
/* $Id$ */
-
package org.apache.lenya.cms.task;
-
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.parameters.Parameters;
-import org.apache.log4j.Category;
-
-
+import org.apache.log4j.Logger;
/**
* A TaskSequence contains of multiple tasks that are executed successively.
*/
public class TaskSequence extends AbstractTask {
- private static Category log = Category.getInstance(TaskSequence.class);
-
- // keeps the task order
- private Task[] tasks;
- private TaskManager taskManager;
-
- /**
- * DOCUMENT ME!
- *
- * @param configuration DOCUMENT ME!
- *
- * @throws ConfigurationException DOCUMENT ME!
- */
- public void init(Configuration configuration) throws ConfigurationException {
- taskManager = new TaskManager();
- taskManager.configure(configuration);
-
- // create task list
- Configuration[] taskConfigurations = configuration.getChildren(TaskManager.TASK_ELEMENT);
- tasks = new Task[taskConfigurations.length];
-
- // set task IDs
- for (int i = 0; i < tasks.length; i++) {
- String taskId = taskConfigurations[i].getAttribute(TaskManager.TASK_ID_ATTRIBUTE);
-
- try {
- tasks[i] = taskManager.getTask(taskId);
- } catch (ExecutionException e) {
- throw new ConfigurationException("Sequence initialization failed: ", e);
+ private static Logger log = Logger.getLogger(TaskSequence.class);
+ // keeps the task order
+ private Task[] tasks;
+ private TaskManager taskManager;
+ /**
+ * DOCUMENT ME!
+ *
+ * @param configuration
+ * DOCUMENT ME!
+ *
+ * @throws ConfigurationException
+ * DOCUMENT ME!
+ */
+ public void init(Configuration configuration) throws ConfigurationException {
+ taskManager = new TaskManager();
+ taskManager.configure(configuration);
+ // create task list
+ Configuration[] taskConfigurations = configuration.getChildren(TaskManager.TASK_ELEMENT);
+ tasks = new Task[taskConfigurations.length];
+ // set task IDs
+ for(int i = 0; i < tasks.length; i++){
+ String taskId = taskConfigurations[i].getAttribute(TaskManager.TASK_ID_ATTRIBUTE);
+ try{
+ tasks[i] = taskManager.getTask(taskId);
+ }catch(ExecutionException e){
+ throw new ConfigurationException("Sequence initialization failed: ", e);
+ }
+ log.debug("Adding task '" + taskId + "' to sequence.");
+ }
+ }
+ /**
+ * Returns the tasks in this sequence.
+ *
+ * @return DOCUMENT ME!
+ */
+ public Task[] getTasks() {
+ return (Task[]) tasks.clone();
+ }
+ /**
+ * Returns the TaskManager that is used to manage the tasks of this TaskSequence.
+ *
+ * @return DOCUMENT ME!
+ */
+ protected TaskManager getTaskManager() {
+ return taskManager;
+ }
+ /**
+ * Returns the ID of a specific Task.
+ *
+ * @param task
+ * the specific task for which the task id is requested.
+ *
+ * @return the task id of the given task
+ *
+ * @throws ExecutionException
+ * if the task could not be found.
+ */
+ public String getTaskId(Task task) throws ExecutionException {
+ String[] taskIds = getTaskManager().getTaskIds();
+ for(int j = 0; j < taskIds.length; j++){
+ if(getTaskManager().getTask(taskIds[j]) == task){
+ return taskIds[j];
+ }
+ }
+ throw new IllegalStateException("Task-ID for " + task + " not found!");
+ }
+ /**
+ * Executes the tasks.
+ *
+ * @param path
+ * DOCUMENT ME!
+ *
+ * @throws ExecutionException
+ * if the execution fails
+ */
+ public void execute(String path) throws ExecutionException {
+ try{
+ Task[] tasks = getTasks();
+ for(int i = 0; i < tasks.length; i++){
+ Task task = tasks[i];
+ String taskId = getTaskId(task);
+ log.debug("Executing task '" + taskId + "'");
+ // create task parameters
+ Parameters taskParameters = new Parameters();
+ String[] names = getParameters().getNames();
+ for(int parIndex = 0; parIndex < names.length; parIndex++){
+ String name = names[parIndex];
+ boolean useParameter = true;
+ if(useParameter){
+ taskParameters.setParameter(name, getParameters().getParameter(name));
+ }
}
-
- log.debug("Adding task '" + taskId + "' to sequence.");
- }
- }
-
- /**
- * Returns the tasks in this sequence.
- *
- * @return DOCUMENT ME!
- */
- public Task[] getTasks() {
- return (Task[]) tasks.clone();
- }
-
- /**
- * Returns the TaskManager that is used to manage the tasks of this TaskSequence.
- *
- * @return DOCUMENT ME!
- */
- protected TaskManager getTaskManager() {
- return taskManager;
- }
-
- /**
- * Returns the ID of a specific Task.
- *
- * @param task the specific task for which the task id is requested.
- *
- * @return the task id of the given task
- *
- * @throws ExecutionException if the task could not be found.
- */
- public String getTaskId(Task task) throws ExecutionException {
- String[] taskIds = getTaskManager().getTaskIds();
-
- for (int j = 0; j < taskIds.length; j++) {
- if (getTaskManager().getTask(taskIds[j]) == task) {
- return taskIds[j];
- }
- }
-
- throw new IllegalStateException("Task-ID for " + task + " not found!");
- }
-
- /**
- * Executes the tasks.
- *
- * @param path DOCUMENT ME!
- *
- * @throws ExecutionException if the execution fails
- */
- public void execute(String path) throws ExecutionException {
- try {
- Task[] tasks = getTasks();
-
- for (int i = 0; i < tasks.length; i++) {
- Task task = tasks[i];
- String taskId = getTaskId(task);
- log.debug("Executing task '" + taskId + "'");
-
- // create task parameters
- Parameters taskParameters = new Parameters();
- String[] names = getParameters().getNames();
-
- for (int parIndex = 0; parIndex < names.length; parIndex++) {
- String name = names[parIndex];
- boolean useParameter = true;
-
- if (useParameter) {
- taskParameters.setParameter(name, getParameters().getParameter(name));
- }
- }
-
- // execute task
- task.parameterize(taskParameters);
- task.execute(path);
- }
- } catch (Exception e) {
- log.error("Cannot execute TaskSequence: ", e);
- }
- }
+ // execute task
+ task.parameterize(taskParameters);
+ task.execute(path);
+ }
+ }catch(Exception e){
+ log.error("Cannot execute TaskSequence: ", e);
+ }
+ }
}
Modified: lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/WorkflowInvoker.java
URL: http://svn.apache.org/viewvc/lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/WorkflowInvoker.java?rev=617035&r1=617034&r2=617035&view=diff
==============================================================================
--- lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/WorkflowInvoker.java (original)
+++ lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/cms/task/WorkflowInvoker.java Wed Jan 30 23:44:03 2008
@@ -14,13 +14,9 @@
* limitations under the License.
*
*/
-
/* $Id$ */
-
package org.apache.lenya.cms.task;
-
import java.util.Map;
-
import org.apache.lenya.ac.Identity;
import org.apache.lenya.ac.Machine;
import org.apache.lenya.ac.Role;
@@ -33,223 +29,187 @@
import org.apache.lenya.workflow.Event;
import org.apache.lenya.workflow.Situation;
import org.apache.lenya.workflow.SynchronizedWorkflowInstances;
-import org.apache.log4j.Category;
-
+import org.apache.log4j.Logger;
public class WorkflowInvoker extends ParameterWrapper {
-
- private static Category log = Category.getInstance(WorkflowInvoker.class);
-
- public static final String ROLES = "roles";
- public static final String USER_ID = "user-id";
- public static final String MACHINE = "machine";
- public static final String EVENT = "event";
-
- public static final String PREFIX = "workflow";
-
- public static final String EVENT_REQUEST_PARAMETER = "workflow.event";
- public static final String LENYA_EVENT_REQUEST_PARAMETER = "lenya.event";
-
- /**
- * Ctor.
- *
- * @param eventName
- * The event name.
- * @param identity
- * The identity.
- * @param roles
- * The roles.
- * @return A namespace map containing the parameters.
- */
- public static NamespaceMap extractParameters(
- String eventName,
- Identity identity,
- Role[] roles) {
- NamespaceMap parameters = new NamespaceMap(PREFIX);
- log.debug("Extractign workflow invoker parameters.");
- log.debug(" Event: [" + eventName + "]");
- parameters.put(EVENT, eventName);
- setRoles(parameters, roles);
- setIdentity(parameters, identity);
- return parameters;
- }
-
- /**
- * Ctor.
- *
- * @param parameters
- * A map containing the prefixed parameters.
- */
- public WorkflowInvoker(Map parameters) {
- super(parameters);
- }
-
- /**
- * Returns the role names.
- *
- * @return A string array.
- */
- protected String[] getRoleIDs() {
- String rolesString = get(ROLES);
- String[] roleIDs = rolesString.split(",");
- return roleIDs;
- }
-
- /**
- * Sets the roles.
- *
- * @param parameters
- * A workflow invoker namespace map.
- * @param roles
- * A role array.
- */
- public static void setRoles(NamespaceMap parameters, Role[] roles) {
-
- String roleString = "";
- for (int i = 0; i < roles.length; i++) {
- if (i > 0) {
- roleString += ",";
- }
- roleString += roles[i].getId();
- }
- parameters.put(ROLES, roleString);
- }
-
- /**
- * Sets the identity.
- *
- * @param parameters
- * A workflow invoker namespace map.
- * @param identity
- * An identity.
- */
- public static void setIdentity(NamespaceMap parameters, Identity identity) {
-
- String userId = "";
- User user = identity.getUser();
- if (user != null) {
- userId = user.getId();
- }
- parameters.put(USER_ID, userId);
-
- String machineIp = "";
- Machine machine = identity.getMachine();
- if (machine != null) {
- machineIp = machine.getIp();
- }
- parameters.put(MACHINE, machineIp);
- }
-
- /**
- * Returns the workflow event name.
- *
- * @return A string.
- */
- public String getEventName() {
- return get(EVENT);
- }
-
- /**
- * Returns the user ID.
- *
- * @return A string.
- */
- public String getUserId() {
- return get(USER_ID);
- }
-
- /**
- * Returns the machine IP address.
- *
- * @return A string.
- */
- public String getMachineIp() {
- return get(MACHINE);
- }
-
- private Document document;
- private boolean doTransition = false;
-
- /**
- * Initializes the workflow invoker.
- *
- * @param publication
- * The publication.
- * @param webappUrl
- * The webapp URL.
- * @throws ExecutionException
- * when something went wrong.
- */
- public void setup(Publication publication, String webappUrl) throws ExecutionException {
- String eventName = getEventName();
- if (eventName == null) {
- log.debug("No workflow event.");
- } else {
- log.debug("Workflow event: [" + eventName + "]");
- // check for workflow instance first (task can initialize the workflow history)
- WorkflowFactory factory = WorkflowFactory.newInstance();
- try {
- document = publication.getDocumentBuilder().buildDocument(publication, webappUrl);
- } catch (DocumentBuildException e) {
- throw new ExecutionException(e);
- }
- doTransition = factory.hasWorkflow(document);
- }
- }
-
- /**
- * Invokes the transition.
- *
- * @throws ExecutionException
- * when something went wrong.
- */
- public void invokeTransition() throws ExecutionException {
- if (doTransition) {
-
- try {
- WorkflowFactory factory = WorkflowFactory.newInstance();
- SynchronizedWorkflowInstances instance =
- factory.buildSynchronizedInstance(document);
- Situation situation =
- factory.buildSituation(getRoleIDs(), getUserId(), getMachineIp());
-
- Event event = null;
- Event[] events = instance.getExecutableEvents(situation);
-
- log.debug("Resolved executable events.");
-
- for (int i = 0; i < events.length; i++) {
- if (events[i].getName().equals(getEventName())) {
- event = events[i];
- }
- }
-
-// assert event != null;
-
- log.debug("Invoking transition.");
- instance.invoke(situation, event);
- log.debug("Invoking transition completed.");
-
- } catch (Exception e) {
- throw new ExecutionException(e);
- }
- }
-
- }
-
- /**
- * @see org.apache.lenya.cms.task.ParameterWrapper#getPrefix()
- */
- public String getPrefix() {
- return PREFIX;
- }
-
- /**
- * @see org.apache.lenya.cms.task.ParameterWrapper#getRequiredKeys()
- */
- protected String[] getRequiredKeys() {
- String[] keys = {
- };
- return keys;
- }
-
+ private static Logger log = Logger.getLogger(WorkflowInvoker.class);
+ public static final String ROLES = "roles";
+ public static final String USER_ID = "user-id";
+ public static final String MACHINE = "machine";
+ public static final String EVENT = "event";
+ public static final String PREFIX = "workflow";
+ public static final String EVENT_REQUEST_PARAMETER = "workflow.event";
+ public static final String LENYA_EVENT_REQUEST_PARAMETER = "lenya.event";
+ /**
+ * Ctor.
+ *
+ * @param eventName
+ * The event name.
+ * @param identity
+ * The identity.
+ * @param roles
+ * The roles.
+ * @return A namespace map containing the parameters.
+ */
+ public static NamespaceMap extractParameters(String eventName, Identity identity, Role[] roles) {
+ NamespaceMap parameters = new NamespaceMap(PREFIX);
+ log.debug("Extractign workflow invoker parameters.");
+ log.debug(" Event: [" + eventName + "]");
+ parameters.put(EVENT, eventName);
+ setRoles(parameters, roles);
+ setIdentity(parameters, identity);
+ return parameters;
+ }
+ /**
+ * Ctor.
+ *
+ * @param parameters
+ * A map containing the prefixed parameters.
+ */
+ public WorkflowInvoker(Map parameters) {
+ super(parameters);
+ }
+ /**
+ * Returns the role names.
+ *
+ * @return A string array.
+ */
+ protected String[] getRoleIDs() {
+ String rolesString = get(ROLES);
+ String[] roleIDs = rolesString.split(",");
+ return roleIDs;
+ }
+ /**
+ * Sets the roles.
+ *
+ * @param parameters
+ * A workflow invoker namespace map.
+ * @param roles
+ * A role array.
+ */
+ public static void setRoles(NamespaceMap parameters, Role[] roles) {
+ String roleString = "";
+ for(int i = 0; i < roles.length; i++){
+ if(i > 0){
+ roleString += ",";
+ }
+ roleString += roles[i].getId();
+ }
+ parameters.put(ROLES, roleString);
+ }
+ /**
+ * Sets the identity.
+ *
+ * @param parameters
+ * A workflow invoker namespace map.
+ * @param identity
+ * An identity.
+ */
+ public static void setIdentity(NamespaceMap parameters, Identity identity) {
+ String userId = "";
+ User user = identity.getUser();
+ if(user != null){
+ userId = user.getId();
+ }
+ parameters.put(USER_ID, userId);
+ String machineIp = "";
+ Machine machine = identity.getMachine();
+ if(machine != null){
+ machineIp = machine.getIp();
+ }
+ parameters.put(MACHINE, machineIp);
+ }
+ /**
+ * Returns the workflow event name.
+ *
+ * @return A string.
+ */
+ public String getEventName() {
+ return get(EVENT);
+ }
+ /**
+ * Returns the user ID.
+ *
+ * @return A string.
+ */
+ public String getUserId() {
+ return get(USER_ID);
+ }
+ /**
+ * Returns the machine IP address.
+ *
+ * @return A string.
+ */
+ public String getMachineIp() {
+ return get(MACHINE);
+ }
+ private Document document;
+ private boolean doTransition = false;
+ /**
+ * Initializes the workflow invoker.
+ *
+ * @param publication
+ * The publication.
+ * @param webappUrl
+ * The webapp URL.
+ * @throws ExecutionException
+ * when something went wrong.
+ */
+ public void setup(Publication publication, String webappUrl) throws ExecutionException {
+ String eventName = getEventName();
+ if(eventName == null){
+ log.debug("No workflow event.");
+ }else{
+ log.debug("Workflow event: [" + eventName + "]");
+ // check for workflow instance first (task can initialize the workflow history)
+ WorkflowFactory factory = WorkflowFactory.newInstance();
+ try{
+ document = publication.getDocumentBuilder().buildDocument(publication, webappUrl);
+ }catch(DocumentBuildException e){
+ throw new ExecutionException(e);
+ }
+ doTransition = factory.hasWorkflow(document);
+ }
+ }
+ /**
+ * Invokes the transition.
+ *
+ * @throws ExecutionException
+ * when something went wrong.
+ */
+ public void invokeTransition() throws ExecutionException {
+ if(doTransition){
+ try{
+ WorkflowFactory factory = WorkflowFactory.newInstance();
+ SynchronizedWorkflowInstances instance = factory.buildSynchronizedInstance(document);
+ Situation situation = factory.buildSituation(getRoleIDs(), getUserId(), getMachineIp());
+ Event event = null;
+ Event[] events = instance.getExecutableEvents(situation);
+ log.debug("Resolved executable events.");
+ for(int i = 0; i < events.length; i++){
+ if(events[i].getName().equals(getEventName())){
+ event = events[i];
+ }
+ }
+ // assert event != null;
+ log.debug("Invoking transition.");
+ instance.invoke(situation, event);
+ log.debug("Invoking transition completed.");
+ }catch(Exception e){
+ throw new ExecutionException(e);
+ }
+ }
+ }
+ /**
+ * @see org.apache.lenya.cms.task.ParameterWrapper#getPrefix()
+ */
+ public String getPrefix() {
+ return PREFIX;
+ }
+ /**
+ * @see org.apache.lenya.cms.task.ParameterWrapper#getRequiredKeys()
+ */
+ protected String[] getRequiredKeys() {
+ String[] keys = {};
+ return keys;
+ }
}
Modified: lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/IndexConfiguration.java
URL: http://svn.apache.org/viewvc/lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/IndexConfiguration.java?rev=617035&r1=617034&r2=617035&view=diff
==============================================================================
--- lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/IndexConfiguration.java (original)
+++ lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/IndexConfiguration.java Wed Jan 30 23:44:03 2008
@@ -14,162 +14,137 @@
* limitations under the License.
*
*/
-
/* $Id$ */
-
package org.apache.lenya.lucene;
-
import java.io.File;
-
import org.apache.lenya.xml.DOMUtil;
import org.apache.lenya.xml.DocumentHelper;
import org.apache.lenya.xml.XPath;
-import org.apache.log4j.Category;
+import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-
-
public class IndexConfiguration {
- static Category log = Category.getInstance(IndexConfiguration.class);
- private String configurationFilePath;
- private String update_index_type;
- private String index_dir;
- private String htdocs_dump_dir;
- private Class indexerClass;
-
- /**
- * Creates a new IndexConfiguration object.
- *
- * @param configurationFilePath DOCUMENT ME!
- */
- public IndexConfiguration(String configurationFilePath) {
- this.configurationFilePath = configurationFilePath;
-
- try {
- File configFile = new File(configurationFilePath);
- Document document = DocumentHelper.readDocument(configFile);
- configure(document.getDocumentElement());
- } catch (Exception e) {
- log.error("Cannot load publishing configuration! ", e);
- System.err.println("Cannot load publishing configuration! " + e);
- }
- }
-
- /**
- * DOCUMENT ME!
- *
- * @param args DOCUMENT ME!
- */
- public static void main(String[] args) {
- if (args.length != 1) {
- System.err.println("Usage: org.apache.lenya.lucene.IndexConfiguration lucene.xconf");
-
- return;
- }
-
- IndexConfiguration ic = new IndexConfiguration(args[0]);
- String parameter;
-
- parameter = ic.getUpdateIndexType();
- System.out.println("Index type: " + parameter);
-
- parameter = ic.getIndexDir();
- System.out.println("Index dir: " + parameter);
- System.out.println("Index dir (resolved): " + ic.resolvePath(parameter));
-
- parameter = ic.getHTDocsDumpDir();
- System.out.println("htdocs_dump: " + parameter);
- System.out.println("htdocs_dump (resolved): " + ic.resolvePath(parameter));
-
- System.out.println("Indexer class: " + ic.getIndexerClass());
- }
-
- /**
- * DOCUMENT ME!
- *
- * @param configuration DOCUMENT ME!
- *
- * @throws Exception DOCUMENT ME!
- */
- public void configure(Element root) throws Exception {
- DOMUtil du = new DOMUtil();
- update_index_type = du.getAttributeValue(root, new XPath("update-index/@type"));
- index_dir = du.getAttributeValue(root, new XPath("index-dir/@src"));
- htdocs_dump_dir = du.getAttributeValue(root, new XPath("htdocs-dump-dir/@src"));
-
- String indexerClassName = du.getAttributeValue(root, new XPath("indexer/@class"));
- indexerClass = Class.forName(indexerClassName);
- }
-
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
- public String getUpdateIndexType() {
- log.debug(".getUpdateIndexType(): " + update_index_type);
-
- return update_index_type;
- }
-
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
- public String getIndexDir() {
- log.debug(".getIndexDir(): " + index_dir);
-
- return index_dir;
- }
-
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
- public String getHTDocsDumpDir() {
- log.debug(".getHTDocsDumpDir(): " + htdocs_dump_dir);
-
- return htdocs_dump_dir;
- }
-
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
- public Class getIndexerClass() {
- log.debug(".getIndexerClass(): " + indexerClass);
-
- return indexerClass;
- }
-
- /**
- * DOCUMENT ME!
- *
- * @param path DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
- public String resolvePath(String path) {
-
- // nothing to do if we already have an absolute pathname
- if ( new File(path) .isAbsolute() ) {
- return path;
- }
-
- // from the Java API doc: "A canonical pathname is both absolute and unique."
- // however we may get an exception while converting a path to it's canonical form
- try {
- String configDir = new File(configurationFilePath) .getAbsoluteFile() .getParent();
- return new File(configDir, path) .getCanonicalPath();
-
- } catch (java.io.IOException e) {
- // FIXME: maybe this Exception should be thrown to the caller ?
- e.printStackTrace();
- return null;
- }
-
- }
+ private static Logger log = Logger.getLogger(IndexConfiguration.class);
+ private String configurationFilePath;
+ private String update_index_type;
+ private String index_dir;
+ private String htdocs_dump_dir;
+ private Class indexerClass;
+ /**
+ * Creates a new IndexConfiguration object.
+ *
+ * @param configurationFilePath
+ * DOCUMENT ME!
+ */
+ public IndexConfiguration(String configurationFilePath) {
+ this.configurationFilePath = configurationFilePath;
+ try{
+ File configFile = new File(configurationFilePath);
+ Document document = DocumentHelper.readDocument(configFile);
+ configure(document.getDocumentElement());
+ }catch(Exception e){
+ log.error("Cannot load publishing configuration! ", e);
+ System.err.println("Cannot load publishing configuration! " + e);
+ }
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param args
+ * DOCUMENT ME!
+ */
+ public static void main(String[] args) {
+ if(args.length != 1){
+ System.err.println("Usage: org.apache.lenya.lucene.IndexConfiguration lucene.xconf");
+ return;
+ }
+ IndexConfiguration ic = new IndexConfiguration(args[0]);
+ String parameter;
+ parameter = ic.getUpdateIndexType();
+ System.out.println("Index type: " + parameter);
+ parameter = ic.getIndexDir();
+ System.out.println("Index dir: " + parameter);
+ System.out.println("Index dir (resolved): " + ic.resolvePath(parameter));
+ parameter = ic.getHTDocsDumpDir();
+ System.out.println("htdocs_dump: " + parameter);
+ System.out.println("htdocs_dump (resolved): " + ic.resolvePath(parameter));
+ System.out.println("Indexer class: " + ic.getIndexerClass());
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param configuration
+ * DOCUMENT ME!
+ *
+ * @throws Exception
+ * DOCUMENT ME!
+ */
+ public void configure(Element root) throws Exception {
+ DOMUtil du = new DOMUtil();
+ update_index_type = du.getAttributeValue(root, new XPath("update-index/@type"));
+ index_dir = du.getAttributeValue(root, new XPath("index-dir/@src"));
+ htdocs_dump_dir = du.getAttributeValue(root, new XPath("htdocs-dump-dir/@src"));
+ String indexerClassName = du.getAttributeValue(root, new XPath("indexer/@class"));
+ indexerClass = Class.forName(indexerClassName);
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String getUpdateIndexType() {
+ log.debug(".getUpdateIndexType(): " + update_index_type);
+ return update_index_type;
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String getIndexDir() {
+ log.debug(".getIndexDir(): " + index_dir);
+ return index_dir;
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String getHTDocsDumpDir() {
+ log.debug(".getHTDocsDumpDir(): " + htdocs_dump_dir);
+ return htdocs_dump_dir;
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Class getIndexerClass() {
+ log.debug(".getIndexerClass(): " + indexerClass);
+ return indexerClass;
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param path
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String resolvePath(String path) {
+ // nothing to do if we already have an absolute pathname
+ if(new File(path).isAbsolute()){
+ return path;
+ }
+ // from the Java API doc: "A canonical pathname is both absolute and unique."
+ // however we may get an exception while converting a path to it's canonical form
+ try{
+ String configDir = new File(configurationFilePath).getAbsoluteFile().getParent();
+ return new File(configDir, path).getCanonicalPath();
+ }catch(java.io.IOException e){
+ // FIXME: maybe this Exception should be thrown to the caller ?
+ e.printStackTrace();
+ return null;
+ }
+ }
}
Modified: lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/ReTokenizeFile.java
URL: http://svn.apache.org/viewvc/lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/ReTokenizeFile.java?rev=617035&r1=617034&r2=617035&view=diff
==============================================================================
--- lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/ReTokenizeFile.java (original)
+++ lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/ReTokenizeFile.java Wed Jan 30 23:44:03 2008
@@ -16,7 +16,6 @@
*/
/* $Id$ */
package org.apache.lenya.lucene;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
@@ -27,274 +26,261 @@
import java.nio.charset.IllegalCharsetNameException;
import java.util.StringTokenizer;
import org.apache.lenya.lucene.html.HTMLParser;
-import org.apache.log4j.Category;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
-
-/**
- * DOCUMENT ME!
- */
public class ReTokenizeFile {
- private static final Category log = Category.getInstance(ReTokenizeFile.class);
- private int offset = 100;
- /**
- * DOCUMENT ME!
- *
- * @param args
- * DOCUMENT ME!
- */
- public static void main(String[] args) {
- if (args.length < 2) {
- System.err.println("Usage: ReTokenizeFile filename word1 word2 ...");
- return;
- }
- try {
- String[] words = new String[args.length - 1]; // {"Cocoon","Lenya"};
- for (int i = 1; i < args.length; i++) {
- words[i - 1] = args[i];
+ private int offset = 100;
+ /**
+ *
+ * @param args
+ * DOCUMENT ME!
+ */
+ public static void main(String[] args) {
+ if(args.length < 2){
+ System.err.println("Usage: ReTokenizeFile filename word1 word2 ...");
+ return;
+ }
+ try{
+ String[] words = new String[args.length - 1]; // {"Cocoon","Lenya"};
+ for(int i = 1; i < args.length; i++){
+ words[i - 1] = args[i];
+ }
+ String s = null;
+ s = new ReTokenizeFile().getExcerpt(new File(args[0]), words);
+ System.err.println(".main(): Excerpt: " + s);
+ }catch(Exception e){
+ System.err.println(".main(): " + e);
+ }
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param file
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws Exception
+ * DOCUMENT ME!
+ */
+ public String reTokenize(File file) throws Exception {
+ TokenStream ts = new StandardAnalyzer().tokenStream("", new HTMLParser(file).getReader());
+ Token token = null;
+ while((token = ts.next()) != null){
+ System.out.println("ReTokenizeFile.reTokenize(File): " + token.termText() + " " + token.startOffset() + " " + token.endOffset() + " " + token.type());
+ }
+ return file.getAbsolutePath();
+ }
+ /**
+ *
+ */
+ public String getExcerpt(File file, String[] words) throws FileNotFoundException, IOException {
+ if(file.getName().substring(file.getName().length() - 4).equals(".pdf")){
+ file = new File(file.getAbsolutePath() + ".txt");
+ }
+ String content = readFileWithEncoding(file);
+ // log.debug(content);
+ content = removeTags(content);
+ // log.debug(content);
+ /*
+ * java.io.Reader reader = new HTMLParser(file).getReader(); char[] chars = new char[1024]; int chars_read; java.io.Writer writer = new java.io.StringWriter();
+ *
+ * while ((chars_read = reader.read(chars)) > 0) { writer.write(chars, 0, chars_read); }
+ */
+ // String html = writer.toString();
+ // html = writer.toString();
+ int index = -1;
+ for(int i = 0; i < words.length; i++){
+ index = content.toLowerCase().indexOf(words[i].toLowerCase());
+ if(index >= 0){
+ int start = index - offset;
+ if(start < 0){
+ start = 0;
}
- String s = null;
- s = new ReTokenizeFile().getExcerpt(new File(args[0]), words);
- System.err.println(".main(): Excerpt: " + s);
- } catch (Exception e) {
- System.err.println(".main(): " + e);
- }
- }
- /**
- * DOCUMENT ME!
- *
- * @param file
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- *
- * @throws Exception
- * DOCUMENT ME!
- */
- public String reTokenize(File file) throws Exception {
- TokenStream ts = new StandardAnalyzer().tokenStream("", new HTMLParser(file).getReader());
- Token token = null;
- while ((token = ts.next()) != null) {
- System.out.println("ReTokenizeFile.reTokenize(File): " + token.termText() + " " + token.startOffset() + " " + token.endOffset() + " " + token.type());
- }
- return file.getAbsolutePath();
- }
- /**
- *
- */
- public String getExcerpt(File file, String[] words) throws FileNotFoundException, IOException {
- if (file.getName().substring(file.getName().length() - 4).equals(".pdf")) {
- file = new File(file.getAbsolutePath() + ".txt");
- }
- String content = readFileWithEncoding(file);
- // log.debug(content);
- content = removeTags(content);
- // log.debug(content);
- /*
- * java.io.Reader reader = new HTMLParser(file).getReader(); char[]
- * chars = new char[1024]; int chars_read; java.io.Writer writer = new
- * java.io.StringWriter();
- *
- * while ((chars_read = reader.read(chars)) > 0) { writer.write(chars,
- * 0, chars_read); }
- */
- // String html = writer.toString();
- // html = writer.toString();
- int index = -1;
- for (int i = 0; i < words.length; i++) {
- index = content.toLowerCase().indexOf(words[i].toLowerCase());
- if (index >= 0) {
- int start = index - offset;
- if (start < 0) {
- start = 0;
- }
- int end = index + words[i].length() + offset;
- if (end >= content.length()) {
- end = content.length() - 1;
- }
- return content.substring(start, end);
+ int end = index + words[i].length() + offset;
+ if(end >= content.length()){
+ end = content.length() - 1;
}
- }
- return null;
- }
- /**
- * Remove tags
- *
- * @param string
- * Content with tags
- *
- * @return Content without tags
- */
- public String removeTags(String string) {
- StringBuffer sb = new StringBuffer("");
- boolean tag = false;
- for (int i = 0; i < string.length(); i++) {
- char ch = string.charAt(i);
- if (ch == '<') {
- tag = true;
- } else if (ch == '>') {
- tag = false;
- } else {
- if (!tag)
- sb.append(string.charAt(i));
+ return content.substring(start, end);
+ }
+ }
+ return null;
+ }
+ /**
+ * Remove tags
+ *
+ * @param string
+ * Content with tags
+ *
+ * @return Content without tags
+ */
+ public String removeTags(String string) {
+ StringBuffer sb = new StringBuffer("");
+ boolean tag = false;
+ for(int i = 0; i < string.length(); i++){
+ char ch = string.charAt(i);
+ if(ch == '<'){
+ tag = true;
+ }else if(ch == '>'){
+ tag = false;
+ }else{
+ if(!tag)
+ sb.append(string.charAt(i));
+ }
+ }
+ return sb.toString();
+ }
+ /**
+ * Is being used by search-and-results.xsp. Is this really still necessary?
+ *
+ * @param string
+ * content
+ *
+ * @return content without <>&
+ */
+ public String tidy(String string) {
+ StringTokenizer st = new StringTokenizer(string, "<>&");
+ StringBuffer sb = new StringBuffer("");
+ while(st.hasMoreElements()){
+ sb.append(st.nextToken());
+ }
+ return sb.toString();
+ }
+ /**
+ * Encloses all words in <code>words</code> that appear in <code>string</code> in <word> tags. The whole string is enclosed in <excerpt> tags.
+ *
+ * @param string
+ * The string to process.
+ * @param words
+ * The words to emphasize.
+ *
+ * @return DOCUMENT ME!
+ */
+ public String emphasizeAsXML(String string, String[] words) {
+ // String emphasizedString = "... Hello <word>World</word>! ...";
+ String lowerCaseString = string.toLowerCase();
+ for(int i = 0; i < words.length; i++){
+ String word = words[i].toLowerCase();
+ // use uppercase tags so that they are not replaced
+ lowerCaseString = lowerCaseString.replaceAll(word, "<WORD>" + word + "</WORD>");
+ }
+ lowerCaseString = lowerCaseString.toLowerCase();
+ // if (true) return "<excerpt>" + lowerCaseString + "</excerpt>";
+ String result = "";
+ int sourceIndex = 0;
+ int index = 0;
+ String[] tags = {"<word>", "</word>"};
+ while(lowerCaseString.indexOf(tags[0], index) != -1){
+ for(int tag = 0; tag < 2; tag++){
+ int subStringLength = lowerCaseString.indexOf(tags[tag], index) - index;
+ String subString = string.substring(sourceIndex, sourceIndex + subStringLength);
+ result += (includeInCDATA(subString) + tags[tag]);
+ sourceIndex += subStringLength;
+ index += (subStringLength + tags[tag].length());
+ }
+ }
+ result += includeInCDATA(string.substring(sourceIndex));
+ return "<excerpt>" + result + "</excerpt>";
+ }
+ /**
+ * Includes a string in CDATA delimiters.
+ */
+ protected String includeInCDATA(String string) {
+ return "<![CDATA[" + string + "]]>";
+ }
+ /**
+ * reads a file and if the file is an xml file, determine its encoding
+ *
+ * @param file
+ * the file to read. (if the file is an xml file with an specified encoding, this will be overwritten)
+ * @return the contents of the file.
+ */
+ protected String readFileWithEncoding(File file) throws FileNotFoundException, IOException {
+ String content = readHtmlFile(file);
+ // test if the file contains xml data and extract the encoding
+ int endOfFirstTag = content.indexOf(">");
+ if(endOfFirstTag > 0 && content.charAt(endOfFirstTag - 1) == '?'){
+ String upperLine = content.substring(0, endOfFirstTag).toUpperCase();
+ int encStart = upperLine.indexOf("ENCODING=") + 10;
+ int encEnd = -1;
+ if(encStart > 0){
+ encEnd = upperLine.indexOf("\"", encStart);
+ if(encEnd == -1){
+ encEnd = upperLine.indexOf("\'", encStart);
}
- }
- return sb.toString();
- }
- /**
- * Is being used by search-and-results.xsp. Is this really still necessary?
- *
- * @param string
- * content
- *
- * @return content without <>&
- */
- public String tidy(String string) {
- StringTokenizer st = new StringTokenizer(string, "<>&");
- StringBuffer sb = new StringBuffer("");
- while (st.hasMoreElements()) {
- sb.append(st.nextToken());
- }
- return sb.toString();
- }
- /**
- * Encloses all words in <code>words</code> that appear in
- * <code>string</code> in <word> tags. The whole string is enclosed
- * in <excerpt> tags.
- *
- * @param string
- * The string to process.
- * @param words
- * The words to emphasize.
- *
- * @return DOCUMENT ME!
- */
- public String emphasizeAsXML(String string, String[] words) {
- String emphasizedString = "... Hello <word>World</word>! ...";
- String lowerCaseString = string.toLowerCase();
- for (int i = 0; i < words.length; i++) {
- String word = words[i].toLowerCase();
- // use uppercase tags so that they are not replaced
- lowerCaseString = lowerCaseString.replaceAll(word, "<WORD>" + word + "</WORD>");
- }
- lowerCaseString = lowerCaseString.toLowerCase();
- // if (true) return "<excerpt>" + lowerCaseString + "</excerpt>";
- String result = "";
- int sourceIndex = 0;
- int index = 0;
- String[] tags = { "<word>", "</word>" };
- while (lowerCaseString.indexOf(tags[0], index) != -1) {
- for (int tag = 0; tag < 2; tag++) {
- int subStringLength = lowerCaseString.indexOf(tags[tag], index) - index;
- String subString = string.substring(sourceIndex, sourceIndex + subStringLength);
- result += (includeInCDATA(subString) + tags[tag]);
- sourceIndex += subStringLength;
- index += (subStringLength + tags[tag].length());
+ }
+ if(encStart > 0 && encEnd > 0){
+ String xmlCharset = upperLine.substring(encStart, encEnd);
+ try{
+ if(Charset.isSupported(xmlCharset)){
+ content = readFile(file, Charset.forName(xmlCharset));
+ }
+ }catch(IllegalCharsetNameException e){
+ // do nothing - thrown by Charset.isSupported
}
- }
- result += includeInCDATA(string.substring(sourceIndex));
- return "<excerpt>" + result + "</excerpt>";
- }
- /**
- * Includes a string in CDATA delimiters.
- */
- protected String includeInCDATA(String string) {
- return "<![CDATA[" + string + "]]>";
- }
- /**
- * reads a file and if the file is an xml file, determine its encoding
- *
- * @param file
- * the file to read. (if the file is an xml file with an
- * specified encoding, this will be overwritten)
- * @return the contents of the file.
- */
- protected String readFileWithEncoding(File file) throws FileNotFoundException, IOException {
- String content = readHtmlFile(file);
- // test if the file contains xml data and extract the encoding
- int endOfFirstTag = content.indexOf(">");
- if (endOfFirstTag > 0 && content.charAt(endOfFirstTag - 1) == '?') {
- String upperLine = content.substring(0, endOfFirstTag).toUpperCase();
- int encStart = upperLine.indexOf("ENCODING=") + 10;
- int encEnd = -1;
- if (encStart > 0) {
- encEnd = upperLine.indexOf("\"", encStart);
- if (encEnd == -1) {
- encEnd = upperLine.indexOf("\'", encStart);
- }
- }
- if (encStart > 0 && encEnd > 0) {
- String xmlCharset = upperLine.substring(encStart, encEnd);
- try {
- if (Charset.isSupported(xmlCharset)) {
- content = readFile(file, Charset.forName(xmlCharset));
- }
- } catch (IllegalCharsetNameException e) {
- // do nothing - thrown by Charset.isSupported
- }
- }
- }
- return content;
- }
- /**
- * read a html file.
- *
- * @param file
- * the file to read
- * @return the content of the file.
- * @throws FileNotFoundException
- * if the file does not exists.
- * @throws IOException
- * if something else went wrong.
- */
- protected String readHtmlFile(File file) throws FileNotFoundException, IOException {
- java.io.Reader reader = new HTMLParser(file).getReader();
- char[] chars = new char[1024];
- int chars_read;
- java.io.Writer writer = new java.io.StringWriter();
- while ((chars_read = reader.read(chars)) > 0) {
- writer.write(chars, 0, chars_read);
- }
- return writer.toString();
- }
- /**
- * reads a file in the specified encoding.
- *
- * @param file
- * the file to read.
- * @param encoding
- * the file encoding
- * @return the content of the file.
- * @throws FileNotFoundException
- * if the file does not exists.
- * @throws IOException
- * if something else went wrong.
- */
- protected String readFile(File file, Charset charset) throws FileNotFoundException, IOException {
- FileInputStream inputFile = new FileInputStream(file);
- InputStreamReader inputStream;
- if (charset != null) {
- inputStream = new InputStreamReader(inputFile, charset);
- } else {
- inputStream = new InputStreamReader(inputFile);
- }
- BufferedReader bufferReader = new BufferedReader(inputStream);
- StringBuffer buffer = new StringBuffer();
- String line = "";
- while (bufferReader.ready()) {
- line = bufferReader.readLine();
- buffer.append(line);
- }
- bufferReader.close();
- inputStream.close();
- inputFile.close();
- return buffer.toString();
- }
- /**
- * Set offset
- */
- public void setOffset(int offset) {
- this.offset = offset;
- }
+ }
+ }
+ return content;
+ }
+ /**
+ * read a html file.
+ *
+ * @param file
+ * the file to read
+ * @return the content of the file.
+ * @throws FileNotFoundException
+ * if the file does not exists.
+ * @throws IOException
+ * if something else went wrong.
+ */
+ protected String readHtmlFile(File file) throws FileNotFoundException, IOException {
+ java.io.Reader reader = new HTMLParser(file).getReader();
+ char[] chars = new char[1024];
+ int chars_read;
+ java.io.Writer writer = new java.io.StringWriter();
+ while((chars_read = reader.read(chars)) > 0){
+ writer.write(chars, 0, chars_read);
+ }
+ return writer.toString();
+ }
+ /**
+ * reads a file in the specified encoding.
+ *
+ * @param file
+ * the file to read.
+ * @param encoding
+ * the file encoding
+ * @return the content of the file.
+ * @throws FileNotFoundException
+ * if the file does not exists.
+ * @throws IOException
+ * if something else went wrong.
+ */
+ protected String readFile(File file, Charset charset) throws FileNotFoundException, IOException {
+ FileInputStream inputFile = new FileInputStream(file);
+ InputStreamReader inputStream;
+ if(charset != null){
+ inputStream = new InputStreamReader(inputFile, charset);
+ }else{
+ inputStream = new InputStreamReader(inputFile);
+ }
+ BufferedReader bufferReader = new BufferedReader(inputStream);
+ StringBuffer buffer = new StringBuffer();
+ String line = "";
+ while(bufferReader.ready()){
+ line = bufferReader.readLine();
+ buffer.append(line);
+ }
+ bufferReader.close();
+ inputStream.close();
+ inputFile.close();
+ return buffer.toString();
+ }
+ /**
+ * Set offset
+ */
+ public void setOffset(int offset) {
+ this.offset = offset;
+ }
}
Modified: lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/SearchFiles.java
URL: http://svn.apache.org/viewvc/lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/SearchFiles.java?rev=617035&r1=617034&r2=617035&view=diff
==============================================================================
--- lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/SearchFiles.java (original)
+++ lenya/branches/revolution/1.3.x/src/java/org/apache/lenya/lucene/SearchFiles.java Wed Jan 30 23:44:03 2008
@@ -16,7 +16,6 @@
*/
/* $Id$ */
package org.apache.lenya.lucene;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
@@ -28,83 +27,84 @@
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
-
/**
* Command Line Interface
*/
class SearchFiles {
- /**
- * main method
- *
- * @param args
- * Directory of the index
- */
- public static void main(String[] args) {
- if (args.length == 0) {
- System.err.println("Usage: org.apache.lenya.lucene.SearchFiles \"directory_where_index_is_located\" <word>");
+ /**
+ * main method
+ *
+ * @param args
+ * Directory of the index
+ */
+ public static void main(String[] args) {
+ if(args.length == 0){
+ System.err.println("Usage: org.apache.lenya.lucene.SearchFiles \"directory_where_index_is_located\" <word>");
+ return;
+ }
+ File index_directory = new File(args[0]);
+ if(!index_directory.exists()){
+ System.err.println("Exception: No such directory: " + index_directory.getAbsolutePath());
+ return;
+ }
+ try{
+ if(args.length > 1){
+ // Hits hits =
+ new SearchFiles().search(args[1], index_directory);
return;
- }
- File index_directory = new File(args[0]);
- if (!index_directory.exists()) {
- System.err.println("Exception: No such directory: " + index_directory.getAbsolutePath());
- return;
- }
- try {
- if (args.length > 1) {
- Hits hits = new SearchFiles().search(args[1], index_directory);
- return;
+ }
+ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ while(true){
+ System.out.print("Search: ");
+ String line = in.readLine();
+ if(line.length() == -1){
+ break;
}
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- while (true) {
- System.out.print("Search: ");
- String line = in.readLine();
- if (line.length() == -1) {
- break;
- }
- Hits hits = new SearchFiles().search(line, index_directory);
- System.out.print("\nAnother Search (y/n) ? ");
- line = in.readLine();
- if ((line.length() == 0) || (line.charAt(0) == 'n')) {
- break;
- }
+ // Hits hits =
+ new SearchFiles().search(line, index_directory);
+ System.out.print("\nAnother Search (y/n) ? ");
+ line = in.readLine();
+ if((line.length() == 0) || (line.charAt(0) == 'n')){
+ break;
}
- } catch (Exception e) {
- System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
- }
- }
- /**
- *
- */
- public Hits search(String line, File index_directory) throws Exception {
- Searcher searcher = new IndexSearcher(index_directory.getAbsolutePath());
- Analyzer analyzer = new StandardAnalyzer();
- // UPGRADE Lucene 1.3 -> 2.2
- // Query query = QueryParser.parse(line, "contents", analyzer);
- QueryParser qp = new QueryParser("contents", analyzer);
- Query query = qp.parse(line);
- System.out.println("Searching for: " + query.toString("contents"));
- Hits hits = searcher.search(query);
- System.out.println("Total matching documents: " + hits.length());
- final int HITS_PER_PAGE = 10;
- for (int start = 0; start < hits.length(); start += HITS_PER_PAGE) {
- int end = Math.min(hits.length(), start + HITS_PER_PAGE);
- for (int i = start; i < end; i++) {
- Document doc = hits.doc(i);
- String path = doc.get("path");
- if (path != null) {
- System.out.println(i + ". " + path);
- } else {
- String url = doc.get("url");
- if (url != null) {
- System.out.println(i + ". " + url);
- System.out.println(" - " + doc.get("title"));
- } else {
- System.out.println(i + ". " + "No path nor URL for this document");
- }
- }
+ }
+ }catch(Exception e){
+ System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
+ }
+ }
+ /**
+ *
+ */
+ public Hits search(String line, File index_directory) throws Exception {
+ Searcher searcher = new IndexSearcher(index_directory.getAbsolutePath());
+ Analyzer analyzer = new StandardAnalyzer();
+ // UPGRADE Lucene 1.3 -> 2.2
+ // Query query = QueryParser.parse(line, "contents", analyzer);
+ QueryParser qp = new QueryParser("contents", analyzer);
+ Query query = qp.parse(line);
+ System.out.println("Searching for: " + query.toString("contents"));
+ Hits hits = searcher.search(query);
+ System.out.println("Total matching documents: " + hits.length());
+ final int HITS_PER_PAGE = 10;
+ for(int start = 0; start < hits.length(); start += HITS_PER_PAGE){
+ int end = Math.min(hits.length(), start + HITS_PER_PAGE);
+ for(int i = start; i < end; i++){
+ Document doc = hits.doc(i);
+ String path = doc.get("path");
+ if(path != null){
+ System.out.println(i + ". " + path);
+ }else{
+ String url = doc.get("url");
+ if(url != null){
+ System.out.println(i + ". " + url);
+ System.out.println(" - " + doc.get("title"));
+ }else{
+ System.out.println(i + ". " + "No path nor URL for this document");
+ }
}
- }
- searcher.close();
- return hits;
- }
+ }
+ }
+ searcher.close();
+ return hits;
+ }
}
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.