package center.task;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ru.vassaev.core.PrmInterface;
import ru.vassaev.core.io.ByteMsg;
import ru.vassaev.core.types.TimeList;
import ru.vassaev.core.base.Null;
import ru.vassaev.core.exception.SysException;
import ru.vassaev.core.util.Strings;
import ru.vassaev.core.util.Xml;
import center.task.api.ATaskAPI;
import center.task.api.ITaskAPI;
import center.task.prm.IDependentParam;
import center.task.prm.Prm;
import center.task.prm.tp.Int;
import center.task.prm.tp.PrmFactory;
import center.task.prm.tp.Str;
/**
* Класс для создания задания с заданным набором параметров
*
* @author Vassaev A.V.
* @version 1.0
*
*/
public class NewTaskInfo extends ATaskInfo {
protected Str task_alias;
protected Str task_api;
protected Str classname;
protected Int block_duration;
protected Int finish_duration;
protected Str arch_day;
protected Int processor_id;
private Set<Object> deletedfiles;
private Map<String, Object> prms_parent;
public NewTaskInfo() throws SysException {
super();
}
public void load(ATaskInfo parent, ATaskInfo extend, Element e)
throws SysException {
super.load(parent, extend, e);
prms = new TreeMap<String, Object>();
prms_parent = new TreeMap<String, Object>();
if (e != null) {
loadNewParams(prms, prms_parent, e);
Element task_api = (Element) Strings.getXMLObject(e, "task_api");
if (task_api != null)
this.task_api = new Str(task_api, this);
Element task_alias = (Element) Strings
.getXMLObject(e, "task_alias");
if (task_alias != null)
this.task_alias = new Str(task_alias, this);
Element classname = (Element) Strings.getXMLObject(e, "classname");
if (classname != null)
this.classname = new Str(classname, this);
Element block_duration = (Element) Strings.getXMLObject(e,
"block_duration");
if (block_duration != null)
this.block_duration = new Int(block_duration, this);
Element finish_duration = (Element) Strings.getXMLObject(e,
"finish_duration");
if (finish_duration != null)
this.finish_duration = new Int(finish_duration, this);
Element arch_day = (Element) Strings.getXMLObject(e, "arch_day");
if (arch_day != null)
this.arch_day = new Str(arch_day, this);
Element processor_id = (Element) Strings.getXMLObject(e,
"processor_id");
if (processor_id != null)
this.processor_id = new Int(processor_id, this);
Element df = (Element) Strings.getXMLObject(e, "deleted-files");
deletedfiles = new HashSet<Object>();
if (df != null) {
NodeList files = Xml.getElementsByTagName(df, "file");
Element file;
for (int i = 0; i < files.getLength(); i++) {
file = (Element) files.item(i);
Object x = Prm.getPrm(file);
deletedfiles.add(x);
}
}
}
}
protected Map<String, Object> getPrmsBySpace(String space) {
Map<String, Object> prms = super.getPrmsBySpace(space);
if (prms != null)
return prms;
if ("classname".equals(space)) {
prms = new HashMap<String, Object>();
prms.put("", classname);
return prms;
}
if ("block_duration".equals(space)) {
prms = new HashMap<String, Object>();
prms.put("", block_duration);
return prms;
}
if ("finish_duration".equals(space)) {
prms = new HashMap<String, Object>();
prms.put("", finish_duration);
return prms;
}
if ("processor_id".equals(space)) {
prms = new HashMap<String, Object>();
prms.put("", processor_id);
return prms;
}
return null;
}
public void loadNewParams(Map<String, Object> prm_,
Map<String, Object> prm_parent, Element pnl) throws SysException {
NodeList nl = pnl.getChildNodes();
PrmFactory fact = new PrmFactory();
for (int i = nl.getLength() - 1; i >= 0; i--) {
Node n = nl.item(i);
if (n.getNodeType() != Node.ELEMENT_NODE)
continue;
String x = n.getNodeName();
Element e = (Element) n;
String name = Strings.getXMLValue(e, "#name");
String grp = Strings.getXMLValue(e, "#grp");
String fn = (grp == null || grp.length() == 0) ? name : grp + "/"
+ name;
if (x.equals("prm"))
prm_.put(fn, fact.getParam(e, this));
if (x.equals("parent"))
prm_parent.put(fn, fact.getParam(e, this));
}
}
/**
* Регистрация задания
*
* @param ta
* - ссылка на API
* @param parent_context
* - родительский контекст
* @param id_processor
* - идентификатор инициатора
* @param grp
* - группа дополнительных параметров
* @param addprms
* - дополнительные параметры к контексту (Map, PrmInterface,
* ByteMsg)
* @throws SysException
* - если невозможно создать задание
* @return Контекст новой задачи в состоянии READY
*/
public Context createAndReadyTask(ITaskAPI ta, Context parent_context,
long id_processor, String grp, Object addprms) throws SysException {
Context cntx;
// Инициализация контекста
cntx = new Context(parent_context, id_processor, 0, ta, this);
return createAndReadyTask(cntx, grp, addprms);
}
public Context createAndReadyTask(Context cntx, String grp, Object addprms)
throws SysException {
String task_api;
String alias;
try {
alias = (task_alias != null) ? (String) task_alias.getValue(cntx)
: cntx.ta.getAlias();
if (alias == null)
alias = cntx.ta.getAlias();
task_api = (this.task_api != null) ?
(String) this.task_api.getValue(cntx)
: cntx.ta.getClass().getCanonicalName();
if (task_api == null)
task_api = cntx.ta.getClass().getCanonicalName();
} catch (CalculateException e1) {
throw new SysException(e1);
}
ITaskAPI ta = ATaskAPI.getInstance(task_api, cntx.ta.getClass(), alias);
if (ta == null)
ta = cntx.ta;
long id_task;
Context parent_context = cntx.parent;
Long id_processor;
if (!ta.equals(cntx.ta)) {
id_processor = ATaskAPI.getApplicationSubject(ta);
if (id_processor == 0L) {
boolean waiting = true;
do {
try {
id_processor = ta.getSubject(0);
waiting = false;
} catch (SysException e) {
System.out.println("Waiting interface...");
try {
Thread.sleep(1000);// TODO нужен параметр
} catch (InterruptedException e1) {
throw new SysException(e1);
}
}
} while (waiting);
ATaskAPI.setApplicationSubject(ta, id_processor);
}
} else
id_processor = cntx.id_subject;
try {
// Получить класс задания
String cls = (String) classname.getValue(cntx);
// Если класс задания не определен,
if (Null.equ(cls) || cls.equals("")) {
cntx.id_task = -1;
return cntx;
}
// Создадим запись о задании
id_task = ta
.createTask(
id_processor,
cls,
(ta.equals(cntx.ta) && parent_context != null) ? parent_context.id_task
: 0);
} catch (CalculateException e) {
throw new SysException(e);
}
Context res;
if (ta.equals(cntx.ta)) {
res = cntx;
res.id_task = id_task;
} else
res = new Context(parent_context, id_processor, id_task, ta, this);
Set<Entry<String, Object>> s = prms.entrySet();
for (Entry<String, Object> x : s)
try {
Object v = x.getValue();
if (Null.equ(v))
continue;
String name = x.getKey();
if (v instanceof IDependentParam) {
IDependentParam d = (IDependentParam) v;
if (!d.isNoSave()) {
TimeList tl = cntx.getTimeList(d.getGLName(), d);
Object vl = d.getValue(cntx);
if (Null.equ(vl))
continue;
long wait = tl.getWaitTime();
long calc = tl.getWorkTime();
long sc = tl.getSystemCallTime();
// ta.setTaskParamObject(id_task, x.getKey(),
// d.getValue(cntx));
ta.setParamObject(id_task, name, vl, wait, calc, sc);
}
} else {
// ta.setTaskParamString(id_task, x.getKey(), v.toString());
ta.setParamObject(id_task, name, v);
}
} catch (CalculateException e) {
throw new SysException(e);
}
// Установить доп. параметры в задании
if (!Null.equ(addprms))
if (addprms instanceof Map) {
Map<String, Object> aprms = (Map<String, Object>) addprms;
for (Entry<String, Object> e : aprms.entrySet()) {
String n = (grp == null) ? e.getKey() : grp + "/"
+ e.getKey();
// ta.setTaskParamObject(id_task, n, e.getValue());
ta.setParamObject(id_task, n, e.getValue());
}
} else if (addprms instanceof PrmInterface) {
PrmInterface aprms = (PrmInterface) addprms;
for (String k : aprms.getFieldNames()) {
String n = (grp == null) ? k : grp + "/" + k;
// ta.setTaskParamString(id_task, n, aprms.getField(k));
ta.setParamObject(id_task, n, aprms.getField(k));
}
} else if (addprms instanceof ByteMsg) {
ByteMsg msg = (ByteMsg) addprms;
PrmInterface aprms = msg.getPrmInterface();
for (String k : aprms.getFieldNames()) {
String n = (grp == null) ? k : grp + "/" + k;
// ta.setTaskParamString(id_task, n, aprms.getField(k));
ta.setParamObject(id_task, n, aprms.getField(k));
}
}
try {
String finish_duration = Strings
.getString((this.finish_duration != null) ? this.finish_duration
.getValue(cntx) : null);
String block_duration = Strings
.getString((this.block_duration != null) ? this.block_duration
.getValue(cntx) : null);
Double arch_day = Strings
.parseDouble((this.arch_day != null) ? this.arch_day
.getValue(cntx) : null);
ta.setTaskDT(id_task, null, finish_duration, block_duration,
arch_day);
// Будет обрабатывать текущий обработчик?
if (this.processor_id != null)
res.id_task = ta.setReady(id_processor, id_task,
Strings.parseLong(processor_id.getValue(cntx)));
else
res.id_task = ta.setReady(id_processor, id_task, null);
return res;
} catch (CalculateException e) {
throw new SysException(e);
}
}
public Set<String> depedentOnParent() {
Set<String> s = classname.depedentOnParent();
if (block_duration != null)
s = Strings.addAllToSet(s, block_duration.depedentOnParent());
if (finish_duration != null)
s = Strings.addAllToSet(s, finish_duration.depedentOnParent());
if (arch_day != null)
s = Strings.addAllToSet(s, arch_day.depedentOnParent());
if (processor_id != null)
s = Strings.addAllToSet(s, processor_id.depedentOnParent());
for (Map.Entry<String, Object> e : prms_parent.entrySet()) {
Object o = e.getValue();
if (o != null && o instanceof IDependentParam) {
IDependentParam p = (IDependentParam) o;
s = Strings.addAllToSet(s, p.depedentOnParent());
}
}
return s;
}
public void delete_files(Context cntx) {
for (Object o : deletedfiles) {
if (o == null)
continue;
if (o instanceof Prm) {
try {
o = ((Prm) o).getObject(cntx);
} catch (SysException e) {
// TODO Auto-generated catch block
e.printStackTrace();
continue;
} catch (CalculateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
continue;
}
if (o == null)
continue;
}
File f;
if (o instanceof File) {
f = (File) o;
} else {
f = new File(Strings.getString(o));
}
boolean b = false;
if (f.exists() && f.isFile())
b = f.delete();
try {
if (b)
System.out.println("File '" + f.getCanonicalPath()
+ "' was deleted");
else
System.out.println("Impossible to delete file '"
+ f.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}