...
 
Commits (3)
......@@ -18,6 +18,9 @@ Require-Bundle: org.eclipse.jface;bundle-version="3.8.0",
org.eclipse.osgi.services;bundle-version="3.3.100"
Import-Package: ch.elexis.core.data.events,
ch.elexis.core.model,
ch.elexis.core.model.tasks,
ch.elexis.core.services.holder,
ch.elexis.core.tasks.model,
ch.elexis.core.ui.dialogs,
ch.elexis.core.ui.icons,
ch.elexis.data,
......
......@@ -27,7 +27,7 @@ public class MailClientComponent {
}
public static String getLastErrorMessage(){
String message = "Kein Fehler";
String message = "";
if (mailClient != null) {
Optional<ErrorTyp> error = mailClient.getLastError();
if(error.isPresent()) {
......
......@@ -84,16 +84,6 @@ public class AttachmentsComposite extends Composite {
getParent().layout(true, true);
}
public String getAttachments(){
String ret = attachments;
if (StringUtils.isNotBlank(ret)) {
ret += ":::" + AttachmentsUtil.toAttachments(documents);
} else {
ret = AttachmentsUtil.toAttachments(documents);
}
return ret;
}
public void addDocument(IDocument document){
if (document != null) {
if (StringUtils.isBlank(documents)) {
......@@ -116,4 +106,12 @@ public class AttachmentsComposite extends Composite {
this.documents = documents;
updateAttachmentsLabel();
}
public String getAttachments(){
return attachments;
}
public String getDocuments(){
return documents;
}
}
package ch.elexis.core.mail.ui.dialogs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuListener;
......@@ -20,18 +23,29 @@ import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.handlers.IHandlerService;
import org.slf4j.LoggerFactory;
import ch.elexis.core.data.events.ElexisEventDispatcher;
import ch.elexis.core.mail.MailAccount;
import ch.elexis.core.mail.MailAccount.TYPE;
import ch.elexis.core.mail.MailMessage;
import ch.elexis.core.mail.TaskUtil;
import ch.elexis.core.mail.ui.client.MailClientComponent;
import ch.elexis.core.services.holder.StoreToStringServiceHolder;
import ch.elexis.core.tasks.model.ITaskDescriptor;
import ch.elexis.core.ui.dialogs.KontaktSelektor;
import ch.elexis.data.Kontakt;
import ch.elexis.data.Mandant;
......@@ -50,9 +64,16 @@ public class SendMailDialog extends TitleAreaDialog {
private String textString = "";
private AttachmentsComposite attachments;
private Command createOutboxCommand;
public SendMailDialog(Shell parentShell){
super(parentShell);
setShellStyle(getShellStyle() | SWT.RESIZE);
ICommandService commandService =
(ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
createOutboxCommand =
commandService.getCommand("at.medevit.elexis.outbox.ui.command.createElementNoUi");
}
@Override
......@@ -272,6 +293,48 @@ public class SendMailDialog extends TitleAreaDialog {
super.okPressed();
}
@Override
protected void createButtonsForButtonBar(Composite parent){
Button outboxBtn = createButton(parent, -1, "in Oubox ablegen", false);
super.createButtonsForButtonBar(parent);
outboxBtn.setEnabled(createOutboxCommand != null && createOutboxCommand.isEnabled());
outboxBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e){
String validation = getValidation();
if (validation != null) {
setErrorMessage(validation);
return;
} else {
setErrorMessage(null);
}
createOutboxElement();
}
private void createOutboxElement(){
MailMessage message =
new MailMessage().to(getTo()).cc(getCc()).subject(getSubject()).text(getText());
message.setAttachments(attachments.getAttachments());
message.setDocuments(attachments.getDocuments());
Optional<ITaskDescriptor> descriptor =
TaskUtil.createSendMailTaskDescriptor(account.getId(), message);
// now try to call the create outbox command, is not part of core ...
try {
HashMap<String, String> params = new HashMap<String, String>();
params.put("at.medevit.elexis.outbox.ui.command.createElementNoUi.dburi",
StoreToStringServiceHolder.getStoreToString(descriptor.get()));
ParameterizedCommand parametrizedCommmand =
ParameterizedCommand.generateCommand(createOutboxCommand, params);
PlatformUI.getWorkbench().getService(IHandlerService.class)
.executeCommand(parametrizedCommmand, null);
} catch (Exception ex) {
LoggerFactory.getLogger(getClass())
.warn("Create OutboxElement command not available");
}
}
});
}
private String getValidation(){
StructuredSelection accountSelection = (StructuredSelection) accountsViewer.getSelection();
if (accountSelection == null || accountSelection.isEmpty()) {
......@@ -321,7 +384,11 @@ public class SendMailDialog extends TitleAreaDialog {
return account;
}
public String getAttachments(){
public String getAttachmentsString(){
return attachments.getAttachments();
}
public String getDocumentsString(){
return attachments.getDocuments();
}
}
package ch.elexis.core.mail.ui.handlers;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Optional;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
......@@ -13,13 +12,16 @@ import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.handlers.HandlerUtil;
import ch.elexis.core.mail.AttachmentsUtil;
import ch.elexis.core.mail.MailMessage;
import ch.elexis.core.mail.TaskUtil;
import ch.elexis.core.mail.ui.client.MailClientComponent;
import ch.elexis.core.mail.ui.dialogs.SendMailDialog;
import ch.elexis.core.model.tasks.TaskException;
import ch.elexis.core.tasks.model.ITask;
import ch.elexis.core.tasks.model.ITaskDescriptor;
import ch.elexis.core.tasks.model.TaskState;
/**
* Handler for sending an Email. The mail can be specified via the command parameters.
......@@ -36,6 +38,8 @@ import ch.elexis.core.mail.ui.dialogs.SendMailDialog;
*/
public class SendMailHandler extends AbstractHandler implements IHandler {
private ITask task;
@Override
public Object execute(ExecutionEvent event) throws ExecutionException{
SendMailDialog sendMailDialog = new SendMailDialog(HandlerUtil.getActiveShell(event));
......@@ -63,82 +67,50 @@ public class SendMailHandler extends AbstractHandler implements IHandler {
if (sendMailDialog.open() == Dialog.OK) {
MailMessage message =
new MailMessage().to(sendMailDialog.getTo()).cc(sendMailDialog.getCc())
.subject(sendMailDialog.getSubject()).text(sendMailDialog.getText());
attachments = sendMailDialog.getAttachments();
if (attachments != null && !attachments.isEmpty()) {
List<File> attachmentList = AttachmentsUtil.getAttachmentsFiles(attachments);
for (File file : attachmentList) {
message.addAttachment(file);
new MailMessage().to(sendMailDialog.getTo()).cc(sendMailDialog.getCc())
.subject(sendMailDialog.getSubject()).text(sendMailDialog.getText());
message.setAttachments(sendMailDialog.getAttachmentsString());
message.setDocuments(sendMailDialog.getDocumentsString());
Optional<ITaskDescriptor> taskDescriptor =
TaskUtil.createSendMailTaskDescriptor(sendMailDialog.getAccount().getId(), message);
if (taskDescriptor.isPresent()) {
try {
new ProgressMonitorDialog(HandlerUtil.getActiveShell(event)).run(false, false,
new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException{
try {
monitor.beginTask("Send Mail ...", IProgressMonitor.UNKNOWN);
task = TaskUtil.executeTaskSync(taskDescriptor.get(), monitor);
monitor.done();
} catch (TaskException e) {
MessageDialog.openError(HandlerUtil.getActiveShell(event),
"Fehler", "Versenden konnte nicht gestartet werden.");
}
}
});
} catch (InvocationTargetException | InterruptedException e) {
MessageDialog.openError(HandlerUtil.getActiveShell(event), "Fehler",
"Versenden konnte nicht gestartet werden.");
}
}
Display display = Display.getDefault();
try {
MailSendRunnable mailSendRunnable =
new MailSendRunnable(display, sendMailDialog, message, event);
new ProgressMonitorDialog(HandlerUtil.getActiveShell(event)).run(false, false,
mailSendRunnable);
return mailSendRunnable.isSuccess();
} catch (InvocationTargetException | InterruptedException e) {
MessageDialog.openError(HandlerUtil.getActiveShell(event), "Fehler",
"Versenden konnte nicht gestartet werden.");
}
}
return false;
}
class MailSendRunnable implements IRunnableWithProgress {
private final Display display;
private final SendMailDialog sendMailDialog;
private final ExecutionEvent event;
private final MailMessage message;
private boolean success;
public MailSendRunnable(Display display, SendMailDialog sendMailDialog, MailMessage message,
ExecutionEvent event){
this.display = display;
this.sendMailDialog = sendMailDialog;
this.event = event;
this.message = message;
this.success = false;
}
public boolean isSuccess(){
return success;
}
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException{
monitor.beginTask("Send Mail ...", IProgressMonitor.UNKNOWN);
if (MailClientComponent.getMailClient().sendMail(sendMailDialog.getAccount(),
message)) {
success = true;
// new OutputLog();
display.asyncExec(new Runnable() {
@Override
public void run(){
MessageDialog.openInformation(HandlerUtil.getActiveShell(event),
"E-Mail versand", "E-Mail erfolgreich versendet.");
}
});
} else {
success = false;
display.asyncExec(new Runnable() {
@Override
public void run(){
String errorMessage = MailClientComponent.getLastErrorMessage();
if (!task.isSucceeded()) {
String errorMessage = MailClientComponent.getLastErrorMessage();
if (errorMessage.isEmpty()) {
MessageDialog.openError(HandlerUtil.getActiveShell(event), "Fehler",
"Versenden konnte nicht gestartet werden.");
} else {
MessageDialog.openError(HandlerUtil.getActiveShell(event), "Fehler",
errorMessage);
}
});
} else {
MessageDialog.openInformation(HandlerUtil.getActiveShell(event),
"E-Mail versand", "E-Mail erfolgreich versendet.");
}
return task.getState() == TaskState.COMPLETED;
}
monitor.done();
}
return false;
}
}
package ch.elexis.core.mail.ui.handlers;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
......@@ -62,10 +60,7 @@ public class SendMailNoUiHandler extends AbstractHandler implements IHandler {
MailMessage message = new MailMessage().to(to).subject(StringUtils.defaultString(subject))
.text(StringUtils.defaultString(text));
if (attachments != null && !attachments.isEmpty()) {
List<File> attachmentList = getAttachmentsList(attachments);
for (File file : attachmentList) {
message.addAttachment(file);
}
message.setAttachments(attachments);
}
if (MailClientComponent.getMailClient().sendMail(mailAccount, message)) {
return null;
......@@ -85,15 +80,4 @@ public class SendMailNoUiHandler extends AbstractHandler implements IHandler {
}
return null;
}
private List<File> getAttachmentsList(String attachments){
List<File> ret = new ArrayList<File>();
if (attachments != null && !attachments.isEmpty()) {
String[] parts = attachments.split(":::");
for (String string : parts) {
ret.add(new File(string));
}
}
return ret;
}
}
......@@ -9,7 +9,9 @@ Multi-Release: true
Bundle-ActivationPolicy: lazy
Service-Component: OSGI-INF/ch.elexis.core.mail.internal.MailClient.xml,
OSGI-INF/ch.elexis.core.mail.internal.DocumentStoreServiceHolder.xml,
OSGI-INF/ch.elexis.core.mail.internal.DocumentConverterServiceHolder.xml
OSGI-INF/ch.elexis.core.mail.internal.DocumentConverterServiceHolder.xml,
OSGI-INF/ch.elexis.core.mail.internal.MailClientRunnableFactory.xml,
OSGI-INF/ch.elexis.core.mail.TaskUtil.xml
Require-Bundle: ch.elexis.core.data;bundle-version="3.2.0",
javax.mail.glassfish;bundle-version="1.4.1",
org.eclipse.osgi.services;bundle-version="3.3.100",
......@@ -17,6 +19,11 @@ Require-Bundle: ch.elexis.core.data;bundle-version="3.2.0",
Export-Package: ch.elexis.core.mail
Automatic-Module-Name: ch.elexis.core.mail
Import-Package: ch.elexis.core.documents,
ch.elexis.core.tasks.model,
com.google.gson;version="2.8.5",
com.google.gson.annotations;version="2.8.5",
javax.activation;version="1.1.0",
org.apache.commons.io;version="2.5.0",
org.apache.commons.lang;version="2.6.0"
org.apache.commons.lang;version="2.6.0",
org.eclipse.core.runtime;version="3.5.0",
org.json
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="ch.elexis.core.mail.TaskUtil">
<reference bind="setTaskService" interface="ch.elexis.core.tasks.model.ITaskService" name="TaskService"/>
<implementation class="ch.elexis.core.mail.TaskUtil"/>
</scr:component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" name="ch.elexis.core.mail.internal.MailClientRunnableFactory">
<service>
<provide interface="ch.elexis.core.model.tasks.IIdentifiedRunnableFactory"/>
</service>
<reference cardinality="1..1" field="mailClient" interface="ch.elexis.core.mail.IMailClient" name="mailClient"/>
<implementation class="ch.elexis.core.mail.internal.MailClientRunnableFactory"/>
</scr:component>
\ No newline at end of file
......@@ -4,4 +4,6 @@ bin.includes = META-INF/,\
.,\
OSGI-INF/ch.elexis.core.mail.internal.MailClient.xml,\
OSGI-INF/ch.elexis.core.mail.internal.DocumentStoreServiceHolder.xml,\
OSGI-INF/ch.elexis.core.mail.internal.DocumentConverterServiceHolder.xml
OSGI-INF/ch.elexis.core.mail.internal.DocumentConverterServiceHolder.xml,\
OSGI-INF/ch.elexis.core.mail.internal.MailClientRunnableFactory.xml,\
OSGI-INF/ch.elexis.core.mail.TaskUtil.xml
package ch.elexis.core.mail;
import java.io.File;
import java.util.ArrayList;
import java.io.Serializable;
import java.util.List;
import javax.mail.internet.AddressException;
......@@ -9,6 +9,7 @@ import javax.mail.internet.InternetAddress;
import org.apache.commons.lang.StringUtils;
/**
* Class representing a Message that can be sent using a {@link MailAccount} and a
* {@link IMailClient}. <br />
......@@ -18,14 +19,21 @@ import org.apache.commons.lang.StringUtils;
* @author thomas
*
*/
public class MailMessage {
public class MailMessage implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5874662524515670629L;
private String to;
private String cc;
private String subject;
private String text;
private List<File> attachments;
private String attachmentsString;
private String documentsString;
/**
* Set the to address.
......@@ -139,7 +147,7 @@ public class MailMessage {
* @return
*/
public boolean hasAttachments(){
return attachments != null && !attachments.isEmpty();
return StringUtils.isNotBlank(documentsString) || StringUtils.isNotBlank(attachmentsString);
}
/**
......@@ -148,18 +156,21 @@ public class MailMessage {
* @return
*/
public List<File> getAttachments(){
return attachments;
String attachmentFilesString = attachmentsString;
if (StringUtils.isNotBlank(attachmentFilesString)
&& !StringUtils.isBlank(documentsString)) {
attachmentFilesString += ":::" + AttachmentsUtil.toAttachments(documentsString);
} else if (!StringUtils.isBlank(documentsString)) {
attachmentFilesString = AttachmentsUtil.toAttachments(documentsString);
}
return AttachmentsUtil.getAttachmentsFiles(attachmentFilesString);
}
/**
* Add an attachment.
*
* @param attachment
*/
public void addAttachment(File attachment){
if (attachments == null) {
attachments = new ArrayList<File>();
}
attachments.add(attachment);
public void setAttachments(String attachments){
this.attachmentsString = attachments;
}
public void setDocuments(String documents){
this.documentsString = documents;
}
}
package ch.elexis.core.mail;
import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import org.eclipse.core.runtime.IProgressMonitor;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.LoggerFactory;
import ch.elexis.core.mail.internal.SendMailRunnable;
import ch.elexis.core.model.tasks.IIdentifiedRunnable;
import ch.elexis.core.model.tasks.TaskException;
import ch.elexis.core.tasks.model.ITask;
import ch.elexis.core.tasks.model.ITaskDescriptor;
import ch.elexis.core.tasks.model.ITaskService;
import ch.elexis.core.tasks.model.TaskTriggerType;
@Component
public class TaskUtil {
private static ITaskService taskService;
@Reference
public void setTaskService(ITaskService taskService){
TaskUtil.taskService = taskService;
}
/**
* Create a new {@link ITaskDescriptor} for sending the message using the account.
*
* @param accountId
* @param message
* @return
*/
public static Optional<ITaskDescriptor> createSendMailTaskDescriptor(String accountId,
MailMessage message){
Optional<IIdentifiedRunnable> sendMailRunnable = taskService.getIdentifiedRunnables()
.stream().filter(ir -> ir.getId().equals(SendMailRunnable.RUNNABLE_ID)).findFirst();
if (sendMailRunnable.isPresent()) {
try {
ITaskDescriptor descriptor =
taskService.createTaskDescriptor(sendMailRunnable.get());
Map<String, Serializable> runContext = descriptor.getRunContext();
runContext.put("accountId", accountId);
runContext.put("message", message);
descriptor.setRunContext(runContext);
taskService.saveTaskDescriptor(descriptor);
return Optional.of(descriptor);
} catch (TaskException e) {
LoggerFactory.getLogger(TaskUtil.class)
.error("Error creating send mail task descriptor", e);
}
}
return Optional.empty();
}
public static ITask executeTaskSync(ITaskDescriptor iTaskDescriptor,
IProgressMonitor progressMonitor) throws TaskException{
ITask task = taskService.trigger(iTaskDescriptor, progressMonitor, TaskTriggerType.MANUAL,
Collections.emptyMap());
while (!task.isFinished()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// ignore
}
}
return task;
}
}
package ch.elexis.core.mail.internal;
import java.util.Collections;
import java.util.List;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import ch.elexis.core.mail.IMailClient;
import ch.elexis.core.model.tasks.IIdentifiedRunnable;
import ch.elexis.core.model.tasks.IIdentifiedRunnableFactory;
@Component
public class MailClientRunnableFactory implements IIdentifiedRunnableFactory {
@Reference
private IMailClient mailClient;
@Override
public List<IIdentifiedRunnable> getProvidedRunnables(){
return Collections.singletonList(new SendMailRunnable(mailClient));
}
}
package ch.elexis.core.mail.internal;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.eclipse.core.runtime.IProgressMonitor;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import com.google.gson.Gson;
import ch.elexis.core.mail.IMailClient;
import ch.elexis.core.mail.MailAccount;
import ch.elexis.core.mail.MailMessage;
import ch.elexis.core.model.tasks.IIdentifiedRunnable;
import ch.elexis.core.model.tasks.TaskException;
public class SendMailRunnable implements IIdentifiedRunnable {
public static final String RUNNABLE_ID = "sendMailFromContext";
private Gson gson = new Gson();
private IMailClient mailClient;
public SendMailRunnable(IMailClient mailClient){
this.mailClient = mailClient;
this.gson = new Gson();
}
@Override
public String getId(){
return RUNNABLE_ID;
}
@Override
public String getLocalizedDescription(){
return "Send an email using the information from the task context";
}
@Override
public Map<String, Serializable> getDefaultRunContext(){
Map<String, Serializable> defaultRunContext = new HashMap<>();
defaultRunContext.put("accountId", RunContextParameter.VALUE_MISSING_REQUIRED);
defaultRunContext.put("message",
RunContextParameter.VALUE_MISSING_REQUIRED);
return defaultRunContext;
}
@Override
public Map<String, Serializable> run(Map<String, Serializable> runContext,
IProgressMonitor progressMonitor, Logger logger) throws TaskException{
String accountId = (String) runContext.get("accountId");
MailMessage message =
getRunContextEntryTyped(runContext, "message", MailMessage.class);
Optional<MailAccount> account = mailClient.getAccount(accountId);
if (message != null && account.isPresent()) {
mailClient.sendMail(account.get(), message);
}
return null;
}
private <T> T getRunContextEntryTyped(Map<String, Serializable> map, String key,
Class<T> clazz){
try {
String valueToString = JSONObject.valueToString(map.get(key));
return gson.fromJson(valueToString, clazz);
} catch (JSONException e) {
// do nothing
}
return null;
}
}
......@@ -3,6 +3,7 @@
<property name="service.model.name" value="ch.elexis.core.tasks.model"/>
<service>
<provide interface="ch.elexis.core.services.IModelService"/>
<provide interface="ch.elexis.core.services.IStoreToStringContribution"/>
</service>
<reference cardinality="1..1" field="entityManager" interface="ch.elexis.core.services.IElexisEntityManager" name="entityManager"/>
<reference cardinality="1..1" field="eventAdmin" interface="org.osgi.service.event.EventAdmin" name="eventAdmin"/>
......
......@@ -100,6 +100,16 @@
</eGenericType>
</eParameters>
</eOperations>
<eOperations name="getRunContextEntryTyped">
<eGenericType eTypeParameter="#//ITask/getRunContextEntryTyped/T"/>
<eTypeParameters name="T"/>
<eParameters name="key" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
<eParameters name="clazz">
<eGenericType eClassifier="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EJavaClass">
<eTypeArguments eTypeParameter="#//ITask/getRunContextEntryTyped/T"/>
</eGenericType>
</eParameters>
</eOperations>
<eOperations name="isSucceeded" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EBoolean">
<eAnnotations source="http://www.eclipse.org/emf/2002/GenModel">
<details key="documentation" value="The task is successfully and purposefully finished."/>
......
......@@ -83,6 +83,11 @@
<genParameters ecoreParameter="model.ecore#//ITask/getResultEntryTyped/clazz"/>
<genTypeParameters ecoreTypeParameter="model.ecore#//ITask/getResultEntryTyped/T"/>
</genOperations>
<genOperations ecoreOperation="model.ecore#//ITask/getRunContextEntryTyped">
<genParameters ecoreParameter="model.ecore#//ITask/getRunContextEntryTyped/key"/>
<genParameters ecoreParameter="model.ecore#//ITask/getRunContextEntryTyped/clazz"/>
<genTypeParameters ecoreTypeParameter="model.ecore#//ITask/getRunContextEntryTyped/T"/>
</genOperations>
<genOperations ecoreOperation="model.ecore#//ITask/isSucceeded"/>
<genOperations ecoreOperation="model.ecore#//ITask/isFailed"/>
<genOperations ecoreOperation="model.ecore#//ITask/setStateCompletedManual">
......
......@@ -238,6 +238,14 @@ public interface ITask extends Identifiable, Deleteable {
*/
<T> T getResultEntryTyped(String key, Class<T> clazz);
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model
* @generated
*/
<T> T getRunContextEntryTyped(String key, Class<T> clazz);
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
......
......@@ -738,6 +738,16 @@ public class ModelPackageImpl extends EPackageImpl implements ModelPackage {
g1 = createEGenericType(t1);
initEOperation(op, g1);
op = addEOperation(iTaskEClass, null, "getRunContextEntryTyped", 0, 1, IS_UNIQUE, IS_ORDERED);
t1 = addETypeParameter(op, "T");
addEParameter(op, ecorePackage.getEString(), "key", 0, 1, IS_UNIQUE, IS_ORDERED);
g1 = createEGenericType(ecorePackage.getEJavaClass());
g2 = createEGenericType(t1);
g1.getETypeArguments().add(g2);
addEParameter(op, g1, "clazz", 0, 1, IS_UNIQUE, IS_ORDERED);
g1 = createEGenericType(t1);
initEOperation(op, g1);
addEOperation(iTaskEClass, ecorePackage.getEBoolean(), "isSucceeded", 0, 1, IS_UNIQUE, IS_ORDERED);
addEOperation(iTaskEClass, ecorePackage.getEBoolean(), "isFailed", 0, 1, IS_UNIQUE, IS_ORDERED);
......
package ch.elexis.core.tasks.internal.model.service;
import java.util.Optional;
import javax.persistence.EntityManager;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.EventAdmin;
import org.slf4j.LoggerFactory;
import ch.elexis.core.common.ElexisEvent;
import ch.elexis.core.constants.StringConstants;
import ch.elexis.core.jpa.model.adapter.AbstractModelService;
import ch.elexis.core.model.Identifiable;
import ch.elexis.core.services.IElexisEntityManager;
import ch.elexis.core.services.IModelService;
import ch.elexis.core.services.IQuery;
import ch.elexis.core.services.IStoreToStringContribution;
@Component(property = IModelService.SERVICEMODELNAME + "=ch.elexis.core.tasks.model")
public class TaskModelService extends AbstractModelService implements IModelService {
public class TaskModelService extends AbstractModelService
implements IModelService, IStoreToStringContribution {
@Reference
private IElexisEntityManager entityManager;
......@@ -59,4 +65,71 @@ public class TaskModelService extends AbstractModelService implements IModelServ
this.entityManager.clearCache();
}
@Override
public Optional<String> storeToString(Identifiable identifiable){
for(Class<?> clazz : identifiable.getClass().getInterfaces()) {
if (clazz.getName().startsWith("ch.elexis.core.tasks.model")) {
return Optional
.of(clazz.getName() + StringConstants.DOUBLECOLON + identifiable.getId());
}
}
return Optional.empty();
}
@Override
public Optional<Identifiable> loadFromString(String storeToString){
if (storeToString == null) {
LoggerFactory.getLogger(getClass()).warn("StoreToString is null");
return Optional.empty();
}
if (storeToString.startsWith("ch.elexis.core.tasks.model")) {
try {
String[] split = splitIntoTypeAndId(storeToString);
// map string to classname
String className = split[0];
String id = split[1];
@SuppressWarnings("unchecked")
Class<Identifiable> clazz =
(Class<Identifiable>) TaskModelService.class.getClassLoader()
.loadClass(className);
if (clazz != null) {
return load(id, clazz);
}
} catch (ClassNotFoundException e) {
LoggerFactory.getLogger(getClass())
.warn("Could not load class of [" + storeToString + "]");
}
}
return Optional.empty();
}
@Override
public Class<?> getEntityForType(String type){
if (type.startsWith("ch.elexis.core.tasks.model")) {
try {
@SuppressWarnings("unchecked")
Class<Identifiable> clazz = (Class<Identifiable>) TaskModelService.class.getClassLoader()
.loadClass(type);
if (clazz != null) {
adapterFactory.getEntityClass(clazz);
}
} catch (ClassNotFoundException e) {
LoggerFactory.getLogger(getClass())
.warn("Could not load class for type [" + type + "]");
}
}
return null;
}
@Override
public String getTypeForEntity(Object entityInstance){
return null;
}
@Override
public String getTypeForModel(Class<?> interfaze){
return null;
}
}
......@@ -194,6 +194,18 @@ public class Task extends AbstractIdDeleteModelAdapter<ch.elexis.core.jpa.entiti
return null;
}
@Override
public <T> T getRunContextEntryTyped(String key, Class<T> clazz){
Map<String, Serializable> map = getRunContext();
try {
String valueToString = JSONObject.valueToString(map.get(key));
return gson.fromJson(valueToString, clazz);
} catch (JSONException e) {
// do nothing
}
return null;
}
@Override
public void setStateCompletedManual(String remark){
String userId = ContextServiceHolder.get().getActiveUser().map(u -> u.getId()).orElse(null);
......@@ -219,7 +231,7 @@ public class Task extends AbstractIdDeleteModelAdapter<ch.elexis.core.jpa.entiti
@Override
public boolean isFinished(){
return (TaskState.COMPLETED == getState() || TaskState.COMPLETED_WARN == getState()
|| TaskState.FAILED == getState());
|| TaskState.FAILED == getState() || TaskState.CANCELLED == getState());
}
private void removeTaskRecord(){
......@@ -292,12 +304,7 @@ public class Task extends AbstractIdDeleteModelAdapter<ch.elexis.core.jpa.entiti
} finally {
ContextServiceHolder.get().setActiveUser(null);
ContextServiceHolder.get().setActiveMandator(null);
if (progressMonitor != null) {
progressMonitor.done();
}
}
}
@Override
......
......@@ -246,6 +246,8 @@ public class TaskServiceImpl implements ITaskService {
String stationIdentifier = contextService.getRootContext().getStationIdentifier();
taskDescriptor.setRunner(StringUtils.abbreviate(stationIdentifier, 64));
contextService.getActiveUser().ifPresent(u -> taskDescriptor.setOwner(u));
saveTaskDescriptor(taskDescriptor);
return taskDescriptor;
......@@ -336,6 +338,7 @@ public class TaskServiceImpl implements ITaskService {
Task task = new Task(taskDescriptor, triggerType, progressMonitor, runContext);
// TODO test if all runContext parameters are satisfied, else reject execution
task.setState(TaskState.QUEUED);
try {
if (taskDescriptor.isSingleton()) {
......@@ -347,12 +350,10 @@ public class TaskServiceImpl implements ITaskService {
}
triggeredTasks.add(task);
} catch (RejectedExecutionException re) {
task.setState(TaskState.CANCELLED);
// TODO triggering failed, where to show?
throw new TaskException(TaskException.EXECUTION_REJECTED, re);
}
task.setState(TaskState.QUEUED);
return task;
}
......