AEM Workflow custom input data - aem

I need to create a workflow in AEM that for a page (specified as payload) finds all the assets used on the page and uploads a list of them to an external service. So far I have most of the code ready, but business process requires me to use a special code for each of the pages (different for each run of the workflow), so that the list is uploaded to correct place.
That is when I have a question - Can you somehow add more input values for an AEM workflow? Maybe by extending the starting dialog, or adding some special step that takes user input? I need to be able to somehow specify the code when launching the workflow or during its runtime.
I have read a lot of documentation but as this is my first time using workflows, I might be missing something really obvious. I will be grateful for any piece of advice, including a link to a relevant piece of docs.

Yes, that is possible. You need to implement a dialog step in your workflow: https://docs.adobe.com/content/help/en/experience-manager-64/developing/extending-aem/extending-workflows/workflows-step-ref.html#dialog-participant-step

You could:
Create a custom menu entry somewhere in AEM (e.g. Page Editor, /apps/wcm/core/content/editor/_jcr_content/content/items/content/header/items/headerbar/items/pageinfopopover/items/list/items/<my-action>, see under libs for examples)
Create a client-library with the categories="[cq.authoring.editor]". So it is loaded as part of the page editor (and not inside the iframe with your page)
Create a JS-Listener, that opens a dialog if the menu-entry was clicked (see code). You can either use plain Coral UI dialogs, or my example misused a Granite page dialog (Granite reads the data-structure in cq:dialog, and creates a Coral UI component edit-dialog out of it - while Coral is the plain JS UI-framework)
Create a Java-Servlet, that catches your request, and creates the workflow. You could theoretically use the AEM servlet. But I often have to write my own, because it lacks some features.
Here is the JS Listener:
/*global Granite,jQuery,document,window */
(function ($, ns, channel, window) {
"use strict";
var START_WORKFLOW_ACTIVATOR_SELECTOR = ".js-editor-myexample-activator";
function onSuccess() {
ns.ui.helpers.notify({
heading: "Example Workflow",
content: "successfully started",
type: ns.ui.helpers.NOTIFICATION_TYPES.SUCCESS
});
}
function onSubmitFail(event, jqXHR) {
var errorMsg = Granite.I18n.getVar($(jqXHR.responseText).find("#Message").html());
ns.ui.helpers.notify({
heading: "Example Workflow",
content: errorMsg,
type: ns.ui.helpers.NOTIFICATION_TYPES.ERROR
});
}
function onReady() {
// add selector for special servlet to form action-url
var $form = ns.DialogFrame.currentFloatingDialog.find("form");
var action = $form.attr("action");
if (action) {
$form.attr("action", action + ".myexample-selector.html");
}
// register dialog-fail event, to show a relevant error message
$(document).on("dialog-fail", onSubmitFail);
// init your dialog here ...
}
function onClose() {
$(document).off("dialog-fail", onSubmitFail);
}
// Listen for the tap on the 'myexample' activator
channel.on("click", START_WORKFLOW_ACTIVATOR_SELECTOR, function () {
var activator = $(this);
// this is a dirty trick, to use a Granite dialog directly (point to data-structure like in cq:dialog)
var dialogUrl = Granite.HTTP.externalize("/apps/...." + Granite.author.ContentFrame.getContentPath());
var dlg = new ns.ui.Dialog({
getConfig: function () {
return {
src: dialogUrl,
loadingMode: "auto",
layout: "auto"
}
},
getRequestData: function () {
return {};
},
"onSuccess": onSuccess,
"onReady": onReady,
"onClose": onClose
});
ns.DialogFrame.openDialog(dlg);
});
}(jQuery, Granite.author, jQuery(document), window));
And here is the servlet
#Component(service = Servlet.class,
property = {
SLING_SERVLET_RESOURCE_TYPES + "=cq:Page",
SLING_SERVLET_SELECTORS + "=myexample-selector",
SLING_SERVLET_METHODS + "=POST",
SLING_SERVLET_EXTENSIONS + "=html"
})
public class RequestExampleWorkflowServlet extends SlingAllMethodsServlet {
#Override
protected void doPost(#Nonnull SlingHttpServletRequest request, #Nonnull SlingHttpServletResponse response) throws IOException {
final Page page = request.getResource().adaptTo(Page.class);
if (page != null) {
Map<String, Object> wfMetaData = new HashMap<>();
wfMetaData.put("workflowTitle", "Request Translation for " + page.getTitle());
wfMetaData.put("something", "Hello World");
try {
WorkflowSession wfSession = request.getResourceResolver().adaptTo(WorkflowSession.class);
if (wfSession != null) {
WorkflowModel wfModel = wfSession.getModel("/var/workflow/models/example-workflow");
WorkflowData wfData = wfSession.newWorkflowData(PayloadInfo.PAYLOAD_TYPE.JCR_PATH.name(), page.getPath());
wfSession.startWorkflow(wfModel, wfData, wfMetaData);
MyServletUtil.respondSlingStyleHtml(response, HttpServletResponse.SC_OK, "Triggered Example Workflow");
} else {
throw new WorkflowException("Cannot retrieve WorkflowSession");
}
} catch (WorkflowException e) {
MyServletUtil.respondSlingStyleHtml(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
} else {
MyServletUtil.respondSlingStyleHtml(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error - cannot get page");
}
}
}

Related

Listen to keyboard input in the whole Blazor page

I'm trying to implement a Blazor app that listens to keyboard input all the time (some kind of full screen game, let's say).
I can think of a key down event listener as a possible implementation for it, since there's not really an input field to auto-focus on.
Is there a better solution to just react to key-presses in any part of the screen?
In case that's the chosen one, how can I add an event listener from a client-side Blazor app? I've failed trying to do so by having a script like this:
EDIT: I modified a little bit the code below to actually make it work after fixing the original, key mistake that I was asking about.
scripts/event-listener.js
window.JsFunctions = {
addKeyboardListenerEvent: function (foo) {
let serializeEvent = function (e) {
if (e) {
return {
key: e.key,
code: e.keyCode.toString(),
location: e.location,
repeat: e.repeat,
ctrlKey: e.ctrlKey,
shiftKey: e.shiftKey,
altKey: e.altKey,
metaKey: e.metaKey,
type: e.type
};
}
};
// window.document.addEventListener('onkeydown', function (e) { // Original error
window.document.addEventListener('keydown', function (e) {
DotNet.invokeMethodAsync('Numble', 'JsKeyDown', serializeEvent(e))
});
}
};
index.html
<head>
<!-- -->
<script src="scripts/event-listener.js"></script>
</head>
Invoking it through:
protected async override Task OnAfterRenderAsync(bool firstRender)
{
await jsRuntime.InvokeVoidAsync("JsFunctions.addKeyboardListenerEvent");
}
and having the following method trying to receive the events:
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
namespace Numble;
public static class InteropKeyPress
{
[JSInvokable]
public static Task JsKeyDown(KeyboardEventArgs e)
{
Console.WriteLine("***********************************************");
Console.WriteLine(e.Key);
Console.WriteLine("***********************************************");
return Task.CompletedTask;
}
}
I manage to get the script executed, but I'm not receiving any events.
The name of the event is keydown, not onkeydown.

In AEM how to add a new node called “listeners” in the component dialog ,without using dialog.xml file

Actaully i am using "before submit" listener to do some validation for my selection box
I have reffered the following link:
https://helpx.adobe.com/experience-manager/using/classic_dialog_validation.html.
But "before submit" method calling only when i place ,
dialog listener in the dialog root level only.
how to place dialog listener in dialog root level(I checked in my project there is no dialog.xml file ,they using only java code to construct component dialog).
Can anyone please help me in this ?enter image description here
Dialog property construction code :
#DialogField(name ="./validateProgram",
fieldLabel = "Validate Program",
fieldDescription = "(synchronized)",
additionalProperties = {
#Property(renderIn = Property.RenderValue.TOUCH,
name = "validation",
value = "validation-program")
},
listeners = {
#Listener(name ="beforesubmit",
value = "function(dialog){" +
"return programValidation.beforeSubmit(dialog);"+
"}")
})
#Selection(
type ="select",
optionsProvider = " ",
dataSource = "/resourcetype/data")
public final String validateProgram;
Java Script code:
window.onload = function() {
programValidation.init();
};
var programValidation= programValidation|| (function($) {
function initialize() {
};
function validate() {
alert("inside validate method");
var res = true;
return res;
};
return {
beforeSubmit: validate,
init: initialize
}
})(jQuery);
You are using the cq component maven plugin this a very vital piece of information to get your question answered.
I have not used this plugin before, but in your case, I assume you are looking for the Listener annotation where you can set the name as beforesubmit and the value as function(){alert(1)}
you'll probably have to set the annotation on a local variable similar to how you would annotate a dialog field '#DialogField', find more docs in the plugin's usage page here: http://code.digitalatolson.com/cq-component-maven-plugin/usage.html
Hope this helps.
Thanks for your support. Found the following way to solve the issue .
I added ValidateFields method from within the 2 listeners (FIELD_LISTENER_LOAD_CONTENT and FIELD_LISTENER_SELECTION_CHANGED)
function ValidateFields(dialog) {
dialog.on("beforesubmit", function(e) {
if(<condtion failed>)
CQ.Ext.Msg.alert(CQ.I18n.getMessage("Error"), CQ.I18n.getMessage("<error message>"));
return false;
} else {
return true;
}
}, this);
}

Frame contents loaded event in GWT

I am creating a DialogBox that contains a Frame widget. I have tried using both the addLoadHander and addAttachHandler hooks to try and capture changes to the frame with no success. Only the initial page load fires either event and after some research it appears that both actually occur when the Widget is attached to the DOM and not when the frames content is loaded.
DialogBox paymentProcessingDialog = new DialogBox(false);
private void submitPayment(String actionURL, String qryString){
Frame processCCWindow = new Frame(actionURL + "?" + qryString);
processCCWindow.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
//This is called when the frame is attached to the dom
//and not when the document is actually ready so it's
//kinda worthless for my scenario
//Note: the addAttachHandler has the same issue
//***call to JSNI idea (see below)
checkURLChange();
}
});
//...irrelevant code to style the DialogBox
VerticalPanel panel = new VerticalPanel();
panel.add(processCCWindow);
paymentProcessingDialog.setWidget(panel);
paymentProcessingDialog.center();
paymentProcessingDialog.show();
}
The URL that is loaded into the frame contains an HTML response from an external server (Paypal - transparent redirect) that immediately re-submits itself back to my server via a form. I am trying to capture the body of the frame once the submission back to my server has completed and the document in the frame has loaded.
I have also tried to use a JSNI method that uses a MutationObserver (got the code from this solution) to try and watch the frame but I believe the JSNI is actually being run inside the parent and not inside the Frame(?) so nothing happens.
I have also tried using a setTimeout to trigger another method in my presenter class but I believe that is running into the same problem as the MutationObserver idea because the console statements never fire.
private static native void checkURLChange()/*-{
new MutationObserver(function(mutations) {
mutations.some(function(mutation) {
if (mutation.type === 'attributes' && mutation.attributeName === 'src') {
console.log(mutation);
console.log('Old src: ', mutation.oldValue);
console.log('New src: ', mutation.target.src);
return true;
}
return false;
});
}).observe(location.href, {
attributes: true,
attributeFilter: ['src'],
attributeOldValue: true,
characterData: false,
characterDataOldValue: false,
childList: false,
subtree: true
});
window.location = "foo";
setTimeout(function() {
#com.myPackage.MyoutPresenter::paymentProcessComplete(Ljava/lang/String;)(document.getElementsByTagName("body")[0].innerText);
console.log("test" + document.getElementsByTagName("body")[0].innerText);
}, 3000);
}-*/;
Does anyone have any thoughts on how I can accomplish this?
I am not familiar with Frame widget, but it appears that you add a handler after you set the URL. Try to build the Frame first (outside of submitPayment, if you use it more than once), and then set the URL:
final Frame processCCWindow = new Frame();
processCCWindow.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
// do something
}
});
private void submitPayment(String actionURL, String qryString){
processCCWindow.setUrl(actionURL + "?" + qryString);
}

Toast Notification Arguments Open Web Browser

I need to send my toast notification arguments and open a web browser. Here is my code:
private void DoNotification()
{
var notifications = serviceClient.GetNotificationsAsync(App.CurrentRestaurantLocation.ID);
foreach (RestaurantNotification note in notifications.Result)
{
IToastNotificationContent toastContent = null;
IToastText02 templateContent = ToastContentFactory.CreateToastText02();
templateContent.TextHeading.Text = note.Title;
templateContent.TextBodyWrap.Text = note.Message;
toastContent = templateContent;
// Create a toast, then create a ToastNotifier object to show
// the toast
ToastNotification toast = toastContent.CreateNotification();
toast.Activated += toast_Activated;
// If you have other applications in your package, you can specify the AppId of
// the app to create a ToastNotifier for that application
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
async void toast_Activated(ToastNotification sender, object args)
{
await Launcher.LaunchUriAsync(new Uri("http://www.google.com"));
}
My activated event happens, however, no web browser opens. That launcher code works without the toast notification.
How do I populate args with a url? My web service returns note.RedirectUrl and I want to feed it in there.
Instead of using the Activated event handler on the ToastNotification, use the OnLaunched handler in the main Application class (which allows launch context to be easily accessed).
For the handler to be invoked, a launch argument needs to be provided in the toast XML. Using the code above, you can add the argument to the the IToastContent object like so:
toastContent.Launch = note.RedirectUrl;
Then in the Application's OnLaunched method, the app can retrieve the launch argument:
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
if (!String.IsNullOrEmpty(args.Argument)) {
var redirectUrl = args.Argument;
}
}
Calling LaunchUriAsync should work as expected when used from OnLaunched.

How do I know that I'm still on the correct page when an async callback returns?

I'm building a Metro app using the single-page navigation model. On one of my pages I start an async ajax request that fetches some information. When the request returns I want to insert the received information into the displayed page.
For example:
WinJS.UI.Pages.define("/showstuff.html", {
processed: function (element, options) {
WinJS.xhr(...).done(function (result) {
element.querySelector('#target').innerText = result.responseText;
});
}
};
But how do I know that the user hasn't navigated away from the page in the meantime? It doesn't make sense to try to insert the text on a different page, so how can I make sure that the page that was loading when the request started is still active?
You can compare the pages URI with the current WinJS.Navigation.location to check if you are still on the page. You can use Windows.Foundation.Uri to pull the path from the pages URI to do this.
WinJS.UI.Pages.define("/showstuff.html", {
processed: function (element, options) {
var page = this;
WinJS.xhr(...).done(function (result) {
if (new Windows.Foundation.Uri(page.uri).path !== WinJS.Navigation.location)
return;
element.querySelector('#target').innerText = result.responseText;
});
}
};
I couldn't find an official way to do this, so I implemented a workaround.
WinJS.Navigation provides events that are fired on navigation. I used the navigating event to build a simple class that keeps track of page views:
var PageViewManager = WinJS.Class.define(
function () {
this.current = 0;
WinJS.Navigation.addEventListener('navigating',
this._handleNavigating.bind(this));
}, {
_handleNavigating: function (eventInfo) {
this.current++;
}
});
Application.pageViews = new PageViewManager();
The class increments a counter each time the user starts a new navigation.
With that counter, the Ajax request can check if any navigation occurred and react accordingly:
WinJS.UI.Pages.define("/showstuff.html", {
processed: function (element, options) {
var pageview = Application.pageViews.current;
WinJS.xhr(...).done(function (result) {
if (Application.pageViews.current != pageview)
return;
element.querySelector('#target').innerText = result.responseText;
});
}
};