Java code snippets

These snippets are intended as examples, not production-ready code.

Data Storage

Retrieve objects based on identifiers

Retrieves the objects of the type of ReturnEntity based on the identifiers retrieved in the SQL query. Java action (gist)

Useful for complex or heavy queries, or queries that require clauses not supported by OQL or xPath queries, such as having, group by, where in. For example when retrieving available time slots from a planning based on a set of conditions. Based on the query api blog post by Andrej Koelewijn.

// BEGIN USER CODE
logger.debug("executeAction: " + this.Sql);

List<IMendixObject> resultList = null;
resultList = Core.dataStorage().executeWithConnection(connection ->
{
    List<IMendixObject> objects = new ArrayList<IMendixObject>();
    List<IMendixIdentifier> resultIDs = new ArrayList<IMendixIdentifier>();
    try {
        PreparedStatement stmt = connection.prepareStatement(this.Sql);
        ResultSet rset = stmt.executeQuery();
        while(rset.next()) {
            resultIDs.add(Core.createMendixIdentifier(rset.getLong(1)));
        }
    }
    catch (SQLException e) {
        logger.error("Failed to execute sql statement: " + e.getMessage());
        throw new MendixRuntimeException(e);
    }    	
    try {
        objects = Core.retrieveIdList(getContext(), resultIDs);
    }
    catch (CoreException e) {
        logger.error("Failed to retrieve objects by id: " + e.getMessage());
    }
    return objects;
});
return resultList;
// END USER CODE

Misc

Logger

// BEGIN EXTRA CODE
private final ILogNode logger = Core.getLogger(this.getClass().getName());
// END EXTRA CODE

Replace tokens in a string with their attribute value

Input a string and object, the tokens marked with {AttributeName} will be replaced by the attribute value of said attribute. Java action (gist) based upon this StackOverflow

// BEGIN USER CODE
Pattern pattern = Pattern.compile("\\{(.+?)\\}");
Matcher matcher = pattern.matcher(StringToReplace);
StringBuffer buffer = new StringBuffer();

while (matcher.find()) {
    String replacement = MxObject.getValue(getContext(),matcher.group(1));
    if (replacement != null) {
        matcher.appendReplacement(buffer, "");
        buffer.append(replacement);
    }
}
matcher.appendTail(buffer);
return buffer.toString();
// END USER CODE`

Verify Webhook Signature

Validate the signature you received. It will generate the signature; using your secret and compare that signature with the signature you receive in the webhook payload. Java action (gist) based upon this StackOverflow

  • HMAC SHA-256 algorithm, create a hash (using secret as a key) of the entire received payload as binary.
  • Encode the binary hash in base64 format.
  • Add prefix sha256= to the binary hash.
  • Compare Signatures
// BEGIN USER CODE
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(endpointsecret.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);

String receivedSignature = "sha256=" + Base64.encodeBase64String(sha256_HMAC.doFinal(payload.getBytes("UTF-8")));

Core.getLogger("MyFirstModule").debug("Calculated signature: " + receivedSignature);
Core.getLogger("MyFirstModule").debug("Received signature: " + sigheader);

return receivedSignature.equals(sigheader);
// END USER CODE