import re import os files = [ 'src/main/java/com/kifi/api/controller/customer/CustomerController.java', 'src/main/java/com/kifi/api/controller/invoice/InvoiceController.java' ] for file in files: with open(file, 'r') as f: content = f.read() # Add import org.springframework.security.core.Authentication; if not present if 'import org.springframework.security.core.Authentication;' not in content: content = content.replace('import org.springframework.web.bind.annotation.*;', 'import org.springframework.security.core.Authentication;\nimport org.springframework.web.bind.annotation.*;') # Replace @RequestAttribute("userId") Long userId, with Authentication authentication, content = content.replace('@RequestAttribute("userId") Long userId,', 'Authentication authentication,') # Replace @RequestAttribute("userId") Long userId with Authentication authentication content = content.replace('@RequestAttribute("userId") Long userId', 'Authentication authentication') # Now, find all method declarations that have (..., Authentication authentication, ...) { # and insert Long userId = Long.valueOf(authentication.getDetails().toString()); right after the { # We can use regex to find method bodies pattern = re.compile(r'(public\s+[^\(]+\([^\)]*Authentication authentication[^\)]*\)\s*\{)') def replacer(match): return match.group(1) + '\n Long userId = Long.valueOf(authentication.getDetails().toString());' content = pattern.sub(replacer, content) with open(file, 'w') as f: f.write(content) print("Controllers fixed!")