-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutomaticASIS.py
More file actions
284 lines (230 loc) · 10.2 KB
/
Copy pathAutomaticASIS.py
File metadata and controls
284 lines (230 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import os
import shutil
import zipfile
import xml.etree.ElementTree as ET
import csv
import re
import secrets
import string
import sys
ADDRESS_KEYS_BY_TYPE = {
'HTTPS': ['urlPath'],
'HTTP': ['httpAddressWithoutQuery'],
'SFTP': ['host'],
'JMS': {
'Sender': ['QueueName_inbound'],
'Receiver': ['QueueName_outbound']
},
'ProcessDirect': ['address'],
'HCIOData': ['address'],
'SOAP': ['address'],
'PollingSFTP': ['host'],
'JDBC': ['alias']
}
TEMP_DIR = './temp'
def unzip_file(zip_path, extract_to):
if not os.path.isfile(zip_path):
raise FileNotFoundError(f"Zip file not found: {zip_path}")
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(extract_to)
def find_iflw_file(root_dir):
for root, _, files in os.walk(root_dir):
for file in files:
if file.endswith('.iflw'):
return os.path.join(root, file)
raise FileNotFoundError("No .iflw file found in extracted content.")
def strip_namespace(tag):
return tag.split('}', 1)[-1] if '}' in tag else tag
def load_parameters(root_dir):
params = {}
for root, _, files in os.walk(root_dir):
if 'parameters.prop' in files:
with open(os.path.join(root, 'parameters.prop'), encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
key = key.replace('\\ ', ' ').strip()
params[key] = value.strip()
break
return params
def parse_manifest(manifest_path):
bundle_name = version = bundle_id = None
if not os.path.isfile(manifest_path):
return bundle_name, version, bundle_id
with open(manifest_path, encoding='utf-8') as f:
content = f.read()
lines = []
for line in content.splitlines():
if line.startswith(' '):
lines[-1] += line[1:]
else:
lines.append(line)
for line in lines:
if line.startswith('Bundle-Name:'):
bundle_name = line.split(':', 1)[1].strip()
elif line.startswith('Bundle-Version:'):
version = line.split(':', 1)[1].strip()
elif line.startswith('Origin-Bundle-SymbolicName:'):
bundle_id = line.split(':', 1)[1].strip()
return bundle_name, version, bundle_id
def parse_package_name(export_info_path):
if not os.path.exists(export_info_path):
return 'Unknown'
with open(export_info_path, encoding='utf-8') as f:
for line in f:
if line.startswith('Name='):
return line.split('=', 1)[1].strip()
return 'Unknown'
def generate_prefix_from_package(package_name):
words = re.findall(r'[A-Z]{2,}|[A-Z][a-z]+', package_name)
prefix = ''.join(word[0] for word in words if word).upper()
return prefix[:5] if prefix else 'PKG'
def extract_message_flows(iflw_path, iflow_name, iflow_id, version, parameters, package_name, uid):
tree = ET.parse(iflw_path)
root = tree.getroot()
results = []
for elem in root.iter():
if strip_namespace(elem.tag) == "messageFlow":
message_data = {
'UID': uid,
'Package': package_name,
'Iflow': iflow_name,
'IflowID': iflow_id,
'IflowVersion': version,
'AdapterType': None,
'TransportProtocol': None,
'AdapterDirection': None,
'AdapterName': None,
'AdapterVersion': None,
'AdapterAddress': None,
'IsParametrized': False
}
for child in elem:
if strip_namespace(child.tag) == "extensionElements":
properties = {}
for prop in child.iter():
if strip_namespace(prop.tag) == "property":
key = value = None
for kv in prop:
tag = strip_namespace(kv.tag)
if tag == "key":
key = kv.text
elif tag == "value":
value = kv.text
if key:
properties[key] = value
message_data['AdapterType'] = properties.get('ComponentType')
message_data['AdapterDirection'] = properties.get('direction')
message_data['AdapterName'] = properties.get('Name')
message_data['TransportProtocol'] = properties.get('TransportProtocol')
message_data['AdapterVersion'] = properties.get('componentVersion')
ctype = message_data['AdapterType']
direction = message_data['AdapterDirection']
possible_keys = ADDRESS_KEYS_BY_TYPE.get(ctype, {})
if isinstance(possible_keys, dict):
possible_keys = possible_keys.get(direction, [])
address = None
for k in possible_keys:
if k in properties:
address = properties[k]
break
if not address:
for key, val in properties.items():
if val and 'url' in key.lower():
address = val
break
def substitute_param(match):
param_key = match.group(1).strip()
message_data['IsParametrized'] = True
return parameters.get(param_key, match.group(0))
if address:
address = re.sub(r'{{(.*?)}}', substitute_param, address)
message_data['AdapterAddress'] = address
if message_data['AdapterType']:
results.append(message_data)
return results
def save_to_csv(data, output_path):
with open(output_path, mode='w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(
file,
fieldnames=['UID', 'Package', 'Iflow', 'IflowID', 'IflowVersion', 'AdapterType', 'TransportProtocol',
'AdapterDirection', 'AdapterName', 'AdapterVersion', 'AdapterAddress', 'IsParametrized'],
quoting=csv.QUOTE_ALL
)
writer.writeheader()
writer.writerows(data)
def prepare_inner_zips(directory):
for root, _, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
if '_' in file and '.' not in file:
new_file_path = file_path + '.zip'
os.rename(file_path, new_file_path)
def process_inner_zip(zip_path, package_name, iflow_index, uid_prefix):
extract_path = os.path.splitext(zip_path)[0]
unzip_file(zip_path, extract_path)
iflw_file = find_iflw_file(extract_path)
parameters = load_parameters(extract_path)
manifest_path = os.path.join(extract_path, 'META-INF', 'MANIFEST.MF')
iflow_name, version, iflow_id = parse_manifest(manifest_path)
uid = f"{uid_prefix}-{iflow_index}"
return extract_message_flows(iflw_file, iflow_name, iflow_id, version, parameters, package_name, uid)
def generate_short_id(length=7):
return ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(length))
def main():
if len(sys.argv) < 2:
print("❌ No input directory provided.")
return
input_dir = sys.argv[1]
output_uid = generate_short_id()
output_csv = os.path.join(input_dir, f'automatic_asis_{output_uid}.csv')
all_flows = []
package_iflow_counter = {}
if os.path.exists(TEMP_DIR):
shutil.rmtree(TEMP_DIR)
os.makedirs(TEMP_DIR)
zip_files = [f for f in os.listdir(input_dir) if f.lower().endswith('.zip')]
if not zip_files:
print("❌ No zip files found.")
return
try:
for zip_file in zip_files:
zip_path = os.path.join(input_dir, zip_file)
short_id = generate_short_id()
extract_dir = os.path.join(TEMP_DIR, short_id)
try:
unzip_file(zip_path, extract_dir)
export_info_path = os.path.join(extract_dir, 'ExportInformation.info')
package_name = parse_package_name(export_info_path)
uid_prefix = generate_prefix_from_package(package_name)
package_iflow_counter.setdefault(uid_prefix, 0)
prepare_inner_zips(extract_dir)
inner_zips = [
os.path.join(root, f)
for root, _, files in os.walk(extract_dir)
for f in files if f.endswith('.zip')
]
if not inner_zips:
print(f"⚠️ No inner zip files found in '{zip_file}'.")
for inner_zip in inner_zips:
try:
package_iflow_counter[uid_prefix] += 1
index = package_iflow_counter[uid_prefix]
flows = process_inner_zip(inner_zip, package_name, index, uid_prefix)
all_flows.extend(flows)
print(f"✅ Processed inner zip '{os.path.basename(inner_zip)}' with {len(flows)} adapters.")
except Exception as e:
print(f"❌ Error processing inner zip '{inner_zip}': {e}")
except Exception as e:
print(f"❌ Error unzipping '{zip_file}': {e}")
if all_flows:
save_to_csv(all_flows, output_csv)
print(f"✅ Saved {len(all_flows)} adapters into '{output_csv}'.")
else:
print("❌ No adapters found to save.")
finally:
if os.path.exists(TEMP_DIR):
shutil.rmtree(TEMP_DIR)
if __name__ == '__main__':
main()