B2B网络软件
标题:
AIWROK软件脚本JSON转换示例
[打印本页]
作者:
YYPOST群发软件
时间:
昨天 09:45
标题:
AIWROK软件脚本JSON转换示例
AIWROK软件脚本JSON转换示例
4.png
(1.32 MB, 下载次数: 0)
下载附件
昨天 09:45
上传
// AIWROK 实用工具集 - 完整示例 (ES5 兼容)
// 包含:文件操作、网络请求、数据处理、UI交互等实用功能
// ES5系统安卓 JavaScript引擎Rhino
//🍎交流QQ群711841924群一,苹果内测群,528816639
// ==================== 1. 文件系统管理工具 ====================
printl("=== 1. 文件系统管理工具 ===");
function FileManager() {
this.basePath = '/sdcard/AIWROK/';
}
FileManager.prototype.createDirectory = function(path) {
try {
var fullPath = this.basePath + path;
// 模拟创建目录
printl("创建目录: " + fullPath);
return true;
} catch (e) {
printl("创建目录失败: " + e);
return false;
}
};
FileManager.prototype.writeFile = function(filename, content) {
try {
var fullPath = this.basePath + filename;
// 模拟写入文件
printl("写入文件: " + fullPath);
printl("内容长度: " + content.length);
return true;
} catch (e) {
printl("写入文件失败: " + e);
return false;
}
};
FileManager.prototype.readFile = function(filename) {
try {
var fullPath = this.basePath + filename;
// 模拟读取文件
printl("读取文件: " + fullPath);
return "模拟文件内容: " + filename;
} catch (e) {
printl("读取文件失败: " + e);
return null;
}
};
FileManager.prototype.listDirectory = function(path) {
try {
var fullPath = this.basePath + path;
// 模拟列出目录内容
printl("列出目录: " + fullPath);
return ['file1.txt', 'file2.json', 'subdir'];
} catch (e) {
printl("列出目录失败: " + e);
return [];
}
};
var fileManager = new FileManager();
printl("FileManager实例已创建");
// 演示文件操作
fileManager.createDirectory('projects');
fileManager.createDirectory('backups');
fileManager.writeFile('config.json', '{"theme": "dark", "version": "1.0"}');
fileManager.readFile('config.json');
fileManager.listDirectory('projects');
sleep.second(2); // 2秒延时
// ==================== 2. 网络请求管理器 ====================
printl("");
printl("=== 2. 网络请求管理器 ===");
function HttpClient() {
this.baseUrl = 'https://api.example.com';
this.headers = {
'Content-Type': 'application/json',
'User-Agent': 'AIWROK-Client/1.0'
};
}
HttpClient.prototype.get = function(endpoint, params) {
params = params || {};
var url = this.baseUrl + endpoint;
// 添加查询参数
var queryString = '';
for (var key in params) {
if (params.hasOwnProperty(key)) {
queryString += (queryString ? '&' : '?') + key + '=' + encodeURIComponent(params[key]);
}
}
printl("GET请求: " + (url + queryString));
printl("Headers: " + JSON.stringify(this.headers));
// 模拟响应
return {
status: 200,
data: { message: '成功获取数据', endpoint: endpoint },
headers: { 'content-type': 'application/json' }
};
};
HttpClient.prototype.post = function(endpoint, data) {
var url = this.baseUrl + endpoint;
printl("POST请求: " + url);
printl("请求数据: " + JSON.stringify(data));
printl("Headers: " + JSON.stringify(this.headers));
// 模拟响应
return {
status: 201,
data: { message: '数据创建成功', id: Math.floor(Math.random() * 1000) },
headers: { 'content-type': 'application/json' }
};
};
HttpClient.prototype.put = function(endpoint, data) {
var url = this.baseUrl + endpoint;
printl("PUT请求: " + url);
printl("更新数据: " + JSON.stringify(data));
// 模拟响应
return {
status: 200,
data: { message: '数据更新成功' },
headers: { 'content-type': 'application/json' }
};
};
HttpClient.prototype.delete = function(endpoint) {
var url = this.baseUrl + endpoint;
printl("DELETE请求: " + url);
// 模拟响应
return {
status: 200,
data: { message: '数据删除成功' },
headers: { 'content-type': 'application/json' }
};
};
var httpClient = new HttpClient();
printl("HttpClient实例已创建");
// 演示网络请求
var getUserResponse = httpClient.get('/users/123', { fields: 'name,email' });
printl("GET响应状态: " + getUserResponse.status);
printl("GET响应数据: " + JSON.stringify(getUserResponse.data));
sleep.second(2); // 2秒延时
var createUserResponse = httpClient.post('/users', {
name: '张三',
email: 'zhangsan@example.com',
age: 25
});
printl("POST响应状态: " + createUserResponse.status);
printl("POST响应数据: " + JSON.stringify(createUserResponse.data));
sleep.second(2); // 2秒延时
// ==================== 3. 数据验证器 ====================
printl("");
printl("=== 3. 数据验证器 ===");
function Validator() {}
Validator.isEmail = function(email) {
var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
};
Validator.isPhone = function(phone) {
var re = /^1[3-9]\d{9}$/;
return re.test(phone);
};
Validator.isURL = function(url) {
var re = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
return re.test(url);
};
Validator.isEmpty = function(value) {
if (value === null || value === undefined) return true;
if (typeof value === 'string') return value.trim().length === 0;
if (Array.isArray(value)) return value.length === 0;
if (typeof value === 'object') return Object.keys(value).length === 0;
return false;
};
Validator.isNumber = function(value) {
return typeof value === 'number' && !isNaN(value);
};
Validator.isBoolean = function(value) {
return typeof value === 'boolean';
};
Validator.validateForm = function(formData, rules) {
var errors = {};
var isValid = true;
for (var field in rules) {
if (rules.hasOwnProperty(field)) {
var rule = rules[field];
var value = formData[field];
if (rule.required && Validator.isEmpty(value)) {
errors[field] = rule.message || field + '不能为空';
isValid = false;
continue;
}
if (!Validator.isEmpty(value)) {
if (rule.type === 'email' && !Validator.isEmail(value)) {
errors[field] = rule.message || field + '格式不正确';
isValid = false;
} else if (rule.type === 'phone' && !Validator.isPhone(value)) {
errors[field] = rule.message || field + '格式不正确';
isValid = false;
} else if (rule.type === 'url' && !Validator.isURL(value)) {
errors[field] = rule.message || field + '格式不正确';
isValid = false;
} else if (rule.minLength && value.length < rule.minLength) {
errors[field] = rule.message || field + '长度不能少于' + rule.minLength;
isValid = false;
} else if (rule.maxLength && value.length > rule.maxLength) {
errors[field] = rule.message || field + '长度不能超过' + rule.maxLength;
isValid = false;
}
}
}
}
return {
isValid: isValid,
errors: errors
};
};
printl("Validator工具类已定义");
// 演示数据验证
var testData = {
email: 'test@example.com',
phone: '13800138000',
url: 'https://www.example.com',
empty: '',
number: 42,
boolean: true
};
printl("邮箱验证: " + Validator.isEmail(testData.email));
printl("手机验证: " + Validator.isPhone(testData.phone));
printl("URL验证: " + Validator.isURL(testData.url));
printl("空值验证: " + Validator.isEmpty(testData.empty));
printl("数字验证: " + Validator.isNumber(testData.number));
printl("布尔验证: " + Validator.isBoolean(testData.boolean));
sleep.second(2); // 2秒延时
// 表单验证示例
var formRules = {
username: { required: true, minLength: 3, maxLength: 20, message: '用户名3-20个字符' },
email: { required: true, type: 'email', message: '邮箱格式不正确' },
phone: { required: false, type: 'phone', message: '手机号格式不正确' }
};
var formData = {
username: 'john_doe',
email: 'john@example.com',
phone: '13800138000'
};
var validationResult = Validator.validateForm(formData, formRules);
printl("表单验证结果: " + JSON.stringify(validationResult));
sleep.second(2); // 2秒延时
// ==================== 4. 缓存管理器 ====================
printl("");
printl("=== 4. 缓存管理器 ===");
function CacheManager() {
this.cache = {};
this.ttl = {}; // time to live
}
CacheManager.prototype.set = function(key, value, ttlSeconds) {
ttlSeconds = ttlSeconds || 3600; // 默认1小时
this.cache[key] = value;
this.ttl[key] = Date.now() + (ttlSeconds * 1000);
printl("设置缓存: " + key + " TTL: " + ttlSeconds + " 秒");
};
CacheManager.prototype.get = function(key) {
if (!this.cache.hasOwnProperty(key)) {
return null;
}
// 检查是否过期
if (Date.now() > this.ttl[key]) {
delete this.cache[key];
delete this.ttl[key];
printl("缓存已过期: " + key);
return null;
}
printl("获取缓存: " + key);
return this.cache[key];
};
CacheManager.prototype.remove = function(key) {
if (this.cache.hasOwnProperty(key)) {
delete this.cache[key];
delete this.ttl[key];
printl("删除缓存: " + key);
return true;
}
return false;
};
CacheManager.prototype.clear = function() {
this.cache = {};
this.ttl = {};
printl("清空所有缓存");
};
CacheManager.prototype.size = function() {
return Object.keys(this.cache).length;
};
CacheManager.prototype.has = function(key) {
return this.cache.hasOwnProperty(key) && Date.now() <= this.ttl[key];
};
var cacheManager = new CacheManager();
printl("CacheManager实例已创建");
// 演示缓存操作
cacheManager.set('user_profile', { name: '张三', age: 25 }, 300); // 5分钟TTL
cacheManager.set('app_config', { theme: 'dark', language: 'zh-CN' }, 3600); // 1小时TTL
printl("缓存大小: " + cacheManager.size());
printl("是否存在user_profile: " + cacheManager.has('user_profile'));
var userProfile = cacheManager.get('user_profile');
printl("获取用户资料: " + JSON.stringify(userProfile));
sleep.second(2); // 2秒延时
cacheManager.remove('user_profile');
printl("删除后缓存大小: " + cacheManager.size());
cacheManager.clear();
printl("清空后缓存大小: " + cacheManager.size());
sleep.second(2); // 2秒延时
// ==================== 5. 事件总线 ====================
printl("");
printl("=== 5. 事件总线 ===");
function EventBus() {
this.events = {};
}
EventBus.prototype.on = function(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
printl("注册事件监听器: " + event);
};
EventBus.prototype.off = function(event, callback) {
if (!this.events[event]) return;
if (callback) {
var index = this.events[event].indexOf(callback);
if (index > -1) {
this.events[event].splice(index, 1);
}
} else {
delete this.events[event];
}
printl("移除事件监听器: " + event);
};
EventBus.prototype.emit = function(event, data) {
if (!this.events[event]) return;
printl("触发事件: " + event + " 数据: " + JSON.stringify(data));
var callbacks = this.events[event].slice(); // 复制数组避免修改问题
for (var i = 0; i < callbacks.length; i++) {
try {
callbacks[i](data);
} catch (e) {
printl("事件回调执行错误: " + e);
}
}
};
EventBus.prototype.once = function(event, callback) {
var self = this;
var wrapper = function(data) {
callback(data);
self.off(event, wrapper);
};
this.on(event, wrapper);
printl("注册一次性事件监听器: " + event);
};
var eventBus = new EventBus();
printl("EventBus实例已创建");
// 演示事件系统
eventBus.on('user_login', function(data) {
printl("用户登录事件处理: " + data.username);
});
eventBus.on('data_loaded', function(data) {
printl("数据加载完成: " + data.count + " 条记录");
});
eventBus.once('app_init', function(data) {
printl("应用初始化完成: " + data.version);
});
// 触发事件
eventBus.emit('user_login', { username: 'john_doe', timestamp: new Date() });
eventBus.emit('data_loaded', { count: 100, source: 'database' });
eventBus.emit('app_init', { version: '1.0.0' });
sleep.second(2); // 2秒延时
// ==================== 6. 任务队列 ====================
printl("");
printl("=== 6. 任务队列 ===");
function TaskQueue(concurrency) {
concurrency = concurrency || 1;
this.queue = [];
this.running = 0;
this.concurrency = concurrency;
this.results = [];
}
TaskQueue.prototype.add = function(task) {
this.queue.push(task);
this.process();
};
TaskQueue.prototype.process = function() {
var self = this;
while (this.running < this.concurrency && this.queue.length > 0) {
var task = this.queue.shift();
this.running++;
// 异步执行任务
(function(currentTask, taskId) {
setTimeout(function() {
try {
var result = currentTask();
self.results.push({ id: taskId, result: result, success: true });
printl("任务完成: " + taskId);
} catch (e) {
self.results.push({ id: taskId, error: e.toString(), success: false });
printl("任务失败: " + taskId + " " + e.toString());
} finally {
self.running--;
self.process(); // 处理下一个任务
}
}, 100); // 模拟异步延迟
})(task, this.results.length + 1);
}
};
TaskQueue.prototype.getResults = function() {
return this.results;
};
TaskQueue.prototype.clear = function() {
this.queue = [];
this.results = [];
this.running = 0;
};
var taskQueue = new TaskQueue(2); // 并发度为2
printl("TaskQueue实例已创建,并发度: " + taskQueue.concurrency);
// 添加任务
taskQueue.add(function() {
printl("执行任务1: 数据清洗");
return { processed: 100, cleaned: 95 };
});
taskQueue.add(function() {
printl("执行任务2: 图片压缩");
return { originalSize: '2MB', compressedSize: '500KB' };
});
taskQueue.add(function() {
printl("执行任务3: 视频转码");
return { duration: '00:05:30', format: 'mp4' };
});
sleep.second(3); // 等待任务完成
printl("任务执行结果: " + JSON.stringify(taskQueue.getResults()));
sleep.second(2); // 2秒延时
// ==================== 7. 配置管理器 ====================
printl("");
printl("=== 7. 配置管理器 ===");
function ConfigManager() {
this.configs = {};
this.defaults = {};
}
ConfigManager.prototype.setDefault = function(key, value) {
this.defaults[key] = value;
if (!this.configs.hasOwnProperty(key)) {
this.configs[key] = value;
}
};
ConfigManager.prototype.set = function(key, value) {
this.configs[key] = value;
printl("设置配置: " + key + " = " + JSON.stringify(value));
};
ConfigManager.prototype.get = function(key) {
if (this.configs.hasOwnProperty(key)) {
return this.configs[key];
}
return this.defaults.hasOwnProperty(key) ? this.defaults[key] : null;
};
ConfigManager.prototype.getAll = function() {
var allConfigs = {};
// 合并默认配置和自定义配置
for (var key in this.defaults) {
allConfigs[key] = this.defaults[key];
}
for (var key in this.configs) {
allConfigs[key] = this.configs[key];
}
return allConfigs;
};
ConfigManager.prototype.reset = function(key) {
if (key) {
if (this.defaults.hasOwnProperty(key)) {
this.configs[key] = this.defaults[key];
} else {
delete this.configs[key];
}
} else {
this.configs = {};
}
printl("重置配置: " + (key || "全部"));
};
var configManager = new ConfigManager();
printl("ConfigManager实例已创建");
// 设置默认配置
configManager.setDefault('theme', 'light');
configManager.setDefault('language', 'en');
configManager.setDefault('debug', false);
// 设置自定义配置
configManager.set('theme', 'dark');
configManager.set('fontSize', 14);
configManager.set('autoSave', true);
printl("当前主题: " + configManager.get('theme'));
printl("语言设置: " + configManager.get('language'));
printl("字体大小: " + configManager.get('fontSize'));
printl("自动保存: " + configManager.get('autoSave'));
printl("调试模式: " + configManager.get('debug'));
printl("所有配置: " + JSON.stringify(configManager.getAll()));
sleep.second(2); // 2秒延时
configManager.reset('theme');
printl("重置主题后: " + configManager.get('theme'));
configManager.reset();
printl("重置所有配置后: " + JSON.stringify(configManager.getAll()));
sleep.second(2); // 2秒延时
// ==================== 8. 日志管理器 ====================
printl("");
printl("=== 8. 日志管理器 ===");
function LogManager() {
this.logs = [];
this.maxLogs = 1000;
this.levels = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3
};
this.currentLevel = this.levels.INFO;
}
LogManager.prototype.log = function(level, message, data) {
if (level < this.currentLevel) return;
var logEntry = {
timestamp: new Date(),
level: this.getLevelName(level),
message: message,
data: data || null
};
this.logs.push(logEntry);
// 限制日志数量
if (this.logs.length > this.maxLogs) {
this.logs.shift();
}
// 输出到控制台
var prefix = '[' + logEntry.timestamp.toISOString() + '] [' + logEntry.level + '] ';
printl(prefix + message);
if (data) {
printl(' 数据: ' + JSON.stringify(data));
}
};
LogManager.prototype.debug = function(message, data) {
this.log(this.levels.DEBUG, message, data);
};
LogManager.prototype.info = function(message, data) {
this.log(this.levels.INFO, message, data);
};
LogManager.prototype.warn = function(message, data) {
this.log(this.levels.WARN, message, data);
};
LogManager.prototype.error = function(message, data) {
this.log(this.levels.ERROR, message, data);
};
LogManager.prototype.getLevelName = function(level) {
for (var name in this.levels) {
if (this.levels[name] === level) {
return name;
}
}
return 'UNKNOWN';
};
LogManager.prototype.getLogs = function(level, limit) {
limit = limit || 50;
var filteredLogs = this.logs;
if (level !== undefined) {
filteredLogs = this.logs.filter(function(log) {
return log.level === this.getLevelName(level);
}.bind(this));
}
return filteredLogs.slice(-limit);
};
LogManager.prototype.clear = function() {
this.logs = [];
printl("日志已清空");
};
var logManager = new LogManager();
printl("LogManager实例已创建");
// 演示日志记录
logManager.debug("调试信息", { detail: "这是调试级别的日志" });
logManager.info("应用启动", { version: "1.0.0", environment: "production" });
logManager.warn("内存使用较高", { used: "80%", total: "1GB" });
logManager.error("数据库连接失败", { host: "localhost", port: 3306 });
sleep.second(2); // 2秒延时
printl("最近5条日志:");
var recentLogs = logManager.getLogs(undefined, 5);
for (var i = 0; i < recentLogs.length; i++) {
printl(" " + recentLogs[i].level + " - " + recentLogs[i].message);
}
logManager.clear();
sleep.second(2); // 2秒延时
// ==================== 9. 字符串工具类 ====================
printl("");
printl("=== 9. 字符串工具类 ===");
function StringUtils() {}
StringUtils.capitalize = function(str) {
if (!str) return str;
return str.charAt(0).toUpperCase() + str.slice(1);
};
StringUtils.camelCase = function(str) {
return str.replace(/[-_\s]+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
};
StringUtils.kebabCase = function(str) {
return str.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[\s_]+/g, '-')
.toLowerCase();
};
StringUtils.truncate = function(str, length, suffix) {
suffix = suffix || '...';
if (str.length <= length) return str;
return str.substring(0, length - suffix.length) + suffix;
};
StringUtils.repeat = function(str, times) {
var result = '';
for (var i = 0; i < times; i++) {
result += str;
}
return result;
};
StringUtils.padLeft = function(str, length, char) {
char = char || ' ';
while (str.length < length) {
str = char + str;
}
return str;
};
StringUtils.padRight = function(str, length, char) {
char = char || ' ';
while (str.length < length) {
str += char;
}
return str;
};
StringUtils.stripHtml = function(html) {
return html.replace(/<[^>]*>/g, '');
};
StringUtils.escapeHtml = function(text) {
return text.replace(/[&<>"']/g, function(match) {
switch (match) {
case '&': return '&';
case '<': return '<';
case '>': return '>';
case '"': return '"';
case "'": return ''';
}
});
};
printl("StringUtils工具类已定义");
// 演示字符串操作
printl("首字母大写: " + StringUtils.capitalize('hello world'));
printl("驼峰命名: " + StringUtils.camelCase('hello-world-test'));
printl("短横线命名: " + StringUtils.kebabCase('helloWorldTest'));
printl("截断字符串: " + StringUtils.truncate('这是一个很长的字符串', 10));
printl("重复字符串: " + StringUtils.repeat('*', 5));
printl("左填充: " + StringUtils.padLeft('42', 5, '0'));
printl("右填充: " + StringUtils.padRight('42', 5, '0'));
printl("去除HTML: " + StringUtils.stripHtml('<p>这是一段<b>HTML</b>文本</p>'));
printl("转义HTML: " + StringUtils.escapeHtml('<script>alert("XSS")</script>'));
sleep.second(2); // 2秒延时
// ==================== 10. 数组工具类 ====================
printl("");
printl("=== 10. 数组工具类 ===");
function ArrayUtils() {}
ArrayUtils.unique = function(arr) {
var seen = {};
var result = [];
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
var key = typeof item + ':' + item;
if (!seen.hasOwnProperty(key)) {
seen[key] = true;
result.push(item);
}
}
return result;
};
ArrayUtils.flatten = function(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(ArrayUtils.flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
};
ArrayUtils.chunk = function(arr, size) {
var result = [];
for (var i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
};
ArrayUtils.shuffle = function(arr) {
var shuffled = arr.slice();
for (var i = shuffled.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = shuffled[i];
shuffled[i] = shuffled[j];
shuffled[j] = temp;
}
return shuffled;
};
ArrayUtils.groupBy = function(arr, key) {
var result = {};
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
var groupKey = item[key];
if (!result.hasOwnProperty(groupKey)) {
result[groupKey] = [];
}
result[groupKey].push(item);
}
return result;
};
ArrayUtils.sum = function(arr, property) {
var total = 0;
for (var i = 0; i < arr.length; i++) {
if (property) {
total += arr[i][property] || 0;
} else {
total += arr[i];
}
}
return total;
};
ArrayUtils.average = function(arr, property) {
if (arr.length === 0) return 0;
var sum = ArrayUtils.sum(arr, property);
return sum / arr.length;
};
printl("ArrayUtils工具类已定义");
// 演示数组操作
var numbers = [1, 2, 3, 2, 4, 1, 5, 3];
printl("去重: " + JSON.stringify(ArrayUtils.unique(numbers)));
var nested = [1, [2, 3], [4, [5, 6]], 7];
printl("扁平化: " + JSON.stringify(ArrayUtils.flatten(nested)));
var largeArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
printl("分块: " + JSON.stringify(ArrayUtils.chunk(largeArray, 3)));
var cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
printl("洗牌前: " + JSON.stringify(cards));
var shuffledCards = ArrayUtils.shuffle(cards);
printl("洗牌后: " + JSON.stringify(shuffledCards));
var users = [
{ name: '张三', age: 25, department: '技术部' },
{ name: '李四', age: 30, department: '市场部' },
{ name: '王五', age: 28, department: '技术部' },
{ name: '赵六', age: 35, department: '财务部' }
];
printl("按部门分组: " + JSON.stringify(ArrayUtils.groupBy(users, 'department')));
printl("年龄总和: " + ArrayUtils.sum(users, 'age'));
printl("平均年龄: " + ArrayUtils.average(users, 'age'));
sleep.second(2); // 2秒延时
// ==================== 总结 ====================
printl("");
printl("=== 实用工具集演示完成 ===");
printl("💡 这些工具在实际项目开发中非常实用!");
printl("包含:文件管理、网络请求、数据验证、缓存、事件系统、任务队列、配置管理、日志、字符串和数组工具");
复制代码
欢迎光临 B2B网络软件 (http://bbs.niubt.cn/)
Powered by Discuz! X3.2