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
Démarrer RESTHeart
Étape 1
mongo-uri : MongoDB: //127.0.0.1
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.483 [main] INFO org.restheart.Bootstrapper - version 3.2.2
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.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.423 [main] INFO org.restheart.Bootstrapper - URL / lié à la ressource MongoDB *
[19659058] 6229838428094629763
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
Étape 2
Créer une liste de règles pour faire le calcul.
Étape 3
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
Étape 3
Étape 4
Après l'importation, supprimez les fichiers Java et, éventuellement, renommez le projet
Etape 5
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
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
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
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]
}
// 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
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
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
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]
}
Exporter le fichier JAR et tester le nouveau service Légende
Etape 1
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
Étape 2
Ajouter le fichier JAR exporté au projet.
Étape 3
Étape 3
Créer un Ruleflow pour tester la nouvelle légende de service.
Étape 4
Étape 4
Faire une nouvelle fiche de test dans la règle et sélectionner le Ruleflow comme sujet de test
Étape 5
Étape 5
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
Récupération de données à partir de MongoDB
Étape 1
Étape 1
] 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];
//
//
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);
}
}
}
}
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
Step 7
Step 8
Hit the API and see the updated MilesTillEmpty property.
That’s It!
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.
] 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];
//
//
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);
}
}
}
}
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
Step 7
Step 8
Hit the API and see the updated MilesTillEmpty property.
That’s It!
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