Connexion à MongoDB depuis Corticon à l'aide de légendes de service
Apprenez à créer une légende de service fonctionnel pouvant lire et stocker vers une instance MongoDB à l'aide de l'API flexible de gestion de sources de données de Corticon
Progress Corticon 5.7 inclut un fichier de configuration de source de données unifiée permettant aux utilisateurs de configurer des connexions externes sources de données. Bien que ce fichier soit principalement utilisé pour se connecter à des bases de données externes (ADC ou EDC), il est exposé dans le cadre des appels de service afin que les utilisateurs puissent connecter Corticon Server à une source de données personnalisée. La base de données n'est pas supportée nativement. Ce guide explique comment se connecter à une instance MongoDB à l'aide d'une API REST.
Avant de commencer, assurez-vous d'avoir tous les logiciels prérequis:
- Corticon Studio 5.7
- Corticon Server 5.7 (pour le déploiement)
- MongoDB 3.6
- MongoDB Compass (pour configurer la base de données et le catalogue)
- RESTHeart 3.2.2
Configurer MongoDB
Suivez les instructions du site Web MongoDB pour installer et démarrer MongoDB. Le site Web propose des guides d'installation pour tous les principaux systèmes d'exploitation de bureau
Open MongoDB Compass
Les paramètres de connexion par défaut doivent vous permettre de vous connecter.
Créer une base de données et une collection
Utilisez" Corticon "comme nom pour les deux. (Vous n'avez pas besoin de créer un document, vous ' ll le fera avec l'API REST)
Démarrer RESTHeart
Étape 1
Décompressez l'archive, ouvrez le répertoire contenant et éditez le fichier etc / restheart.yml avec votre éditeur de texte favori. Assurez-vous de configurer la propriété mongo-uri pour inclure l'adresse et le port corrects de votre serveur MongoDB. Par exemple, si vous exécutez MongoDB localement sur le port 27017, modifiez la ligne suivante à partir de ceci:
mongo-uri : MongoDB: //127.0.0.1
à ceci:
mongo-uri : MongoDB: //127.0.0.1: 27017
Étape 2
Démarrez RESTHeart, et vous devriez voir la sortie comme suit:
09: 59: 43.461 [main] INFO org.restheart.Bootstrapper - Console de couleur ANSI: true
09: 59: 43.481 [main] INFO org.restheart.Bootstrapper - Commencer l'occurrence de RESTHeart par défaut
09: 59: 43.483 [main] INFO org.restheart.Bootstrapper - version 3.2.2
09: 59: 43.486 [main] INFO org.restheart.Bootstrapper - Connexion au fichier C: Utilisateurs bblais AppData Local Temp \ restheart. [19659036] l og avec niveau INFO
09: 59: 43.486 [main] INFO org.restheart.Bootstrapper - Connexion à la console avec le niveau INFO
09: 59: 44.229 [main] INFO org.restheart.Bootstrapper - MongoDB connexion pool initialisée
09: 59: 44.230 [main] INFO org.restheart.Bootstrapper - MongoDB version 3.6.2
09: 59: 44.230 [main] WARN org.restheart.Bootstrapper - ***** Aucun Identity Manager spécifié . Authentification désactivée.
09: 59: 44.231 [main] WARN org.restheart.Bootstrapper - ***** Aucun gestionnaire d'accès spécifié. les utilisateurs peuvent faire n'importe quoi.
09: 59: 44.232 [main] INFO org.restheart.Bootstrapper - Mécanisme d'authentification io.undertow.security.impl.BasicAuthen
ticationMechanism activé
09: 59: 44.232 [main] INFO org.restheart. Bootstrapper - Authentification par jeton activée avec le jeton TTL 15 minutes
09: 59: 44.242 [main] INFO org.restheart.Bootstrapper - écouteur HTTPS lié à 0.0.0.04444
09: 59: 44.243 [main] INFO org.restheart.Bootstrapper - écouteur HTTP lié à 0.0.0.0:8080
09: 59: 44.244 [main] INFO org.restheart.Bootstrapper - Cache local pour les propriétés db et collection activées avec TTL
1000 msecs
09: 59: 44.245 [main] INFO org.restheart.Bootstrapper - Le cache local pour les magasins de schéma n'est pas activé
09: 59: 44.423 [main] INFO org.restheart.Bootstrapper - URL / lié à la ressource MongoDB *
09: 59: 44.558 [main] INFO org.restheart.Bootstrapper - Navigateur de ressources statiques incorporées extrait dans C: Utilisateurs bblais
AppData Local Temp restheart-
[19659058] 6229838428094629763
09: 59: 44.596 [main] INFO org.restheart.Bootstrapper - URL / navigateur lié aux ressources statiques C: Utilisateurs bblais AppData
Local Temp restheart-622983842809462976 3. Access Manager: false
09: 59: 44.790 [main] INFO org.restheart.Bootstrapper - RESTHeart a ouvert
Étape 3
Testez le point de terminaison en utilisant votre navigateur préféré ou votre client HTTP.
L'API REST connectée à MongoDB est maintenant opérationnelle.
Créer le service de décision
Étape 1
Ouvrir Corticon Studio et créer un vocabulaire simple Vous pouvez suivre cet exemple de calculateur de kilométrage: il va prendre des informations sur une voiture et calculer le nombre de kilomètres qu'il peut parcourir avant d'avoir besoin de carburant.
Étape 2
Créer une liste de règles pour faire le calcul.
Étape 3
Effectuez une simulation et ajoutez quelques exemples de données pour vous assurer que le service de décision fonctionne
4
Lancez le test et vérifiez vos résultats
Connectez le service de décision à votre instance MongoDB à l'aide d'une légende de service
Étape 1
Ajoutez une configuration ADC à votre vocabulaire et choisissez (19659028]
Étape 2
Remplacez l'URL par défaut par le chemin d'accès à l'API RESTHeart et ajoutez le nom du document à l'URL. Dans cet exemple, le nom du document est "cars".
Étape 3
Créer un appel de service En tant que raccourci, importez le fichier Corticon 5.7 / Samples / Weather Callout dans votre projet; contient déjà toutes les bibliothèques nécessaires
Étape 4
Après l'importation, supprimez les fichiers Java et, éventuellement, renommez le projet
Etape 5
Ecrivez le code pour créer une classe pour votre légende, en commençant par stocker les données. ne vous inquiétez pas trop de la gestion des erreurs.)
public
static
void storeData (ICcDataObjectManager dataObjectManager) jette une exception {
//
[19659069DIFFÉRENTESPERSONNAGES]
//
Convertir
nos DataObjects
en
JSON

[1945909]
//
// Puisque nous parlons
à
d'une API REST [19659115] convertir
les
'voitures'
en
JSON
[19659108]
Ensemble
"Voiture"
);
// Ce sera le JSONObject que nous envoyons
[1945909]
JSONObject carsJson = nouveau JSONObject ();
//
Et
ce sera le tableau que nous avons mis
tous
les
'voitures'
en
[19659108]
JSONArray carsArray = nouveau JSONArray ();
[19659069]
//
Convertir
les objets de données, chacun sera un objet json
dans
le tableau
// Chaque attribut sera une propriété
pour
(ICcDataObject currentCar: voitures) {
[19659069]
JSONObject currentCarJSON = nouveau JSONObject ();
// Récupère les noms d'attributs
Ensemble
AttributNoms = currentCar.getAttributeNames ();
[19659069
// Boucle à travers les attributs
pour
(String currentAttributeName: attributeNames) {
// Placer la valeur d'attribut
[19659069]
currentCarJSON.put (currentAttributeName, currentCar.getAttributeValue (nomAttribut actuel));
}
[196AIS59184] //
Ajouter
la nouvelle voiture objet JSON
à
la rangée
// Récupère les noms d'attributs
Ensemble
AttributNoms = currentCar.getAttributeNames ();
// Boucle à travers les attributs
pour
(String currentAttributeName: attributeNames) {
// Placer la valeur d'attribut
[19659069]
currentCarJSON.put (currentAttributeName, currentCar.getAttributeValue (nomAttribut actuel));
}
[196AIS59184] //
Ajouter
la nouvelle voiture objet JSON
à
la rangée
carsArray.put (currentCarJSON);
}
[1945905]
// Placer le tableau
dans
l'objet JSON
[19659108]
voituresJson.put (
"Voitures"
(Object) carsArray);
[1965906EN]. 9]
[1945904]
//
//
Connectez
à
MongoDB
//
// Récupère le gestionnaire de sources de données
IDatasourceManager datasourceManager = dataObjectManager.getDatasourceManager ();
// Récupère notre source de données MongoDB
IDatasource mongoDBDatasource = datasourceManager. getDatasource (
"MongoDB"
);
[19659069]
//
Ouvert
une connexion http
à
la base de données
//
Connectez
à
MongoDB
//
// Récupère le gestionnaire de sources de données
IDatasourceManager datasourceManager = dataObjectManager.getDatasourceManager ();
// Récupère notre source de données MongoDB
IDatasource mongoDBDatasource = datasourceManager. getDatasource (
"MongoDB"
);
[19659069]
//
Ouvert
une connexion http
à
la base de données
URL mongoDBConnectionURL = nouvelle URL (mongoDBDatasource.getDatasour ceConnectionURL ());
HttpURLConnection mongoDBConnection = (HttpURLConnection) mongoDBConnectionURL.openConnection ();
[1945905]
[19459028Cetarticleapparaîtdansl'éditionbilingue]
// Puisque nous stockons, nous voulons que
à
utilisent la méthode HTTP
'PUT'
[19659069]
mongoDBConnection.setRequestMethod (
"PUT"
);
//
Définir
le type de contenu
mongoDBConnection.setRequestProperty (
"Content-Type"
"application / json"
);
// Assurez-vous de pouvoir écrire
à
la
connexion
mongoDBConnection.setDoOutput (
true
)
// Nous allons
à
écrire les données
à
la
connexion
sortie
flux
[1945909]
BufferedWriter jsonContentWriter =
null
;
essayez {
Qu'est-ce que c'est? jsonContentWriter = new BufferedWriter (nouveau OutputStreamWriter (mongoDBConnection.getOutputStream ()));
//
Convertir
notre JSON
vers [19659105] une chaîne
à
envoie
à
l'API REST
[19659184] jsonContentWriter.write (carsJson.toString ())
[19659069]
// Rincer le ruisseau
jsonContentWriter.flush ()
//
Ouvert
connexion
// Nous allons
à
écrire les données
à
la
connexion
sortie
flux
BufferedWriter jsonContentWriter =
null
;
essayez {
Qu'est-ce que c'est? jsonContentWriter = new BufferedWriter (nouveau OutputStreamWriter (mongoDBConnection.getOutputStream ()));
//
Convertir
notre JSON
vers [19659105] une chaîne
à
envoie
à
l'API REST
[19659184] jsonContentWriter.write (carsJson.toString ())
[19659069]
// Rincer le ruisseau
jsonContentWriter.flush ()
//
Ouvert
connexion
mongoDBConnection.
connect
();
[19459028Ensavoirplussurcetartiste]
// Imprimer
sortir
une règle
[19659105]
le
succès
ou
échec
int
mongoDBResponseCode = mongoDBConnection.getResponseCode ();
si (mongoDBResponseCode> = 200 && mongoDBResponseCode <30 0) {
dataObjectManager.postMessage (ICcDataObjectManager.INFO,
"Appel MongoDB PUT RÉUSSI avec un statut de "
+
Integer
.toString (mongoDBResponseCode),
null
);
[19659069]
}
autre
{
dataObjectManager .postMessage (ICcDataObjectManager.INFO,
"L'appel de MongoDB PUT a échoué avec un statut de"
+
Integer
.toString (mongoDBResponseCode),
null
);
}
[19659069]
} finalement [
//
Fermer
le flux
et
connexion
lorsque nous avons terminé
si (jsonContentWriter! =
null
) {
jsonContentWriter.
fermer
();
}
mongoDBConnection.disconnect ();
}
[19459028Cetarticleaététraduitle]
}
[19659069]
} finalement [
//
Fermer
le flux
et
connexion
lorsque nous avons terminé
si (jsonContentWriter! =
null
) {
jsonContentWriter.
fermer
();
}
mongoDBConnection.disconnect ();
}
[19459028Cetarticleaététraduitle]
}
Exporter le fichier JAR et tester le nouveau service Légende
Etape 1
Pour exporter le fichier JAR, faites un clic droit sur le projet, sélectionnez Exporter dans le menu et sélectionnez Fichier Java / JAR depuis le options de l'assistant.
Étape 2
Ajouter le fichier JAR exporté au projet.
Étape 3
Créer un Ruleflow pour tester la nouvelle légende de service.
Étape 4
Faire une nouvelle fiche de test dans la règle et sélectionner le Ruleflow comme sujet de test
Étape 5
Lancer le test
Si vous avez réussi l'API REST, vous devriez voir le nouveau document rempli de données.
Maintenant, vous avez stocké des données dans MongoDB .
Récupération de données à partir de MongoDB
Étape 1
Revenez à l'appel de service et mettez-le à jour pour lire les informations de l'API REST au lieu de les stocker.
] Ajoutez la méthode suivante à votre légende de service. public
static
void readData (ICcDataObjectManager dataObjectManager) renvoie Exception {
// Ce sera l'objet qui contient la réponse JSON [19659117] à partir de
le reste API
JSONObject mongoDBCarDocument =
null [19659140];
[19659108]
//
//
Connectez
à
MongoDB
[19659069] //
// Récupère le gestionnaire de sources de données
IDatasourceManager gestionnaire de données = dataObjectManager.getDatasourceManager ();
// Récupérer notre source de données MongoDB
[19659069]
IDatasource mongoDBDatasource = datasourceManager.getDatasource (
"MongoDB"
);
[19659069]
//
Ouvrir
une connexion http
à
la base de données
URL mongoDBConnectionURL = nouvelle URL (mongoDBDatasource.getDatasourceConnectionURL ());
HttpURLConnexion mongoDBConnection = (HttpURLConnection) mongoDBConnectionURL.openConnection ();
// Puisque nous lisons, nous voulons
] à
utilisent la méthode HTTP
'GET' " title="" data-openoriginalimageonclick="true"/>
mongoDBConnection.setRequestMethod (
"OBTENIR"
);
[1945908]
//
Servez
le type de contenu
[1945909]
mongoDBConnection.setRequestProperty (
"Content-Type"
"application / json"
);
//Make the
connection
mongoDBConnection.
connect
();
//Print
out
a
rule
message
on
success [19659156]or
failure
int
mongoDBResponseCode = mongoDBConnection.getResponseCode();
if(mongoDBResponseCode >= 200 && mongoDBResponseCode < 300) {
dataObjectManager.postMessage(ICcDataObjectManager.INFO,
"MongoDB GET call SUCCEEDED with a status of "
+
Integer
.toString(mongoDBResponseCode),
null
);
}
else[19659105]{
dataObjectManager.postMessage(ICcDataObjectManager.INFO,
"MongoDB GET call FAILED with a status of "
+
Integer
.toString(mongoDBResponseCode),
null
);
}
//
Read
response data
BufferedReader jsonContentReader =
null
;
[19659069]
try {
jsonContentReader = new BufferedReader(new InputStreamReader(mongoDBConnection.getInputStream()));
//Get
all
the data
from
the stream
StringBuilder jsonResultStringBuilder = new StringBuilder();
//
Read
each line
of
the input
to
the
end
String lineOfJson =
null
;
while( (lineOfJson = jsonContentReader.readLine()) !=
null
) {
jsonResultStringBuilder.append(lineOfJson);
}
//
Convert
the entire message payload
into
a JSONObject
mongoDBCarDocument = new JSONObject(jsonResultStringBuilder.toString());
} finally {
if(jsonContentReader !=
null
) {
jsonContentReader.
close
();
}
mongoDBConnection.disconnect();
}
//
//
Convert
our JSON
to
DataObjects
//
//Get the
'cars'
array
out
of
the Document
JSONArray carsJsonArray = mongoDBCarDocument.getJSONArray(
"Cars"
);
//
Create
a data object based
off
of
each car
in
the array.
for
(
int
carsIndex = 0; carsIndex < carsJsonArray.length(); carsIndex++) {
//Get the JSONObject
out
of
the array
JSONObject currentCar = carsJsonArray.getJSONObject(carsIndex);
//
Create
the ICcDataObject
ICcDataObject carDataObject = dataObjectManager.createEntity(
"Car"
);
Set
attributeNames = carDataObject.getAttributeNames();
//Loop through the data object attributes
and
if they are properties
in
the JSONObject,
set
them
for
(String currentAttributeName : attributeNames) {
if(currentCar.has(currentAttributeName)) {
//Get the attribute's type
String currentAttributeType = carDataObject.getAttributeDataType(currentAttributeName);
/ /
Create
a variable
for
storing the attribute value
in
Object currentAttributeValue =
null
;
//Long
if(currentAttributeType.
contains
(
"Long"
)) {
currentAttribu teValue = new Long(currentCar.getLong(currentAttributeName));
}
//BigDecimal
else
if(currentAttributeType.
contains
(
"BigDecimal"
)) {
currentAttributeValue = new BigDecimal(currentCar.getLong(currentAttributeName));
[19659884]}
//
Integer
else
if(currentAttributeType.
contains
(
"Integer"
)) {
currentAttributeValue = new
Integer
(currentCar.getInt(currentAttributeName));
}
//String
else
{
currentAttributeValue = currentCar.getString(currentAttributeName);
}
carDataObject.setAttributeValue(currentAttributeName, currentAttributeValue);
}
}
}
}
public
static
void readData (ICcDataObjectManager dataObjectManager) renvoie Exception {
// Ce sera l'objet qui contient la réponse JSON [19659117] à partir de
le reste API
JSONObject mongoDBCarDocument =
null [19659140];
[19659108]
//
//
Connectez
à
MongoDB
[19659069] //
// Récupère le gestionnaire de sources de données
IDatasourceManager gestionnaire de données = dataObjectManager.getDatasourceManager ();
// Récupérer notre source de données MongoDB
[19659069]
IDatasource mongoDBDatasource = datasourceManager.getDatasource (
"MongoDB"
);
[19659069]
//
Ouvrir
une connexion http
à
la base de données
URL mongoDBConnectionURL = nouvelle URL (mongoDBDatasource.getDatasourceConnectionURL ());
HttpURLConnexion mongoDBConnection = (HttpURLConnection) mongoDBConnectionURL.openConnection ();
// Puisque nous lisons, nous voulons
] à
utilisent la méthode HTTP
'GET' " title="" data-openoriginalimageonclick="true"/>
mongoDBConnection.setRequestMethod (
"OBTENIR"
);
[1945908]
//
Servez
le type de contenu
[1945909]
mongoDBConnection.setRequestProperty (
"Content-Type"
"application / json"
);
//Make the
connection
mongoDBConnection.
connect
();
//Print
out
a
rule
message
on
success [19659156]or
failure
int
mongoDBResponseCode = mongoDBConnection.getResponseCode();
if(mongoDBResponseCode >= 200 && mongoDBResponseCode < 300) {
dataObjectManager.postMessage(ICcDataObjectManager.INFO,
"MongoDB GET call SUCCEEDED with a status of "
+
Integer
.toString(mongoDBResponseCode),
null
);
}
else[19659105]{
dataObjectManager.postMessage(ICcDataObjectManager.INFO,
"MongoDB GET call FAILED with a status of "
+
Integer
.toString(mongoDBResponseCode),
null
);
}
//
Read
response data
BufferedReader jsonContentReader =
null
;
[19659069]
try {
jsonContentReader = new BufferedReader(new InputStreamReader(mongoDBConnection.getInputStream()));
//Get
all
the data
from
the stream
StringBuilder jsonResultStringBuilder = new StringBuilder();
//
Read
each line
of
the input
to
the
end
String lineOfJson =
null
;
while( (lineOfJson = jsonContentReader.readLine()) !=
null
) {
jsonResultStringBuilder.append(lineOfJson);
}
//
Convert
the entire message payload
into
a JSONObject
mongoDBCarDocument = new JSONObject(jsonResultStringBuilder.toString());
} finally {
if(jsonContentReader !=
null
) {
jsonContentReader.
close
();
}
mongoDBConnection.disconnect();
}
//
//
Convert
our JSON
to
DataObjects
//
//Get the
'cars'
array
out
of
the Document
JSONArray carsJsonArray = mongoDBCarDocument.getJSONArray(
"Cars"
);
//
Create
a data object based
off
of
each car
in
the array.
for
(
int
carsIndex = 0; carsIndex < carsJsonArray.length(); carsIndex++) {
//Get the JSONObject
out
of
the array
JSONObject currentCar = carsJsonArray.getJSONObject(carsIndex);
//
Create
the ICcDataObject
ICcDataObject carDataObject = dataObjectManager.createEntity(
"Car"
);
Set
attributeNames = carDataObject.getAttributeNames();
//Loop through the data object attributes
and
if they are properties
in
the JSONObject,
set
them
for
(String currentAttributeName : attributeNames) {
if(currentCar.has(currentAttributeName)) {
//Get the attribute's type
String currentAttributeType = carDataObject.getAttributeDataType(currentAttributeName);
/ /
Create
a variable
for
storing the attribute value
in
Object currentAttributeValue =
null
;
//Long
if(currentAttributeType.
contains
(
"Long"
)) {
currentAttribu teValue = new Long(currentCar.getLong(currentAttributeName));
}
//BigDecimal
else
if(currentAttributeType.
contains
(
"BigDecimal"
)) {
currentAttributeValue = new BigDecimal(currentCar.getLong(currentAttributeName));
[19659884]}
//
//
Connectez
à
MongoDB
//
// Récupère le gestionnaire de sources de données
IDatasourceManager gestionnaire de données = dataObjectManager.getDatasourceManager ();
// Récupérer notre source de données MongoDB
[19659069]
IDatasource mongoDBDatasource = datasourceManager.getDatasource (
"MongoDB"
);
[19659069]
//
Ouvrir
une connexion http
à
la base de données
URL mongoDBConnectionURL = nouvelle URL (mongoDBDatasource.getDatasourceConnectionURL ());
HttpURLConnexion mongoDBConnection = (HttpURLConnection) mongoDBConnectionURL.openConnection ();
// Puisque nous lisons, nous voulons
] à
utilisent la méthode HTTP
'GET' " title="" data-openoriginalimageonclick="true"/>
mongoDBConnection.setRequestMethod (
"OBTENIR"
);
[1945908]
//
Servez
le type de contenu
[1945909]
mongoDBConnection.setRequestProperty (
"Content-Type"
"application / json"
);
//Make the
connection
mongoDBConnection.
connect
();
//Print
out
a
rule
message
on
success [19659156]or
failure
int
mongoDBResponseCode = mongoDBConnection.getResponseCode();
if(mongoDBResponseCode >= 200 && mongoDBResponseCode < 300) {
dataObjectManager.postMessage(ICcDataObjectManager.INFO,
"MongoDB GET call SUCCEEDED with a status of "
+
Integer
.toString(mongoDBResponseCode),
null
);
}
else[19659105]{
dataObjectManager.postMessage(ICcDataObjectManager.INFO,
"MongoDB GET call FAILED with a status of "
+
Integer
.toString(mongoDBResponseCode),
null
);
}
//
Read
response data
BufferedReader jsonContentReader =
null
;
[19659069]
try {
jsonContentReader = new BufferedReader(new InputStreamReader(mongoDBConnection.getInputStream()));
//Get
all
the data
from
the stream
StringBuilder jsonResultStringBuilder = new StringBuilder();
//
Read
each line
of
the input
to
the
end
String lineOfJson =
null
;
while( (lineOfJson = jsonContentReader.readLine()) !=
null
) {
jsonResultStringBuilder.append(lineOfJson);
}
//
Convert
the entire message payload
into
a JSONObject
mongoDBCarDocument = new JSONObject(jsonResultStringBuilder.toString());
} finally {
if(jsonContentReader !=
null
) {
jsonContentReader.
close
();
}
mongoDBConnection.disconnect();
}
//
//
Convert
our JSON
to
DataObjects
//
//Get the
'cars'
array
out
of
the Document
JSONArray carsJsonArray = mongoDBCarDocument.getJSONArray(
"Cars"
);
//
Create
a data object based
off
of
each car
in
the array.
for
(
int
carsIndex = 0; carsIndex < carsJsonArray.length(); carsIndex++) {
//Get the JSONObject
out
of
the array
JSONObject currentCar = carsJsonArray.getJSONObject(carsIndex);
//
Create
the ICcDataObject
ICcDataObject carDataObject = dataObjectManager.createEntity(
"Car"
);
Set
attributeNames = carDataObject.getAttributeNames();
//Loop through the data object attributes
and
if they are properties
in
the JSONObject,
set
them
for
(String currentAttributeName : attributeNames) {
if(currentCar.has(currentAttributeName)) {
//Get the attribute's type
String currentAttributeType = carDataObject.getAttributeDataType(currentAttributeName);
/ /
Create
a variable
for
storing the attribute value
in
Object currentAttributeValue =
null
;
//Long
if(currentAttributeType.
contains
(
"Long"
)) {
currentAttribu teValue = new Long(currentCar.getLong(currentAttributeName));
}
//BigDecimal
else
if(currentAttributeType.
contains
(
"BigDecimal"
)) {
currentAttributeValue = new BigDecimal(currentCar.getLong(currentAttributeName));
[19659884]}
//
Ouvrir
une connexion http
à
la base de données
URL mongoDBConnectionURL = nouvelle URL (mongoDBDatasource.getDatasourceConnectionURL ());
HttpURLConnexion mongoDBConnection = (HttpURLConnection) mongoDBConnectionURL.openConnection ();
// Puisque nous lisons, nous voulons
] à
utilisent la méthode HTTP
'GET' " title="" data-openoriginalimageonclick="true"/>
mongoDBConnection.setRequestMethod (
"OBTENIR"
);
//
Servez
le type de contenu
mongoDBConnection.setRequestProperty (
"Content-Type"
"application / json"
);
//Make the
connection
mongoDBConnection.
connect
();
//Print
out
a
rule
message
on
success [19659156]or
failure
int
mongoDBResponseCode = mongoDBConnection.getResponseCode();
if(mongoDBResponseCode >= 200 && mongoDBResponseCode < 300) {
dataObjectManager.postMessage(ICcDataObjectManager.INFO,
"MongoDB GET call SUCCEEDED with a status of "
+
Integer
.toString(mongoDBResponseCode),
null
);
}
else[19659105]{
dataObjectManager.postMessage(ICcDataObjectManager.INFO,
"MongoDB GET call FAILED with a status of "
+
Integer
.toString(mongoDBResponseCode),
null
);
}
//
Read
response data
BufferedReader jsonContentReader =
null
;
try {
jsonContentReader = new BufferedReader(new InputStreamReader(mongoDBConnection.getInputStream()));
//Get
all
the data
from
the stream
StringBuilder jsonResultStringBuilder = new StringBuilder();
//
Read
each line
of
the input
to
the
end
String lineOfJson =
null
;
while( (lineOfJson = jsonContentReader.readLine()) !=
null
) {
jsonResultStringBuilder.append(lineOfJson);
}
//
Convert
the entire message payload
into
a JSONObject
mongoDBCarDocument = new JSONObject(jsonResultStringBuilder.toString());
} finally {
if(jsonContentReader !=
null
) {
jsonContentReader.
close
();
}
mongoDBConnection.disconnect();
}
//
//
Convert
our JSON
to
DataObjects
//
//Get the
'cars'
array
out
of
the Document
JSONArray carsJsonArray = mongoDBCarDocument.getJSONArray(
"Cars"
);
//
Create
a data object based
off
of
each car
in
the array.
for
(
int
carsIndex = 0; carsIndex < carsJsonArray.length(); carsIndex++) {
//Get the JSONObject
out
of
the array
JSONObject currentCar = carsJsonArray.getJSONObject(carsIndex);
//
Create
the ICcDataObject
ICcDataObject carDataObject = dataObjectManager.createEntity(
"Car"
);
Set
attributeNames = carDataObject.getAttributeNames();
//Loop through the data object attributes
and
if they are properties
in
the JSONObject,
set
them
for
(String currentAttributeName : attributeNames) {
if(currentCar.has(currentAttributeName)) {
//Get the attribute's type
String currentAttributeType = carDataObject.getAttributeDataType(currentAttributeName);
/ /
Create
a variable
for
storing the attribute value
in
Object currentAttributeValue =
null
;
//Long
if(currentAttributeType.
contains
(
"Long"
)) {
currentAttribu teValue = new Long(currentCar.getLong(currentAttributeName));
}
//BigDecimal
else
if(currentAttributeType.
contains
(
"BigDecimal"
)) {
currentAttributeValue = new BigDecimal(currentCar.getLong(currentAttributeName));
[19659884]}
//
Integer
else
if(currentAttributeType.
contains
(
"Integer"
)) {
currentAttributeValue = new
Integer
(currentCar.getInt(currentAttributeName));
}
//String
else
{
currentAttributeValue = currentCar.getString(currentAttributeName);
}
carDataObject.setAttributeValue(currentAttributeName, currentAttributeValue);
}
}
}
}
Step 3
Export the JAR file again and restart Corticon Studio.
Step 4
Create a new Ruleflow to handle retrieval from the database. Put the calculator Rulesheet in the Ruleflow to use the data retrieved from the database.
Step 5
Add a new Testsheet with the new Ruleflow as test subject to try out the new service. Run the test.
Step 6
If the retrieval succeeds, bring everything together by adding the first service callout, which saves information to the database, to the Ruleflow.
Step 7
Test again.
Step 8
Hit the API and see the updated MilesTillEmpty property.
That’s It!
With that, we're done with this example. If you’re feeling adventurous, you can also export the datasource configuration file and build a Decision Service for deploying to the server. Now, you know how to create a working service callout that can read from and store to a MongoDB instance using Corticon. And you can use this approach to create interesting and useful callouts with Corticon’s flexible datasource management API.
This is just one of many new improvements we’ve delivered with Corticon 5.7. Check out everything that’s new in this releasethen contact us to schedule a demo and let us know what you think.
Source link