Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export const component: IComponent = {
}
```

Every `errorCode` returned by your check function must be listed in `reservedErrorCodes`. You cannot use the Mendix reserved prefixes `cw`, `ce`, or `ci`during registration or the check will fail and a generic error message will appear in the **Errors** pane.
Every `errorCode` returned by your check function must be listed in `reservedErrorCodes`. You cannot use the Mendix reserved prefixes `cw`, `ce`, or `ci` during registration, or the check will fail and a generic error message will appear in the **Errors** pane. In addition, error codes reserved by another extension cannot be reused, or the API will fail.

{{< figure src="/attachments/apidocs-mxsdk/apidocs/extensibility-api/web/consistencyChecks/generic_error.png" alt="" >}}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Before starting this how-to, make sure you have completed the following prerequi

## Custom Document Model

Studio Pro allows you to extend its metamodel by adding custom document types. These documents can store arbitrary data that can be serialized as strings. When you register an editor (a user-defined UI component) for a specific document type, documents of that type appear in the UI alongside built-in document types such as constants, Java actions, and pages. They appear in the **New Document** and **Find Advanced** dialogs, context menus for adding documents, the App Explorer, and other UI elements that display Studio Pro documents. You can register custom editors to appear as tabs or as modal dialogs.
Studio Pro allows you to extend its metamodel by adding custom document types. These documents can store arbitrary data that can be serialized as strings. When you register an editor (a user-defined UI component) for a specific document type, documents of that type appear in the UI alongside built-in document types such as constants, Java actions, and pages. They appear in the **New Document** and **Find Advanced** dialogs, context menus for adding documents, the App Explorer, and other UI elements that display Studio Pro documents. You can register custom editors to appear as tabs or as modal dialogs. You can also add [Consistency Checks](/apidocs-mxsdk/apidocs/web-extensibility-api-11/consistency-checks/) and [Java Action Activities](/apidocs-mxsdk/apidocs/web-extensibility-api-11/java-action-activities-blob-documents/) for custom blob documents.

## Registering a New Document Type

Expand All @@ -28,15 +28,15 @@ To register a new document type, do the following:

```typescript {hl_lines=["8-24"]}
import { IComponent, getStudioProApi } from "@mendix/extensions-api";
import { personDarkThemeIcon, personDocumentType, personLightThemeIcon } from "../model/constants";
import { personDarkThemeIcon, personDocumentType, personLightThemeIcon, personReadableDocumentType } from "../model/constants";
import { PersonInfo } from "../model/PersonInfo";

export const component: IComponent = {
async loaded(componentContext) {
const studioPro = getStudioProApi(componentContext);
await studioPro.app.model.customBlobDocuments.registerDocumentType<PersonInfo>({
type: personDocumentType,
readableTypeName: 'Person',
readableTypeName: personReadableDocumentType,
defaultContent: {
firstName: '',
lastName: '',
Expand All @@ -60,6 +60,7 @@ To register a new document type, do the following:

```typescript
export const personDocumentType = 'myextension.Person';
export const personReadableDocumentType = 'Person';
export const personLightThemeIcon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAGKADAAQAAAABAAAAGAAAAADiNXWtAAABKElEQVRIDd2Vyw3CMBBEAxIUAWVQBxIcKIBiuNAAFVAIV2iAA2cKoAGYF9nIctaxscIBRhrZ2Z3d9T9N8++YaoIb8ShexYcjfWz40FRhraib+MwQDdpijKXci7nEsZ8YYrOoSe6LEdsLpurFtW1yudiskjXPFSaHufGciFxwqZ9cLcJNWXnjAK2Zi7NdOsKcjlwdcIlygaV+crUIl8jbwnauj5F4CY2ujw0fmiTCAndDtXC2g+HzNq8JJVau9m2Jl+CkKAYxEbfi2ZE+Nnxo4jjeqQ5Sx3QnZThTH4gNX5yc7/cx9WLavovGKJfizJG+NXKSJy+afO2raI3oE1vyqaAA+OpjRwHWtqYIMdZekdMEUy15/NBkl8WsICMbz4ng2A3+y1TOH8ALNqHxhf/P+xwAAAAASUVORK5CYII=';
export const personDarkThemeIcon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAWdJREFUSIm1ljFuwkAQRd/giFTkABS5gMsolBRcIFBwCOTGNUfgDtDRJ9yDioaCKlJ8B0dYmyLjZGLtrh0Jj7SyNPP3f894dtbinHP0aIM+yQHuYkERuQdegDnwBIw1VABH4BV4c86VQRIXMGABXADXsi7AIsjjIR4AG0NwAnIgBUa6UvWdDG4DDLoI1OQlkAFJJMtEMWUtEhXQstTksxCxR2hmRP6UCwMamppnXcnN/sx8k6FPYGlqHixLRCAx32RZ++05mOtz65y7Btsu3I1XYNvgwmZwJty1XbNINYOzL4MxgIg8/Pftjb1bLmgZFSJSiAgiMvHEJhorYhxWoAY+Gt9RnyvP3lUDY/f+ipr67fmuX258U6ACPoEd8Kxrp74KmBp8rhz7H58JetsUWCtRcwZVwLqtTTsdNM3kAHzoOtg3V0z8oCmov1FhwP0NO93U77g2Qje5cETJvHaLKzMqcAvr/a/iC+JcVEP5CMhEAAAAAElFTkSuQmCC';
```
Expand Down Expand Up @@ -267,6 +268,40 @@ In the next highlighted block, document contents are fetched whenever a new docu

The code then provides a way to save changes.

### Creating a Document from Code {#creating-a-document-from-code}

The `createDocument` method creates a new document and requires a container ID (a module or a folder), a type, content, and a document name. Documents can only be created when the project is initialized: when an extension first loads as its containing project opens, the project database is not yet built. It becomes available after the extension updates and reloads. Check that the project is available before creating or updating documents.

```typescript
const project: ProjectMetadata | null = await studioPro.app.projectManager.getProjectMetadata();

if (project !== null){
await studioPro.app.model.customBlobDocuments.createDocument<PersonInfo>({
containerId: myModuleContainer.$ID,
type: personReadableDocumentType,
content: {
firstName: 'John',
lastName: 'Doe',
age: 30,
email: 'john.doe@info.com'
},
documentName: "person_document"
});
}
```

### Updating a Document from Code

It is also possible to update an existing document from the api, using the `updateDocumentContent` method. It is also necessary for the project to be initialized, or the document will not be found.

```typescript
const project: ProjectMetadata | null = await studioPro.app.projectManager.getProjectMetadata();

if (project !== null){
await studioPro.app.model.customBlobDocuments.updateDocumentContent<SimpleOpenProjectDocument>(documentId, newContent);
}
```

### Update Build and Manifest Files

The highlighted text in `build-extension.mjs` and `manifest.json` shows the changes necessary to ensure the `editor` entry point builds and loads properly.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
---
title: "Java Action Activities for Custom Blob Documents"
linktitle: "Java Action Activities"
url: /apidocs-mxsdk/apidocs/web-extensibility-api-11/java-action-activities/
description: "Describes how to allow a Custom Blob Document to have its own Java Action activity in a microflow"
---

## Introduction

Java Actions can have Custom Blob Documents as a parameter. You can link the Java Action directly to a document type when the type is registered. This allows the user to drag a Custom Blob Document from the **App Explorer** directly into a microflow, and a new Java Action Activity is automatically generated with that exact Blob Document as the parameter value for the Java Action.

## Prerequisites

* This how-to uses the results of [Get Started with the Web Extensibility API](/apidocs-mxsdk/apidocs/web-extensibility-api-11/getting-started/). Complete that how-to before starting this one.
* Familiarize yourself with creating custom documents as described in [Custom Blob Documents](/apidocs-mxsdk/apidocs/web-extensibility-api-11/custom-blob-document-api/). Also useful to know about [consistency checks for blob documents](/apidocs-mxsdk/apidocs/web-extensibility-api-11/consistency-checks/).

## Registering a Custom Blob Document with a Java Action

If the Java Action that contains a Blob Document type as its parameter already exists in your extension, you can use its qualified name during the registration call of your Blob Document type. The registration method triggers when the app opens and extensions are loaded, linking the two.

```typescript
async loaded(componentContext) {
const studioPro = getStudioProApi(componentContext);
await studioPro.app.model.customBlobDocuments.registerDocumentType<PersonInfo>({
type: personDocumentType,
readableTypeName: 'Person',
defaultContent: {
firstName: '',
lastName: '',
age: 0,
email: ''
},
javaActionQualifiedName: 'MyModule.MyJavaAction'
});

...
}
```

If you want to create the Java Action that has your new Blob Document Type as a parameter at the same time as registering the document, you can do so as shown below. However, be aware that the Java Action will be created every time your extension gets loaded. This code below is a simple example to show how to create a Java Action and assign its parameter types to a Blob Document type.

```typescript

async loaded(componentContext) {
const studioPro = getStudioProApi(componentContext);

const moduleName = "MyModule";
const javaActionName = "MyJavaAction";

await createJavaActionWithBlobDocumentParameter(studioPro, moduleName, javaActionName, personDocumentType, "Person");

await studioPro.app.model.customBlobDocuments.registerDocumentType<PersonInfo>({
type: personDocumentType,
readableTypeName: 'Person',
defaultContent: {
firstName: '',
lastName: '',
age: 0,
email: ''
},
javaActionQualifiedName: `${moduleName}.${javaActionName}`
});

...
}

async function createJavaActionWithBlobDocumentParameter(studioPro: StudioProApi, moduleName: string, javaActionName: string, customDocumentTypeName: string, customDocumentReadableTypeName: string) {
const module = await studioPro.app.model.modules.getModule(moduleName);

if (!module) {
throw new Error(`Module was not found.`);
}

const javaActions = studioPro.app.model.javaActions;

const javaAction = await javaActions.createUnit(module.$ID, {
name: javaActionName
});

const parameterType = await javaActions.createElement<CodeActions.CustomBlobDocumentParameterType>(
"CodeActions$CustomBlobDocumentParameterType"
);

parameterType.customDocumentTypeName = customDocumentTypeName;
parameterType.customDocumentReadableTypeName = customDocumentReadableTypeName;

const parameter = await javaActions.createElement<JavaActions.JavaActionParameter>("JavaActions$JavaActionParameter", {
name: "document"
});

parameter.actionParameterType = parameterType;

javaAction.actionParameters.push(parameter);

await javaActions.save(javaAction);

return javaAction;
}

```

### Sample Type That Keeps Track of the Java Action Name

```typescript
export type JavaActionDocument = {
javaActionQualifiedName: string | undefined;
renamedJavaActionQualifiedName?: string | undefined;
someValue?: string | undefined;
};
```

### Consistency Checks for Lost Action and Parameter Types
```typescript
const withJavaActionDocumentType = "myextension.JavaActionDocument";

const wrongActionParameterErrorCode = "WRNJAP";
const noJavaActionErrorCode = "NOJAA";
const wrongNamedJavaActionErrorCode = "WRNJAA";
const reservedErrorCodes = [wrongActionParameterErrorCode, noJavaActionErrorCode, wrongNamedJavaActionErrorCode];

async function getConsistencyCheck(studioPro: StudioProApi) {
return async (data: JavaActionDocument) => {
const errors: ConsistencyError[] = [];

if (!data.javaActionQualifiedName || data.javaActionQualifiedName.trim().length === 0) {
errors.push({
errorCode: noJavaActionErrorCode,
errorDescription: `The Document of type ${withJavaActionDocumentType} must have a java action associated with it.`,
severity: "error",
elementText: "Parameter"
});
}

const [action] = await studioPro.app.model.javaActions.loadAll(unit => {
const name = `${unit.moduleName}.${unit.name}`;
return name === data.javaActionQualifiedName || name === data.renamedJavaActionQualifiedName;
});

const dependentElementIds: string[] = [];

if (!action) {
errors.push({
errorCode: noJavaActionErrorCode,
errorDescription: `The Document of type ${withJavaActionDocumentType} must have a java action associated with it.`,
severity: "error",
elementText: "Parameter"
});

return {
errors,
dependentElementIds
};
} else dependentElementIds.push(action.$ID); // track the JavaAction as a dependency of this document.

if (data.renamedJavaActionQualifiedName && data.renamedJavaActionQualifiedName !== data.javaActionQualifiedName) {
errors.push({
errorCode: wrongNamedJavaActionErrorCode,
errorDescription: `The Java action was renamed from ${data.javaActionQualifiedName} to ${data.renamedJavaActionQualifiedName}.`,
severity: "error",
elementText: "Name"
});

return {
errors,
dependentElementIds
};
}

const blobDocumentParameters = action.actionParameters.filter(
parameter => parameter.actionParameterType.$Type === "CodeActions$CustomBlobDocumentParameterType"
);

const correctTypeParameter = blobDocumentParameters.filter(
parameter =>
parameter.actionParameterType.$Type === "CodeActions$CustomBlobDocumentParameterType" &&
parameter.actionParameterType.customDocumentTypeName === withJavaActionDocumentType
);

const wrongTypeParameter = blobDocumentParameters.filter(
parameter =>
parameter.actionParameterType.$Type === "CodeActions$CustomBlobDocumentParameterType" &&
parameter.actionParameterType.customDocumentTypeName !== withJavaActionDocumentType
);

if (correctTypeParameter.length !== 1 || wrongTypeParameter.length > 0) {
errors.push({
errorCode: wrongActionParameterErrorCode,
errorDescription: `The Java Action "${data.javaActionQualifiedName}" must have a single parameter of type ${withJavaActionDocumentType}.`,
severity: "error",
elementText: "Parameter"
});
}

return {
errors,
dependentElementIds
};
};
}
```

### Tracking Java Action Renamed or Re-Added with Same Name After Deletion

Using events from `studioPro.app.projectChanges`, you can track when a Java Action is renamed or re-added with the same name:

```typescript
studioPro.app.projectChanges.addEventListener("elementsRenamed", async ({ elements }) => {
const javaActionsRenamed = elements.filter(element => element.documentType === "JavaActions$JavaAction");

const javaActionBlobDocuments = await studioPro.app.model.customBlobDocuments.getDocumentsOfType(withJavaActionDocumentType);
for (const doc of javaActionBlobDocuments) {
const d = await studioPro.app.model.customBlobDocuments.getDocumentById<JavaActionDocument>(doc.id);

if ("document" in d && d.document) {
for (const javaActionRenamed of javaActionsRenamed) {
// renamed JavaAction's old name matches our JavaAction, so we track the new name.
if (javaActionRenamed.oldName.qualifiedName === d.document.contents.javaActionQualifiedName) {
d.document.contents.renamedJavaActionQualifiedName = javaActionRenamed.newName.qualifiedName;

// always save the document so that the consistency checks run again
await studioPro.app.model.customBlobDocuments.updateDocumentContent(d.document.$ID, d.document.contents);
}

// renamed JavaAction new name matches our name, we can stop tracking the rename
if (javaActionRenamed.newName.qualifiedName === d.document.contents.javaActionQualifiedName) {
d.document.contents.renamedJavaActionQualifiedName = undefined;

// always save the document so that the consistency checks run again
await studioPro.app.model.customBlobDocuments.updateDocumentContent(d.document.$ID, d.document.contents);
}
}
}
}
});

studioPro.app.projectChanges.addEventListener("documentAdded", async ({ document }) => {
const javaActionDocuments = await studioPro.app.model.customBlobDocuments.getDocumentsOfType(withJavaActionDocumentType);

for (const doc of javaActionDocuments) {
const d = await studioPro.app.model.customBlobDocuments.getDocumentById<JavaActionDocument>(doc.id);

if ("document" in d && d.document) {
const javaAction = (await studioPro.app.model.javaActions.loadAll(ja => ja.$ID === document.documentId)).find(
ja => ja.$ID === document.documentId
);

if (javaAction) {
const qualifiedName = (javaAction as JavaActions.JavaAction & { $QualifiedName: string }).$QualifiedName;

// new JavaAction is in fact our own
if (d.document.contents.javaActionQualifiedName === qualifiedName) {
d.document.contents.javaActionQualifiedName = qualifiedName;
d.document.contents.renamedJavaActionQualifiedName = undefined;

// trigger the change to run consistency checks again, since this new
// action is probably missing the required parameters of the correct type.
await studioPro.app.model.customBlobDocuments.updateDocumentContent(d.document.$ID, d.document.contents);
}
}
}
}
});
```

{{% alert color="info" %}}
Studio Pro does not track the deletion or renaming of Java Actions that are linked to Custom Blob Documents. These consistency checks can help you handle those cases. These code samples are simple examples to use as a basis for your own production code.
{{% /alert %}}


## Limitations

A Custom Blob Document and Java Action relationship is one-to-one. There can only be one Java Action per document type. If an extension tries to link a Java Action that is already linked to another type, the API will throw an error.

It is recommended to write some [consistency checks](/apidocs-mxsdk/apidocs/web-extensibility-api-11/consistency-checks/) to detect when the Java Action is renamed or deleted, or when its parameter types change. Add the `javaActionQualifiedName` property to the Custom Blob Document contents so it is included in the document data when the consistency checks run.
Loading
Loading