📢 转载信息
原文作者:Aditya Prakash, Jihye Seo, and Yash Shah
许多企业都背负着建立在过时技术上的关键任务系统,这些系统维护和扩展起来愈发困难。
本文演示了如何使用带有代理式工作流的 Amazon Bedrock Converse API 和 Amazon Nova Premier,系统地将遗留的 C 代码迁移到现代的 Java/Spring 框架应用程序中。通过将迁移过程分解为专业的代理角色并实施稳健的反馈循环,组织可以实现以下目标:
- 减少迁移时间和成本 – 自动化处理重复的转换任务,而人类工程师则专注于高价值工作。
- 提高代码质量 – 专业验证代理确保迁移后的代码遵循现代最佳实践。
- 最大限度地降低风险 – 系统化的方法可防止在迁移过程中丢失关键业务逻辑。
- 实现云集成 – 生成的 Java/Spring 代码可以无缝集成到 AWS 服务中。
挑战
将代码从遗留系统迁移到现代框架带来了若干重大挑战,需要结合人工智能能力和人类专业知识的平衡方法:
- 语言范式差异 – 将 C 代码转换为 Java 需要应对内存管理、错误处理和编程范式的基本差异。C 的过程性特点和直接内存操作与 Java 的面向对象方法和自动内存管理形成了鲜明对比。虽然人工智能可以自动处理许多语法转换,但开发人员必须审查和验证这些转换的语义正确性。
- 架构复杂性 – 遗留系统通常具有组件之间复杂的相互依赖关系,需要人工分析和规划。在我们的案例中,C 代码库包含模块之间错综复杂的关系,某些 TP(事务程序)连接到多达 12 个其他模块。人类开发人员必须创建依赖关系映射并确定迁移顺序,通常从依赖关系最少的叶节点开始。人工智能可以协助识别这些关系,但关于迁移序列的战略决策需要人类的判断。
- 维护业务逻辑 – 确保在翻译过程中准确保留关键业务逻辑需要持续的人工监督。我们的分析显示,虽然对于简单、结构良好的代码,自动迁移非常成功,但嵌入在大型文件(超过 700 行)中的复杂业务逻辑需要仔细的人工审查和经常进行的手动细化,以防止错误或遗漏。
- 不一致的命名和结构 – 遗留代码通常包含不一致的命名约定和结构,在迁移过程中必须将其标准化。人工智能可以处理许多常规转换——例如转换函数名称中的字母数字 ID、将 C 风格的错误代码转换为 Java 异常,以及将 C 结构体转换为 Java 类——但人类开发人员必须建立命名标准并审查自动化转换可能存在歧义的边缘情况。
- 集成复杂性 – 在转换单个文件后,人工指导的集成对于创建统一的应用程序至关重要。在单个文件转换过程中,原始 C 文件中一致的变量名往往会变得不一致,这需要开发人员进行协调工作并促进适当的模块间通信。
- 质量保证 – 验证转换后的代码是否保持与原始代码的功能等效性,需要结合自动化测试和人工验证。这对于复杂的业务逻辑尤其重要,因为细微的差异可能导致重大问题。开发人员必须设计全面的测试套件并进行彻底的代码审查,以确保迁移的准确性。
这些挑战要求采用系统化的方法,将大型语言模型 (LLM) 的模式识别能力与结构化工作流程和必要的监督相结合,以取得成功的转换成果。关键在于利用人工智能处理常规转换,同时让人类参与战略决策、复杂逻辑验证和质量保证环节。
解决方案概述
该解决方案使用 Amazon Bedrock Converse API 结合 Amazon Nova Premier,通过系统化的代理式工作流将遗留的 C 代码转换为现代的 Java/Spring 框架代码。这种方法将复杂的迁移过程分解为可管理的步骤,允许迭代改进和处理 token 限制。解决方案架构由几个关键组件构成:
- 代码分析代理 (Code analysis agent) – 分析 C 代码结构和依赖关系
- 转换代理 (Conversion agent) – 将 C 代码转换为 Java/Spring 代码
- 安全评估代理 (Security assessment agent) – 识别遗留代码和迁移代码中的漏洞
- 验证代理 (Validation agent) – 验证转换的完整性和准确性
- 精炼代理 (Refine agent) – 根据验证代理的反馈重写代码
- 集成代理 (Integration agent) – 合并单独转换的文件
我们的代理式工作流是使用 Strands Agents 框架结合 Amazon Bedrock Converse API 实现的,用于强大的代理编排和 LLM 推理。该架构(如下所示)使用混合方法,结合了 Strands 的会话管理功能和自定义的 BedrockInference 处理,以实现 token 续写。
该解决方案使用的核心技术包括:
- Strands Agents 框架 (v1.1.0+) – 提供代理生命周期管理、会话处理和结构化代理通信
- Amazon Bedrock Converse API – 使用 Amazon Nova Premier 模型驱动 LLM 推理
- 自定义 BedrockInference 类 – 通过文本预填充和响应续写来处理 token 限制
- 基于 Asyncio 的编排 – 实现并发处理和非阻塞代理执行
该工作流包括以下步骤:
1. 代码分析:
- 代码分析代理 – 执行输入代码分析以了解转换要求。检查 C 代码库结构,识别依赖关系,并评估复杂性。
- 框架集成 – 使用 Strands 进行会话管理,同时使用
BedrockInference进行分析。 - 输出 – 带有依赖关系映射和转换建议的 JSON 结构化分析。
2. 文件分类和元数据创建:
- 实现 – 带有复杂性评估的
FileMetadata数据类。 - 分类 – 简单(0–300 行)、中等(300–700 行)、复杂(超过 700 行)。
- 文件类型 – 标准 C 文件、头文件和数据库 I/O (DBIO) 文件。
3. 单个文件转换:
- 转换代理 – 根据代码分析代理的信息对单个文件执行代码迁移。
- Token 处理 – 使用
stitch_output()方法处理超过 token 限制的大文件。
4. 安全评估阶段:
- 安全评估代理 – 对遗留 C 代码和转换后的 Java 代码执行全面的漏洞分析。
- 风险分类 – 按严重性(关键、高、中、低)对安全问题进行分类。
- 缓解建议 – 提供具体的代码修复和安全最佳实践。
- 输出 – 带有可操作修复步骤的详细安全报告。
5. 验证和反馈循环:
- 验证代理 – 分析转换的完整性和准确性。
- 精炼代理 – 根据验证结果应用迭代改进。
- 迭代控制 – 最多五个反馈迭代,在结果满意时提前终止。
- 会话持久性 – Strands 框架在迭代中维护对话上下文。
6. 集成和定稿:
- 集成代理 – 尝试合并单独转换的文件。
- 一致性解决 – 标准化变量命名并提供正确的依赖关系。
- 输出生成 – 创建统一的 Java/Spring 应用程序结构。
7. DBIO 转换(专业化)
- 目的 – 将 SQL DBIO C 源代码转换为 MyBatis XML 映射器文件。
- 框架 – 使用相同的 Strands 和
BedrockInference混合方法以保持一致性。
该解决方案的关键编排特性包括:
- 会话持久性 – 每次转换都在代理交互中维护会话状态。
- 错误恢复 – 全面的错误处理和优雅降级。
- 性能跟踪 – 内置的处理时间、迭代计数和成功率指标。
- Token 续写 – 通过响应拼接无缝处理大文件。
这种特定于框架的实现有助于可靠、可扩展的代码转换,同时保持处理各种 C 代码库结构和复杂性的灵活性。
先决条件
在实施此代码转换解决方案之前,请确保您已配置以下组件:
- AWS 环境:
- 拥有适当权限以访问具有 Amazon Nova Premier 模型访问权限的 Amazon Bedrock 的 AWS 帐户
- Amazon Elastic Compute Cloud (Amazon EC2) 实例(t3.medium 或更大)用于开发和测试,或在本地机器中进行开发环境设置
- 开发设置:
- 安装了 Python 3.10+,带有 Boto3 SDK 和 Strands Agents
- 配置了适当凭证和 AWS 区域的 AWS Command Line Interface (AWS CLI)
- 用于遗留代码库和转换后代码版本控制的 Git
- 能够处理 C 和 Java 代码库的文本编辑器或集成开发环境 (IDE)
- 源和目标代码库要求:
- 以结构化目录格式组织的 C 源代码
- Java 11+ 和 Maven/Gradle 构建工具
- Spring Framework 5.x 或 Spring Boot 2.x+ 依赖项
帖子中使用的源代码和提示可以在 GitHub 仓库中找到。
基于代理的转换过程
该解决方案使用基于 Strands 框架实现的复杂多代理系统,其中每个代理专门负责代码转换过程的特定方面。这种分布式方法在保持处理多样化代码结构和复杂性的灵活性的同时,提供了彻底的分析、准确的转换和全面的验证。
Strands 框架集成
每个代理都扩展了 BaseStrandsConversionAgent 类,该类提供了一种结合 Strands 会话管理和自定义 BedrockInference 功能的混合架构:
class BaseStrandsConversionAgent(ABC):
def (self, name: str, bedrock_inference, system_prompt: str):
self.name = name
self.bedrock = bedrock_inference # Custom BedrockInference for token handling
self.system_prompt = system_prompt
# Create strands agent for session management
self.strands_agent = Agent(name=name, system_prompt=system_prompt)
async def execute_async(self, context: ConversionContext) -> Dict[str, Any]:
# Implemented by each specialized agent
pass
代码分析代理
代码分析代理检查 C 代码库的结构,识别文件之间的依赖关系并确定最佳转换策略。此代理有助于确定转换文件的优先顺序并识别潜在的挑战。以下是代码分析代理的提示模板:
You are a Code Analysis Agent with expertise in legacy C codebases and modern Java/Spring architecture. <c_codebase>
{c_code}
</c_codebase> ## TASK
Your task is to analyze the provided C code to prepare for migration. Perform a comprehensive analysis and provide the following:
## INSTRUCTIONS 1. DEPENDENCY ANALYSIS:
- Identify all file dependencies (which files include or reference others)
- Map function calls between files
- Detect shared data structures and global variables 2. COMPLEXITY ASSESSMENT:
- Categorize each file as Simple (0-300 lines), Medium (300-700 lines), or Complex (700+ lines)
- Identify files with complex control flow, pointer manipulation, or memory management
- Flag any platform-specific or hardware-dependent code 3. CONVERSION PLANNING:
- Recommend a conversion sequence (which files to convert first)
- Suggest logical splitting points for large files
- Identify common patterns that can be standardized during conversion 4. RISK ASSESSMENT:
- Highlight potential conversion challenges (e.g., pointer arithmetic, bitwise operations)
- Identify business-critical sections requiring special attention
- Note any undocumented assumptions or behaviors 5. ARCHITECTURE RECOMMENDATIONS:
- Suggest appropriate Java/Spring components for each C module
- Recommend DTO structure and service organization
- Propose database access strategy using a persistence framework Format your response as a structured JSON document with these sections.
转换代理
转换代理负责将 C 代码实际转换为 Java/Spring 代码。此代理被分配为在 C 和 Java/Spring 框架方面拥有专业知识的高级软件开发人员角色。转换代理的提示模板如下:
You are a Senior Software Developer with 15+ years of experience in both C and Java Spring framework. <c_file>
{c_code}
</c_file> ## TASK
Your task is to convert legacy C code to modern Java Spring code with precision and completeness. ## CONVERSION GUIDELINES: 1. CODE STRUCTURE:
- Create appropriate Java classes (Service, DTO, Mapper interfaces)
- Preserve original function and variable names unless they conflict with Java conventions
- Use Spring annotations appropriately (@Service, @Repository, etc.)
- Implement proper package structure based on functionality 2. JAVA BEST PRACTICES:
- Use Lombok annotations (@Data, @Slf4j, @RequiredArgsConstructor) to reduce boilerplate
- Implement proper exception handling instead of error codes
- Replace pointer operations with appropriate Java constructs
- Convert C-style arrays to Java collections where appropriate 3. SPRING FRAMEWORK INTEGRATION:
- Use dependency injection instead of global variables
- Implement a persistence framework mappers for database operations
- Replace direct SQL calls with mapper interfaces
- Use Spring's transaction management 4. SPECIFIC TRANSFORMATIONS:
- Replace PFM_TRY/PFM_CATCH with Java try-catch blocks
- Convert mpfmdbio calls to a persistence framework mapper method calls
- Replace mpfm_dlcall with appropriate Service bean injections
- Convert NGMHEADER references to input.getHeaderVo() calls
- Replace PRINT_ and PFM_DBG macros with SLF4J logging
- Convert ngmf_ methods to CommonAPI.ngmf method calls 5. DATA HANDLING:
- Create separate DTO classes for input and output structures
- Use proper Java data types (String instead of char arrays, etc.)
- Implement proper null handling and validation
- Remove manual memory management code ## OUTPUT FORMAT:
- Include filename at the top of each Java file: #filename: [filename].java
- Place executable Java code inside <java></java> tags
- Organize multiple output files clearly with proper headers Generate complete, production-ready Java code that fully implements all functionality from the original C code.
安全评估代理
安全评估代理对原始 C 代码和转换后的 Java 代码执行全面的漏洞分析,识别潜在的安全风险并提供具体的缓解策略。此代理对于确保在迁移过程中不会将安全漏洞带入以及新代码遵循安全最佳实践至关重要。以下是安全评估代理的提示模板:
You are a Security Assessment Agent with expertise in identifying vulnerabilities in both C and Java codebases, specializing in secure code migration practices. ORIGINAL C CODE:
<c_code>
{c_code}
</c_code> CONVERTED JAVA CODE:
<java_code>
{java_code}
</java_code> ## TASK
Your task is to perform comprehensive security analysis on both the legacy C code and converted Java code, identifying vulnerabilities and providing specific mitigation recommendations. ## SECURITY ANALYSIS FRAMEWORK 1. **LEGACY C CODE VULNERABILITIES:**
- Buffer overflow risks (strcpy, strcat, sprintf usage)
- Memory management issues (dangling pointers, memory leaks)
- Integer overflow/underflow vulnerabilities
- Format string vulnerabilities
- Race conditions in multi-threaded code
- Improper input validation and sanitization
- SQL injection risks in database operations
- Insecure cryptographic implementations 2. **JAVA CODE SECURITY ASSESSMENT:**
- Input validation and sanitization gaps
- SQL injection vulnerabilities in persistence framework queries
- Improper exception handling that leaks sensitive information
- Authentication and authorization bypass risks
- Insecure deserialization vulnerabilities
- Cross-site scripting (XSS) prevention in web endpoints
- Logging of sensitive data
- Dependency vulnerabilities in Spring framework usage 3. **MIGRATION-SPECIFIC RISKS:**
- Security assumptions that don't translate between languages
- Privilege escalation through improper Spring Security configuration
- Data exposure through overly permissive REST endpoints
- Session management vulnerabilities
- Configuration security (hardcoded credentials, insecure defaults) 4. **COMPLIANCE AND BEST PRACTICES:**
- OWASP Top 10 compliance assessment
- Spring Security best practices implementation
- Secure coding standards adherence
- Data protection and privacy considerations ## OUTPUT FORMAT
Provide your analysis as a structured JSON with these fields:
- "critical_vulnerabilities": array of critical security issues requiring immediate attention
- "security_risk_issues": array of security concerns
- "secure_code_recommendations": specific code changes to implement security fixes
- "spring_security_configurations": recommended Spring Security configurations
- "compliance_gaps": areas where code doesn't meet security standards
- "migration_security_notes": security considerations specific to the C-to-Java migration
For each vulnerability, include:
- Description of the security risk
- Potential impact and attack vectors
- Specific line numbers or code sections affected
- Detailed remediation steps with code examples
- Priority level and recommended timeline for fixes Be thorough in identifying both obvious and subtle security issues that could be exploited in production environments.
验证代理
验证代理审查转换后的代码,以识别缺失或错误转换的组件。此代理提供详细的反馈,用于后续的转换迭代。验证代理的提示模板如下:
You are a Code Validation Agent specializing in verifying C to Java/Spring migrations. ORIGINAL C CODE:
<c_code>
{c_code}
</c_code> CONVERTED JAVA CODE:
<java_code>
{java_code}
</java_code> ## TASK
Your task is to thoroughly analyze the conversion quality and identify any issues or omissions.
Perform a comprehensive validation focusing on these aspects: ## INSTRUCTIONS
1. COMPLETENESS CHECK:
- Verify all functions from C code are implemented in Java
- Confirm all variables and data structures are properly converted
- Check that all logical branches and conditions are preserved
- Ensure all error handling paths are implemented 2. CORRECTNESS ASSESSMENT:
- Identify any logical errors in the conversion
- Verify proper transformation of C-specific constructs (pointers, structs, etc.)
- Check for correct implementation of memory management patterns
- Validate proper handling of string operations and byte manipulation 3. SPRING FRAMEWORK COMPLIANCE:
- Verify appropriate use of Spring annotations and patterns
- Check proper implementation of dependency injection
- Validate correct use of persistence framework mappers
- Ensure proper service structure and organization 4. CODE QUALITY EVALUATION:
- Assess Java code quality and adherence to best practices
- Check for proper exception handling
- Verify appropriate logging implementation
- Evaluate overall code organization and readability ## OUTPUT FORMAT
Provide your analysis as a structured JSON with these fields:
- "complete": boolean indicating if conversion is complete
- "missing_elements": array of specific functions, variables, or logic blocks that are missing
- "incorrect_transformations": array of elements that were incorrectly transformed
- "spring_framework_issues": array of Spring-specific implementation issues
- "quality_concerns": array of code quality issues
- "recommendations": specific, actionable recommendations for improvement Be thorough and precise in your analysis, as your feedback will directly inform the next iteration of the conversion process.
带精炼代理的反馈循环实现
反馈循环是实现转换后代码迭代改进的关键组成部分。此过程包括以下步骤:
- 由转换代理进行初始转换。
- 由安全评估代理进行安全评估。
- 由验证代理进行验证。
- 精炼代理整合反馈(整合验证和安全反馈)。
- 重复此过程,直到达到满意的结果。
精炼代理将安全漏洞修复与功能改进相结合,并将安全评估结果提供给开发团队,供其在投入生产部署前进行最终审查和批准。以下是用于代码精炼的提示模板:
You are a Senior Software Developer specializing in C to Java/Spring migration with expertise in secure coding practices.
ORIGINAL C CODE:
<c_code>
{c_code}
</c_code> YOUR PREVIOUS JAVA CONVERSION:
<previous_java>
{previous_java_code}
</previous_java> VALIDATION FEEDBACK:
<validation_feedback>
{validation_feedback}
</validation_feedback> SECURITY ASSESSMENT:
<security_feedback>
{security_feedback}
</security_feedback> ## TASK
You've previously converted C code to Java, but validation and security assessment have identified issues that need to be addressed. Your task is to improve the conversion by addressing all identified functional and security issues while maintaining complete functionality.
## INSTRUCTIONS
1. ADDRESSING MISSING ELEMENTS:
- Implement any functions, variables, or logic blocks identified as missing
- Ensure all control flow paths from the original code are preserved
- Add any missing error handling or edge cases
2. CORRECTING TRANSFORMATIONS:
- Fix any incorrectly transformed code constructs
- Correct any logical errors in the conversion
- Properly implement C-specific patterns in Java
3. IMPLEMENTING SECURITY FIXES:
- Address all critical and high-risk security vulnerabilities identified
- Implement secure coding practices (input validation, parameterized queries, etc.)
- Replace insecure patterns with secure Java/Spring alternatives
- Add proper exception handling that does not leak sensitive information
4. IMPROVING SPRING IMPLEMENTATION:
- Correct any issues with Spring annotations or patterns
- Ensure proper dependency injection and service structure
- Fix persistence framework mapper implementations if needed
- Implement Spring Security configurations as recommended
5. MAINTAINING CONSISTENCY:
- Ensure naming conventions are consistent throughout the code
- Maintain consistent patterns for similar operations
- Preserve the structure of the original code where appropriate
## OUTPUT FORMAT
Output the improved Java code inside <java></java> tags, with appropriate file headers. ... [内容被截断]
🚀 想要体验更好更全面的AI调用?
欢迎使用青云聚合API,约为官网价格的十分之一,支持300+全球最新模型,以及全球各种生图生视频模型,无需翻墙高速稳定,文档丰富,小白也可以简单操作。
评论区