Here are the examples of the java api com.google.common.collect.ImmutableMap.builder() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2636 Examples
19
Source : TestDirectoryExplorerUDFs.java
with Apache License 2.0
from zpochen
with Apache License 2.0
from zpochen
// DRILL-4720
@Test
public void testDirectoryUDFsWithAndWithoutMetadataCache() throws Exception {
FileSystem fs = getLocalFileSystem();
// prepare test table with parreplacedions
Path table = new Path(getTempDir("table_with_parreplacedions"));
String tablePath = table.toUri().getPath();
Path dataFile = new Path(TestTools.getWorkingPath(), "src/test/resources/parquet/alltypes_required.parquet");
createParreplacedions(fs, table, dataFile, 2);
Map<String, String> configurations = ImmutableMap.<String, String>builder().put("mindir", "part_1").put("imindir", "part_1").put("maxdir", "part_2").put("imaxdir", "part_2").build();
String query = "select dir0 from dfs.`%s` where dir0 = %s('dfs', '%s') limit 1";
// run tests without metadata cache
for (Map.Entry<String, String> entry : configurations.entrySet()) {
testBuilder().sqlQuery(query, tablePath, entry.getKey(), tablePath).unOrdered().baselineColumns("dir0").baselineValues(entry.getValue()).go();
}
// generate metadata
test("refresh table metadata dfs.`%s`", tablePath);
// run tests with metadata cache
for (Map.Entry<String, String> entry : configurations.entrySet()) {
testBuilder().sqlQuery(query, tablePath, entry.getKey(), tablePath).unOrdered().baselineColumns("dir0").baselineValues(entry.getValue()).go();
}
}
19
Source : TestDirectoryExplorerUDFs.java
with Apache License 2.0
from zpochen
with Apache License 2.0
from zpochen
@Test
public void testIncorrectFunctionPlacement() throws Exception {
Map<String, String> configMap = ImmutableMap.<String, String>builder().put("select %s('dfs.root','" + path + "') from dfs.`" + path + "/*/*.csv`", "Select List").put("select dir0 from dfs.`" + path + "/*/*.csv` order by %s('dfs.root','" + path + "')", "Order By").put("select max(dir0) from dfs.`" + path + "/*/*.csv` group by %s('dfs.root','" + path + "')", "Group By").put("select concat(concat(%s('dfs.root','" + path + "'),'someName'),'someName') from dfs.`" + path + "/*/*.csv`", "Select List").put("select dir0 from dfs.`" + path + "/*/*.csv` order by concat(%s('dfs.root','" + path + "'),'someName')", "Order By").put("select max(dir0) from dfs.`" + path + "/*/*.csv` group by concat(%s('dfs.root','" + path + "'),'someName')", "Group By").build();
for (Map.Entry<String, String> configEntry : configMap.entrySet()) {
for (ConstantFoldingTestConfig functionConfig : tests) {
try {
test(String.format(configEntry.getKey(), functionConfig.funcName));
} catch (UserRemoteException e) {
replacedertThat(e.getMessage(), containsString(String.format("Directory explorers [MAXDIR, IMAXDIR, MINDIR, IMINDIR] functions are not supported in %s", configEntry.getValue())));
}
}
}
}
19
Source : ViewableWithPermissions.java
with Apache License 2.0
from zpochen
with Apache License 2.0
from zpochen
private static Map<String, Object> createModel(final boolean authEnabled, final SecurityContext sc, final boolean showControls, final Object pageModel) {
final boolean isAdmin = !authEnabled || /* when auth is disabled every user is an admin user */
(showControls && sc.isUserInRole(DrillUserPrincipal.ADMIN_ROLE));
final boolean isUserLoggedIn = AuthDynamicFeature.isUserLoggedIn(sc);
final ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.<String, Object>builder().put("showStorage", isAdmin).put("showOptions", isAdmin).put("showThreads", isAdmin).put("showLogs", isAdmin).put("showLogin", authEnabled && showControls && !isUserLoggedIn).put("showLogout", authEnabled && showControls && isUserLoggedIn).put("loggedInUserName", authEnabled && showControls && isUserLoggedIn ? sc.getUserPrincipal().getName() : DrillUserPrincipal.ANONYMOUS_USER).put("showControls", showControls);
if (pageModel != null) {
mapBuilder.put("model", pageModel);
}
return mapBuilder.build();
}
19
Source : TestHiveStorage.java
with Apache License 2.0
from zpochen
with Apache License 2.0
from zpochen
// DRILL-3688
@Test
public void testIncorrectHeaderFooterProperty() throws Exception {
Map<String, String> testData = ImmutableMap.<String, String>builder().put("hive.skipper.kv_incorrect_skip_header", "skip.header.line.count").put("hive.skipper.kv_incorrect_skip_footer", "skip.footer.line.count").build();
String query = "select * from %s";
String exceptionMessage = "Hive table property %s value 'A' is non-numeric";
for (Map.Entry<String, String> entry : testData.entrySet()) {
try {
test(String.format(query, entry.getKey()));
} catch (UserRemoteException e) {
replacedertThat(e.getMessage(), containsString(String.format(exceptionMessage, entry.getValue())));
}
}
}
19
Source : AnnotationDescriptor.java
with Apache License 2.0
from zpochen
with Apache License 2.0
from zpochen
static Map<String, AnnotationDescriptor> buildAnnotationsMap(List<AnnotationDescriptor> annotations) {
ImmutableMap.Builder<String, AnnotationDescriptor> annMapBuilder = ImmutableMap.builder();
for (AnnotationDescriptor ann : annotations) {
annMapBuilder.put(ann.getAnnotationType(), ann);
}
return annMapBuilder.build();
}
19
Source : CaseInsensitiveMap.java
with Apache License 2.0
from zpochen
with Apache License 2.0
from zpochen
/**
* Returns a new instance of {@link ImmutableMap} with key case-insensitivity. This map is built from the given
* map. See {@link ImmutableMap}.
*
* @param map map to copy from
* @param <VALUE> type of values to be stored in the map
* @return key case-insensitive immutable map
*/
public static <VALUE> CaseInsensitiveMap<VALUE> newImmutableMap(final Map<? extends String, ? extends VALUE> map) {
final ImmutableMap.Builder<String, VALUE> builder = ImmutableMap.builder();
for (final Entry<? extends String, ? extends VALUE> entry : map.entrySet()) {
builder.put(entry.getKey().toLowerCase(), entry.getValue());
}
return new CaseInsensitiveMap<>(builder.build());
}
19
Source : SonarQubeCoverageGenerator.java
with Apache License 2.0
from Zetten
with Apache License 2.0
from Zetten
/**
* Reads the content of the given file and returns a matching map.
*
* <p>It replacedumes the file contains lines in the form key:value. For each line it creates an entry
* in the map with the corresponding key and value.
*/
private static ImmutableMap<String, String> getMapFromFile(String file) {
ImmutableMap.Builder<String, String> mapBuilder = ImmutableMap.builder();
try (FileInputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, UTF_8);
BufferedReader reader = new BufferedReader(inputStreamReader)) {
for (String keyToValueLine = reader.readLine(); keyToValueLine != null; keyToValueLine = reader.readLine()) {
String[] keyAndValue = keyToValueLine.split(":");
if (keyAndValue.length == 2) {
mapBuilder.put(keyAndValue[0], keyAndValue[1]);
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading file " + file + ": " + e.getMessage());
}
return mapBuilder.build();
}
19
Source : ExamplesWithGuavaTest.java
with Apache License 2.0
from zendesk
with Apache License 2.0
from zendesk
private static Map<String, Object> deal(int value, List<String> tags) {
return ImmutableMap.<String, Object>builder().put("value", value).put("tags", tags).build();
}
19
Source : Harvester.java
with Apache License 2.0
from zegelin
with Apache License 2.0
from zegelin
public Labels globalLabels() {
final InetAddress localBroadcastAddress = metadataFactory.localBroadcastAddress();
final MetadataFactory.EndpointMetadata localMetadata = metadataFactory.endpointMetadata(localBroadcastAddress).orElseThrow(() -> new IllegalStateException("Unable to get metadata about the local node."));
final ImmutableMap.Builder<String, String> mapBuilder = ImmutableMap.builder();
LabelEnum.addIfEnabled(GlobalLabel.CLUSTER, enabledGlobalLabels, mapBuilder, metadataFactory::clusterName);
LabelEnum.addIfEnabled(GlobalLabel.NODE, enabledGlobalLabels, mapBuilder, () -> InetAddresses.toAddrString(localBroadcastAddress));
LabelEnum.addIfEnabled(GlobalLabel.DATACENTER, enabledGlobalLabels, mapBuilder, localMetadata::dataCenter);
LabelEnum.addIfEnabled(GlobalLabel.RACK, enabledGlobalLabels, mapBuilder, localMetadata::rack);
return new Labels(mapBuilder.build());
}
19
Source : SysRoleServiceImpl.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* 初始化 {@link #roleCache} 缓存
*/
@Override
@PostConstruct
public void initLocalCache() {
// 获取菜单列表,如果有更新
List<SysRoleDO> roleList = this.loadRoleIfUpdate(maxUpdateTime);
if (CollUtil.isEmpty(roleList)) {
return;
}
// 写入缓存
ImmutableMap.Builder<Long, SysRoleDO> builder = ImmutableMap.builder();
roleList.forEach(sysRoleDO -> builder.put(sysRoleDO.getId(), sysRoleDO));
roleCache = builder.build();
// 断言,避免告警
replacedert roleList.size() > 0;
maxUpdateTime = roleList.stream().max(Comparator.comparing(BaseDO::getUpdateTime)).get().getUpdateTime();
log.info("[initLocalCache][初始化 Role 数量为 {}]", roleList.size());
}
19
Source : SysMenuServiceImpl.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* 初始化 {@link #menuCache} 和 {@link #permissionMenuCache} 缓存
*/
@Override
@PostConstruct
public synchronized void initLocalCache() {
// 获取菜单列表,如果有更新
List<SysMenuDO> menuList = this.loadMenuIfUpdate(maxUpdateTime);
if (CollUtil.isEmpty(menuList)) {
return;
}
// 构建缓存
ImmutableMap.Builder<Long, SysMenuDO> menuCacheBuilder = ImmutableMap.builder();
ImmutableMultimap.Builder<String, SysMenuDO> permMenuCacheBuilder = ImmutableMultimap.builder();
menuList.forEach(menuDO -> {
menuCacheBuilder.put(menuDO.getId(), menuDO);
permMenuCacheBuilder.put(menuDO.getPermission(), menuDO);
});
menuCache = menuCacheBuilder.build();
permissionMenuCache = permMenuCacheBuilder.build();
// 断言,避免告警
replacedert menuList.size() > 0;
maxUpdateTime = menuList.stream().max(Comparator.comparing(BaseDO::getUpdateTime)).get().getUpdateTime();
log.info("[initLocalCache][缓存菜单,数量为:{}]", menuList.size());
}
19
Source : SysDeptServiceImpl.java
with MIT License
from YunaiV
with MIT License
from YunaiV
@Override
@PostConstruct
public synchronized void initLocalCache() {
// 获取部门列表,如果有更新
List<SysDeptDO> deptList = this.loadDeptIfUpdate(maxUpdateTime);
if (CollUtil.isEmpty(deptList)) {
return;
}
// 构建缓存
ImmutableMap.Builder<Long, SysDeptDO> builder = ImmutableMap.builder();
ImmutableMultimap.Builder<Long, SysDeptDO> parentBuilder = ImmutableMultimap.builder();
deptList.forEach(sysRoleDO -> {
builder.put(sysRoleDO.getId(), sysRoleDO);
parentBuilder.put(sysRoleDO.getParentId(), sysRoleDO);
});
// 设置缓存
deptCache = builder.build();
parentDeptCache = parentBuilder.build();
// 断言,避免告警
replacedert deptList.size() > 0;
maxUpdateTime = deptList.stream().max(Comparator.comparing(BaseDO::getUpdateTime)).get().getUpdateTime();
log.info("[initLocalCache][初始化 Dept 数量为 {}]", deptList.size());
}
19
Source : WithBasicAuthSecurityConfiguration.java
with MIT License
from yidongnan
with MIT License
from yidongnan
// Client-Side
@Bean
StubTransformer mappedCredentialsStubTransformer() {
return CallCredentialsHelper.mappedCredentialsStubTransformer(ImmutableMap.<String, CallCredentials>builder().put("test", testCallCredentials("client1")).put("noPerm", testCallCredentials("client2")).put("unknownUser", testCallCredentials("unknownUser")).build());
}
19
Source : InProcessOrAlternativeChannelFactory.java
with MIT License
from yidongnan
with MIT License
from yidongnan
@Override
public Map<String, ConnectivityState> getConnectivityState() {
return ImmutableMap.<String, ConnectivityState>builder().putAll(inProcessChannelFactory.getConnectivityState()).putAll(alternativeChannelFactory.getConnectivityState()).build();
}
19
Source : OperatorNode.java
with Apache License 2.0
from yahoo
with Apache License 2.0
from yahoo
private Map<String, Object> annotationCopy(Map<String, Object> annotations) {
ImmutableMap.Builder<String, Object> newAnnotations = ImmutableMap.builder();
for (Map.Entry<String, Object> annotation : annotations.entrySet()) {
String key = annotation.getKey();
Object value = COPY_OR_OMIT.apply(annotation.getValue());
if (value != null) {
newAnnotations.put(key, value);
}
}
return newAnnotations.build();
}
19
Source : KubeMetadata.java
with Apache License 2.0
from xuxinkun
with Apache License 2.0
from xuxinkun
@Override
public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) {
requireNonNull(prefix, "prefix is null");
ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder();
for (SchemaTableName tableName : listTables(session, prefix)) {
KubeTableHandle tableHandle = kubeTables.getTable(tableName);
if (tableHandle != null) {
columns.put(tableName, kubeTables.getColumns(tableHandle));
}
}
return columns.build();
}
19
Source : KubeMetadata.java
with Apache License 2.0
from xuxinkun
with Apache License 2.0
from xuxinkun
private Map<String, ColumnHandle> getColumnHandles(KubeTableHandle tableHandle) {
ImmutableMap.Builder<String, ColumnHandle> columnHandles = ImmutableMap.builder();
int index = 0;
for (ColumnMetadata column : kubeTables.getColumns(tableHandle)) {
columnHandles.put(column.getName(), new KubeColumnHandle(column.getName(), column.getType(), index));
}
return columnHandles.build();
}
19
Source : EthereumMetadata.java
with Apache License 2.0
from xiaoyao1991
with Apache License 2.0
from xiaoyao1991
@Override
public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) {
requireNonNull(prefix, "prefix is null");
ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder();
List<SchemaTableName> tableNames = prefix.getSchemaName() == null ? listTables(session, null) : ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName()));
for (SchemaTableName tableName : tableNames) {
ConnectorTableMetadata tableMetadata = getTableMetadata(tableName);
// table can disappear during listing operation
if (tableMetadata != null) {
columns.put(tableName, tableMetadata.getColumns());
}
}
return columns.build();
}
19
Source : EthereumMetadata.java
with Apache License 2.0
from xiaoyao1991
with Apache License 2.0
from xiaoyao1991
@SuppressWarnings("ValueOfIncrementOrDecrementUsed")
@Override
public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle) {
EthereumTableHandle ethereumTableHandle = convertTableHandle(tableHandle);
String tableName = ethereumTableHandle.getTableName();
ImmutableMap.Builder<String, ColumnHandle> columnHandles = ImmutableMap.builder();
int index = 0;
if (EthereumTable.BLOCK.getName().equals(tableName)) {
columnHandles.put("block_number", new EthereumColumnHandle(connectorId, index++, "block_number", BigintType.BIGINT));
columnHandles.put("block_hash", new EthereumColumnHandle(connectorId, index++, "block_hash", VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("block_parentHash", new EthereumColumnHandle(connectorId, index++, "block_parentHash", VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("block_nonce", new EthereumColumnHandle(connectorId, index++, "block_nonce", VarcharType.createVarcharType(H8_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("block_sha3Uncles", new EthereumColumnHandle(connectorId, index++, "block_sha3Uncles", VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("block_logsBloom", new EthereumColumnHandle(connectorId, index++, "block_logsBloom", VarcharType.createVarcharType(H256_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("block_transactionsRoot", new EthereumColumnHandle(connectorId, index++, "block_transactionsRoot", VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("block_stateRoot", new EthereumColumnHandle(connectorId, index++, "block_stateRoot", VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("block_miner", new EthereumColumnHandle(connectorId, index++, "block_miner", VarcharType.createVarcharType(H20_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("block_difficulty", new EthereumColumnHandle(connectorId, index++, "block_difficulty", BigintType.BIGINT));
columnHandles.put("block_totalDifficulty", new EthereumColumnHandle(connectorId, index++, "block_totalDifficulty", BigintType.BIGINT));
columnHandles.put("block_size", new EthereumColumnHandle(connectorId, index++, "block_size", IntegerType.INTEGER));
columnHandles.put("block_extraData", new EthereumColumnHandle(connectorId, index++, "block_extraData", VarcharType.VARCHAR));
columnHandles.put("block_gasLimit", new EthereumColumnHandle(connectorId, index++, "block_gasLimit", DoubleType.DOUBLE));
columnHandles.put("block_gasUsed", new EthereumColumnHandle(connectorId, index++, "block_gasUsed", DoubleType.DOUBLE));
columnHandles.put("block_timestamp", new EthereumColumnHandle(connectorId, index++, "block_timestamp", BigintType.BIGINT));
columnHandles.put("block_transactions", new EthereumColumnHandle(connectorId, index++, "block_transactions", new ArrayType(VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH))));
columnHandles.put("block_uncles", new EthereumColumnHandle(connectorId, index++, "block_uncles", new ArrayType(VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH))));
} else if (EthereumTable.TRANSACTION.getName().equals(tableName)) {
columnHandles.put("tx_hash", new EthereumColumnHandle(connectorId, index++, "tx_hash", VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("tx_nonce", new EthereumColumnHandle(connectorId, index++, "tx_nonce", BigintType.BIGINT));
columnHandles.put("tx_blockHash", new EthereumColumnHandle(connectorId, index++, "tx_blockHash", VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("tx_blockNumber", new EthereumColumnHandle(connectorId, index++, "tx_blockNumber", BigintType.BIGINT));
columnHandles.put("tx_transactionIndex", new EthereumColumnHandle(connectorId, index++, "tx_transactionIndex", IntegerType.INTEGER));
columnHandles.put("tx_from", new EthereumColumnHandle(connectorId, index++, "tx_from", VarcharType.createVarcharType(H20_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("tx_to", new EthereumColumnHandle(connectorId, index++, "tx_to", VarcharType.createVarcharType(H20_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("tx_value", new EthereumColumnHandle(connectorId, index++, "tx_value", DoubleType.DOUBLE));
columnHandles.put("tx_gas", new EthereumColumnHandle(connectorId, index++, "tx_gas", DoubleType.DOUBLE));
columnHandles.put("tx_gasPrice", new EthereumColumnHandle(connectorId, index++, "tx_gasPrice", DoubleType.DOUBLE));
columnHandles.put("tx_input", new EthereumColumnHandle(connectorId, index++, "tx_input", VarcharType.VARCHAR));
} else if (EthereumTable.ERC20.getName().equals(tableName)) {
columnHandles.put("erc20_token", new EthereumColumnHandle(connectorId, index++, "erc20_token", VarcharType.createUnboundedVarcharType()));
columnHandles.put("erc20_from", new EthereumColumnHandle(connectorId, index++, "erc20_from", VarcharType.createVarcharType(H20_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("erc20_to", new EthereumColumnHandle(connectorId, index++, "erc20_to", VarcharType.createVarcharType(H20_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("erc20_value", new EthereumColumnHandle(connectorId, index++, "erc20_value", DoubleType.DOUBLE));
columnHandles.put("erc20_txHash", new EthereumColumnHandle(connectorId, index++, "erc20_txHash", VarcharType.createVarcharType(H32_BYTE_HASH_STRING_LENGTH)));
columnHandles.put("erc20_blockNumber", new EthereumColumnHandle(connectorId, index++, "erc20_blockNumber", BigintType.BIGINT));
} else {
throw new IllegalArgumentException("Unknown Table Name " + tableName);
}
return columnHandles.build();
}
19
Source : TestingCluster.java
with Apache License 2.0
from xiancloud
with Apache License 2.0
from xiancloud
private static Map<InstanceSpec, Collection<InstanceSpec>> listToMap(Collection<InstanceSpec> list) {
ImmutableMap.Builder<InstanceSpec, Collection<InstanceSpec>> mapBuilder = ImmutableMap.builder();
for (InstanceSpec spec : list) {
mapBuilder.put(spec, list);
}
return mapBuilder.build();
}
19
Source : TreeCache.java
with Apache License 2.0
from xiancloud
with Apache License 2.0
from xiancloud
/**
* Return the current set of children at the given path, mapped by child name. There are no
* guarantees of accuracy; this is merely the most recent view of the data. If there is no
* node at this path, {@code null} is returned.
*
* @param fullPath full path to the node to check
* @return a possibly-empty list of children if the node is alive, or null
*/
public Map<String, ChildData> getCurrentChildren(String fullPath) {
TreeNode node = find(fullPath);
if (node == null || node.nodeState != NodeState.LIVE) {
return null;
}
ConcurrentMap<String, TreeNode> map = node.children;
Map<String, ChildData> result;
if (map == null) {
result = ImmutableMap.of();
} else {
ImmutableMap.Builder<String, ChildData> builder = ImmutableMap.builder();
for (Map.Entry<String, TreeNode> entry : map.entrySet()) {
TreeNode childNode = entry.getValue();
ChildData childData = childNode.childData;
// Double-check liveness after retreiving data.
if (childData != null && childNode.nodeState == NodeState.LIVE) {
builder.put(entry.getKey(), childData);
}
}
result = builder.build();
}
// Double-check liveness after retreiving children.
return node.nodeState == NodeState.LIVE ? result : null;
}
19
Source : JuggPreloadHandler.java
with MIT License
from XhinLiang
with MIT License
from XhinLiang
@Override
public Map<String, String> patternToMessage() {
return //
ImmutableMap.<String, String>builder().put("preload list", //
"list all preloaders.").put("preload {{packageName}}", //
"preload package").build();
}
19
Source : JuggHistoryHandler.java
with MIT License
from XhinLiang
with MIT License
from XhinLiang
@Override
public Map<String, String> patternToMessage() {
return //
ImmutableMap.<String, String>builder().put("history", //
"list all histories.").put("history {{search}}", //
"search histories").build();
}
19
Source : JuggHelpHandler.java
with MIT License
from XhinLiang
with MIT License
from XhinLiang
@Override
public Map<String, String> patternToMessage() {
return //
ImmutableMap.<String, String>builder().put("help", //
"list all help messages.").put("help {{handlerName}}", //
"list help messages of this handler").build();
}
19
Source : JuggDumpHandler.java
with MIT License
from XhinLiang
with MIT License
from XhinLiang
@Override
public Map<String, String> patternToMessage() {
return //
ImmutableMap.<String, String>builder().put("dump list", //
"list available files.").put("dump save", //
"save current context.").put("dump load {{id}}", //
"load saved context by id.").put("dump rm {{id}}", //
"rm saved context.").put("dump current", //
"show current context.").build();
}
19
Source : JuggAliasHandler.java
with MIT License
from XhinLiang
with MIT License
from XhinLiang
@Override
public Map<String, String> patternToMessage() {
return //
ImmutableMap.<String, String>builder().put("alias target", //
"list all current alias.").put("alias target {{aliaName}} {{realName}}", //
"list help messages of this handler").build();
}
19
Source : JuggEvalHandler.java
with MIT License
from XhinLiang
with MIT License
from XhinLiang
@Override
public Map<String, String> patternToMessage() {
return //
ImmutableMap.<String, String>builder().put("obj", //
"obj to json, obj could be a OGNL local field or a bean.").put("bean.method()", //
"call method of bean").put("bean.method(1L)", //
"call method of bean with param 1L").put("obj = bean.method(1L)", //
"call method of bean with param 1L, and set the result as a OGNL local field call 'obj'.").build();
}
19
Source : VariableMap.java
with GNU General Public License v2.0
from xgdsmileboy
with GNU General Public License v2.0
from xgdsmileboy
/**
* Initializes the reverse map.
*/
private synchronized void initReverseMap() {
if (reverseMap == null) {
ImmutableMap.Builder<String, String> rm = ImmutableMap.builder();
for (Map.Entry<String, String> entry : map.entrySet()) {
rm.put(entry.getValue(), entry.getKey());
}
reverseMap = rm.build();
}
}
19
Source : RenamePrototypes.java
with GNU General Public License v2.0
from xgdsmileboy
with GNU General Public License v2.0
from xgdsmileboy
/**
* Gets the property renaming map.
*
* @return A mapping from original names to new names
*/
VariableMap getPropertyMap() {
ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
for (Property p : properties.values()) {
if (p.newName != null) {
map.put(p.oldName, p.newName);
}
}
return new VariableMap(map.build());
}
19
Source : RenameProperties.java
with GNU General Public License v2.0
from xgdsmileboy
with GNU General Public License v2.0
from xgdsmileboy
/**
* Gets the property renaming map (the "answer key").
*
* @return A mapping from original names to new names
*/
VariableMap getPropertyMap() {
ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
for (Property p : propertyMap.values()) {
if (p.newName != null) {
map.put(p.oldName, p.newName);
}
}
return new VariableMap(map.build());
}
19
Source : Config.java
with GNU General Public License v2.0
from xgdsmileboy
with GNU General Public License v2.0
from xgdsmileboy
/**
* Create the annotation names from the user-specified
* annotation whitelist.
*/
private static Map<String, Annotation> buildAnnotationNames(Set<String> annotationWhitelist) {
ImmutableMap.Builder<String, Annotation> annotationBuilder = ImmutableMap.builder();
annotationBuilder.putAll(Annotation.recognizedAnnotations);
for (String unrecognizedAnnotation : annotationWhitelist) {
if (!Annotation.recognizedAnnotations.containsKey(unrecognizedAnnotation)) {
annotationBuilder.put(unrecognizedAnnotation, Annotation.NOT_IMPLEMENTED);
}
}
return annotationBuilder.build();
}
19
Source : FcmModelConverter.java
with Apache License 2.0
from wultra
with Apache License 2.0
from wultra
/**
* Convert Message to payload for WebClient.
*
* @param message Message to send.
* @param validateOnly Whether to perform only validation.
* @return Flux of DataBuffer.
*/
public Flux<DataBuffer> convertMessageToFlux(Message message, boolean validateOnly) {
ImmutableMap.Builder<String, Object> payloadBuilder = ImmutableMap.<String, Object>builder().put("message", message);
if (validateOnly) {
payloadBuilder.put("validate_only", true);
}
ImmutableMap<String, Object> payload = payloadBuilder.build();
String convertedMessage;
try {
StringWriter writer = new StringWriter();
JsonGenerator gen = jsonFactory.createJsonGenerator(writer);
gen.serialize(payload);
gen.close();
convertedMessage = writer.toString();
} catch (IOException ex) {
logger.error("Json serialization failed: {}", ex.getMessage(), ex);
return null;
}
DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
DefaultDataBuffer dataBuffer = factory.wrap(ByteBuffer.wrap(convertedMessage.getBytes(StandardCharsets.UTF_8)));
return Flux.just(dataBuffer);
}
19
Source : ScriptRunBackgroundServlet.java
with Apache License 2.0
from wttech
with Apache License 2.0
from wttech
private Map<String, Object> createMapWithJobIdKey(Job job) {
return ImmutableMap.<String, Object>builder().put(ID_REQUEST_PARAMETER, job.getId()).build();
}
19
Source : HistoricalStatsRequestBuilder.java
with Apache License 2.0
from WojciechZankowski
with Apache License 2.0
from WojciechZankowski
private Map<String, String> getDateParams() {
if (date != null) {
return ImmutableMap.<String, String>builder().put("date", IEX_YEAR_MONTH_FORMATTER.format(date)).build();
}
return ImmutableMap.of();
}
19
Source : HistoricalDailyStatsRequestBuilder.java
with Apache License 2.0
from WojciechZankowski
with Apache License 2.0
from WojciechZankowski
private Map<String, String> getDateParams() {
if (date != null) {
return ImmutableMap.<String, String>builder().put("date", IEX_YEAR_MONTH_FORMATTER.format(date)).build();
} else if (fullDate != null) {
return ImmutableMap.<String, String>builder().put("date", IEX_DATE_FORMATTER.format(fullDate)).build();
} else if (last != null) {
return ImmutableMap.<String, String>builder().put("last", String.valueOf(last)).build();
}
return ImmutableMap.of();
}
19
Source : AbstractRequestFilterBuilder.java
with Apache License 2.0
from WojciechZankowski
with Apache License 2.0
from WojciechZankowski
protected Map<String, String> getFilterParams() {
if (requestFilter != null) {
return ImmutableMap.<String, String>builder().put("filter", requestFilter.getColumnList()).build();
}
return ImmutableMap.of();
}
19
Source : CiTypeServiceImplTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Transactional
@Test
public void testCreateCiDataShouldIgnoreAutoFillRuleForNotCreatedCiAttr() {
givenAppliedCiTypeAndAttr();
givenUnappliedCiTypeAndRef();
givenAutoFillRuleForUnappliedAttrReferencingAppliedCiAttr();
String guid = ciService.create(appliedCiTypeId, ImmutableMap.<String, Object>builder().put("code", "code").put("appliedAttr", "appliedAttr").build());
replacedert.replacedertNotNull(guid);
}
19
Source : StateMachineTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
private void insertCiData(int ciTypeId) throws Exception {
Map<?, ?> jsonMap = ImmutableMap.builder().put("description", "insert desc").put("name", String.valueOf(System.currentTimeMillis())).build();
String reqJson = JsonUtil.toJson(ImmutableList.of(jsonMap));
mvc.perform(post("/api/v2/ci/{ciTypeId}/create", ciTypeId).contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data[0].guid", notNullValue()));
}
19
Source : ApiV2ControllerTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Test
public void retrieveCiLayersFromCatsCrossResourceReferenceToCodes() throws Exception {
Map<?, ?> jsonMap = ImmutableMap.builder().put("filters", ImmutableList.builder().add(new Filter("catName", "eq", "ci_layer")).build()).put("refResources", ImmutableList.builder().add("codes").build()).build();
String reqJson = JsonUtil.toJson(jsonMap);
mvc.perform(post("/api/v2/enum/cats/retrieve").contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data.contents[0].codes", hreplacedize(4)));
}
19
Source : ApiV2ControllerTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Test
public void retrieveCiLayersFromCodesCrossResourceReferenceToCat() throws Exception {
Map<?, ?> jsonMap = ImmutableMap.builder().put("filters", ImmutableList.builder().add(new Filter("cat.catName", "eq", "ci_layer")).build()).put("refResources", ImmutableList.builder().add("cat").build()).put("sorting", ImmutableMap.builder().put("asc", true).put("field", "code").build()).build();
String reqJson = JsonUtil.toJson(jsonMap);
mvc.perform(post("/api/v2/enum/codes/retrieve").contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data.contents", hreplacedize(4)));
}
19
Source : ApiV2ControllerTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Test
public void retrieveCiWithFilterThenReturnFilteredCiData() throws Exception {
int ciTypeId = 2;
Map<?, ?> jsonMap = ImmutableMap.builder().put("filters", ImmutableList.builder().add(ImmutableMap.builder().put("name", "name_en").put("operator", "eq").put("value", "Bank system").build()).build()).build();
String reqJson = JsonUtil.toJson(jsonMap);
mvc.perform(post("/api/v2/ci/" + ciTypeId + "/retrieve").contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data.contents[0].data.name_en", is("Bank system")));
}
19
Source : ApiV2ControllerTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
private ImmutableMap<Object, Object> genCatTypeUpdateRequest(String callbackId, String catName, int catTypeId) {
return ImmutableMap.builder().put("callbackId", callbackId).put("catTypeId", catTypeId).put("catTypeName", catName).put("description", "mock_description_update").build();
}
19
Source : ApiV2ControllerTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Test
public void retrieveCiZoomLevelsFromCatsCrossResourceReferenceToCodes() throws Exception {
Map<?, ?> jsonMap = ImmutableMap.builder().put("filters", ImmutableList.builder().add(new Filter("catName", "eq", "ci_zoom_level")).build()).put("refResources", ImmutableList.builder().add("codes").build()).build();
String reqJson = JsonUtil.toJson(jsonMap);
mvc.perform(post("/api/v2/enum/cats/retrieve").contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data.contents", hreplacedize(1))).andExpect(jsonPath("$.data.contents[0].codes", hreplacedize(4)));
}
19
Source : ApiV2ControllerTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Test
public void applyCiTypeWithAttrsThenTheCiStatusShouldBeCreatedAndCanBeRetrievedWithoutException() throws Exception {
int ciTypeId = 21;
mvc.perform(post("/api/v2/ci/" + ciTypeId + "/retrieve").contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(jsonPath("$.statusCode", is("ERR_INVALID_ARGUMENT")));
mvc.perform(post("/api/v2/ciTypes/applyAll").contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.statusCode", is("OK")));
this.reload();
Map<?, ?> jsonMap = ImmutableMap.builder().put("filters", ImmutableList.builder().add(ImmutableMap.builder().put("name", "name").put("operator", "eq").put("value", "Mock_Ci_Type_A").build()).build()).build();
String reqJson = JsonUtil.toJson(jsonMap);
mvc.perform(post("/api/v2/ciTypes/retrieve").contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data.contents", hreplacedize(1))).andExpect(jsonPath("$.data.contents[0].status", is("created")));
mvc.perform(post("/api/v2/ci/" + ciTypeId + "/retrieve").contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(jsonPath("$.statusCode", is("OK")));
}
19
Source : ApiV2ControllerTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Test
public void retrieveCatTypesWithFilterThenReturnFilteredCatTypes() throws Exception {
Map<?, ?> jsonMap = ImmutableMap.builder().put("filters", ImmutableList.builder().add(ImmutableMap.builder().put("name", "catTypeName").put("operator", "eq").put("value", "CMDB Commons").build()).build()).build();
String reqJson = JsonUtil.toJson(jsonMap);
mvc.perform(post("/api/v2/enum/catTypes/retrieve").contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data.contents", hreplacedize(1)));
}
19
Source : ApiV2ControllerTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
private ImmutableMap<Object, Object> genCatTypeCreateRequest(String callbackId, String mockCatTypeName, int ciTypeId) {
return ImmutableMap.builder().put("callbackId", callbackId).put("catTypeName", mockCatTypeName).put("description", "mock_description").put("ciTypeId", ciTypeId).build();
}
19
Source : ApiV2ControllerStateTransitionTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
private void insertNonDesignTypeCiData(int ciTypeId) throws Exception {
Map<?, ?> jsonMap = ImmutableMap.builder().put("description", "insert desc").put("name", String.valueOf(System.currentTimeMillis())).build();
String reqJson = JsonUtil.toJson(ImmutableList.of(jsonMap));
MvcResult mvcResult = mvc.perform(post("/api/v2/ci/{ciTypeId}/create", ciTypeId).contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data[0].guid", notNullValue())).andReturn();
String retContent = mvcResult.getResponse().getContentreplacedtring();
String guid = JsonUtil.asNodeByPath(retContent, "/data/0/guid").asText();
queryCiDataShouldBeSuccessful(ciTypeId, guid, "created", false);
}
19
Source : ApiV2ControllerStateTransitionTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
private void updateCiData(int ciTypeId, String guid) throws Exception {
// get existing description
com.webank.cmdb.dto.QueryRequest request;
String existingDesc = getFieldValue(ciTypeId, guid, "description", false);
Map<?, ?> jsonMap = ImmutableMap.builder().put("guid", guid).put("description", "update desc new").build();
String updateJson = JsonUtil.toJson(ImmutableList.of(jsonMap));
MvcResult updateResult = mvc.perform(post("/api/v2/ci/{ciTypeId}/update", ciTypeId).contentType(MediaType.APPLICATION_JSON).content(updateJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data", hreplacedize(equalTo(1)))).andReturn();
String updatedRet = updateResult.getResponse().getContentreplacedtring();
JsonNode updateResultDataNode = new ObjectMapper().readTree(updatedRet).get("data");
if (updateResultDataNode.isArray()) {
replacedertThat(updateResultDataNode.get(0).get("description").asText(), equalTo("update desc new"));
}
String parentGuid = JsonUtil.asNodeByPath(updatedRet, "/data/0/p_guid").asText();
if (!Strings.isNullOrEmpty(parentGuid)) {
// compare the description from parent ci with existing description
request = new com.webank.cmdb.dto.QueryRequest();
request.getDialect().setShowCiHistory(true);
request.setFilters(Lists.newArrayList(new Filter("guid", FilterOperator.Equal.getCode(), parentGuid)));
MvcResult parentResult = mvc.perform(post("/api/v2/ci/{ciTypeId}/retrieve", ciTypeId).contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(request))).andReturn();
String parentRetContent = parentResult.getResponse().getContentreplacedtring();
String parentDesc = JsonUtil.asNodeByPath(parentRetContent, "/data/contents/0/data/description").asText();
replacedertThat(parentDesc, equalTo(existingDesc));
}
}
19
Source : ApiV2ControllerStateTransitionTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
private void insertDesignTypeCiData(int ciTypeId) throws Exception {
Map<?, ?> jsonMap = ImmutableMap.builder().put("description", "insert desc").put("state", 141).put("name", String.valueOf(System.currentTimeMillis())).build();
String reqJson = JsonUtil.toJson(ImmutableList.of(jsonMap));
MvcResult mvcResult = mvc.perform(post("/api/v2/ci/{ciTypeId}/create", ciTypeId).contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data[0].guid", notNullValue())).andReturn();
String retContent = mvcResult.getResponse().getContentreplacedtring();
String guid = JsonUtil.asNodeByPath(retContent, "/data/0/guid").asText();
queryCiDataShouldBeSuccessful(ciTypeId, guid, "new", false);
}
19
Source : ApiV2ControllerRoleCiTypeCtrlAttrConditionTest.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Test
public void whenCreateRoleCiTypeCtrlAttrConditionShouldReturnRoleId() throws Exception {
List<?> jsonList = ImmutableList.builder().add(ImmutableMap.builder().put("callbackId", "123456").put("roleCiTypeCtrlAttrId", 3).put("ciTypeAttrId", 10109).put("conditionValueExprs", Lists.newArrayList("subsys_design[{key_name eq 'WECUBE-DEMO'}]:guid")).put("conditionType", "Expression").build()).build();
String reqJson = JsonUtil.toJson(jsonList);
mvc.perform(post("/api/v2/role-citype-ctrl-attr-conditions/create").contentType(MediaType.APPLICATION_JSON).content(reqJson)).andExpect(jsonPath("$.statusCode", is("OK"))).andExpect(jsonPath("$.data[0].conditionId", greaterThanOrEqualTo(1))).andExpect(jsonPath("$.data[0].conditionType", is("Expression")));
}
See More Examples