/********************************************************* 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.util.HashMap;
import java.util.Map;
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import sos.spooler.Job;
import sos.spooler.Order;
import sos.spooler.Variable_set;
import com.sos.JSHelper.Basics.JSJobUtilities;
import com.sos.JSHelper.Exceptions.JobSchedulerException;
import com.sos.JSHelper.Logging.JobSchedulerLog4JAppender;
import com.sos.JSHelper.Logging.Log4JHelper;
import com.sos.localization.Messages;
/**
* \file JobSchedulerJobAdapter.java
*
* \class JobSchedulerJobAdapter
*
* \brief
* JobSchedulerJobAdapter is the base-class for a Java-API Adapter-Class.
*
* \details
*
* \code
* .... code goes here ...
* \endcode
*
* <p style="text-align:center">
* <br />---------------------------------------------------------------------------
* <br /> APL/Software GmbH - Berlin
* <br />##### generated by ClaviusXPress (http://www.sos-berlin.com) #########
* <br />---------------------------------------------------------------------------
* </p>
* \author KB
* @version $Id$13.06.2010
* \see reference
*
* Created on 13.06.2010 11:34:05
*/
public class JobSchedulerJobAdapter extends JobSchedulerJob implements JSJobUtilities, IJSCommands {
private final String conClassName = "JobSchedulerJobAdapter";
private Variable_set objJobOrOrderParams = null;
protected static Logger logger = null;
@SuppressWarnings("unused")
private static Log4JHelper objLogger = null;
public JobSchedulerJobAdapter() {
//
}
@Override
public boolean spooler_init() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::spooler_init";
return super.spooler_init();
}
@Override
public boolean spooler_process() throws Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::spooler_process";
try {
super.spooler_process();
// TODO �ber eine Option steuern. Die auch in die Standard-Option-Class aufnehmen
String strJobName = this.getJobName();
strJobName = strJobName.replace('/', '-'); //$NON-NLS-1$
Log4JHelper.flgUseJobSchedulerLog4JAppender = true;
objLogger = new Log4JHelper("./" + strJobName + "-log4j.properties"); //$NON-NLS-1$
logger = Logger.getRootLogger();
JobSchedulerLog4JAppender objJSAppender = null;
/**
* the JobSchedulerLog4JAppender is used as the stdout-appender
* Therefore the code-snippet below asked log4j what the stdout-appender
* is and if it is the JobSchedulerLog4JAppender, the Instance of the
* sosJobSchedulerLogger is set.
*
* All Log4J-Messages are redirected to the sosLogger.
*/
Appender objStdoutAppender = logger.getAppender("stdout"); //$NON-NLS-1$
if (objStdoutAppender instanceof JobSchedulerLog4JAppender) {
objJSAppender = (JobSchedulerLog4JAppender) objStdoutAppender;
objJSAppender.setSchedulerLogger(sosLogger);
logger.info("LOG-I-0020: JobSchedulerLog4JAppender is configured as log4j-appender");
if (spooler_log.level() < 0) {
logger.setLevel(Level.DEBUG);
}
}
if (objJSAppender == null) {
SimpleLayout layout = new SimpleLayout();
objJSAppender = new JobSchedulerLog4JAppender(layout);
Appender consoleAppender = objJSAppender ; // JobSchedulerLog4JAppender(layout);
logger.addAppender(consoleAppender);
// ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF:
logger.setLevel(Level.DEBUG);
logger.debug("LOG-I-0010: Log4j configured programmatically");
}
objJSAppender.setSchedulerLogger(sosLogger);
logger.info("User-Dir : " + System.getProperty("user.dir")); //$NON-NLS-1$
}
catch (JobSchedulerException e) {
return false;
}
catch (RuntimeException e) {
return false;
}
catch (Exception e) {
return false;
}
finally {
} // finally
return (spooler_task.job().order_queue() != null);
} // spooler_process
/**
*
* \brief getSchedulerParameterAsProperties
*
* \details
*
* \return HashMap<String,String>
*
* @param pSchedulerParameterSet
* @return
* @throws Exception
*/
protected HashMap<String, String> getSchedulerParameterAsProperties(Variable_set pSchedulerParameterSet) {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::getSchedulerParameterAsProperties";
System.out.println(conClassName);
HashMap<String, String> SchedulerParameters = new HashMap<String, String>();
try {
if (pSchedulerParameterSet != null) {
String strNames = pSchedulerParameterSet.names();
logger.debug("Names = " + strNames);
String[] names = pSchedulerParameterSet.names().split(";");
for (int i = 0; i < names.length; i++) {
String key = names[i];
String val = pSchedulerParameterSet.var(names[i]);
logger.debug ("key = " + key + ", value = " + val);
SchedulerParameters.put(key, val);
}
}
return SchedulerParameters;
}
catch (Exception e) {
throw new RuntimeException("error occurred reading Parameter from Variable_set : " + e.getMessage(), e);
}
}
/**
*
* \brief getParameters
*
* \details
* Returns a variable_set with all job and/or order-Parameters.
* At the same time, the class-global variable objJobOrderParams is filled.
* A Parameter is a pair of key and value.
*
* \return Variable_set
*
*/
protected Variable_set getJobOrOrderParameters() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::getParameters";
try {
Variable_set objJobOrOrderParameters = spooler.create_variable_set();
objJobOrOrderParameters = spooler_task.params();
if (spooler_task.job().order_queue() != null) {
Order order = spooler_task.order();
if (order.params() != null)
objJobOrOrderParameters.merge(order.params());
}
objJobOrOrderParams = objJobOrOrderParameters;
logger.debug("Number of Params found for Job or Order is : " + objJobOrOrderParameters.count());
return objJobOrOrderParameters;
}
catch (Exception e) {
throw new RuntimeException("error occurred getting Parameters for job or order: " + e.getMessage(), e);
}
}
/**
*
* \brief getParameters
*
* \details
* Returns a Variable_set with either the job- or the order-parameters.
*
* \return Variable_set
*
*/
public Variable_set getParameters() {
Order order = null;
try {
// Variable_set params = spooler.create_variable_set();
Variable_set params = spooler_task.params();
if (spooler_task.job().order_queue() != null) {
order = spooler_task.order();
if (order.params() != null)
params.merge(order.params());
}
return params;
}
catch (Exception e) {
String strM = String.format(Messages.getMsg("JSJ-E-100"), e.getMessage());
logger.error(strM, e);
throw new JobSchedulerException(strM);
}
}
/**
*
* \brief setParameters
*
* \details
* Set all Job- or Order-Parameters as a Variable_set.
*
* \return void
*
* @param pVariableSet
*/
public void setParameters(Variable_set pVariableSet) {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::setParameters";
this.objJobOrOrderParams = pVariableSet;
} // private void setParameters
/**
*
* \brief setJSParam
*
* \details
*
* \return SOSSSH2SuperClass
*
* @param pstrKey
* @param pstrValue
* @return
*/
public void setJSParam(final String pstrKey, final String pstrValue) {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::setJSParam";
if (spooler_task.params() != null) {
spooler_task.params().set_var(pstrKey, pstrValue);
}
if (spooler_task.order() != null) {
Order order = spooler_task.order();
if (order.params() != null) {
order.params().set_var(pstrKey, pstrValue);
}
}
if (objJobOrOrderParams != null) {
objJobOrOrderParams.set_var(pstrKey, pstrValue);
}
} // private SOSSSH2SuperClass setJSParam
/**
*
* \brief setJSParam
*
* \details
*
* \return
*
* @param pstrKey
* @param pstrValue
*/
public void setJSParam(final String pstrKey, final StringBuffer pstrValue) {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::setJSParam";
setJSParam(pstrKey, pstrValue.toString());
} // private SOSSSH2SuperClass setJSParam
/**
*
* \brief replaceSchedulerVars
*
* \details
*
* \return void
*
* @param isWindows
*/
public String replaceSchedulerVars(boolean isWindows, final String pstrString2Modify) {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::replaceSchedulerVars";
String strTemp = pstrString2Modify;
logger.debug("Start replacing of job- and/or order-parameters .");
if (objJobOrOrderParams != null) {
String[] paramNames = objJobOrOrderParams.names().split(";");
String regExPattern = "(?i)";
String regex = "(?i)";
if (isWindows) {
regExPattern += "'%'SCHEDULER_PARAM_%1$s'%'";
}
else {
regExPattern += "\\$\\{?SCHEDULER_PARAM_%1$s\\}?";
}
logger.debug("regExPattern = " + regExPattern);
for (String name : paramNames) {
/**
* \todo
* TODO os-abh�ngigkeit besser herstellen als hier gemacht
*
* TODO Es ist doch eigentlich noch viel besser, wenn die Variablen
* (zus�tzlich) als Environment-variablen gesetzt werden.
*/
String strParamValue = objJobOrOrderParams.value(name);
if (name.contains("password") == false) {
logger.debug("name = " + name + ", value = " + strParamValue);
}
regex = String.format(regExPattern, name);
// if (isWindows) {
// regex += "%SCHEDULER_PARAM_" + name + "%";
// }
// else {
// regex += "\\$\\{?SCHEDULER_PARAM_" + name + "\\}?";
// }
strTemp = myReplaceAll(strTemp, regex, strParamValue);
}
logger.info("string after replacing-operation is = \n" + strTemp);
}
else {
logger.debug("No job- or order-parameters found. No replacing was done.");
}
return strTemp;
}
/**
*
* \brief myReplaceAll
*
* \details
*
* \return String
*
* @param source
* @param what
* @param replacement
*/
public String myReplaceAll(String source, String what, String replacement) {
String newReplacement = replacement.replaceAll("\\$", "\\\\\\$");
return source.replaceAll("(?m)" + what, newReplacement);
}
/**
*
* \brief StackTrace2String
*
* \details
* This Method creates a String with all infos from the stack as a trace.
*
* \return String
*
* @param e
*/
public String StackTrace2String(final Exception e) {
String strT = e.getMessage() + "\n";
final StackTraceElement arrStack[] = e.getStackTrace();
for (final StackTraceElement objS : arrStack) {
strT += objS.toString() + "\n";
}
return strT;
} // void ShowStackTrace (Exception e)
protected JSJobUtilities getJSJobUtilities() {
return this;
}
@Override
public void setJSJobUtilites(JSJobUtilities pobjJSJobUtilities) {
// TODO Auto-generated method stub
}
@SuppressWarnings("unchecked")
protected HashMap<String, String> DeletePrefix(HashMap<String, String> phsmParameters, String pstrPrefix) {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::DeletePrefix";
String strTemp;
HashMap<String, String> hsmNewMap = new HashMap<String, String>();
if (phsmParameters != null) {
for (final Object element : phsmParameters.entrySet()) {
final Map.Entry<String, String> mapItem = (Map.Entry<String, String>) element;
String strMapKey = mapItem.getKey().toString();
if (mapItem.getValue() != null) {
strTemp = mapItem.getValue().toString();
}
else {
strTemp = null;
}
// hsmNewMap.put(strMapKey, strTemp);
// logger.debug("strMapKey:" + strMapKey + " strTemp:" +strTemp + "pstrPrefix:" + pstrPrefix );
if (strMapKey.startsWith(pstrPrefix)) {
// TODO avoid java.util.ConcurrentModificationException
// (http://java.sun.com/javase/6/docs/api/java/util/Iterator.html#remove() )
// phsmParameters.remove(strMapKey);
strMapKey = strMapKey.replaceAll(pstrPrefix, "");
// logger.debug("strMapKey after replace:" + strMapKey );
hsmNewMap.put(strMapKey, strTemp);
mapItem.setValue("\n");
}
else { // possible case: <nodeName>/<prefix><name> -> <nodeName>/<name>
String strP = "/" + pstrPrefix;
if (strMapKey.contains(strP)) {
strMapKey = strMapKey.replace(strP, "/");
hsmNewMap.put(strMapKey, strTemp);
mapItem.setValue("\n");
}
}
}
}
return hsmNewMap;
} // private HashMap <String, String> DeletePrefix
@Override // JSJobUtilities
public String getCurrentNodeName() {
final String conMethodName = conClassName + "::getNodeName";
String lstrNodeName = "";
Order objCurrentOrder = spooler_task.order();
if (objCurrentOrder != null) {
lstrNodeName = objCurrentOrder.state();
logger.info (String.format("%1$s: Current NodeName is '%2$s'.", conMethodName, lstrNodeName));
}
else {
Job objCurrentJob = spooler_task.job();
lstrNodeName = objCurrentJob.name();
logger.info (String.format("%1$s: Current Job is '%2$s'.", conMethodName, lstrNodeName));
}
return lstrNodeName;
} // public String getNodeName
@Override
public Object getSpoolerObject() {
return spooler;
}
@Override
public String executeXML(String pstrJSXmlCommand) {
String strX = spooler.execute_xml(pstrJSXmlCommand);
return strX;
}
}