Java Code Examples for cn.hutool.core.util.StrUtil#format()

The following examples show how to use cn.hutool.core.util.StrUtil#format() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Wrapper.java    From yue-library with Apache License 2.0 6 votes vote down vote up
/**
 * 包装字段名<br>
 * 有时字段与SQL的某些关键字冲突,导致SQL出错,因此需要将字段名用单引号或者反引号包装起来,避免冲突
 * @param field 字段名
 * @return 包装后的字段名
 */
public String wrap(String field){
	if(preWrapQuote == null || sufWrapQuote == null || StrUtil.isBlank(field)) {
		return field;
	}
	
	//如果已经包含包装的引号,返回原字符
	if(StrUtil.isSurround(field, preWrapQuote, sufWrapQuote)){
		return field;
	}
	
	//如果字段中包含通配符或者括号(字段通配符或者函数),不做包装
	if(StrUtil.containsAnyIgnoreCase(field, "*", "(", " ", " as ")) {
		return field;
	}
	
	//对于Oracle这类数据库,表名中包含用户名需要单独拆分包装
	if(field.contains(StrUtil.DOT)){
		final Collection<String> target = CollectionUtil.filter(StrUtil.split(field, StrUtil.C_DOT), (Editor<String>) t -> StrUtil.format("{}{}{}", preWrapQuote, t, sufWrapQuote));
		return CollectionUtil.join(target, StrUtil.DOT);
	}
	
	return StrUtil.format("{}{}{}", preWrapQuote, field, sufWrapQuote);
}
 
Example 2
Source File: BaseProxyHandler.java    From Jpom with MIT License 6 votes vote down vote up
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    Map<String, Object> attributes = session.getAttributes();
    NodeModel nodeModel = (NodeModel) attributes.get("nodeInfo");
    UserModel userInfo = (UserModel) attributes.get("userInfo");
    String dataValue = (String) attributes.get(dataParName);
    String userName = UserModel.getOptUserName(userInfo);
    userName = URLUtil.encode(userName);
    if (nodeModel != null) {
        String url = NodeForward.getSocketUrl(nodeModel, nodeUrl);
        url = StrUtil.format(url, dataValue, userName);
        // 连接节点
        ProxySession proxySession = new ProxySession(url, session);
        session.getAttributes().put("proxySession", proxySession);
    }
    session.sendMessage(new TextMessage(StrUtil.format("欢迎加入:{} 会话id:{} ", userInfo.getName(), session.getId())));
}
 
Example 3
Source File: LinuxSystemCommander.java    From Jpom with MIT License 6 votes vote down vote up
@Override
public String stopService(String serviceName) {
    if (StrUtil.startWith(serviceName, StrUtil.SLASH)) {
        String ps = getPs(serviceName);
        List<String> list = StrUtil.splitTrim(ps, StrUtil.LF);
        if (list == null || list.isEmpty()) {
            return "stop";
        }
        String s = list.get(0);
        list = StrUtil.splitTrim(s, StrUtil.SPACE);
        if (list == null || list.size() < 2) {
            return "stop";
        }
        File file = new File(SystemUtil.getUserInfo().getHomeDir());
        int pid = Convert.toInt(list.get(1), 0);
        if (pid <= 0) {
            return "error stop";
        }
        return kill(file, pid);
    }
    String format = StrUtil.format("service {} stop", serviceName);
    return CommandUtil.execSystemCommand(format);
}
 
Example 4
Source File: SnowFlakeId.java    From magic-starter with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * (根据业务名称)生成下一个主键
 *
 * @param businessName 业务名称
 * @return 主键
 * @throws IdException 主键生成异常
 */
@Override
public synchronized long nextId(BusinessName businessName) throws IdException {
	long timestamp = genTime();
	if (timestamp < lastTimestamp) {
		// 如果服务器时间有问题(时钟后退) 报错。
		throw new IllegalStateException(StrUtil.format("Clock moved backwards. Refusing to generate id for {}ms", lastTimestamp - timestamp));
	}
	if (lastTimestamp == timestamp) {
		// 4095
		long sequenceMask = ~(-1L << sequenceBits);
		sequence = (sequence + 1) & sequenceMask;
		if (sequence == 0) {
			timestamp = tilNextMillis(lastTimestamp);
		}
	} else {
		sequence = 0L;
	}

	lastTimestamp = timestamp;

	return ((timestamp - EPOCH) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) | (workerId << workerIdShift) | sequence;
}
 
Example 5
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example 6
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example 7
Source File: AbstractProjectCommander.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 尝试jps 中查看进程id
 *
 * @param tag 进程标识
 * @return 运行标识
 */
private String getJpsStatus(String tag) {
    String execSystemCommand = CommandUtil.execSystemCommand("jps -mv");
    List<String> list = StrSpliter.splitTrim(execSystemCommand, StrUtil.LF, true);
    for (String item : list) {
        if (JvmUtil.checkCommandLineIsJpom(item, tag)) {
            String[] split = StrUtil.split(item, StrUtil.SPACE);
            return StrUtil.format("{}:{}", AbstractProjectCommander.RUNNING_TAG, split[0]);
        }
    }
    return AbstractProjectCommander.STOP_TAG;
}
 
Example 8
Source File: BaseDao.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 获取表名
 *
 * @param t 对象
 * @return 表名
 */
private String getTableName(T t) {
	Table tableAnnotation = t.getClass().getAnnotation(Table.class);
	if (ObjectUtil.isNotNull(tableAnnotation)) {
		return StrUtil.format("`{}`", tableAnnotation.name());
	} else {
		return StrUtil.format("`{}`", t.getClass().getName().toLowerCase());
	}
}
 
Example 9
Source File: SpringBootDemoHelloworldApplication.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * Hello,World
 *
 * @param who 参数,非必须
 * @return Hello, ${who}
 */
@GetMapping("/hello")
public String sayHello(@RequestParam(required = false, name = "who") String who) {
	if (StrUtil.isBlank(who)) {
		who = "World";
	}
	return StrUtil.format("Hello, {}!", who);
}
 
Example 10
Source File: BaseDao.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 通用根据主键删除
 *
 * @param pk 主键
 * @return 影响行数
 */
protected Integer deleteById(P pk) {
	String tableName = getTableName();
	String sql = StrUtil.format("DELETE FROM {table} where id = ?", Dict.create().set("table", tableName));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(pk));
	return jdbcTemplate.update(sql, pk);
}
 
Example 11
Source File: AbstractProjectCommander.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 查看状态
 *
 * @param tag 运行标识
 * @return 查询结果
 * @throws Exception 异常
 */
public String status(String tag) throws Exception {
    VirtualMachine virtualMachine = JvmUtil.getVirtualMachine(tag);
    if (virtualMachine == null) {
        return getJpsStatus(tag);
    }
    try {
        return StrUtil.format("{}:{}", AbstractProjectCommander.RUNNING_TAG, virtualMachine.id());
    } finally {
        virtualMachine.detach();
    }
}
 
Example 12
Source File: UploadFileHeader.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
 * 获得头信息字符串字符串中指定的值
 * 
 * @param dataHeader 头信息
 * @param fieldName 字段名
 * @return 字段值
 */
private String getDataFieldValue(String dataHeader, String fieldName) {
	String value = null;
	String token = StrUtil.format("{}=\"", fieldName);
	int pos = dataHeader.indexOf(token);
	if (pos > 0) {
		int start = pos + token.length();
		int end = dataHeader.indexOf('"', start);
		if ((start > 0) && (end > 0)) {
			value = dataHeader.substring(start, end);
		}
	}
	return value;
}
 
Example 13
Source File: JpomManifest.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 获取当前的管理名文件
 *
 * @return file
 */
public static File getScriptFile() {
    File runPath = getRunPath().getParentFile().getParentFile();
    String type = JpomApplication.getAppType().name();
    File scriptFile = FileUtil.file(runPath, StrUtil.format("{}.{}", type, CommandUtil.SUFFIX));
    if (!scriptFile.exists() || scriptFile.isDirectory()) {
        throw new JpomRuntimeException("当前服务中没有命令脚本:" + StrUtil.format("{}.{}", type, CommandUtil.SUFFIX));
    }
    return scriptFile;
}
 
Example 14
Source File: DbConfig.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 获取数据库的jdbc 连接
 *
 * @return jdbc
 */
public String getDbUrl() {
    File file = FileUtil.file(ExtConfigBean.getInstance().getAbsolutePath(), DB, JpomApplication.getAppType().name());
    String path = FileUtil.getAbsolutePath(file);
    return StrUtil.format("jdbc:h2:{}", path);
}
 
Example 15
Source File: WindowsSystemCommander.java    From Jpom with MIT License 4 votes vote down vote up
@Override
public String stopService(String serviceName) {
    String format = StrUtil.format("net stop {}", serviceName);
    return CommandUtil.execSystemCommand(format);
}
 
Example 16
Source File: UploadFile.java    From yue-library with Apache License 2.0 4 votes vote down vote up
/**
 * 断言是否文件流可用
 * @throws IOException
 */
private void assertValid() throws IOException {
	if(! isUploaded()) {
		throw new IOException(StrUtil.format("File [{}] upload fail", getFileName()));
	}
}
 
Example 17
Source File: LinuxSystemCommander.java    From Jpom with MIT License 4 votes vote down vote up
private String getPs(String serviceName) {
    String ps = StrUtil.format("ps -ef | grep -v 'grep' | egrep {}", serviceName);
    return CommandUtil.execSystemCommand(ps);
}
 
Example 18
Source File: SshInstallAgentController.java    From Jpom with MIT License 4 votes vote down vote up
@RequestMapping(value = "installAgentSubmit.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Feature(method = MethodFeature.INSTALL)
@OptLog(UserOperateLogV1.OptType.SshInstallAgent)
public String installAgentSubmit(@ValidatorItem(value = ValidatorRule.NOT_BLANK) String id,
                                 @ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "节点数据") String nodeData,
                                 @ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "安装路径") String path) throws Exception {
    // 判断输入的节点信息
    Object object = getNodeModel(nodeData);
    if (object instanceof JsonMessage) {
        return object.toString();
    }
    NodeModel nodeModel = (NodeModel) object;
    //
    SshModel sshModel = sshService.getItem(id);
    Objects.requireNonNull(sshModel, "没有找到对应ssh");
    //
    String tempFilePath = ServerConfigBean.getInstance().getUserTempPath().getAbsolutePath();
    MultipartFileBuilder cert = createMultipart().addFieldName("file").setSavePath(tempFilePath);
    String filePath = cert.save();
    //
    File outFle = FileUtil.file(tempFilePath, Type.Agent.name() + "_" + IdUtil.fastSimpleUUID());
    try {
        try (ZipFile zipFile = new ZipFile(filePath)) {
            // 判断文件是否正确
            ZipEntry sh = zipFile.getEntry(Type.Agent.name() + ".sh");
            ZipEntry lib = zipFile.getEntry("lib" + StrUtil.SLASH);
            if (sh == null || null == lib || !lib.isDirectory()) {
                return JsonMessage.getString(405, "不能jpom 插件包");
            }
            ZipUtil.unzip(zipFile, outFle);
        }
        // 获取上传的tag
        File shFile = FileUtil.file(outFle, Type.Agent.name() + ".sh");
        List<String> lines = FileUtil.readLines(shFile, CharsetUtil.CHARSET_UTF_8);
        String tag = null;
        for (String line : lines) {
            line = line.trim();
            if (StrUtil.startWith(line, "Tag=\"") && StrUtil.endWith(line, "\"")) {
                tag = line.substring(5, line.length() - 1);
                break;
            }
        }
        if (StrUtil.isEmpty(tag)) {
            return JsonMessage.getString(405, "管理命令中不存在tag");
        }
        //  读取授权信息
        File configFile = FileUtil.file(outFle, "extConfig.yml");
        if (configFile.exists()) {
            List<Map<String, Object>> load = YmlUtil.load(configFile);
            Map<String, Object> map = load.get(0);
            Object user = map.get(ConfigBean.AUTHORIZE_USER_KEY);
            nodeModel.setLoginName(Convert.toStr(user, ""));
            //
            Object pwd = map.get(ConfigBean.AUTHORIZE_PWD_KEY);
            nodeModel.setLoginPwd(Convert.toStr(pwd, ""));
        }
        // 查询远程是否运行
        if (sshService.checkSshRun(sshModel, tag)) {
            return JsonMessage.getString(300, "对应服务器中已经存在Jpom 插件端,不需要再次安装啦");
        }
        // 上传文件到服务器
        sshService.uploadDir(sshModel, path, outFle);
        //
        String shPtah = FileUtil.normalize(path + "/" + Type.Agent.name() + ".sh");
        String command = StrUtil.format("sh {} start upgrade", shPtah);
        String result = sshService.exec(sshModel, command);
        // 休眠10秒
        Thread.sleep(10 * 1000);
        if (StrUtil.isEmpty(nodeModel.getLoginName()) || StrUtil.isEmpty(nodeModel.getLoginPwd())) {
            String error = this.getAuthorize(sshModel, nodeModel, path);
            if (error != null) {
                return error;
            }
        }
        nodeModel.setOpenStatus(true);
        // 绑定关系
        nodeModel.setSshId(sshModel.getId());
        nodeService.addItem(nodeModel);
        //
        return JsonMessage.getString(200, "操作成功:" + result);
    } finally {
        // 清理资源
        FileUtil.del(filePath);
        FileUtil.del(outFle);
    }
}
 
Example 19
Source File: NodeModel.java    From Jpom with MIT License 4 votes vote down vote up
public String getRealUrl(NodeUrl nodeUrl) {
    return StrUtil.format("{}://{}{}", getProtocol(), getUrl(), nodeUrl.getUrl());
}
 
Example 20
Source File: PropertiesUtils.java    From WeBASE-Codegen-Monkey with Apache License 2.0 3 votes vote down vote up
/**
 * get the very specific value of settings without a default value.
 * 
 * return the specific config value, eg. return event property prefer to contract value.
 * 
 * @param contractName
 * @param eventName
 * @param feature
 * @return
 */
public static String getPropertyWithoutDefault(String type, String contractName, String eventName, String feature) {
    String contractTemplate = "{}.{}.{}";
    String eventTemplate = "{}.{}.{}.{}";
    String eventConfig = StrUtil.format(eventTemplate, type, contractName, eventName, feature);
    String contractConfig = StrUtil.format(contractTemplate, type, contractName, feature);
    return PropertiesUtils.getProperty(eventConfig, contractConfig);
}