Package sos.scheduler.job

Source Code of sos.scheduler.job.JobSchedulerJob

/********************************************************* begin of preamble
**
** Copyright (C) 2003-2010 Software- und Organisations-Service GmbH.
** All rights reserved.
**
** This file may be used under the terms of either the
**
**   GNU General Public License version 2.0 (GPL)
**
**   as published by the Free Software Foundation
**   http://www.gnu.org/licenses/gpl-2.0.txt and appearing in the file
**   LICENSE.GPL included in the packaging of this file.
**
** or the
** 
**   Agreement for Purchase and Licensing
**
**   as offered by Software- und Organisations-Service GmbH
**   in the respective terms of supply that ship with this file.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
** IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
** THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
** POSSIBILITY OF SUCH DAMAGE.
********************************************************** end of preamble*/
package sos.scheduler.job;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Properties;

import sos.connection.SOSConnection;
import sos.settings.SOSConnectionSettings;
import sos.settings.SOSProfileSettings;
import sos.settings.SOSSettings;
import sos.spooler.Job_impl;
import sos.util.SOSArguments;
import sos.util.SOSLogger;
import sos.util.SOSSchedulerLogger;

/**
* Base class for Scheduler Jobs
*
* @author Andreas Liebert
*/
public class JobSchedulerJob extends Job_impl {

  /** logging */
  protected SOSSchedulerLogger    sosLogger      = null;

  /** Database connection */
  private SOSConnection      sosConnection    = null;

  /** Settings from the database */
  private SOSConnectionSettings  connectionSettings  = null;

  /** job Settings */
  private SOSSettings        jobSettings      = null;

  /** Job Properties */
  private Properties        jobProperties    = null;

  /** task id assigned by the Job Scheduler */
  private int            jobId        = 0;

  /** configured job name Scheduler */
  private String          jobName        = null;

  /** configured job title */
  private String          jobTitle      = null;

  /** name of the application (for settings) */
  protected String        application      = new String("");

  /*
   * initializes the database connection to the database configured
   * in config/factory.ini <br/>
   * @see sos.spooler.Job_impl#spooler_init()
   */
  public boolean spooler_init() {

    try {
      boolean rc = super.spooler_init();
      if (!rc)
        return false;
      this.setLogger(new SOSSchedulerLogger(spooler_log));

      try { // to initialize database connection
        this.setJobSettings(new SOSProfileSettings(spooler.ini_path()));
        this.setJobProperties(this.jobSettings.getSection("spooler"));
        if (this.getJobProperties().isEmpty())
          throw new Exception("no settings found in section [spooler] of configuration file: " + spooler.ini_path());
        if (this.getJobProperties().getProperty("db") == null || this.getJobProperties().getProperty("db").length() == 0)
          throw new Exception("no settings found for entry [db] in section [spooler] of configuration file: " + spooler.ini_path());
        if (this.getJobProperties().getProperty("db_class") == null || this.getJobProperties().getProperty("db_class").length() == 0)
          throw new Exception("no settings found for entry [db_class] in section [spooler] of configuration file: " + spooler.ini_path());

        if (this.getLogger() != null)
          sosLogger.debug6("connecting to database.. .");

        /*
        String dbProperty = this.getJobProperties().getProperty("db").replaceAll("jdbc:", "-url=jdbc:");
        dbProperty = dbProperty.substring(dbProperty.indexOf('-'));
       
        SOSArguments arguments = new SOSArguments(dbProperty);

        this.setConnection( SOSConnection.createInstance( 
                              this.getJobProperties().getProperty("db_class"),
                              arguments.as_string("-class=", ""),
                              arguments.as_string("-url=", ""),
                              arguments.as_string("-user=", ""),
                              arguments.as_string("-password=", ""),
                              (SOSLogger)new SOSSchedulerLogger(this.spooler_log) )
                      );
        */
        this.setConnection(getSchedulerConnection(this.getJobSettings(), this.getLogger()));
        this.getConnection().connect();

        this.setConnectionSettings(new SOSConnectionSettings(this.getConnection(), "SETTINGS", this.getLogger()));

        if (this.getLogger() != null)
          this.getLogger().debug6("..successfully connected to Job Scheduler database.");
      }
      catch (Exception e) {
        spooler_log.info("connect to database failed: " + e);
        spooler_log.info("running without database...");
      }
      if (spooler_job != null && getJobSettings() != null)
        setJobProperties(getJobSettings().getSection("job " + spooler_job.name()));
      if (spooler_task != null)
        this.setJobId(spooler_task.id());
      if (spooler_job != null)
        this.setJobName(spooler_job.name());
      if (spooler_job != null)
        this.setJobTitle(spooler_job.title());
      this.getSettings();
      return true;
    }
    catch (Exception e) {
      spooler_log.error(e.getMessage());
      return false;
    }
  }

  /**
   * Closes the database connection
   */
  public void spooler_exit() {

    try {
      try { // to close the database connection
        if (this.getConnection() != null) {
          spooler_log.debug6("spooler_exit(): disconnecting.. ..");
          this.getConnection().disconnect();
          this.setConnection(null);
        }
      }
      catch (Exception e) {
        spooler_log.warn("spooler_exit(): disconnect failed: " + e.toString());
      }

      spooler_log.info("Job " + this.getJobName() + " terminated.");
    }
    catch (Exception e) {
    } // no errror processing at job level
  }

  /**
   * @return Returns the jobSettings.
   */
  public SOSSettings getJobSettings() {
    return this.jobSettings;
  }

  /**
   * @param jobSettings
   *            The jobSettings to set.
   */
  public void setJobSettings(SOSSettings jobSettings) {
    this.jobSettings = jobSettings;
  }

  /**
   * @return Returns the sosConnection.
   */
  public SOSConnection getConnection() {
    return this.sosConnection;
  }

  /**
   * @param sosConnection
   *            The sosConnection to set.
   */
  public void setConnection(SOSConnection sosConnection) {
    this.sosConnection = sosConnection;
  }

  /**
   * @return Returns the sosLogger.
   */
  public SOSSchedulerLogger getLogger() {
    return sosLogger;
  }

  /**
   * @param sosLogger
   *            The sosLogger to set.
   */
  public void setLogger(SOSSchedulerLogger sosLogger) {
    this.sosLogger = sosLogger;
  }

  /**
   * @return Returns the jobProperties.
   */
  public Properties getJobProperties() {
    return this.jobProperties;
  }

  /**
   * @param jobProperties
   *            The jobProperties to set.
   */
  public void setJobProperties(Properties jobProperties) {
    this.jobProperties = jobProperties;
  }

  /**
   * @return Returns the connectionSettings.
   */
  public SOSConnectionSettings getConnectionSettings() {
    return connectionSettings;
  }

  /**
   * @param connectionSettings The connectionSettings to set.
   */
  public void setConnectionSettings(SOSConnectionSettings connectionSettings) {
    this.connectionSettings = connectionSettings;
  }

  /**
   * @return Returns the jobId.
   */
  protected int getJobId() {
    return jobId;
  }

  /**
   * @param jobId The jobId to set.
   */
  protected void setJobId(int jobId) {
    this.jobId = jobId;
  }

  /**
   * @return Returns the jobName.
   */
  protected String getJobName() {
    return jobName;
  }

  /**
   * @param jobName The jobName to set.
   */
  protected void setJobName(String jobName) {
    this.jobName = jobName;
  }

  /**
   * @return Returns the jobTitle.
   */
  protected String getJobTitle() {
    return jobTitle;
  }

  /**
   * @param jobTitle The jobTitle to set.
   */
  protected void setJobTitle(String jobTitle) {
    this.jobTitle = jobTitle;
  }

  /**
   * @param application The application to set.
   */
  protected void setApplication(String application) {
    this.application = application;
  }

  /**
   * @return Returns the application.
   */
  protected String getApplication() {
    return application;
  }

  /**
   * returns the Settings for the Job Scheduler as SOSSettings object
   * @param factoryIni Path to factory.ini (delivered by spooler.ini_path() )
   * @throws Exception
   */
  public static SOSSettings getSchedulerSettings(String factoryIni) throws Exception {
    SOSSettings schedulerSettings = new SOSProfileSettings(factoryIni);
    return schedulerSettings;
  }

  /**
   * Returns a SOSConnection object for the database connection of the Job Scheduler
   * The database connection must be opened with connect() and closed with disconnect()
   *
   * @param schedulerSettings Job Scheduler Settings      
   * @throws Exception
   */
  public static SOSConnection getSchedulerConnection(SOSSettings schedulerSettings) throws Exception {
    return getSchedulerConnection(schedulerSettings, null);
  }

  /**
   * Returns a SOSConnection object for the database connection of the Job Scheduler
   * The database connection must be opened with connect() and closed with disconnect()
   *
   * @param schedulerSettings Job Scheduler Settings 
   * @param log SOSLogger, which will be used by the database connection     
   * @throws Exception
   */
  public static SOSConnection getSchedulerConnection(SOSSettings schedulerSettings, SOSLogger log) throws Exception {
    String dbProperty = schedulerSettings.getSection("spooler").getProperty("db").replaceAll("jdbc:", "-url=jdbc:");
    dbProperty = dbProperty.substring(dbProperty.indexOf('-'));
    if (dbProperty.endsWith("-password="))
      dbProperty = dbProperty.substring(0, dbProperty.length() - 10);
    SOSArguments arguments = new SOSArguments(dbProperty);

    SOSConnection conn;
    if (log != null) {
      conn = SOSConnection.createInstance(schedulerSettings.getSection("spooler").getProperty("db_class"), arguments.as_string("-class=", ""),
          arguments.as_string("-url=", ""), arguments.as_string("-user=", ""), arguments.as_string("-password=", ""), log);
    }
    else {
      conn = SOSConnection.createInstance(schedulerSettings.getSection("spooler").getProperty("db_class"), arguments.as_string("-class=", ""),
          arguments.as_string("-url=", ""), arguments.as_string("-user=", ""), arguments.as_string("-password=", ""));
    }

    return conn;
  }

  /**
   * read initial job settings
   */
  private boolean getSettings() {

    try {
      if (spooler_job == null)
        return false;

      setJobSettings(new SOSProfileSettings(spooler.ini_path()));
      setJobProperties(getJobSettings().getSection("job " + spooler_job.name()));

      if (getJobProperties().isEmpty())
        return false;

      if (getJobProperties().getProperty("delay_after_error") != null) {
        String[] delays = getJobProperties().getProperty("delay_after_error").toString().split(";");
        if (delays.length > 0)
          spooler_job.clear_delay_after_error();
        for (int i = 0; i < delays.length; i++) {
          String[] delay = delays[i].split(":");
          spooler_job.set_delay_after_error(Integer.parseInt(delay[0]), delay[1]);
        }
      }

      return true;

    }
    catch (Exception e) {
      spooler_log.error(e.getMessage());
      return false;
    }
  }

  protected URL createURL(String fileName) throws Exception {
    URL url = null;
    try {
      url = new URL(fileName);
    }
    catch (MalformedURLException ex) {
      try {
        File f = new File(fileName);
        String path = f.getCanonicalPath();
        if (fileName.startsWith("/")) {
          path = fileName;
        }

        String fs = System.getProperty("file.separator");
        if (fs.length() == 1) {
          char sep = fs.charAt(0);
          if (sep != '/')
            path = path.replace(sep, '/');
          if (path.charAt(0) != '/')
            path = '/' + path;
        }
        if (!path.startsWith("file://")) {
          path = "file://" + path;
        }
        url = new URL(path);
      }
      catch (MalformedURLException e) {
        throw (new Exception("error in createURL(): " + e.getMessage()));
      }
    }
    return url;
  }

  protected URI createURI(String fileName) throws Exception {
    URI uri = null;
    try {
      uri = new URI(fileName);
    }
    // catch (URISyntaxException ex) {
    catch (Exception e) {
      try {
        File f = new File(fileName);
        String path = f.getCanonicalPath();
        if (fileName.startsWith("/")) {
          path = fileName;
        }

        String fs = System.getProperty("file.separator");
        if (fs.length() == 1) {
          char sep = fs.charAt(0);
          if (sep != '/')
            path = path.replace(sep, '/');
          if (path.charAt(0) != '/')
            path = '/' + path;
        }
        if (!path.startsWith("file://")) {
          path = "file://" + path;
        }
        uri = new URI(path);
      }
      // catch (URISyntaxException ex) {
      catch (Exception ex) {
        throw (new Exception("error in createURI(): " + e.getMessage()));
      }
    }
    return uri;
  }

  protected File createFile(String fileName) throws Exception {
    try {
      if (fileName == null || fileName.length() == 0) {
        throw new Exception("empty file name provided");
      }

      if (fileName.startsWith("file://")) {
        return new File(createURI(fileName));
      }
      else {
        return new File(fileName);
      }
    }
    catch (Exception e) {
      throw new Exception("error in createFile() [" + fileName + "]: " + e.getMessage());
    }
  }

  /**
   * Im package sos.net.jar ist die Configuration.xml vorhanden.
   * Diese wird im sos/scheduler/ftp/SOSFTPConfiguration.xml XIncludiert. Es k�nnen nur Dateien includiert werden,
   * die nicht im Jars vorhanden sind. Also m�ssen dies auf der Festplatte erzeugt werden, soweit diese nicht vorhanden sind.
   *
   * Hier in der Methode createFile_ wird die Configuration.xml einmal erstellt.
   * 
   * @param file
   * @throws Exception
   */
  public void createIncludeConfigurationFile(String file, String newFile) throws Exception {

    try {
      InputStream in = null;

      if (new File(newFile).exists()) {
        return;
      }

      try {
        in = new java.io.FileInputStream(file);
      }
      catch (Exception e) {
        //throw new Exception ("error while reading  " + REQUIRED_DEFAULT_PARAMETERS_FILENAME + ": " + e.toString(), e);
        getLogger().debug9(e.toString());
      }

      if (in == null) {
        getLogger().debug9("try again to Read " + file + " from Class path.");
        in = getClass().getClassLoader().getSystemResourceAsStream(file);//aus Klassenpfad holen

      }

      getLogger().debug9("get InputStream from " + file + "=" + in);
      if (in == null) {
        getLogger().debug9("try again to read InputStream from Library. " + file);
        in = getClass().getClassLoader().getResourceAsStream(file);//aus der Bibliothel holen
        getLogger().debug9("InputStream is =" + in);
      }

      if (in == null) {
        throw new Exception("could not read File " + file);
      }

      //jetzt speichern
      OutputStream out = null;
      byte[] buffer = new byte[10000];
      try {

        //out = new FileOutputStream("sos.net.sosftp.Configuration.xml" ,false);
        out = new FileOutputStream(newFile, false);
        while (true) {
          synchronized (buffer) {
            int amountRead = in.read(buffer);
            if (amountRead == -1) {
              break;
            }
            out.write(buffer, 0, amountRead);
          }
        }

      }
      finally {
        if (in != null) {
          in.close();
        }
        if (out != null) {
          out.close();
        }
      }

    }
    catch (Exception e) {
      throw new Exception("error creating cInclude File " + file + ", cause: " + e.toString(), e);
    }

  }
}
TOP

Related Classes of sos.scheduler.job.JobSchedulerJob

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.