Use Python to manage content in "Enterprise Architect" software from "sparx systems" - python

Currently i am working with enterprise architect software for creating packages, diagrams.
Is it possible to work in Enterprise architect software using python script ? Some example like Deleting and creating packages and diagrams etc. If so refer example code or link.

Sure, that's no problem.
import win32com.client
from singleton import Singleton
#Singleton
class Repository:
def __init__(self):
try:
self.eaRep = win32com.client.Dispatch("EA.App").Repository
models = self.eaRep.models
done = True
except Exception as e:
print (e)
done = False
(The #Singleton can be found on the net but you can work without it.)
Then in your main program you can access the repository like
rep = repository.Repository.Instance()
print rep.modules.getAt(0).name
etc. Have fun

import win32com.client
def open_repository(path, login, password):
eaApp = win32com.client.Dispatch("EA.App")
eaRep = eaApp.Repository
if login:
eaRep.SuppressSecurityDialog = True
eaRep.OpenFile2(path, login, password)
else:
eaRep.OpenFile(path)
return eaRep
please use OpenFile for open your model. (OpenFile2 if your model has enabled security)

Related

Sublime Text 3: Simple plug-in that changes color theme depending on remote host

Setup: I use Sublime Text 3 (ST), and I often have 2-3 different sessions with Sublime + iTerm2 open in different remote workspaces using RemoteSubl.
Using a simple batch script, I have set my iTerm2 to change colours (by activating a different iTerm user) when I ssh into a different host.
I was wondering if the same could be done for RemoteSubl? Such that when I open something from a specific host/ip/port, then Sublime opens in a different colour scheme, depending on the host/ip/port.
Solution attempt: So far, this is my attempt at building a small plugin that changes colour scheme when host is remote_host.
import sublime
import sublime_plugin
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, view):
try:
host = view.settings().get('remote_subl.host')
print(host)
if host == 'remote_host':
view.settings().set(
'color_scheme',
'Packages/Color Scheme - Default/Mariana.tmTheme')
print(view.settings().get('color_scheme'))
except:
print("Not on remote_host")
pass
Problem: When using using view.settings().get('remote_subl.host') in the console it works fine, and returns remote_host. However, when running the script view.run_command('example') I get the "Not on remote_host" print, indicating that the try loop fails for some reason.
After Keiths suggestions:
import sublime
import sublime_plugin
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, view):
view = self.view
host = view.settings().get('remote_subl.host', None)
print(host)
if host:
view.settings().set(
'color_scheme',
'Packages/Color Scheme - Default/Mariana.tmTheme')
print(view.settings().get('color_scheme'))
if host is None:
view.settings().set(
'color_scheme',
'Packages/Color Scheme - Default/Monokai.tmTheme')
print(view.settings().get('color_scheme'))
view isn't an argument that is passed to the TextCommand's run method. Instead, it is a property on self. Changing it to the following should work:
import sublime
import sublime_plugin
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
try:
host = view.settings().get('remote_subl.host')
print(host)
if host == 'dsintmain':
view.settings().set(
'color_scheme',
'Packages/Color Scheme - Default/Mariana.tmTheme')
print(view.settings().get('color_scheme'))
except:
print("Not on remote_host")
pass
I would also recommend printing the exception that occurs to help debug things like this in future. Even better, rather than expecting an exception in normal usage, provide a default value to the get method on the settings (i.e. None) and remove the exception handling altogether.
host = view.settings().get('remote_subl.host', None)
That way, if something does really go wrong, you'll see the traceback in the ST console.

mitmproxy load script using API (Python)

Good day,
I am trying to implement the mitmproxy into a bigger application.
For that, I need to be able to load those so called inline scripts in my code and not via command line. I could not find any helpful information about that in the documentation.
I am using mitmproxy version 0.17 and Python 2.7.
I know there is a newer version available, but that one didnt worked using the code examples.
This is the base code I have:
from mitmproxy import controller, proxy
from mitmproxy.proxy.server import ProxyServer
class ProxyMaster(controller.Master):
def __init__(self, server):
controller.Master.__init__(self, server)
def run(self):
try:
return controller.Master.run(self)
except KeyboardInterrupt:
self.shutdown()
def handle_request(self, flow):
flow.reply()
def handle_response(self, flow):
flow.reply()
config = proxy.ProxyConfig(port=8080)
server = ProxyServer(config)
m = ProxyMaster(server)
m.run()
How could I run this proxy using inline scripts?
Thanks in advance
I figured myself out a really ugly workaround.
Instead of using controller.Master I had to use flow.FlowMaster as the controller.Master lib does not seem to be able to handle inline scripts.
For some reason just loading the files did not work, they get triggered immediately, but not by running their matching hooks.
Instead of using the hooks which are not working, I am loading the matching functions as you can see in handle_response (try/except is missing and threading could be useful)
from mitmproxy import flow, proxy
from mitmproxy.proxy.server import ProxyServer
import imp
class ProxyMaster(flow.FlowMaster):
def run(self):
try:
return flow.FlowMaster.run(self)
except KeyboardInterrupt:
self.shutdown()
def handle_request(self, flow):
flow.reply()
def handle_response(self, flow):
for inline_script in self.scripts:
script_file = imp.load_source("response", inline_script.filename)
script_file.response(self, flow)
flow.reply()
proxy_config = proxy.ProxyConfig(port=8080)
server = ProxyServer(proxy_config)
state = flow.State()
m = ProxyMaster(server, state)
m.load_script("upsidedowninternet.py")
m.load_script("add_header.py")
m.run()
Any ideas about doing it the right way are appreciated.

cherrypy mvc with mysql issue

Problem setting up the MVC design with Cherrypy/MySQL. Here is the setup: (assume all the imports are correct)
##controller.py
class User(object):
def __init__(self):
self.model = model.User()
#cherrypy.expose
def index(self):
return 'some HTML to display user home'
## model.py
class Model(object):
_db = None
def __init__(self):
self._db = cherrypy.thread_data.db
class User(Model):
def getuser(self, email):
#get the user with _db and return result
##service.py
class UserService(object):
def __init__(self):
self._model = model.User()
def GET(self, email):
return self._model.getuser(email)
##starting the server
user = controller.User()
user.service = service.UserService()
cherrypy.tree.mount(user, '/user', self.config)
#app.merge(self.config)
cherrypy.engine.subscribe("start_thread", self._onThreadStart)
self._onThreadStart(-1)
def _onThreadStart(self, threadIndex):
cherrypy.thread_data.db = mysql.connect(**self.config["database"])
if __name__ == '__main__':
cherrypy.engine.start()
cherrypy.engine.block()
the above code has error in model.py at the line: cherrypy.thread_data.db.
I got:
AttributeError: '_ThreadData' object has no attribute 'db'
not sure why, could you please point me into the right direction? I can get the connection, and pull info from controller.py at User index, but not in model.py?
Please help.. thanks.
CherryPy doesn't decide for you what tools to use. It is up to you to pick the tools that fit you and your tasks the best. Thus CherryPy doesn't setup any database connection, your cherrypy.thread_data.db, it's your job.
Personally I use the same concept of responsibility separation, kind of MVC, for my CherryPy apps so there follow two possible ways to achieve what you want.
Design note
I would like to note that the simple solution of thread-mapped database connections, at least in case of MySQL, works pretty well in practice. And additional complexity of more old-fashioned connection pools may not be necessary.
There're however points that shouldn't be overlooked. Your database connection may become killed, lost or be in any other state that won't allow you to make queries on it. In this case reconnection must be preformed.
Also pay attention to avoid connection sharing between threads as it will result in hard-to-debug errors and Python crashes. In your example code, it may relate to a service dispatcher and its cache.
Bootstrapping phase
In your code that sets configuration, mounts CherryPy apps, etc.
bootstrap.py
# ...
import MySQLdb as mysql
def _onThreadStart(threadIndex):
cherrypy.thread_data.db = mysql.connect(**config['database'])
cherrypy.engine.subscribe('start_thread', _onThreadStart)
# useful for tests to have db connection on current thread
_onThreadStart(-1)
model.py
import cherrypy
import MySQLdb as mysql
class Model(object):
'''Your abstract model'''
_db = None
def __init__(self):
self._db = cherrypy.thread_data.db
try:
# reconnect if needed
self._db.ping(True)
except mysql.OperationalError:
pass
I wrote a complete CherryPy deployment tutorial, cherrypy-webapp-skeleton, a couple of years ago. You can take a look at the code, as the demo application uses exactly this approach.
Model property
To achieve less code coupling and to avoid import cycles it could be a good idea to move all database related code to model module. It may include, initial connection queries like setting operation timezone, making MySQLdb converters timzeone-aware, etc.
model.py
class Model(object):
def __init__(self):
try:
# reconnect if needed
self._db.ping(True)
except mysql.OperationalError:
pass
#property
def _db(self):
'''Thread-mapped connection accessor'''
if not hasattr(cherrypy.thread_data, 'db'):
cherrypy.thread_data.db = mysql.connect(**config['database'])
return cherrypy.thread_data.db

Abstracting Automated Testing Code Into Python Objects

I currently am doing some automated testing via Appium and python for testing an Android application. I'd like to abstract away some of the details so the tests read easier.
Right now I have just have an entire class doing the testing. For example, I'd like to turn this:
# authentication
self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
username = self.driver.find_element_by_name('username')
password = self.driver.find_element_by_name('pw')
username.send_keys('some username')
password.send_keys('some password')
login_button = self.driver.find_element_by_name('Login')
login_button.click()
Into something like this:
Authentication.login(self.driver, 'largedata_lgabriel#hmbnet.com', 'R3DruM24')
Where our Authentication class might look like this:
class Authentication:
def login(driver, username, password):
input_username = driver.find_element_by_name('username')
input_password = driver.find_element_by_name('pw')
input_username.send_keys(username)
input_password.send_keys(password)
login_button = driver.find_element_by_name('Login')
login_button.click()
This would require creating an 'Authentication' class, but I'm unsure how to import these methods into my main testing class, and how to share the web driver object.
Here's how I structure this kind of thing. I also use unittest.TestCase which I want to highly recommend for any python automation; it'll allow you to lean on setUpClass, tearDownClass (one-time for all the derivative tests), and setUp, tearDown (before each test function) to do a lot of the set up and tear down stuff you need to do.
For my iOS-specific Appium tests:
Base file: ios_base.py
class iOSBase(unittest.TestCase):
#classmethod
def setUpClass(self):
# Set up logging if you want it
# Set up the XCode and iOS Simulator details you need if you're doing iOS
# Set up Appium
def setUp(self):
# Per test, I like to log the start of each test
self.log.info("--- {0} ---".format(self._testMethodName))
# etc. on setUp / tearDown stuff, whatever you need
# Helpful function like you have in mind
def login(self, username, password):
# You'll get self.driver for free by using setUpClass, yea!
Test file(s): test_login.py
from ios_base import iOSBase
class iOSLoginTests(iOSBase):
# Add any additional login-specific setUp you might want here, see also super()
def test_valid_login(self):
self.login(good_username, good_password)
def test_login_invalid_username(self):
self.login(bad_username, good_password)
# etc.

How to self-handling cookies in PyObjC

I'm implementing a minimal browser in PyObjC for my study.
First, I googled about the way to use webkit from pyobjc and wrote code like below:
#coding: utf-8
import Foundation
import WebKit
import AppKit
import objc
def main():
app = AppKit.NSApplication.sharedApplication()
rect = Foundation.NSMakeRect(100,350,600,800)
win = AppKit.NSWindow.alloc()
win.initWithContentRect_styleMask_backing_defer_(
rect,
AppKit.NSTitledWindowMask |
AppKit.NSClosableWindowMask |
AppKit.NSResizableWindowMask |
AppKit.NSMiniaturizableWindowMask,
AppKit.NSBackingStoreBuffered,
False)
win.display()
win.orderFrontRegardless()
webview = WebKit.WebView.alloc()
webview.initWithFrame_(rect)
pageurl = Foundation.NSURL.URLWithString_("http://twitter.com")
req = Foundation.NSURLRequest.requestWithURL_(pageurl)
webview.mainFrame().loadRequest_(req)
win.setContentView_(webview)
app.run()
if __name__ == '__main__':
main()
It worked fine. But I noticed that this browser is sharing cookies with safari. I want it to be independent from my Safari.app.
So I googled again and I learned that I can override cookie-handling-methods by using NSMutableURLRequest.
Below is the second code I tested:
#coding: utf-8
import Foundation
import WebKit
import AppKit
import objc
def main():
app = AppKit.NSApplication.sharedApplication()
rect = Foundation.NSMakeRect(100,350,600,800)
win = AppKit.NSWindow.alloc()
win.initWithContentRect_styleMask_backing_defer_(
rect,
AppKit.NSTitledWindowMask |
AppKit.NSClosableWindowMask |
AppKit.NSResizableWindowMask |
AppKit.NSMiniaturizableWindowMask,
AppKit.NSBackingStoreBuffered,
False)
win.display()
win.orderFrontRegardless()
webview = WebKit.WebView.alloc()
webview.initWithFrame_(rect)
pageurl = Foundation.NSURL.URLWithString_("http://twitter.com")
req = Foundation.NSMutableURLRequest.requestWithURL_(pageurl)
Foundation.NSMutableURLRequest.setHTTPShouldHandleCookies_(req, False)
webview.mainFrame().loadRequest_(req)
win.setContentView_(webview)
app.run()
if __name__ == '__main__':
main()
This code show me a login screen of twitter :-)
But I couldn't login to twitter by this browser.
I input account name, password and pushed enter key. Then the browser displays the timeline of the account which I always use in Safari.app.
Yes, I know that it's proper result.
I didn't write anything about handling cookies.
And my question is on this point.
I want to know that:
How can I implement and use something like NSHTTPCookieStorage?
Can I write it in python?
Thank you.
To start with the easy part: if it is possible to do this in Objective-C it should also be possible with PyObjC.
That said, it is unclear to me if this is possible at all. How can I have multiple instances of webkit without sharing cookies? seems to indicate that it isn't although you might be able to do something through the webkit delegate.
An other alternative is to use NSURLProtocol, register a custom NSURLProtocol class for handling http/https requests and implement that using Python's urllib or urllib2. The PyDocURL example shows how to do this (that example registers a subclass for pydoc:// URLs).
More information on NSURLConnection is on Apple's website.
Updated with an implemention hint:
An alternate method might be to disable cookie storaga by NSHTTPCookieStorage (NSHTTPCookieStorage.sharedHTTPCookieStorage.setCookieAcceptPolicy_(NSHTTPCookieAcceptPolicyNever)). Then use the webkit resource loading delegate to handle cookies yourself:
Maintain your own cookie store (possibly using a class in urllib2)
In webView:resource:willSendRequest:redirectResponse:fromDataSource: add cookie headers based on information in that store
In webView:resource:didReceiveResponse:fromDataSource: check for "set-cookie" headers and update your own cookie store.
It shouldn't be too hard to do this, and I'd love to have this functionality as an example on the PyObjC website (or even as a utility class in the WebKit bindings for PyObjC).

Categories