view software/eXist/mpdl-modules/src/org/exist/xquery/modules/mpdldoc/GetJobs.java @ 0:408254cf2f1d

Erstellung
author Josef Willenborg <jwillenborg@mpiwg-berlin.mpg.de>
date Wed, 24 Nov 2010 17:24:23 +0100
parents
children
line wrap: on
line source

/*
 *  eXist Open Source Native XML Database: Extension module
 *  Copyright (C) 2008 Josef Willenborg
 *  jwillenborg@mpiwg-berlin.mpg.de
 *  http://www.mpiwg-berlin.mpg.de
 *  
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *  
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *  
 *  $Id: TextModule.java $
 */
package org.exist.xquery.modules.mpdldoc;

import java.util.ArrayList;
import java.util.Date;

import org.exist.dom.QName;
import org.exist.http.servlets.RequestWrapper;
import org.exist.memtree.DocumentImpl;
import org.exist.memtree.MemTreeBuilder;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.Variable;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.functions.request.RequestModule;
import org.exist.xquery.value.JavaObjectValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;

import de.mpg.mpiwg.berlin.mpdl.exception.ApplicationException;
import de.mpg.mpiwg.berlin.mpdl.general.MpdlConstants;
import de.mpg.mpiwg.berlin.mpdl.schedule.MpdlChainScheduler;
import de.mpg.mpiwg.berlin.mpdl.schedule.MpdlDocOperation;

/**
 * @author Josef Willenborg (jwillenborg@mpiwg-berlin.mpg.de)
 */
public class GetJobs extends BasicFunction {

	public final static FunctionSignature signature =
		new FunctionSignature(
			new QName("get-jobs", MPDLDocModule.NAMESPACE_URI, MPDLDocModule.PREFIX),
			"A function which delivers all jobs or the job given by an id.",
			new SequenceType[] { new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE)},
			new SequenceType(Type.NODE, Cardinality.EXACTLY_ONE));

	public GetJobs(XQueryContext context) {
		super(context, signature);
	}

	public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
	  try {
      Sequence firstSeq = args[0];
      if (firstSeq.isEmpty())
        return Sequence.EMPTY_SEQUENCE;
      String firstSeqStrValue = firstSeq.getStringValue();
      boolean getAllJobs = false;
      if (firstSeqStrValue.equals("all"))
        getAllJobs = true;
      MpdlChainScheduler scheduler = MpdlChainScheduler.getInstance();
      ArrayList<MpdlDocOperation> docOperations = new ArrayList<MpdlDocOperation>();
      if (getAllJobs) {
        docOperations = scheduler.getDocOperations();
      } else {
        String jobIdStr = firstSeq.getStringValue();
        int jobId = Integer.parseInt(jobIdStr);
        MpdlDocOperation docOperation = scheduler.getDocOperation(jobId);
        if (docOperation != null)
          docOperations.add(docOperation);
      }
      DocumentImpl doc = null;
      if ((getAllJobs && ! docOperations.isEmpty()) || (! getAllJobs && ! docOperations.isEmpty())) {
        MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startElement("", "mpdl-doc-operations", "mpdl-doc-operations", null);
        for (int i=0; i<docOperations.size(); i++) {
          MpdlDocOperation docOperation = docOperations.get(i);
          builder.startElement("", "mpdl-doc-operation", "mpdl-doc-operation", null);
          builder.startElement("", "name", "name", null);
          builder.characters(docOperation.getName());
          builder.endElement();
          builder.startElement("", "job-id", "job-id", null);
          int jobId = docOperation.getOrderId();
          builder.characters(String.valueOf(jobId));
          builder.endElement();
          builder.startElement("", "status", "status", null);
          builder.startElement("", "started", "started", null);
          Date start = docOperation.getStart();
          String startStr = "No start time available because job is scheduled into server queue where other jobs have been started earlier";
          if (start != null)
            startStr = start.toString();
          builder.characters(startStr);
          builder.endElement();
          builder.startElement("", "finished", "finished", null);
          Date end = docOperation.getEnd();
          String endStr = "No end time available because job is not finished yet";
          if (end != null)
            endStr = end.toString();
          builder.characters(endStr);
          builder.endElement();
          builder.startElement("", "description", "description", null);
          String status = docOperation.getStatus();
          if (status != null)
            builder.characters(status);
          builder.endElement();
          String eXistBaseUrlStr = getEXistFullBaseUrlStr();
          builder.startElement("", "url", "url", null);
          String statusUrl = eXistBaseUrlStr + "/" + MpdlConstants.MPDL_PROJECT_NAME + "/scheduler/" + "get-jobs.xql?id=" + jobId;
          builder.characters(statusUrl);
          builder.endElement();
          builder.startElement("", "error-message", "error-message", null);
          String errorMessage = docOperation.getErrorMessage();
          if (errorMessage == null)
            builder.characters("no error");
          else
            builder.characters(errorMessage);
          builder.endElement();
          builder.endElement();
          String escidocDestUrl = null;
          String existDestUrl = null;
          if (docOperation.isFinished() && ! docOperation.isError()) {
            escidocDestUrl = docOperation.getESciDocDestUrl();
            existDestUrl = eXistBaseUrlStr + "/" + MpdlConstants.MPDL_PROJECT_NAME + "/" + "page-query-result.xql?document=" + docOperation.getDestUrl();
          }
          if (docOperation.getName().equals("delete")  || docOperation.getName().equals("deleteExist")) {
            builder.startElement("", "dest", "dest", null);
            builder.startElement("", "doc-base", "doc-base", null);
            builder.characters(docOperation.getDocBase());
            builder.endElement();
            builder.startElement("", "language", "language", null);
            builder.characters(docOperation.getLanguage());
            builder.endElement();
            builder.startElement("", "file-name", "file-name", null);
            builder.characters(docOperation.getFileName());
            builder.endElement();
            if (! docOperation.getName().equals("deleteExist")) {
              builder.startElement("", "escidoc-url", "escidoc-url", null);
              if (escidocDestUrl != null)
                builder.characters(escidocDestUrl);
              builder.endElement();
            }
            builder.startElement("", "exist-url", "exist-url", null);
            if (existDestUrl != null)
              builder.characters(existDestUrl);
            builder.endElement();
            builder.endElement();
          } else if (docOperation.getName().equals("create") || docOperation.getName().equals("update") || docOperation.getName().equals("updateExist")) {
            builder.startElement("", "src", "src", null);
            builder.startElement("", "url", "url", null);
            builder.characters(docOperation.getSrcUrl());
            builder.endElement();
            builder.startElement("", "upload-file-name", "upload-file-name", null);
            builder.characters(docOperation.getUploadFileName());
            builder.endElement();
            builder.endElement();
            builder.startElement("", "dest", "dest", null);
            builder.startElement("", "doc-base", "doc-base", null);
            builder.characters(docOperation.getDocBase());
            builder.endElement();
            builder.startElement("", "language", "language", null);
            builder.characters(docOperation.getLanguage());
            builder.endElement();
            builder.startElement("", "file-name", "file-name", null);
            builder.characters(docOperation.getFileName());
            builder.endElement();
            if (! docOperation.getName().equals("updateExist")) {
              builder.startElement("", "escidoc-url", "escidoc-url", null);
              if (escidocDestUrl != null)
                builder.characters(escidocDestUrl);
              builder.endElement();
            }
            builder.startElement("", "exist-url", "exist-url", null);
            if (existDestUrl != null)
              builder.characters(existDestUrl);
            builder.endElement();
            builder.endElement();
          }
          builder.startElement("", "description", "description", null);
          builder.characters("Document operations are maintained on server asychronously. Each operation is scheduled into a server job queue " + 
              "and is executed when all previous started jobs in the queue are worked off. Each operation needs some execution time dependant " + 
              "on the size and the number of pages of the document, the speed of the network connection and the performance of the used " +
              "eSciDoc and eXist server.");
          builder.endElement();
          builder.endElement();
        }
        builder.endElement();
        doc = ((DocumentImpl) builder.getDocument());
      } else if (getAllJobs && docOperations.isEmpty()) {
        MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startElement("", "message", "message", null);
        builder.characters("there are no scheduled jobs (neither finished, queued or executed)");
        builder.endElement();
        doc = ((DocumentImpl) builder.getDocument());
      } else {
        MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startElement("", "error", "error", null);
        builder.startElement("", "message", "message", null);
        String jobIdStr = firstSeq.getStringValue();
        int jobId = Integer.parseInt(jobIdStr);
        builder.characters("job with id: " + jobId + " was not scheduled and could therefore not be listed");
        builder.endElement();
        builder.endElement();
        doc = ((DocumentImpl) builder.getDocument());
      }
      if (doc == null)
        return Sequence.EMPTY_SEQUENCE;
      else 
        return doc;
	  } catch (ApplicationException e) {
	    throw new XPathException(e);
	  }
	}
	
  private String getEXistFullBaseUrlStr() {
    return "http://" + MpdlConstants.MPDL_FULL_EXIST_HOST_NAME;
  }
  
  private String getBaseUrlStr() {
    String baseUrlStr = "";
    try {
      RequestModule myModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI);
      // request object is read from global variable $request
      Variable var = myModule.resolveVariable(RequestModule.REQUEST_VAR);
      JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0);
      RequestWrapper requestWrapper = (RequestWrapper) value.getObject();
      // String protocol = requestWrapper.getProtocol();
      String hostName = requestWrapper.getServerName();
      int port = requestWrapper.getServerPort();
      baseUrlStr = "http" + "://" + hostName + ":" + port;    
    } catch (XPathException e) {

    }
    return baseUrlStr;
  }
}