import re
def extract_java_method_names(file_path):
# 주석 제거를 위한 정규 표현식
comment_pattern = r"(//.*?$|/\*.*?\*/|/\*\*.*?\*/)" # //, /* */, /** */ 주석
# 메서드 정의 패턴 (접근 제어자, 반환형 포함, 클래스 제외)
method_pattern = r"(?:public|protected|private|static|\s)*\s+\w+\s+(\w+)\s*\(.*?\)\s*\{" # 함수 이름만 추출
# 클래스 정의 패턴
class_pattern = r"(?:public|protected|private|\s)*\s*class\s+(\w+)" # 클래스 이름 추출
# 블록 키워드 (제외할 블록 리스트)
block_keywords = {"if", "else", "try", "catch", "finally", "while", "for", "switch", "do", "synchronized"}
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 주석 제거
content_no_comments = re.sub(comment_pattern, "", content, flags=re.S | re.M)
# 클래스 이름 추출
class_names = re.findall(class_pattern, content_no_comments)
# 메서드 이름 추출
raw_methods = re.findall(method_pattern, content_no_comments)
# 블록 키워드와 클래스 이름 제외
methods = [method for method in raw_methods if method not in block_keywords and method not in class_names]
return methods
# 파일 경로 지정
java_file_path = "YourJavaFile.java"
method_names = extract_java_method_names(java_file_path)
# 결과 출력
print("Extracted Method Names:")
for name in method_names:
print(name)
=============
import re
def extract_java_methods(file_path):
# 정규식 패턴
comment_pattern = r"(//.*?$|/\*.*?\*/|/\*\*.*?\*/)" # 주석 제거
block_keywords = {"if", "else", "try", "catch", "finally", "while", "for", "switch", "do", "synchronized"} # 블록 키워드
method_pattern = r"(?:public|protected|private|static|\s)*\s+\w+\s+(\w+)\s*\(.*?\)\s*\{" # 메서드 패턴
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 주석 제거
content_no_comments = re.sub(comment_pattern, "", content, flags=re.S | re.M)
# 메서드 추출
raw_methods = re.findall(method_pattern, content_no_comments)
# 블록 키워드 제외
methods = []
for method in raw_methods:
method_name = method.split('(')[0].strip().split()[-1] # 메서드 이름 추출
if method_name not in block_keywords:
methods.append(method.strip("{").strip())
return methods
# 파일 경로 지정
java_file_path = "YourJavaFile.java"
methods = extract_java_methods(java_file_path)
# 결과 출력
print("Extracted Methods:")
for method in methods:
print(method)
=====================
import re
import os
import pandas as pd
# Initialize object_list and java_list
object_list = ["TABLE1", "TABLE2", "VIEW1", "SEQUENCE1"] # Example DB objects
java_list = ["one.java", "two.java", "three.java"] # Example Java files
# Placeholder for the results
object_loc_results = []
cross_map_results = []
# Helper function to extract functions and strings from Java code
def extract_functions_and_strings(java_code):
functions = re.findall(r"\b(public|private|protected)?\s+\w+\s+(\w+)\s*\(.*?\)", java_code)
functions = [func[1] for func in functions] # Extract only function names
strings = re.findall(r'"(.*?)"', java_code)
return functions, strings
# Helper function to find DB object usage
for java_file in java_list:
if not os.path.exists(java_file):
print(f"File not found: {java_file}")
continue
with open(java_file, "r") as file:
java_code = file.read()
functions, strings = extract_functions_and_strings(java_code)
for obj in object_list:
func_count = sum(obj in func for func in functions)
string_count = strings.count(obj)
total_count = func_count + string_count
if total_count > 0:
object_loc_results.append({
"java_file": java_file,
"object_name": obj,
"found_in": "FUNCTION" if func_count else "STRING",
"count": total_count
})
# Mapping function calls between Java files
for func in functions:
for other_file in java_list:
if other_file == java_file:
continue
with open(other_file, "r") as other_file_obj:
other_code = other_file_obj.read()
if re.search(rf"\b{func}\b", other_code):
for obj in object_list:
if obj in java_code:
cross_map_results.append({
"caller_java_code": java_file,
"caller_java_func": func,
"callee_java_code": other_file,
"callee_java_func": func,
"target_object_nm": obj
})
# Save results to Excel
object_loc_df = pd.DataFrame(object_loc_results)
cross_map_df = pd.DataFrame(cross_map_results)
with pd.ExcelWriter("db_object_mapping.xlsx") as writer:
object_loc_df.to_excel(writer, sheet_name="object_loc_mas", index=False)
cross_map_df.to_excel(writer, sheet_name="cross_map_mas", index=False)
print("Results saved to db_object_mapping.xlsx")
'정리 > IT공부' 카테고리의 다른 글
[Python] 빠르게 Flask를 이용해 Microservice Architecture 구현 (0) | 2023.11.11 |
---|---|
[IT지식] SessionNotCreatedException 해결하기 (0) | 2023.11.10 |
[Java] SuppressWarnings 종류 (1) | 2023.11.06 |
[IT] 윈도우 작업 스케줄러로 특정한 시간에 특정 파일 실행하기 (직접실행 안열림) (0) | 2023.11.04 |
[IT] 윈도우 시작 프로그램 활용 (지연 실행, 프로그램 실행 후 실행) (0) | 2023.11.03 |