Java Code Examples for com.jstarcraft.core.utility.StringUtility#format()

The following examples show how to use com.jstarcraft.core.utility.StringUtility#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: MovieService.java    From jstarcraft-example with Apache License 2.0 6 votes vote down vote up
/**
 * 个性化搜索
 * 
 * @param userIndex
 * @param searchKey
 * @return
 * @throws Exception
 */
@LockableMethod(strategy = HashLockableStrategy.class)
public Object2FloatMap<MovieItem> getSearchItems(@LockableParameter int userIndex, String searchKey) throws Exception {
    // 标识-得分映射
    Object2FloatMap<MovieItem> item2ScoreMap = new Object2FloatOpenHashMap<>();

    long current = System.currentTimeMillis();
    Query query = queryParser.parse(searchKey, MovieItem.TITLE);
    KeyValue<List<Document>, FloatList> search = engine.retrieveDocuments(query, null, 0, 1000);
    List<Document> documents = search.getKey();
    FloatList scores = search.getValue();
    for (int index = 0, size = documents.size(); index < size; index++) {
        Document document = documents.get(index);
        MovieItem item = items.get(document.getField(MovieItem.INDEX).numericValue().intValue());
        float score = scores.getFloat(index);
        item2ScoreMap.put(item, score);
    }
    String message = StringUtility.format("搜索数量:{},搜索耗时:{}", documents.size(), System.currentTimeMillis() - current);
    logger.info(message);

    return item2ScoreMap;
}
 
Example 2
Source File: CommandWorker.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    InputDefinition inputDefinition = definition.getInputDefinition();
    OutputDefinition outputDefinition = definition.getOutputDefinition();
    Method method = definition.getMethod();
    Object[] requests = inputDefinition.getInputValues(dispatcher.getCodecs(), message, session);
    Object response = null;
    try {
        response = method.invoke(object, requests);
    } catch (Exception exception) {
        String string = StringUtility.format("工作者执行方法[{}]时异常", method);
        LOGGER.error(string, exception);
    }
    MessageBody body = outputDefinition.getMessageBody(dispatcher.getCodecs(), response);
    MessageHead head = message.getHead();
    dispatcher.sendResponse(definition, session, head.getSequence(), body);
}
 
Example 3
Source File: MethodAccessor.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(Object object) {
    Object value = null;
    try {
        value = method.invoke(object);
    } catch (Exception exception) {
        String message = StringUtility.format("属性[{}]访问异常", method);
        logger.error(message);
        throw new StorageException(message, exception);
    }
    return value;
}
 
Example 4
Source File: JsonType.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private static String getColumnName(ResultSet resultSet, String fieldName) throws SQLException {
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    int count = resultSetMetaData.getColumnCount();
    for (int index = 1; index <= count; index++) {
        String columnLabel = resultSetMetaData.getColumnLabel(index);
        String columnName = resultSetMetaData.getColumnName(index);
        if (columnLabel.equalsIgnoreCase(fieldName)) {
            return columnName;
        }
    }
    String message = StringUtility.format("字段{}对应的数据列不存在", fieldName);
    throw new StorageAccessException(message);
}
 
Example 5
Source File: SecurityUtility.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * 获取AES对称秘钥
 * 
 * @return
 */
public static byte[] getAes() {
    try {
        KeyGenerator aes = KeyGenerator.getInstance(AES);
        SecureRandom random = new SecureRandom();
        aes.init(random);
        SecretKey key = aes.generateKey();
        return key.getEncoded();
    } catch (Exception exception) {
        String message = StringUtility.format("获取AES密匙异常:[{}]");
        throw new RuntimeException(message, exception);
    }
}
 
Example 6
Source File: SecurityUtility.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * Blowfish加密
 * 
 * @param data
 * @param key
 * @return
 */
public static byte[] encryptBlowfish(final byte[] data, final byte[] key) {
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, Blowfish);
        Cipher cipher = Cipher.getInstance(Blowfish);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    } catch (Exception exception) {
        String message = StringUtility.format("Blowfish加密数据异常:[{}]", Arrays.toString(data));
        throw new RuntimeException(message, exception);
    }
}
 
Example 7
Source File: ResourceStorage.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * 装载指定类型的管理器
 * 
 * @param clazz
 */
public void loadManager(Class<?> clazz) {
    ResourceManager<?, ?> manager = this.managers.get(clazz);
    try {
        manager.load();
    } catch (Exception exception) {
        String message = StringUtility.format("资源[{}]装载异常", clazz);
        logger.error(message);
        throw new StorageException(message, exception);
    }
}
 
Example 8
Source File: SecurityUtility.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * SHA224摘要
 * 
 * @param data
 * @return
 */
public static byte[] signatureSha224(byte[] data) {
    try {
        MessageDigest algorithm = MessageDigest.getInstance(SHA224);
        return algorithm.digest(data);
    } catch (Exception exception) {
        String message = StringUtility.format("[{}]:SHA224信息摘要异常", data);
        throw new RuntimeException(message, exception);
    }
}
 
Example 9
Source File: SecurityUtility.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * Blowfish解密
 * 
 * @param data
 * @param key
 * @return
 */
public static byte[] decryptBlowfish(final byte[] data, final byte[] key) {
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, Blowfish);
        Cipher cipher = Cipher.getInstance(Blowfish);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    } catch (Exception exception) {
        String message = StringUtility.format("Blowfish解密数据异常:[{}]", Arrays.toString(data));
        throw new RuntimeException(message, exception);
    }
}
 
Example 10
Source File: SecurityUtility.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * SHA384摘要
 * 
 * @param data
 * @return
 */
public static byte[] signatureSha384(byte[] data) {
    try {
        MessageDigest algorithm = MessageDigest.getInstance(SHA384);
        return algorithm.digest(data);
    } catch (Exception exception) {
        String message = StringUtility.format("[{}]:SHA384信息摘要异常", data);
        throw new RuntimeException(message, exception);
    }
}
 
Example 11
Source File: ScriptContext.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * 在上下文中使用指定类
 * 
 * @param name
 * @param clazz
 * @return
 */
public ScriptContext useClass(String name, Class<?> clazz) {
    if (contextClasses.containsKey(name) || contextMethods.containsKey(name)) {
        throw new ScriptContextException(StringUtility.format("脚本上下文名称冲突[{}]", name));
    } else {
        contextClasses.put(name, clazz);
        return this;
    }
}
 
Example 12
Source File: SchedulePersistenceManager.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private void persist(PersistenceElement element) {
	if (element == null) {
		return;
	}
	if (!state.get().equals(CacheState.STARTED)) {
		String message = StringUtility.format("定时策略[{}]已经停止,拒绝接收元素[{}]", name, element);
		LOGGER.error(message);
		throw new CacheException(message);
	}
	// 保证异步操作与异步持久不会冲突
	Object cacheId = element.getCacheId();
	Lock writeLock = waitForLock.writeLock();
	try {
		writeLock.lock();
		PersistenceElement current = newElements.get(cacheId);
		if (current == null) {
			current = element;
			newElements.put(cacheId, current);
		} else {
			current.modify(element);
			if (current.isIgnore()) {
				// 忽略只清理elementMap,不清理elementQueue
				newElements.remove(cacheId);
			}
		}
	} catch (CacheOperationException exception) {
		exceptionCount.incrementAndGet();
	} finally {
		writeLock.unlock();
	}
}
 
Example 13
Source File: SecurityUtility.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * AES解密
 * 
 * @param data
 * @param key
 * @return
 */
public static byte[] decryptAes(final byte[] data, final byte[] key) {
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, AES);
        Cipher cipher = Cipher.getInstance(AES);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    } catch (Exception exception) {
        String message = StringUtility.format("AES解密数据异常:[{}]", Arrays.toString(data));
        throw new RuntimeException(message, exception);
    }
}
 
Example 14
Source File: BerkeleyManager.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
public boolean deleteInstance(BerkeleyTransactor transactor, K id) {
	Transaction transaction = transactor == null ? null : transactor.getTransaction();
	if (primaryIndex.delete(transaction, id)) {
		return true;
	} else {
		String message = StringUtility.format("删除的实例[{}:{}]不存在", metadata.getOrmName(), id);
		if (logger.isDebugEnabled()) {
			logger.debug(message);
		}
		return false;
	}
}
 
Example 15
Source File: JsonUtility.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * 将JSON字符串转换为对象
 * 
 * @param json
 * @param type
 * @return
 */
public static <T> T string2Object(String json, Type type) {
    if (StringUtility.isBlank(json)) {
        return null;
    }
    try {
        return (T) TYPE_CONVERTER.readValue(json, TYPE_FACTORY.constructType(type));
    } catch (Exception exception) {
        String message = StringUtility.format("将JSON字符串[{}]转换为对象时异常", json);
        throw new RuntimeException(message, exception);
    }
}
 
Example 16
Source File: ObjectConverter.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Override
public void writeValueTo(ProtocolWriter context, Type type, ClassDefinition definition, Object value) throws Exception {
    OutputStream out = context.getOutputStream();
    byte information = ClassDefinition.getCode(Specification.OBJECT);
    if (value == null) {
        out.write(information);
        return;
    }
    int reference = context.getObjectIndex(value);
    if (reference != -1) {
        information |= REFERENCE_MARK;
        out.write(information);
        NumberConverter.writeNumber(out, reference);
    } else {
        information |= OBJECT_MARK;
        out.write(information);
        context.putObjectValue(value);

        // int code = definition.getCode();
        // NumberConverter.writeNumber(out, code);
        PropertyDefinition[] properties = definition.getProperties();
        // int size = properties.size();
        // if (size > PROPERTY_LIMIT) {
        // String message = StringUtility.format("类型[{}]属性数量[{}]超过最大值[{}]",
        // definition.getClass(), size, PROPERTY_LIMIT);
        // throw new ProtocolConverterException(message, new
        // RuntimeException(message));
        // }
        // out.write((byte) size);
        for (PropertyDefinition property : properties) {
            Object object;
            try {
                object = property.getValue(value);
                ProtocolConverter converter = context.getProtocolConverter(property.getSpecification());
                definition = context.getClassDefinition(property.getCode());
                converter.writeValueTo(context, property.getType(), definition, object);
            } catch (Exception exception) {
                String message = StringUtility.format("取值[{}]实例属性[{}]异常", definition.getName(), property.getName());
                throw new CodecConvertionException(message, exception);
            }
        }
    }
}
 
Example 17
Source File: QueuePersistenceStrategyTestCase.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testInhibit() throws Exception {
    int size = 1000;
    PersistenceStrategy strategy = getPersistenceStrategy("strategy", getPersistenceConfiguration());
    strategy.start(accessor, cacheInformations);
    PersistenceManager<Integer, MockEntityObject> manager = strategy.getPersistenceManager(MockEntityObject.class);

    // 创建数据
    long begin = System.currentTimeMillis();
    for (int index = 0; index < size; index++) {
        manager.createInstance(MockEntityObject.instanceOf(index, "birdy" + index, "hong", index, index));
    }
    while (true) {
        if (manager.getWaitSize() == 0) {
            break;
        }
        Thread.sleep(1000);
    }
    long end = System.currentTimeMillis();
    String message = StringUtility.format("创建{}数据的时间:{}毫秒", size, end - begin);
    logger.debug(message);

    // 修改数据
    int times = 10000;
    begin = System.currentTimeMillis();
    for (int index = 0; index < times; index++) {
        int id = RandomUtility.randomInteger(0, 5);
        manager.updateInstance(MockEntityObject.instanceOf(id, "xiao" + index, "xiao", index * index, index * index));
        // 有抑制才需要检查等待数量的大小
        if (manager.getWaitSize() > 5) {
            Assert.fail();
        }
    }
    while (true) {
        if (manager.getWaitSize() == 0) {
            break;
        }
        Thread.sleep(1000);
    }
    end = System.currentTimeMillis();
    message = StringUtility.format("修改{}数据的时间:{}毫秒", times, end - begin);
    logger.debug(message);

    // 删除数据
    begin = System.currentTimeMillis();
    for (int index = 0; index < size; index++) {
        manager.deleteInstance(index);
    }
    while (true) {
        if (manager.getWaitSize() == 0) {
            break;
        }
        Thread.sleep(1000);
    }
    end = System.currentTimeMillis();
    message = StringUtility.format("删除{}数据的时间:{}毫秒", size, end - begin);
    logger.debug(message);

    strategy.stop();
}
 
Example 18
Source File: Neo4jAccessor.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Override
public <K extends Comparable, I, T extends IdentityObject<K>> List<T> queryInstances(Class<T> clazz, String name, StorageCondition<I> condition) {
	try {
		Neo4jMetadata metadata = metadatas.get(clazz);
		HashMap<String, Object> parameters = new HashMap<>();
		StringBuilder buffer = new StringBuilder(INDEX_2_OBJECT_SET_BEGIN);
		ConditionType type = condition.getType();
		I[] values = condition.getValues();
		switch (type) {
		case All:
			break;
		case Between:
			buffer.append(BETWEEN_CONDITION);
			break;
		case Equal:
			buffer.append(EQUAL_CONDITION);
			break;
		case Higher:
			buffer.append(HIGHER_CONDITION);
			break;
		case In:
			StringBuilder string = new StringBuilder();
			for (int index = 1, size = values.length - 1; index <= size; index++) {
				string.append(", {");
				string.append(index);
				string.append("}");
			}
			buffer.append(StringUtility.format(IN_CONDITION, name, string.toString()));
			break;
		case Lower:
			buffer.append(LOWER_CONDITION);
			break;
		case Unequal:
			buffer.append(UNEQUAL_CONDITION);
			break;
		}
		buffer.append(INDEX_2_OBJECT_SET_END);
		String cql = buffer.toString();
		cql = StringUtility.format(cql, metadata.getOrmName(), name, name);
		for (int index = 0; index < values.length; index++) {
			parameters.put(String.valueOf(index), values[index]);
		}
		Iterable<T> keyValues = template.query(clazz, cql, parameters);
		List<T> list = new ArrayList<>(BATCH_SIZE);
		for (T keyValue : keyValues) {
			list.add(keyValue);
		}
		return list;
	} finally {
		template.clear();
	}
}
 
Example 19
Source File: SecurityUtility.java    From jstarcraft-core with Apache License 2.0 3 votes vote down vote up
/**
 * SHA1摘要
 * 
 * <pre>
 * http://www.atool.org/hash.php
 * </pre>
 * 
 * @param data
 * @return
 */
public static byte[] signatureSha1(byte[] data) {
    try {
        MessageDigest algorithm = MessageDigest.getInstance(SHA1);
        return algorithm.digest(data);
    } catch (Exception exception) {
        String message = StringUtility.format("[{}]:SHA1信息摘要异常", data);
        throw new RuntimeException(message, exception);
    }
}
 
Example 20
Source File: SecurityUtility.java    From jstarcraft-core with Apache License 2.0 3 votes vote down vote up
/**
 * MD5摘要
 * 
 * <pre>
 * http://www.atool.org/hash.php
 * </pre>
 * 
 * @param data
 * @return
 */
public static byte[] signatureMd5(byte[] data) {
    try {
        MessageDigest algorithm = MessageDigest.getInstance(MD5);
        return algorithm.digest(data);
    } catch (Exception exception) {
        String message = StringUtility.format("[{}]:MD5信息摘要异常", data);
        throw new RuntimeException(message, exception);
    }
}