Skip to content

Commit 407f76b

Browse files
committed
Refactor import statements to use iop instead of grongier.pex
1 parent 719ef83 commit 407f76b

File tree

20 files changed

+1188
-12
lines changed

20 files changed

+1188
-12
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ repository = "https://github.com/grongierisc/interoperability-embedded-python"
3939
issues = "https://github.com/grongierisc/interoperability-embedded-python/issues"
4040

4141
[project.scripts]
42-
iop = "grongier.pex._cli:main"
42+
iop = "iop._cli:main"
4343

4444
[tool.setuptools.packages.find]
4545
where = ["src"]

src/iop/_director.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ def test_component(target,message=None,classname=None,body=None):
255255
# else create a python object
256256
else:
257257
# python message are casted to Grongier.PEX.Message
258-
message = iris.cls("Grongier.PEX.Message")._New()
258+
message = iris.cls("IOP.Message")._New()
259259
message.classname = classname
260260
if body:
261261
message.jstr = _Utils.string_to_stream(body)
@@ -264,7 +264,7 @@ def test_component(target,message=None,classname=None,body=None):
264264
# serialize the message
265265
business_host = _BusinessHost()
266266
serial_message = business_host._dispatch_serializer(message)
267-
response = iris.cls('Grongier.PEX.Utils').dispatchTestComponent(target,serial_message)
267+
response = iris.cls('IOP.Utils').dispatchTestComponent(target,serial_message)
268268
try:
269269
deserialized_response = business_host._dispatch_deserializer(response)
270270
except ImportError as e:

src/tests/registerFiles/bo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

22

3-
from iop import BusinessOperation
3+
from grongier.pex import BusinessOperation
44

55
import iris
66

src/tests/registerFiles/bp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from iop import BusinessProcess
1+
from grongier.pex import BusinessProcess
22

33
from message import PostMessage
44

src/tests/registerFiles/bs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from iop import BusinessService
1+
from grongier.pex import BusinessService
22

33
import iris
44

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import iop
2+
import requests
3+
import iris
4+
import json
5+
6+
class RedditInboundAdapter(iop.InboundAdapter):
7+
8+
def OnInit(self):
9+
10+
if not hasattr(self,'Feed'):
11+
self.Feed = "/new/"
12+
13+
if self.Limit is None:
14+
raise TypeError('no Limit field')
15+
16+
self.LastPostName = ""
17+
18+
return 1
19+
20+
def OnTask(self):
21+
self.LOGINFO(f"LIMIT:{self.Limit}")
22+
if self.Feed == "" :
23+
return 1
24+
25+
tSC = 1
26+
# HTTP Request
27+
try:
28+
server = "https://www.reddit.com"
29+
requestString = self.Feed+".json?before="+self.LastPostName+"&limit="+self.Limit
30+
self.LOGINFO(server+requestString)
31+
response = requests.get(server+requestString)
32+
response.raise_for_status()
33+
34+
data = response.json()
35+
updateLast = 0
36+
37+
for key, value in enumerate(data['data']['children']):
38+
if value['data']['selftext']=="":
39+
continue
40+
post = iris.cls('dc.Reddit.Post')._New()
41+
post._JSONImport(json.dumps(value['data']))
42+
post.OriginalJSON = json.dumps(value)
43+
if not updateLast:
44+
self.LastPostName = value['data']['name']
45+
updateLast = 1
46+
response = self.BusinessHost.ProcessInput(post)
47+
except requests.exceptions.HTTPError as err:
48+
if err.response.status_code == 429:
49+
self.LOGWARNING(err.__str__())
50+
else:
51+
raise err
52+
except Exception as err:
53+
self.LOGERROR(err.__str__())
54+
raise err
55+
56+
return tSC

src/tests/registerFilesIop/bo.py

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
2+
3+
from iop import BusinessOperation
4+
5+
import iris
6+
7+
from message import MyResponse
8+
9+
import os
10+
import datetime
11+
import smtplib
12+
from email.mime.text import MIMEText
13+
14+
class EmailOperation(BusinessOperation):
15+
16+
def OnMessage(self, pRequest):
17+
18+
sender = 'admin@example.com'
19+
receivers = [ pRequest.ToEmailAddress ]
20+
21+
22+
port = 1025
23+
msg = MIMEText('This is test mail')
24+
25+
msg['Subject'] = pRequest.Found+" found"
26+
msg['From'] = 'admin@example.com'
27+
msg['To'] = pRequest.ToEmailAddress
28+
29+
with smtplib.SMTP('localhost', port) as server:
30+
31+
# server.login('username', 'password')
32+
server.sendmail(sender, receivers, msg.as_string())
33+
print("Successfully sent email")
34+
35+
36+
37+
class EmailOperationWithIrisAdapter(BusinessOperation):
38+
39+
def get_adapter_type():
40+
"""
41+
Name of the registred Adapter
42+
"""
43+
return "EnsLib.EMail.OutboundAdapter"
44+
45+
def OnMessage(self, pRequest):
46+
47+
mailMessage = iris.cls("%Net.MailMessage")._New()
48+
mailMessage.Subject = pRequest.Found+" found"
49+
self.Adapter.AddRecipients(mailMessage,pRequest.ToEmailAddress)
50+
mailMessage.Charset="UTF-8"
51+
52+
title = author = url = ""
53+
if (pRequest.Post is not None) :
54+
title = pRequest.Post.title
55+
author = pRequest.Post.author
56+
url = pRequest.Post.url
57+
58+
mailMessage.TextData.WriteLine("More info:")
59+
mailMessage.TextData.WriteLine("Title: "+title)
60+
mailMessage.TextData.WriteLine("Author: "+author)
61+
mailMessage.TextData.WriteLine("URL: "+url)
62+
63+
return self.Adapter.SendMail(mailMessage)
64+
65+
class FileOperation(BusinessOperation):
66+
67+
def OnInit(self):
68+
if hasattr(self,'Path'):
69+
os.chdir(self.Path)
70+
71+
def OnMessage(self, pRequest):
72+
73+
ts = title = author = url = text = ""
74+
75+
if (pRequest.Post is not None):
76+
title = pRequest.Post.Title
77+
author = pRequest.Post.Author
78+
url = pRequest.Post.Url
79+
text = pRequest.Post.Selftext
80+
ts = datetime.datetime.fromtimestamp(pRequest.Post.CreatedUTC).__str__()
81+
82+
line = ts+" : "+title+" : "+author+" : "+url
83+
filename = pRequest.Found+".txt"
84+
85+
86+
self.PutLine(filename, line)
87+
self.PutLine(filename, "")
88+
self.PutLine(filename, text)
89+
self.PutLine(filename, " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *")
90+
91+
return
92+
93+
def PutLine(self,filename,string):
94+
try:
95+
with open(filename, "a",encoding="utf-8") as outfile:
96+
outfile.write(string)
97+
except Exception as e:
98+
raise e
99+
100+
class FileOperationWithIrisAdapter(BusinessOperation):
101+
102+
def get_adapter_type():
103+
"""
104+
Name of the registred Adapter
105+
"""
106+
return "EnsLib.File.OutboundAdapter"
107+
108+
def OnMessage(self, pRequest):
109+
110+
ts = title = author = url = text = ""
111+
112+
if (pRequest.Post != ""):
113+
title = pRequest.Post.Title
114+
author = pRequest.Post.Author
115+
url = pRequest.Post.Url
116+
text = pRequest.Post.Selftext
117+
ts = iris.cls("%Library.PosixTime").LogicalToOdbc(iris.cls("%Library.PosixTime").UnixTimeToLogical(pRequest.Post.CreatedUTC))
118+
119+
line = ts+" : "+title+" : "+author+" : "+url
120+
filename = pRequest.Found+".txt"
121+
122+
self.Adapter.PutLine(filename, line)
123+
self.Adapter.PutLine(filename, "")
124+
self.Adapter.PutLine(filename, text)
125+
self.Adapter.PutLine(filename, " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *")
126+
127+
return
128+
129+
class MyOperation(BusinessOperation):
130+
131+
def OnMessage(self, request):
132+
self.LOGINFO('hello')
133+
return MyResponse(request.StringValue)
134+
135+
if __name__ == "__main__":
136+
137+
op = FileOperation()
138+
from message import PostMessage,PostClass
139+
msg = PostMessage(PostClass('foo','foo','foo','foo',1,'foo'),'bar','bar')
140+
op.OnMessage(msg)

src/tests/registerFilesIop/bp.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from iop import BusinessProcess
2+
3+
from message import PostMessage
4+
5+
class FilterPostRoutingRule(BusinessProcess):
6+
7+
def OnInit(self):
8+
9+
if not hasattr(self,'Target'):
10+
self.Target = "Python.FileOperation"
11+
12+
return
13+
14+
def OnRequest(self, request: PostMessage):
15+
if 'dog'.upper() in request.Post.Selftext.upper():
16+
request.ToEmailAddress = 'dog@company.com'
17+
request.Found = 'Dog'
18+
if 'cat'.upper() in request.Post.Selftext.upper():
19+
request.ToEmailAddress = 'cat@company.com'
20+
request.Found = 'Cat'
21+
return self.SendRequestSync(self.Target,request)

src/tests/registerFilesIop/bs.py

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
from iop import BusinessService
2+
3+
import iris
4+
5+
import json
6+
7+
from message import PostMessage
8+
from obj import PostClass
9+
10+
class RedditService(BusinessService):
11+
12+
def get_adapter_type():
13+
"""
14+
Name of the registred Adapter
15+
"""
16+
return "Ens.InboundAdapter"
17+
18+
def OnInit(self):
19+
20+
if not hasattr(self,'Feed'):
21+
self.Feed = "/new/"
22+
23+
if not hasattr(self,'Limit'):
24+
raise TypeError('no Limit field')
25+
26+
if not hasattr(self,'Target'):
27+
self.Target = "Python.FilterPostRoutingRule"
28+
29+
self.LastPostName = ""
30+
31+
return 1
32+
33+
def OnProcessInput(self,request):
34+
35+
post = self.OnTask()
36+
if post is not None:
37+
msg = PostMessage()
38+
msg.Post = post
39+
self.send_request_sync("test",msg)
40+
41+
def OnTask(self) -> PostClass:
42+
43+
try:
44+
server = "https://www.reddit.com"
45+
requestString = self.Feed+".json?before="+self.LastPostName+"&limit="+self.Limit
46+
47+
response = requests.get(server+requestString)
48+
# response.raise_for_status()
49+
50+
# data = response.json()
51+
data = json.loads("""
52+
{"data":{"children":[{"kind": "t3", "data": {"approved_at_utc": null, "subreddit": "Livros", "selftext": " Ol\\u00e1 amigos do Cat Reddit; \\n\\n​\\n\\nGostaria de vir compartilhar um pensamento que venho tendo nessas \\u00faltimas semanas. \\n\\n\\u201cO incentivo \\u00e0 leitura nunca foi t\\u00e3o importante em compara\\u00e7\\u00e3o as d\\u00e9cadas anteriores.\\u201d\\n\\nNunca foi t\\u00e3o dif\\u00edcil ser brasileiro: infla\\u00e7\\u00e3o que supera 2 d\\u00edgitos, governo federal que n\\u00e3o liga pra educa\\u00e7\\u00e3o da popula\\u00e7\\u00e3o e alto n\\u00edvel de desemprego. \\n\\nDiante desse cen\\u00e1rio preocupante, digo que tenho muito orgulho do meu trabalho, exercendo ele vejo uma mudan\\u00e7a real em como a popula\\u00e7\\u00e3o est\\u00e1 cada vez mais interessada e curiosa na busca de desenvolvimento pessoal. Vejo significado e prop\\u00f3sito na minha vida exercendo minha profiss\\u00e3o. Espalho conhecimento por um pre\\u00e7o bastante acess\\u00edvel em compara\\u00e7\\u00e3o a outras livrarias. \\n\\nAl\\u00e9m disso, voc\\u00eas me ajudam muito quando compram um livro. A cada dia estou mais perto da quantia necess\\u00e1ria para come\\u00e7ar meu mestrado em Coimbra. \\n\\nObrigados a todos que v\\u00eam me apoiando e que seguem minha jornada.\\n\\n​\\n\\nGrande abra\\u00e7o a todos.", "author_fullname": "t2_1g037lor", "saved": false, "mod_reason_title": null, "gilded": 0, "clicked": false, "title": "VENDER LIVROS \\u00c9 UM DOS TRABALHO MAIS SIGNIFICANTES EM UMA \\u00c9POCA DE OBSCURANTISMO.", "link_flair_richtext": [], "subreddit_name_prefixed": "r/Livros", "hidden": false, "pwls": null, "link_flair_css_class": "", "downs": 0, "thumbnail_height": null, "top_awarded_type": null, "hide_score": true, "name": "t3_tjflyd", "quarantine": false, "link_flair_text_color": "light", "upvote_ratio": 1.0, "author_flair_background_color": null, "subreddit_type": "public", "ups": 1, "total_awards_received": 0, "media_embed": {}, "thumbnail_width": null, "author_flair_template_id": null, "is_original_content": false, "user_reports": [], "secure_media": null, "is_reddit_media_domain": false, "is_meta": false, "category": null, "secure_media_embed": {}, "link_flair_text": "Mercado editorial e pol\\u00edticas p\\u00fablicas", "can_mod_post": false, "score": 1, "approved_by": null, "is_created_from_ads_ui": false, "author_premium": false, "thumbnail": "self", "edited": false, "author_flair_css_class": null, "author_flair_richtext": [], "gildings": {}, "content_categories": null, "is_self": true, "mod_note": null, "created": 1647879710.0, "link_flair_type": "text", "wls": null, "removed_by_category": null, "banned_by": null, "author_flair_type": "text", "domain": "self.Livros", "allow_live_comments": false, "selftext_html": "<!-- SC_OFF --><div class=\\"md\\"><p>Ol\\u00e1 amigos do Reddit; </p>\\n\\n<p>​</p>\\n\\n<p>Gostaria de vir compartilhar um pensamento que venho tendo nessas \\u00faltimas semanas. </p>\\n\\n<p>\\u201cO incentivo \\u00e0 leitura nunca foi t\\u00e3o importante em compara\\u00e7\\u00e3o as d\\u00e9cadas anteriores.\\u201d</p>\\n\\n<p>Nunca foi t\\u00e3o dif\\u00edcil ser brasileiro: infla\\u00e7\\u00e3o que supera 2 d\\u00edgitos, governo federal que n\\u00e3o liga pra educa\\u00e7\\u00e3o da popula\\u00e7\\u00e3o e alto n\\u00edvel de desemprego. </p>\\n\\n<p>Diante desse cen\\u00e1rio preocupante, digo que tenho muito orgulho do meu trabalho, exercendo ele vejo uma mudan\\u00e7a real em como a popula\\u00e7\\u00e3o est\\u00e1 cada vez mais interessada e curiosa na busca de desenvolvimento pessoal. Vejo significado e prop\\u00f3sito na minha vida exercendo minha profiss\\u00e3o. Espalho conhecimento por um pre\\u00e7o bastante acess\\u00edvel em compara\\u00e7\\u00e3o a outras livrarias. </p>\\n\\n<p>Al\\u00e9m disso, voc\\u00eas me ajudam muito quando compram um livro. A cada dia estou mais perto da quantia necess\\u00e1ria para come\\u00e7ar meu mestrado em Coimbra. </p>\\n\\n<p>Obrigados a todos que v\\u00eam me apoiando e que seguem minha jornada.</p>\\n\\n<p>​</p>\\n\\n<p>Grande abra\\u00e7o a todos.</p>\\n</div><!-- SC_ON -->", "likes": null, "suggested_sort": "confidence", "banned_at_utc": null, "view_count": null, "archived": false, "no_follow": true, "is_crosspostable": false, "pinned": false, "over_18": false, "all_awardings": [], "awarders": [], "media_only": false, "link_flair_template_id": "6bfc7288-b343-11ea-99c8-0e35844b0e2f", "can_gild": false, "spoiler": false, "locked": false, "author_flair_text": null, "treatment_tags": [], "visited": false, "removed_by": null, "num_reports": null, "distinguished": null, "subreddit_id": "t5_2tlr4", "author_is_blocked": false, "mod_reason_by": null, "removal_reason": null, "link_flair_background_color": "#6b6031", "id": "tjflyd", "is_robot_indexable": true, "report_reasons": null, "author": "Afteroui", "discussion_type": null, "num_comments": 0, "send_replies": true, "whitelist_status": null, "contest_mode": false, "mod_reports": [], "author_patreon_flair": false, "author_flair_text_color": null, "permalink": "/r/Livros/comments/tjflyd/vender_livros_\\u00e9_um_dos_trabalho_mais/", "parent_whitelist_status": null, "stickied": false, "url": "https://www.reddit.com/r/Livros/comments/tjflyd/vender_livros_\\u00e9_um_dos_trabalho_mais/", "subreddit_subscribers": 12094, "created_utc": 1647879710.0, "num_crossposts": 0, "media": null, "is_video": false}}]}}
53+
""")
54+
updateLast = 0
55+
56+
for key, value in enumerate(data['data']['children']):
57+
if value['data']['selftext']=="":
58+
continue
59+
post = PostClass.from_dict(value['data'])
60+
post.OriginalJSON = json.dumps(value)
61+
62+
if not updateLast:
63+
self.LastPostName = value['data']['name']
64+
updateLast = 1
65+
return post
66+
67+
except requests.exceptions.HTTPError as err:
68+
if err.response.status_code == 429:
69+
self.LOGWARNING(err.__str__())
70+
else:
71+
raise err
72+
except Exception as err:
73+
self.LOGERROR(err.__str__())
74+
raise err
75+
76+
return None
77+
78+
79+
class RedditServiceWithIrisAdapter(BusinessService):
80+
81+
def get_adapter_type():
82+
"""
83+
Name of the registred Adapter
84+
"""
85+
return "dc.Reddit.InboundAdapter"
86+
87+
def OnProcessInput(self, messageInput):
88+
msg = iris.cls("dc.Demo.PostMessage")._New()
89+
msg.Post = messageInput
90+
return self.SendRequestSync(self.Target,msg)
91+
92+
def OnInit(self):
93+
94+
if not hasattr(self,'Target'):
95+
self.Target = "Python.FilterPostRoutingRule"
96+
97+
return
98+
99+
class RedditServiceWithPexAdapter(BusinessService):
100+
101+
def get_adapter_type():
102+
"""
103+
Name of the registred Adapter
104+
"""
105+
return "Python.RedditInboundAdapter"
106+
107+
def OnProcessInput(self, messageInput):
108+
msg = iris.cls("dc.Demo.PostMessage")._New()
109+
msg.Post = messageInput
110+
return self.SendRequestSync(self.Target,msg)
111+
112+
def OnInit(self):
113+
114+
if not hasattr(self,'Target'):
115+
self.Target = "Python.FilterPostRoutingRule"
116+
117+
return
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from iop import BusinessService
2+
3+
class BS(BusinessService):
4+
5+
@staticmethod
6+
def get_adapter_type():
7+
return 'EnsLib.File.InboundAdapter'

0 commit comments

Comments
 (0)