Welcome to the MOTECH Documentation

The topics below will give you an introduction to MOTECH, an open source mHealth platform developed by the Grameen Foundation. Some of these topics are quite technical in nature (i.e. aimed at software developers), while others are more accessible to people who aren’t familiar with software code.

About MOTECH

Mobile Technology for Community Health (MOTECH) is a modular, extensible open source software project originally designed for mobile health (mHealth), which can also be used outside of the health domain. It allows organizations to use mobile technology to communicate information to patients, collect data about patients, alert caregivers to patients’ status, and schedule caregivers’ work. The modular system allows organizations to choose among multiple mHealth technologies and to enable data sharing for users of the system.

MOTECH Architecture Overview

MOTECH consists of the core platform and several modules, each providing use of a technology such as SMS or email, or access to an external system such as CommCare. Organizations can choose to install one or more modules, and developers can extend MOTECH by writing new modules. MOTECH is written in Java. It depends on open source systems including Apache Tomcat, Apache ActiveMQ, and Quartz. For more information about MOTECH architecture, see Core Architecture and Modules Architecture.

What can MOTECH do?

The MOTECH Platform can be used for setting appointments, tracking any scheduled activity, and managing workers deployed in the field. Its initial implementations have been for mHealth projects that improve health by sending messages to patients and caregivers based on an evaluation of the recommended schedule of care compared to the patient’s health-related actions. Some features of typical MOTECH-based applications are:

Communicate information to patients via voice or SMS according to a schedule of care defined for the patient’s condition, e.g.:

  • Reminders for ANC appointments, lab visits, etc.
  • Reminders to take medication on schedule, e.g., DOTS, ART, etc.
  • Reminder notices to take children for scheduled immunization services

Collect data from patients or caregivers, e.g.:

  • Patients report their symptoms prior to treatment or during treatment (adverse events)
  • Patients give feedback on service delivery
  • Caregivers report what service was delivered to a patient and on what date

Alert caregivers of the status of their patients, e.g.:

  • Notify Community Health Worker when patient has not taken ART, DOTS or other drugs
  • Notify nurse when patient has not kept a scheduled appointment (e.g., ANC visit)

Facilitate communication between patients, caregivers, and/or health administrators, e.g.:

  • Establish secure peer networks for patients who share similar health concerns
  • Initiate conversations between patients and caregivers in a way that allows the caregiver to manage the workload effectively

Creating Applications

This section is intended to help implementers of MOTECH get started creating custom solutions. The topics below cover some of the common features that need to be configured for a MOTECH app.

As the platform matures, most of the features below will be usable by implementers without developing any software code. As of now, a number of these features do require some coding in order to use (the topics below provide sample code where appropriate).

Introduction

Motech provides Maven archetypes in its Nexus repository which you can use to create a new Motech module. The archetypes supply basic source code needed for a new module, as well as configuration files for packaging the module as a bundle to be loaded into a Motech server.

The first archetype is the minimal bundle archetype. This supplies just enough source code and configuration to make a “Hello World” module.

Additional archetypes can add functionality to the minimal archetype:
  • The http bundle archetype adds a servlet to respond to HTTP requests, and a simple web user interface.
  • The repository bundle archetype adds a repository layer for storing and retrieving data from MOTECH’s data services.
  • The settings bundle archetype adds a properties file to store custom module configuration, and exposes the configuration through Motech’s web user interface

Any combination of these additional archetypes may be added to the minimal archetype.

Minimal Bundle Archetype

To create a new minimal bundle from the minimal bundle archetype, use the following command:

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=minimal-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module"

This will create a new Maven project in your current directory.

This is a long command. Here is an explanation of the parameters:

parameter value explanation
-DinteractiveMode false no need to wait for user input
-DarchetypeRepository http://nexus.motechproject.org/content/repositories/releases where to find the archetype
-DarchetypeGroupId org.motechproject group name for the archetype
-DarchetypeArtifactId minimal-bundle-archetype which archetype to use
-DarchetypeVersion 0.24-SNAPSHOT Motech version to use with the new module
-DgroupId org.motechproject group name for the new module
-DartifactId motech-test-module artifact name for the new module
-Dpackage archetype.test Java package for new module classes
-Dversion 0.1-SNAPSHOT version of the new module itself
-DbundleName “Archetype Test Module” name of the new module

HTTP Bundle Archetype

To create a new bundle that has HTTP support, use the following two commands from the same directory.

Create a minimal bundle with configuration modified for HTTP:

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=minimal-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module" -Dhttp=true

Note the new parameter:

-Dhttp true

Add new source files from the HTTP archetype:

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=http-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module"

Note the new archetype Id:

-DarchetypeArtifactId http-bundle-archetype

Repository Bundle Archetype

To create a new bundle that has support for MOTECH’s data services, use the following two commands from the same directory.

Create a minimal bundle with configuration modified for repository:

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=minimal-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module" -Drepository=true

Add new source files from the repository archetype:

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=repository-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module"

Settings Bundle Archetype

To create a new bundle that has module settings support, use the following two commands from the same directory.

Create a minimal bundle with configuration modified for settings:

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=minimal-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module" -Dsettings=true

Add new source files from the settings archetype:

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=settings-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module"

Combined Bundle Archetype

The minimal bundle archetype can be supplemented with any combination of additional archetypes. To create a bundle that uses them all, use all the following commands from the same directory.

Create a minimal bundle with configuration modified for all additional archetypes:

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=minimal-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module" -Dhttp=true -Drepository=true -Dsettings=true

Add source files from all the additional archetypes:

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=http-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module"

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=repository-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module"

mvn archetype:generate -DinteractiveMode=false -DarchetypeRepository=http://nexus.motechproject.org/content/repositories/releases -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=settings-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module"

Using Archetypes Locally

You can also use the archetypes locally, without the Motech Nexus repository. First, you must build the archetypes locally. You can either follow the developer guidelines to set up your developer environemt, or to build locally without commiting:

git clone https://code.google.com/p/motech/
cd motech
mvn clean install

Then you can use the archetypes from your Maven local catalog:

mvn archetype:generate -DinteractiveMode=false -DarchetypeCatalog=local -DarchetypeGroupId=org.motechproject -DarchetypeArtifactId=minimal-bundle-archetype -DarchetypeVersion=0.24-SNAPSHOT -DgroupId=org.motechproject -DartifactId=motech-test-module -Dpackage=archetype.test -Dversion=0.1-SNAPSHOT -DbundleName="Archetype Test Module"

Note the new parameter:

-DarchetypeCatalog local

Installing and Upgrading MOTECH

There will be more text here.

Configuring Messaging: SMS

There will be more text here.

Configuring Messaging: IVR

There will be more text here.

Connecting MOTECH to OpenMRS

There will be more text here.

Integrating MOTECH with CommCare

There will be more text here.

Using the Tasks Module

There will be more text here.

Configuring Pill Reminders

There will be more text here.

Configuring Your MOTECH App to be HIPAA Compliant

There will be more text here.

MOTECH Mailing Lists

The mailing lists below are the best way to keep in touch with us. Please join the discussion!

MOTECH Developers

Mailing list for regular contributors to the MOTECH Platform source repository - used for design discussions and other issues impacting the developer community.

motech-dev@googlegroups.com Join Dev List

MOTECH Implementers

Mailing list for implementers and other users of MOTECH - used mostly for communication related to releases. Traffic is moderated and very low volume.

motech-implementers@googlegroups.com Join Implementers List

Architecture and Technical Overviews

Core Architecture

Architecture Overview

MOTECH can logically be broken into the core platform and modules. The core platform wraps several well-known open source systems, and augments and exposes their features to the other components. The main functions of the core are to wrap ActiveMQ (which provides the message queue) and present an internal pub/sub like event interface to the module and implementation layers. The core also provides a module loading environment (OSGi), an interface to the Scheduler, and access to the database.

MOTECH Architecture Diagram

Modules within MOTECH are self-contained bits of functionality that are loaded into the server via the OSGi host. Typically a module provides one type of functionality, such as SMS or access to an external health system. For more information, see Modules Architecture. For a list of current and planned modules, see Modules.

MOTECH is designed to be horizontally scalable with multiple MOTECHs all acting as workers connecting to the same message queue.

Design Philosophy

Stateless

A core design principle of the MOTECH platform is that the server should be stateless across requests to allow for horizontal scalability. It is expected that code running within the MOTECH server should perform a single action per request and then return. The module should never persist any state in memory or local disk and expect that state to be available to later requests.

Events

To aid in the development of stateless services, the MOTECH engine provides a pub/sub like event system. (The event system follows the publish-subscribe pattern but does not implement the standard Java pub/sub protocol.) It helps to decouple emitters of events from the modules that wish to consume them. Any module can emit an event by calling the EventRelay and passing it a MotechEvent and a subject. To register for an event, a module just needs to annotate a method with the list of event subjects of interest.

For more information, see Event and Scheduler Architecture.

Scheduled Events & Timers

To assist in the development of a stateless event-based server, the MOTECH platform provides access to a flexible scheduling system. Using the open source Quartz engine, MOTECH can easily schedule events for future consumption. For more information, see Event and Scheduler Architecture.

Subsystems

Tasks System

The Tasks system allows you to connect modules without code by using tasks. Each task consists of three parts:

  1. Trigger: an event raised by Module A (or the Scheduler)
  2. Filter: a conditional statement specifying whether the task should run
  3. Action: an action executed by Module B in response

In between the trigger and the action, tasks may use data loaders to look up data from other modules that are registered as data sources.

Data Services

MOTECH Data Services is a flexible data modeling system that allows users to define and share custom schemas without code, and provides auditing and revision tracking. It is a JDBC-based user configurable database abstraction layer on top of a standard SQL database. It provides generated POJOs and OSGi service interfaces for the data objects, generated CRUD events, and generated user interface for data browsing and editing. In a future release it will also support auto-generation of REST APIs.

Dependencies on Third-Party Systems

Quartz Scheduler

Quartz is an open source job scheduling engine that enables MOTECH modules to schedule events for future consumption.

Tomcat

Apache Tomcat provides the application container for MOTECH.

ActiveMQ

Apache ActiveMQ is an open source message broker that provides the message queue.

OSGi

Each MOTECH module is an OSGi bundle. Using OSGi allows the platform to manage the bundle lifecycle (adding, removing, starting, and stopping modules), and allows modules to expose service interfaces. For more information, see Modules Architecture.

Event and Scheduler Architecture

Event Handling and Scheduling among Modules

The following diagram provides three examples of Motech modules:

  • Motech module A publishes events, schedules new jobs and listens for events. An example of a Motech platform that has these three responsibilities is the Message Campaign module.

  • Motech module B schedules new jobs.

  • Motech module C listens to events of subject X and Y: listener X listens to events of subject X, and listener Y listens to events of subject Y.

    Events and Modules Diagram

Event Handling and Scheduling Architecture

To schedule a job in MOTECH, the core platform exposes the MotechSchedulerService. Clients of the service have an instance of it injected into the class that uses it. This service employs Quartz to schedule MotechScheduledJobs. When triggered, MotechScheduledJobs raise events that are sent through an event relay to the event queue. These messages are dequeued and then received by a consumer, the event listener registry, which in turn discovers all of the listeners on the event and invokes the appropriate method that was listening on that event.

Scheduler Architecture Diagram
Notes
  • The scheduler service retrieves the Quartz Scheduler from the SchedulerFactoryBean. The service can only schedule MotechScheduledJobs, which all must include a MotechEvent.
  • When the trigger for the scheduled job is satisfied, the job is executed and the accompanying Motech event is sent to the SchedulerFireEventGateway interface. This gateway is defined in schedulerFiredEventChannelAdapter.xml and a proxy is generated by Spring at runtime.
  • The SchedulerFireEventGateway serves as an outbound message gateway to shuttle messages to the event relay, which then sends JMS messages to the event queue.
  • The event queue dequeues messages and routes them to the event listener registry. The core platform has one consumer for events, a channel that routes messages to an event listener registry.
  • The event listener registry retrieves the listeners that are listening on the motech event it is relaying (listening is based on the value bound to the motech event’s subject key).
  • The core platform scans new bundles for any method annotated as a MotechListener, and registers those methods with the listener registry.
  • If the event has a specific destination or only one listener, the listener’s handle method is called. This will invoke the method that was annotated as a MotechListener. These listener classes can be project specific and will reside outside of the core platform.
  • If the event has multiple listeners, a separate event is raised for each listener. The original event object is not handled by a listener in this case.
  • The EventListener’s handle method will invoke the method that was annotated as a MotechListener. The MotechEvent will be passed to that method as a parameter.

Modules Architecture

Modules within MOTECH are self-contained bundles of functionality that are loaded into the server via the OSGi host. Modules interact with the core platform through its APIs and with other modules, either through their APIs or by consuming their events. Modules can expose service interfaces of their own as well as emit their own events. Modules may also register servlet controllers, which allow them to respond to HTTP requests.

Through MOTECH Data Services, a modules may expose entities from its data model. This allows a module to provide a data editor, REST APIs, record-level security, and field-level auditing. Via the Tasks system, modules can expose triggers, data and actions to be orchestrated by other modules.

See Modules for the list of current and planned modules.

Reasons to create a module include developing application-specific UI, business logic, and data models. Another reason is to develop generic reusable functionality to share with the MOTECH community.

Data Services Architecture

There will be text here.

Security Model

There will be text here.

Modules

Alerts

Collects alerts for users in an inbox-like container

Appointments

Provides appointment scheduling and reminding

Call Flow

Manages the sequence of greetings and prompts for an Interactive Voice Response (IVR) call

CMS Lite

Provides basic content storage and retrieval

CommCare

Integrates the MOTECH platform with CommCareHQ, an open-source platform to help manage community health workers

Data Services

Integrates data from external data sources and provides sharable data schemas

Decision Tree[Deprecated]

Provides APIs for constructing an IVR decision tree

Email

Sends and logs email messages

Event Aggregation

Groups common events and republishes them as a single event at a specified time

Event Logging

Allows MOTECH modules to easily see each others’ events

IVR

Integrates the MOTECH platform with Interactive Voice Response (IVR) services

IVR Asterisk

Connects the MOTECH platform IVR with an Asterisk server using the VoiceGlue VoiceXML browser

IVR Kookoo

Integrates the MOTECH platform with Kookoo’s hosted IVR service

IVR Verboice

Integrates the MOTECH platform with Verboice’s hosted IVR service

IVR Voxeo

Integrates the MOTECH platform with Voxeo’s hosted IVR service

Message Campaign

Enrolls users in message campaigns with flexible content-scheduling rules

Metrics

Displays web site metrics using logging and the open source tools StatsD and Graphite

Mobile Forms

Supports configurable forms and data collection through mobile devices that support the OpenXData format

MRS (Medical Record System)

Provides a basic specification for integrating the platform with a medical record system

OpenMRS

Integrates the MOTECH platform with OpenMRS, an open source electronic medical record platform

Outbox

A voicemail-like messaging system for end users

Pill Reminder

A flexible reminder system focused on medication

Schedule Tracking

Enrolls users for alerts based on complex scheduling rules

Scheduler

Publishes events on a schedule, using the open source Quartz engine.

SMS

Provides a basic specification for integrating the MOTECH platform with an SMS provider to send/receive SMS messages

Tasks

Responds to specified triggers; for example, a task can be set to enroll a patient in an alerts schedule in response to an incoming SMS message with a particular subject

Developing the MOTECH Platform

This section of the documentation is aimed at developers and maintainers of the MOTECH Platform. These docs help MOTECH devs get up and running, from configuring a machine, to getting the code, and committing and reviewing changes. If you find any errors in the topics below, or you have any other questions about MOTECH development, please contact us via the mailing list.

Setting up a Development Environment

The topics below will walk you through installing MOTECH on a Mac or Linux machine. Note that the Docker-based setup is much faster than the “official” method but the instructions are in beta. If you have any trouble with either approach, please feel free to contact us via motech-dev@googlegroups.com.

Installing MOTECH for Developers (“Official” Method)

Installing on Ubuntu

The versions below may change, most likely the latest stable release will work for your purposes. If they do not, please feel free to send in feedback.

  1. Install Ubuntu Desktop 12.04.2 LTS 64bit

    Installation instructions

    Note

    64-bit is required for Motech’s installation

  2. Install Maven, Git, Curl, Activemq, and mysql

    1. In terminal, type

      sudo apt-get install curl git maven activemq mysql-server
      
    2. On a fresh Ubuntu installation, you may need to run the following first

      sudo apt-get update
      
  3. Configure ActiveMQ

    Run the following

    sudo ln -s /etc/activemq/instances-available/main /etc/activemq/instances-enabled/main
    

    Note

    For ActiveMQ scheduled delivery to work, you must set the attribute: schedulerSupport=”true” for the broker element in your activemq.xml config file. This file should be located at (active-mq-folder)/conf/activemq.xml.See ActiveMQ docs.

  4. Install JDK 7

    1. Go to The Java JDK Download Page

    2. Accept License Agreement

    3. Click on jdk-7u51-linux-x64.tar.gz (or latest stable version)

    4. Extract the file into your home directory, ie: /home/*<user>*/jdk1.7.0_51

    5. Set the proper Java environment and change maven options:

      1. Start a new terminal session

      2. Edit your .profile file

        nano ~/.profile
        
      3. append the following at the end of the file:

        export PATH="$HOME/jdk1.7.0_21/bin:$PATH"
        export JAVA_HOME=$HOME/jdk1.7.0_21
        export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"
        
      4. Save the changes (Ctrl+X) and quit

      5. Confirm the settings are right

      6. Log out & log back in & start a new terminal

      7. Type

        java -version && env | grep MAVEN_OPTS
        

      You should see something like:

      java version "1.7.0_51"
      Java(TM) SE Runtime Environment (build 1.7.0_51-b11)
      Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)
      MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=128m
      
  5. Install Tomcat7

    1. Go to Tomcat’s download page

    2. Under 7.0.52 (or the latest stable version) - Binary Distributions - Core, click on tar.gz

    3. Once downloaded, expand the file to your home directory, i.e.: /home/*<user>*/apache-tomcat-7.0.52

    4. Edit the tomcat-users.xml file (located under \etc\tomcat7\conf\) to add an admin user:

    5. In the terminal type

      nano ~/apache-tomcat-7.0.52/conf/tomcat-users.xml
      
    6. Insert a line similar to the following before the closing </tomcat-users> tag:

      <user username="*<username>*" password="*<password>*" roles="manager-gui"/>
      
    7. Save the changes (Ctrl+X) then quit

    8. Now edit ~/.bashrc to setup tomcat’s environment variable

      nano ~/.bashrc
      
    9. Append the following line:

      export CATALINA_HOME=$HOME/apache-tomcat-7.0.52
      
    10. Save the changes (Ctrl+X) then quit

    11. Start a new terminal session or type

      source ~/.bashrc
      
  6. Install CouchDB

    1. Download the latest stable sources from http://couchdb.apache.org and then follow the instructions in the INSTALL.Unix file.

      For Ubuntu 13.10, just run:

      sudo apt-get install couchdb
      
    2. Once this is done, navigate to http://localhost:5984 to verify that the installation completed successfully.

      {"couchdb":"Welcome","uuid":"52068def93b82a2653dcf352a4f9273a","version":"1.4.0","vendor":{"version":"1.4.0","name":"The Apache Software Foundation"}}
      
  7. Install CouchDB-Lucene

    1. Follow these instructions also be sure to follow the proxy handler instructions

    2. Once the proxy has been configured, restart couchdb with:

      sudo service couchdb restart
      
    3. After restarting couchdb, navigate to http://localhost:5984/_fti and you should see something like this:

      {"couchdb-lucene":"Welcome","version":"0.10.0-SNAPSHOT"}
      
  8. Setup MySQL

    1. In your motech source root directory, type in the terminal:

      $ mysql -u root -p
      
    2. then type:

      sql> create database motechquartz;
      sql> create database motech_data_services;
      sql> create user 'quartz'@'localhost' identified by 'quartz2123';
      sql> grant all privileges on motechquartz.* to 'quartz'@'localhost';
      sql> exit;
      
    3. then type:

      mysql -u root -p motechquartz < modules/scheduler/scheduler/sql/create_db_schema_quartz_v2.1.sql
      
  9. Start Tomcat
    1. In terminal, type:

      ~/apache-tomcat-7.0.52/bin/catalina.sh jpda start
      
    2. You should see messages similar to:

      Using CATALINA_BASE:   /home/*<user>*/apache-tomcat-7.0.52
      Using CATALINA_HOME:   /home/*<user>*/apache-tomcat-7.0.52
      Using CATALINA_TMPDIR: /home/*<user>*/apache-tomcat-7.0.52/temp
      Using JRE_HOME:        /home/*<user>*/jdk1.7.0_51
      Using CLASSPATH:       /home/*<user>*/apache-tomcat-7.0.52/bin/bootstrap.jar:/home/*<user>*/...
      
    3. You can also confirm tomcat was started by going to http://localhost:8080 in a browser

  10. Jump to the Building and Installing MOTECH section to install MOTECH

Installing on a Macintosh
  1. Installing Prerequisites for MOTECH

    1. Installing HomeBrew

      To install Homebrew, run the following in the terminal

      ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
      
    2. Use Homebrew to install git, erlang, ActiveMQ, and Apache Tomcat:
      brew install git
      brew install activemq
      brew install tomcat
      brew install maven
      
    3. Homebrew installations are located in /usr/local/Cellar` with symlinks in ``/usr/local/bin, which should already be part of your $PATH environment variable.

      Note

      Homebrew provides instructions about how to run these applications, as well as how to have launchd start them automatically on system startup.

    4. Configuring Tomcat:

      Edit the tomcat-users.xml file to add an admin user. Insert a line similar to the following before the closing </tomcat-users> tag:

      <user username="motech" password="motech" roles="manager-gui"/>
      
    5. Installing JDK 7:

      Mac OS includes JDK6 by default, however JDK 7 is required for MOTECH. Use these instructions to install the latest version of the JDK.

    6. Installing MySQL:

      1. Before installing MySQL, you will need Xcode from the App Store. This can take a while; it’s a big download.

      2. Next start Xcode from the Launchpad (rocketship icon in the dock) and select Install. Then you can quit Xcode; you don’t need to keep it running.

        Note

        (Command Line Tools using Xcode are included in OS X Mavericks, but not previous OS versions. If you are running Mountain Lion, you can follow these instructions: http://blog.mclaughlinsoftware.com/2012/12/10/mountain-lion-pre-mysql/)

      3. Go to http://dev.mysql.com/downloads/mysql/ and download the appropriate DMG archive. Open it, double-click on the installer, and follow directions.

      4. Once mysql has finished installing, double-click the MySQL preferences pane in the DMG and follow instructions. For more details see ‘these instructions’_ .

      Note

      Homebrew can be used to install MySQL, however Homebrew will not install the Mysql System Preferences control panel.

  2. Setting up Symbolic Link and Environment Variables

    1. Create a symbolic link from the Tomcat directory (Homebrew installs into /usr/local/Cellar/tomcat/<version number>/libexec) to /usr/local/tomcat:

      ln -s /usr/local/Cellar/tomcat/`brew info tomcat | grep stable | awk '{print $3}' | sed 's/,//'`/libexec /usr/local/tomcat
      
    2. Edit your ~/.bash_profile to set environment variables (catalina is Tomcat):

      export JAVA_HOME="/Library/Java/Home"
      export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"
      export CATALINA_HOME="/usr/local/tomcat"
      export CATALINA_OPTS="-Xms1024m -Xmx2048m -XX:MaxPermSize=1024m"
      export PATH=/usr/local/mysql/bin:$PATH
      
    3. When you’re done editing:
      source ~/.bash_profile
      
  3. Jump to the Building and Installing MOTECH section to install MOTECH

Building and Installing MOTECH
  1. Getting the MOTECH code

  2. Building MOTECH

    1. Assuming you issued the git clone command in your home directory root, in the terminal

      $ cd ~/motech
      $ mvn install
      

    b.) It takes some time to build MOTECH, but eventually you should see:

    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 29:19.284s
    [INFO] Finished at: Fri Jun 07 12:12:43 PDT 2013
    [INFO] Final Memory: 152M/378M
    [INFO] ------------------------------------------------------------------------
    

    Note

    Should you get a java.lang.OutOfMemoryError exception, it may be because you forgot to set MAVEN_OPT as described in [3.5]. But you may need to increase -Xmx. So something like -Xmx1024m might work.

  3. Install MOTECH

    1. In a browser, go to http://localhost:8080

      Tomcat server home page
    2. Click on Manager App

    3. Type the user/password you used in tomcat-users.xml

      temporary hack you need to remove ~/.motech/config/motech-settings.conf to allow the create initial user wizard.

    4. In the Tomcat Web Application Manager, scroll down to the Deploy section and the WAR file to deploy subsection, click on Browseand select or navigate to ~/motech/platform/server/target/motech-platform-server.war then click on Deploy

      Tomcat web application page
    5. Depending on your machine it could take a while for motech-platform-server to deploy

    6. In the Tomcat Web Application Manager page, click on /motech-platform-server, you get the MOTECH initial user screen

      Motech initial user page
Installing the IDE, Intellij IDEA Community Edition & open MOTECH project
  1. Go to the Jetbrains home page and click on Download Now in the Community Edition box, then expand the file to your home directory.

  2. From a terminal, assuming you extracted IntelliJ to ~/idea-IC-129.713, start IntelliJ

    $ ~/idea-IC-129.713/bin/idea.sh
    
  3. Select Import Project

Import project view
  1. Select ~/motech/pom.xml, a dialog box will appear. Set the options as shown:

  2. Click Next

  3. In Select Profiles, do not select any profile, click Next

  4. In Select Maven projects to Import, there should only be one project: org.motechproject:motech:0.20-SNAPSHOT, click Next

  5. In Please select project SDK, if the 1.7.0_21 is present, select it, otherwise add it:

  6. Click +

  7. Select JDK

  8. Select /home/frank/jdk1.7.0_21, then click OK

  9. Click Next

  10. Click Finish

  11. Background processes will take a long time

  12. You can also create a menu launcher, so you can start IntelliJ from the gui:

    1. From the Tools menu select Create Desktop Entry

    2. A IntelliJ menu item will be created in the Development application group

    3. Debug demo module in IntelliJ

    4. Start IntelliJ (from the command line, or from launcher icon if you created one)

    5. It’ll automatically open the motech project (if it was the last project you worked on)

    6. From the Run menu select Edit Configurations

    7. Click on the green +

    8. Select Remote

    9. Give a name to your Run/Debug configuration and change the port to 8000 as:

      ide configuration
    10. Hit OK

    11. Set a breakpoint somewhere in the demo module code, i.e.:

    12. From the Run menu, select Debug ‘Tomcat’ where Tomcat is the name of your configuration.

    13. In the browser go to the place that will hit the breakpoint, i.e.: if you setup a breakpoint as in the previous screen, then in the Demo module, click the Decision Trees tab, and you should hit the breakpoint!

      ide configuration

Installing MOTECH Using Docker (“Beta”)

Note

These instructions assume you’re running on Ubuntu. This setup is also possible on Mac OSX but the steps are slightly different. We hope to provide OSX instructions in future.

This document provides instructions for creating a MOTECH environment using Docker containers. These instructions are “in beta” (the official installation guide is still the one here), but many members of the MOTECH dev team have been following this approach with success. This installation method is much faster than the official route.

There are two supported ways to install MOTECH with Docker:

  1. As an implementer - follow this approach if you want to install a released version of MOTECH.
  2. As a developer - follow this approach if you will be developing MOTECH and want to build the platform and modules from source code.
Get Docker, Fig and motech-docker

Whether you’re installing as an implementer or a developer, you’ll need Docker and Fig:

Docker
  1. Follow the instructions on the Docker website to get the latest version of Docker.

  2. Execute the following to configure Docker to work for non-root users:

    sudo groupadd docker
    sudo gpasswd -a ${USER} docker (logout and re-login)
    sudo service docker restart
    
Fig

Execute the following to install Fig:

sudo apt-get install python-pip python-dev build-essential
sudo pip install -U fig
motech-docker

Clone the motech-docker project from GitHub or download it as a zip file and extract it. You’ll need to run all Fig commands from the motech-docker directory.

Implementer Setup

Go to your motech-docker directory. To setup as an implementer (everything is automagically installed):

./setup_as_imp.sh

Type the following to start MOTECH in the background:

fig up -d

Voila! MOTECH has started. Wait a little bit (about 30s) then direct your browser to: http://localhost:8080/motech-platform-server

Note

‘fig up’ ERASES ALL YOUR DATA (well not really all, but pretend it does). You have to run it at least once to setup MOTECH. If you run it again, it’ll erase everything you did in MOTECH. It’s useful to start afresh, but remember: it nukes everything!

Developer Setup

Go to your motech-docker directory. To setup as a dev:

./setup_as_dev.sh

Type the following to start all the pieces that MOTECH needs to run in the background:

fig up -d

Once you start the containers with the fig up -d command above and before you build MOTECH for the first time, you need to copy the MOTECH binaries into the container’s /root/.motech/bundles directory.

Conveniently, the container’s /root/.motech/bundles directory is exposed as the docker-motech-bundles directory (with a-rw access) in your home directory (also note that the container’s /root/.motech/config dir is also exposed as ~/docker-motech-config). So, you can either manually copy the necessary binaries, or you can create a symbolic link to ~/docker-motech-bundles from ~/.motech/bundles.

Assuming the latter, and that you never built MOTECH before, you’d run the following commands:

# go to your home dir
cd
# create the .motech dir
mkdir .motech
# create the symlink
ln -s ~/docker-motech-bundles .motech/bundles

If you built MOTECH before, you can just delete the bundles directory and create the symlink using the command above.

Build, deploy and run MOTECH: see :doc:dev_install.

Some Useful Fig Commands
Stop MOTECH
fig stop
Restart MOTECH
fig start
Watching logs

To watch all the logs (very verbose):

fig logs

To watch only the tomcat logs:

fig logs tomcat

See the sections in the generated fig.yml to see what other logs you can watch.

Configuring MOTECH

There will be more text here. This doc may belong in “Setting up a Development Environment” or in “Getting Started”.

Developing and Submitting a Patch

We use a web-based code review system called Gerrit. Using this system, anyone can comment on a proposed change before it is merged to our Git repository. It’s pretty easy to use; the instructions below will get you started.

Create a Gerrit Account

  1. Navigate to http://review.motechproject.org/
  2. Click sign in on top-right
  3. Select Open ID provider (only Google accounts are enabled)
  4. Select user name
  5. Upload your SSH public key

Configuring Your Git Client to Use Gerrit

Follow these steps once for each MOTECH code repository that you clone.

  1. Get source code

    git clone ssh://<userid>@review.motechproject.org:29418/motech
    
  2. Set up review branch

    cd motech
    git config remote.origin.push refs/heads/*:refs/for/*
    
  3. Install change-id generation hook

    scp -p -P 29418 <userid>@review.motechproject.org:hooks/commit-msg .git/hooks/
    

Development Workflow

  1. Checkout to feature branch

    git checkout -b newfeature
    
  2. Make changes/test/multiple commits

  3. When ready to submit changes: update master, squash commits and merge feature branch

    git checkout master && git pull --rebase
    git merge --squash newfeature
    git gui
    
  4. Edit commit message using the proper commit message format

  5. Push changes

    git push origin
    

Submitting Changes (Patch Set) to Incorporate Review Comments

If you’ve received some code review feedback and you’d like to make some changes, follow the steps below to add your changes as a new “patch set” to the existing Gerrit code review.

  1. Checkout patch from gerrit change:
    1. Navigate to http://review.motechproject.org/#/c/<change id>/
    2. Copy pull url under patch set section and run
  2. Make changes

  3. Copy change ID from Gerrit (top section in Gerrit change page)

  4. Amend change ID in commit message

  5. Squash commits

  6. Push changes

Pushing to Remote Branches (Not for Review)

This practice enables developers to share in-progress feature work with others without actually submitting the changes for review.

  1. Use branch namespace dev

    git checkout -b dev/newfeature
    git add . && git commit -m "message"
    git push -u origin dev/newfeature:dev/newfeature
    
  2. Once done with feature, squash commits and merge with master. Submit for review as mentioned above.

MOTECH Code Repositories

Each repository can be cloned from either GitHub/Google Code or Gerrit. If you’re only interested in a copy of the code and will not be contributing, use the GitHub repo (no sign-in required). Otherwise use the Gerrit repo (sign-in required) where each commit will trigger a Jenkins build and be submitted for code review. Jenkins is our continuous integration (CI) system. Once your change is approved and merged by an authorized Gerrit reviewer, it will show up on the GitHub/Google Code repo.

MOTECH Platform

The platform repo contains the motech-platform-server Tomcat servlet. In addition it also contains the essential Admin, Config, Tasks, Motech Data Services, Email, and Scheduler modules.

  • Google Code Repository

    git clone https://code.google.com/p/motech
    
  • Gerrit Repository

    git clone ssh://<userid>@review.motechproject.org:29418/motech
    

MOTECH Modules

This repo is the home of all optional MOTECH modules.

  • GitHub Repository

    git clone https://github.com/motech/modules
    
  • Gerrit Repository

    git clone ssh://<userid>@review.motechproject.org:29418/modules
    

Commit Message Format

To ensure that our commit messages are both concise and informative, all MOTECH committers are asked to follow the git commit message format outlined below. For reference, Linus Torvalds provides a description of a good commit message here.

Format

  1. First line is the Jira issue ID + subject (max 50 chars)
  2. Leave a blank line (if not, the entire message is interpreted as subject)
  3. Summary (ensure it is wrapped to a reasonable number of characters, e.g. 72, because git log does not handle wrapping).

The description of the change should be both brief and informative. The Linux kernel documentation has this to say about good commit summaries:

...the “summary” must be no more than 70-75 characters, and it must describe both what the patch changes, as well as why the patch might be necessary. It is challenging to be both succinct and descriptive, but that is what a well-written summary should do.

Author/Committer

There is no need to include the names of the developers who developed the change in the subject line. If there is more than one person working on a change, the committer is asked to include the –author parameter in his/her git commit to specify the second person’s name.

Example

Here is an example of a MOTECH commit message:

MOTECH-678 Moves campaign modules to github

Disables pillreminder, message-campaign and scheduletracking modules from main pom.xml as they’ve moved to a new repo on github - https://github.com/motech/platform-campaigns

Change-Id: I5964249887160c868fa9598c413aebb93a49fa32

Coding Conventions

Text to come

Code Review Workflow and Checklist

Text to come

Authoring Documentation

This document provides information specific to setting up and authoring Sphinx documentation for MOTECH. The Sphinx Documentation Guide is also a good resource.

Each MOTECH repository contains a docs directory populated with reStructured Text (reST) files. These files are built by Sphinx and hosted at http://readthedocs.org. A Sphinx plugin, called Javasphinx, builds Javadoc for the MOTECH codebase.

Installing Sphinx and Javasphinx

If you are working on MOTECH documentation, it is helpful to build the docs locally and review changes in advance of checkin. The steps below will get your environment configured to build Sphinx docs.

Install python utils

sudo apt-get install python-setuptools
sudo apt-get install python-dev
sudo apt-get install python-pip

Install sphinx

sudo easy_install sphinx

Install javasphinx and motechjavasphinx

sudo apt-get install libxslt-dev
sudo apt-get install libxml2-dev
sudo apt-get install zlib1g-dev
cd docs
sudo pip install -r requirements.txt

Building Docs

ReadTheDocs.org automatically builds Sphinx projects, but it is a good idea to build your documents and make sure they render correctly before you push your changes up to the code repository.

To build Sphinx docs, go to the docs directory and type:

make html

You can then use a web browser to view docs/build/html/index.html and make sure everything looks good.

Authoring and Submitting New Documents

To create a new documentation topic, simply create a file with extension .rst under the docs directory. Create a table-of-contents entry for your new doc in the appropriate index.rst file. The reStructuredText Primer is good to have handy as you write your doc.

When your document is ready for review, follow the instructions for creating and submitting a patch to submit it for code review.

Project Management

There will be text here.

Release Strategy and Procedure

Text to come

Browser Compatibility

Text to come

Demos

Demo: Create a Message Campaign

Text to come

Demo: Create a Care Schedule

Text to come

Demo: Modeling a New System with Data Services

Text to come

Demo: Hello World

Text to come

Demo: OpenMRS Schedule Tracking

Text to come

Javadoc

org.motechproject.admin.domain

AdminSettings

public class AdminSettings

AdminSettings class is used to store settings for Admin module and specifies that these settings are read-only (by checking config source from bootstrap)

Constructors
AdminSettings
public AdminSettings(List<Settings> settingsList, boolean readOnly)
Methods
getSettingsList
public List<Settings> getSettingsList()
isReadOnly
public boolean isReadOnly()
setReadOnly
public void setReadOnly(boolean readOnly)
setSettingsList
public void setSettingsList(List<Settings> settingsList)

NotificationRule

public class NotificationRule

A notification rule persisted in the database. Represents a rule for sending out a single notification. Contains information about this notification’s recipient and the ActionType representing a method used for notifying the recipient.

Constructors
NotificationRule
public NotificationRule()
NotificationRule
public NotificationRule(String recipient, ActionType actionType, Level level, String moduleName)
Methods
getActionType
public ActionType getActionType()
getId
public Long getId()
getLevel
public Level getLevel()
getModuleName
public String getModuleName()
getRecipient
public String getRecipient()
matches
public boolean matches(StatusMessage message)
setActionType
public void setActionType(ActionType actionType)
setId
public void setId(Long id)
setLevel
public void setLevel(Level level)
setModuleName
public void setModuleName(String moduleName)
setRecipient
public void setRecipient(String recipient)

QueueMBean

public class QueueMBean

Represents a JMS queue. Holds information about the queue statistics.

Constructors
QueueMBean
public QueueMBean(String destination)
Methods
getConsumerCount
public long getConsumerCount()
getDequeueCount
public long getDequeueCount()
getDestination
public String getDestination()
getEnqueueCount
public long getEnqueueCount()
getExpiredCount
public long getExpiredCount()
getInflightCount
public long getInflightCount()
getQueueSize
public long getQueueSize()
setConsumerCount
public void setConsumerCount(long consumerCount)
setDequeueCount
public void setDequeueCount(long dequeueCount)
setDestination
public void setDestination(String destination)
setEnqueueCount
public void setEnqueueCount(long enqueueCount)
setExpiredCount
public void setExpiredCount(long expiredCount)
setInflightCount
public void setInflightCount(long inflightCount)
setQueueSize
public void setQueueSize(long queueSize)

QueueMessage

public class QueueMessage

Represents a message from the JMS queue.

Constructors
QueueMessage
public QueueMessage(String messageId, Boolean redelivered, Date timestamp)
Methods
getMessageId
public String getMessageId()
getRedelivered
public Boolean getRedelivered()
getTimestamp
public String getTimestamp()

StatusMessage

public class StatusMessage

Represents a message displayed in the ‘messages’ section of the Admin UI. Persisted by MDS module. Apart from the message and its Level, contains also information about the module that sent the message. The timeout field represents the DateTime of the message expiration.

Constructors
StatusMessage
public StatusMessage()
StatusMessage
public StatusMessage(String text, String moduleName, Level level)
StatusMessage
public StatusMessage(String text, String moduleName, Level level, DateTime timeout)
Methods
getDate
public DateTime getDate()
getLevel
public Level getLevel()
getModuleName
public String getModuleName()
getText
public String getText()
getTimeout
public DateTime getTimeout()
setDate
public void setDate(DateTime date)
setLevel
public void setLevel(Level level)
setModuleName
public void setModuleName(String moduleName)
setText
public void setText(String text)
setTimeout
public void setTimeout(DateTime timeout)

org.motechproject.admin.messages

ActionType

public enum ActionType

Represents an action which should be taken for a notification, in particular which message channel should be used to communicate the notification.

Enum Constants
EMAIL
public static final ActionType EMAIL
SMS
public static final ActionType SMS

Level

public enum Level

Represents the level of a org.motechproject.admin.domain.StatusMessage, which is reflected on the UI. Posting a org.motechproject.admin.domain.StatusMessage with a CRITICAL level will trigger notifications.

See also: org.motechproject.admin.domain.StatusMessage

Enum Constants
CRITICAL
public static final Level CRITICAL
DEBUG
public static final Level DEBUG
ERROR
public static final Level ERROR
INFO
public static final Level INFO
WARN
public static final Level WARN

org.motechproject.admin.service

NotificationRulesDataService

public interface NotificationRulesDataService extends MotechDataService<NotificationRule>

MDS data service for NotificationRules.

StatusMessageService

public interface StatusMessageService
Methods
critical
void critical(String text, String moduleName)
critical
void critical(String text, String moduleName, DateTime timeout)
debug
void debug(String text, String moduleName)
debug
void debug(String text, String moduleName, DateTime timeout)
error
void error(String text, String moduleName)
error
void error(String text, String moduleName, DateTime timeout)
getActiveMessages
List<StatusMessage> getActiveMessages()
getAllMessages
List<StatusMessage> getAllMessages()
getNotificationRules
List<NotificationRule> getNotificationRules()
info
void info(String text, String moduleName)
info
void info(String text, String moduleName, DateTime timeout)
postMessage
void postMessage(StatusMessage message)
postMessage
void postMessage(String text, String moduleName, Level level)
postMessage
void postMessage(String text, String moduleName, Level level, DateTime timeout)
removeMessage
void removeMessage(StatusMessage message)
removeNotificationRule
void removeNotificationRule(String id)
removeNotificationRule
void removeNotificationRule(Long id)
saveNotificationRules
void saveNotificationRules(List<NotificationRule> notificationRules)
saveRule
void saveRule(NotificationRule notificationRule)
warn
void warn(String text, String moduleName)
warn
void warn(String text, String moduleName, DateTime timeout)

StatusMessagesDataService

public interface StatusMessagesDataService extends MotechDataService<StatusMessage>

MDS data service for StatusMessages.

Methods
findByTimeout
List<StatusMessage> findByTimeout(Range<DateTime> timeout)

org.motechproject.bundle.extender

MotechExtenderConfigFactory

public class MotechExtenderConfigFactory implements FactoryBean<Properties>

Creates the extender configuration for Motech, currently only blueprint dependency wait time. In order to change the blueprint extender dependency wait time used during platform runtime, org.motechproject.blueprint.dependencies.waittime should be set with the wait time in milliseconds. The default blueprint timeout is 5 minutes.

Fields
DEP_WAIT_TIME_ENV
public static final String DEP_WAIT_TIME_ENV
DEP_WAIT_TIME_KEY
public static final String DEP_WAIT_TIME_KEY
Methods
getObject
public Properties getObject()
getObjectType
public Class<?> getObjectType()
isSingleton
public boolean isSingleton()

MotechOsgiApplicationContextCreator

public class MotechOsgiApplicationContextCreator implements OsgiApplicationContextCreator
Methods
createApplicationContext
public DelegatedExecutionOsgiBundleApplicationContext createApplicationContext(BundleContext bundleContext)
setConfigurationScanner
public void setConfigurationScanner(ConfigurationScanner configurationScanner)

MotechOsgiConfigurableApplicationContext

public class MotechOsgiConfigurableApplicationContext extends OsgiBundleXmlApplicationContext implements ConfigurableWebApplicationContext
Constructors
MotechOsgiConfigurableApplicationContext
public MotechOsgiConfigurableApplicationContext(String[] configurationLocations)
Methods
getNamespace
public String getNamespace()
getServletConfig
public ServletConfig getServletConfig()
getServletContext
public ServletContext getServletContext()
setConfigLocation
public void setConfigLocation(String configLocation)
setNamespace
public void setNamespace(String namespace)
setServletConfig
public void setServletConfig(ServletConfig servletConfig)
setServletContext
public void setServletContext(ServletContext servletContext)
waitForContext
public void waitForContext(int waitTimeInMillis)

org.motechproject.commons.api

AbstractDataProvider

public abstract class AbstractDataProvider extends MotechObject implements DataProvider
Methods
getBody
protected String getBody()
getClassForType
protected Class<?> getClassForType(String type)
getPackageRoot
public abstract String getPackageRoot()
getSupportClasses
public abstract List<Class<?>> getSupportClasses()
isAssignable
protected boolean isAssignable(Class<?> check, List<Class<?>> classes)
setBody
protected void setBody(String body)
setBody
protected void setBody(Resource resource)
supports
public boolean supports(String type)
toJSON
public String toJSON()

ApplicationContextServiceReferenceUtils

public final class ApplicationContextServiceReferenceUtils
Fields
SERVICE_NAME
public static final String SERVICE_NAME
Methods
isNotValid
public static boolean isNotValid(ServiceReference serviceReference)
isValid
public static boolean isValid(ServiceReference serviceReference)

CastUtils

public final class CastUtils
Methods
cast
public static <T> List<T> cast(Class<T> clazz, Enumeration enumeration)

CsvConverter

public final class CsvConverter

The CsvConverter class, provides methods responsible for conversion to CSV-formatted strings.

Methods
convertToCSV
public static String convertToCSV(List<List<String>> list)

DataProvider

public interface DataProvider
Methods
getName
String getName()
lookup
Object lookup(String type, String lookupName, Map<String, String> lookupFields)
supports
boolean supports(String type)
toJSON
String toJSON()

IdentityProvider

public interface IdentityProvider
Methods
getIdentity
String getIdentity()

MotechEnumUtils

public final class MotechEnumUtils

Misc enum-related helper functions

Methods
toEnumSet
public static <T extends Enum> Set<T> toEnumSet(Class<T> enumClass, Set<String> strings)

Returns a set of enums given a set of strings and an enum class

Parameters:
  • enumClass – the enum class
  • strings – a set of strings
Returns:

the enum set constructed from the given string set

toEnumSet
public static <T extends Enum> Set<T> toEnumSet(Class<T> enumClass, String csv)

Returns a set of enums given a comma separated string and an enum class

Parameters:
  • enumClass – the enum class
  • csv – a comma separated string representing a set of enum values
Returns:

the enum set constructed from the given string

toString
public static String toString(Set<? extends Enum> items)

Returns a csv string given a set of enums

Parameters:
  • items – a set of enums
Returns:

the csv string constructed from the given enum set

toStringSet
public static Set<String> toStringSet(Set<? extends Enum> items)

Returns a set of strings given a set of enums

Parameters:
  • items – a set of enums
Returns:

the string set constructed from the given enum set

MotechException

public class MotechException extends RuntimeException
Constructors
MotechException
public MotechException(String s, Throwable throwable)
MotechException
public MotechException(String message)

MotechMapUtils

public final class MotechMapUtils

The MotechMapUtils class contains methods that allow modifications and operations on maps

Methods
asProperties
public static Properties asProperties(Map<Object, Object> map)

Converts java.util.Map into java.util.Properties

Parameters:
  • map – Map to convert
Returns:

Properties, created from given map

mergeMaps
public static Map<Object, Object> mergeMaps(Map<Object, Object> overridingMap, Map<Object, Object> baseMap)

Null-safe merge of two maps. If both parameters are null it returns empty map. If one of the maps is null, it returns the other one. If a key is present in two maps, the value in the merged map will be taken from the overriding map.

Parameters:
  • overridingMap – The map overriding values in the base map
  • baseMap – The base map
Returns:

merged map

MotechObject

public class MotechObject

LayerSupertype for entire motech project. Used optionally through the motech project.

Methods
assertArgumentNotEmpty
protected void assertArgumentNotEmpty(String objectName, String argument)
assertArgumentNotNull
protected void assertArgumentNotNull(String objectName, Object object)
logError
protected void logError(String templateMessage, Object... params)
logError
protected void logError(String message)
logError
protected void logError(String message, Exception e)
logInfo
protected void logInfo(String templateMessage, Object... params)
logger
protected Logger logger()

NanoStopWatch

public class NanoStopWatch
Constructors
NanoStopWatch
public NanoStopWatch()
Methods
duration
public long duration()
start
public NanoStopWatch start()

Range

public class Range<T>
Constructors
Range
public Range(T min, T max)
Methods
equals
public boolean equals(Object o)
getMax
public T getMax()
getMin
public T getMin()
hashCode
public int hashCode()

SystemIdentityProvider

public class SystemIdentityProvider implements IdentityProvider
Methods
getIdentity
public String getIdentity()

Tenant

public class Tenant
Constructors
Tenant
Tenant(TenantIdentity identity)
Methods
canHaveQueue
public boolean canHaveQueue(String queueName)
current
public static Tenant current()
getId
public String getId()
getSuffixedId
public String getSuffixedId()

TenantIdentity

public class TenantIdentity
Constructors
TenantIdentity
public TenantIdentity()
TenantIdentity
public TenantIdentity(IdentityProvider identityProvider)
Methods
getId
public String getId()

org.motechproject.commons.api.json

MotechJsonReader

public class MotechJsonReader
Constructors
MotechJsonReader
public MotechJsonReader()
MotechJsonReader
public MotechJsonReader(FieldNamingStrategy fieldNamingStrategy)
Methods
readFromFile
public Object readFromFile(String classpathFile, Type ofType)
readFromStream
public Object readFromStream(InputStream stream, Type ofType)
readFromString
public Object readFromString(String text, Type ofType)
readFromString
public Object readFromString(String text, Type ofType, Map<Type, Object> typeAdapters)

org.motechproject.commons.api.model

ExtensibleDataObject

public abstract class ExtensibleDataObject<T>
Methods
addData
public T addData(String key, Object value)
addData
public T addData(Map<String, Object> data)
getData
public Map<String, Object> getData()

MotechProperties

public class MotechProperties extends HashMap<String, String>

org.motechproject.commons.couchdb.dao

BaseDao

public interface BaseDao<T extends MotechBaseDataObject>
Methods
add
void add(T entity)
contains
boolean contains(String id)
get
T get(String id)
getAll
List<T> getAll()
remove
void remove(T entity)
safeRemove
void safeRemove(T entity)
update
void update(T entity)

BusinessIdNotUniqueException

public class BusinessIdNotUniqueException extends RuntimeException
Constructors
BusinessIdNotUniqueException
public BusinessIdNotUniqueException(String fieldName, String id)
Methods
getFieldName
public String getFieldName()
getId
public String getId()

MotechBaseRepository

public abstract class MotechBaseRepository<T extends MotechBaseDataObject> extends CouchDbRepositorySupport<T>
Constructors
MotechBaseRepository
protected MotechBaseRepository(Class<T> type, CouchDbConnector db)
Methods
addOrReplace
protected void addOrReplace(T entity, String businessFieldName, String businessId)
bulkAddOrUpdate
public void bulkAddOrUpdate(List<T> records)
bulkDelete
public void bulkDelete(List<T> records)
getAll
public List<T> getAll()
getAll
protected List<T> getAll(int limit)
queryViewWithKeyList
public List<T> queryViewWithKeyList(String viewName, List<String> keys)
removeAll
public void removeAll(String fieldName, String value)
removeAll
public void removeAll()
safeRemove
public void safeRemove(T entity)
singleResult
protected T singleResult(List<T> resultSet)

org.motechproject.commons.couchdb.lucene.query

CouchDbLuceneQuery

public class CouchDbLuceneQuery
Fields
DATE_TIME_FORMAT
public static final String DATE_TIME_FORMAT
Methods
build
public StringBuilder build()
with
public CouchDbLuceneQuery with(String field, String value)
withAny
public CouchDbLuceneQuery withAny(String field, Set<String> values)
withDate
public CouchDbLuceneQuery withDate(String field, DateTime value)
withDateRange
public CouchDbLuceneQuery withDateRange(String field, Range<DateTime> value)
withField
public CouchDbLuceneQuery withField(String field, String type, String value)
withInt
public CouchDbLuceneQuery withInt(String field, int value)

org.motechproject.commons.couchdb.model

MotechBaseDataObject

public abstract class MotechBaseDataObject extends CouchDbDocument
Constructors
MotechBaseDataObject
protected MotechBaseDataObject()
MotechBaseDataObject
protected MotechBaseDataObject(String type)
Methods
getType
public String getType()
setType
protected void setType(String type)

org.motechproject.commons.couchdb.query

QueryParam

public class QueryParam
Constructors
QueryParam
public QueryParam()
QueryParam
public QueryParam(int pageNumber, int recordsPerPage, String sortBy, boolean reverse)
Methods
getPageNumber
public int getPageNumber()
getRecordsPerPage
public int getRecordsPerPage()
getSortBy
public String getSortBy()
isReverse
public boolean isReverse()
setPageNumber
public void setPageNumber(int pageNumber)
setRecordsPerPage
public void setRecordsPerPage(int recordsPerPage)
setReverse
public void setReverse(boolean reverse)
setSortBy
public void setSortBy(String sortBy)

org.motechproject.commons.couchdb.service

CouchDbManager

public interface CouchDbManager
Methods
getConnector
CouchDbConnector getConnector(String dbName)

DbConnectionException

public class DbConnectionException extends RuntimeException
Constructors
DbConnectionException
public DbConnectionException(String message)
DbConnectionException
public DbConnectionException(String message, Throwable cause)

org.motechproject.commons.date

ParseException

public class ParseException extends RuntimeException
Constructors
ParseException
public ParseException(String s)

org.motechproject.commons.date.model

DayOfWeek

public enum DayOfWeek
Enum Constants
Friday
public static final DayOfWeek Friday
Monday
public static final DayOfWeek Monday
Saturday
public static final DayOfWeek Saturday
Sunday
public static final DayOfWeek Sunday
Thursday
public static final DayOfWeek Thursday
Tuesday
public static final DayOfWeek Tuesday
Wednesday
public static final DayOfWeek Wednesday

Time

public class Time implements Comparable<Time>, Serializable
Constructors
Time
public Time()
Time
public Time(int hour, int minute)
Time
public Time(Integer hour, Integer minute)
Time
public Time(LocalTime localTime)
Time
public Time(String timeStr)
Methods
compareTo
public int compareTo(Time otherTime)
equals
public boolean equals(Object obj)
ge
public boolean ge(Time toCompare)
getDateTime
public DateTime getDateTime(DateTime dateTime)
getHour
public Integer getHour()
getMinute
public Integer getMinute()
hashCode
public int hashCode()
isBefore
public boolean isBefore(Time other)
le
public boolean le(Time toCompare)
parseTime
public static Time parseTime(String time, String separator)
setHour
public void setHour(Integer hour)
setMinute
public void setMinute(Integer minute)
timeStr
public String timeStr()
toString
public String toString()
valueOf
public static Time valueOf(String str)

org.motechproject.commons.date.util

DateTimeSourceUtil

public final class DateTimeSourceUtil
Methods
now
public static DateTime now()
setSourceInstance
public static void setSourceInstance(DateTimeSource sourceInstance)
timeZone
public static DateTimeZone timeZone()
today
public static LocalDate today()

DateUtil

public final class DateUtil
Methods
daysPast
public static int daysPast(LocalDate localDate, DayOfWeek dayOfWeek)
daysStarting
public static List<DayOfWeek> daysStarting(DayOfWeek day, int numberOfDays)
daysToCalendarWeekEnd
public static int daysToCalendarWeekEnd(LocalDate date, int calendarWeekStartDay)
endOfDay
public static DateTime endOfDay(Date dateTime)
getDifferenceOfDatesInYears
public static int getDifferenceOfDatesInYears(Date startDate)
greaterThanOrEqualTo
public static List<DateTime> greaterThanOrEqualTo(DateTime date, List<DateTime> dates)
inRange
public static boolean inRange(DateTime reference, DateTime start, DateTime end)
isOnOrAfter
public static boolean isOnOrAfter(DateTime firstDate, DateTime secondDate)
isOnOrBefore
public static boolean isOnOrBefore(DateTime firstDate, DateTime secondDate)
lessThan
public static List<DateTime> lessThan(DateTime date, List<DateTime> dates)
newDate
public static LocalDate newDate(int year, int month, int day)
newDate
public static LocalDate newDate(Date date)
newDate
public static LocalDate newDate(DateTime dateTime)
newDateTime
public static DateTime newDateTime(LocalDate localDate, int hour, int minute, int second)
newDateTime
public static DateTime newDateTime(Date date)
newDateTime
public static DateTime newDateTime(LocalDate date)
newDateTime
public static DateTime newDateTime(LocalDate localDate, Time time)
newDateTime
public static DateTime newDateTime(int year, int month, int day, Time time)
newDateTime
public static DateTime newDateTime(int year, int month, int day)
newDateTime
public static DateTime newDateTime(int year, int month, int day, int hour, int minute, int second)
nextApplicableWeekDay
public static DateTime nextApplicableWeekDay(DateTime fromDate, List<DayOfWeek> applicableDays)
nextApplicableWeekDayIncludingFromDate
public static DateTime nextApplicableWeekDayIncludingFromDate(DateTime fromDate, List<DayOfWeek> applicableDays)
now
public static DateTime now()
nowUTC
public static DateTime nowUTC()
setTimeZone
public static DateTime setTimeZone(DateTime dateTime)
setTimeZoneUTC
public static DateTime setTimeZoneUTC(DateTime dateTime)
time
public static Time time(DateTime dateTime)
today
public static LocalDate today()
tomorrow
public static LocalDate tomorrow()

JodaFormatter

public class JodaFormatter
Constructors
JodaFormatter
public JodaFormatter()
Methods
formatDateTime
public String formatDateTime(DateTime dateTime)
formatPeriod
public String formatPeriod(Period period)

Format joda period as text, eg: “1 year”

Parameters:
  • period – time interval
parse
public Period parse(String intervalString, Locale locale)

Parse time interval in different units, eg: “1 year”

Parameters:
  • intervalString – time interval format number: integer unit : year, month, week, day, hour, minute, second (can use plural forms also) currently compound units like 1 year and 2 months are not supported
parseDateTime
public DateTime parseDateTime(String isoDateTime)
parsePeriod
public Period parsePeriod(String intervalString)

StringUtil

public final class StringUtil
Methods
isNullOrEmpty
public static boolean isNullOrEmpty(String str)

org.motechproject.commons.date.util.datetime

DateTimeSource

public interface DateTimeSource
Methods
now
DateTime now()
timeZone
DateTimeZone timeZone()
today
LocalDate today()

DefaultDateTimeSource

public class DefaultDateTimeSource implements DateTimeSource
Constructors
DefaultDateTimeSource
public DefaultDateTimeSource()
Methods
now
public DateTime now()
timeZone
public DateTimeZone timeZone()
today
public LocalDate today()

org.motechproject.commons.date.valueobjects

WallTime

public class WallTime implements Serializable
Constructors
WallTime
public WallTime(String userReadableForm)
Methods
asPeriod
public Period asPeriod()
equals
public boolean equals(Object o)
getHours
public int getHours()
getMinutes
public int getMinutes()
hashCode
public int hashCode()
inDays
public int inDays()
inMillis
public long inMillis()
inMinutes
public int inMinutes()
isLessThanADay
public boolean isLessThanADay()

WallTimeUnit

public enum WallTimeUnit
Enum Constants
Day
public static final WallTimeUnit Day
Hour
public static final WallTimeUnit Hour
Minute
public static final WallTimeUnit Minute
Week
public static final WallTimeUnit Week

org.motechproject.commons.sql.service

SqlDBManager

public interface SqlDBManager

Classes inheriting this interface are responsible for getting sql properties from the bootstrap configuration.

Methods
getSqlProperties
Properties getSqlProperties(Properties propertiesToUpdate)
updateSqlProperties
void updateSqlProperties()

org.motechproject.config.core

MotechConfigurationException

public class MotechConfigurationException extends RuntimeException

The object of this class is thrown when there is a problem with reading the configuration from the predefined sources.

Constructors
MotechConfigurationException
public MotechConfigurationException(String message, Exception exception)
Parameters:
  • message – A descriptive message explaining the nature of the problem resulted in exception
  • exception – Actual exception (if any) that this exception resulted from
MotechConfigurationException
public MotechConfigurationException(String message)

org.motechproject.config.core.constants

ConfigurationConstants

public final class ConfigurationConstants

Provides all the configuration constants.

Fields
AMQ_BROKER_URL
public static final String AMQ_BROKER_URL
AMQ_CONCURRENT_CONSUMERS
public static final String AMQ_CONCURRENT_CONSUMERS
AMQ_MAX_CONCURRENT_CONSUMERS
public static final String AMQ_MAX_CONCURRENT_CONSUMERS
AMQ_MAX_REDELIVERIES
public static final String AMQ_MAX_REDELIVERIES
AMQ_QUEUE_EVENTS
public static final String AMQ_QUEUE_EVENTS
AMQ_QUEUE_SCHEDULER
public static final String AMQ_QUEUE_SCHEDULER
AMQ_REDELIVERY_DELAY_IN_MILLIS
public static final String AMQ_REDELIVERY_DELAY_IN_MILLIS
BUNDLE_ID
public static final String BUNDLE_ID
BUNDLE_SECTION
public static final String BUNDLE_SECTION
BUNDLE_SETTINGS_CHANGED_EVENT_SUBJECT
public static final String BUNDLE_SETTINGS_CHANGED_EVENT_SUBJECT
BUNDLE_SYMBOLIC_NAME
public static final String BUNDLE_SYMBOLIC_NAME
CONFIG_MODULE_DIR_PREFIX
public static final String CONFIG_MODULE_DIR_PREFIX
EVENT_RELAY_CLASS_NAME
public static final String EVENT_RELAY_CLASS_NAME
FILE_CHANGED_EVENT_SUBJECT
public static final String FILE_CHANGED_EVENT_SUBJECT
FILE_CREATED_EVENT_SUBJECT
public static final String FILE_CREATED_EVENT_SUBJECT
FILE_DELETED_EVENT_SUBJECT
public static final String FILE_DELETED_EVENT_SUBJECT
FILE_PATH
public static final String FILE_PATH
LANGUAGE
public static final String LANGUAGE
LOGINMODE
public static final String LOGINMODE
MOTECH_EVENT_CLASS_NAME
public static final String MOTECH_EVENT_CLASS_NAME
PLATFORM_SETTINGS_CHANGED_EVENT_SUBJECT
public static final String PLATFORM_SETTINGS_CHANGED_EVENT_SUBJECT
PROVIDER_NAME
public static final String PROVIDER_NAME
PROVIDER_URL
public static final String PROVIDER_URL
SERVER_URL
public static final String SERVER_URL
SETTINGS
public static final String SETTINGS
SETTINGS_FILE_NAME
public static final String SETTINGS_FILE_NAME
STATUS_MSG_TIMEOUT
public static final String STATUS_MSG_TIMEOUT
SUPPORTED_FILE_EXTNS
public static final String[] SUPPORTED_FILE_EXTNS
UPLOAD_SIZE
public static final String UPLOAD_SIZE

org.motechproject.config.core.domain

AbstractDBConfig

public abstract class AbstractDBConfig

This abstract class encapsulates the database configuration, composed of as db url, username and password.

Constructors
AbstractDBConfig
public AbstractDBConfig(String url, String driver, String username, String password)
Parameters:
  • url
  • driver
  • username
  • password
Methods
equals
public boolean equals(Object o)
getDriver
public String getDriver()
getPassword
public String getPassword()
getUrl
public String getUrl()
getUsername
public String getUsername()
hashCode
public int hashCode()
toString
public String toString()

BootstrapConfig

public class BootstrapConfig

Represents the bootstrap configuration object. It is composed of:

  1. DBConfig - represents the database related bootstrap object.
  2. Tenant ID - represents the identifier of the tenant.
  3. Configuration source - represents the source of configuration (FILE / UI).
Fields
CONFIG_SOURCE
public static final String CONFIG_SOURCE
COUCHDB_PASSWORD
public static final String COUCHDB_PASSWORD
COUCHDB_URL
public static final String COUCHDB_URL
COUCHDB_USERNAME
public static final String COUCHDB_USERNAME
DEFAULT_TENANT_ID
public static final String DEFAULT_TENANT_ID
SQL_DRIVER
public static final String SQL_DRIVER
SQL_PASSWORD
public static final String SQL_PASSWORD
SQL_URL
public static final String SQL_URL
SQL_USER
public static final String SQL_USER
TENANT_ID
public static final String TENANT_ID
Constructors
BootstrapConfig
public BootstrapConfig(DBConfig couchDbConfig, SQLDBConfig sqlConfig, String tenantId, ConfigSource configSource)
Parameters:
  • couchDbConfig
  • sqlConfig
  • tenantId
  • configSource
Throws:
  • org.motechproject.config.core.MotechConfigurationException – if dbConfig is null.
Methods
equals
public boolean equals(Object o)
getConfigSource
public ConfigSource getConfigSource()
getCouchDbConfig
public DBConfig getCouchDbConfig()
getSqlConfig
public SQLDBConfig getSqlConfig()
getTenantId
public String getTenantId()
hashCode
public int hashCode()
toString
public String toString()

ConfigLocation

public class ConfigLocation

Defines a MOTECH configuration location. If the given location starts with a leading file separator character, the location is treated as a file system directory. Otherwise, it is treated as a classpath location.

Constructors
ConfigLocation
public ConfigLocation(String configLocation)
Methods
equals
public boolean equals(Object o)
getExistingConfigFiles
public List<File> getExistingConfigFiles()
getFile
public File getFile(String fileName, FileAccessType accessType)

This method Returns the java.io.File object for the given file name relative to the config location. It also checks for the requested file accessibility. If the requested access type check is ConfigLocation.FileAccessType.READABLE, the file’s existence and readability will be checked. Similarly, if the requested access type check is ConfigLocation.FileAccessType.WRITABLE, then the write accessibility to the file will be checked. If the file does not exists, write accessibility of its ancestors will be checked.

Parameters:
Throws:
Returns:

File relative to the config location.

getLocation
public String getLocation()
getUrlResource
UrlResource getUrlResource()
hasPlatformConfigurationFile
public boolean hasPlatformConfigurationFile()
hashCode
public int hashCode()
toResource
public Resource toResource()

Resource corresponding to the config location.

Returns:resource
toString
public String toString()

ConfigLocation.FileAccessType

public static enum FileAccessType

Defines the access check required.

Enum Constants
READABLE
public static final ConfigLocation.FileAccessType READABLE
WRITABLE
public static final ConfigLocation.FileAccessType WRITABLE

ConfigSource

public final class ConfigSource

Represents the source from which MOTECH configuration should be read.

Fields
FILE
public static final ConfigSource FILE
UI
public static final ConfigSource UI
Methods
getName
public String getName()
isFile
public boolean isFile()
isValid
public static boolean isValid(String name)
toString
public String toString()
valueOf
public static ConfigSource valueOf(String name)

DBConfig

public class DBConfig extends AbstractDBConfig

DBConfig encapsulates the database configuration, composed of as db url, username and password.

Constructors
DBConfig
public DBConfig(String url, String username, String password)
Parameters:
  • url
  • username
  • password
Throws:
  • org.motechproject.config.core.MotechConfigurationException – if given url is invalid.

SQLDBConfig

public class SQLDBConfig extends AbstractDBConfig

This class encapsulates the SQL database configuration, composed of as db url, username and password.

Constructors
SQLDBConfig
public SQLDBConfig(String url, String driver, String username, String password)
Parameters:
  • url
  • driver
  • username
  • password
Throws:
  • org.motechproject.config.core.MotechConfigurationException – if given url is invalid.

org.motechproject.config.core.filestore

ConfigLocationFileStore

public class ConfigLocationFileStore

Used to read default platform config location(s) from config-location.properties and also to save in the file in the default location.

config-location.properties file will be loaded according to the behaviour of org.apache.commons.configuration.PropertiesConfiguration as specified here.

Fields
CONFIG_LOCATION_PROPERTY_KEY
public static final String CONFIG_LOCATION_PROPERTY_KEY
Constructors
ConfigLocationFileStore
public ConfigLocationFileStore(PropertiesConfiguration propertiesConfiguration)
Methods
add
public void add(String location)
getAll
public Iterable<ConfigLocation> getAll()

PropertiesReader

public final class PropertiesReader

A utility class for loading properties from a file.

Methods
getProperties
public static Properties getProperties(File file)

org.motechproject.config.core.filters

ConfigFileFilter

public class ConfigFileFilter extends FileFileFilter

FileFilter implementation to filter configuration files.

Fields
PLATFORM_CORE_CONFIG_FILTER
public static final FileFileFilter PLATFORM_CORE_CONFIG_FILTER
Methods
accept
public boolean accept(File file)
isFileSupported
public static boolean isFileSupported(File file)
isPlatformCoreConfigFile
public static boolean isPlatformCoreConfigFile(File file)

org.motechproject.config.core.service

CoreConfigurationService

public interface CoreConfigurationService

Loads and saves the core configuration required to start the Motech instance.

Fields
CORE_SETTINGS_CACHE_NAME
String CORE_SETTINGS_CACHE_NAME
Methods
addConfigLocation
void addConfigLocation(String location)

Adds the new config location to the list of existing config locations where configurations are loaded from in the file system.

Parameters:
  • location – config location to add.
Throws:
  • FileSystemException
evictMotechCoreSettingsCache
void evictMotechCoreSettingsCache()
getConfigLocation
ConfigLocation getConfigLocation()

Returns the config location where all the config files are present.

Returns:configLocation.
loadBootstrapConfig
BootstrapConfig loadBootstrapConfig()

Loads the bootstrap configuration.

Returns:bootstrap configuration.
saveBootstrapConfig
void saveBootstrapConfig(BootstrapConfig bootstrapConfig)

Saves the bootstrap configuration

Parameters:
  • bootstrapConfig – Bootstrap config

org.motechproject.config.domain

ModulePropertiesRecord

public class ModulePropertiesRecord

The ModulePropertiesRecord class represents a database record of a certain module properties.

Fields
PROPERTIES_FILE_EXTENSION
public static final String PROPERTIES_FILE_EXTENSION
Constructors
ModulePropertiesRecord
public ModulePropertiesRecord()
ModulePropertiesRecord
public ModulePropertiesRecord(Map<String, String> properties, String module, String version, String bundle, String filename, boolean raw)
ModulePropertiesRecord
public ModulePropertiesRecord(Properties props, String module, String version, String bundle, String filename, boolean raw)
Methods
buildFrom
public static ModulePropertiesRecord buildFrom(File file)
equals
public boolean equals(Object obj)
getBundle
public String getBundle()
getFilename
public String getFilename()
getModule
public String getModule()
getProperties
public Map<String, String> getProperties()
getVersion
public String getVersion()
hashCode
public int hashCode()
isRaw
public boolean isRaw()
sameAs
public boolean sameAs(Object dataObject)
setBundle
public void setBundle(String bundle)
setFilename
public void setFilename(String filename)
setModule
public void setModule(String module)
setProperties
public void setProperties(Map<String, String> properties)
setRaw
public void setRaw(boolean raw)
setVersion
public void setVersion(String version)
toString
public String toString()

org.motechproject.config.monitor

ConfigFileMonitor

public class ConfigFileMonitor implements FileListener

The ConfigFileMonitor is used to monitor changes in config files and send appropriate events.

Methods
fileChanged
public void fileChanged(FileChangeEvent fileChangeEvent)
fileCreated
public void fileCreated(FileChangeEvent fileChangeEvent)
fileDeleted
public void fileDeleted(FileChangeEvent fileChangeEvent)
init
public void init()
setFileMonitor
public void setFileMonitor(DefaultFileMonitor fileMonitor)
stop
public void stop()
updateFileMonitor
public void updateFileMonitor()

org.motechproject.config.service

ConfigurationService

public interface ConfigurationService

Central configuration service that monitors and manages configurations.

Fields
SETTINGS_CACHE_NAME
String SETTINGS_CACHE_NAME
Methods
addOrUpdate
void addOrUpdate(File file)

Saves both property and raw configurations in FILE mode only. Files are classified as either raw config or properties based on the extension of the file.

Parameters:
  • file – File to read configuration from.
addOrUpdateModuleRecord
void addOrUpdateModuleRecord(ModulePropertiesRecord record)
addOrUpdateModuleRecords
void addOrUpdateModuleRecords(List<ModulePropertiesRecord> records)
addOrUpdateProperties
void addOrUpdateProperties(String module, String version, String bundle, String filename, Properties newProperties, Properties defaultProperties)

Depending on the config source, it will either store properties in the DB or file. Only properties that are different from the default ones are stored. If the properties database record or file doesn’t exist yet for the given module, it will be created.

Parameters:
  • module – The module we wish to update properties for
  • version – Version of updated bundle
  • bundle – Symbolic name of updated bundle
  • filename – Resource filename
  • newProperties – New properties to store
  • defaultProperties – Default properties of the module
Throws:
  • IOException – if module properties cannot be retrieved from file
createZipWithConfigFiles
FileInputStream createZipWithConfigFiles(String propertyFile, String fileName)

Uses current configuration and default one to find changed properties and then connects them with annotations. Moreover creates file with non default configurations and packs is into the zip file.

Parameters:
  • propertyFile – name of exported file
Throws:
  • IOException
Returns:

FileInputStream that contains zip file

delete
void delete(String module)

Deletes the db record corresponding to the module.

deleteByBundle
void deleteByBundle(String module)

Deletes the db record corresponding to the module with given bundle symbolic name.

evictMotechSettingsCache
void evictMotechSettingsCache()
getAllModuleProperties
Map<String, Properties> getAllModuleProperties(String module, Map<String, Properties> defaultProperties)

Retrieves all the module properties and returns them as Map, where key is the filename.

Parameters:
  • module – The module we wish to retrieve properties for
  • defaultProperties – Default properties of the module
Throws:
  • IOException – if any of the module properties file cannot be read
Returns:

Properties mapped by filename

getConfigSource
ConfigSource getConfigSource()

This method allows to check whether MOTECH is currently running in the FILE or UI mode

Returns:Current Config Source
getModuleProperties
Properties getModuleProperties(String module, String filename, Properties defaultProperties)

Retrieves merged properties, given default set. Depending on the ConfigSource, it will either merge default properties with the properties from DB or get properties from file.

Parameters:
  • module – The module we wish to retrieve properties for
  • filename – Resource filename
  • defaultProperties – Default properties of the module
Throws:
  • IOException – if module properties cannot be read from file
Returns:

Merged properties of the certain module

getPlatformSettings
MotechSettings getPlatformSettings()
getRawConfig
InputStream getRawConfig(String module, String filename, Resource resource)

Allows to retrieve raw JSON data either from the database or file, depending on the specified ConfigSource mode.

Parameters:
  • module – Module we wish to retrieve raw data for
  • filename – Resource filename
  • resource – Resource file containing default rawConfig, in case no other has been found
Throws:
  • IOException
Returns:

Raw JSON data as InputStream

listRawConfigNames
List<String> listRawConfigNames(String module)

Depending on the selected ConfigSource mode, this method looks for all registered raw data properties within the specified module.

Parameters:
  • module – Module we wish to perform look for
Returns:

List of filenames that register raw config for specified module

loadBootstrapConfig
BootstrapConfig loadBootstrapConfig()

Loads bootstrap config that is used to start up the Motech server.

The bootstrap configuration is loaded in the following order:

  1. Load the configuration from bootstrap.properties from the config directory specified by the environment variable MOTECH_CONFIG_DIR. bootstrap.properties contains the following properties:

    couchDb.url (Mandatory)
    couchDb.username (If required)
    couchDb.password (If required)
    sql.url (Mandatory)
    sql.username (If required)
    sql.password (If required)
    tenant.id (Optional. Defaults to 'DEFAULT')
    config.source (Optional. Defaults to 'UI')
    

    An example bootstrap.properties is given below:

    couchDb.url=http://localhost:5984
    couchDb.username=motech
    couchDb.password=motech
    sql.url=jdbc:mysql://localhost:3306/
    sql.username=motech
    sql.password=motech
    tenant.id=MotherChildCare
    config.source=FILE
    
  2. If MOTECH_CONFIG_DIR environment variable is not set, load the specific configuration values from the following environment variables:

    MOTECH_COUCHDB_URL (Mandatory)
    MOTECH_COUCHDB_USERNAME (If required)
    MOTECH_COUCHDB_PASSWORD (If required)
    MOTECH_SQL_URL (Mandatory)
    MOTECH_SQL_USERNAME (If required)
    MOTECH_SQL_PASSWORD (If required)
    MOTECH_TENANT_ID (Optional. Defaults to 'DEFAULT')
    MOTECH_CONFIG_SOURCE (Optional. Defaults to 'UI')
    
  3. If MOTECH_DB_URL environment is not set, load the configuration from bootstrap.properties from the default MOTECH config directory specified in the file config-locations.properties.

Throws:
Returns:

Bootstrap configuration

loadConfig
SettingsRecord loadConfig()
loadDefaultConfig
SettingsRecord loadDefaultConfig()
processExistingConfigs
void processExistingConfigs(List<File> files)

Adds, updates, or deletes configurations in FILE mode only. Files are classified as either raw config or properties based on the extension of the file.s

Parameters:
  • files – Files to read configuration from.
rawConfigExists
boolean rawConfigExists(String module, String filename)

Allows to check if raw data has been registered for specified module

Parameters:
  • module – Module symbolic name
  • filename – Resource filename
Returns:

True if raw data exists for given parameters, false otherwise

registersProperties
boolean registersProperties(String module, String filename)

Checks if given module registers certain property file

Parameters:
  • module – Module we wish to perform check for
  • filename – Resource filename
Returns:

True if properties exist, false otherwise

removeModuleRecords
void removeModuleRecords(List<ModulePropertiesRecord> records)
removeProperties
void removeProperties(String module, String filename)

Removes properties for given module from database or file.

Parameters:
  • module – The module we wish to remove properties for
  • filename – Resource filename
requiresConfigurationFiles
boolean requiresConfigurationFiles()
retrieveRegisteredBundleNames
List<String> retrieveRegisteredBundleNames()

Depending on the selected ConfigSource mode, this method looks for registered bundle properties and returns a list of files it has found

Returns:List of files with registered properties
save
void save(BootstrapConfig bootstrapConfig)

Saves the given BootstrapConfig in the bootstrap.properties file located in default MOTECH config location. The default motech config location is specified in the file config-locations.properties.

Parameters:
  • bootstrapConfig – Bootstrap configuration.
Throws:
savePlatformSettings
void savePlatformSettings(Properties settings)
savePlatformSettings
void savePlatformSettings(MotechSettings settings)
saveRawConfig
void saveRawConfig(String module, String version, String bundle, String filename, InputStream rawData)

Allows persisting of raw json properties either in the database or file, depending on the selected ConfigSource mode.

Parameters:
  • module – Module we wish to save properties for
  • filename – Resource filename
  • rawData – Raw JSON data to persist
Throws:
  • IOException
setPlatformSetting
void setPlatformSetting(String key, String value)
updateConfigLocation
void updateConfigLocation(String newConfigLocation)

Adds a new config location and restarts the monitor.

Parameters:
  • newConfigLocation – New config location
updatePropertiesAfterReinstallation
void updatePropertiesAfterReinstallation(String module, String version, String bundle, String filename, Properties defaultProperties, Properties newProperties)

Works similar to addOrUpdateProperties but instead of just adding / updating properties checks database for any deprecated properties and removes to ensure that only current ones are available

Parameters:
  • module – The module we wish to update properties for
  • version – Version of updated bundle
  • bundle – Symbolic name of updated bundle
  • filename – Resource filename
  • newProperties – New properties to store
  • defaultProperties – Default properties of the module
Throws:
  • IOException – if module properties cannot be retrieved from file

ModulePropertiesService

public interface ModulePropertiesService extends MotechDataService<ModulePropertiesRecord>
Methods
findByBundle
List<ModulePropertiesRecord> findByBundle(String bundle)
findByModule
List<ModulePropertiesRecord> findByModule(String module)
findByModuleAndFileName
List<ModulePropertiesRecord> findByModuleAndFileName(String module, String filename)

org.motechproject.email.builder

EmailRecordSearchCriteria

public class EmailRecordSearchCriteria

The EmailRecordSearchCriteria class represents search criteria that may be used for searching org.motechproject.email.domain.EmailRecord entities in Motech Data Services. A consumer of this class may create search criteria to query on multiple fields by calling several of the with* methods. To perform the search, use org.motechproject.email.service.EmailAuditService.findEmailRecords(EmailRecordSearchCriteria).

Methods
getDeliveryStatuses
public Set<DeliveryStatus> getDeliveryStatuses()

Gets the delivery statuses criterion.

Returns:the delivery statuses criterion for this search criteria
getDeliveryTimeRange
public Range<DateTime> getDeliveryTimeRange()

Gets the delivery time range criterion.

Returns:the deliveryTimeRange criterion for this search criteria
getFromAddress
public String getFromAddress()

Gets the from address criterion.

Returns:the fromAddress criterion for this search criteria
getMessage
public String getMessage()

Gets the message body criterion.

Returns:the message criterion for this search criteria
getQueryParams
public QueryParams getQueryParams()

Gets the query paramaters that are used for controlling order and size of the query results for this search criteria.

Returns:the query params for this search criteria
getSubject
public String getSubject()

Gets the subject criterion.

Returns:the subject criterion for this search criteria
getToAddress
public String getToAddress()

Gets the to address criterion.

Returns:the toAddress criterion for this search criteria
withDeliveryStatuses
public EmailRecordSearchCriteria withDeliveryStatuses(Set<DeliveryStatus> deliveryStatuses)

Sets the delivery statuses criterion to the set specified

Parameters:
  • deliveryStatuses – the delivery statuses on which to search
Returns:

this EmailRecordSearchCriteria with its deliveryStatuses criterion set to the provided statuses

withDeliveryStatuses
public EmailRecordSearchCriteria withDeliveryStatuses(DeliveryStatus... deliveryStatuses)

Sets the delivery statuses criterion to the set specified

Parameters:
  • deliveryStatuses – the delivery statuses on which to search
Returns:

this EmailRecordSearchCriteria with its deliveryStatuses criterion set to the provided statuses

withFromAddress
public EmailRecordSearchCriteria withFromAddress(String fromAddress)

Sets the fromAddress criterion to the address specified

Parameters:
  • fromAddress – the sender email address on which to search
Returns:

this EmailRecordSearchCriteria with its fromAddress criterion set to the provided address

withMessage
public EmailRecordSearchCriteria withMessage(String message)

Sets the message criterion to the message specified

Parameters:
  • message – the email message body on which to search
Returns:

this EmailRecordSearchCriteria with its message criterion set to the provided message

withMessageTime
public EmailRecordSearchCriteria withMessageTime(DateTime deliveryTimeRange)

Sets the send time criterion to the time specified. Use this method to search on a specific date/time; if a range is needed, use withMessageTimeRange instead.

Parameters:
  • deliveryTimeRange – the specific time on which to search
Returns:

this EmailRecordSearchCriteria with its deliveryTimeRange criterion set to the specified date/time

withMessageTimeRange
public EmailRecordSearchCriteria withMessageTimeRange(Range<DateTime> deliveryTimeRange)

Sets the sent time criterion to the range specified. Use this method to search on a time range; if searching on a specific date/time is needed, use withMessageTime instead.

Parameters:
  • deliveryTimeRange – the date/time range on which to search
Returns:

this EmailRecordSearchCriteria with its deliveryTimeRange criterion set to the specified date/time range

withQueryParams
public EmailRecordSearchCriteria withQueryParams(QueryParams queryParams)

Sets the queryParams of the search criteria to the parameters specified. Use this method when it is necessary to specify order and size of query results. This is used mainly for paging/ordering queries from the UI.

Parameters:
  • queryParams – the query parameters to include with the search criteria
Returns:

this EmailRecordSearchCriteria with its queryParams set to the provided parameters

withSubject
public EmailRecordSearchCriteria withSubject(String subject)

Sets the subject criterion to the subject specified

Parameters:
  • subject – the subject on which to search
Returns:

this EmailRecordSearchCriteria with its subject criterion set to the provided subject

withToAddress
public EmailRecordSearchCriteria withToAddress(String toAddress)

Sets the toAddress criterion to the address specified

Parameters:
  • toAddress – the recipient email address on which to search
Returns:

this EmailRecordSearchCriteria with its toAddress criterion set to the provided address

org.motechproject.email.contract

Mail

public class Mail

The Mail class represents an email message.

Constructors
Mail
public Mail(String fromAddress, String toAddress, String subject, String message)

Creates a new instance of Mail, with all fields set to the values specified in the parameters.

Parameters:
  • fromAddress – the email address of the sender
  • toAddress – the email address of the recipient
  • subject – the subject of the email
  • message – the body of the email
Methods
equals
public boolean equals(Object obj)

Indicates whether some other object is “equal to” this one. Returns true if this Mail and the object to compare have reference equality or their field values are all equal.

Parameters:
  • obj – The reference object with which to compare
Returns:

true if this object is the same as the obj argument; false otherwise.

getFromAddress
public String getFromAddress()

Gets the email address of the sender.

Returns:the sender of the message
getMessage
public String getMessage()

Gets the message body.

Returns:the body of the message
getSubject
public String getSubject()

Gets the message subject.

Returns:the subject of the message
getText
public String getText()
getToAddress
public String getToAddress()

Gets the email address of the recipient.

Returns:the recipient of the message
hashCode
public int hashCode()

Returns a hash code value for this Mail object.

Returns:a hash code value for this Mail object
toString
public String toString()

Returns a string representation of this Mail object.

Returns:a string representation of this Mail object

org.motechproject.email.domain

DeliveryStatus

public enum DeliveryStatus

The DeliveryStatus Enum contains the possible delivery states for an email message.

Enum Constants
ERROR
public static final DeliveryStatus ERROR

There was an error sending the message.

RECEIVED
public static final DeliveryStatus RECEIVED

The message was received.

SENT
public static final DeliveryStatus SENT

The message was sent.

EmailRecord

public class EmailRecord

The EmailRecord class represents a record of a sent Email. This class is exposed as an org.motechproject.mds.annotations.Entity through Motech Data Services.

See also: org.motechproject.mds.annotations

Constructors
EmailRecord
public EmailRecord()

Creates a new instance of EmailRecord, with all fields set to null.

EmailRecord
public EmailRecord(String fromAddress, String toAddress, String subject, String message, DateTime deliveryTime, DeliveryStatus deliveryStatus)

Creates a new instance of EmailRecord, with all fields set to the values specified in the parameters.

Parameters:
  • fromAddress – the email address of the sender
  • toAddress – the email address of the recipient
  • subject – the subject of the email
  • message – the body of the email
  • deliveryTime – the date and time that the email was sent
  • deliveryStatus – the delivery status of the email
Methods
equals
public boolean equals(Object obj)

Indicates whether some other object is “equal to” this one. Returns true if this EmailRecord and the object to compare have reference equality or their field values are all equal.

Parameters:
  • obj – The reference object with which to compare.
Returns:

true if this object is the same as the obj argument; false otherwise.

getDeliveryStatus
public DeliveryStatus getDeliveryStatus()

Gets the delivery status.

Returns:the delivery status of the message
getDeliveryTime
public DateTime getDeliveryTime()

Gets the delivery time.

Returns:the time that the email was sent
getFromAddress
public String getFromAddress()

Gets the email address of the sender.

Returns:the sender of the message
getId
public Long getId()
getMessage
public String getMessage()

Gets the message body.

Returns:the body of the message
getSubject
public String getSubject()

Gets the message subject.

Returns:the subject of the message
getToAddress
public String getToAddress()

Gets the email address of the recipient.

Returns:the recipient of the message
hashCode
public int hashCode()

Returns a hash code value for this EmailRecord object.

Returns:a hash code value for this EmailRecord object
setFromAddress
public void setFromAddress(String fromAddress)

Sets the email address of the sender.

Parameters:
  • fromAddress – the sender of the message
setId
public void setId(Long id)
setMessage
public void setMessage(String message)

Sets the message body.

Parameters:
  • message – the body of the message
setSubject
public void setSubject(String subject)

Sets the message subject.

Parameters:
  • subject – the subject of the message
setToAddress
public void setToAddress(String toAddress)

Sets the email address of the recipient.

Parameters:
  • toAddress – the recipient of the message
toString
public String toString()

Returns a string representation of this EmailRecord object.

Returns:a string representation of this EmailRecord object

EmailRecordComparator

public class EmailRecordComparator implements Comparator<EmailRecord>

The EmailRecordComparator class is an implementation of the Comparator interface, that allows callers to compare org.motechproject.email.domain.EmailRecord objects by a single field.

Constructors
EmailRecordComparator
public EmailRecordComparator(Boolean ascending, String compareField)

Creates a new EmailRecordComparator that supports comparison based on the specified field.

Parameters:
  • ascending – boolean indicating whether comparisons should be ascending or descending
  • compareField – the field for which comparisons should be performed
Methods
compare
public int compare(EmailRecord o1, EmailRecord o2)

Compares its two arguments for order. If ascending is true, returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. If ascending is false, returns a positive integer, zero, or negative integer as the first argument is less than, equal to, or greater than the second.

Parameters:
  • o1 – the first EmailRecord to be compared
  • o2 – the second EmailRecord to be compared
Returns:

a positive integer, zero, or negative integer indicating the result of comparing the objects

EmailRecords

public class EmailRecords<T>

The EmailRecords class wraps the EmailRecord list and stores the current item count.

Constructors
EmailRecords
public EmailRecords()

Creates a new instance of EmailRecords, which contains no records.

EmailRecords
public EmailRecords(Integer totalRecords, Integer page, Integer totalPages, List<T> allRecords)

Creates a new instance of EmailRecords, with all fields set to the values specified in the parameters. The page and totalPages parameters are for the purposes of paginating the list of records in the UI.

Parameters:
  • totalRecords – the total number of records
  • page – the current page
  • totalPages – the total number of pages
  • allRecords – the list of records
Methods
getPage
public Integer getPage()

Gets the current page.

Returns:the current page
getRecords
public Integer getRecords()

Gets the total number of records.

Returns:the total number of records
getRows
public List<T> getRows()

Gets the list of records.

Returns:the list of records
getTotal
public Integer getTotal()

Gets the total number of pages.

Returns:the total number of pages
setRows
public void setRows(List<T> rows)

Sets the list of records.

Parameters:
  • rows – the list of records
setTotal
public void setTotal(Integer total)

Sets the total number of records.

Parameters:
  • total – the total number of records
toString
public String toString()

Returns a string representation of this EmailRecords object.

Returns:a string representation of this EmailRecords object

org.motechproject.email.service

EmailAuditService

public interface EmailAuditService

The EmailAuditService interface provides methods for logging email activity, as well as searching and deleting the email logs.

Methods
countEmailRecords
long countEmailRecords(EmailRecordSearchCriteria criteria)

Returns the count of EmailRecord entries matching the specified search criteria.

Returns:the count of email records matching the provided criteria
delete
void delete(EmailRecord emailRecord)

Deletes the specified EmailRecord entry from the email log.

findAllEmailRecords
List<EmailRecord> findAllEmailRecords()

Finds and returns all EmailRecord entries in the email log.

Returns:all email records in the email log
findById
EmailRecord findById(long id)

Finds an EmailRecord in the log by ID.

Parameters:
  • id – the identifier of the record to find
Returns:

the email record that matches the provided identifier, or null if no matching record exists

findEmailRecords
List<EmailRecord> findEmailRecords(EmailRecordSearchCriteria criteria)

Finds and returns all EmailRecord entries matching the specified search criteria.

Returns:all email records matching the provided criteria
log
void log(EmailRecord mailRecord)

Adds the provided EmailRecord to the email log.

Parameters:
  • mailRecord – the record to add to the email log

EmailRecordService

public interface EmailRecordService extends MotechDataService<EmailRecord>

This service provides data access for org.motechproject.email.domain.EmailRecord. The implementation is generated by Motech Data Services and published as an OSGi service.

Methods
countFind
long countFind(String fromAddress, String toAddress, String subject, String message, Range<DateTime> deliveryTimeRange, Set<DeliveryStatus> deliveryStatuses)

Returns the count of all EmailRecord entries matching the specified search parameters.

Parameters:
  • fromAddress – the sender address on which to search
  • toAddress – the recipient address on which to search
  • subject – the subject on which to search
  • message – the message body on which to search
  • deliveryTimeRange – the delivery time range on which to search
  • deliveryStatuses – the delivery statuses on which to search
Returns:

the count of EmailRecord entries that match the specified criteria

find
List<EmailRecord> find(String fromAddress, String toAddress, String subject, String message, Range<DateTime> deliveryTimeRange, Set<DeliveryStatus> deliveryStatuses, QueryParams queryParams)

Finds and returns all EmailRecord entries matching the specified search parameters. This method is exposed as a org.motechproject.mds.annotations.Lookup through Motech Data Services.

Parameters:
  • fromAddress – the sender address on which to search
  • toAddress – the recipient address on which to search
  • subject – the subject on which to search
  • message – the message body on which to search
  • deliveryTimeRange – the delivery time range on which to search
  • deliveryStatuses – the delivery statuses on which to search
  • queryParams – the query parameters to include with the search criteria
Returns:

the list of EmailRecord entries that match the specified criteria

See also: org.motechproject.mds.annotations

findByRecipientAddress
List<EmailRecord> findByRecipientAddress(String recipientAddress)

Finds and returns all EmailRecord entries for the specified recipient address. This method is exposed as a org.motechproject.mds.annotations.Lookup through Motech Data Services.

Parameters:
  • recipientAddress – the recipient address on which to search
Returns:

the list of EmailRecord entries that match the specified address

See also: org.motechproject.mds.annotations

EmailSenderService

public interface EmailSenderService

The EmailSenderService interface provides a method for sending email.

Methods
send
void send(Mail message)

Attempts to send the supplied email message. Adds an org.motechproject.email.domain.EmailRecord entry to the log with the details of the activity.

Parameters:
  • message – the message to send
Throws:
  • MailException – if an error occurs when attempting to send the message

org.motechproject.event

MotechEvent

public class MotechEvent implements Serializable

Motech Scheduled Event data carrier class, Instance of this class with event specific data will be send by Motech Scheduler when a scheduled event is fired

This class is immutable

Fields
EVENT_TYPE_KEY_NAME
public static final String EVENT_TYPE_KEY_NAME
PARAM_DISCARDED_MOTECH_EVENT
public static final String PARAM_DISCARDED_MOTECH_EVENT
PARAM_INVALID_MOTECH_EVENT
public static final String PARAM_INVALID_MOTECH_EVENT
PARAM_REDELIVERY_COUNT
public static final String PARAM_REDELIVERY_COUNT
Constructors
MotechEvent
public MotechEvent()
MotechEvent
public MotechEvent(String subject)

Constructor with subject only (parameters can be added interactively)

Parameters:
  • subject
    • event destination
Throws:
  • IllegalArgumentException
MotechEvent
public MotechEvent(String subject, Map<String, Object> parameters)

Constructor

Parameters:
  • subject
    • event type: Pill Reminder, Appointment Reminder ...
  • parameters
    • a Map of additional parameters
Throws:
  • IllegalArgumentException
Methods
copy
public MotechEvent copy(String subject, Map<String, Object> parameters)
equals
public boolean equals(Object o)
getEndTime
public Date getEndTime()
getId
public UUID getId()
getMessageRedeliveryCount
public int getMessageRedeliveryCount()
getParameters
public Map<String, Object> getParameters()

Sets empty HashMap if parameters=null

getSubject
public String getSubject()
hashCode
public int hashCode()
incrementMessageRedeliveryCount
public void incrementMessageRedeliveryCount()
isLastEvent
public boolean isLastEvent()
setEndTime
public MotechEvent setEndTime(Date endDate)
setId
public void setId(UUID id)
setLastEvent
public MotechEvent setLastEvent(boolean lastEvent)
toString
public String toString()

org.motechproject.event.listener

EventListener

public interface EventListener
Methods
getIdentifier
String getIdentifier()

Retrieve a unique identifier/key for the given listener class. This identifier is used when messages are destine for this specific listener type

Returns:Unique listener identifier/key
handle
void handle(MotechEvent event)

Handle an particular event that has been received

Parameters:
  • event

EventListenerRegistryService

public interface EventListenerRegistryService

This interface is necessary for OSGi service publication. The implementing class acts as a registry for all scheduled event listeners. One can register themselves to listen for a specific set of event types.

Methods
clearListenersForBean
void clearListenersForBean(String beanName)

This method is responsible for removing listeners for a particular bean. This is necessary when bundles are stopped in some fashion so that the listener does not persist.

Parameters:
  • beanName – The bean name from the Spring context of the candidate class for listener clearing
getListenerCount
int getListenerCount(String subject)

Get the count of listeners for a particular subject.

Parameters:
  • subject
getListeners
Set<EventListener> getListeners(String subject)

Retrieve a list of event listeners for a given event type. If there are no listeners, an empty list is returned.

Parameters:
  • subject – The event type that you are seeking listeners for
Returns:

A list of scheduled event listeners that are interested in that event

hasListener
boolean hasListener(String subject)

See if a particular subject has any listeners.

Parameters:
  • subject
registerListener
void registerListener(EventListener listener, List<String> subjects)

Register an event listener to be notified when events of a given type are received via the Server JMS Event Queue.

Parameters:
  • listener – the listener instance
  • subjects – the event types that a listener is interested in
registerListener
void registerListener(EventListener listener, String subject)

EventRelay

public interface EventRelay
Methods
sendEventMessage
void sendEventMessage(MotechEvent motechEvent)

org.motechproject.event.listener.annotations

MotechListener

public @interface MotechListener
Author:yyonkov

MotechListenerAbstractProxy

public abstract class MotechListenerAbstractProxy implements EventListener

Event Listener Proxy base abstract class

Author:yyonkov
Constructors
MotechListenerAbstractProxy
public MotechListenerAbstractProxy(String name, Object bean, Method method)
Parameters:
  • name
  • bean
  • method
Methods
callHandler
public abstract void callHandler(MotechEvent event)

Needs to be implemented by concrete Proxies

Parameters:
  • event
getBean
public Object getBean()
getIdentifier
public String getIdentifier()
getMethod
public Method getMethod()
handle
public void handle(MotechEvent event)

MotechListenerEventProxy

public class MotechListenerEventProxy extends MotechListenerAbstractProxy

Responsible for dispatching to void doSomething(MotechEvent event) {} type of handlers

Author:yyonkov
Constructors
MotechListenerEventProxy
public MotechListenerEventProxy(String name, Object bean, Method method)
Parameters:
  • name
  • bean
  • method
Methods
callHandler
public void callHandler(MotechEvent event)

MotechListenerNamedParametersProxy

public class MotechListenerNamedParametersProxy extends MotechListenerAbstractProxy
Author:yyonkov
Constructors
MotechListenerNamedParametersProxy
public MotechListenerNamedParametersProxy(String name, Object bean, Method method)
Parameters:
  • name
  • bean
  • method
Methods
callHandler
public void callHandler(MotechEvent event)

MotechListenerType

public enum MotechListenerType

ENUM defining the annotation types

Author:yyonkov
Enum Constants
MOTECH_EVENT
public static final MotechListenerType MOTECH_EVENT
NAMED_PARAMETERS
public static final MotechListenerType NAMED_PARAMETERS

MotechParam

public @interface MotechParam
Author:yyonkov

org.motechproject.event.queue

MotechCachingConnectionFactory

public class MotechCachingConnectionFactory extends CachingConnectionFactory

The MotechCachingConnectionFactory is used to created connection to ActiveMQ.

Methods
doCreateConnection
protected Connection doCreateConnection()
setBrokerUrl
public void setBrokerUrl(String brokerURL)
setPassword
public void setPassword(String password)
setUsername
public void setUsername(String username)

MotechEventConfig

public class MotechEventConfig
Methods
getMessageMaxRedeliveryCount
public int getMessageMaxRedeliveryCount()
getMessageRedeliveryDelay
public long getMessageRedeliveryDelay()

MotechEventHeaderMapper

public class MotechEventHeaderMapper extends DefaultJmsHeaderMapper

For the delay to work, set attribute schedulerSupport=”true” in the broker element of the activemq.xml Ref: http://activemq.apache.org/delay-and-schedule-message-delivery.html

Methods
fromHeaders
public void fromHeaders(MessageHeaders messageHeaders, Message message)

MotechEventTransformer

public class MotechEventTransformer
Methods
transform
public MotechEvent transform(MotechEvent motechEvent)

OutboundEventGateway

public interface OutboundEventGateway
Methods
sendEventMessage
void sendEventMessage(MotechEvent motechEvent)

Sends the given MotechEvent message as a payload to the message channel defined in the Spring Integration configuration file.

Parameters:
  • motechEvent

org.motechproject.mds.annotations

Cascade

public @interface Cascade

The Cascade annotation is used by developers to set correct cascade properties for the given field that is a relationship.

See also: org.motechproject.mds.annotations.internal.FieldProcessor

Entity

public @interface Entity

The Entity annotation is used by developers to point classes, that should be mapped as Motech Dataservices Entities. The discovery logic for this annotation is done in org.motechproject.mds.annotations.internal.EntityProcessor

See also: org.motechproject.mds.annotations.internal.EntityProcessor

Field

public @interface Field

The Field annotation is used by developers to point fields, that should be mapped as entity fields. The discovery logic for this annotation is done in org.motechproject.mds.annotations.internal.FieldProcessor.

Only fields, ‘getter’ or ‘setter’ methods can have this annotation for other methods this annotation is omitted.

See also: org.motechproject.mds.annotations.internal.FieldProcessor

Ignore

public @interface Ignore

Thanks to this annotation, developers can point public fields and getter/setter method of a private field that should not be added to the schema definition of an entity. By default, all public fields of an object are added. The discovery logic for this annotation is done in the FieldProcessor

See also: org.motechproject.mds.annotations.internal.FieldProcessor

InSet

public @interface InSet

The annotated element must have value that will be in defined set.

Supported types are:

  • Integer
  • Double
  • int, double

Lookup

public @interface Lookup

The Lookup annotation is used by developers to point methods, in classes that implements org.motechproject.mds.service.MotechDataService, that should be mapped as Motech Dataservices Lookups. The discovery logic for this annotation is done in org.motechproject.mds.annotations.internal.LookupProcessor

See also: org.motechproject.mds.annotations.internal.LookupProcessor

LookupField

public @interface LookupField

The LookupField annotation allows developers to point fields in Lookup method, that should be mapped as Lookup fields for Developer Defined Lookup. The discovery logic for this annotation is done in org.motechproject.mds.annotations.internal.LookupProcessor

See also: org.motechproject.mds.annotations.internal.LookupProcessor

NotInSet

public @interface NotInSet

The annotated element must not have value that will be in defined set.

Supported types are:

  • Integer
  • Double
  • int, double

UIDisplayable

public @interface UIDisplayable

The UIDisplayable annotation is used by developers to mark a field as being in the default display for a listing of objects. The discovery logic for this annotation is done in org.motechproject.mds.annotations.internal.UIDisplayableProcessor.

Only fields, ‘getter’ or ‘setter’ methods can have this annotation for other methods this annotation is omitted.

See also: org.motechproject.mds.annotations.internal.UIDisplayableProcessor

UIFilterable

public @interface UIFilterable

The UIFilterable annotation is used by developers to mark a field that allow users to filter a list of objects by the values in the field. The discovery logic for this annotation is done in org.motechproject.mds.annotations.internal.UIFilterableProcessor.

Only fields, ‘getter’ or ‘setter’ methods can have this annotation for other methods this annotation is omitted. Also this annotation is permitted on fields of type Date, Boolean or List.

See also: org.motechproject.mds.annotations.internal.UIFilterableProcessor

org.motechproject.mds.builder

EntityBuilder

public interface EntityBuilder

An entity builder is responsible for building the entity class from an Entity schema.

Methods
build
ClassData build(Entity entity)

Builds a class definition for a given entity. The class is not registered with any classloader.

Parameters:
  • entity – the entity schema
Returns:

bytes of the newly constructed class

buildDDE
ClassData buildDDE(Entity entity, Bundle bundle)

Builds Developer Defined Entity. The main difference between regular build method and this one, is that this method fetches the class definition from the given bundle, and injects members to the constructed class from there, if possible, rather than building everything from scratch.

Parameters:
  • entity – the entity schema
  • bundle – the bundle to fetch class definition from
Returns:

bytes of the constructed class

buildHistory
ClassData buildHistory(Entity entity)

Builds History class definition for the given entity. The history class definition contains the same members as the entity class, plus some fields history-exclusive, like schema version.

Parameters:
  • entity – the entity schema
Returns:

bytes of the constructed class

buildTrash
ClassData buildTrash(Entity entity)

Builds Trash class definition for the given entity. The trash class definition contains the same members as the entity class, plus some fields trash-exclusive.

Parameters:
  • entity – the entity schema
Returns:

bytes of the constructed class

prepareHistoryClass
void prepareHistoryClass(Entity entity)

Builds empty history class definition for the given entity and adds it to the class pool.

Parameters:
  • entity – the entity schema
prepareTrashClass
void prepareTrashClass(Entity entity)

Builds empty trash class definition for the given entity and adds it to the class pool.

Parameters:
  • entity – the entity schema

EntityInfrastructureBuilder

public interface EntityInfrastructureBuilder

The EntityInfrastructureBuilder is responsible for building infrastructure for a given entity: repository, interface and service classes.

Methods
buildHistoryInfrastructure
List<ClassData> buildHistoryInfrastructure(String className)

Builds the repository, interface and implementation of this interface classes for the given history class. The names for classes are generated by org.motechproject.mds.util.ClassName.getRepositoryName(String), org.motechproject.mds.util.ClassName.getInterfaceName(String), org.motechproject.mds.util.ClassName.getServiceName(String), respectively.

Parameters:
  • className – a name of history class.
Returns:

a list of classes that represents infrastructure for the history class.

buildInfrastructure
List<ClassData> buildInfrastructure(Entity entity)

Builds the repository, interface and implementation of this interface classes for the given entity. The names for classes are generated by org.motechproject.mds.util.ClassName.getRepositoryName(String), org.motechproject.mds.util.ClassName.getInterfaceName(String), org.motechproject.mds.util.ClassName.getServiceName(String), respectively.

Parameters:
Returns:

a list of classes that represents infrastructure for the given entity.

EntityMetadataBuilder

public interface EntityMetadataBuilder

The EntityMetadataBuilderImpl class is responsible for building jdo metadata for an entity class.

Methods
addBaseMetadata
void addBaseMetadata(JDOMetadata jdoMetadata, ClassData classData)

Adds base information about package and class name to a javax.jdo.metadata.JDOMetadata instance.

Parameters:
addEntityMetadata
void addEntityMetadata(JDOMetadata jdoMetadata, Entity entity)

Adds information about package and class name to a javax.jdo.metadata.JDOMetadata instance.

Parameters:
addHelperClassMetadata
void addHelperClassMetadata(JDOMetadata jdoMetadata, ClassData classData, Entity entity)

Creates metadata with basic information about package and class name to the javax.jdo.metadata.JDOMetadata instance. Additionally, fetches fields from passed entites and adds metadata for fields, if it’s necessary. If entity is null, it will work just like addBaseMetadata(JDOMetadata, ClassData) and won’t add any metadata for fields.

Parameters:
fixEnhancerIssuesInMetadata
void fixEnhancerIssuesInMetadata(JDOMetadata jdoMetadata)

This updates the metadata after enhancement. Nucleus makes some “corrections” which do not work with the runtime enhancer.

EnumBuilder

public interface EnumBuilder

An enum builder is responsible for building the enum class with the same values as those are defined in the field.

Methods
build
ClassData build(ComboboxHolder holder)

MDSConstructor

public interface MDSConstructor

This interface provide method to create a class for the given entity. The implementation of this interface should also construct other classes like repository, service interface and implementation for this service interface.

Methods
constructEntities
boolean constructEntities(boolean buildDDE)

Creates a class definition and insert it into the MDS class loader based on data from database. The implementation of this method should also create a repository, interface (when it’s necessary) and implementation of this interface.

After executing this method, there should be possible to create an instance of the given class definition and save it to database by javax.jdo.PersistenceManager provided by DataNucleus.

An interface related with class definition should be created only for entities from outside bundles and if the bundle does not define its interface.

Parameters:
  • buildDDEtrue if class definitions for entities from outside bundles should also be created; otherwise false.
Returns:

true if there were entities for which class definitions should be created; otherwise false.

updateFields
void updateFields(Long entityId, Map<String, String> fieldNameChanges)

Updates the field names of an entity. This method changes the database schema by changing column names to the new value. This is done for the entity instances, history instances and trash instances.

Parameters:
  • entityId – The ID of an entity to update
  • fieldNameChanges – A map, indexed by current field names and values being updated field names.

MDSDataProviderBuilder

public interface MDSDataProviderBuilder
Methods
generateDataProvider
String generateDataProvider()

org.motechproject.mds.config

DeleteMode

public enum DeleteMode

The DeleteMode presents what should happen with objects when they are deleted. They can be deleted permanently DELETE or moved to the trash TRASH. This enum is related with the property org.motechproject.mds.util.Constants.Config.MDS_DELETE_MODE.

The UNKNOWN value should not be used in code as appropriate value. It was added to ensure that the fromString(String) method will not return {@value null} value.

Enum Constants
DELETE
public static final DeleteMode DELETE
TRASH
public static final DeleteMode TRASH
UNKNOWN
public static final DeleteMode UNKNOWN

MdsConfig

public class MdsConfig

Class responsible for handling MDS configuration. Since MDS don’t use Server Config everything connected to the MDS configuration needs to be handled by the module itself.

Constructors
MdsConfig
public MdsConfig()
Methods
asProperties
public Properties asProperties()
getDataNucleusProperties
public Properties getDataNucleusProperties()
getProperties
public Properties getProperties(String filename)
getResourceFileName
public String getResourceFileName(Resource resource)
setConfig
public void setConfig(List<Resource> resources)

ModuleSettings

public class ModuleSettings extends Properties

The ModuleSettings contains the base module settings which are inside the org.motechproject.mds.util.Constants.Config.MODULE_FILE. The getters and setters inside this class always checks the given property and if it is incorrect then the default value of the given property will be returned.

Fields
DEFAULT_DELETE_MODE
public static final DeleteMode DEFAULT_DELETE_MODE
DEFAULT_EMPTY_TRASH
public static final Boolean DEFAULT_EMPTY_TRASH
DEFAULT_TIME_UNIT
public static final TimeUnit DEFAULT_TIME_UNIT
DEFAULT_TIME_VALUE
public static final Integer DEFAULT_TIME_VALUE
Methods
equals
public boolean equals(Object obj)
getDeleteMode
public DeleteMode getDeleteMode()
getTimeUnit
public TimeUnit getTimeUnit()
getTimeValue
public Integer getTimeValue()
hashCode
public int hashCode()
isEmptyTrash
public Boolean isEmptyTrash()
setDeleteMode
public void setDeleteMode(String deleteMode)
setDeleteMode
public void setDeleteMode(DeleteMode deleteMode)
setEmptyTrash
public void setEmptyTrash(String emptyTrash)
setEmptyTrash
public void setEmptyTrash(Boolean emptyTrash)
setTimeUnit
public void setTimeUnit(String timeUnit)
setTimeUnit
public void setTimeUnit(TimeUnit timeUnit)
setTimeValue
public void setTimeValue(String timeValue)
setTimeValue
public void setTimeValue(Integer timeValue)
toString
public String toString()

ModuleSettings.Deserializer

public static final class Deserializer extends JsonDeserializer<ModuleSettings>
Methods
deserialize
public ModuleSettings deserialize(JsonParser jp, DeserializationContext ctxt)

ModuleSettings.Serializer

public static final class Serializer extends JsonSerializer<ModuleSettings>
Methods
serialize
public void serialize(ModuleSettings value, JsonGenerator jgen, SerializerProvider provider)

SettingsService

public interface SettingsService

The SettingsService is a service class for org.motechproject.server.config.SettingsFacade. Its main purpose is to create better access to module settings for developers.

Methods
getDeleteMode
DeleteMode getDeleteMode()
getModuleSettings
ModuleSettings getModuleSettings()
getProperties
Properties getProperties()
getTimeUnit
TimeUnit getTimeUnit()
getTimeValue
Integer getTimeValue()
isEmptyTrash
Boolean isEmptyTrash()
saveModuleSettings
void saveModuleSettings(ModuleSettings settings)

TimeUnit

public enum TimeUnit

The TimeUnit specifies what time unit should be used to specify time when the module trash should be cleaned. This enum is related with the property org.motechproject.mds.util.Constants.Config.MDS_TIME_UNIT.

Each value from this enum can be converted to long value that presents time interval in milliseconds. For example the HOURS value is equal to {@value 3.6E6}.

The UNKNOWN value should not be used in code as appropriate value. It was added to ensure that the fromString(String) method will not return {@value null} value.

Enum Constants
DAYS
public static final TimeUnit DAYS
HOURS
public static final TimeUnit HOURS
MONTHS
public static final TimeUnit MONTHS
UNKNOWN
public static final TimeUnit UNKNOWN
WEEKS
public static final TimeUnit WEEKS
YEARS
public static final TimeUnit YEARS

org.motechproject.mds.domain

BrowsingSettings

public class BrowsingSettings

The BrowsingSettings contains information about fields that will be visible on UI and could be used as filter on UI.

This class is read only (the data are not saved to database) and its main purpose is to provide methods that help developer to get displayed and filterable fields.

Constructors
BrowsingSettings
public BrowsingSettings(Entity entity)
Methods
getDisplayedFields
public List<Field> getDisplayedFields()
getEntity
public Entity getEntity()
getFilterableFields
public List<Field> getFilterableFields()
setEntity
public void setEntity(Entity entity)
toDto
public BrowsingSettingsDto toDto()

ClassData

public class ClassData

Represents a class name and its byte code.

Constructors
ClassData
public ClassData(String className, byte[] bytecode)
ClassData
public ClassData(String className, byte[] bytecode, boolean interfaceClass)
ClassData
public ClassData(Entity entity, byte[] bytecode)
ClassData
public ClassData(Entity entity, byte[] bytecode, boolean interfaceClass)
ClassData
public ClassData(String className, String module, String namespace, byte[] bytecode)
ClassData
public ClassData(String className, String module, String namespace, byte[] bytecode, EntityType type)
ClassData
public ClassData(String className, String module, String namespace, byte[] bytecode, boolean interfaceClass)
ClassData
public ClassData(String className, String module, String namespace, byte[] bytecode, boolean interfaceClass, EntityType type)
Methods
getBytecode
public byte[] getBytecode()
getClassName
public String getClassName()
getModule
public String getModule()
getNamespace
public String getNamespace()
getType
public EntityType getType()
isDDE
public boolean isDDE()
isInterfaceClass
public boolean isInterfaceClass()
toString
public String toString()

ComboboxHolder

public class ComboboxHolder extends FieldHolder

The main purpose of this class is to find out what kind of type should be used when the field will be added to the class definition.

Constructors
ComboboxHolder
public ComboboxHolder(Field field)
ComboboxHolder
public ComboboxHolder(Entity entity, Field field)
ComboboxHolder
public ComboboxHolder(EntityDto entity, FieldDto field)
ComboboxHolder
public ComboboxHolder(List<? extends Pair<String, String>> metadata, List<? extends Pair<String, ?>> settings, String defaultEnumName)
Methods
getEnumName
public String getEnumName()
getValues
public String[] getValues()
isAllowMultipleSelections
public boolean isAllowMultipleSelections()
isAllowUserSupplied
public boolean isAllowUserSupplied()
isEnum
public boolean isEnum()
isEnumList
public boolean isEnumList()
isString
public boolean isString()
isStringList
public boolean isStringList()

ConfigSettings

public class ConfigSettings
Constructors
ConfigSettings
public ConfigSettings()
ConfigSettings
public ConfigSettings(DeleteMode deleteMode, boolean emptyTrash, int afterTimeValue, TimeUnit afterTimeUnit)
Methods
getAfterTimeUnit
public TimeUnit getAfterTimeUnit()
getAfterTimeValue
public int getAfterTimeValue()
getDeleteMode
public DeleteMode getDeleteMode()
getEmptyTrash
public boolean getEmptyTrash()
getId
public Long getId()
setAfterTimeUnit
public void setAfterTimeUnit(TimeUnit afterTimeUnit)
setAfterTimeValue
public void setAfterTimeValue(int afterTimeValue)
setDeleteMode
public void setDeleteMode(DeleteMode deleteMode)
setEmptyTrash
public void setEmptyTrash(boolean emptyTrash)
setId
public void setId(Long id)

Entity

public class Entity

The Entity class contains information about an entity. Also it contains information about advanced settings related with the entity.

Constructors
Entity
public Entity()
Entity
public Entity(String className)
Entity
public Entity(String className, String module, String namespace, SecurityMode securityMode)
Entity
public Entity(String className, String name, String module, String namespace, SecurityMode securityMode, Set<String> securityMembers)
Methods
addField
public void addField(Field field)
addLookup
public void addLookup(Lookup lookup)
advancedSettingsDto
public AdvancedSettingsDto advancedSettingsDto()
getBrowsingSettings
public BrowsingSettings getBrowsingSettings()
getClassName
public String getClassName()
getDrafts
public List<EntityDraft> getDrafts()
getEntityVersion
public Long getEntityVersion()
getField
public Field getField(Long id)
getField
public Field getField(String name)
getFields
public List<Field> getFields()
getId
public Long getId()
getLookupById
public Lookup getLookupById(Long lookupId)
getLookupByName
public Lookup getLookupByName(String lookupName)
getLookups
public List<Lookup> getLookups()
getLookupsDtos
public List<LookupDto> getLookupsDtos()
getModule
public String getModule()
getName
public String getName()
getNamespace
public String getNamespace()
getRestOptions
public RestOptions getRestOptions()
getSecurityMembers
public Set<String> getSecurityMembers()
getSecurityMode
public SecurityMode getSecurityMode()
getStringComboboxFields
public List<Field> getStringComboboxFields()
getSuperClass
public String getSuperClass()
getTracking
public Tracking getTracking()
isAbstractClass
public boolean isAbstractClass()
isActualEntity
public boolean isActualEntity()
isBaseEntity
public boolean isBaseEntity()
isDDE
public boolean isDDE()
isDraft
public boolean isDraft()
removeField
public void removeField(Long fieldId)
removeLookup
public void removeLookup(Long lookupId)
setAbstractClass
public void setAbstractClass(boolean abstractClass)
setClassName
public void setClassName(String className)
setDrafts
public void setDrafts(List<EntityDraft> drafts)
setEntityVersion
public void setEntityVersion(Long entityVersion)
setFields
public void setFields(List<Field> fields)
setId
public void setId(Long id)
setLookups
public void setLookups(List<Lookup> lookups)
setModule
public void setModule(String module)
setName
public final void setName(String name)
setNamespace
public void setNamespace(String namespace)
setRestOptions
public void setRestOptions(RestOptions restOptions)
setSecurity
public void setSecurity(SecurityMode securityMode, List<String> securityMembersList)
setSecurityMembers
public void setSecurityMembers(Set<String> securityMembers)
setSecurityMode
public void setSecurityMode(SecurityMode securityMode)
setSuperClass
public void setSuperClass(String superClass)
setTracking
public void setTracking(Tracking tracking)
toDto
public EntityDto toDto()
updateAdvancedSetting
public void updateAdvancedSetting(AdvancedSettingsDto advancedSettings)
updateFromDraft
public void updateFromDraft(EntityDraft draft)

EntityAudit

public class EntityAudit extends Entity

This class represents a single historical commit of an Entity.

Methods
getModificationDate
public DateTime getModificationDate()
getOwnerUsername
public String getOwnerUsername()
getVersion
public Long getVersion()
isActualEntity
public boolean isActualEntity()
setModificationDate
public void setModificationDate(DateTime modificationDate)
setOwnerUsername
public void setOwnerUsername(String ownerUsername)
setVersion
public void setVersion(Long version)

EntityDraft

public class EntityDraft extends Entity

This class represents a users draft of an Entity. A draft is a users work in progress from the UI. This shares the table with its superclass, Entity.

Constructors
EntityDraft
public EntityDraft()
Methods
getDraftOwnerUsername
public String getDraftOwnerUsername()
getFieldNameChanges
public Map<String, String> getFieldNameChanges()
getLastModificationDate
public DateTime getLastModificationDate()
getParentEntity
public Entity getParentEntity()
getParentVersion
public Long getParentVersion()
isActualEntity
public boolean isActualEntity()
isChangesMade
public boolean isChangesMade()
isDraft
public boolean isDraft()
isOutdated
public boolean isOutdated()
setChangesMade
public void setChangesMade(boolean changesMade)
setDraftOwnerUsername
public void setDraftOwnerUsername(String draftOwnerUsername)
setFieldNameChanges
public void setFieldNameChanges(Map<String, String> fieldNameChanges)
setLastModificationDate
public void setLastModificationDate(DateTime lastModificationDate)
setParentEntity
public void setParentEntity(Entity parentEntity)
setParentVersion
public void setParentVersion(Long parentVersion)
toDto
public EntityDto toDto()

EntityInfo

public class EntityInfo

The EntityInfo class contains base information about the given entity like class name or infrastructure classes name.

See also: org.motechproject.mds.service.JarGeneratorService

Methods
getClassName
public String getClassName()
getInfrastructure
public String[] getInfrastructure()
getInterfaceName
public String getInterfaceName()
getName
public String getName()
getRepository
public String getRepository()
getServiceName
public String getServiceName()
setClassName
public void setClassName(String className)
setInterfaceName
public void setInterfaceName(String interfaceName)
setRepository
public void setRepository(String repository)
setServiceName
public void setServiceName(String serviceName)

EntityType

public enum EntityType
Enum Constants
HISTORY
public static final EntityType HISTORY
STANDARD
public static final EntityType STANDARD
TRASH
public static final EntityType TRASH

Field

public class Field

The Field class contains information about a single field.

Constructors
Field
public Field()
Field
public Field(Entity entity, String displayName, String name, Set<Lookup> lookups)
Field
public Field(Entity entity, String name, String displayName, Type type, boolean required, boolean readOnly)
Field
public Field(Entity entity, String displayName, String name, boolean required, boolean readOnly, String defaultValue, String tooltip, Set<Lookup> lookups)
Methods
addMetadata
public void addMetadata(FieldMetadata metadata)
addSetting
public void addSetting(FieldSetting setting)
addValidation
public void addValidation(FieldValidation validation)
copy
public Field copy()
getDefaultValue
public String getDefaultValue()
getDisplayName
public String getDisplayName()
getEntity
public Entity getEntity()
getId
public Long getId()
getLookups
public Set<Lookup> getLookups()
getMetadata
public List<FieldMetadata> getMetadata()
getMetadata
public FieldMetadata getMetadata(String key)
getMetadataById
public FieldMetadata getMetadataById(Long id)
getName
public String getName()
getSettingByName
public FieldSetting getSettingByName(String name)
getSettings
public List<FieldSetting> getSettings()
getTooltip
public String getTooltip()
getType
public Type getType()
getUIDisplayPosition
public Long getUIDisplayPosition()
getValidationByName
public FieldValidation getValidationByName(String name)
getValidations
public List<FieldValidation> getValidations()
isExposedViaRest
public boolean isExposedViaRest()
isReadOnly
public boolean isReadOnly()
isRequired
public boolean isRequired()
isTracked
public boolean isTracked()
isUIDisplayable
public boolean isUIDisplayable()
isUIFilterable
public boolean isUIFilterable()
setDefaultValue
public void setDefaultValue(String defaultValue)
setDisplayName
public void setDisplayName(String displayName)
setEntity
public void setEntity(Entity entity)
setExposedViaRest
public void setExposedViaRest(boolean exposedViaRest)
setId
public void setId(Long id)
setLookups
public void setLookups(Set<Lookup> lookups)
setMetadata
public void setMetadata(List<FieldMetadata> metadata)
setName
public final void setName(String name)
setReadOnly
public void setReadOnly(boolean readOnly)
setRequired
public void setRequired(boolean required)
setSettings
public void setSettings(List<FieldSetting> settings)
setTooltip
public void setTooltip(String tooltip)
setTracked
public void setTracked(boolean tracked)
setType
public void setType(Type type)
setUIDisplayPosition
public void setUIDisplayPosition(Long uiDisplayPosition)
setUIDisplayable
public void setUIDisplayable(boolean uiDisplayable)
setUIFilterable
public void setUIFilterable(boolean uiFilterable)
setValidations
public void setValidations(List<FieldValidation> validations)
toDto
public FieldDto toDto()
update
public Field update(FieldDto field)

FieldHolder

public class FieldHolder

The main purpose of this class is to give a easy way to access values inside metadata and settings related with the given field.

Constructors
FieldHolder
public FieldHolder(Field field)
FieldHolder
public FieldHolder(FieldDto field)
FieldHolder
protected FieldHolder(List<? extends Pair<String, String>> metadata, List<? extends Pair<String, ?>> settings)
Methods
getMetadata
public String getMetadata(String name)
getMetadata
public String getMetadata(String name, String defaultValue)
getSetting
public String getSetting(String name)
getSetting
public String getSetting(String name, String defaultValue)
getSettingAsArray
public String[] getSettingAsArray(String name)
getSettingAsBoolean
public boolean getSettingAsBoolean(String name)

FieldMetadata

public class FieldMetadata implements Pair<String, String>

The FieldMetadata class contains information about a single metadata added into a field.

Constructors
FieldMetadata
public FieldMetadata()
FieldMetadata
public FieldMetadata(Field field, String key)
FieldMetadata
public FieldMetadata(MetadataDto metadata)
FieldMetadata
public FieldMetadata(Field field, String key, String value)
Methods
copy
public FieldMetadata copy()
getField
public Field getField()
getId
public Long getId()
getKey
public String getKey()
getValue
public String getValue()
setField
public void setField(Field field)
setId
public void setId(Long id)
setKey
public void setKey(String key)
setValue
public void setValue(String value)
toDto
public MetadataDto toDto()
update
public final void update(MetadataDto metadata)

FieldSetting

public class FieldSetting implements Pair<String, String>
Constructors
FieldSetting
public FieldSetting()
FieldSetting
public FieldSetting(Field field, TypeSetting details)
FieldSetting
public FieldSetting(Field field, TypeSetting details, String value)
Methods
copy
public FieldSetting copy()
getDetails
public TypeSetting getDetails()
getField
public Field getField()
getId
public Long getId()
getKey
public String getKey()
getValue
public String getValue()
setDetails
public void setDetails(TypeSetting details)
setField
public void setField(Field field)
setId
public void setId(Long id)
setValue
public void setValue(String value)
toDto
public SettingDto toDto()

FieldValidation

public class FieldValidation

The FieldValidation class contains the value that is related with the correct type validation and information about that whether the given validation is enabled or not.

Constructors
FieldValidation
public FieldValidation()
FieldValidation
public FieldValidation(Field field, TypeValidation details)
FieldValidation
public FieldValidation(Field field, TypeValidation details, String value, boolean enabled)
Methods
copy
public FieldValidation copy()
getDetails
public TypeValidation getDetails()
getField
public Field getField()
getId
public Long getId()
getValue
public String getValue()
isEnabled
public boolean isEnabled()
setDetails
public void setDetails(TypeValidation details)
setEnabled
public void setEnabled(boolean enabled)
setField
public void setField(Field field)
setId
public void setId(Long id)
setValue
public void setValue(String value)
toDto
public ValidationCriterionDto toDto()

Lookup

public class Lookup

The Lookup class contains information about single lookup

Constructors
Lookup
public Lookup()
Lookup
public Lookup(String lookupName, boolean singleObjectReturn, boolean exposedViaRest, List<Field> fields)
Lookup
public Lookup(String lookupName, boolean singleObjectReturn, boolean exposedViaRest, List<Field> fields, boolean readOnly, String methodName)
Lookup
public Lookup(String lookupName, boolean singleObjectReturn, boolean exposedViaRest, List<Field> fields, boolean readOnly, String methodName, List<String> rangeLookupFields, List<String> setLookupFields, Map<String, String> customOperators)
Lookup
public Lookup(String lookupName, boolean singleObjectReturn, boolean exposedViaRest, List<Field> fields, boolean readOnly, String methodName, List<String> rangeLookupFields, List<String> setLookupFields, Map<String, String> customOperators, Map<String, Boolean> useGenericParams)
Lookup
public Lookup(String lookupName, boolean singleObjectReturn, boolean exposedViaRest, List<Field> fields, Entity entity)
Lookup
public Lookup(LookupDto lookupDto, List<Field> lookupFields)
Methods
copy
public Lookup copy(List<Field> fields)
getCustomOperators
public Map<String, String> getCustomOperators()
getEntity
public Entity getEntity()
getFields
public List<Field> getFields()
getId
public Long getId()
getLookupFieldById
public final Field getLookupFieldById(Long id)
getLookupFieldByName
public final Field getLookupFieldByName(String name)
getLookupName
public String getLookupName()
getMethodName
public String getMethodName()
getRangeLookupFields
public final List<String> getRangeLookupFields()
getSetLookupFields
public final List<String> getSetLookupFields()
getUseGenericParams
public Map<String, Boolean> getUseGenericParams()
isExposedViaRest
public boolean isExposedViaRest()
isRangeParam
public boolean isRangeParam(Field field)
isReadOnly
public boolean isReadOnly()
isSetParam
public boolean isSetParam(Field field)
isSingleObjectReturn
public boolean isSingleObjectReturn()
setCustomOperators
public void setCustomOperators(Map<String, String> customOperators)
setEntity
public void setEntity(Entity entity)
setExposedViaRest
public void setExposedViaRest(boolean exposedViaRest)
setFields
public void setFields(List<Field> fields)
setId
public void setId(Long id)
setLookupName
public final void setLookupName(String lookupName)
setMethodName
public void setMethodName(String methodName)
setRangeLookupFields
public void setRangeLookupFields(List<String> rangeLookupFields)
setReadOnly
public void setReadOnly(boolean readOnly)
setSetLookupFields
public void setSetLookupFields(List<String> setLookupFields)
setSingleObjectReturn
public void setSingleObjectReturn(boolean singleObjectReturn)
setUseGenericParams
public void setUseGenericParams(Map<String, Boolean> useGenericParams)
toDto
public LookupDto toDto()
update
public final void update(LookupDto lookupDto, List<Field> lookupFields)

OneToManyRelationship

public class OneToManyRelationship extends Relationship

A specialization of the Relationship class. Represents a one-to-many relationship.

Methods
getFieldType
public String getFieldType(Field field, EntityType type)
getGenericSignature
public String getGenericSignature(Field field, EntityType type)

OneToOneRelationship

public class OneToOneRelationship extends Relationship

A specialization of the Relationship class. Represents a one-to-one relationship.

Methods
getFieldType
public String getFieldType(Field field, EntityType type)
getGenericSignature
public String getGenericSignature(Field field, EntityType type)

Relationship

public class Relationship

A class representing a relationship type. This class is inherited by different types of relationships. This class only represents the field type and provides some utility methods. It is not used in entities themselves.

Methods
getFieldType
public String getFieldType(Field field, EntityType type)
getGenericSignature
public String getGenericSignature(Field field, EntityType type)
getRelatedClassName
protected String getRelatedClassName(Field field, EntityType type)

RelationshipHolder

public class RelationshipHolder extends FieldHolder

The main purpose of this class is to find out how cascade should be used for the given field with relationship type.

Constructors
RelationshipHolder
public RelationshipHolder(Field field)
RelationshipHolder
public RelationshipHolder(ClassData data, Field field)
Methods
getRelatedClass
public String getRelatedClass()
isCascadeDelete
public boolean isCascadeDelete()
isCascadePersist
public boolean isCascadePersist()
isCascadeUpdate
public boolean isCascadeUpdate()
isOneToMany
public boolean isOneToMany()
isOneToOne
public boolean isOneToOne()

RestOptions

public class RestOptions

The RestOptions class representing rest options of given entity. This class is related with table in database with the same name.

Constructors
RestOptions
public RestOptions()
RestOptions
public RestOptions(Entity entity)
Methods
copy
public RestOptions copy()
getEntity
public Entity getEntity()
getFields
public List<Field> getFields()
getId
public Long getId()
getLookups
public List<Lookup> getLookups()
isAllowCreate
public boolean isAllowCreate()
isAllowDelete
public boolean isAllowDelete()
isAllowRead
public boolean isAllowRead()
isAllowUpdate
public boolean isAllowUpdate()
setAllowCreate
public void setAllowCreate(boolean allowCreate)
setAllowDelete
public void setAllowDelete(boolean allowDelete)
setAllowRead
public void setAllowRead(boolean allowRead)
setAllowUpdate
public void setAllowUpdate(boolean allowUpdate)
setEntity
public void setEntity(Entity entity)
setId
public void setId(Long id)
toDto
public RestOptionsDto toDto()
update
public final void update(RestOptionsDto restOptionsDto)

Tracking

public class Tracking

The Tracking contains information about which fields and what kind of actions should be logged. This class is related with table in database with the same name.

Constructors
Tracking
public Tracking()
Tracking
public Tracking(Entity entity)
Methods
copy
public Tracking copy()
getEntity
public Entity getEntity()
getFields
public List<Field> getFields()
getId
public Long getId()
isAllowCreate
public boolean isAllowCreate()
isAllowDelete
public boolean isAllowDelete()
isAllowRead
public boolean isAllowRead()
isAllowUpdate
public boolean isAllowUpdate()
setAllowCreate
public void setAllowCreate(boolean allowCreate)
setAllowDelete
public void setAllowDelete(boolean allowDelete)
setAllowRead
public void setAllowRead(boolean allowRead)
setAllowUpdate
public void setAllowUpdate(boolean allowUpdate)
setEntity
public void setEntity(Entity entity)
setId
public void setId(Long id)
toDto
public TrackingDto toDto()

Type

public class Type

The Type class contains information about a single type in mds system. The mds type can have a settings and validations that can be assigned to field with the same type.

Constructors
Type
public Type()
Type
public Type(Class<?> typeClass)
Type
public Type(String displayName, String description, Class<?> typeClass)
Methods
getDefaultName
public String getDefaultName()
getDescription
public String getDescription()
getDisplayName
public String getDisplayName()
getId
public Long getId()
getSettings
public List<TypeSetting> getSettings()
getTypeClass
public Class<?> getTypeClass()
getTypeClassName
public String getTypeClassName()
getValidations
public List<TypeValidation> getValidations()
hasSettings
public boolean hasSettings()
hasValidation
public boolean hasValidation()
isBlob
public boolean isBlob()
isCombobox
public boolean isCombobox()
isRelationship
public boolean isRelationship()
parse
public Object parse(String str)
setDefaultName
public void setDefaultName(String defaultName)
setDescription
public void setDescription(String description)
setDisplayName
public void setDisplayName(String displayName)
setId
public void setId(Long id)
setSettings
public void setSettings(List<TypeSetting> settings)
setTypeClass
public void setTypeClass(Class<?> typeClass)
setValidations
public void setValidations(List<TypeValidation> validations)
toDto
public TypeDto toDto()

TypeSetting

public class TypeSetting

The TypeSetting contains settings for the given mds type. This class is related with table in database with the same name.

Constructors
TypeSetting
public TypeSetting()
TypeSetting
public TypeSetting(String name)
Methods
getDefaultValue
public String getDefaultValue()
getId
public Long getId()
getName
public String getName()
getTypeSettingOptions
public List<TypeSettingOption> getTypeSettingOptions()
getValueType
public Type getValueType()
setDefaultValue
public void setDefaultValue(String defaultValue)
setId
public void setId(Long id)
setName
public void setName(String name)
setTypeSettingOptions
public void setTypeSettingOptions(List<TypeSettingOption> typeSettingOptions)
setValueType
public void setValueType(Type valueType)

TypeSettingOption

public class TypeSettingOption

The TypeSettingOption contains a single setting option for the given type setting. This class is related with table in database with the same name.

Constructors
TypeSettingOption
public TypeSettingOption(String name)
Methods
getId
public Long getId()
getName
public String getName()
setId
public void setId(Long id)
setName
public void setName(String name)

TypeValidation

public class TypeValidation

The TypeValidation contains a single validation option for the given type. This class is related with table in database with the same name.

Constructors
TypeValidation
public TypeValidation()
TypeValidation
public TypeValidation(String displayName, Type valueType)
Methods
getAnnotations
public List<Class<? extends Annotation>> getAnnotations()
getDisplayName
public String getDisplayName()
getId
public Long getId()
getValueType
public Type getValueType()
setAnnotations
public void setAnnotations(List<Class<? extends Annotation>> annotations)
setDisplayName
public void setDisplayName(String displayName)
setId
public void setId(Long id)
setValueType
public void setValueType(Type valueType)
toString
public String toString()

org.motechproject.mds.dto

AdvancedSettingsDto

public class AdvancedSettingsDto

The AdvancedSettingsDto contains information about advanced settings of an entity.

Methods
addNewIndex
public void addNewIndex(String lookupName)
equals
public boolean equals(Object obj)

{@inheritDoc}

getBrowsing
public BrowsingSettingsDto getBrowsing()
getEntityId
public Long getEntityId()
getId
public Long getId()
getIndexes
public List<LookupDto> getIndexes()
getRestOptions
public RestOptionsDto getRestOptions()
getTracking
public TrackingDto getTracking()
hashCode
public int hashCode()

{@inheritDoc}

removeIndex
public void removeIndex(Integer idx)
setBrowsing
public void setBrowsing(BrowsingSettingsDto browsing)
setEntityId
public void setEntityId(Long entityId)
setId
public void setId(Long id)
setIndexes
public void setIndexes(List<LookupDto> indexes)
setRestOptions
public void setRestOptions(RestOptionsDto restOptions)
setTracking
public void setTracking(TrackingDto tracking)
toString
public String toString()

{@inheritDoc}

BrowsingSettingsDto

public class BrowsingSettingsDto

The BrowsingSettingsDto contains informations about filed browsing settings

Methods
addDisplayedField
public void addDisplayedField(Number id)
addFilterableField
public void addFilterableField(Number id)
containsDisplayedField
public boolean containsDisplayedField(Long number)
containsFilterableField
public boolean containsFilterableField(Number id)
equals
public boolean equals(Object obj)

{@inheritDoc}

getDisplayedFields
public List<Number> getDisplayedFields()
getFilterableFields
public List<Number> getFilterableFields()
hashCode
public int hashCode()

{@inheritDoc}

indexOfDisplayedField
public long indexOfDisplayedField(Long id)
removeFilterableField
public void removeFilterableField(Number id)
setDisplayedFields
public void setDisplayedFields(List<Number> displayedFields)
setFilterableFields
public void setFilterableFields(List<Number> filterableFields)
toString
public String toString()

{@inheritDoc}

DraftData

public class DraftData

The DraftData contains information that are used later for creating temporary changes in field.

Fields
ADD_NEW_INDEX
public static final String ADD_NEW_INDEX
ADVANCED
public static final String ADVANCED
DISPLAY_NAME
public static final String DISPLAY_NAME
FIELD
public static final String FIELD
FIELD_ID
public static final String FIELD_ID
NAME
public static final String NAME
PATH
public static final String PATH
REMOVE_INDEX
public static final String REMOVE_INDEX
SECURITY
public static final String SECURITY
TYPE_CLASS
public static final String TYPE_CLASS
VALUE
public static final String VALUE
Methods
getPath
public String getPath()
getValue
public Object getValue(String key)
getValues
public Map<String, Object> getValues()
isCreate
public boolean isCreate()
isEdit
public boolean isEdit()
isForAdvanced
public boolean isForAdvanced()
isForField
public boolean isForField()
isForSecurity
public boolean isForSecurity()
isRemove
public boolean isRemove()
setCreate
public void setCreate(boolean create)
setEdit
public void setEdit(boolean edit)
setRemove
public void setRemove(boolean remove)
setValues
public void setValues(Map<String, Object> values)

DraftResult

public class DraftResult implements Serializable

After users do draft changes an instance of this class is returned. It contains information about the draft state.

Constructors
DraftResult
public DraftResult(boolean changesMade, boolean outdated)
Methods
isChangesMade
public boolean isChangesMade()
isOutdated
public boolean isOutdated()
setChangesMade
public void setChangesMade(boolean changesMade)
setOutdated
public void setOutdated(boolean outdated)

EntityDto

public class EntityDto

The EntityDto class contains only basic information about an entity like id, name, module and namespace.

Constructors
EntityDto
public EntityDto()
EntityDto
public EntityDto(String className)
EntityDto
public EntityDto(Long id, String className)
EntityDto
public EntityDto(String className, SecurityMode securityMode, Set<String> securityMembers)
EntityDto
public EntityDto(Long id, String className, SecurityMode securityMode, Set<String> securityMembers)
EntityDto
public EntityDto(Long id, String className, String module, SecurityMode securityMode, Set<String> securityMembers)
EntityDto
public EntityDto(Long id, String className, String module, String namespace, SecurityMode securityMode, Set<String> securityMembers)
EntityDto
public EntityDto(String className, String name, String module, String namespace, SecurityMode securityMode, Set<String> securityMembers)
EntityDto
public EntityDto(Long id, String className, String name, String module, String namespace, SecurityMode securityMode, Set<String> securityMembers)
EntityDto
public EntityDto(Long id, String className, String name, String module, String namespace, SecurityMode securityMode, Set<String> securityMembers, String superClass)
EntityDto
public EntityDto(Long id, String className, String name, String module, String namespace, SecurityMode securityMode, Set<String> securityMembers, String superClass, boolean abstractClass)
Methods
equals
public boolean equals(Object obj)

{@inheritDoc}

getClassName
public String getClassName()
getId
public Long getId()
getModule
public String getModule()
getName
public String getName()
getNamespace
public String getNamespace()
getSecurityMembers
public Set<String> getSecurityMembers()
getSecurityMode
public SecurityMode getSecurityMode()
getSuperClass
public String getSuperClass()
hashCode
public int hashCode()

{@inheritDoc}

isAbstractClass
public boolean isAbstractClass()
isDDE
public boolean isDDE()
isModified
public boolean isModified()
isOutdated
public boolean isOutdated()
isReadOnly
public boolean isReadOnly()
setAbstractClass
public void setAbstractClass(boolean abstractClass)
setClassName
public void setClassName(String className)
setId
public void setId(Long id)
setModified
public void setModified(boolean modified)
setModule
public void setModule(String module)
setName
public void setName(String name)
setNamespace
public void setNamespace(String namespace)
setOutdated
public void setOutdated(boolean outdated)
setReadOnly
public void setReadOnly(boolean readOnly)
setSecurityMembers
public void setSecurityMembers(Set<String> securityMembers)
setSecurityMode
public void setSecurityMode(SecurityMode securityMode)
setSuperClass
public void setSuperClass(String superClass)
toString
public String toString()

{@inheritDoc}

FieldBasicDto

public class FieldBasicDto

The FieldBasicDto contains basic information about a field.

Constructors
FieldBasicDto
public FieldBasicDto()
FieldBasicDto
public FieldBasicDto(String displayName, String name)
FieldBasicDto
public FieldBasicDto(String displayName, String name, boolean required, Object defaultValue, String tooltip)
Methods
equals
public boolean equals(Object obj)

{@inheritDoc}

getDefaultValue
public Object getDefaultValue()
getDisplayName
public String getDisplayName()
getName
public String getName()
getTooltip
public String getTooltip()
hashCode
public int hashCode()

{@inheritDoc}

isRequired
public boolean isRequired()
setDefaultValue
public void setDefaultValue(Object defaultValue)
setDisplayName
public void setDisplayName(String displayName)
setName
public void setName(String name)
setRequired
public void setRequired(boolean required)
setTooltip
public void setTooltip(String tooltip)
toString
public String toString()

{@inheritDoc}

FieldDto

public class FieldDto

The FieldDto class contains information about an existing field in an entity.

Constructors
FieldDto
public FieldDto()
FieldDto
public FieldDto(Long id, Long entityId, TypeDto type, FieldBasicDto basic, boolean readOnly, List<MetadataDto> metadata, FieldValidationDto validation, List<SettingDto> settings, List<LookupDto> lookups)
FieldDto
public FieldDto(Long id, Long entityId, TypeDto type, FieldBasicDto basic, boolean readOnly, FieldValidationDto validation)
Methods
addEmptyMetadata
public void addEmptyMetadata()
addMetadata
public void addMetadata(MetadataDto metadata)
equals
public boolean equals(Object obj)

{@inheritDoc}

getBasic
public FieldBasicDto getBasic()
getEntityId
public Long getEntityId()
getId
public Long getId()
getLookups
public List<LookupDto> getLookups()
getMetadata
public List<MetadataDto> getMetadata()
getMetadata
public MetadataDto getMetadata(String key)
getSetting
public SettingDto getSetting(String name)
getSettings
public List<SettingDto> getSettings()
getType
public TypeDto getType()
getValidation
public FieldValidationDto getValidation()
hashCode
public int hashCode()

{@inheritDoc}

isReadOnly
public boolean isReadOnly()
removeMetadata
public void removeMetadata(Integer idx)
setBasic
public void setBasic(FieldBasicDto basic)
setEntityId
public void setEntityId(Long entityId)
setId
public void setId(Long id)
setLookups
public void setLookups(List<LookupDto> lookups)
setMetadata
public void setMetadata(List<MetadataDto> metadata)
setReadOnly
public void setReadOnly(boolean readOnly)
setSettings
public void setSettings(List<SettingDto> settings)
setType
public void setType(TypeDto type)
setValidation
public void setValidation(FieldValidationDto validation)
toString
public String toString()

{@inheritDoc}

FieldInstanceDto

public class FieldInstanceDto

The FieldInstanceDto class contains information about an existing field in an instance.

Constructors
FieldInstanceDto
public FieldInstanceDto()
FieldInstanceDto
public FieldInstanceDto(Long id, Long instanceId, FieldBasicDto basic)
Methods
equals
public boolean equals(Object obj)

{@inheritDoc}

getBasic
public FieldBasicDto getBasic()
getId
public Long getId()
getInstanceId
public Long getInstanceId()
hashCode
public int hashCode()

{@inheritDoc}

setBasic
public void setBasic(FieldBasicDto basic)
setId
public void setId(Long id)
setInstanceId
public void setInstanceId(Long instanceId)
toString
public String toString()

{@inheritDoc}

FieldValidationDto

public class FieldValidationDto

The FieldValidationDto class contains information about validation criteria for field.

Fields
DOUBLE
public static final FieldValidationDto DOUBLE

Constant DOUBLE contains validation criteria for double type.

INTEGER
public static final FieldValidationDto INTEGER

Constant INTEGER contains validation criteria for integer type.

STRING
public static final FieldValidationDto STRING

Constant STRING contains validation criteria for string type.

Constructors
FieldValidationDto
public FieldValidationDto()
FieldValidationDto
public FieldValidationDto(ValidationCriterionDto... criteria)
Methods
addCriterion
public void addCriterion(ValidationCriterionDto criterion)
equals
public boolean equals(Object obj)

{@inheritDoc}

getCriteria
public List<ValidationCriterionDto> getCriteria()
getCriterion
public ValidationCriterionDto getCriterion(String displayName)
hashCode
public int hashCode()

{@inheritDoc}

setCriteria
public void setCriteria(List<ValidationCriterionDto> criteria)
toString
public String toString()

{@inheritDoc}

LookupDto

public class LookupDto

The LookupDto class contains information about single lookup defined by user

Constructors
LookupDto
public LookupDto()
LookupDto
public LookupDto(String lookupName, boolean singleObjectReturn, boolean exposedViaRest)
LookupDto
public LookupDto(String lookupName, boolean singleObjectReturn, boolean exposedViaRest, List<LookupFieldDto> lookupFields, boolean readOnly)
LookupDto
public LookupDto(String lookupName, boolean singleObjectReturn, boolean exposedViaRest, List<LookupFieldDto> lookupFields, boolean readOnly, String methodName)
LookupDto
public LookupDto(Long id, String lookupName, boolean singleObjectReturn, boolean exposedViaRest, List<LookupFieldDto> lookupFields, boolean readOnly, String methodName)
Methods
addField
public void addField(Long field)
addField
public void addField(Integer field)
equals
public boolean equals(Object o)

{@inheritDoc}

getId
public Long getId()
getLookupFields
public final List<LookupFieldDto> getLookupFields()
getLookupName
public String getLookupName()
getMethodName
public String getMethodName()
hashCode
public int hashCode()

{@inheritDoc}

insertField
public void insertField(Integer idx, Integer fieldId)
insertField
public void insertField(Integer idx, Long fieldId)
isExposedViaRest
public boolean isExposedViaRest()
isReadOnly
public boolean isReadOnly()
isSingleObjectReturn
public boolean isSingleObjectReturn()
removeField
public void removeField(Long fieldId)
removeField
public void removeField(Integer fieldId)
setExposedViaRest
public void setExposedViaRest(boolean isExposedViaRest)
setId
public void setId(Long id)
setLookupFields
public void setLookupFields(List<LookupFieldDto> lookupFields)
setLookupName
public void setLookupName(String lookupName)
setMethodName
public void setMethodName(String methodName)
setReadOnly
public void setReadOnly(boolean readOnly)
setSingleObjectReturn
public void setSingleObjectReturn(boolean singleObjectReturn)
toString
public String toString()

{@inheritDoc}

LookupFieldDto

public class LookupFieldDto

Represents a field added to a lookup. The lookup using a given field can be done using multiple lookup types.

Constructors
LookupFieldDto
public LookupFieldDto()
LookupFieldDto
public LookupFieldDto(Long id, String name, Type type)
LookupFieldDto
public LookupFieldDto(Long id, String name, Type type, String customOperator)
LookupFieldDto
public LookupFieldDto(Long id, String name, Type type, String customOperator, boolean useGenericParam)
Methods
equals
public boolean equals(Object o)
getCustomOperator
public String getCustomOperator()
getId
public Long getId()
getName
public String getName()
getType
public Type getType()
hashCode
public int hashCode()
isUseGenericParam
public boolean isUseGenericParam()
setCustomOperator
public void setCustomOperator(String customOperator)
setId
public void setId(Long id)
setName
public void setName(String name)
setType
public void setType(Type type)
setUseGenericParam
public void setUseGenericParam(boolean useGenericParam)

LookupFieldDto.Type

public static enum Type

The lookup type represents whether the lookup will be done by comparing to a single field, matching values to a range, or matching to a set of values.

Enum Constants
RANGE
public static final LookupFieldDto.Type RANGE
SET
public static final LookupFieldDto.Type SET
VALUE
public static final LookupFieldDto.Type VALUE

MetadataDto

public class MetadataDto implements Pair<String, String>

The MetadataDto contains key and value of a single field metadata.

Constructors
MetadataDto
public MetadataDto()
MetadataDto
public MetadataDto(String key, String value)
MetadataDto
public MetadataDto(Long id, String key, String value)
Methods
equals
public boolean equals(Object obj)

{@inheritDoc}

getId
public Long getId()
getKey
public String getKey()
getValue
public String getValue()
hashCode
public int hashCode()

{@inheritDoc}

setId
public void setId(Long id)
setKey
public void setKey(String key)
setValue
public void setValue(String value)
toString
public String toString()

{@inheritDoc}

RestOptionsDto

public class RestOptionsDto

Class representing rest options of given entity.

Constructors
RestOptionsDto
public RestOptionsDto()
RestOptionsDto
public RestOptionsDto(boolean create, boolean read, boolean update, boolean delete)
Methods
addField
public void addField(Number id)
addLookup
public void addLookup(Number id)
containsFieldId
public boolean containsFieldId(Number id)
containsLookupId
public boolean containsLookupId(Number id)
equals
public boolean equals(Object obj)

{@inheritDoc}

getFieldIds
public List<Number> getFieldIds()
getId
public Long getId()
getLookupIds
public List<Number> getLookupIds()
hashCode
public int hashCode()

{@inheritDoc}

isCreate
public boolean isCreate()
isDelete
public boolean isDelete()
isRead
public boolean isRead()
isUpdate
public boolean isUpdate()
removeField
public void removeField(Number id)
removeLookup
public void removeLookup(Number id)
setCreate
public void setCreate(boolean create)
setDelete
public void setDelete(boolean delete)
setFieldIds
public void setFieldIds(List<Number> fieldIds)
setId
public void setId(Long id)
setLookupIds
public void setLookupIds(List<Number> lookupIds)
setRead
public void setRead(boolean read)
setUpdate
public void setUpdate(boolean update)
toString
public String toString()

{@inheritDoc}

SettingDto

public class SettingDto implements Pair<String, Object>

The SettingDto contains information about a single setting inside a field.

Constructors
SettingDto
public SettingDto()
SettingDto
public SettingDto(String name, Object value)
SettingDto
public SettingDto(String name, Object value, TypeDto type, SettingOptions... options)
Methods
copy
public SettingDto copy()
equals
public boolean equals(Object obj)

{@inheritDoc}

getKey
public String getKey()
getName
public String getName()
getOptions
public List<SettingOptions> getOptions()
getType
public TypeDto getType()
getValue
public Object getValue()
getValueAsString
public String getValueAsString()
hashCode
public int hashCode()

{@inheritDoc}

setName
public void setName(String name)
setOptions
public void setOptions(List<SettingOptions> options)
setType
public void setType(TypeDto type)
setValue
public void setValue(Object value)
toString
public String toString()

{@inheritDoc}

SettingOptions

public enum SettingOptions

The SettingOptions contains available options that can be added to field setting.

Enum Constants
POSITIVE
public static final SettingOptions POSITIVE

Ensure that a value in a given setting is a number and it has a positive value.

REQUIRE
public static final SettingOptions REQUIRE

Force setting a value for a given setting.

TrackingDto

public class TrackingDto

The TrackingDto contains information about which fields and what kind of actions should be logged.

Methods
addAction
public void addAction(String action)
addField
public void addField(Number fieldId)
equals
public boolean equals(Object obj)

{@inheritDoc}

getActions
public List<String> getActions()
getFields
public List<Long> getFields()
hashCode
public int hashCode()

{@inheritDoc}

isAllowCreate
public boolean isAllowCreate()
isAllowDelete
public boolean isAllowDelete()
isAllowRead
public boolean isAllowRead()
isAllowUpdate
public boolean isAllowUpdate()
removeAction
public void removeAction(String action)
removeField
public void removeField(Number fieldId)
setActions
public void setActions(List<String> actions)
setFields
public void setFields(List<Long> fields)
toString
public String toString()

{@inheritDoc}

TypeDto

public class TypeDto

The TypeDto class contains information about an available field in an entity.

Fields
BLOB
public static final TypeDto BLOB

Constant BLOB is a representation of the MDS BLOB type.

BOOLEAN
public static final TypeDto BOOLEAN

Constant BOOLEAN is a representation of the MDS Boolean type.

DATE
public static final TypeDto DATE

Constant DATE is a representation of the MDS Date type.

DATETIME
public static final TypeDto DATETIME

Constant DATETIME is a representation of the MDS DateTime type.

DOUBLE
public static final TypeDto DOUBLE

Constant DOUBLE is a representation of the MDS Decimal type.

INTEGER
public static final TypeDto INTEGER

Constant INTEGER is a representation of the MDS Integer type.

LIST
public static final TypeDto LIST

Constant LIST is a representation of the MDS Combobox type.

LOCAL_DATE
public static final TypeDto LOCAL_DATE

Constant LOCAL_DATE is a representation of the org.joda.time.LocalDate type.

LONG
public static final TypeDto LONG

Constant LONG is a representation of the MDS Long type.

MAP
public static final TypeDto MAP

Constant MAP is a representation of the MDS Map type.

PERIOD
public static final TypeDto PERIOD

Constant PERIOD is a representation of the MDS Period type.

STRING
public static final TypeDto STRING

Constant STRING is a representation of the MDS String type.

TIME
public static final TypeDto TIME

Constant TIME is a representation of the MDS Time type.

Constructors
TypeDto
public TypeDto()
TypeDto
public TypeDto(String displayName, String description, String defaultName, String typeClass)
TypeDto
public TypeDto(Long id, String displayName, String description, String defaultName, String typeClass)
Methods
equals
public boolean equals(Object obj)

{@inheritDoc}

getDefaultName
public String getDefaultName()
getDescription
public String getDescription()
getDisplayName
public String getDisplayName()
getId
public Long getId()
getTypeClass
public String getTypeClass()
hashCode
public int hashCode()

{@inheritDoc}

isCombobox
public boolean isCombobox()
isRelationship
public boolean isRelationship()
setDefaultName
public void setDefaultName(String defaultName)
setDescription
public void setDescription(String description)
setDisplayName
public void setDisplayName(String displayName)
setId
public void setId(Long id)
setTypeClass
public void setTypeClass(String typeClass)
toString
public String toString()

{@inheritDoc}

ValidationCriterionDto

public class ValidationCriterionDto

The ValidationCriterionDto contains information about single criterion for field validation.

Constructors
ValidationCriterionDto
public ValidationCriterionDto()
ValidationCriterionDto
public ValidationCriterionDto(String displayName, TypeDto type)
ValidationCriterionDto
public ValidationCriterionDto(String displayName, TypeDto type, Object value, boolean enabled)
Methods
equals
public boolean equals(Object obj)

{@inheritDoc}

getDisplayName
public String getDisplayName()
getType
public TypeDto getType()
getValue
public Object getValue()
hashCode
public int hashCode()

{@inheritDoc}

isEnabled
public boolean isEnabled()
setDisplayName
public void setDisplayName(String displayName)
setEnabled
public void setEnabled(boolean enabled)
setType
public void setType(TypeDto type)
setValue
public void setValue(Object value)
toString
public String toString()

{@inheritDoc}

valueAsString
public String valueAsString()

org.motechproject.mds.enhancer

MdsJDOEnhancer

public class MdsJDOEnhancer extends JDOEnhancer

The MdsJDOEnhancer class is a wrapper for org.datanucleus.api.jdo.JDOEnhancer class. Its task is to add the missing information into created entity class.

Constructors
MdsJDOEnhancer
public MdsJDOEnhancer(Properties config, ClassLoader classLoader)
Methods
addClass
public void addClass(ClassData classData)

org.motechproject.mds.ex

EmptyTrashException

public class EmptyTrashException extends MdsException

The EmptyTrashException exception signals a situation that there were some problems with cleaning the module trash.

Constructors
EmptyTrashException
public EmptyTrashException(Throwable cause)

Constructs a new EmptyTrashException with mds.error.emptyTrashException as a message key.

Parameters:
  • cause – the cause of exception.

EntityAlreadyExistException

public class EntityAlreadyExistException extends MdsException

The EntityAlreadyExistException exception signals a situation in which a user wants to create a new entity with a name that already exist in database.

Constructors
EntityAlreadyExistException
public EntityAlreadyExistException()

Constructs a new EntityAlreadyExistException with mds.error.entityAlreadyExist as a message key.

EntityChangedException

public class EntityChangedException extends MdsException

This exception signals that an Entity was changed(presumably by another user).

Constructors
EntityChangedException
public EntityChangedException()

EntityCreationException

public class EntityCreationException extends MdsException

The EntityCreationException exception signals a situation when there were problems with creating new entity class.

Constructors
EntityCreationException
public EntityCreationException(Throwable cause)

Constructs a new EntityCreationException with mds.error.entityBuilderFailure as a message key.

Parameters:
  • cause – the cause of exception.
EntityCreationException
public EntityCreationException(String messageKey)

EntityDeletedException

public class EntityDeletedException extends MdsException

This exception signals that the Entity was deleted(presumably by an another user).

Constructors
EntityDeletedException
public EntityDeletedException()

EntityInfrastructureException

public class EntityInfrastructureException extends MdsException

The EntityInfrastructureException exception signals a situation when there were problems with creating repository/service interface/service class for entity.

Constructors
EntityInfrastructureException
public EntityInfrastructureException(Throwable cause)

Constructs a new EntityInfrastructureException with mds.error.entityInfrastructureFailure as a message key.

Parameters:
  • cause – the cause of exception.

EntityNotFoundException

public class EntityNotFoundException extends MdsException

The EntityNotFoundException exception signals a situation in which an entity with a given id does not exist in database.

Constructors
EntityNotFoundException
public EntityNotFoundException()

Constructs a new EntityNotFoundException with mds.error.entityNotFound as a message key.

EntityReadOnlyException

public class EntityReadOnlyException extends MdsException

The EntityReadOnlyException exception signals a situation in which a user wants to make changes on an entity which is read only (it was created by a module).

Constructors
EntityReadOnlyException
public EntityReadOnlyException()

Constructs a new EntityReadOnlyException with mds.error.entityIsReadOnly as a message key.

EntitySchemaMismatchException

public class EntitySchemaMismatchException extends MdsException

The EntitySchemaMismatch exception signals a situation in which a user wants to revert their instance to a version on a different schema version.

Constructors
EntitySchemaMismatchException
public EntitySchemaMismatchException()

Constructs a new EntitySchemaMismatch with mds.error.entitySchemaMismatch as a message key.

FieldNotFoundException

public class FieldNotFoundException extends MdsException

This exception signals that a given field was not found for the Entity.

Constructors
FieldNotFoundException
public FieldNotFoundException()

FieldUsedInLookupException

public class FieldUsedInLookupException extends MdsException

Exception indicating that a field cannot be removed, since it is used in a lookup.

Constructors
FieldUsedInLookupException
public FieldUsedInLookupException(String fieldName, String lookupNames)

IllegalLookupException

public class IllegalLookupException extends RuntimeException

Signales that the user defined an illegal lookup.

Constructors
IllegalLookupException
public IllegalLookupException(String message)

LoaderException

public class LoaderException extends RuntimeException

The LoaderException exception signals situations in which there were problems with correct loading the given class or its dependencies.

Constructors
LoaderException
public LoaderException(Throwable cause)

LookupExecutionException

public class LookupExecutionException extends MdsException

Signals that we were not able to execute a lookup for a given entity.

Constructors
LookupExecutionException
public LookupExecutionException()
LookupExecutionException
public LookupExecutionException(Throwable cause)

LookupNameIsRepeatedException

public class LookupNameIsRepeatedException extends MdsException

The LookupNameIsRepeatedException exception signals a situation when are more than one lookups in the entity with the same name.

Constructors
LookupNameIsRepeatedException
public LookupNameIsRepeatedException()

LookupNotFoundException

public class LookupNotFoundException extends MdsException

The LookupNotFoundException exception signals a situation in which a lookup with given id does not exist in database.

Constructors
LookupNotFoundException
public LookupNotFoundException()

Constructs a new LookupNotFoundException with mds.error.lookupNotFound as a message key.

MdsException

public class MdsException extends RuntimeException

The MdsException exception is a basic class for all other exceptions defined in the mds module. It contains information about a message key which will be used on UI to present a message in appropriate language.

Constructors
MdsException
public MdsException(String messageKey)

Constructs a new mds exception with the specified message key.

Parameters:
  • messageKey – the message key used later to display message in appropriate language on UI.
MdsException
public MdsException(String messageKey, String params)

Constructs a new mds exception with the specified message key and params.

Parameters:
  • messageKey – the message key used later to display message in appropriate language on UI.
  • params – the params used later to change placeholders in the message
MdsException
public MdsException(String messageKey, String... params)

Constructs a new mds exception with the specified message key and params.

Parameters:
  • messageKey – the message key used later to display message in appropriate language on UI.
  • params – the params used later to change placeholders in the message
MdsException
public MdsException(String messageKey, Throwable cause)

Constructs a new mds exception with the specified message key and the specified cause.

Parameters:
  • messageKey – the message key used later to display message in appropriate language on UI.
  • cause – the cause of exception.
MdsException
public MdsException(String messageKey, String params, Throwable cause)

Constructs a new mds exception with the specified message key and the specified cause.

Parameters:
  • messageKey – the message key used later to display message in appropriate language on UI.
  • params – the params used later to change placeholders in the message
  • cause – the cause of exception.
Methods
getMessageKey
public String getMessageKey()
getParams
public String getParams()

MdsSchedulerException

public class MdsSchedulerException extends RuntimeException

The MdsSchedulerException exception signals problems with scheduling MDS jobs

Constructors
MdsSchedulerException
public MdsSchedulerException(String message, Throwable cause)

NoSuchTypeException

public class NoSuchTypeException extends MdsException

An exception which signals that a given type does not exist in the database.

Constructors
NoSuchTypeException
public NoSuchTypeException()

Constructs a new NoSuchTypeException with mds.error.noSuchType as a message key.

ObjectNotFoundException

public class ObjectNotFoundException extends MdsException

Signals that the expected object was not found in the database.

Constructors
ObjectNotFoundException
public ObjectNotFoundException()

ObjectReadException

public class ObjectReadException extends MdsException

Signals that we were unable to we are unable to parse the object coming from the database.

Constructors
ObjectReadException
public ObjectReadException()
ObjectReadException
public ObjectReadException(Throwable cause)

ObjectUpdateException

public class ObjectUpdateException extends MdsException

Signals that we were unable to update object instance from the provided data.

Constructors
ObjectUpdateException
public ObjectUpdateException()
ObjectUpdateException
public ObjectUpdateException(Throwable cause)

ReservedKeywordException

public class ReservedKeywordException extends MdsException

Signals that field/lookup name is invalid because it is a java keyword.

Constructors
ReservedKeywordException
public ReservedKeywordException(String keyword)

SecurityException

public class SecurityException extends MdsException

The SecurityException exception signals a situation in which user wants to perform an operation on objects, they don’t have access to.

Constructors
SecurityException
public SecurityException()

Constructs a new SecurityException with mds.error.securityError as a message key.

ServiceNotFoundException

public class ServiceNotFoundException extends MdsException

Signals that service for a corresponding entity was not found. This most likely signals an issue with entities bundle.

Constructors
ServiceNotFoundException
public ServiceNotFoundException()

TrashClassNotFoundException

public class TrashClassNotFoundException extends MdsException

An Exception thrown when MDS fails to load trash class for an entity

Constructors
TrashClassNotFoundException
public TrashClassNotFoundException(String className)

TypeAlreadyExistsException

public class TypeAlreadyExistsException extends MdsException

The TypeAlreadyExistsException is thrown, if the user attempts to add a field type, with a display name that already exists in the database

Constructors
TypeAlreadyExistsException
public TypeAlreadyExistsException()

TypeNotFoundException

public class TypeNotFoundException extends RuntimeException

The TypeNotFoundException exception signals a situation in which a type with given name does not exist in database.

Constructors
TypeNotFoundException
public TypeNotFoundException(String msg)

TypeValidationAlreadyExistsException

public class TypeValidationAlreadyExistsException extends MdsException

The TypeValidationAlreadyExistsException is thrown, if the user attempts to add a type validation when there is already validation for given type

Constructors
TypeValidationAlreadyExistsException
public TypeValidationAlreadyExistsException()

org.motechproject.mds.filter

Filter

public class Filter implements Serializable

Represents a filter on a field.

Constructors
Filter
public Filter()
Filter
public Filter(String field, FilterType type)
Methods
filterForQuery
public String filterForQuery()
getField
public String getField()
getType
public FilterType getType()
paramsDeclarationForQuery
public String paramsDeclarationForQuery()
requiresFiltering
public boolean requiresFiltering()
setField
public void setField(String field)
setType
public void setType(FilterType type)
valuesForQuery
public Object[] valuesForQuery()

FilterType

public enum FilterType

Represents a method of filtering.

Enum Constants
ALL
public static final FilterType ALL
NO
public static final FilterType NO
PAST_7_DAYS
public static final FilterType PAST_7_DAYS
THIS_MONTH
public static final FilterType THIS_MONTH
THIS_YEAR
public static final FilterType THIS_YEAR
TODAY
public static final FilterType TODAY
YES
public static final FilterType YES

org.motechproject.mds.javassist

JavassistBuilder

public final class JavassistBuilder

Builder class for javassist related tasks. Helps with building appropriate elements of class e.g. fields, getters, field initializer

Methods
createEnumInitializer
public static CtField.Initializer createEnumInitializer(String enumType, String defaultValue)
createField
public static CtField createField(CtClass declaring, CtClass type, String name, String genericSignature)
createGetter
public static CtMethod createGetter(String fieldName, CtClass declaring, CtField field)
createInitializer
public static CtField.Initializer createInitializer(String typeClass, String defaultValueAsString)
createListInitializer
public static CtField.Initializer createListInitializer(String genericType, Object defaultValue)
createLocaleInitializer
public static CtField.Initializer createLocaleInitializer(String defaultValue)
createSetter
public static CtMethod createSetter(String fieldName, CtField field)
createSimpleInitializer
public static CtField.Initializer createSimpleInitializer(String type, Object defaultValue)
createSimpleInitializer
public static CtField.Initializer createSimpleInitializer(String type, String defaultValue)
getGetterName
public static String getGetterName(String fieldName, CtClass declaring, CtField field)
getSetterName
public static String getSetterName(String fieldName)

JavassistHelper

public final class JavassistHelper

Helper class for javassist related tasks. Helps with generic signature generation, plus methods related with analyzing and loading javassist class representations.

Methods
containsDeclaredField
public static boolean containsDeclaredField(CtClass ctClass, String fieldName)
containsDeclaredMethod
public static boolean containsDeclaredMethod(CtClass ctClass, String methodName)
containsField
public static boolean containsField(CtClass ctClass, String fieldName)
containsMethod
public static boolean containsMethod(CtClass ctClass, String methodName)
findDeclaredField
public static CtField findDeclaredField(CtClass ctClass, String fieldName)
findDeclaredMethod
public static CtMethod findDeclaredMethod(CtClass ctClass, String methodName)
findField
public static CtField findField(CtClass ctClass, String fieldName)
findMethod
public static CtMethod findMethod(CtClass ctClass, String methodName)
genericSignature
public static String genericSignature(Class<?> typeClass, Class<?> genericParam)
genericSignature
public static String genericSignature(Class<?> typeClass, String genericParam)
genericSignature
public static String genericSignature(String typeClass, String genericParam)
hasInterface
public static boolean hasInterface(CtClass ctClass, CtClass ctInterface)
inheritsFromCustomClass
public static boolean inheritsFromCustomClass(Class<?> clazz)
loadClass
public static CtClass loadClass(Bundle bundle, String className, ClassPool classPool)
removeDeclaredFieldIfExists
public static void removeDeclaredFieldIfExists(CtClass ctClass, String fieldName)
removeDeclaredMethodIfExists
public static void removeDeclaredMethodIfExists(CtClass ctClass, String methodName)
removeFieldIfExists
public static void removeFieldIfExists(CtClass ctClass, String fieldName)
removeMethodIfExists
public static void removeMethodIfExists(CtClass ctClass, String methodName)
toClassPath
public static String toClassPath(Class<?> clazz)
toClassPath
public static String toClassPath(String clazz)
toClassPath
public static String toClassPath(String clazz, boolean extension)
toGenericParam
public static String toGenericParam(Class<?> clazz)
toGenericParam
public static String toGenericParam(String clazz)

JavassistLoader

public class JavassistLoader extends Loader<ClassData>

The JavassistLoader is a implementation of the org.motechproject.mds.util.Loader interface. It takes class information from instance of org.motechproject.mds.domain.ClassData and the missing classes are taken from org.motechproject.mds.javassist.MotechClassPool

See also: org.motechproject.mds.util.Loader, org.motechproject.mds.domain.ClassData, org.motechproject.mds.javassist.MotechClassPool

Constructors
JavassistLoader
public JavassistLoader(MDSClassLoader classLoader)
Methods
doWhenClassNotFound
public void doWhenClassNotFound(String name)
getClassDefinition
public Class<?> getClassDefinition(ClassData data)
loadClass
public Class<?> loadClass(ClassData arg)

MotechClassPool

public final class MotechClassPool

This class holds the javasisst classpool, enriched by motech classes. All predefined additions to the ClassPool should take place here. The classpool should also be retrieved using this class, in order to be sure that the a initialization took place.

Methods
clearEnhancedData
public static void clearEnhancedData()
getDefault
public static ClassPool getDefault()
getEnhancedClassData
public static ClassData getEnhancedClassData(String className)
getEnhancedClasses
public static Collection<ClassData> getEnhancedClasses(boolean includeInerfaces)
getHistoryClassData
public static ClassData getHistoryClassData(String className)
getInterfaceName
public static String getInterfaceName(String className)
getRepositoryName
public static String getRepositoryName(String className)
getServiceImplName
public static String getServiceImplName(String className)
getServiceInterface
public static String getServiceInterface(String className)
getTrashClassData
public static ClassData getTrashClassData(String className)
isDDEReady
public static boolean isDDEReady(String className)
isServiceInterfaceRegistered
public static boolean isServiceInterfaceRegistered(String className)
registerDDE
public static void registerDDE(String className)
registerEnhancedClassData
public static void registerEnhancedClassData(ClassData enhancedClassData)
registerEnum
public static void registerEnum(String enumName)
registerHistoryClassData
public static void registerHistoryClassData(ClassData cData)
registerServiceInterface
public static void registerServiceInterface(String className, String interfaceName)
registerTrashClassData
public static void registerTrashClassData(ClassData cData)
registeredEnums
public static Collection<String> registeredEnums()
registeredInterfaces
public static Collection<String> registeredInterfaces()
unregisterEnhancedData
public static void unregisterEnhancedData(String className)

org.motechproject.mds.jdo

AbstractObjectValueGenerator

public abstract class AbstractObjectValueGenerator<T> implements ObjectValueGenerator

Base class for other generator classes. It takes value of property (see getPropertName() method) from object and modify it depending on the implementation. If the modified value is null then the java.lang.IllegalStateException is thrown.

Parameters:
  • <T> – type of property
Methods
generate
public Object generate(ExecutionContext ec, Object obj, ExtensionMetaData[] extensions)
getPropertName
protected abstract String getPropertName()
modify
protected abstract T modify(T value)

Modifies the given value. This method cannot return null value.

Parameters:
  • value – the given value related with property.
Returns:

modified value.

CreationDateValueGenerator

public class CreationDateValueGenerator extends DateTimeValueGenerator

The CreationDateValueGenerator class is responsible for generating value for org.motechproject.mds.util.Constants.Util.CREATION_DATE_FIELD_NAME field.

Methods
getPropertName
protected String getPropertName()

CreatorValueGenerator

public class CreatorValueGenerator extends UsernameValueGenerator

The CreatorValueGenerator class is responsible for generating value for org.motechproject.mds.util.Constants.Util.CREATOR_FIELD_NAME field.

Methods
getPropertName
protected String getPropertName()

DateTimeValueGenerator

public abstract class DateTimeValueGenerator extends AbstractObjectValueGenerator<DateTime>

The DateTimeValueGenerator class modifies properties with org.joda.time.DateTime type. If the given value is null then the current time is returned; otherwise the given value is returned.

Methods
modify
protected DateTime modify(DateTime value)

MDSClassLoaderResolver

public class MDSClassLoaderResolver implements ClassLoaderResolver

This is a wrapper for org.motechproject.mds.jdo.MDSClassLoaderResolverImpl. All calls for the org.datanucleus.ClassLoaderResolver interface are passed to the current instance of the ClassLoaderResolver implementation. When we hit a NullPointerException originating in Felix, we can determine it is due to a synchronization bug after bundle updates - as a result of this DataNucleus has passed us ClassLoaders from the former Bundle version. In that case we reload the instance passing it the ClassLoaders from the new bundle.

Constructors
MDSClassLoaderResolver
public MDSClassLoaderResolver()
MDSClassLoaderResolver
public MDSClassLoaderResolver(ClassLoader pmLoader)
Methods
classForName
public Class classForName(String name, ClassLoader primary)
classForName
public Class classForName(String name, ClassLoader primary, boolean initialize)
classForName
public Class classForName(String name)
classForName
public Class classForName(String name, boolean initialize)
getResource
public URL getResource(String resourceName, ClassLoader primary)
getResources
public Enumeration<URL> getResources(String resourceName, ClassLoader primary)
isAssignableFrom
public boolean isAssignableFrom(String className, Class clazz)
isAssignableFrom
public boolean isAssignableFrom(Class clazz, String className)
isAssignableFrom
public boolean isAssignableFrom(String className1, String className2)
registerUserClassLoader
public void registerUserClassLoader(ClassLoader loader)
setPrimary
public void setPrimary(ClassLoader primary)
setRuntimeClassLoader
public void setRuntimeClassLoader(ClassLoader loader)
unsetPrimary
public void unsetPrimary()

MDSClassLoaderResolverImpl

class MDSClassLoaderResolverImpl extends ClassLoaderResolverImpl

The main purpose of the MDSClassLoaderResolverImpl class is to avoid situation in which standard datanucleus class loader resolver does not see classes that are saved in database. This is the main implementation that extends the standard ClassLoaderResolverImpl from datanucleus. Due to a synchronization bug in Felix, there are cases when we will instantiate this more then once (after we hit the bug).

Constructors
MDSClassLoaderResolverImpl
public MDSClassLoaderResolverImpl()
MDSClassLoaderResolverImpl
public MDSClassLoaderResolverImpl(ClassLoader pmLoader)
Methods
classForName
public Class classForName(String name, ClassLoader primary)

MdsJdoAnnotationReader

public class MdsJdoAnnotationReader extends JDOAnnotationReader

MDS JDO annotation reader, extends the regular org.datanucleus.api.jdo.metadata.JDOAnnotationReader This class was introduced because org.datanucleus.api.jdo.metadata.JDOAnnotationReader would not read field annotations for metadata if there was no class level JDO annotations. This extension will recognize the org.motechproject.mds.annotations.Entity annotation as an annotation indicating that the class is persistence capable.

Constructors
MdsJdoAnnotationReader
public MdsJdoAnnotationReader(MetaDataManager mgr)
Methods
isClassPersistenceCapable
protected AnnotationObject isClassPersistenceCapable(Class cls)

MdsTransactionManager

public class MdsTransactionManager extends JdoTransactionManager

We override springs transaction for classloader control. We store context classloaders as thread local variables, and switch them with the MDS classloader for the transaction. Since we only allow operations in transactions, this entry point for classloader switching is enough.

Methods
doBegin
protected void doBegin(Object transaction, TransactionDefinition definition)
doCleanupAfterCompletion
protected void doCleanupAfterCompletion(Object transaction)

ModificationDateValueGenerator

public class ModificationDateValueGenerator extends DateTimeValueGenerator

The ModificationDateValueGenerator class is responsible for generating value for org.motechproject.mds.util.Constants.Util.MODIFICATION_DATE_FIELD_NAME field.

Methods
getPropertName
protected String getPropertName()

ModifiedByValueGenerator

public class ModifiedByValueGenerator extends UsernameValueGenerator

The ModifiedByValueGenerator class is responsible for generating value for org.motechproject.mds.util.Constants.Util.MODIFIED_BY_FIELD_NAME field.

Methods
getPropertName
protected String getPropertName()

OwnerValueGenerator

public class OwnerValueGenerator extends UsernameValueGenerator

The OwnerValueGenerator class is responsible for generating value for org.motechproject.mds.util.Constants.Util.OWNER_FIELD_NAME field.

Methods
getPropertName
protected String getPropertName()

SchemaGenerator

public class SchemaGenerator implements InitializingBean

The schema generator class is responsible for generating the table schema for entities upon start. Schema for all entity classes has to be generated, otherwise issues might arise in foreign key generation for example. This code runs in the generated entities bundle.

Constructors
SchemaGenerator
public SchemaGenerator(JDOPersistenceManagerFactory persistenceManagerFactory)
Methods
afterPropertiesSet
public void afterPropertiesSet()
generateSchema
public void generateSchema()

TimeTypeConverter

public class TimeTypeConverter implements TypeConverter<Time, String>

This is datanucleus type converter we plug in. It is responsible for converting org.motechproject.commons.date.model.Time instances to Strings which are persisted.

Methods
toDatastoreType
public String toDatastoreType(Time memberValue)
toMemberType
public Time toMemberType(String datastoreValue)

UsernameValueGenerator

public abstract class UsernameValueGenerator extends AbstractObjectValueGenerator<String>

The UsernameValueGenerator class modifies properties with java.lang.String type. The given value is returned without any change if it is not blank. Otherise the class tries to get current logged user name. If the user exists and name is not blank then this name is returned otherwise the empty string is returned.

Methods
modify
protected String modify(String value)

org.motechproject.mds.query

CollectionProperty

public class CollectionProperty extends Property<Collection>

The CollectionProperty class represent a property that will be used in JDO query and it has to have the given value(s).

Constructors
CollectionProperty
public CollectionProperty(String name, Object value)
Methods
generateDeclareParameter
public CharSequence generateDeclareParameter(int idx)
generateFilter
public CharSequence generateFilter(int idx)
shouldIgnoreThisProperty
protected boolean shouldIgnoreThisProperty()
unwrap
public Collection unwrap()

CustomOperatorProperty

public class CustomOperatorProperty<T> extends Property<T>

The CustomOperatorProperty class represents a property that will be used in JDO query. This class allows inserting a custom operator, such as >, <=, matches(), etc.

Parameters:
  • <T> – type of the passed value
Constructors
CustomOperatorProperty
public CustomOperatorProperty(String name, T value, String operator)
Methods
generateFilter
public CharSequence generateFilter(int idx)
getOperator
public String getOperator()
isOperatorAMethod
public boolean isOperatorAMethod()

EqualProperty

public class EqualProperty<T> extends Property<T>

The EqualProperty class represents a property that will be used in JDO query and it has to be equal to the given value.

Parameters:
  • <T> – type of the passed value
Constructors
EqualProperty
public EqualProperty(String name, T value)
Methods
generateFilter
public CharSequence generateFilter(int idx)

MatchesProperty

public class MatchesProperty extends CustomOperatorProperty<String>

A convenience extension of the org.motechproject.mds.query.CustomOperatorProperty. The custom operator is “matches()” and the underlying type is String. The value passed will be wrapped inside .*.* for matching purposes.

Constructors
MatchesProperty
public MatchesProperty(String name, String value)

Property

public abstract class Property<T>

The Property class represents a property that will be used in JDO query. Classes that extend this class should define how that property should be used in WHERE section in JDO query.

Parameters:
  • <T> – type of the passed value
Constructors
Property
protected Property(String name, T value)
Methods
asDeclareParameter
public CharSequence asDeclareParameter(int idx)
asFilter
public CharSequence asFilter(int idx)
containsOnlyNullValues
protected boolean containsOnlyNullValues(Collection collection)
generateDeclareParameter
protected CharSequence generateDeclareParameter(int idx)
generateFilter
protected abstract CharSequence generateFilter(int idx)
getName
public String getName()
getValue
public T getValue()
shouldIgnoreThisProperty
protected boolean shouldIgnoreThisProperty()
unwrap
public Collection unwrap()

PropertyBuilder

public final class PropertyBuilder

The PropertyBuilder class is a util class that helps create appropriate property class based on passed name and value.

Methods
create
public static Property create(Field field, Object value)
create
public static Property create(String name, Object value)
create
public static Property create(String name, Object value, String operator)

QueryExecution

public interface QueryExecution<T>

Allows users to execute custom queries through Motech Data Services. Implementations need only to implement the execute method, which can operate directly on the javax.jdo.Query object. The return value type is left to the implementation.

Parameters:
  • <T> – the type that will be returned from this query
Methods
execute
T execute(Query query, InstanceSecurityRestriction restriction)

QueryExecutor

public final class QueryExecutor

The QueryExecutor util class provides methods that help execute a JDO query.

Methods
execute
public static Object execute(Query query, InstanceSecurityRestriction restriction)
execute
public static Object execute(Query query, Object value, InstanceSecurityRestriction restriction)
executeWithArray
public static Object executeWithArray(Query query, Object[] values, InstanceSecurityRestriction restriction)
executeWithArray
public static Object executeWithArray(Query query, List<Property> properties)
executeWithFilter
public static Object executeWithFilter(Query query, Filter filter, InstanceSecurityRestriction restriction)

QueryParams

public class QueryParams implements Serializable

Utility class containing parameters which control order and size of query results. Used mainly for paging/ordering queries from the UI.

Constructors
QueryParams
public QueryParams(Integer page, Integer pageSize)
QueryParams
public QueryParams(Order order)
QueryParams
public QueryParams(Integer page, Integer pageSize, Order order)
Methods
ascOrder
public static QueryParams ascOrder(String field)
descOrder
public static QueryParams descOrder(String field)
getOrder
public Order getOrder()
getPage
public Integer getPage()
getPageSize
public Integer getPageSize()
isOrderSet
public boolean isOrderSet()
isPagingSet
public boolean isPagingSet()

QueryUtil

public final class QueryUtil

The QueryUtil util class provides methods that help developer to create a JDO query.

See also: javax.jdo.Query

Methods
asMatchesPattern
public static String asMatchesPattern(String string)

Returns the string in a form a pattern used for searching with the matches operator.

Parameters:
  • string – The string to search for.
Returns:

The string in format .*<string>.* or the string unchanged if it is empty.

setCountResult
public static void setCountResult(Query query)
setQueryParams
public static void setQueryParams(Query query, QueryParams queryParams)
useFilter
public static void useFilter(Query query, Filter filter)
useFilter
public static void useFilter(Query query, String[] properties, Object[] values)
useFilter
public static void useFilter(Query query, String[] properties, Object[] values, InstanceSecurityRestriction restriction)
useFilter
public static void useFilter(Query query, List<Property> properties)
useFilter
public static void useFilter(Query query, List<Property> properties, InstanceSecurityRestriction restriction)
useFilterFromPattern
public static void useFilterFromPattern(Query query, String pattern, List<Property> properties)

RangeProperty

public class RangeProperty<T> extends Property<Range<T>>

The RangeProperty class represents a property that will be used in JDO query and it has to be inside the given range.

Parameters:
  • <T> – type used in range.
Constructors
RangeProperty
public RangeProperty(String name, Range<T> value)
Methods
generateDeclareParameter
public CharSequence generateDeclareParameter(int idx)
generateFilter
public CharSequence generateFilter(int idx)
shouldIgnoreThisProperty
protected boolean shouldIgnoreThisProperty()
unwrap
public Collection unwrap()

RestrictionProperty

public class RestrictionProperty extends EqualProperty<String>

The RestrictionProperty class represents a property that will be used in JDO query and depends on restriction criteria the creator or owner field in an instance has to have the appropriate user name.

Constructors
RestrictionProperty
public RestrictionProperty(InstanceSecurityRestriction restriction, String value)

SetProperty

public class SetProperty<T> extends Property<Set<T>>

The SetProperty class represents a property that will be used in JDO query and it has to have one of the value from the given set.

Parameters:
  • <T> – type used in set.
Constructors
SetProperty
public SetProperty(String name, Set<T> value)
Methods
generateDeclareParameter
public CharSequence generateDeclareParameter(int idx)
generateFilter
public CharSequence generateFilter(int idx)
shouldIgnoreThisProperty
protected boolean shouldIgnoreThisProperty()
unwrap
public Collection unwrap()

org.motechproject.mds.repository

AllConfigSettings

public class AllConfigSettings extends MotechDataRepository<ConfigSettings>

AllConfigSettings is responsible for communication with database for MDS configuration.

Constructors
AllConfigSettings
public AllConfigSettings()
Methods
addOrUpdate
public void addOrUpdate(ConfigSettings record)

AllEntities

public class AllEntities extends MotechDataRepository<Entity>

The AllEntities class is a repository class that operates on instances of org.motechproject.mds.domain.Entity.

Constructors
AllEntities
public AllEntities()
Methods
contains
public boolean contains(String className)
create
public Entity create(EntityDto dto)
delete
public void delete(Long id)
retrieveByClassName
public Entity retrieveByClassName(String className)
retrieveById
public Entity retrieveById(Long id)

AllEntityAudits

public class AllEntityAudits extends MotechDataRepository<EntityAudit>

This a repository for persisting entity audits. It provides methods which created audits, by cloning the giving entity.

Constructors
AllEntityAudits
public AllEntityAudits()
Methods
createAudit
public EntityAudit createAudit(Entity entity, String username)

AllEntityDrafts

public class AllEntityDrafts extends MotechDataRepository<EntityDraft>

This a repository for persisting entity drafts. It provides methods which created drafts, by cloning the giving entity.

Constructors
AllEntityDrafts
public AllEntityDrafts()
Methods
create
public EntityDraft create(Entity entity, String username)
deleteAll
public void deleteAll(Entity entity)
retrieve
public EntityDraft retrieve(Entity entity, String username)
retrieveAll
public List<EntityDraft> retrieveAll(String username)
retrieveAll
public List<EntityDraft> retrieveAll(Entity entity)
setProperties
public void setProperties(EntityDraft draft, Entity entity)
setProperties
public void setProperties(EntityDraft draft, Entity entity, String username)
update
public EntityDraft update(EntityDraft draft)

AllTypeSettings

public class AllTypeSettings extends MotechDataRepository<TypeSetting>

The AllTypeSettings class is a repository class that operates on instances of org.motechproject.mds.domain.TypeSetting.

Constructors
AllTypeSettings
public AllTypeSettings()

AllTypeValidations

public class AllTypeValidations extends MotechDataRepository<TypeValidation>

The AllTypeValidations class is a repository class that operates on instances of org.motechproject.mds.domain.TypeValidation.

Constructors
AllTypeValidations
public AllTypeValidations()

AllTypes

public class AllTypes extends MotechDataRepository<Type>

The AllTypes repository class allows persistence and retrieving of Field Types in Data Services database.

Constructors
AllTypes
public AllTypes()
Methods
retrieveByClassName
public Type retrieveByClassName(String className)

MetadataHolder

public class MetadataHolder

Holds the current JDO metadata for Seuss. Allows reloading the metadata and retrieval for modifications.

Methods
addProcessedRelation
public void addProcessedRelation(String className)
getJdoMetadata
public JDOMetadata getJdoMetadata()
isRelationProcessed
public boolean isRelationProcessed(String className)
reloadMetadata
public JDOMetadata reloadMetadata()
setPersistenceManagerFactory
public void setPersistenceManagerFactory(PersistenceManagerFactory persistenceManagerFactory)

MotechDataRepository

public abstract class MotechDataRepository<T>

This is a basic repository class with standard CRUD operations. It should be used by other repositories inside this package.

This class is also used as super class to create a repository related with the given entity schema in org.motechproject.mds.builder.EntityInfrastructureBuilder.

Parameters:
  • <T> – the type of class
Constructors
MotechDataRepository
protected MotechDataRepository(Class<T> classType)
Methods
count
public long count(InstanceSecurityRestriction restriction)
count
public long count(String[] properties, Object[] values, InstanceSecurityRestriction restriction)
count
public long count(List<Property> properties, InstanceSecurityRestriction restriction)
countForFilter
public long countForFilter(Filter filter)
countForFilter
public long countForFilter(Filter filter, InstanceSecurityRestriction restriction)
create
public T create(T object)
delete
public void delete(T object)
delete
public void delete(String property, Object value, InstanceSecurityRestriction restriction)
delete
public void delete(String[] properties, Object[] values, InstanceSecurityRestriction restriction)
deleteAll
public void deleteAll(String property, Object value)
deleteAll
public void deleteAll(String property, Object value, InstanceSecurityRestriction restriction)
deleteAll
public void deleteAll(String[] properties, Object[] values, InstanceSecurityRestriction restriction)
exists
public boolean exists(String property, Object value)
exists
public boolean exists(String[] properties, Object[] values)
filter
public List<T> filter(Filter filter, QueryParams queryParams)
filter
public List<T> filter(Filter filter, QueryParams queryParams, InstanceSecurityRestriction restriction)
getClassType
public Class<T> getClassType()
getDetachedField
public Object getDetachedField(T instance, String field)
getPersistenceManager
public PersistenceManager getPersistenceManager()
retrieve
public T retrieve(Object key)
retrieve
public T retrieve(String property, Object value)
retrieve
public T retrieve(String property, Object value, InstanceSecurityRestriction restriction)
retrieve
public T retrieve(String[] properties, Object[] values)
retrieve
public T retrieve(String[] properties, Object[] values, InstanceSecurityRestriction restriction)
retrieveAll
public List<T> retrieveAll()
retrieveAll
public List<T> retrieveAll(InstanceSecurityRestriction restriction)
retrieveAll
public List<T> retrieveAll(String property, Object value)
retrieveAll
public List<T> retrieveAll(String property, Object value, InstanceSecurityRestriction restriction)
retrieveAll
public List<T> retrieveAll(String[] properties, Object[] values, InstanceSecurityRestriction restriction)
retrieveAll
public List<T> retrieveAll(String[] properties, Object[] values, QueryParams queryParams, InstanceSecurityRestriction restriction)
retrieveAll
public List<T> retrieveAll(QueryParams queryParams, InstanceSecurityRestriction restriction)
retrieveAll
public List<T> retrieveAll(List<Property> properties, InstanceSecurityRestriction restriction)
retrieveAll
public List<T> retrieveAll(List<Property> properties, QueryParams queryParams, InstanceSecurityRestriction restriction)
setPersistenceManagerFactory
public void setPersistenceManagerFactory(PersistenceManagerFactory persistenceManagerFactory)
update
public T update(T object)

org.motechproject.mds.service

DefaultMotechDataService

public abstract class DefaultMotechDataService<T> implements MotechDataService<T>

This is a basic implementation of org.motechproject.mds.service.MotechDataService. Mainly it is used as super class to create a service related with the given entity schema in org.motechproject.mds.builder.EntityInfrastructureBuilder but it can be also used by other services inside this package.

Parameters:
  • <T> – the type of entity schema.
Methods
count
public long count()
count
protected long count(List<Property> properties)
countForFilter
public long countForFilter(Filter filter)
create
public T create(T object)
delete
public void delete(T object)
delete
public void delete(String primaryKeyName, Object value)
deleteAll
public void deleteAll()
doInTransaction
public <R> R doInTransaction(TransactionCallback<R> transactionCallback)
executeQuery
public <R> R executeQuery(QueryExecution<R> queryExecution)
filter
public List<T> filter(Filter filter)
filter
public List<T> filter(Filter filter, QueryParams queryParams)
findById
public T findById(Long id)
findTrashInstanceById
public T findTrashInstanceById(Object instanceId, Object entityId)
getDetachedField
public Object getDetachedField(T instance, String fieldName)
getId
protected Object getId(T instance)
getRepository
protected MotechDataRepository<T> getRepository()
initializeSecurityState
public void initializeSecurityState()
retrieve
public T retrieve(String primaryKeyName, Object value)
retrieveAll
public List<T> retrieveAll()
retrieveAll
public List<T> retrieveAll(QueryParams queryParams)
retrieveAll
protected List<T> retrieveAll(List<Property> properties)
retrieveAll
protected List<T> retrieveAll(List<Property> properties, QueryParams queryParams)
revertFromTrash
public void revertFromTrash(Object newInstance, Object trash)
setAllEntities
public void setAllEntities(AllEntities allEntities)
setEntityService
public void setEntityService(EntityService entityService)
setHistoryService
public void setHistoryService(HistoryService historyService)
setRepository
public void setRepository(MotechDataRepository<T> repository)
setTransactionManager
public void setTransactionManager(JdoTransactionManager transactionManager)
setTrashService
public void setTrashService(TrashService trashService)
update
public T update(T object)
validateCredentials
protected InstanceSecurityRestriction validateCredentials()
validateCredentials
protected InstanceSecurityRestriction validateCredentials(T instance)

EntityService

public interface EntityService

This interface provides methods related with executing actions on an entity.

Methods
abandonChanges
void abandonChanges(Long entityId)
addDisplayedFields
void addDisplayedFields(EntityDto entityDto, Map<String, Long> positions)
addFields
void addFields(EntityDto entity, Collection<FieldDto> fields)
addFilterableFields
void addFilterableFields(EntityDto entityDto, Collection<String> fieldNames)
addLookups
void addLookups(Long entityId, Collection<LookupDto> lookups)
commitChanges
void commitChanges(Long entityId)
commitChanges
void commitChanges(Long entityId, String changesOwner)
createEntity
EntityDto createEntity(EntityDto entityDto)
deleteEntity
void deleteEntity(Long entityId)
findEntityFieldByName
FieldDto findEntityFieldByName(Long entityId, String name)
findFieldByName
FieldDto findFieldByName(Long entityId, String name)
getAdvancedSettings
AdvancedSettingsDto getAdvancedSettings(Long entityId)
getAdvancedSettings
AdvancedSettingsDto getAdvancedSettings(Long entityId, boolean committed)
getCurrentSchemaVersion
Long getCurrentSchemaVersion(String entityClassName)
getDisplayFields
List<FieldDto> getDisplayFields(Long entityId)
getEntitiesWithLookups
List<EntityDto> getEntitiesWithLookups()
getEntity
EntityDto getEntity(Long entityId)
getEntityByClassName
EntityDto getEntityByClassName(String className)
getEntityDraft
EntityDraft getEntityDraft(Long entityId)
getEntityDraft
EntityDraft getEntityDraft(Long entityId, String username)
getEntityFields
List<FieldDto> getEntityFields(Long entityId)
getEntityForEdit
EntityDto getEntityForEdit(Long entityId)
getEntityLookups
List<LookupDto> getEntityLookups(Long entityId)
getFields
List<FieldDto> getFields(Long entityId)
getLookupByName
LookupDto getLookupByName(Long entityId, String lookupName)
listEntities
List<EntityDto> listEntities()
listEntities
List<EntityDto> listEntities(boolean withSecurityCheck)
listWorkInProgress
List<EntityDto> listWorkInProgress()
saveDraftEntityChanges
DraftResult saveDraftEntityChanges(Long entityId, DraftData draftData, String username)
saveDraftEntityChanges
DraftResult saveDraftEntityChanges(Long entityId, DraftData draftData)
updateComboboxValues
void updateComboboxValues(Long entityId, Map<String, Collection> fieldValuesToUpdate)
updateDraft
EntityDto updateDraft(Long entityId)

HistoryService

public interface HistoryService

The HistoryService provides methods related with processing historical changes on the given instance of entity.

Methods
countHistoryRecords
long countHistoryRecords(Object instance)
getHistoryForInstance
List getHistoryForInstance(Object instance, QueryParams queryParams)

Returns the historical data for the given instance. This method return historical data only for objects that are not in the MDS trash. For trash instances the return value will be incorrect.

Parameters:
  • instance – an instance created from the given entity definition.
  • queryParams – Query parameters such as page number, size of page and sort direction. If null method will return all history records.
Returns:

a list of historical data related with the given instance.

record
void record(Object instance)

Records changes made on the given instance of entity. The first historical data should be equal to data inside the given instance. Two instance of historical data should be connected using appropriate fields (defined in history class definition). This method should be used only for instances that are not in the MDS trash.

Parameters:
  • instance – an instance created from the given entity definition.
remove
void remove(Object instance)

Removes all historical data with information what changes were made on the given instance of entity.

Parameters:
  • instance – an instance created from the given entity definition.
setTrashFlag
void setTrashFlag(Object instance, Object trash, boolean flag)

Sets the trash flag for historical data related with the given instance object.

Parameters:
  • instance – an instance created from the given entity definition.
  • flag – true if instance was moved to trash; otherwise false.

JarGeneratorService

public interface JarGeneratorService

This interface provides methods to create a bundle jar with all entities defined in MDS module.

Fields
BLUEPRINT_TEMPLATE
String BLUEPRINT_TEMPLATE
BLUEPRINT_XML
String BLUEPRINT_XML
BUNDLE_IMPORTS
String BUNDLE_IMPORTS
DATANUCLEUS_PROPERTIES
String DATANUCLEUS_PROPERTIES
ENTITY_LIST_FILE
String ENTITY_LIST_FILE
MDS_COMMON_CONTEXT
String MDS_COMMON_CONTEXT
MDS_ENTITIES_CONTEXT
String MDS_ENTITIES_CONTEXT
MDS_ENTITIES_CONTEXT_TEMPLATE
String MDS_ENTITIES_CONTEXT_TEMPLATE
MOTECH_MDS_PROPERTIES
String MOTECH_MDS_PROPERTIES
PACKAGE_JDO
String PACKAGE_JDO
Methods
generate
File generate()

Generates a jar file that contains entity class definitions, repositories, interfaces, implementations of these interfaces. The jar should also contains class related with historical data and trash.

Throws:
  • IOException – if an I/O error occurs while the jar is creating.
Returns:

file that point to an entitites bundle jar.

regenerateMdsDataBundle
void regenerateMdsDataBundle(boolean buildDDE)

Constructs entities, builds and starts the entities bundle jar

Parameters:
  • buildDDEtrue if class definitions for entities from outside bundles should also be created; otherwise false.

See also: .generate()

regenerateMdsDataBundle
void regenerateMdsDataBundle(boolean buildDDE, boolean startBundle)

Constructs entities, builds the entities bundle jar. The generated bundle will start only if the startBundle will be set to true.

Parameters:
  • buildDDEtrue if class definitions for entities from outside bundles should also be created; otherwise false.
  • startBundletrue if the generated bundle should start; otherwise false.

See also: .generate()

regenerateMdsDataBundleAfterDdeEnhancement
void regenerateMdsDataBundleAfterDdeEnhancement(String moduleName)

Constructs entities, builds and starts the entities bundle jar. This method should be used after DDE enhancement. It will build all DDE classes and refresh the module from which the DDE being enhanced comes from.

Parameters:
  • moduleName – module name of the entity from which the enhanced DDE comes from

See also: .generate()

MdsSchedulerService

public interface MdsSchedulerService
Methods
scheduleRepeatingJob
void scheduleRepeatingJob(long interval)
unscheduleRepeatingJob
void unscheduleRepeatingJob()

MotechDataService

public interface MotechDataService<T>

This is a basic service interface with CRUD operations. Mainly it is used as super interface to create service interface related with the given entity schema in org.motechproject.mds.builder.EntityInfrastructureBuilder but it can be also used by other service interfaces inside this package.

Parameters:
  • <T> – the type of entity schema.
Methods
count
long count()
countForFilter
long countForFilter(Filter filter)
create
T create(T object)
delete
void delete(T object)
delete
void delete(String primaryKeyName, Object value)
deleteAll
void deleteAll()
doInTransaction
<R> R doInTransaction(TransactionCallback<R> transactionCallback)
executeQuery
<R> R executeQuery(QueryExecution<R> queryExecution)
filter
List<T> filter(Filter filter)
filter
List<T> filter(Filter filter, QueryParams queryParams)
findById
T findById(Long id)
findTrashInstanceById
T findTrashInstanceById(Object instanceId, Object entityId)
getDetachedField
Object getDetachedField(T instance, String fieldName)
retrieve
T retrieve(String primaryKeyName, Object value)
retrieveAll
List<T> retrieveAll()
retrieveAll
List<T> retrieveAll(QueryParams queryParams)
revertFromTrash
void revertFromTrash(Object newInstance, Object trash)
update
T update(T object)

TransactionalMotechDataService

public abstract class TransactionalMotechDataService<T> extends DefaultMotechDataService<T>

The main goal of the TransactionalMotechDataService class is to resolve problems with transaction annotations not working for generated lookups. We use the traditional transaction callback instead.

Parameters:
  • <T> – the type of entity schema.
Methods
count
protected long count(List<Property> properties)
retrieveAll
protected List<T> retrieveAll(List<Property> properties)
retrieveAll
protected List<T> retrieveAll(List<Property> properties, QueryParams queryParams)

TrashService

public interface TrashService

The TrashService provides methods related with the module trash mode (by default the mode is active and it can be turned off by the user).

Methods
countTrashRecords
long countTrashRecords(String className)
emptyTrash
void emptyTrash()

Cleans the module trash. All instances in trash should be removed permanently and if they contain any historical data they should also be removed permanently.

This method should only be executed by the job created in the scheduleEmptyTrashJob() method.

findTrashById
Object findTrashById(Object instanceId, Object entityId)

Return instance with given id from trash.

Parameters:
  • instanceId – id of instance
  • entityId – id of instance entity
getInstancesFromTrash
Collection getInstancesFromTrash(String entityName, QueryParams queryParams)

Returns the collection of instances from trash of a certain entity. Returned collection contains only instances that are on the current schema version.

Parameters:
  • entityName – Instances of what entity should be looked for
  • queryParams – Query parameters such as page number, size of page and sort direction. If null method will return all records in trash.
Returns:

Collection of instances on the current schema version in trash

isTrashMode
boolean isTrashMode()

Checks if trash mode is active. This method should be used before executing the moveToTrash(Object,Long) method to resolve whether the given instance should be moved to trash or removed permanently.

Returns:true if delete mode is equal to org.motechproject.mds.config.DeleteMode.TRASH; false otherwise.
moveFromTrash
void moveFromTrash(Object newInstance, Object trash)

Sets history for given trashed instance to match the new one and deletes trashed one from trash.

Parameters:
  • newInstance – instance to be returned from trash
  • trash – trashed instance to be removed
moveToTrash
void moveToTrash(Object instance, Long schemaVersion)

Moves the given instance to the trash. This method should only be executed, when the module trash mode is active.

Parameters:
  • instance – an instance created from the given entity definition.

See also: .isTrashMode()

scheduleEmptyTrashJob
void scheduleEmptyTrashJob()

Sets the repeating schedule job that will be executed from time to time. Execution time depends on the value of time value and time unit (defined in org.motechproject.mds.util.Constants.Config.MODULE_FILE).

Before scheduling new job, the old one should be unscheduled to prevent the errors.

TypeService

public interface TypeService

The TypeService is an interface defining available methods to execute various actions on Field Types.

Methods
findType
TypeDto findType(Class<?> clazz)
findValidations
List<TypeValidation> findValidations(TypeDto type, Class<? extends Annotation> aClass)
getAllTypes
List<TypeDto> getAllTypes()
getType
Type getType(TypeValidation validation)

org.motechproject.mds.service.impl

BasePersistenceService

public abstract class BasePersistenceService

The BasePersistenceService class provides utility methods for communication with the database for HistoryServiceImpl and TrashServiceImpl. It allows to create and retrieve instances, load proper classes and parse values.

Methods
create
protected <T> Object create(Class<T> clazz, Object src, EntityType type)
create
protected <T> Object create(Class<T> clazz, Object src, EntityType type, ObjectReference objectReference)
findService
protected MotechDataService findService(Class<?> clazz)
getClass
protected Class<?> getClass(Object src, EntityType type)
getClass
protected Class<?> getClass(String srcClassName, EntityType type)
getCurrentSchemaVersion
protected Long getCurrentSchemaVersion(String className)
getEntities
protected List<Entity> getEntities()
getEntity
protected Entity getEntity(Long id)
getEntitySchemaVersion
protected Long getEntitySchemaVersion(Object src)
getInstanceClassName
protected String getInstanceClassName(Object instance)
getInstanceId
protected Long getInstanceId(Object instance)
getPersistenceManagerFactory
protected PersistenceManagerFactory getPersistenceManagerFactory()
getValue
protected Object getValue(Field field, Object src, Object target, EntityType type, ObjectReference objectReference)
setAllEntities
public void setAllEntities(AllEntities allEntities)
setBundleContext
public void setBundleContext(BundleContext bundleContext)
setPersistenceManagerFactory
public void setPersistenceManagerFactory(PersistenceManagerFactory persistenceManagerFactory)

EntityServiceImpl

public class EntityServiceImpl implements EntityService

Default implementation of org.motechproject.mds.service.EntityService interface.

Methods
abandonChanges
public void abandonChanges(Long entityId)
addDisplayedFields
public void addDisplayedFields(EntityDto entityDto, Map<String, Long> positions)
addFields
public void addFields(EntityDto entityDto, Collection<FieldDto> fields)
addFilterableFields
public void addFilterableFields(EntityDto entityDto, Collection<String> fieldNames)
addLookups
public void addLookups(Long entityId, Collection<LookupDto> lookups)
commitChanges
public void commitChanges(Long entityId, String changesOwner)
commitChanges
public void commitChanges(Long entityId)
createEntity
public EntityDto createEntity(EntityDto entityDto)
deleteEntity
public void deleteEntity(Long entityId)
findEntityFieldByName
public FieldDto findEntityFieldByName(Long entityId, String name)
findFieldByName
public FieldDto findFieldByName(Long entityId, String name)
getAdvancedSettings
public AdvancedSettingsDto getAdvancedSettings(Long entityId)
getAdvancedSettings
public AdvancedSettingsDto getAdvancedSettings(Long entityId, boolean committed)
getCurrentSchemaVersion
public Long getCurrentSchemaVersion(String className)
getDisplayFields
public List<FieldDto> getDisplayFields(Long entityId)
getEntitiesWithLookups
public List<EntityDto> getEntitiesWithLookups()
getEntity
public EntityDto getEntity(Long entityId)
getEntityByClassName
public EntityDto getEntityByClassName(String className)
getEntityDraft
public EntityDraft getEntityDraft(Long entityId)
getEntityDraft
public EntityDraft getEntityDraft(Long entityId, String username)
getEntityFields
public List<FieldDto> getEntityFields(Long entityId)
getEntityForEdit
public EntityDto getEntityForEdit(Long entityId)
getEntityLookups
public List<LookupDto> getEntityLookups(Long entityId)
getFields
public List<FieldDto> getFields(Long entityId)
getLookupByName
public LookupDto getLookupByName(Long entityId, String lookupName)
listEntities
public List<EntityDto> listEntities()
listEntities
public List<EntityDto> listEntities(boolean withSecurityCheck)
listWorkInProgress
public List<EntityDto> listWorkInProgress()
saveDraftEntityChanges
public DraftResult saveDraftEntityChanges(Long entityId, DraftData draftData, String username)
saveDraftEntityChanges
public DraftResult saveDraftEntityChanges(Long entityId, DraftData draftData)
setAllEntities
public void setAllEntities(AllEntities allEntities)
setAllEntityAudits
public void setAllEntityAudits(AllEntityAudits allEntityAudits)
setAllEntityDrafts
public void setAllEntityDrafts(AllEntityDrafts allEntityDrafts)
setAllTypes
public void setAllTypes(AllTypes allTypes)
setMDSConstructor
public void setMDSConstructor(MDSConstructor mdsConstructor)
updateComboboxValues
public void updateComboboxValues(Long entityId, Map<String, Collection> fieldValuesToUpdate)
updateDraft
public EntityDto updateDraft(Long entityId)

HistoryServiceImpl

public class HistoryServiceImpl extends BasePersistenceService implements HistoryService

Default implementation of org.motechproject.mds.service.HistoryService interface.

Methods
countHistoryRecords
public long countHistoryRecords(Object instance)
create
protected <T> Object create(Class<T> clazz, Object src, EntityType type)
getHistoryForInstance
public List getHistoryForInstance(Object instance, QueryParams queryParams)
record
public void record(Object instance)
remove
public void remove(Object instance)
setTrashFlag
public void setTrashFlag(Object instance, Object trash, boolean flag)

JarGeneratorServiceImpl

public class JarGeneratorServiceImpl implements JarGeneratorService

Default implementation of org.motechproject.mds.service.JarGeneratorService interface.

Methods
generate
public File generate()
regenerateMdsDataBundle
public synchronized void regenerateMdsDataBundle(boolean buildDDE)
regenerateMdsDataBundle
public void regenerateMdsDataBundle(boolean buildDDE, boolean startBundle)
regenerateMdsDataBundleAfterDdeEnhancement
public void regenerateMdsDataBundleAfterDdeEnhancement(String moduleName)
setBundleContext
public void setBundleContext(BundleContext bundleContext)
setMdsConstructor
public void setMdsConstructor(MDSConstructor mdsConstructor)
setMdsDataProvider
public void setMdsDataProvider(MDSDataProvider mdsDataProvider)
setMetadataHolder
public void setMetadataHolder(MetadataHolder metadataHolder)
setMonitor
public void setMonitor(EntitiesBundleMonitor monitor)
setVelocityEngine
public void setVelocityEngine(VelocityEngine velocityEngine)

MdsScheduledJob

public class MdsScheduledJob implements Job

Job responsible for emptying MDS trash.

Methods
execute
public void execute(JobExecutionContext jobExecutionContext)

MdsSchedulerServiceImpl

public class MdsSchedulerServiceImpl implements MdsSchedulerService
Fields
DEFAULT_WAIT_TIME
public static final int DEFAULT_WAIT_TIME
JOB_GROUP_NAME
public static final String JOB_GROUP_NAME
MAX_REPEAT_COUNT
public static final int MAX_REPEAT_COUNT
RETRIEVAL_RETRIES_COUNT
public static final int RETRIEVAL_RETRIES_COUNT
SCHEDULER_SYMBOLIC_NAME
public static final String SCHEDULER_SYMBOLIC_NAME
Constructors
MdsSchedulerServiceImpl
public MdsSchedulerServiceImpl(BundleContext bundleContext)
Methods
scheduleRepeatingJob
public void scheduleRepeatingJob(long interval)
unscheduleRepeatingJob
public void unscheduleRepeatingJob()

TrashServiceImpl

public class TrashServiceImpl extends BasePersistenceService implements TrashService

Default implementation of org.motechproject.mds.service.TrashService interface.

Methods
countTrashRecords
public long countTrashRecords(String className)
emptyTrash
public void emptyTrash()
findTrashById
public Object findTrashById(Object instanceId, Object entityId)
getInstancesFromTrash
public Collection getInstancesFromTrash(String className, QueryParams queryParams)
isTrashMode
public boolean isTrashMode()
moveFromTrash
public void moveFromTrash(Object newInstance, Object trash)
moveToTrash
public void moveToTrash(Object instance, Long entityVersion)
scheduleEmptyTrashJob
public void scheduleEmptyTrashJob()
setHistoryService
public void setHistoryService(HistoryService historyService)
setMdsSchedulerService
public void setMdsSchedulerService(MdsSchedulerService mdsSchedulerService)
setSettingsService
public void setSettingsService(SettingsService settingsService)

TypeServiceImpl

public class TypeServiceImpl implements TypeService

Default implementation of org.motechproject.mds.service.TypeService interface

Methods
findType
public TypeDto findType(Class<?> clazz)
findValidations
public List<TypeValidation> findValidations(TypeDto type, Class<? extends Annotation> aClass)
getAllTypes
public List<TypeDto> getAllTypes()
getType
public Type getType(TypeValidation validation)
setAllTypeValidations
public void setAllTypeValidations(AllTypeValidations allTypeValidations)
setAllTypes
public void setAllTypes(AllTypes allTypes)

org.motechproject.mds.util

ClassName

public final class ClassName

The ClassName util provides several methods which should help for example with getting class name or package from string representation of class. There is also methods related with creating names for repository, service interface and implementation of this service interface.

Methods
getEntityName
public static String getEntityName(String className)
getHistoryClassName
public static String getHistoryClassName(String className)
getInterfaceName
public static String getInterfaceName(String className)
getPackage
public static String getPackage(String className)
getRepositoryName
public static String getRepositoryName(String className)
getServiceName
public static String getServiceName(String className)
getSimpleName
public static String getSimpleName(String className)
getTrashClassName
public static String getTrashClassName(String className)
trimTrashHistorySuffix
public static String trimTrashHistorySuffix(String className)

Constants

public final class Constants

The Constants contains constant values used in MDS module. They are grouped by their role.

Constants.AnnotationFields

public static final class AnnotationFields

The AnnotationFields contains constant values related with attributes names in mds annotations.

See also: org.motechproject.mds.annotations.Entity, org.motechproject.mds.annotations.Field, org.motechproject.mds.annotations.Ignore, org.motechproject.mds.annotations.Lookup, org.motechproject.mds.annotations.LookupField

Fields
DELETE
public static final String DELETE

Constant DELETE corresponding to the attribute name delete

DISPLAY_NAME
public static final String DISPLAY_NAME

Constant DISPLAY_NAME corresponding to the primitive value displayName

FRACTION
public static final String FRACTION

Constant FRACTION corresponding to the primitive value fraction

INTEGER
public static final String INTEGER

Constant INTEGER corresponding to the primitive value integer

MAX
public static final String MAX

Constant MAX corresponding to the primitive value max

MIN
public static final String MIN

Constant MIN corresponding to the primitive value min

MODULE
public static final String MODULE

Constant MODULE corresponding to the attribute name module

NAME
public static final String NAME

Constant NAME corresponding to the attribute name name

NAMESPACE
public static final String NAMESPACE

Constant NAMESPACE corresponding to the attribute name namespace

PERSIST
public static final String PERSIST

Constant PERSIST corresponding to the attribute name persist

REGEXP
public static final String REGEXP

Constant REGEXP corresponding to the primitive value regexp

UPDATE
public static final String UPDATE

Constant UPDATE corresponding to the attribute name update

VALUE
public static final String VALUE

Constant VALUE corresponding to the primitive value value

Constants.BundleNames

public static final class BundleNames

The names of the mds bundles.

Fields
MDS_BUNDLE_NAME
public static final String MDS_BUNDLE_NAME
MDS_BUNDLE_SYMBOLIC_NAME
public static final String MDS_BUNDLE_SYMBOLIC_NAME
MDS_ENTITIES_NAME
public static final String MDS_ENTITIES_NAME
MDS_ENTITIES_SYMBOLIC_NAME
public static final String MDS_ENTITIES_SYMBOLIC_NAME
MDS_MIGRATION_NAME
public static final String MDS_MIGRATION_NAME
MDS_MIGRATION_SYMBOLIC_NAME
public static final String MDS_MIGRATION_SYMBOLIC_NAME
SYMBOLIC_NAME_PREFIX
public static final String SYMBOLIC_NAME_PREFIX

Constants.Config

public static final class Config

The Config contains constant values related with properties inside files:

  • datanucleus.properties
  • motech-mds.properties
Fields
DATANUCLEUS_FILE
public static final String DATANUCLEUS_FILE

Constant DATANUCLEUS_FILE presents the file name with configuration for datanucleus.

EMPTY_TRASH_JOB
public static final String EMPTY_TRASH_JOB

Constant EMPTY_TRASH_JOB presents a name of job scheduled by scheduler module.

MDS_DELETE_MODE
public static final String MDS_DELETE_MODE

Constant MDS_DELETE_MODE presents what should happen with objects when there are deleted. They can be deleted permanently or moved to the trash.The following values are valid for this property:

  • delete
  • trash
MDS_EMPTY_TRASH
public static final String MDS_EMPTY_TRASH

The boolean property that specifies if the trash should be empty after some time.

See also: .MDS_DELETE_MODE, .MDS_TIME_VALUE, .MDS_TIME_UNIT

MDS_TIME_UNIT
public static final String MDS_TIME_UNIT

The property that specifies what time unit should be used to specify time when trash should be cleaned. The following values are valid for this property:

  • Hours
  • Days
  • Weeks
  • Months
  • Years

See also: .MDS_DELETE_MODE, .MDS_EMPTY_TRASH, .MDS_TIME_VALUE

MDS_TIME_VALUE
public static final String MDS_TIME_VALUE

The integer property that specifies after what time (according with correct time unit) trash should be cleaned.

See also: .MDS_DELETE_MODE, .MDS_EMPTY_TRASH, .MDS_TIME_UNIT

MODULE_FILE
public static final String MODULE_FILE

Constant MODULE_FILE presents the file name with configuration for MDS module.

Constants.Manifest

public static final class Manifest

The Manifest contains constant values related with attributes inside the motech-platform-dataservices-entities bundle manifest.

See also: org.motechproject.mds.service.JarGeneratorService, org.motechproject.mds.service.impl.JarGeneratorServiceImpl

Fields
BUNDLE_MANIFESTVERSION
public static final String BUNDLE_MANIFESTVERSION

Constant BUNDLE_MANIFESTVERSION presents a version of bundle manifest.

BUNDLE_NAME_SUFFIX
public static final String BUNDLE_NAME_SUFFIX

Constant BUNDLE_NAME_SUFFIX presents suffix of the name of bundle that will be created by implementation of org.motechproject.mds.service.JarGeneratorService interface.

MANIFEST_VERSION
public static final String MANIFEST_VERSION

Constant MANIFEST_VERSION presents a version of jar manifest.

SYMBOLIC_NAME_SUFFIX
public static final String SYMBOLIC_NAME_SUFFIX

Constant SYMBOLIC_NAME_SUFFIX presents suffix of the bundle symbolic name of bundle that will be created by implementation of org.motechproject.mds.service.JarGeneratorService interface.

Constants.MetadataKeys

public static final class MetadataKeys

The keys used in fields metadata

Fields
ENUM_CLASS_NAME
public static final String ENUM_CLASS_NAME
MAP_KEY_TYPE
public static final String MAP_KEY_TYPE
MAP_VALUE_TYPE
public static final String MAP_VALUE_TYPE

Constants.Operators

public static final class Operators

Operators that users can use in lookups.

Fields
ENDS_WITH
public static final String ENDS_WITH
EQ
public static final String EQ
EQ_IGNORE_CASE
public static final String EQ_IGNORE_CASE
GT
public static final String GT
GT_EQ
public static final String GT_EQ
LT
public static final String LT
LT_EQ
public static final String LT_EQ
MATCHES
public static final String MATCHES
NEQ
public static final String NEQ
STARTS_WITH
public static final String STARTS_WITH

Constants.Packages

public static final class Packages

The Packages contains constant values related with packages inside MDS module.

Fields
BASE
public static final String BASE

Constant BASE presents the base package for all pakcages inside MDS module.

ENTITY
public static final String ENTITY

Constant ENTITY presents a package for entity classes.

See also: .BASE

REPOSITORY
public static final String REPOSITORY

Constant REPOSITORY presents a package for repository classes.

See also: .BASE

SERVICE
public static final String SERVICE

Constant SERVICE presents a package for service interfaces.

See also: .BASE

SERVICE_IMPL
public static final String SERVICE_IMPL

Constant SERVICE_IMPL presents a package for implementation of interfaces defined in SERVICE package.

See also: .BASE, .SERVICE

Constants.PackagesGenerated

public static final class PackagesGenerated
Fields
ENTITY
public static final String ENTITY

Constant ENTITY presents a package for generated entity classes.

REPOSITORY
public static final String REPOSITORY

Constant REPOSITORY presents a package for generated repository classes.

See also: .ENTITY

SERVICE
public static final String SERVICE

Constant SERVICE presents a package for generated service interfaces.

See also: .ENTITY

SERVICE_IMPL
public static final String SERVICE_IMPL

Constant SERVICE_IMPL presents a package for generated implementation of interfaces defined in SERVICE package.

See also: .SERVICE

Constants.Roles

public static final class Roles

The Roles contains constant values related with security roles.

Fields
DATA_ACCESS
public static final String DATA_ACCESS

Users with ‘Data Access’ have the ability to view the Data Browser tab. From that tab then can search for objects within the system, view and modify the data stored in the system.

HAS_ANY_MDS_ROLE
public static final String HAS_ANY_MDS_ROLE

Spring security el expression to check if the given user has any of the MDS roles.

See also: .SCHEMA_ACCESS, .SETTINGS_ACCESS, .DATA_ACCESS

HAS_DATA_ACCESS
public static final String HAS_DATA_ACCESS

Spring security el expression to check if the given user has the ‘Data Access’ role.

See also: .DATA_ACCESS

HAS_DATA_OR_SCHEMA_ACCESS
public static final String HAS_DATA_OR_SCHEMA_ACCESS

Spring security el expression to check if the given user has the ‘Schema Access’ or ‘Data Access’ roles.

See also: .SCHEMA_ACCESS, .DATA_ACCESS

HAS_SCHEMA_ACCESS
public static final String HAS_SCHEMA_ACCESS

Spring security el expression to check if the given user has the ‘Schema Access’ role.

See also: .SCHEMA_ACCESS

HAS_SETTINGS_ACCESS
public static final String HAS_SETTINGS_ACCESS

Spring security el expression to check if the given user has the ‘Settings Access’ role.

See also: .SETTINGS_ACCESS

SCHEMA_ACCESS
public static final String SCHEMA_ACCESS

Users with ‘Schema Access’ have the ability to view the Schema Editor tab of the UI. Then can add new objects, delete existing objects and modify the fields on existing objects.

SETTINGS_ACCESS
public static final String SETTINGS_ACCESS

Users with ‘Settings Access’ have the ability to view the Settings tab. From that tab then can modify data retention policies as well as import and export schema and data.

Constants.Settings

public static final class Settings

Keys for entity settings.

Fields
ALLOW_MULTIPLE_SELECTIONS
public static final String ALLOW_MULTIPLE_SELECTIONS
ALLOW_USER_SUPPLIED
public static final String ALLOW_USER_SUPPLIED
COMBOBOX_VALUES
public static final String COMBOBOX_VALUES
STRING_MAX_LENGTH
public static final String STRING_MAX_LENGTH

Constants.Util

public static final class Util

The Util contains constant values to help avoid string literal repetition.

See also: pmd

Fields
CREATION_DATE_DISPLAY_FIELD_NAME
public static final String CREATION_DATE_DISPLAY_FIELD_NAME
CREATION_DATE_FIELD_NAME
public static final String CREATION_DATE_FIELD_NAME
CREATOR_DISPLAY_FIELD_NAME
public static final String CREATOR_DISPLAY_FIELD_NAME
CREATOR_FIELD_NAME
public static final String CREATOR_FIELD_NAME
DATANUCLEUS
public static final String DATANUCLEUS
ENTITY
public static final String ENTITY

Constant ENTITY corresponding to the field name of the class that want to create a bidirectional connection with instane of org.motechproject.mds.domain.Entity

FALSE
public static final String FALSE

Constant FALSE corresponding to the primitive value false

ID_DISPLAY_FIELD_NAME
public static final String ID_DISPLAY_FIELD_NAME
ID_FIELD_NAME
public static final String ID_FIELD_NAME
MODIFICATION_DATE_DISPLAY_FIELD_NAME
public static final String MODIFICATION_DATE_DISPLAY_FIELD_NAME
MODIFICATION_DATE_FIELD_NAME
public static final String MODIFICATION_DATE_FIELD_NAME
MODIFIED_BY_DISPLAY_FIELD_NAME
public static final String MODIFIED_BY_DISPLAY_FIELD_NAME
MODIFIED_BY_FIELD_NAME
public static final String MODIFIED_BY_FIELD_NAME
OWNER_DISPLAY_FIELD_NAME
public static final String OWNER_DISPLAY_FIELD_NAME
OWNER_FIELD_NAME
public static final String OWNER_FIELD_NAME
TRUE
public static final String TRUE

Constant TRUE corresponding to the primitive value true

FieldHelper

public final class FieldHelper

Utility class handling dynamic setting of field values

Methods
setField
public static void setField(Object current, String path, List value)

HistoryFieldUtil

public final class HistoryFieldUtil

The HistoryFieldUtil class provides helper methods to determine field names in the given history class.

Methods
currentVersion
public static String currentVersion(Class<?> historyClass)
isLast
public static String isLast(Class<?> historyClass)
schemaVersion
public static String schemaVersion(Class<?> historyClass)
trashFlag
public static String trashFlag(Class<?> historyClass)

InstanceSecurityRestriction

public class InstanceSecurityRestriction

Represents a restriction on entity instances

Methods
isByCreator
public boolean isByCreator()
isByOwner
public boolean isByOwner()
isEmpty
public boolean isEmpty()
setByCreator
public void setByCreator(boolean byCreator)
setByOwner
public void setByOwner(boolean byOwner)

Loader

public abstract class Loader<T>

The Loader is an abstract class that checks if all class dependencies to the given class definition are resolved. If not then the missing class name is taken from exception and the doWhenClassNotFound(String) method is executed.

Parameters:
  • <T> – the type of argument data
Methods
doWhenClassNotFound
public abstract void doWhenClassNotFound(String name)
getClassDefinition
public abstract Class<?> getClassDefinition(T arg)
loadClass
public Class<?> loadClass(T arg)

LookupName

public final class LookupName

Utility class for dealing with lookup names.

Methods
lookupCountMethod
public static String lookupCountMethod(String lookupNameOrMethodName)
lookupMethod
public static String lookupMethod(String lookupName)

MDSClassLoader

public class MDSClassLoader extends ClassLoader

The MDSClassLoader class is a mds wrapper for ClassLoader.

Constructors
MDSClassLoader
protected MDSClassLoader()
MDSClassLoader
protected MDSClassLoader(ClassLoader parent)
Methods
defineClass
public Class<?> defineClass(String name, byte[] bytecode)
getInstance
public static MDSClassLoader getInstance()
getStandaloneInstance
public static MDSClassLoader getStandaloneInstance()
getStandaloneInstance
public static MDSClassLoader getStandaloneInstance(ClassLoader parent)
reloadClassLoader
public static void reloadClassLoader()
safeDefineClass
public Class<?> safeDefineClass(String name, byte[] bytecode)

MemberUtil

public final class MemberUtil
Fields
FIELD_NAME_START_IDX
public static final Integer FIELD_NAME_START_IDX
GETTER_PREFIX
public static final String GETTER_PREFIX
SETTER_PREFIX
public static final String SETTER_PREFIX
Methods
getCorrectType
public static Class<?> getCorrectType(AnnotatedElement object)
getCorrectType
public static Class<?> getCorrectType(Member object)
getFieldName
public static String getFieldName(AnnotatedElement object)
getFieldName
public static String getFieldName(Member object)
getGenericType
public static Class<?> getGenericType(AnnotatedElement object)
getGenericType
public static Class<?> getGenericType(AnnotatedElement object, int typeNumber)
getGenericType
public static Class<?> getGenericType(Member object, int typeNumber)
getMembers
public static List<Member> getMembers(Class<?> clazz, Predicate methodPredicate, Predicate fieldPredicate)

NumberPredicate

public class NumberPredicate implements Predicate
Constructors
NumberPredicate
public NumberPredicate(Number element)
Methods
evaluate
public boolean evaluate(Object candidate)

ObjectReference

public class ObjectReference

Represents an object reference. It holds an information about related field name, as well as the object that the field should reference to.

Constructors
ObjectReference
public ObjectReference(String fieldName, Object reference)
Methods
getFieldName
public String getFieldName()
getReference
public Object getReference()
setFieldName
public void setFieldName(String fieldName)
setReference
public void setReference(Object reference)

Order

public class Order implements Serializable

Represents an order in a query

Constructors
Order
public Order(String field)
Order
public Order(String field, String direction)
Order
public Order(String field, Direction direction)
Methods
getDirection
public Direction getDirection()
getField
public String getField()
toString
public String toString()

Order.Direction

public static enum Direction
Enum Constants
ASC
public static final Order.Direction ASC
DESC
public static final Order.Direction DESC

Pair

public interface Pair<N, V>

The Pair util interface should use everywhere where developer needs a pair of key-value

Parameters:
  • <N> – type of key
  • <V> – type of value

See also: org.motechproject.mds.domain.FieldMetadata, org.motechproject.mds.domain.FieldSetting, org.motechproject.mds.dto.MetadataDto, org.motechproject.mds.dto.SettingDto

Methods
getKey
N getKey()
getValue
V getValue()

PropertyUtil

public final class PropertyUtil extends PropertyUtils

The PropertyUtil util class provides the same method like org.apache.commons.beanutils.PropertyUtils and two additional methods for safe writing and reading property in the given bean.

Methods
getPropertyDescriptors
public static PropertyDescriptor[] getPropertyDescriptors(Object bean)
safeGetProperty
public static Object safeGetProperty(Object bean, String name)
safeSetProperty
public static void safeSetProperty(Object bean, String name, Object value)

SecurityMode

public enum SecurityMode

This enum describes security mode for an entity

Enum Constants
CREATOR
public static final SecurityMode CREATOR
EVERYONE
public static final SecurityMode EVERYONE
OWNER
public static final SecurityMode OWNER
ROLES
public static final SecurityMode ROLES
USERS
public static final SecurityMode USERS

SecurityUtil

public final class SecurityUtil

The SecurityUtil class provides helper methods to retrieve logged user details, such as username or roles

Methods
getUserRoles
public static List<String> getUserRoles()
getUsername
public static String getUsername()

TypeHelper

public final class TypeHelper

A helper class for parsing and formatting mds supported types.

Methods
breakString
public static String[] breakString(String str)
breakString
public static String[] breakString(String str, String[] removes, String[] search, String[] replacement, String separator)
breakStringForList
public static String[] breakStringForList(String str)
format
public static String format(Object obj)
getPrimitive
public static Class<?> getPrimitive(Class<?> clazz)
getWrapperForPrimitive
public static Class<?> getWrapperForPrimitive(Class<?> clazz)
hasPrimitive
public static boolean hasPrimitive(Class<?> clazz)
isPrimitive
public static boolean isPrimitive(Class<?> clazz)
isPrimitive
public static boolean isPrimitive(String className)
parse
public static Object parse(Object val, Class<?> toClass)
parse
public static Object parse(Object val, String toClass)
parse
public static Object parse(Object val, String toClass, ClassLoader classLoader)
parse
public static Object parse(Object val, String toClass, String genericType)
parse
public static Object parse(Object val, String toClass, String genericType, ClassLoader classLoader)
parseIntToBool
public static boolean parseIntToBool(Integer val)
parseList
public static List parseList(List val, Class<?> generic)
parseNumber
public static Number parseNumber(Object val, String toClass)
parseString
public static Object parseString(String str, Class<?> toClass)
parseString
public static Object parseString(String str, String toClass)
parseString
public static Object parseString(String str, Class<?> toClass, Class<?> generic)
parseStringToMap
public static Map parseStringToMap(String str)
toRange
public static Range toRange(Object object, String typeClass)
toSet
public static Set toSet(Object object, String typeClass)

ValidationUtil

public final class ValidationUtil

Common validation utils for mds.

Methods
validateNoJavaKeyword
public static void validateNoJavaKeyword(String str)

org.motechproject.osgi.web

Activator

public class Activator implements BundleActivator
Methods
resourceMappings
protected Map<String, String> resourceMappings()
start
public void start(BundleContext context)
stop
public void stop(BundleContext context)

ApplicationContextTracker

public abstract class ApplicationContextTracker extends ServiceTracker

Base class for every class that wishes to track Spring application context. Contains a methods that help with synchronous processing.

Constructors
ApplicationContextTracker
public ApplicationContextTracker(BundleContext context)
Methods
contextInvalidOrProcessed
protected boolean contextInvalidOrProcessed(ServiceReference serviceReference, ApplicationContext applicationContext)
getLock
protected Object getLock()
markAsProcessed
protected void markAsProcessed(ApplicationContext applicationContext)
removeFromProcessed
protected void removeFromProcessed(ApplicationContext applicationContext)

BlueprintActivator

public class BlueprintActivator implements BundleActivator
Methods
start
public void start(BundleContext context)
stop
public void stop(BundleContext context)

BlueprintApplicationContextTracker

public class BlueprintApplicationContextTracker extends ApplicationContextTracker

The BlueprintApplicationContextTracker class tracks application contexts, which are registered as services.

Constructors
BlueprintApplicationContextTracker
public BlueprintApplicationContextTracker(BundleContext context)
Methods
addingService
public Object addingService(ServiceReference serviceReference)
removedService
public void removedService(ServiceReference reference, Object service)

BundleContextWrapper

public class BundleContextWrapper implements BundleContextAware
Fields
CONTEXT_SERVICE_NAME
public static final String CONTEXT_SERVICE_NAME
Constructors
BundleContextWrapper
public BundleContextWrapper()
BundleContextWrapper
public BundleContextWrapper(BundleContext context)
Methods
getBundleApplicationContext
public ApplicationContext getBundleApplicationContext()
getBundleContext
public BundleContext getBundleContext()
getCurrentBundleSymbolicName
public String getCurrentBundleSymbolicName()
getService
public <T> T getService(Class<T> clazz)
setBundleContext
public void setBundleContext(BundleContext bundleContext)

BundleRegister

public final class BundleRegister

The BundleRegister Singleton class is used for recording bundles. This class will help to reconfigure logger’s levels.

Methods
addBundle
public void addBundle(Bundle bundle)
getBundleList
public List<Bundle> getBundleList()
getInstance
public static BundleRegister getInstance()

BundledJspView

public class BundledJspView extends JstlView implements BundleContextAware
Methods
render
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
setBundleContext
public void setBundleContext(BundleContext bundleContext)

HttpServiceTracker

public class HttpServiceTracker extends ServiceTracker
Constructors
HttpServiceTracker
public HttpServiceTracker(BundleContext context, Map<String, String> resourceMapping)
Methods
addingService
public Object addingService(ServiceReference serviceReference)
removedService
public void removedService(ServiceReference ref, Object service)
start
public void start()
unregister
public void unregister()

HttpServiceTrackers

public class HttpServiceTrackers
Methods
addTrackerFor
public HttpServiceTracker addTrackerFor(Bundle bundle)
isBeingTracked
public boolean isBeingTracked(Bundle bundle)
removeTrackerFor
public HttpServiceTracker removeTrackerFor(Bundle bundle)

Log4JBundleLoader

public class Log4JBundleLoader

This Log4JBundleLoader class is responsible for loading configuration of the loggers from the saved properties or file in bundle (log4j.xml).

Methods
checkListContainLogger
public boolean checkListContainLogger(List<LogMapping> loggers, String log)
checkLogXmlConfiguration
public boolean checkLogXmlConfiguration(Document log4jDoc)
createLoggerProperties
public Properties createLoggerProperties(List<LogMapping> log)
loadBundle
public void loadBundle(Bundle bundle)
loadLoggerDbConfiguration
public void loadLoggerDbConfiguration()
setLog4jConf
public void setLog4jConf(String log4jConf)

ModuleRegistrationData

public class ModuleRegistrationData

Object used to registered a module withing the Motech UI system. Represents a module and is used for building the common user interface. All modules that wish to register within the UI system must either expose this class as a spring bean in their application context or manually register it through the UIFrameworkService OSGi service.

See also: UIFrameworkService

Constructors
ModuleRegistrationData
public ModuleRegistrationData()
ModuleRegistrationData
public ModuleRegistrationData(String moduleName, String url)
ModuleRegistrationData
public ModuleRegistrationData(String moduleName, Map<String, String> i18n)
ModuleRegistrationData
public ModuleRegistrationData(String moduleName, String url, List<String> angularModules, Map<String, String> i18n)
Methods
addAngularModule
public void addAngularModule(String moduleName)
addI18N
public void addI18N(String fileName, String fileLocation)
addSubMenu
public void addSubMenu(String url, String label)
addSubMenu
public void addSubMenu(String url, String label, String roleForAccess)
equals
public boolean equals(Object o)
getAngularModules
public List<String> getAngularModules()
getAngularModulesStr
public String getAngularModulesStr()
getBundle
public Bundle getBundle()
getCriticalMessage
public String getCriticalMessage()
getDefaultURL
public String getDefaultURL()
getI18n
public Map<String, String> getI18n()
getModuleName
public String getModuleName()
getResourcePath
public String getResourcePath()
getRoleForAccess
public List<String> getRoleForAccess()
getSettingsURL
public String getSettingsURL()
getSubMenu
public Map<String, SubmenuInfo> getSubMenu()
getUrl
public String getUrl()
hashCode
public int hashCode()
isNeedsAttention
public boolean isNeedsAttention()
removeAngularModule
public void removeAngularModule(String moduleName)
setBundle
public void setBundle(Bundle bundle)
setCriticalMessage
public void setCriticalMessage(String criticalMessage)
setDefaultURL
public void setDefaultURL(String defaultURL)
setModuleName
public void setModuleName(String moduleName)
setNeedsAttention
public void setNeedsAttention(boolean needsAttention)
setResourcePath
public void setResourcePath(String resourcePath)
setRoleForAccess
public void setRoleForAccess(String role)
setRoleForAccess
public void setRoleForAccess(List<String> roles)
setSettingsURL
public void setSettingsURL(String settingsURL)
setSubMenu
public void setSubMenu(Map<String, SubmenuInfo> subMenu)
setUrl
public void setUrl(String url)

MotechOsgiWebApplicationContext

public class MotechOsgiWebApplicationContext extends OsgiBundleXmlApplicationContext implements ConfigurableWebApplicationContext
Constructors
MotechOsgiWebApplicationContext
public MotechOsgiWebApplicationContext()
Methods
getNamespace
public String getNamespace()
getServletConfig
public ServletConfig getServletConfig()
getServletContext
public ServletContext getServletContext()
isInitialized
public boolean isInitialized()
setConfigLocation
public void setConfigLocation(String configLocation)
setNamespace
public void setNamespace(String namespace)
setServletConfig
public void setServletConfig(ServletConfig servletConfig)
setServletContext
public void setServletContext(ServletContext servletContext)
waitForContext
public void waitForContext(int waitTimeInMillis)

OsgiDispatcherServlet

public class OsgiDispatcherServlet extends DispatcherServlet
Constructors
OsgiDispatcherServlet
public OsgiDispatcherServlet(BundleContext bundleContext)
OsgiDispatcherServlet
public OsgiDispatcherServlet(BundleContext bundleContext, ConfigurableWebApplicationContext configurableWebApplicationContext)
Methods
initFrameworkServlet
protected void initFrameworkServlet()
postProcessWebApplicationContext
protected void postProcessWebApplicationContext(ConfigurableWebApplicationContext wac)

OsgiWebApplicationContext

public class OsgiWebApplicationContext implements WebApplicationContext
Constructors
OsgiWebApplicationContext
public OsgiWebApplicationContext(ApplicationContext applicationContext, ConfigurableWebApplicationContext configurableWebApplicationContext)
Methods
containsBean
public boolean containsBean(String name)
containsBeanDefinition
public boolean containsBeanDefinition(String beanName)
containsLocalBean
public boolean containsLocalBean(String name)
findAnnotationOnBean
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
getAliases
public String[] getAliases(String name)
getAutowireCapableBeanFactory
public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
getBean
public Object getBean(String name)
getBean
public <T> T getBean(String name, Class<T> requiredType)
getBean
public <T> T getBean(Class<T> requiredType)
getBean
public Object getBean(String name, Object... args)
getBeanDefinitionCount
public int getBeanDefinitionCount()
getBeanDefinitionNames
public String[] getBeanDefinitionNames()
getBeanNamesForType
public String[] getBeanNamesForType(Class<?> type)
getBeanNamesForType
public String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit)
getBeansOfType
public <T> Map<String, T> getBeansOfType(Class<T> type)
getBeansOfType
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
getBeansWithAnnotation
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
getClassLoader
public ClassLoader getClassLoader()
getDisplayName
public String getDisplayName()
getEnvironment
public ConfigurableEnvironment getEnvironment()
getId
public String getId()
getMessage
public String getMessage(String code, Object[] args, String defaultMessage, Locale locale)
getMessage
public String getMessage(String code, Object[] args, Locale locale)
getMessage
public String getMessage(MessageSourceResolvable resolvable, Locale locale)
getParent
public ApplicationContext getParent()
getParentBeanFactory
public BeanFactory getParentBeanFactory()
getResource
public Resource getResource(String location)
getResources
public Resource[] getResources(String locationPattern)
getServletContext
public ServletContext getServletContext()
getStartupDate
public long getStartupDate()
getType
public Class<?> getType(String name)
isPrototype
public boolean isPrototype(String name)
isSingleton
public boolean isSingleton(String name)
isTypeMatch
public boolean isTypeMatch(String name, Class<?> targetType)
publishEvent
public void publishEvent(ApplicationEvent event)

UIFrameworkService

public interface UIFrameworkService

Service responsible for managing the interface. Provides methods for registering/un-registering modules. All modules are represented by ModuleRegistrationData objects, either registered directly through this service or automatically by exposing it in their spring context. This service also allows manipulation of module state, by marking given modules as requiring attention on the UI.

Fields
MODULES_WITHOUT_SUBMENU
String MODULES_WITHOUT_SUBMENU
MODULES_WITHOUT_UI
String MODULES_WITHOUT_UI
MODULES_WITH_SUBMENU
String MODULES_WITH_SUBMENU
Methods
getModuleData
ModuleRegistrationData getModuleData(String moduleName)
getModuleDataByAngular
ModuleRegistrationData getModuleDataByAngular(String angularModule)
getModuleDataByBundle
ModuleRegistrationData getModuleDataByBundle(Bundle bundle)
getRegisteredModules
Map<String, Collection<ModuleRegistrationData>> getRegisteredModules()
isModuleRegistered
boolean isModuleRegistered(String moduleName)
moduleBackToNormal
void moduleBackToNormal(String moduleName)
moduleBackToNormal
void moduleBackToNormal(String moduleName, String submenu)
moduleNeedsAttention
void moduleNeedsAttention(String moduleName, String message)
moduleNeedsAttention
void moduleNeedsAttention(String moduleName, String submenu, String message)
registerModule
void registerModule(ModuleRegistrationData module)
unregisterModule
void unregisterModule(String moduleName)

UIServiceTracker

public class UIServiceTracker extends ServiceTracker
Constructors
UIServiceTracker
public UIServiceTracker(BundleContext context, ModuleRegistrationData moduleRegistrationData)
UIServiceTracker
public UIServiceTracker(BundleContextWrapper wrapper, ModuleRegistrationData moduleRegistrationData)
Methods
addingService
public Object addingService(ServiceReference ref)
removedService
public void removedService(ServiceReference ref, Object service)
start
public void start()

UIServiceTrackers

public class UIServiceTrackers
Methods
addTrackerFor
public UIServiceTracker addTrackerFor(Bundle bundle, ApplicationContext applicationContext)
isBeingTracked
public boolean isBeingTracked(Bundle bundle)
removeTrackerFor
public UIServiceTracker removeTrackerFor(Bundle bundle)

WebUIBundleActivator

public class WebUIBundleActivator extends org.motechproject.osgi.web.Activator
Methods
moduleId
protected String moduleId()
resourceFolder
protected String resourceFolder()
resourceMappings
protected Map<String, String> resourceMappings()
start
public void start(BundleContext context)
stop
public void stop(BundleContext context)

org.motechproject.osgi.web.domain

LogMapping

public class LogMapping
Constructors
LogMapping
public LogMapping()
LogMapping
public LogMapping(String logName, String logLevel)
Methods
equals
public boolean equals(Object obj)
getLogLevel
public String getLogLevel()
getLogName
public String getLogName()
hashCode
public int hashCode()
setLogLevel
public void setLogLevel(String logLevel)
setLogName
public void setLogName(String logName)
toString
public String toString()

org.motechproject.osgi.web.exception

RenderException

public class RenderException extends Exception
Constructors
RenderException
public RenderException(String message)
RenderException
public RenderException(String message, Throwable cause)
RenderException
public RenderException(Throwable cause)

ServletRegistrationException

public class ServletRegistrationException extends RuntimeException
Constructors
ServletRegistrationException
public ServletRegistrationException(String message)
ServletRegistrationException
public ServletRegistrationException(String message, Throwable cause)
ServletRegistrationException
public ServletRegistrationException(Throwable cause)

org.motechproject.osgi.web.ext

ApplicationEnvironment

public final class ApplicationEnvironment
Fields
DEVELOPMENT
public static final String DEVELOPMENT
ENVIRONMENT
public static final String ENVIRONMENT
Methods
getEnvironment
public static String getEnvironment()
getModulePath
public static String getModulePath(BundleName bundleName)
isInDevelopmentMode
public static boolean isInDevelopmentMode()

BundleName

public class BundleName
Constructors
BundleName
public BundleName(String bundleSymbolicName)
Methods
equals
public boolean equals(Object bundle)
hashCode
public int hashCode()
underscore
public String underscore()

FileSystemAwareUIHttpContext

public class FileSystemAwareUIHttpContext extends UiHttpContext
Constructors
FileSystemAwareUIHttpContext
public FileSystemAwareUIHttpContext(HttpContext context, String resourceRootDirectoryPath)
Methods
getResource
public URL getResource(String name)
getResourceRootDirectoryPath
public String getResourceRootDirectoryPath()

HttpContextFactory

public final class HttpContextFactory
Methods
getHttpContext
public static HttpContext getHttpContext(HttpContext httpContext, Bundle bundle)

UiHttpContext

public class UiHttpContext implements HttpContext
Constructors
UiHttpContext
public UiHttpContext(HttpContext context)
Methods
getContext
protected HttpContext getContext()
getMimeType
public String getMimeType(String name)
getResource
public URL getResource(String name)
handleSecurity
public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response)

org.motechproject.osgi.web.service

ServerLogService

public interface ServerLogService

Interface for accessing Logger’s configuration from the saved properties

Fields
ROOT_LOGGER_NAME
String ROOT_LOGGER_NAME
Methods
changeLogLevel
void changeLogLevel(String name, String level)
changeRootLogLevel
void changeRootLogLevel(String level)
getAllLogMappings
List<LogMapping> getAllLogMappings()
getLogLevels
List<LogMapping> getLogLevels()
getRootLogLevel
LogMapping getRootLogLevel()
reconfigure
void reconfigure()
removeLogger
void removeLogger(String name)

org.motechproject.osgi.web.settings

Loggers

public class Loggers

Loggers class that holds information about all loggers in our system.

Constructors
Loggers
public Loggers()
Loggers
public Loggers(List<LogMapping> loggers, LogMapping root)
Methods
equals
public boolean equals(Object obj)
getLoggers
public List<LogMapping> getLoggers()
getRoot
public LogMapping getRoot()
getTrash
public List<LogMapping> getTrash()
hashCode
public int hashCode()
setLoggers
public void setLoggers(List<LogMapping> loggers)
setRoot
public void setRoot(LogMapping root)
setTrash
public void setTrash(List<LogMapping> trash)

org.motechproject.osgi.web.util

BundleHeaders

public class BundleHeaders
Constructors
BundleHeaders
public BundleHeaders(BundleContext bundleContext)
BundleHeaders
public BundleHeaders(Bundle bundle)
Methods
get
public Object get(Object key)
getContextPath
public String getContextPath()
getName
public String getName()
getResourcePath
public String getResourcePath()
getStringValue
public String getStringValue(String key)
getSymbolicName
public String getSymbolicName()
getVersion
public String getVersion()
isBluePrintEnabled
public boolean isBluePrintEnabled()

WebBundleUtil

public final class WebBundleUtil

Utility class that’s purpose is easing bundle related operations/searches.

Methods
findBundleByName
public static Bundle findBundleByName(BundleContext bundleContext, String name)
findBundleBySymbolicName
public static Bundle findBundleBySymbolicName(BundleContext bundleContext, String symbolicName)
getContextLocation
public static String getContextLocation(Bundle bundle)
getContextPath
public static String getContextPath(Bundle bundle)
getModuleId
public static String getModuleId(Bundle bundle)

org.motechproject.scheduler.builder

CronJobExpressionBuilder

public class CronJobExpressionBuilder
Constructors
CronJobExpressionBuilder
public CronJobExpressionBuilder(Time startTime, Integer repeatWindowInHours, Integer repeatIntervalInMinutes)
Methods
build
public String build()

CronJobSimpleExpressionBuilder

public class CronJobSimpleExpressionBuilder
Constructors
CronJobSimpleExpressionBuilder
public CronJobSimpleExpressionBuilder(Time startTime)
Methods
build
public String build()
withRepeatIntervalInDays
public CronJobSimpleExpressionBuilder withRepeatIntervalInDays(int repeatIntervalInDays)

WeeklyCronJobExpressionBuilder

public class WeeklyCronJobExpressionBuilder
Constructors
WeeklyCronJobExpressionBuilder
public WeeklyCronJobExpressionBuilder(DayOfWeek dayOfWeek)
WeeklyCronJobExpressionBuilder
public WeeklyCronJobExpressionBuilder(int dayOfWeekNumber)
Methods
build
public String build()
withTime
public WeeklyCronJobExpressionBuilder withTime(Time time)

org.motechproject.scheduler.contract

CronJobId

public class CronJobId extends JobId
Constructors
CronJobId
public CronJobId(String subject, String id)
CronJobId
public CronJobId(MotechEvent event)

CronSchedulableJob

public class CronSchedulableJob implements Serializable

Schedulable Job - a data carrier class for a scheduled job that can be fired unlimited number of times as specified with the cron expression

Author:Igor (iopushnyev@2paths.com) Date: 16/02/11 Time: 1:43 PM
Constructors
CronSchedulableJob
public CronSchedulableJob(MotechEvent motechEvent, String cronExpression, Date startTime, Date endTime)
CronSchedulableJob
public CronSchedulableJob(MotechEvent motechEvent, String cronExpression)
CronSchedulableJob
public CronSchedulableJob(MotechEvent motechEvent, String cronExpression, Date startTime, Date endTime, boolean ignorePastFiresAtStart)
Methods
equals
public boolean equals(Object obj)
getCronExpression
public String getCronExpression()
getEndTime
public Date getEndTime()
getMotechEvent
public MotechEvent getMotechEvent()
getStartTime
public Date getStartTime()
hashCode
public int hashCode()
isIgnorePastFiresAtStart
public boolean isIgnorePastFiresAtStart()
toString
public String toString()

DayOfWeekSchedulableJob

public final class DayOfWeekSchedulableJob implements Serializable

Job that is scheduled on particular days of week

Constructors
DayOfWeekSchedulableJob
public DayOfWeekSchedulableJob(MotechEvent motechEvent, LocalDate start, LocalDate end, List<DayOfWeek> days, Time time, boolean ignorePastFiresAtStart)
DayOfWeekSchedulableJob
public DayOfWeekSchedulableJob(MotechEvent motechEvent, LocalDate start, LocalDate end, List<DayOfWeek> days, Time time)
Methods
getCronDays
public List<Integer> getCronDays()
getEndDate
public LocalDate getEndDate()
getMotechEvent
public MotechEvent getMotechEvent()
getStartDate
public LocalDate getStartDate()
getTime
public Time getTime()
isIgnorePastFiresAtStart
public boolean isIgnorePastFiresAtStart()

EventInfo

public class EventInfo

EventInfo is the class which contains information about event associated with scheduled job.

Constructors
EventInfo
public EventInfo()
Methods
getParameters
public Map<String, Object> getParameters()
getSubject
public String getSubject()
setParameters
public void setParameters(Map<String, Object> parameters)
setSubject
public void setSubject(String subject)

JobBasicInfo

public class JobBasicInfo

JobBasicInfo is the class which contains information about scheduled job and its current state.

Fields
ACTIVITY_ACTIVE
public static final String ACTIVITY_ACTIVE
ACTIVITY_FINISHED
public static final String ACTIVITY_FINISHED
ACTIVITY_NOTSTARTED
public static final String ACTIVITY_NOTSTARTED
JOBTYPE_CRON
public static final String JOBTYPE_CRON
JOBTYPE_REPEATING
public static final String JOBTYPE_REPEATING
JOBTYPE_RUNONCE
public static final String JOBTYPE_RUNONCE
STATUS_BLOCKED
public static final String STATUS_BLOCKED
STATUS_ERROR
public static final String STATUS_ERROR
STATUS_OK
public static final String STATUS_OK
STATUS_PAUSED
public static final String STATUS_PAUSED
Constructors
JobBasicInfo
public JobBasicInfo()
JobBasicInfo
public JobBasicInfo(String activity, String status, String name, String startDate, String nextFireDate, String endDate, String jobType, String info)
Methods
getActivity
public String getActivity()
getEndDate
public String getEndDate()
getInfo
public String getInfo()
getJobType
public String getJobType()
getName
public String getName()
getNextFireDate
public String getNextFireDate()
getStartDate
public String getStartDate()
getStatus
public String getStatus()
setActivity
public void setActivity(String activity)
setEndDate
public void setEndDate(String endDate)
setInfo
public void setInfo(String info)
setJobType
public void setJobType(String jobType)
setName
public void setName(String name)
setNextFireDate
public void setNextFireDate(String nextFireDate)
setStartDate
public void setStartDate(String startDate)
setStatus
public void setStatus(String status)

JobDetailedInfo

public class JobDetailedInfo

JobDetailedInfo is the class which wraps the EventInfo list.

See also: EventInfo

Constructors
JobDetailedInfo
public JobDetailedInfo()
JobDetailedInfo
public JobDetailedInfo(List<EventInfo> eventInfoList)
Methods
getEventInfoList
public List<EventInfo> getEventInfoList()
setEventInfoList
public void setEventInfoList(List<EventInfo> eventInfoList)

JobId

public abstract class JobId implements Serializable
Constructors
JobId
public JobId(String subject, String id, String suffix)
JobId
public JobId(MotechEvent motechEvent, String suffix)
Methods
toString
public String toString()
value
public String value()

RepeatingJobId

public class RepeatingJobId extends JobId
Fields
SUFFIX_REPEATJOBID
public static final String SUFFIX_REPEATJOBID
Constructors
RepeatingJobId
public RepeatingJobId(String subject, String id)
RepeatingJobId
public RepeatingJobId(MotechEvent repeatingEvent)

RepeatingSchedulableJob

public class RepeatingSchedulableJob implements Serializable

Schedulable Job - a data carrier class for a scheduled job that can be fired set number of times

Constructors
RepeatingSchedulableJob
public RepeatingSchedulableJob()
RepeatingSchedulableJob
public RepeatingSchedulableJob(MotechEvent motechEvent, Date startTime, Date endTime, Integer repeatCount, Long repeatIntervalInMilliSeconds, boolean ignorePastFiresAtStart)
RepeatingSchedulableJob
public RepeatingSchedulableJob(MotechEvent motechEvent, Date startTime, Date endTime, Long repeatIntervalInMilliSeconds, boolean ignorePastFiresAtStart)
Methods
equals
public boolean equals(Object obj)
getEndTime
public Date getEndTime()
getMotechEvent
public MotechEvent getMotechEvent()
getRepeatCount
public Integer getRepeatCount()
getRepeatIntervalInMilliSeconds
public Long getRepeatIntervalInMilliSeconds()
getStartTime
public Date getStartTime()
hashCode
public int hashCode()
isIgnorePastFiresAtStart
public boolean isIgnorePastFiresAtStart()
isUseOriginalFireTimeAfterMisfire
public boolean isUseOriginalFireTimeAfterMisfire()
setEndTime
public RepeatingSchedulableJob setEndTime(Date endTime)
setIgnorePastFiresAtStart
public RepeatingSchedulableJob setIgnorePastFiresAtStart(boolean ignorePastFiresAtStart)

Ignore past fires when start time of job is in past.

ex : repeating job with interval of 5 unit, and current time in between fire 2 and 3 will start triggering from 3rd firetime.
 1     2     3     4
 |-----|-----|-----|
 start    ^current time
Parameters:
  • ignorePastFiresAtStart
setMotechEvent
public RepeatingSchedulableJob setMotechEvent(MotechEvent motechEvent)
setRepeatCount
public RepeatingSchedulableJob setRepeatCount(Integer repeatCount)
setRepeatIntervalInMilliSeconds
public RepeatingSchedulableJob setRepeatIntervalInMilliSeconds(Long repeatIntervalInMilliSeconds)
setStartTime
public RepeatingSchedulableJob setStartTime(Date startTime)
setUseOriginalFireTimeAfterMisfire
public RepeatingSchedulableJob setUseOriginalFireTimeAfterMisfire(boolean useOriginalFireTimeAfterMisfire)
toString
public String toString()

RunOnceJobId

public class RunOnceJobId extends JobId
Fields
SUFFIX_RUNONCEJOBID
public static final String SUFFIX_RUNONCEJOBID
Constructors
RunOnceJobId
public RunOnceJobId(String subject, String id)
RunOnceJobId
public RunOnceJobId(MotechEvent runOnceEvent)

RunOnceSchedulableJob

public final class RunOnceSchedulableJob implements Serializable

Run Once Schedulable Job - a data carrier class for a job scheduled in the future that can be fired only once

This class is immutable

User: Igor (iopushnyev@2paths.com) Date: 16/02/11 Time: 1:43 PM

Constructors
RunOnceSchedulableJob
public RunOnceSchedulableJob(MotechEvent motechEvent, Date startDate)

Constructor

Parameters:
  • motechEvent
    • event data message that will be send by Motech Scheduler when this job is fired
  • startDate
    • date and time when the job fill be fired
Throws:
  • IllegalArgumentException – if motechEvent or startDate is null or startDate is in past
Methods
equals
public boolean equals(Object o)
getMotechEvent
public MotechEvent getMotechEvent()
getStartDate
public Date getStartDate()
hashCode
public int hashCode()
toString
public String toString()

org.motechproject.scheduler.exception

MotechSchedulerException

public class MotechSchedulerException extends RuntimeException

User: Igor (iopushnyev@2paths.com) Date: 17/02/11 Time: 4:20 PM

Constructors
MotechSchedulerException
public MotechSchedulerException()
MotechSchedulerException
public MotechSchedulerException(String message)
MotechSchedulerException
public MotechSchedulerException(String message, Throwable cause)
MotechSchedulerException
public MotechSchedulerException(Throwable cause)

SchedulerInstantiationException

public class SchedulerInstantiationException extends RuntimeException
Constructors
SchedulerInstantiationException
public SchedulerInstantiationException(Throwable e)

SchedulerShutdownException

public class SchedulerShutdownException extends RuntimeException

The SchedulerShutdownException exception informs about that there were problems with shutdown scheduler.

Constructors
SchedulerShutdownException
public SchedulerShutdownException(Throwable e)

org.motechproject.scheduler.factory

MotechSchedulerFactoryBean

public class MotechSchedulerFactoryBean

The MotechSchedulerFactoryBean is used to created scheduler and start it.

Constructors
MotechSchedulerFactoryBean
public MotechSchedulerFactoryBean(ApplicationContext applicationContext, Properties schedulerProperties)
Methods
getQuartzScheduler
public Scheduler getQuartzScheduler()
getQuartzSchedulerFactoryBean
public SchedulerFactoryBean getQuartzSchedulerFactoryBean()
init
public void init()
shutdown
public void shutdown()

org.motechproject.scheduler.service

MotechSchedulerActionProxyService

public interface MotechSchedulerActionProxyService
Methods
scheduleCronJob
void scheduleCronJob(String subject, Map<Object, Object> parameters, String cronExpression, DateTime startTime, DateTime endTime, Boolean ignorePastFiresAtStart)
scheduleDayOfWeekJob
void scheduleDayOfWeekJob(String subject, Map<Object, Object> parameters, DateTime start, DateTime end, List<Object> days, DateTime time, Boolean ignorePastFiresAtStart)
scheduleRepeatingJob
void scheduleRepeatingJob(String subject, Map<Object, Object> parameters, DateTime startTime, DateTime endTime, Integer repeatCount, Long repeatIntervalInMilliSeconds, Boolean ignorePastFiresAtStart, Boolean useOriginalFireTimeAfterMisfire)
scheduleRunOnceJob
void scheduleRunOnceJob(String subject, Map<Object, Object> parameters, DateTime startDate)
unscheduleJobs
void unscheduleJobs(String subject)

MotechSchedulerService

public interface MotechSchedulerService

ingroup scheduler Motech Scheduler Service Interface provides methods to schedule reschedule and unschedule a job Set a global policy that determines trigger fire behaviour for misfired triggers. For details see quartz documentations for misfire policy do_nothing -> @see CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING fire_once_now -> @see CronTrigger.MISFIRE_INSTRUCTION_FIRE_ONCE_NOW ignore -> @see CronTrigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY fire_now -> @see SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW ignore -> @see SimpleTrigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY reschedule_next_with_existing_count -> @see SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT reschedule_next_with_remaining_count -> @see SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT reschedule_now_with_existing_count -> @see SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT reschedule_now_with_remaining_count -> @see SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT Scheduler can use couchdb for its job store. To enable set the following properties org.quartz.jobStore.class = org.motechproject.quartz.CouchDbStore org.quartz.jobStore.dbNameGenerator = org.motechproject.scheduler.service.impl.MultiTenantQuartzDatabaseName # provides database names for the jobstore, used in a multi-tenant environment to have separate databases for each tenant; leave blank to use a single database org.quartz.jobStore.properties = # a couchdb.properties file understood by ektorp to specify the database environment

Author:Igor (iopushnyev@2paths.com) Date: 16/02/11
Fields
JOB_ID_KEY
String JOB_ID_KEY
Methods
getScheduledJobDetailedInfo
JobDetailedInfo getScheduledJobDetailedInfo(JobBasicInfo jobBasicInfo)
getScheduledJobTimings
List<Date> getScheduledJobTimings(String subject, String externalJobId, Date startDate, Date endDate)
getScheduledJobTimingsWithPrefix
List<Date> getScheduledJobTimingsWithPrefix(String subject, String externalJobIdPrefix, Date startDate, Date endDate)
getScheduledJobsBasicInfo
List<JobBasicInfo> getScheduledJobsBasicInfo()
rescheduleJob
void rescheduleJob(String subject, String externalId, String cronExpression)

Reschedules a job with the given job ID to be fired according to the given Cron Expression Previous version of the configured Motech Scheduled Even that will be created when the job is fired remains us it was

Parameters:
  • subject
  • externalId
  • cronExpression
safeScheduleJob
void safeScheduleJob(CronSchedulableJob cronSchedulableJob)

Same as scheduleJob, except that it would update existing job if one exists instead of creating a new one

Parameters:
  • cronSchedulableJob
safeScheduleRepeatingJob
void safeScheduleRepeatingJob(RepeatingSchedulableJob repeatingSchedulableJob)

Same as safeScheduleRepeatingJob with intervening = true

Parameters:
  • repeatingSchedulableJob
safeScheduleRunOnceJob
void safeScheduleRunOnceJob(RunOnceSchedulableJob schedulableJob)

Same as scheduleRunOnceJob, except that it would update existing job if one exists instead of creating a new one

Parameters:
  • schedulableJob
safeUnscheduleAllJobs
void safeUnscheduleAllJobs(String jobIdPrefix)
safeUnscheduleJob
void safeUnscheduleJob(String subject, String externalId)

Same as unscheduleJob except that it would not throw an exception if the job doesn’t exist

Parameters:
  • subject
  • externalId
safeUnscheduleRepeatingJob
void safeUnscheduleRepeatingJob(String subject, String externalId)

Same as unscheduleRepeatingJob except that it would not throw an exception if the job doesn’t exist

Parameters:
  • subject
  • externalId
safeUnscheduleRunOnceJob
void safeUnscheduleRunOnceJob(String subject, String externalId)

Same as unscheduleRunOnceJob except that it would not throw an exception if the job doesn’t exist

Parameters:
  • subject
  • externalId
scheduleDayOfWeekJob
void scheduleDayOfWeekJob(DayOfWeekSchedulableJob dayOfWeekSchedulableJob)

Same as safeScheduleDayOfWeekJob with intervening = true

Parameters:
  • dayOfWeekSchedulableJob
scheduleJob
void scheduleJob(CronSchedulableJob cronSchedulableJob)

Schedules the given schedulable job. The Job ID by which the job will be referencing in the future should be provided in an Instance of MotechEvent in SchedulableJob (see MotechEvent.jobId) If a job with the same job ID as the given exists, this job will be unscheduled and the given schedulable job will be scheduled

Parameters:
  • cronSchedulableJob
scheduleRepeatingJob
void scheduleRepeatingJob(RepeatingSchedulableJob repeatingSchedulableJob)

Schedules the given schedulable job. The Job ID by which the job will be referencing in the future should be provided in an Instance of MotechEvent in SchedulableJob (see MotechEvent.jobId) If a job with the same job ID as the given exists, this job will be unscheduled and the given schedulable job will be scheduled

Parameters:
  • repeatingSchedulableJob
scheduleRunOnceJob
void scheduleRunOnceJob(RunOnceSchedulableJob schedulableJob)
unscheduleAllJobs
void unscheduleAllJobs(String jobIdPrefix)
unscheduleJob
void unscheduleJob(String subject, String externalId)

Unschedules a job with the given job ID

Parameters:
  • subject – : String representing domain operation eg. “pill-reminder”, “outbox-call” or motechEvent.getSubject()
  • externalId – : domain specific id as String.
unscheduleJob
void unscheduleJob(JobId job)
unscheduleRepeatingJob
void unscheduleRepeatingJob(String subject, String externalId)
unscheduleRunOnceJob
void unscheduleRunOnceJob(String subject, String externalId)

Unschedules a run once job with the given job ID

Parameters:
  • subject – : String representing domain operation eg. “pill-reminder”, “outbox-call” or motechEvent.getSubject()
  • externalId – : domain specific id as String.
updateScheduledJob
void updateScheduledJob(MotechEvent motechEvent)

Updates MotechEvent data of the job defined by jobIb in the given instance of that class

Parameters:
  • motechEvent

org.motechproject.scheduler.service.impl

MotechScheduledJob

public class MotechScheduledJob implements Job
Methods
execute
public void execute(JobExecutionContext jobExecutionContext)

MotechScheduler

public final class MotechScheduler

ingroup scheduler

Main class that can bootstrap a Motech Scheduler

Author:Igor (iopushnyev@2paths.com)
Methods
main
public static void main(String[] args)

MotechSchedulerActionProxyServiceImpl

public class MotechSchedulerActionProxyServiceImpl implements MotechSchedulerActionProxyService
Constructors
MotechSchedulerActionProxyServiceImpl
public MotechSchedulerActionProxyServiceImpl(MotechSchedulerService schedulerService)
Methods
scheduleCronJob
public void scheduleCronJob(String subject, Map<Object, Object> parameters, String cronExpression, DateTime startTime, DateTime endTime, Boolean ignorePastFiresAtStart)
scheduleDayOfWeekJob
public void scheduleDayOfWeekJob(String subject, Map<Object, Object> parameters, DateTime start, DateTime end, List<Object> days, DateTime time, Boolean ignorePastFiresAtStart)
scheduleRepeatingJob
public void scheduleRepeatingJob(String subject, Map<Object, Object> parameters, DateTime startTime, DateTime endTime, Integer repeatCount, Long repeatIntervalInMilliSeconds, Boolean ignorePastFiresAtStart, Boolean useOriginalFireTimeAfterMisfire)
scheduleRunOnceJob
public void scheduleRunOnceJob(String subject, Map<Object, Object> parameters, DateTime startDate)
unscheduleJobs
public void unscheduleJobs(String subject)

MotechSchedulerServiceImpl

public class MotechSchedulerServiceImpl implements MotechSchedulerService

Motech Scheduler Service implementation

See also: MotechSchedulerService

Fields
JOB_GROUP_NAME
public static final String JOB_GROUP_NAME
Constructors
MotechSchedulerServiceImpl
public MotechSchedulerServiceImpl(MotechSchedulerFactoryBean motechSchedulerFactoryBean, SettingsFacade schedulerSettings)
Methods
assertArgumentNotNull
protected void assertArgumentNotNull(String objectName, Object object)
getScheduledJobDetailedInfo
public JobDetailedInfo getScheduledJobDetailedInfo(JobBasicInfo jobBasicInfo)
getScheduledJobTimings
public List<Date> getScheduledJobTimings(String subject, String externalJobId, Date startDate, Date endDate)
getScheduledJobTimingsWithPrefix
public List<Date> getScheduledJobTimingsWithPrefix(String subject, String externalJobIdPrefix, Date startDate, Date endDate)
getScheduledJobsBasicInfo
public List<JobBasicInfo> getScheduledJobsBasicInfo()
logObjectIfNotNull
protected void logObjectIfNotNull(Object obj)
rescheduleJob
public void rescheduleJob(String subject, String externalId, String cronExpression)
safeScheduleJob
public void safeScheduleJob(CronSchedulableJob cronSchedulableJob)
safeScheduleRepeatingJob
public void safeScheduleRepeatingJob(RepeatingSchedulableJob repeatingSchedulableJob)
safeScheduleRunOnceJob
public void safeScheduleRunOnceJob(RunOnceSchedulableJob schedulableJob)
safeUnscheduleAllJobs
public void safeUnscheduleAllJobs(String jobIdPrefix)
safeUnscheduleJob
public void safeUnscheduleJob(String subject, String externalId)
safeUnscheduleRepeatingJob
public void safeUnscheduleRepeatingJob(String subject, String externalId)
safeUnscheduleRunOnceJob
public void safeUnscheduleRunOnceJob(String subject, String externalId)
scheduleDayOfWeekJob
public void scheduleDayOfWeekJob(DayOfWeekSchedulableJob dayOfWeekSchedulableJob)
scheduleJob
public void scheduleJob(CronSchedulableJob cronSchedulableJob)
scheduleRepeatingJob
public void scheduleRepeatingJob(RepeatingSchedulableJob repeatingSchedulableJob)
scheduleRunOnceJob
public void scheduleRunOnceJob(RunOnceSchedulableJob schedulableJob)
unscheduleAllJobs
public void unscheduleAllJobs(String jobIdPrefix)
unscheduleJob
public void unscheduleJob(String subject, String externalId)
unscheduleJob
public void unscheduleJob(JobId job)
unscheduleRepeatingJob
public void unscheduleRepeatingJob(String subject, String externalId)
unscheduleRunOnceJob
public void unscheduleRunOnceJob(String subject, String externalId)
updateScheduledJob
public void updateScheduledJob(MotechEvent motechEvent)

org.motechproject.security.annotations

SecurityAnnotationBeanPostProcessor

public class SecurityAnnotationBeanPostProcessor implements BeanPostProcessor

A BeanPostProcessor used by Motech to load permissions from modules. Given a module context, it looks for PreAuthorize and PostAuthorize annotations. These annotations are then parsed using an ExpressionParser. The permission names are deduced from hasRole and hasAnyRole in the annotation value. The names of permissions are then saved using the MotechPermissionService. The bundle name used to construct the permission is retrieved from the application context.

Constructors
SecurityAnnotationBeanPostProcessor
public SecurityAnnotationBeanPostProcessor(MotechPermissionService permissionService)
Methods
postProcessAfterInitialization
public Object postProcessAfterInitialization(Object bean, String beanName)
postProcessBeforeInitialization
public Object postProcessBeforeInitialization(Object bean, String beanName)
processAnnotations
public void processAnnotations(ApplicationContext applicationContext)

org.motechproject.security.authentication

MotechAccessVoter

public class MotechAccessVoter implements AccessDecisionVoter<Object>

A custom AccessDecisionVoter for voting on whether a specific user has access to a particular URL. For example, a security rule can specify that the users motech and admin have access to a particular URL. This loads the metadata source with attributes for ACCESS_motech and ACCESS_admin. When a user invokes that URL, an affirmative based voting system will check whether or not the user is motech or admin. If not, they are denied permission, otherwise they are granted access.

Methods
supports
public boolean supports(ConfigAttribute attribute)
supports
public boolean supports(Class<?> clazz)
vote
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes)

MotechBasicAuthenticationEntryPoint

public class MotechBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint

An entry point for BASIC authentications, sets the correct server realm key.

Fields
SECURITY_REALM_KEY
public static final String SECURITY_REALM_KEY
Constructors
MotechBasicAuthenticationEntryPoint
public MotechBasicAuthenticationEntryPoint(SettingsFacade settingsFacade)

MotechLoginUrlAuthenticationEntryPoint

public class MotechLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint
Methods
commence
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)

MotechLogoutSuccessHandler

public class MotechLogoutSuccessHandler implements LogoutHandler

A logout handler for removing Motech user sessions from Motech’s internally kept session handler. This is invoked when a user logs out.

Methods
logout
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication)

MotechPasswordEncoder

public class MotechPasswordEncoder extends BCryptPasswordEncoder
Methods
encodePassword
public String encodePassword(String rawPassword)
isPasswordValid
public boolean isPasswordValid(String encPassword, String rawPassword)

MotechRestBasicAuthenticationEntryPoint

public class MotechRestBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint

A custom entry point that is invoked when there is an authentication exception within the filter. This ensures that when a user does not have login privileges and are unable to authenticate, a 401 unauthorized response is returned.

Fields
SECURITY_REALM_KEY
public static final String SECURITY_REALM_KEY
Constructors
MotechRestBasicAuthenticationEntryPoint
public MotechRestBasicAuthenticationEntryPoint(SettingsFacade settingsFacade)
Methods
commence
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)

MotechSuccessHandler

public class MotechSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler
Methods
onAuthenticationSuccess
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
setSessionHandler
public void setSessionHandler(SessionHandler sessionHandler)

org.motechproject.security.builder

SecurityRuleBuilder

public class SecurityRuleBuilder

The security rule builder is responsible for building a SecurityFilterChain, which consists of a matcher pattern and a list of Spring security filters. The filters are created and configured base upon the security rule’s settings.

Fields
NO_METHODS_REQUIRED_EXCEPTION_MESSAGE
public static final String NO_METHODS_REQUIRED_EXCEPTION_MESSAGE
NO_PATTERN_EXCEPTION_MESSAGE
public static final String NO_PATTERN_EXCEPTION_MESSAGE
NO_PROTOCOL_EXCEPTION_MESSAGE
public static final String NO_PROTOCOL_EXCEPTION_MESSAGE
NO_SUPPORTED_SCHEMES_EXCEPTION_MESSAGE
public static final String NO_SUPPORTED_SCHEMES_EXCEPTION_MESSAGE
Methods
buildSecurityChain
public synchronized SecurityFilterChain buildSecurityChain(MotechURLSecurityRule securityRule, HTTPMethod method)
setAuthenticationManager
public void setAuthenticationManager(AuthenticationManager authenticationManager)
setBasicAuthenticationEntryPoint
public void setBasicAuthenticationEntryPoint(AuthenticationEntryPoint basicAuthenticationEntryPoint)
setChannelDecisionManager
public void setChannelDecisionManager(ChannelDecisionManager channelDecisionManager)
setLoginAuthenticationEntryPoint
public void setLoginAuthenticationEntryPoint(AuthenticationEntryPoint loginAuthenticationEntryPoint)
setMotechLogoutHandler
public void setMotechLogoutHandler(MotechLogoutSuccessHandler motechLogoutHandler)
setOpenIDAuthenticationFilter
public void setOpenIDAuthenticationFilter(OpenIDAuthenticationFilter openIDAuthenticationFilter)
setSettingsFacade
public void setSettingsFacade(SettingsFacade settingsFacade)
setUsernamePasswordAuthenticationFilter
public void setUsernamePasswordAuthenticationFilter(UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter)

org.motechproject.security.constants

HTTPMethod

public enum HTTPMethod

Enumeration of HTTP request method.

Enum Constants
ANY
public static final HTTPMethod ANY
DELETE
public static final HTTPMethod DELETE
GET
public static final HTTPMethod GET
OPTIONS
public static final HTTPMethod OPTIONS
POST
public static final HTTPMethod POST
PUT
public static final HTTPMethod PUT
TRACE
public static final HTTPMethod TRACE

PermissionNames

public final class PermissionNames
Fields
ACTIVATE_USER_PERMISSION
public static final String ACTIVATE_USER_PERMISSION
ADD_USER_PERMISSION
public static final String ADD_USER_PERMISSION
DELETE_USER_PERMISSION
public static final String DELETE_USER_PERMISSION
EDIT_USER_PERMISSION
public static final String EDIT_USER_PERMISSION
MANAGE_PERMISSION_PERMISSION
public static final String MANAGE_PERMISSION_PERMISSION
MANAGE_ROLE_PERMISSION
public static final String MANAGE_ROLE_PERMISSION
MANAGE_USER_PERMISSION
public static final String MANAGE_USER_PERMISSION
VIEW_BASIC_EMAIL_LOGS_PERMISSION
public static final String VIEW_BASIC_EMAIL_LOGS_PERMISSION
VIEW_DETAILED_EMAIL_LOGS_PERMISSION
public static final String VIEW_DETAILED_EMAIL_LOGS_PERMISSION
VIEW_SECURITY
public static final String VIEW_SECURITY

Protocol

public enum Protocol

Enumeration of Protocols supported by the module

Enum Constants
HTTP
public static final Protocol HTTP
HTTPS
public static final Protocol HTTPS

Scheme

public enum Scheme

Enumeration of scheme supported by the module

Enum Constants
BASIC
public static final Scheme BASIC
NO_SECURITY
public static final Scheme NO_SECURITY
OATH
public static final Scheme OATH

not supported yet

OPEN_ID
public static final Scheme OPEN_ID
USERNAME_PASSWORD
public static final Scheme USERNAME_PASSWORD

SecurityConfigConstants

public final class SecurityConfigConstants

A class for holding constants related to the options available for dynamic security rules. MotechURLSecurityRule is where these options are used. Prefixes related to security voting are also stored in this class.

Fields
ANY_PATTERN
public static final String ANY_PATTERN
ROLE_ACCESS_PREFIX
public static final String ROLE_ACCESS_PREFIX
USER_ACCESS_PREFIX
public static final String USER_ACCESS_PREFIX

org.motechproject.security.domain

MotechPermission

public class MotechPermission
Constructors
MotechPermission
public MotechPermission()
MotechPermission
public MotechPermission(String permissionName, String bundleName)
Methods
getBundleName
public String getBundleName()
getPermissionName
public String getPermissionName()
setBundleName
public void setBundleName(String bundleName)
setPermissionName
public void setPermissionName(String permissionName)
toString
public String toString()

MotechRole

public class MotechRole
Constructors
MotechRole
public MotechRole()
MotechRole
public MotechRole(String roleName, List<String> permissionNames, boolean deletable)
Methods
getPermissionNames
public List<String> getPermissionNames()
getRoleName
public String getRoleName()
hasPermission
public boolean hasPermission(String permissionName)
isDeletable
public boolean isDeletable()
removePermission
public void removePermission(String permissionName)
setDeletable
public void setDeletable(boolean deletable)
setPermissionNames
public void setPermissionNames(List<String> permissionNames)
setRoleName
public void setRoleName(String roleName)

MotechSecurityConfiguration

public class MotechSecurityConfiguration

The MotechSecurityConfiguration is a single document that contains all of the URL security rule configuration. The configuration was designed as one document because the entire filter chain must be reconstructed each time it is updated, therefore managing many references is unnecessary.

Constructors
MotechSecurityConfiguration
public MotechSecurityConfiguration()
MotechSecurityConfiguration
public MotechSecurityConfiguration(List<MotechURLSecurityRule> securityRules)
Methods
getSecurityRules
public List<MotechURLSecurityRule> getSecurityRules()
setSecurityRules
public void setSecurityRules(List<MotechURLSecurityRule> securityRules)

MotechURLSecurityRule

public class MotechURLSecurityRule

The MotechURLSecurityRule specifies the configuration for setting up a Spring SecurityFilterChain.

Details regarding configuration:

  • pattern - URL pattern the security rule applies to
  • supportedSchemes - Security rules that should apply to the URL, such as BASIC or OPEN_ID
  • protocol - Protocol the security rule applies to, such as HTTP or HTTPS
  • permissionAccess - Requires user has at least one of the listed permission to access the URL
  • userAccess - User specific access for a URL, such as motech or admin, when combined with permission access they act as an either or (one must be true)
  • priority - For future use in determining the ordering of filter chains, may be deprecated depending on UI implementation
  • rest - Whether the endpoint is meant for a form login process or as an REST end-point that does not create a session for the
  • origin - The module or user the rule originated from
  • version - The version of the module or platform the rule was created
  • methodsRequired - HTTP methods the rule applies to, if ANY is used then any method is matched, if a set is used, such as GET, POST, etc, then each will have its own corresponding filter chain with the same security found in that rule
Methods
getId
public Long getId()
getMethodsRequired
public List<HTTPMethod> getMethodsRequired()
getOrigin
public String getOrigin()
getPattern
public String getPattern()
getPermissionAccess
public List<String> getPermissionAccess()
getPriority
public int getPriority()
getProtocol
public Protocol getProtocol()
getSupportedSchemes
public List<Scheme> getSupportedSchemes()
getUserAccess
public List<String> getUserAccess()
getVersion
public String getVersion()
isActive
public boolean isActive()
isDeleted
public boolean isDeleted()
isRest
public boolean isRest()
setActive
public void setActive(boolean active)
setDeleted
public void setDeleted(boolean deleted)
setId
public void setId(Long id)
setMethodsRequired
public void setMethodsRequired(List<HTTPMethod> methodsRequired)
setOrigin
public void setOrigin(String origin)
setPattern
public void setPattern(String pattern)
setPermissionAccess
public void setPermissionAccess(List<String> permissionAccess)
setPriority
public void setPriority(int priority)
setProtocol
public void setProtocol(Protocol protocol)
setRest
public void setRest(boolean rest)
setSupportedSchemes
public void setSupportedSchemes(List<Scheme> supportedSchemes)
setUserAccess
public void setUserAccess(List<String> userAccess)
setVersion
public void setVersion(String version)

MotechUser

public class MotechUser
Constructors
MotechUser
public MotechUser()
MotechUser
public MotechUser(String userName, String password, String email, String externalId, List<String> roles, String openId, Locale locale)
Methods
equals
public boolean equals(Object o)
getEmail
public String getEmail()
getExternalId
public String getExternalId()
getLocale
public Locale getLocale()
getOpenId
public String getOpenId()
getPassword
public String getPassword()
getRoles
public List<String> getRoles()
getUserName
public String getUserName()
hasRole
public boolean hasRole(String role)
hashCode
public int hashCode()
isActive
public boolean isActive()
setActive
public void setActive(boolean active)
setEmail
public void setEmail(String email)
setExternalId
public void setExternalId(String externalId)
setLocale
public void setLocale(Locale locale)
setOpenId
public void setOpenId(String openId)
setPassword
public void setPassword(String password)
setRoles
public void setRoles(List<String> roles)
setUserName
public void setUserName(String userName)
toString
public String toString()

MotechUserProfile

public class MotechUserProfile implements Serializable
Constructors
MotechUserProfile
public MotechUserProfile(MotechUser user)
Methods
getExternalId
public String getExternalId()
getLocale
public Locale getLocale()
getRoles
public List<String> getRoles()
getUserName
public String getUserName()
hasRole
public boolean hasRole(String role)
isActive
public boolean isActive()

PasswordRecovery

public class PasswordRecovery
Methods
getEmail
public String getEmail()
getExpirationDate
public DateTime getExpirationDate()
getLocale
public Locale getLocale()
getToken
public String getToken()
getUsername
public String getUsername()
setEmail
public void setEmail(String email)
setExpirationDate
public void setExpirationDate(DateTime expirationDate)
setLocale
public void setLocale(Locale locale)
setToken
public void setToken(String token)
setUsername
public void setUsername(String username)

org.motechproject.security.ex

EmailExistsException

public class EmailExistsException extends RuntimeException
Constructors
EmailExistsException
public EmailExistsException(String message)

InvalidTokenException

public class InvalidTokenException extends Exception
Constructors
InvalidTokenException
public InvalidTokenException()
InvalidTokenException
public InvalidTokenException(String message)

NonAdminUserException

public class NonAdminUserException extends Exception
Constructors
NonAdminUserException
public NonAdminUserException(String message)

RoleHasUserException

public class RoleHasUserException extends RuntimeException

Represents a failed attempt to delete a role currently assigned to a user.

Constructors
RoleHasUserException
public RoleHasUserException(String message)

SecurityConfigException

public class SecurityConfigException extends RuntimeException

A runtime exception thrown when the security config does not pass validation constraints required in order to construct a new security chain. Ideally should not be thrown as the UI should not allow invalid data to be submitted.

Constructors
SecurityConfigException
public SecurityConfigException(String message)

UserNotFoundException

public class UserNotFoundException extends Exception
Constructors
UserNotFoundException
public UserNotFoundException()
UserNotFoundException
public UserNotFoundException(String message)

org.motechproject.security.model

PermissionDto

public class PermissionDto implements Serializable

The PermissionDto contains information about permission.

Constructors
PermissionDto
public PermissionDto()
PermissionDto
public PermissionDto(MotechPermission motechPermission)
PermissionDto
public PermissionDto(String permissionName, String bundleName)
Methods
equals
public boolean equals(Object obj)
getBundleName
public String getBundleName()
getPermissionName
public String getPermissionName()
hashCode
public int hashCode()
setBundleName
public void setBundleName(String bundleName)
setPermissionName
public void setPermissionName(String permissionName)
toString
public String toString()

RoleDto

public class RoleDto

Transfer Motech role data between representations.

Role data transfer object facilitates exchange of role data among services, repository, and client user interface.

Constructors
RoleDto
public RoleDto()
RoleDto
public RoleDto(MotechRole motechRole)
RoleDto
public RoleDto(String roleName, List<String> permissionNames)
RoleDto
public RoleDto(String roleName, List<String> permissionNames, boolean deletable)
Methods
equals
public boolean equals(Object obj)
getOriginalRoleName
public String getOriginalRoleName()
getPermissionNames
public List<String> getPermissionNames()
getRoleName
public String getRoleName()
hashCode
public int hashCode()
isDeletable
public boolean isDeletable()
setDeletable
public void setDeletable(boolean deletable)
setOriginalRoleName
public void setOriginalRoleName(String originalRoleName)
setPermissionNames
public void setPermissionNames(List<String> permissionNames)
setRoleName
public void setRoleName(String roleName)
toString
public String toString()

SecurityConfigDto

public class SecurityConfigDto

Used to transfer security configuration to and from a web request and UI

Methods
getSecurityRules
public List<SecurityRuleDto> getSecurityRules()
setSecurityRules
public void setSecurityRules(List<SecurityRuleDto> securityRules)

SecurityRuleDto

public class SecurityRuleDto

Transfer Motech security rule data between representations.

Methods
getId
public Long getId()
getMethodsRequired
public List<String> getMethodsRequired()
getOrigin
public String getOrigin()
getPattern
public String getPattern()
getPermissionAccess
public List<String> getPermissionAccess()
getPriority
public int getPriority()
getProtocol
public String getProtocol()
getSupportedSchemes
public List<String> getSupportedSchemes()
getUserAccess
public List<String> getUserAccess()
getVersion
public String getVersion()
isActive
public boolean isActive()
isDeleted
public boolean isDeleted()
isRest
public boolean isRest()
setActive
public void setActive(boolean active)
setDeleted
public void setDeleted(boolean deleted)
setId
public void setId(Long id)
setMethodsRequired
public void setMethodsRequired(List<String> methodsRequired)
setOrigin
public void setOrigin(String origin)
setPattern
public void setPattern(String pattern)
setPermissionAccess
public void setPermissionAccess(List<String> permissionAccess)
setPriority
public void setPriority(int priority)
setProtocol
public void setProtocol(String protocol)
setRest
public void setRest(boolean rest)
setSupportedSchemes
public void setSupportedSchemes(List<String> supportedSchemes)
setUserAccess
public void setUserAccess(List<String> userAccess)
setVersion
public void setVersion(String version)

UserDto

public class UserDto
Constructors
UserDto
public UserDto()
UserDto
public UserDto(MotechUser motechUser)
Methods
getEmail
public String getEmail()
getExternalId
public String getExternalId()
getLocale
public Locale getLocale()
getOpenId
public String getOpenId()
getPassword
public String getPassword()
getRoles
public List<String> getRoles()
getUserName
public String getUserName()
isActive
public boolean isActive()
isGeneratePassword
public boolean isGeneratePassword()
setActive
public void setActive(boolean active)
setEmail
public void setEmail(String email)
setExternalId
public void setExternalId(String externalId)
setGeneratePassword
public void setGeneratePassword(boolean generatePassword)
setLocale
public void setLocale(Locale locale)
setOpenId
public void setOpenId(String openId)
setPassword
public void setPassword(String password)
setRoles
public void setRoles(List<String> roles)
setUserName
public void setUserName(String userName)

org.motechproject.security.repository

AllMotechPermissions

public class AllMotechPermissions
Methods
add
public void add(MotechPermission permission)
delete
public void delete(MotechPermission permission)
findByPermissionName
public MotechPermission findByPermissionName(String permissionName)
getPermissions
public List<MotechPermission> getPermissions()
setDataService
public void setDataService(MotechPermissionsDataService dataService)

AllMotechRoles

public class AllMotechRoles
Methods
add
public void add(MotechRole role)
findByRoleName
public MotechRole findByRoleName(String roleName)
getRoles
public List<MotechRole> getRoles()
remove
public void remove(MotechRole motechRole)
setDataService
public void setDataService(MotechRolesDataService dataService)
update
public void update(MotechRole motechRole)

AllMotechSecurityRules

public class AllMotechSecurityRules

Implementation of DAO interface that utilizes a MDS back-end for storage. Only one MotechSecurityConfiguration file should be saved at a time, so adding the document looks for the old document in order to update it if it already exists. Rather than updating the object reference, the old configuration’s ID and revision are used for the new document.

Methods
addOrUpdate
public void addOrUpdate(MotechSecurityConfiguration config)
getMotechSecurityConfiguration
public MotechSecurityConfiguration getMotechSecurityConfiguration()
getRuleById
public MotechURLSecurityRule getRuleById(Long id)
getRules
public List<MotechURLSecurityRule> getRules()
getRulesByOrigin
public List<MotechURLSecurityRule> getRulesByOrigin(String origin)
remove
public void remove(MotechSecurityConfiguration config)
setDataService
public void setDataService(MotechURLSecurityRuleDataService dataService)

AllMotechUsers

public class AllMotechUsers
Methods
add
public void add(MotechUser user)
addOpenIdUser
public void addOpenIdUser(MotechUser user)
findByRole
public List<MotechUser> findByRole(String role)
findByUserName
public MotechUser findByUserName(String userName)
findUserByEmail
public MotechUser findUserByEmail(String email)
findUserByOpenId
public MotechUser findUserByOpenId(String openId)
getOpenIdUsers
public List<MotechUser> getOpenIdUsers()
getUsers
public List<MotechUser> getUsers()
remove
public void remove(MotechUser motechUser)
setDataService
public void setDataService(MotechUsersDataService dataService)
update
public void update(MotechUser motechUser)

AllPasswordRecoveries

public class AllPasswordRecoveries
Methods
add
public void add(PasswordRecovery passwordRecovery)
allRecoveries
public List<PasswordRecovery> allRecoveries()
createRecovery
public PasswordRecovery createRecovery(String username, String email, String token, DateTime expirationDate, Locale locale)
findForToken
public PasswordRecovery findForToken(String token)
findForUser
public PasswordRecovery findForUser(String username)
getExpired
public List<PasswordRecovery> getExpired()
remove
public void remove(PasswordRecovery passwordRecovery)
setDataService
public void setDataService(PasswordRecoveriesDataService dataService)
update
public void update(PasswordRecovery passwordRecovery)

MotechPermissionsDataService

public interface MotechPermissionsDataService extends MotechDataService<MotechPermission>
Methods
findByPermissionName
MotechPermission findByPermissionName(String permissionName)

MotechRolesDataService

public interface MotechRolesDataService extends MotechDataService<MotechRole>
Methods
findByRoleName
MotechRole findByRoleName(String roleName)

MotechURLSecurityRuleDataService

public interface MotechURLSecurityRuleDataService extends MotechDataService<MotechURLSecurityRule>
Methods
findByOrigin
List<MotechURLSecurityRule> findByOrigin(String origin)

MotechUsersDataService

public interface MotechUsersDataService extends MotechDataService<MotechUser>
Methods
findByEmail
MotechUser findByEmail(String email)
findByOpenId
MotechUser findByOpenId(String openId)
findByRole
List<MotechUser> findByRole(String role)
findByUserName
MotechUser findByUserName(String userName)

PasswordRecoveriesDataService

public interface PasswordRecoveriesDataService extends MotechDataService<PasswordRecovery>
Methods
findByExpirationDate
List<PasswordRecovery> findByExpirationDate(Range<DateTime> range)
findForToken
PasswordRecovery findForToken(String token)
findForUser
PasswordRecovery findForUser(String username)

org.motechproject.security.service

AuthoritiesService

public interface AuthoritiesService

Service interface to retrieve authorities(permissions) for a given MotechUser

Methods
authoritiesFor
List<GrantedAuthority> authoritiesFor(MotechUser user)

MotechPermissionService

public interface MotechPermissionService

Service for managing Motech permissions.

Methods
addPermission
void addPermission(PermissionDto permission)
deletePermission
void deletePermission(String permissionName)
getPermissions
List<PermissionDto> getPermissions()

MotechProxyManager

public class MotechProxyManager

The MotechProxyManager acts as a wrapper around Spring’s FilterChainProxy. The FilterChainProxy contains a list of immutable SecurityFilterChain objects which Spring’s security consults for filters when handling requests. In order to dynamically define new secure, a new FilterChainProxy is constructed and the reference is updated. The MotechProxyManager acts as a customized delegate in MotechDelegatingFilterProxy.

Methods
getDefaultSecurityConfiguration
public MotechSecurityConfiguration getDefaultSecurityConfiguration()

This method reads default security configuration from the file containing security rules and returns it.

Returns:MotechSecurityConfiguration default security rules
getFilterChainProxy
public FilterChainProxy getFilterChainProxy()
initializeProxyChain
public void initializeProxyChain()

This method serves the same purpose of rebuildProxyChain, but does not require any kind of security authentication so it should only ever be used by the activator, which does not have an authentication object.

rebuildProxyChain
public synchronized void rebuildProxyChain()

Method to invoke to dynamically re-define the Spring security. All rules converted into security filter chains in order to create a new FilterChainProxy. The order of the rules in the list matters for filtering purposes.

setProxy
public void setProxy(FilterChainProxy proxy)
setSecurityRuleBuilder
public void setSecurityRuleBuilder(SecurityRuleBuilder securityRuleBuilder)
setSecurityRulesDAO
public void setSecurityRulesDAO(AllMotechSecurityRules securityRulesDAO)

MotechRoleService

public interface MotechRoleService
Methods
createRole
void createRole(RoleDto role)
deleteRole
void deleteRole(RoleDto role)
getRole
RoleDto getRole(String roleName)
getRoles
List<RoleDto> getRoles()
updateRole
void updateRole(RoleDto role)

MotechURLSecurityService

public interface MotechURLSecurityService

Service to access and update security configuration details from the platform. Permission based, method level security is defined to prevent unauthorized users from updating security.

Methods
findAllSecurityRules
List<SecurityRuleDto> findAllSecurityRules()

A protected method for viewing security rule information for the platform.

Returns:All URL security rules found in the database
updateSecurityConfiguration
void updateSecurityConfiguration(SecurityConfigDto configuration)

A protected method for updating security configuration for the platform.

Parameters:
  • configuration – The updated security information, which will cause an updating of the motech proxy manager

MotechUserService

public interface MotechUserService

Service interface that defines APIs to retrieve and manage user details

Methods
activateUser
void activateUser(String username)
changePassword
MotechUserProfile changePassword(String username, String oldPassword, String newPassword)
deleteUser
void deleteUser(UserDto user)
getCurrentUser
UserDto getCurrentUser()
getLocale
Locale getLocale(String userName)
getOpenIdUsers
List<MotechUserProfile> getOpenIdUsers()
getRoles
List<String> getRoles(String userName)
getUser
UserDto getUser(String userName)
getUserByEmail
UserDto getUserByEmail(String email)
getUsers
List<MotechUserProfile> getUsers()
hasActiveAdminUser
boolean hasActiveAdminUser()
hasUser
boolean hasUser(String username)
register
void register(String username, String password, String email, String externalId, List<String> roles, Locale locale)
register
void register(String username, String password, String email, String externalId, List<String> roles, Locale locale, boolean isActive, String openId)
retrieveUserByCredentials
MotechUserProfile retrieveUserByCredentials(String username, String password)
sendLoginInformation
void sendLoginInformation(String userName, String password)
setLocale
void setLocale(String userName, Locale locale)
updateUserDetailsWithPassword
void updateUserDetailsWithPassword(UserDto user)
updateUserDetailsWithoutPassword
void updateUserDetailsWithoutPassword(UserDto user)

PasswordRecoveryService

public interface PasswordRecoveryService
Methods
cleanUpExpiredRecoveries
void cleanUpExpiredRecoveries()
oneTimeTokenOpenId
void oneTimeTokenOpenId(String email)
passwordRecoveryRequest
void passwordRecoveryRequest(String email)
resetPassword
void resetPassword(String token, String password, String passwordConfirmation)
validateToken
boolean validateToken(String token)
validateTokenAndLoginUser
void validateTokenAndLoginUser(String token, HttpServletRequest request, HttpServletResponse response)

SecurityRoleLoader

public class SecurityRoleLoader
Constructors
SecurityRoleLoader
public SecurityRoleLoader(MotechRoleService roleService)
Methods
loadRoles
public void loadRoles(ApplicationContext applicationContext)

SecurityRuleLoader

public class SecurityRuleLoader

Helper class that scans an application context for security rules and re-initializes the MotechProxyManager security chain.

Methods
loadRules
public synchronized void loadRules(ApplicationContext applicationContext)

Attempts to load rules from the application context, if rules are found, the security configuration is updated. Synchronized so there are not race conditions on the data.

setAllSecurityRules
public void setAllSecurityRules(AllMotechSecurityRules allSecurityRules)
setProxyManager
public void setProxyManager(MotechProxyManager proxyManager)

UserContextService

public interface UserContextService

Interface to refresh user context (all or specified username)

Methods
refreshAllUsersContextIfActive
void refreshAllUsersContextIfActive()
refreshUserContextIfActive
void refreshUserContextIfActive(String userName)

org.motechproject.server.api

BundleIcon

public class BundleIcon
Fields
ICON_LOCATIONS
public static final String[] ICON_LOCATIONS
Constructors
BundleIcon
public BundleIcon(byte[] icon, String mime)
Methods
getContentLength
public int getContentLength()
getIcon
public byte[] getIcon()
getMime
public String getMime()

BundleInformation

public class BundleInformation

Class acting as a DTO for a Bundle in the system.

Fields
BUNDLE_NAME
protected static final String BUNDLE_NAME
Constructors
BundleInformation
public BundleInformation(Bundle bundle)
Methods
equals
public boolean equals(Object arg0)
getAngularModule
public String getAngularModule()
getBundleId
public long getBundleId()
getLocation
public String getLocation()
getModuleName
public String getModuleName()
getName
public String getName()
getSettingsURL
public String getSettingsURL()
getState
public State getState()
getSymbolicName
public String getSymbolicName()
getVersion
public Version getVersion()
hasStatus
public boolean hasStatus(int status)
hashCode
public int hashCode()
setAngularModule
public void setAngularModule(String angularModule)
setModuleName
public void setModuleName(String moduleName)
setSettingsURL
public void setSettingsURL(String settingsURL)

BundleInformation.State

public enum State

Represents the bundle state.

Enum Constants
ACTIVE
public static final BundleInformation.State ACTIVE
INSTALLED
public static final BundleInformation.State INSTALLED
RESOLVED
public static final BundleInformation.State RESOLVED
STARTING
public static final BundleInformation.State STARTING
STOPPING
public static final BundleInformation.State STOPPING
UNINSTALLED
public static final BundleInformation.State UNINSTALLED
UNKNOWN
public static final BundleInformation.State UNKNOWN

BundleLoader

public interface BundleLoader

Interface for custom bundle loading processes

Author:Ricky Wang
Methods
loadBundle
void loadBundle(Bundle bundle)
Parameters:
  • bundle
Throws:

BundleLoadingException

public class BundleLoadingException extends Exception
Constructors
BundleLoadingException
public BundleLoadingException(String message)
BundleLoadingException
public BundleLoadingException(String message, Throwable cause)
BundleLoadingException
public BundleLoadingException(Throwable cause)

JarInformation

public class JarInformation
Fields
BUNDLE_SYMBOLIC_NAME
public static final String BUNDLE_SYMBOLIC_NAME
BUNDLE_VERSION
public static final String BUNDLE_VERSION
EXTRACTION_FAILED
public static final String EXTRACTION_FAILED
IMPLEMENTATION_TITLE
public static final String IMPLEMENTATION_TITLE
IMPLEMENTATION_VENDOR_ID
public static final String IMPLEMENTATION_VENDOR_ID
IMPLEMENTATION_VERSION
public static final String IMPLEMENTATION_VERSION
Constructors
JarInformation
public JarInformation(File file)
Methods
getBundleSymbolicName
public String getBundleSymbolicName()
getBundleVersion
public String getBundleVersion()
getFilename
public String getFilename()
getImplementationTitle
public String getImplementationTitle()
getImplementationVendorID
public String getImplementationVendorID()
getImplementationVersion
public String getImplementationVersion()
getPath
public String getPath()

JarInformationHandler

public class JarInformationHandler
Fields
JAR_FILE_EXTENSION
public static final String JAR_FILE_EXTENSION
Constructors
JarInformationHandler
public JarInformationHandler(String path)
Methods
extractJarInformationFromPath
public void extractJarInformationFromPath()
getJarList
public List<JarInformation> getJarList()
getPath
public String getPath()
initHandler
public void initHandler()

org.motechproject.server.config

SettingsFacade

public class SettingsFacade

SettingsFacade provides an interface to access application configuration present in files or database

Methods
afterPropertiesSet
public void afterPropertiesSet()
areConfigurationSettingsRegistered
public boolean areConfigurationSettingsRegistered()
asProperties
public Properties asProperties()
constructSymbolicName
protected String constructSymbolicName()
findFilename
protected String findFilename(String key)
getActivemqConfig
public Properties getActivemqConfig()
getModuleName
public String getModuleName()
getPlatformSettings
public MotechSettings getPlatformSettings()
getProperties
public Properties getProperties(String filename)
getProperty
public String getProperty(String key)
getProperty
public String getProperty(String key, String filename)
getRawConfig
public InputStream getRawConfig(String filename)
getResourceFileName
protected static String getResourceFileName(Resource resource)
getSymbolicName
public String getSymbolicName()
registerAllProperties
protected void registerAllProperties()
registerAllRawConfig
protected void registerAllRawConfig()
registerProperties
protected void registerProperties(String filename, Properties properties)
saveConfigProperties
public void saveConfigProperties(String filename, Properties properties)
savePlatformSettings
public void savePlatformSettings(MotechSettings settings)
saveRawConfig
public void saveRawConfig(String filename, Resource resource)
setConfigFiles
public void setConfigFiles(List<Resource> resources)
setConfigurationService
public void setConfigurationService(ConfigurationService configurationService)
setModuleName
public void setModuleName(String moduleName)
setProperty
public void setProperty(String key, String value)
setRawConfigFiles
public void setRawConfigFiles(List<Resource> resources)
unregisterProperties
public void unregisterProperties(String symbolicName)

org.motechproject.server.config.domain

LoginMode

public final class LoginMode

Encapsulates the operations on login mode

Fields
OPEN_ID
public static final LoginMode OPEN_ID
REPOSITORY
public static final LoginMode REPOSITORY
Methods
getName
public String getName()
isOpenId
public boolean isOpenId()
isRepository
public boolean isRepository()
valueOf
public static LoginMode valueOf(String loginMode)

MotechSettings

public interface MotechSettings

Interface for main motech settings managment

Methods
asProperties
Properties asProperties()
getActivemqProperties
Properties getActivemqProperties()
getConfigFileChecksum
String getConfigFileChecksum()
getFilePath
String getFilePath()
getLanguage
String getLanguage()
getLastRun
DateTime getLastRun()
getLoginMode
LoginMode getLoginMode()
getProviderName
String getProviderName()
getProviderUrl
String getProviderUrl()
getServerHost
String getServerHost()
getServerUrl
String getServerUrl()
getStatusMsgTimeout
String getStatusMsgTimeout()
getUploadSize
String getUploadSize()
isPlatformInitialized
boolean isPlatformInitialized()
load
void load(DigestInputStream dis)
savePlatformSetting
void savePlatformSetting(String key, String value)
setConfigFileChecksum
void setConfigFileChecksum(String configFileChecksum)
setFilePath
void setFilePath(String filePath)
setLanguage
void setLanguage(String language)
setLastRun
void setLastRun(DateTime lastRun)
setLoginModeValue
void setLoginModeValue(String loginMode)
setPlatformInitialized
void setPlatformInitialized(boolean platformInitialized)
setProviderName
void setProviderName(String providerName)
setProviderUrl
void setProviderUrl(String providerUrl)
setServerUrl
void setServerUrl(String serverUrl)
setStatusMsgTimeout
void setStatusMsgTimeout(String statusMsgTimeout)
setUploadSize
void setUploadSize(String uploadSize)
updateFromProperties
void updateFromProperties(Properties props)
updateSettings
void updateSettings(String configFileChecksum, String filePath, Properties platformSettings)

MotechURL

public class MotechURL
Fields
URL_PATTERN
public static final String URL_PATTERN
Constructors
MotechURL
public MotechURL(String url)
Methods
getHost
public String getHost()
toString
public String toString()

SettingsRecord

public class SettingsRecord implements MotechSettings

Class for storing settings values

Constructors
SettingsRecord
public SettingsRecord()
Methods
asProperties
public Properties asProperties()
getActivemqProperties
public Properties getActivemqProperties()
getConfigFileChecksum
public String getConfigFileChecksum()
getFilePath
public String getFilePath()
getLanguage
public String getLanguage()
getLastRun
public DateTime getLastRun()
getLoginMode
public LoginMode getLoginMode()
getLoginModeValue
public String getLoginModeValue()
getPlatformSettings
public Map<String, String> getPlatformSettings()
getProviderName
public String getProviderName()
getProviderUrl
public String getProviderUrl()
getServerHost
public String getServerHost()
getServerUrl
public String getServerUrl()
getStatusMsgTimeout
public String getStatusMsgTimeout()
getUploadSize
public String getUploadSize()
isPlatformInitialized
public boolean isPlatformInitialized()
load
public synchronized void load(DigestInputStream dis)
mergeWithDefaults
public void mergeWithDefaults(Properties defaultConfig)
removeDefaults
public void removeDefaults(Properties defaultConfig)
savePlatformSetting
public void savePlatformSetting(String key, String value)
setConfigFileChecksum
public void setConfigFileChecksum(String configFileChecksum)
setFilePath
public void setFilePath(String filePath)
setLanguage
public void setLanguage(String language)
setLastRun
public void setLastRun(DateTime lastRun)
setLoginModeValue
public void setLoginModeValue(String loginMode)
setPlatformInitialized
public void setPlatformInitialized(boolean platformInitialized)
setPlatformSettings
public void setPlatformSettings(Map<String, String> platformSettings)
setProviderName
public void setProviderName(String providerName)
setProviderUrl
public void setProviderUrl(String providerUrl)
setServerUrl
public void setServerUrl(String serverUrl)
setStatusMsgTimeout
public void setStatusMsgTimeout(String statusMsgTimeout)
setUploadSize
public void setUploadSize(String uploadSize)
updateFromProperties
public void updateFromProperties(Properties props)
updateSettings
public void updateSettings(String configFileChecksum, String filePath, Properties platformSettings)

org.motechproject.server.config.service

ConfigLoader

public class ConfigLoader

Config loader used to load the platform core settings.

Methods
findExistingConfigs
public List<File> findExistingConfigs()

Finds all configs from the config location

Throws:
  • IOException – If there is any error while handling the files.
loadDefaultConfig
public SettingsRecord loadDefaultConfig()
loadMotechSettings
public SettingsRecord loadMotechSettings()
setCoreConfigurationService
public void setCoreConfigurationService(CoreConfigurationService coreConfigurationService)
setEventAdmin
public void setEventAdmin(EventAdmin eventAdmin)
setResourceLoader
public void setResourceLoader(ResourceLoader resourceLoader)

PlatformSettingsService

public interface PlatformSettingsService

Platform Settings service used to handle platform settings.

Methods
exportPlatformSettings
Properties exportPlatformSettings()

SettingService

public interface SettingService extends MotechDataService<SettingsRecord>

org.motechproject.server.startup

MotechPlatformState

public enum MotechPlatformState

Defines the different states of the MOTECH system.

Enum Constants
DB_ERROR
public static final MotechPlatformState DB_ERROR
FIRST_RUN
public static final MotechPlatformState FIRST_RUN
NEED_BOOTSTRAP_CONFIG
public static final MotechPlatformState NEED_BOOTSTRAP_CONFIG
NEED_CONFIG
public static final MotechPlatformState NEED_CONFIG
NORMAL_RUN
public static final MotechPlatformState NORMAL_RUN
NO_DB
public static final MotechPlatformState NO_DB
STARTUP
public static final MotechPlatformState STARTUP

StartupManager

public class StartupManager

StartupManager controlling and managing the application loading

Methods
canLaunchBundles
public boolean canLaunchBundles()
getDefaultSettings
public SettingsRecord getDefaultSettings()

This function is only called when the default configuration is loaded and is no config in the database or external files

isBootstrapConfigRequired
public boolean isBootstrapConfigRequired()
isConfigRequired
public boolean isConfigRequired()
startup
public void startup()

org.motechproject.server.ui

LocaleService

public interface LocaleService

A service responsible for localization. Allows retrieval/settings of user language as well as retrieving localized messages for a user request. Can also be used to retrieve a list of usable languages.

Methods
getMessages
Map<String, String> getMessages(HttpServletRequest request)
getSupportedLanguages
NavigableMap<String, String> getSupportedLanguages()
getUserLocale
Locale getUserLocale(HttpServletRequest request)
setUserLocale
void setUserLocale(HttpServletRequest request, HttpServletResponse response, Locale locale)

org.motechproject.server.ui.ex

AlreadyRegisteredException

public class AlreadyRegisteredException extends RuntimeException
Constructors
AlreadyRegisteredException
public AlreadyRegisteredException(String msg)

org.motechproject.server.web.controller

Constants

public final class Constants

Class that has all the common UI constants.

Fields
REDIRECT_BOOTSTRAP
public static final String REDIRECT_BOOTSTRAP
REDIRECT_HOME
public static final String REDIRECT_HOME
REDIRECT_STARTUP
public static final String REDIRECT_STARTUP

DashboardController

public class DashboardController

Main application controller. Responsible for retrieving information shared across the UI of different modules. The view returned by this controller will embed the UI of the currently requested module.

Methods
accessdenied
public ModelAndView accessdenied(HttpServletRequest request)
getTime
public String getTime(HttpServletRequest request)
getUptime
public DateTime getUptime()
getUser
public UserInfo getUser(HttpServletRequest request)
index
public ModelAndView index(HttpServletRequest request)
setBundleContext
public void setBundleContext(BundleContext bundleContext)
setLocaleService
public void setLocaleService(LocaleService localeService)
setStartupManager
public void setStartupManager(StartupManager startupManager)

ForgotController

public class ForgotController

Forgot Controller for reset password.

Methods
forgotPost
public String forgotPost(String email)
getForgotViewData
public ForgotViewData getForgotViewData(HttpServletRequest request)
login
public ModelAndView login(HttpServletRequest request)

LocaleController

public class LocaleController

The LocaleController class is responsible for handling requests connected with internationalization

Methods
getAvailableLocales
public Map<String, String> getAvailableLocales(HttpServletRequest request)
getLangLocalisation
public Map<String, String> getLangLocalisation(HttpServletRequest request)
getSupportedLanguages
public NavigableMap<String, String> getSupportedLanguages()
getUserLang
public String getUserLang(HttpServletRequest request)
setUserLang
public void setUserLang(HttpServletRequest request, HttpServletResponse response, String language, String country, String variant)

LoginController

public class LoginController

Login Controller for user authentication.

Methods
getLoginViewData
public LoginViewData getLoginViewData(HttpServletRequest request)
login
public ModelAndView login(HttpServletRequest request)

ModuleController

public class ModuleController
Methods
getConfig
public List<ModuleConfig> getConfig()
getCriticalMessage
public String getCriticalMessage(String moduleName)
getMenu
public ModuleMenu getMenu(HttpServletRequest request)
getUser
public UserInfo getUser(HttpServletRequest request)
setBundleContext
public void setBundleContext(BundleContext bundleContext)
setLocaleService
public void setLocaleService(LocaleService localeService)
setMenuBuilder
public void setMenuBuilder(MenuBuilder menuBuilder)
setUiFrameworkService
public void setUiFrameworkService(UIFrameworkService uiFrameworkService)

ResetController

public class ResetController
Methods
getResetViewData
public ResetViewData getResetViewData(HttpServletRequest request)
reset
public ResetViewData reset(ResetForm form, HttpServletRequest request)
resetView
public ModelAndView resetView(HttpServletRequest request)

StartupController

public class StartupController

StartupController that manages the platform system start up and captures the platform core settings and user information.

Methods
getStartupViewData
public StartupViewData getStartupViewData(HttpServletRequest request)
setStartupFormValidatorFactory
public void setStartupFormValidatorFactory(StartupFormValidatorFactory validatorFactory)
startup
public ModelAndView startup()
submitForm
public List<String> submitForm(StartupForm startupSettings)

StatusController

public class StatusController
Methods
status
public String status()

org.motechproject.server.web.form

LoginForm

public class LoginForm
Methods
getPassword
public String getPassword()
getUserName
public String getUserName()
setPassword
public void setPassword(String password)
setUserName
public void setUserName(String userName)

ResetForm

public class ResetForm
Fields
PASSWORD
public static final String PASSWORD
PASSWORD_CONFIRMATION
public static final String PASSWORD_CONFIRMATION
Methods
getPassword
public String getPassword()
getPasswordConfirmation
public String getPasswordConfirmation()
getToken
public String getToken()
setPassword
public void setPassword(String password)
setPasswordConfirmation
public void setPasswordConfirmation(String passwordConfirmation)
setToken
public void setToken(String token)

StartupForm

public class StartupForm
Fields
ADMIN_CONFIRM_PASSWORD
public static final String ADMIN_CONFIRM_PASSWORD
ADMIN_LOGIN
public static final String ADMIN_LOGIN
ADMIN_PASSWORD
public static final String ADMIN_PASSWORD
LANGUAGE
public static final String LANGUAGE
LOGIN_MODE
public static final String LOGIN_MODE
PROVIDER_NAME
public static final String PROVIDER_NAME
PROVIDER_URL
public static final String PROVIDER_URL
QUEUE_URL
public static final String QUEUE_URL
Methods
getAdminConfirmPassword
public String getAdminConfirmPassword()
getAdminEmail
public String getAdminEmail()
getAdminLogin
public String getAdminLogin()
getAdminPassword
public String getAdminPassword()
getLanguage
public String getLanguage()
getLoginMode
public String getLoginMode()
getProviderName
public String getProviderName()
getProviderUrl
public String getProviderUrl()
getQueueUrl
public String getQueueUrl()
getSchedulerUrl
public String getSchedulerUrl()
setAdminConfirmPassword
public void setAdminConfirmPassword(String adminConfirmPassword)
setAdminEmail
public void setAdminEmail(String adminEmail)
setAdminLogin
public void setAdminLogin(String adminLogin)
setAdminPassword
public void setAdminPassword(String adminPassword)
setLanguage
public void setLanguage(String language)
setLoginMode
public void setLoginMode(String loginMode)
setProviderName
public void setProviderName(String providerName)
setProviderUrl
public void setProviderUrl(String providerUrl)
setQueueUrl
public void setQueueUrl(String queueUrl)
setSchedulerUrl
public void setSchedulerUrl(String schedulerUrl)

StartupSuggestionsForm

public class StartupSuggestionsForm
Constructors
StartupSuggestionsForm
public StartupSuggestionsForm()
Methods
addDatabaseSuggestion
public void addDatabaseSuggestion(String suggestion)
addQueueSuggestion
public void addQueueSuggestion(String suggestion)
addSchedulerSuggestion
public void addSchedulerSuggestion(String suggestion)
getDatabaseUrls
public List<String> getDatabaseUrls()
getQueueUrls
public List<String> getQueueUrls()
getSchedulerUrls
public List<String> getSchedulerUrls()

UserInfo

public class UserInfo
Constructors
UserInfo
public UserInfo(String userName, boolean securityLaunch, String lang)
Methods
equals
public boolean equals(Object obj)
getLang
public String getLang()
getUserName
public String getUserName()
hashCode
public int hashCode()
isSecurityLaunch
public boolean isSecurityLaunch()
toString
public String toString()

org.motechproject.server.web.helper

Header.ElementOrder

public static class ElementOrder
Methods
getAfter
public String getAfter()
getBefore
public String getBefore()
getOrder
public String getOrder()
getPath
public String getPath()
setAfter
public void setAfter(String after)
setBefore
public void setBefore(String before)
setOrder
public void setOrder(String order)
setPath
public void setPath(String path)

Header.HeaderOrder

public static class HeaderOrder
Methods
getCss
public List<ElementOrder> getCss()
getJs
public List<ElementOrder> getJs()
getLib
public List<ElementOrder> getLib()
setCss
public void setCss(List<ElementOrder> css)
setJs
public void setJs(List<ElementOrder> js)
setLib
public void setLib(List<ElementOrder> lib)

SuggestionHelper

public class SuggestionHelper

Helper class for creating UI suggestions for the user. Checks default locations for available services.

Fields
DEFAULT_ACTIVEMQ_URL
public static final String DEFAULT_ACTIVEMQ_URL
Methods
suggestActivemqUrl
public String suggestActivemqUrl()

Suggests the ActiveMQ url.

Returns:The suggested url, or an empty string if the instance is not found.

org.motechproject.server.web.validator

AbstractValidator

public interface AbstractValidator

Basic interface which startup settings validators implement

Methods
validate
void validate(StartupForm target, List<String> errors, ConfigSource configSource)

OpenIdUserValidator

public class OpenIdUserValidator implements AbstractValidator

Validates presence of OpenId related field values Also validates provider URL

Constructors
OpenIdUserValidator
public OpenIdUserValidator(UrlValidator urlValidator)
Methods
validate
public void validate(StartupForm target, List<String> errors, ConfigSource configSource)

PersistedUserValidator

public class PersistedUserValidator implements AbstractValidator

Validates presence of admin user registration fields. Checks existence of user with identical name Checks existence of user with identical email Checks that password and confirmed password field are same.

Constructors
PersistedUserValidator
public PersistedUserValidator(MotechUserService userService)
Methods
validate
public void validate(StartupForm target, List<String> errors, ConfigSource configSource)

QueueURLValidator

public class QueueURLValidator implements AbstractValidator

Validates presence of Queue URL and if present whether it is in expected format or not

Constructors
QueueURLValidator
public QueueURLValidator()
QueueURLValidator
public QueueURLValidator(UrlValidator urlValidator)
Methods
validate
public void validate(StartupForm target, List<String> errors, ConfigSource configSource)

RequiredFieldValidator

public class RequiredFieldValidator implements AbstractValidator

Generic validator class that validates presence of a given field

Fields
ERROR_REQUIRED
public static final String ERROR_REQUIRED
Constructors
RequiredFieldValidator
public RequiredFieldValidator(String fieldName, String fieldValue)
Methods
equals
public boolean equals(Object o)
hashCode
public int hashCode()
validate
public void validate(StartupForm target, List<String> errors, ConfigSource configSource)

ResetFormValidator

public class ResetFormValidator
Methods
validate
public List<String> validate(ResetForm target)

StartupFormValidator

public class StartupFormValidator

StartupFormValidator validates user information during registration process

Constructors
StartupFormValidator
public StartupFormValidator()
Methods
add
public void add(AbstractValidator validator)
getValidators
public List<AbstractValidator> getValidators()
validate
public List<String> validate(StartupForm target, ConfigSource configSource)

StartupFormValidatorFactory

public class StartupFormValidatorFactory

Factory to create startUpFormValidator with requisite validators. If Admin User exists,the admin user is not created so the relevant validators are not added.

Methods
getStartupFormValidator
public StartupFormValidator getStartupFormValidator(StartupForm startupSettings, MotechUserService userService)

UserRegistrationValidator

public class UserRegistrationValidator implements AbstractValidator

Validator to validate user registration details. Delegates to either @OpenIdUserValidator or @UserRegistrationValidator depending on login mode preference.

Constructors
UserRegistrationValidator
public UserRegistrationValidator(PersistedUserValidator persistedUserValidator, OpenIdUserValidator openIdUserValidator)
Methods
validate
public void validate(StartupForm target, List<String> errors, ConfigSource configSource)

ValidationUtils

public final class ValidationUtils

Validation utils that consists of common validations that can be used across multiple controllers.

Methods
validateEmptyOrWhitespace
public static void validateEmptyOrWhitespace(Errors errors, String errorMessageFormat, String... fields)
validateUrl
public static void validateUrl(Errors errors, String dbUrlField)

org.motechproject.tasks.annotations

TaskAction

public @interface TaskAction

TaskActionParam

public @interface TaskActionParam

Marks method parameter to be treated as action parameter.

Each parameter in the given method has to have this annotation otherwise it will be a problem with the proper execution of the channel action.

See also: TaskAction, TaskChannel, TaskAnnotationBeanPostProcessor

TaskAnnotationBeanPostProcessor

public class TaskAnnotationBeanPostProcessor implements BeanPostProcessor

Factory class which is looking for classes with TaskChannel annotation to add them to the channel definition as channel action.

See also: TaskAction, TaskActionParam, TaskChannel

Constructors
TaskAnnotationBeanPostProcessor
public TaskAnnotationBeanPostProcessor(BundleContext bundleContext, ChannelService channelService)
Methods
postProcessAfterInitialization
public Object postProcessAfterInitialization(Object bean, String beanName)
postProcessBeforeInitialization
public Object postProcessBeforeInitialization(Object bean, String beanName)
processAnnotations
public void processAnnotations(ApplicationContext applicationContext)

TaskChannel

public @interface TaskChannel

org.motechproject.tasks.contract

ActionEventRequest

public class ActionEventRequest
Constructors
ActionEventRequest
public ActionEventRequest(String displayName, String subject, String description, String serviceInterface, String serviceMethod, SortedSet<ActionParameterRequest> actionParameters)
ActionEventRequest
public ActionEventRequest(String displayName, String subject, String description, String serviceInterface, String serviceMethod)
Methods
addParameter
public void addParameter(ActionParameterRequest parameter, boolean changeOrder)
equals
public boolean equals(Object obj)
getActionParameters
public SortedSet<ActionParameterRequest> getActionParameters()
getDescription
public String getDescription()
getDisplayName
public String getDisplayName()
getServiceInterface
public String getServiceInterface()
getServiceMethod
public String getServiceMethod()
getSubject
public String getSubject()
hasService
public boolean hasService()
hasSubject
public boolean hasSubject()
hashCode
public int hashCode()
isValid
public boolean isValid()
toString
public String toString()

ActionParameterRequest

public class ActionParameterRequest implements Comparable<ActionParameterRequest>

Object representation of a parameter in the channel action request definition.

See also: ActionEventRequest

Constructors
ActionParameterRequest
public ActionParameterRequest(String key, String displayName, Integer order, String type, boolean required)
ActionParameterRequest
public ActionParameterRequest(String key, String displayName, Integer order, String type)
ActionParameterRequest
public ActionParameterRequest(String key, String displayName, Integer order)
ActionParameterRequest
public ActionParameterRequest(String key, String displayName)
Methods
compareTo
public int compareTo(ActionParameterRequest o)
equals
public boolean equals(Object obj)
getDisplayName
public String getDisplayName()
getKey
public String getKey()
getOrder
public Integer getOrder()
getType
public String getType()
hashCode
public int hashCode()
isRequired
public boolean isRequired()
setOrder
public void setOrder(int order)
toString
public String toString()

ChannelRequest

public class ChannelRequest

Service layer object denoting a org.motechproject.tasks.domain.Channel. Used by ChannelService

Constructors
ChannelRequest
public ChannelRequest(String displayName, String moduleName, String moduleVersion, String description, List<TriggerEventRequest> triggerTaskEvents, List<ActionEventRequest> actionTaskEvents)
Methods
equals
public boolean equals(Object obj)
getActionTaskEvents
public List<ActionEventRequest> getActionTaskEvents()
getDescription
public String getDescription()
getDisplayName
public String getDisplayName()
getModuleName
public String getModuleName()
getModuleVersion
public String getModuleVersion()
getTriggerTaskEvents
public List<TriggerEventRequest> getTriggerTaskEvents()
hashCode
public int hashCode()
setModuleName
public void setModuleName(String moduleName)
setModuleVersion
public void setModuleVersion(String moduleVersion)
toString
public String toString()

EventParameterRequest

public class EventParameterRequest
Constructors
EventParameterRequest
public EventParameterRequest(String displayName, String eventKey, String type)
EventParameterRequest
public EventParameterRequest(String displayName, String eventKey)
Methods
equals
public boolean equals(Object obj)
getDisplayName
public String getDisplayName()
getEventKey
public String getEventKey()
getType
public String getType()
hashCode
public int hashCode()
toString
public String toString()

TriggerEventRequest

public class TriggerEventRequest
Constructors
TriggerEventRequest
public TriggerEventRequest(String displayName, String subject, String description, List<EventParameterRequest> eventParameters)
Methods
equals
public boolean equals(Object obj)
getDescription
public String getDescription()
getDisplayName
public String getDisplayName()
getEventParameters
public List<EventParameterRequest> getEventParameters()
getSubject
public String getSubject()
hashCode
public int hashCode()
toString
public String toString()

org.motechproject.tasks.domain

ActionEvent

public class ActionEvent extends TaskEvent
Constructors
ActionEvent
public ActionEvent()
ActionEvent
public ActionEvent(String displayName, String subject, String description, SortedSet<ActionParameter> actionParameters)
ActionEvent
public ActionEvent(String displayName, String description, String serviceInterface, String serviceMethod, SortedSet<ActionParameter> actionParameters)
ActionEvent
public ActionEvent(String displayName, String subject, String description, String serviceInterface, String serviceMethod, SortedSet<ActionParameter> actionParameters)
ActionEvent
public ActionEvent(ActionEventRequest actionEventRequest)
Methods
accept
public boolean accept(TaskActionInformation info)
addParameter
public void addParameter(ActionParameter parameter, boolean changeOrder)
containsParameter
public boolean containsParameter(String key)
equals
public boolean equals(Object obj)
getActionParameters
public SortedSet<ActionParameter> getActionParameters()
getServiceInterface
public String getServiceInterface()
getServiceMethod
public String getServiceMethod()
hasService
public boolean hasService()
hashCode
public int hashCode()
setActionParameters
public void setActionParameters(SortedSet<ActionParameter> actionParameters)
setServiceInterface
public void setServiceInterface(String serviceInterface)
setServiceMethod
public void setServiceMethod(String serviceMethod)
toString
public String toString()

ActionParameter

public class ActionParameter extends Parameter implements Comparable<ActionParameter>

Object representation of a parameter in the channel action definition.

See also: ActionEvent

Constructors
ActionParameter
public ActionParameter()
ActionParameter
public ActionParameter(String displayName, String key)
ActionParameter
public ActionParameter(String displayName, String key, boolean required)
ActionParameter
public ActionParameter(String displayName, String key, Integer order)
ActionParameter
public ActionParameter(String displayName, String key, ParameterType type)
ActionParameter
public ActionParameter(String displayName, String key, ParameterType type, boolean required)
ActionParameter
public ActionParameter(String displayName, String key, ParameterType type, Integer order)
ActionParameter
public ActionParameter(ActionParameterRequest actionParameterRequest)
ActionParameter
public ActionParameter(String displayName, String key, ParameterType type, Integer order, boolean required)
Methods
compareTo
public int compareTo(ActionParameter o)
equals
public boolean equals(Object obj)
getKey
public String getKey()
getOrder
public Integer getOrder()
hashCode
public int hashCode()
isRequired
public boolean isRequired()
setKey
public void setKey(String key)
setOrder
public void setOrder(Integer order)
setRequired
public void setRequired(boolean required)
toString
public String toString()

Channel

public class Channel
Constructors
Channel
public Channel()
Channel
public Channel(String displayName, String moduleName, String moduleVersion)
Channel
public Channel(String displayName, String moduleName, String moduleVersion, String description, List<TriggerEvent> triggerTaskEvents, List<ActionEvent> actionTaskEvents)
Channel
public Channel(ChannelRequest channelRequest)
Methods
addActionTaskEvent
public void addActionTaskEvent(ActionEvent actionEvent)
containsAction
public boolean containsAction(TaskActionInformation actionInformation)
containsTrigger
public boolean containsTrigger(TaskTriggerInformation triggerInformation)
equals
public boolean equals(Object obj)
getAction
public ActionEvent getAction(TaskActionInformation actionInformation)
getActionTaskEvents
public List<ActionEvent> getActionTaskEvents()
getDescription
public String getDescription()
getDisplayName
public String getDisplayName()
getModuleName
public String getModuleName()
getModuleVersion
public String getModuleVersion()
getTrigger
public TriggerEvent getTrigger(TaskTriggerInformation triggerInformation)
getTriggerTaskEvents
public List<TriggerEvent> getTriggerTaskEvents()
hashCode
public int hashCode()
setActionTaskEvents
public void setActionTaskEvents(List<ActionEvent> actionTaskEvents)
setDescription
public void setDescription(String description)
setDisplayName
public void setDisplayName(String displayName)
setModuleName
public void setModuleName(String moduleName)
setModuleVersion
public void setModuleVersion(String moduleVersion)
setTriggerTaskEvents
public void setTriggerTaskEvents(List<TriggerEvent> triggerTaskEvents)
toString
public String toString()

ChannelRegisterEvent

public class ChannelRegisterEvent

A wrapper over a MotechEvent with subject {@value EventSubjects#CHANNEL_REGISTER_SUBJECT}. Raised when a channel is registered with the tasks module

Constructors
ChannelRegisterEvent
public ChannelRegisterEvent(String moduleName)
ChannelRegisterEvent
public ChannelRegisterEvent(MotechEvent motechEvent)
Methods
getChannelModuleName
public String getChannelModuleName()
toMotechEvent
public MotechEvent toMotechEvent()

DataSource

public class DataSource extends TaskConfigStep
Constructors
DataSource
public DataSource()
DataSource
public DataSource(Long providerId, Long objectId, String type, String name, List<Lookup> lookup, boolean failIfDataNotFound)
DataSource
public DataSource(String providerName, Long providerId, Long objectId, String type, String name, List<Lookup> lookup, boolean failIfDataNotFound)
Methods
equals
public boolean equals(Object obj)
getLookup
public List<Lookup> getLookup()
getName
public String getName()
getObjectId
public Long getObjectId()
getProviderId
public Long getProviderId()
getProviderName
public String getProviderName()
getType
public String getType()
hashCode
public int hashCode()
isFailIfDataNotFound
public boolean isFailIfDataNotFound()
objectEquals
public boolean objectEquals(Long providerId, Long objectId, String type)
setFailIfDataNotFound
public void setFailIfDataNotFound(boolean failIfDataNotFound)
setLookup
public void setLookup(Object lookup)
setName
public void setName(String name)
setObjectId
public void setObjectId(Long objectId)
setProviderId
public void setProviderId(Long providerId)
setProviderName
public void setProviderName(String providerName)
setType
public void setType(String type)
toString
public String toString()

EventParameter

public class EventParameter extends Parameter
Constructors
EventParameter
public EventParameter()
EventParameter
public EventParameter(String displayName, String eventKey)
EventParameter
public EventParameter(String displayName, String eventKey, ParameterType type)
EventParameter
public EventParameter(EventParameterRequest eventParameterRequest)
Methods
equals
public boolean equals(Object obj)
getEventKey
public String getEventKey()
hashCode
public int hashCode()
setEventKey
public void setEventKey(String eventKey)
toString
public String toString()

FieldParameter

public class FieldParameter extends Parameter
Constructors
FieldParameter
public FieldParameter()
FieldParameter
public FieldParameter(String displayName, String fieldKey)
FieldParameter
public FieldParameter(String displayName, String fieldKey, ParameterType type)
Methods
equals
public boolean equals(Object obj)
getFieldKey
public String getFieldKey()
hashCode
public int hashCode()
setFieldKey
public void setFieldKey(String fieldKey)
toString
public String toString()

Filter

public class Filter implements Serializable
Constructors
Filter
public Filter()
Filter
public Filter(EventParameter eventParameter, boolean negationOperator, String operator, String expression)
Filter
public Filter(String displayName, String key, ParameterType type, boolean negationOperator, String operator, String expression)
Methods
equals
public boolean equals(Object obj)
getDisplayName
public String getDisplayName()
getExpression
public String getExpression()
getKey
public String getKey()
getOperator
public String getOperator()
getType
public ParameterType getType()
hashCode
public int hashCode()
isNegationOperator
public boolean isNegationOperator()
setDisplayName
public void setDisplayName(String displayName)
setExpression
public void setExpression(String expression)
setKey
public void setKey(String key)
setNegationOperator
public void setNegationOperator(boolean negationOperator)
setOperator
public void setOperator(String operator)
setType
public void setType(ParameterType type)
toString
public String toString()

FilterSet

public class FilterSet extends TaskConfigStep
Constructors
FilterSet
public FilterSet()
FilterSet
public FilterSet(List<Filter> filters)
Methods
addFilter
public void addFilter(Filter filter)
equals
public boolean equals(Object obj)
getFilters
public List<Filter> getFilters()
hashCode
public int hashCode()
setFilters
public void setFilters(List<Filter> filters)
toString
public String toString()

KeyInformation

public final class KeyInformation

Object representation of dragged field from trigger or data source.

This class represents a single dragged field from trigger or data source. This class does not expose a public constructor. You have to use parse(String) method if you want to parse single field or parseAll(String) if you want ot get all fields from a given string.

Fields
ADDITIONAL_DATA_PREFIX
public static final String ADDITIONAL_DATA_PREFIX

Prefix which is used for data source fields.

TRIGGER_PREFIX
public static final String TRIGGER_PREFIX

Prefix which is used for trigger fields.

Methods
equals
public boolean equals(Object obj)
fromAdditionalData
public boolean fromAdditionalData()

Check if the field is from the data source.

Returns:true if the field is from the data source otherwise false
fromTrigger
public boolean fromTrigger()

Check if the field is from the trigger.

Returns:true if the field is from the trigger otherwise false
getDataProviderId
public Long getDataProviderId()
getKey
public String getKey()
getManipulations
public List<String> getManipulations()

Get manipulations assigned to the field.

Returns:list of manipulations
getObjectId
public Long getObjectId()
getObjectType
public String getObjectType()
getOriginalKey
public String getOriginalKey()

Get original representation of the dragged field.

Returns:string representation of the field
getPrefix
public String getPrefix()
hasManipulations
public boolean hasManipulations()

Check if the field has any manipulations.

Returns:true if the field has manipulations otherwise false
hashCode
public int hashCode()
parse
public static KeyInformation parse(String input)

Parse given string to instance of KeyInformation.

This method should be used to convert string representation of dragged field to instance of KeyInformation.

Argument has adhere to one of the following format:

  • trigger field format: trigger.eventKey
  • data source format: ad.dataProviderId.objectType#objectId.fieldKey

Argument can also contain list of manipulation which should be executed on field before it will be used by org.motechproject.tasks.service.TaskTriggerHandler class. Manipulations should be connected together by the ? character.

Example of input argument:

  • ad.279f5fdf60700d9717270b1ae3011eb1.CaseInfo#0.fieldValues.phu_id
  • trigger.message?format(Ala,cat)?capitalize
Parameters:
  • input – string representation of a dragged field from trigger or data source
Throws:
  • IllegalArgumentException – exception is thrown if format for data source field is incorrect or if the dragged field is not from trigger or data source.
Returns:

Object representation of a dragged field

parseAll
public static List<KeyInformation> parseAll(String input)

Find all fields from given input and convert them to the instance of KeyInformation.

This method should be used to find and convert all of string representation of the field from trigger and/or data sources. Fields in input have to adhere to one of the following formats:

  • trigger field format: {{trigger.eventKey}}
  • data source format: {{ad.dataProviderId.objectType#objectId.fieldKey}}

To find fields in the input argument this method uses regular expression. When field is found it is converted to an instance of KeyInformation by using the parse(String) method.

Fields are found by the following regular expression: {{((.*?))(}})(?![^(]*)). The expression searches for strings that start with {{ and end with }} and are not within ( and ). Because of manipulations which contain additional data in (...) needed to execute manipulation on the field (e.g.: join needs to have the join character) and the text in (...) can be another string representation of the dragged field, the expression has to check if the field has this kind of manipulation.

Example of input argument:

  • {{trigger.message?format(Ala,cat)?capitalize}}
  • You get the following message: {{trigger.message}}
Parameters:
  • input – string with one or more string representation of dragged fields from trigger and/or data sources
Throws:
Returns:

list of object representation of dragged fields.

Lookup

public class Lookup implements Serializable
Constructors
Lookup
public Lookup()
Lookup
public Lookup(String field, String value)
Methods
equals
public boolean equals(Object obj)
getField
public String getField()
getValue
public String getValue()
hashCode
public int hashCode()
setField
public void setField(String field)
setValue
public void setValue(String value)

LookupFieldsParameter

public class LookupFieldsParameter
Constructors
LookupFieldsParameter
public LookupFieldsParameter()
LookupFieldsParameter
public LookupFieldsParameter(String displayName, List<String> fields)
Methods
equals
public boolean equals(Object obj)
getDisplayName
public String getDisplayName()
getFields
public List<String> getFields()
hashCode
public int hashCode()
setDisplayName
public void setDisplayName(String displayName)
setFields
public void setFields(List<String> fields)
toString
public String toString()

ManipulationTarget

public enum ManipulationTarget

Defines the target of various manipulations used in a task for both triggers and data sources.

Enum Constants
ALL
public static final ManipulationTarget ALL
DATE
public static final ManipulationTarget DATE
STRING
public static final ManipulationTarget STRING

ManipulationType

public enum ManipulationType

Defines the type of various manipulations used in a task for both triggers and data sources.

Enum Constants
CAPITALIZE
public static final ManipulationType CAPITALIZE
DATETIME
public static final ManipulationType DATETIME
FORMAT
public static final ManipulationType FORMAT
JOIN
public static final ManipulationType JOIN
PLUSDAYS
public static final ManipulationType PLUSDAYS
SPLIT
public static final ManipulationType SPLIT
SUBSTRING
public static final ManipulationType SUBSTRING
TOLOWER
public static final ManipulationType TOLOWER
TOUPPER
public static final ManipulationType TOUPPER
UNKNOWN
public static final ManipulationType UNKNOWN

OperatorType

public enum OperatorType

Object representation of available operators in filter definition.

Enum Constants
AFTER
public static final OperatorType AFTER
AFTER_NOW
public static final OperatorType AFTER_NOW
BEFORE
public static final OperatorType BEFORE
BEFORE_NOW
public static final OperatorType BEFORE_NOW
CONTAINS
public static final OperatorType CONTAINS
ENDSWITH
public static final OperatorType ENDSWITH
EQUALS
public static final OperatorType EQUALS
EQ_NUMBER
public static final OperatorType EQ_NUMBER
EXIST
public static final OperatorType EXIST
GT
public static final OperatorType GT
LESS_DAYS_FROM_NOW
public static final OperatorType LESS_DAYS_FROM_NOW
LESS_MONTHS_FROM_NOW
public static final OperatorType LESS_MONTHS_FROM_NOW
LT
public static final OperatorType LT
MORE_DAYS_FROM_NOW
public static final OperatorType MORE_DAYS_FROM_NOW
MORE_MONTHS_FROM_NOW
public static final OperatorType MORE_MONTHS_FROM_NOW
STARTSWITH
public static final OperatorType STARTSWITH

Parameter

public abstract class Parameter implements Serializable
Constructors
Parameter
protected Parameter()
Parameter
protected Parameter(String displayName, ParameterType type)
Methods
equals
public boolean equals(Object obj)
getDisplayName
public String getDisplayName()
getType
public ParameterType getType()
hashCode
public int hashCode()
setDisplayName
public void setDisplayName(String displayName)
setType
public void setType(ParameterType type)
toString
public String toString()

ParameterType

public enum ParameterType

Defines the type of various values used in a task including trigger parameters, action parameters and data source object fields.

Enum Constants
BOOLEAN
public static final ParameterType BOOLEAN
DATE
public static final ParameterType DATE
DOUBLE
public static final ParameterType DOUBLE
INTEGER
public static final ParameterType INTEGER
LIST
public static final ParameterType LIST
LONG
public static final ParameterType LONG
MAP
public static final ParameterType MAP
TEXTAREA
public static final ParameterType TEXTAREA
TIME
public static final ParameterType TIME
UNICODE
public static final ParameterType UNICODE
UNKNOWN
public static final ParameterType UNKNOWN

SettingsDto

public class SettingsDto
Methods
getTaskPossibleErrors
public String getTaskPossibleErrors()
isValid
public boolean isValid()
setTaskPossibleErrors
public void setTaskPossibleErrors(String taskPossibleErrors)

Task

public class Task

A task is set of actions that are executed in response to a trigger. The actions and the trigger are defined by their respective Channels.

Constructors
Task
public Task()
Task
public Task(String name, TaskTriggerInformation trigger, List<TaskActionInformation> actions)
Task
public Task(String name, TaskTriggerInformation trigger, List<TaskActionInformation> actions, TaskConfig taskConfig, boolean enabled, boolean hasRegisteredChannel)
Methods
addAction
public void addAction(TaskActionInformation action)
addValidationErrors
public void addValidationErrors(Set<TaskError> validationErrors)
equals
public boolean equals(Object obj)
getActions
public List<TaskActionInformation> getActions()
getDescription
public String getDescription()
getId
public Long getId()
getName
public String getName()
getTaskConfig
public TaskConfig getTaskConfig()
getTrigger
public TaskTriggerInformation getTrigger()
getValidationErrors
public Set<TaskError> getValidationErrors()
hasRegisteredChannel
public boolean hasRegisteredChannel()
hasValidationErrors
public boolean hasValidationErrors()
hashCode
public int hashCode()
isEnabled
public boolean isEnabled()
removeValidationError
public void removeValidationError(String message)
setActions
public void setActions(List<TaskActionInformation> actions)
setDescription
public void setDescription(String description)
setEnabled
public void setEnabled(boolean enabled)
setHasRegisteredChannel
public void setHasRegisteredChannel(boolean hasRegisteredChannel)
setId
public void setId(Long id)
setName
public void setName(String name)
setTaskConfig
public void setTaskConfig(TaskConfig taskConfig)
setTrigger
public void setTrigger(TaskTriggerInformation trigger)
setValidationErrors
public void setValidationErrors(Set<TaskError> validationErrors)
toString
public String toString()

TaskActionInformation

public class TaskActionInformation extends TaskEventInformation

Represents an action event configured with a Task

Constructors
TaskActionInformation
public TaskActionInformation()
TaskActionInformation
public TaskActionInformation(String displayName, String channelName, String moduleName, String moduleVersion, String subject)
TaskActionInformation
public TaskActionInformation(String displayName, String channelName, String moduleName, String moduleVersion, String subject, Map<String, String> values)
TaskActionInformation
public TaskActionInformation(String displayName, String channelName, String moduleName, String moduleVersion, String serviceInterface, String serviceMethod)
TaskActionInformation
public TaskActionInformation(String displayName, String channelName, String moduleName, String moduleVersion, String subject, String serviceInterface, String serviceMethod, Map<String, String> values)
Methods
equals
public boolean equals(Object obj)
getServiceInterface
public String getServiceInterface()
getServiceMethod
public String getServiceMethod()
getValues
public Map<String, String> getValues()
hasService
public boolean hasService()
hashCode
public int hashCode()
setServiceInterface
public void setServiceInterface(String serviceInterface)
setServiceMethod
public void setServiceMethod(String serviceMethod)
setValues
public void setValues(Map<String, String> values)
toString
public String toString()

TaskActivity

public class TaskActivity implements Comparable<TaskActivity>
Constructors
TaskActivity
public TaskActivity()
TaskActivity
public TaskActivity(String message, Long task, TaskActivityType activityType)
TaskActivity
public TaskActivity(String message, String field, Long task, TaskActivityType activityType)
TaskActivity
public TaskActivity(String message, List<String> fields, Long task, TaskActivityType activityType)
TaskActivity
public TaskActivity(String message, List<String> fields, Long task, TaskActivityType activityType, String stackTraceElement)
Methods
compareTo
public int compareTo(TaskActivity o)
equals
public boolean equals(Object obj)
getActivityType
public TaskActivityType getActivityType()
getDate
public DateTime getDate()
getFields
public List<String> getFields()
getMessage
public String getMessage()
getStackTraceElement
public String getStackTraceElement()
getTask
public Long getTask()
hashCode
public int hashCode()
setActivityType
public void setActivityType(TaskActivityType activityType)
setDate
public void setDate(DateTime date)
setField
public void setField(String field)
setFields
public void setFields(List<String> fields)
setMessage
public void setMessage(String message)
setStackTraceElement
public void setStackTraceElement(String stackTraceElement)
setTask
public void setTask(Long task)
toString
public String toString()

TaskActivityType

public enum TaskActivityType
Enum Constants
ERROR
public static final TaskActivityType ERROR
SUCCESS
public static final TaskActivityType SUCCESS
WARNING
public static final TaskActivityType WARNING

TaskBuilder

public class TaskBuilder
Constructors
TaskBuilder
public TaskBuilder()
Methods
addAction
public TaskBuilder addAction(TaskActionInformation action)
addDataSource
public TaskBuilder addDataSource(DataSource dataSource)
addFilterSet
public TaskBuilder addFilterSet(FilterSet filterSet)
build
public Task build()
clear
public TaskBuilder clear()
isEnabled
public TaskBuilder isEnabled(boolean enabled)
withDescription
public TaskBuilder withDescription(String description)
withId
public TaskBuilder withId(Long id)
withName
public TaskBuilder withName(String name)
withTaskConfig
public TaskBuilder withTaskConfig(TaskConfig taskConfig)
withTrigger
public TaskBuilder withTrigger(TaskTriggerInformation trigger)

TaskConfig

public class TaskConfig implements Serializable
Methods
add
public TaskConfig add(TaskConfigStep... configSteps)
addAll
public TaskConfig addAll(SortedSet<TaskConfigStep> set)
equals
public boolean equals(Object obj)
getDataSource
public DataSource getDataSource(Long providerId, Long objectId, String objectType)
getDataSources
public List<DataSource> getDataSources()
getDataSources
public SortedSet<DataSource> getDataSources(Long providerId)
getFilters
public List<FilterSet> getFilters()
getSteps
public SortedSet<TaskConfigStep> getSteps()
hashCode
public int hashCode()
removeAll
public TaskConfig removeAll()
removeDataSources
public TaskConfig removeDataSources()
removeFilterSets
public TaskConfig removeFilterSets()
setDataSources
public void setDataSources(List<DataSource> dataSources)
setFilters
public void setFilters(List<FilterSet> filters)
toString
public String toString()

TaskConfigStep

public abstract class TaskConfigStep implements Comparable<TaskConfigStep>, Serializable
Methods
compareTo
public int compareTo(TaskConfigStep o)
equals
public boolean equals(Object obj)
getOrder
public Integer getOrder()
hashCode
public int hashCode()
setOrder
public void setOrder(Integer order)
toString
public String toString()

TaskDataProvider

public class TaskDataProvider

The TaskDataProvider class cointains all informations about data providers used in tasks

Constructors
TaskDataProvider
public TaskDataProvider()
TaskDataProvider
public TaskDataProvider(String name, List<TaskDataProviderObject> objects)
Methods
containsProviderObject
public boolean containsProviderObject(String type)
containsProviderObjectField
public boolean containsProviderObjectField(String type, String fieldKey)
containsProviderObjectLookup
public boolean containsProviderObjectLookup(String type, String lookupField)
equals
public boolean equals(Object obj)
getId
public Long getId()
getKeyType
public String getKeyType(String key)
getName
public String getName()
getObjects
public List<TaskDataProviderObject> getObjects()
getProviderObject
public TaskDataProviderObject getProviderObject(String type)
hashCode
public int hashCode()
setId
public void setId(Long id)
setName
public void setName(String name)
setObjects
public void setObjects(List<TaskDataProviderObject> objects)
toString
public String toString()

TaskDataProviderObject

public class TaskDataProviderObject implements Serializable
Constructors
TaskDataProviderObject
public TaskDataProviderObject()
TaskDataProviderObject
public TaskDataProviderObject(String displayName, String type, List<LookupFieldsParameter> lookupFields, List<FieldParameter> fields)
Methods
containsField
public boolean containsField(String fieldKey)
equals
public boolean equals(Object obj)
getDisplayName
public String getDisplayName()
getFields
public List<FieldParameter> getFields()
getLookupFields
public List<LookupFieldsParameter> getLookupFields()
getType
public String getType()
hashCode
public int hashCode()
setDisplayName
public void setDisplayName(String displayName)
setFields
public void setFields(List<FieldParameter> fields)
setLookupFields
public void setLookupFields(List<Object> lookupFields)
setType
public void setType(String type)
toString
public String toString()

TaskError

public class TaskError implements Serializable
Constructors
TaskError
public TaskError()
TaskError
public TaskError(TaskErrorType type, String... args)
TaskError
public TaskError(String message, String... args)
Methods
equals
public boolean equals(Object obj)
getArgs
public List<String> getArgs()
getMessage
public String getMessage()
hashCode
public int hashCode()
setArgs
public void setArgs(List<String> args)
setMessage
public void setMessage(String message)
toString
public String toString()

TaskErrorType

public enum TaskErrorType
Enum Constants
BLANK
public static final TaskErrorType BLANK
EMPTY_COLLECTION
public static final TaskErrorType EMPTY_COLLECTION
NULL
public static final TaskErrorType NULL
VERSION
public static final TaskErrorType VERSION

TaskEvent

public abstract class TaskEvent implements Serializable
Constructors
TaskEvent
protected TaskEvent()
TaskEvent
protected TaskEvent(String description, String displayName, String subject)
Methods
containsParameter
public boolean containsParameter(String key)
equals
public boolean equals(Object obj)
equalsSubject
protected boolean equalsSubject(String subject)
getDescription
public String getDescription()
getDisplayName
public String getDisplayName()
getSubject
public String getSubject()
hasSubject
public boolean hasSubject()
hashCode
public int hashCode()
setDescription
public void setDescription(String description)
setDisplayName
public void setDisplayName(String displayName)
setSubject
public void setSubject(String subject)
toString
public String toString()

TaskEventInformation

public abstract class TaskEventInformation implements Serializable
Constructors
TaskEventInformation
public TaskEventInformation()
TaskEventInformation
public TaskEventInformation(String displayName, String channelName, String moduleName, String moduleVersion, String subject)
Methods
equals
public boolean equals(Object obj)
getChannelName
public String getChannelName()
getDisplayName
public String getDisplayName()
getModuleName
public String getModuleName()
getModuleVersion
public String getModuleVersion()
getSubject
public String getSubject()
hasSubject
public boolean hasSubject()
hashCode
public int hashCode()
setChannelName
public void setChannelName(String channelName)
setDisplayName
public void setDisplayName(String displayName)
setModuleName
public void setModuleName(String moduleName)
setModuleVersion
public void setModuleVersion(String moduleVersion)
setSubject
public void setSubject(String subject)
toString
public String toString()

TaskTriggerInformation

public class TaskTriggerInformation extends TaskEventInformation
Constructors
TaskTriggerInformation
public TaskTriggerInformation()
TaskTriggerInformation
public TaskTriggerInformation(String displayName, String channelName, String moduleName, String moduleVersion, String subject)
TaskTriggerInformation
public TaskTriggerInformation(TaskTriggerInformation other)

TriggerEvent

public class TriggerEvent extends TaskEvent

The TriggerEvent class is responsible for storing data about event

Constructors
TriggerEvent
public TriggerEvent()
TriggerEvent
public TriggerEvent(String displayName, String subject, String description, List<EventParameter> eventParameters)
TriggerEvent
public TriggerEvent(TriggerEventRequest triggerEventRequest)
Methods
containsParameter
public boolean containsParameter(String key)
equals
public boolean equals(Object obj)
getEventParameters
public List<EventParameter> getEventParameters()
getKeyType
public String getKeyType(String key)
hashCode
public int hashCode()
setEventParameters
public void setEventParameters(List<EventParameter> eventParameters)
toString
public String toString()

org.motechproject.tasks.ex

ActionNotFoundException

public class ActionNotFoundException extends Exception
Constructors
ActionNotFoundException
public ActionNotFoundException(String message)

TaskHandlerException

public class TaskHandlerException extends Exception
Constructors
TaskHandlerException
public TaskHandlerException(TaskFailureCause failureCause, String messageKey)
TaskHandlerException
public TaskHandlerException(TaskFailureCause failureCause, String messageKey, String... args)
TaskHandlerException
public TaskHandlerException(TaskFailureCause failureCause, String messageKey, Throwable cause, String... args)
Methods
getArgs
public List<String> getArgs()
getFailureCause
public TaskFailureCause getFailureCause()
getMessage
public String getMessage()

TaskNotFoundException

public class TaskNotFoundException extends IllegalArgumentException
Constructors
TaskNotFoundException
public TaskNotFoundException(Long taskId)

TriggerNotFoundException

public class TriggerNotFoundException extends Exception
Constructors
TriggerNotFoundException
public TriggerNotFoundException(String message)

ValidationException

public class ValidationException extends IllegalArgumentException
Constructors
ValidationException
public ValidationException(String objectType, Set<TaskError> taskErrors)
Methods
getMessage
public String getMessage()
getTaskErrors
public Set<TaskError> getTaskErrors()

org.motechproject.tasks.json

ActionEventRequestDeserializer

public class ActionEventRequestDeserializer implements JsonDeserializer<ActionEventRequest>
Fields
ACTION_PARAMETERS_FIELD
public static final String ACTION_PARAMETERS_FIELD
DESCRIPTION_FIELD
public static final String DESCRIPTION_FIELD
DISPLAY_NAME_FIELD
public static final String DISPLAY_NAME_FIELD
SERVICE_INTERFACE_FIELD
public static final String SERVICE_INTERFACE_FIELD
SERVICE_METHOD_FIELD
public static final String SERVICE_METHOD_FIELD
SUBJECT_FIELD
public static final String SUBJECT_FIELD
Methods
deserialize
public ActionEventRequest deserialize(JsonElement element, Type type, JsonDeserializationContext context)

TaskConfigDeserializer

public class TaskConfigDeserializer extends JsonDeserializer<TaskConfig>
Methods
deserialize
public TaskConfig deserialize(JsonParser parser, DeserializationContext context)

TaskDeserializer

public class TaskDeserializer extends JsonDeserializer<Task>
Methods
deserialize
public Task deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)

org.motechproject.tasks.repository

ChannelsDataService

public interface ChannelsDataService extends MotechDataService<Channel>
Methods
findByModuleName
Channel findByModuleName(String moduleName)

TaskActivitiesDataService

public interface TaskActivitiesDataService extends MotechDataService<TaskActivity>
Methods
byTask
List<TaskActivity> byTask(Long task)

TasksDataService

public interface TasksDataService extends MotechDataService<Task>

org.motechproject.tasks.service

ChannelService

public interface ChannelService

Manages CRUD operations for a Channel.

Methods
addOrUpdate
void addOrUpdate(Channel channel)
getAllChannels
List<Channel> getAllChannels()
getChannel
Channel getChannel(String moduleName)
getChannelIcon
BundleIcon getChannelIcon(String moduleName)
registerChannel
void registerChannel(ChannelRequest channelRequest)
registerChannel
void registerChannel(InputStream stream, String moduleName, String moduleVersion)

DataProviderDataService

public interface DataProviderDataService extends MotechDataService<TaskDataProvider>
Methods
findByName
TaskDataProvider findByName(String name)

DataSourceObject

public class DataSourceObject

DataSourceObject is the result of a org.motechproject.commons.api.DataProvider lookup.

Constructors
DataSourceObject
public DataSourceObject(String objectId, Object objectValue, boolean failIfNotFound)
Methods
equals
public boolean equals(Object o)
getObjectId
public String getObjectId()
getObjectValue
public Object getObjectValue()
hashCode
public int hashCode()
isFailIfNotFound
public boolean isFailIfNotFound()

HandlerPredicates

final class HandlerPredicates

Utility class defining filters over some collections.

Methods
activeTasks
public static Predicate activeTasks()
withServiceName
public static Predicate withServiceName(String serviceName)

KeyEvaluator

public class KeyEvaluator

KeyEvaluator evaluates the value of a key in the context of a task which is used to execute filters and actions.

Constructors
KeyEvaluator
public KeyEvaluator(TaskContext taskContext)
Methods
evaluateTemplateString
public String evaluateTemplateString(String template)
getValue
public Object getValue(KeyInformation keyInformation)
manipulate
String manipulate(String manipulation, String value)

MethodHandler

class MethodHandler

Utility class used by TaskTriggerHandler to construct a list of parameter types of the method in the correct order.

See also: TaskTriggerHandler

Constructors
MethodHandler
public MethodHandler(ActionEvent action, Map<String, Object> parameters)
Methods
getClasses
public Class[] getClasses()
getObjects
public Object[] getObjects()
isParametrized
public boolean isParametrized()

TaskActionExecutor

class TaskActionExecutor

Builds action parameters from TaskContext and executes the action by invoking its service or raising its event.

Constructors
TaskActionExecutor
TaskActionExecutor(TaskService taskService, TaskActivityService activityService, EventRelay eventRelay)
Methods
createParameters
Map<String, Object> createParameters(TaskActionInformation info, ActionEvent action)
execute
void execute(Task task, TaskActionInformation actionInformation, TaskContext taskContext)
setBundleContext
void setBundleContext(BundleContext bundleContext)

TaskActivityService

public interface TaskActivityService
Methods
addError
void addError(Task task, TaskHandlerException e)
addSuccess
void addSuccess(Task task)
addWarning
void addWarning(Task task)
addWarning
void addWarning(Task task, String key, String value)
addWarning
void addWarning(Task task, String key, String field, Exception e)
deleteActivitiesForTask
void deleteActivitiesForTask(Long taskId)
errorsFromLastRun
List<TaskActivity> errorsFromLastRun(Task task)
getAllActivities
List<TaskActivity> getAllActivities()
getTaskActivities
List<TaskActivity> getTaskActivities(Long taskId)

TaskContext

public class TaskContext

TaskContext holds task trigger event and data provider lookup objects that are used while executing filters/actions.

Constructors
TaskContext
public TaskContext(Task task, MotechEvent event, TaskActivityService activityService)
Methods
addDataSourceObject
public void addDataSourceObject(String objectId, Object dataSourceObject, boolean failIfDataNotFound)
getDataSourceObjectValue
public Object getDataSourceObjectValue(String objectId, String field, String objectType)
getTask
public Task getTask()
getTriggerParameters
public Map<String, Object> getTriggerParameters()
getTriggerValue
public Object getTriggerValue(String key)
publishWarningActivity
public void publishWarningActivity(String message, String field)

TaskDataProviderService

public interface TaskDataProviderService
Methods
getProvider
TaskDataProvider getProvider(String name)
getProviderById
TaskDataProvider getProviderById(Long providerId)
getProviders
List<TaskDataProvider> getProviders()
registerProvider
void registerProvider(String json)
registerProvider
void registerProvider(InputStream stream)

TaskFilterExecutor

public class TaskFilterExecutor

The TaskFilterExecutor applies a list of filters in a #TaskContext.

  • convertTo - convert a given value to a correct type,
  • getFieldValue - get value of a field defined in the key from the given object,
  • getTriggerKey - get value of a trigger event parameter,
  • checkFilters - executed defined filters for a task,
  • manipulate - executed the given manipulation on the given string value.
Methods
checkFilters
public boolean checkFilters(List<Filter> filters, TaskContext taskContext)

TaskInitializer

class TaskInitializer

The TaskInitializer class prepares an action in the task definition to execution.

  • evalConfigSteps - executes all config steps (load data sources, check filters) defined in the task,

See also: TaskTriggerHandler, TaskActionExecutor

Constructors
TaskInitializer
TaskInitializer(TaskContext taskContext)
Methods
evalConfigSteps
public boolean evalConfigSteps(Map<String, DataProvider> dataProviders)

TaskService

public interface TaskService
Methods
deleteTask
void deleteTask(Long taskId)
exportTask
String exportTask(Long taskId)
findTasksDependentOnModule
List<Task> findTasksDependentOnModule(String moduleName)
findTasksForTrigger
List<Task> findTasksForTrigger(TriggerEvent trigger)
findTasksForTriggerSubject
List<Task> findTasksForTriggerSubject(String subject)
findTrigger
TriggerEvent findTrigger(String subject)
getActionEventFor
ActionEvent getActionEventFor(TaskActionInformation taskActionInformation)
getAllTasks
List<Task> getAllTasks()
getTask
Task getTask(Long taskId)
importTask
void importTask(String json)
save
void save(Task task)

TaskTriggerHandler

public class TaskTriggerHandler implements TriggerHandler

The TaskTriggerHandler receives events and executes tasks for which the trigger event subject is the same as the received event subject.

Constructors
TaskTriggerHandler
public TaskTriggerHandler(TaskService taskService, TaskActivityService activityService, EventListenerRegistryService registryService, EventRelay eventRelay, SettingsFacade settings)
Methods
addDataProvider
public void addDataProvider(DataProvider provider)
handle
public void handle(MotechEvent event)
registerHandlerFor
public final void registerHandlerFor(String subject)
removeDataProvider
public void removeDataProvider(String taskDataProviderId)
setBundleContext
public void setBundleContext(BundleContext bundleContext)
setDataProviders
void setDataProviders(Map<String, DataProvider> dataProviders)

TriggerHandler

public interface TriggerHandler

Standard interface for tasks which executes tasks.

Methods
handle
void handle(MotechEvent event)
registerHandlerFor
void registerHandlerFor(String subject)

org.motechproject.tasks.util

BundleContextUtil

public final class BundleContextUtil
Methods
getSymbolicNames
public static List<String> getSymbolicNames(BundleContext context)

ManagementDataProvider

public class ManagementDataProvider implements OsgiServiceLifecycleListener
Constructors
ManagementDataProvider
public ManagementDataProvider(TaskDataProviderService taskDataProviderService)
ManagementDataProvider
public ManagementDataProvider(TaskTriggerHandler handler, TaskDataProviderService taskDataProviderService)
Methods
bind
public void bind(Object service, Map serviceProperties)
unbind
public void unbind(Object service, Map serviceProperties)

Contribute

Thank you for your interest in contributing to MOTECH. There are many different ways to get involved - regardless of your area of expertise and time commitment, there is likely a useful way for you to contribute. Please peruse the sections below for some instructions on how to get started contributing in specific areas. If there is another way you’d like to help that isn’t listed, just let us know what your interests are and we can help find a project for you.

Development

Want to help us develop MOTECH? The step by step guide below will help you get started. The instructions may be incomplete, or may contain some errors, so please just let us know if something is missing or incorrect. Our mailing list is populated with helpful people who will help you get going - and will get this documentation up to date with any issues you encounter.

Here is how to get started:

Mailing Lists and Accounts

  1. Sign up for the MOTECH Developer mailing list - this is the best place to get help with any questions about MOTECH development.
  2. Create an account on Gerrit, our code review system.
  3. Get a Jira account if you’ll need to report/track issues - there is no self-serve way to request a Jira account yet, so please just email the MOTECH Developer list and we’ll get you set up.

Dev Environment & Tools

  1. Configure your dev machine.
  2. Configure your Git client to submit changes via Gerrit.
  3. Familiarize yourself with our CI.

Finding Something to Work On

  1. Some MOTECH devs have found that reviewing code written by others before they jump in and develop their own is a good way to get their feet wet. If that sounds like your style, feel free to jump into any code review on Gerrit and add your comments.
  2. If you’d rather dive right in, we’d recommend that you find a “community” issue from our issue tracker - these are bugs and user stories that we think are good introductory items for MOTECH newbies. See a list of all current “community” issues here.
  3. If you’re already building your own system on top of MOTECH and you’d like us to incorporate your changes for an issue you’ve found and fixed, please first check whether the issue already exists in our issue tracker. If you are not sure, please email the mailing list and we’ll help you determine whether the issue is already known. Please track your work with a new issue so that we can evaluate it for inclusion in the Platform.

Developing and Submitting Your Code

  1. If your fix will be nontrivial, please leverage the mailing list for feedback on your design before you get too far - we are a friendly bunch and can help ensure you are headed in the right direction.
  2. When you’re ready to push your changes, please squash your commits to keep the change history concise, and write a commit message that conforms to our guidelines.
  3. Submit your code using git push origin - if you configured your environment correctly, this sends your changes to Gerrit, our code review system.
  4. Please incorporate code review feedback and update your patch as needed - once your change has passed code review, one of the project maintainers will merge your change to the repo.
  5. Resolve the relevant issue(s) in Jira.

Documentation

There will be text here.

Translation

Bonjour!

We are using Transifex to manage MOTECH translations, which makes it easy for non-geeks to help. If you speak multiple languages and would like to help us make MOTECH multilingual, please start by checking out our translation page to determine whether your language(s) are on our list. Do we have a translation in progress for your language? Great! We’d love your help translating additional strings. Do we not have a translation started for your language? Also great! We’d love your help getting one started.

Either way, please sign up for Transifex (free), and then contact us. Let us know your Transifex user ID and which language(s) you’d like to work on, and we’ll help you get started.

Indices and tables

  • genindex
  • modindex
  • search