focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public IndexRange get(String index) throws NotFoundException { final DBQuery.Query query = DBQuery.and( DBQuery.notExists("start"), DBQuery.is(IndexRange.FIELD_INDEX_NAME, index)); final MongoIndexRange indexRange = collection.findOne(query); if (indexRange == null) { throw new NotFoundException("Index range for index <" + index + "> not found."); } return indexRange; }
@Test(expected = NotFoundException.class) public void getThrowsNotFoundException() throws Exception { indexRangeService.get("does-not-exist"); }
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchIcmpTypeTest() { Criterion criterion = Criteria.matchIcmpType((byte) 250); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
@GET @Produces(MediaType.APPLICATION_JSON) @Path("{networkId}/devices") public Response getVirtualDevices(@PathParam("networkId") long networkId) { NetworkId nid = NetworkId.networkId(networkId); Set<VirtualDevice> vdevs = vnetService.getVirtualDevices(nid); return ok(encodeArray(VirtualDevice.class, "devices", vdevs)).build(); }
@Test public void testGetVirtualDevicesArray() { NetworkId networkId = networkId3; vdevSet.add(vdev1); vdevSet.add(vdev2); expect(mockVnetService.getVirtualDevices(networkId)).andReturn(vdevSet).anyTimes(); replay(mockVnetService); WebTarget wt = target(); String location = "vnets/" + networkId.toString() + "/devices"; String response = wt.path(location).request().get(String.class); assertThat(response, containsString("{\"devices\":[")); final JsonObject result = Json.parse(response).asObject(); assertThat(result, notNullValue()); assertThat(result.names(), hasSize(1)); assertThat(result.names().get(0), is("devices")); final JsonArray vnetJsonArray = result.get("devices").asArray(); assertThat(vnetJsonArray, notNullValue()); assertEquals("Virtual devices array is not the correct size.", vdevSet.size(), vnetJsonArray.size()); vdevSet.forEach(vdev -> assertThat(vnetJsonArray, hasVdev(vdev))); verify(mockVnetService); }
public void commitPartitions() throws Exception { commitPartitions((subtaskIndex, attemptNumber) -> true); }
@Test void testPartitionPathNotExist() throws Exception { Files.delete(path); LinkedHashMap<String, String> staticPartitions = new LinkedHashMap<String, String>(); FileSystemCommitter committer = new FileSystemCommitter( fileSystemFactory, metaStoreFactory, true, new Path(path.toString()), 1, false, identifier, staticPartitions, policies); committer.commitPartitions(); assertThat(outputPath.toFile().list()).isEqualTo(new String[0]); }
@Override public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException { Configuration configuration = context.getConfiguration(); int numSplits = DistCpUtils.getInt(configuration, JobContext.NUM_MAPS); if (numSplits == 0) return new ArrayList<InputSplit>(); return getSplits(configuration, numSplits, DistCpUtils.getLong(configuration, DistCpConstants.CONF_LABEL_TOTAL_BYTES_TO_BE_COPIED)); }
@Test public void testGetSplits() throws Exception { testGetSplits(9); for (int i=1; i<N_FILES; ++i) testGetSplits(i); }
@Override public BatchKVResponse<K, EntityResponse<V>> wrapResponse(DataMap dataMap, Map<String, String> headers, ProtocolVersion version) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException { if (dataMap == null) { return null; } return new BatchEntityResponse<>(dataMap, _keyType, _entityType, _keyParts, _complexKeyType, version); }
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "batchEntityResponseDataProvider") public void testDecoding(List<String> keys, ProtocolVersion protocolVersion) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException { final String resultKey = keys.get(0); final String statusKey = keys.get(1); final String errorKey = keys.get(2); final DataMap resultData = new DataMap(); resultData.put(resultKey, _record.data()); final DataMap statusData = new DataMap(); statusData.put(statusKey, _status.getCode()); final DataMap errorData = new DataMap(); errorData.put(errorKey, _error.data()); final DataMap data = new DataMap(); data.put(BatchResponse.RESULTS, resultData); data.put(BatchResponse.STATUSES, statusData); data.put(BatchResponse.ERRORS, errorData); final BatchEntityResponseDecoder<String, TestRecord> decoder = new BatchEntityResponseDecoder<>(new TypeSpec<>(TestRecord.class), new TypeSpec<>(String.class), Collections.<String, CompoundKey.TypeInfo>emptyMap(), null); final BatchKVResponse<String, EntityResponse<TestRecord>> response = decoder.wrapResponse(data, Collections.<String, String>emptyMap(), protocolVersion); final Map<String, EntityResponse<TestRecord>> results = response.getResults(); final Map<String, ErrorResponse> errors = response.getErrors(); final Collection<String> uniqueKeys = new HashSet<>(keys); Assert.assertEquals(results.size(), uniqueKeys.size()); Assert.assertEquals(errors.size(), 1); Assert.assertEquals(results.get(resultKey).getEntity(), _record); Assert.assertEquals(results.get(statusKey).getStatus(), _status); Assert.assertEquals(results.get(errorKey).getError(), _error); Assert.assertEquals(errors.get(errorKey), _error); // Check that the response still contains the original data map Assert.assertEquals(response.data(), data); }
static Date parseDate(final String value) { try { return getUtilDateFormat().parse(value); } catch (ParseException e) { return throwRuntimeParseException(value, e, DATE_FORMAT); } }
@Test public void testUtilDate() { long now = System.currentTimeMillis(); Date date1 = new Date(now); Date date2 = DateHelper.parseDate(new SimpleDateFormat(DateHelperTest.DATE_FORMAT, Locale.US).format(date1)); Calendar cal1 = Calendar.getInstance(Locale.US); cal1.setTimeInMillis(date1.getTime()); Calendar cal2 = Calendar.getInstance(Locale.US); cal2.setTimeInMillis(date2.getTime()); assertEquals(cal1.get(Calendar.YEAR), cal2.get(Calendar.YEAR)); assertEquals(cal1.get(Calendar.MONTH), cal2.get(Calendar.MONTH)); assertEquals(cal1.get(Calendar.DAY_OF_MONTH), cal2.get(Calendar.DAY_OF_MONTH)); assertEquals(cal1.get(Calendar.HOUR_OF_DAY), cal2.get(Calendar.HOUR_OF_DAY)); assertEquals(cal1.get(Calendar.MINUTE), cal2.get(Calendar.MINUTE)); assertEquals(cal1.get(Calendar.SECOND), cal2.get(Calendar.SECOND)); }
@Override public boolean trySetCapacity(int capacity) { return get(trySetCapacityAsync(capacity)); }
@Test public void testExpire() throws InterruptedException { RBoundedBlockingQueue<Integer> queue = redisson.getBoundedBlockingQueue("queue1"); queue.trySetCapacity(10); queue.add(1); queue.add(2); queue.expire(Duration.ofMillis(100)); Thread.sleep(500); assertThat(queue).isEmpty(); assertThat(queue.size()).isZero(); }
public void extractTablesFromSelect(final SelectStatement selectStatement) { if (selectStatement.getCombine().isPresent()) { CombineSegment combineSegment = selectStatement.getCombine().get(); extractTablesFromSelect(combineSegment.getLeft().getSelect()); extractTablesFromSelect(combineSegment.getRight().getSelect()); } if (selectStatement.getFrom().isPresent() && !selectStatement.getCombine().isPresent()) { extractTablesFromTableSegment(selectStatement.getFrom().get()); } selectStatement.getWhere().ifPresent(optional -> extractTablesFromExpression(optional.getExpr())); if (null != selectStatement.getProjections() && !selectStatement.getCombine().isPresent()) { extractTablesFromProjections(selectStatement.getProjections()); } selectStatement.getGroupBy().ifPresent(optional -> extractTablesFromOrderByItems(optional.getGroupByItems())); selectStatement.getOrderBy().ifPresent(optional -> extractTablesFromOrderByItems(optional.getOrderByItems())); selectStatement.getHaving().ifPresent(optional -> extractTablesFromExpression(optional.getExpr())); selectStatement.getWithSegment().ifPresent(optional -> extractTablesFromCTEs(optional.getCommonTableExpressions())); selectStatement.getLock().ifPresent(this::extractTablesFromLock); }
@Test void assertExtractTablesFromSelectProjectsWithFunctionWithSubQuery() { FunctionSegment functionSegment = new FunctionSegment(0, 0, "", ""); SelectStatement subQuerySegment = mock(SelectStatement.class); when(subQuerySegment.getFrom()).thenReturn(Optional.of(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order"))))); SubquerySegment subquerySegment = new SubquerySegment(0, 0, subQuerySegment, ""); SubqueryExpressionSegment subqueryExpressionSegment = new SubqueryExpressionSegment(subquerySegment); functionSegment.getParameters().add(subqueryExpressionSegment); ExpressionProjectionSegment expressionProjectionSegment = new ExpressionProjectionSegment(0, 0, "", functionSegment); ProjectionsSegment projectionsSegment = new ProjectionsSegment(0, 0); projectionsSegment.getProjections().add(expressionProjectionSegment); SelectStatement selectStatement = mock(SelectStatement.class); when(selectStatement.getProjections()).thenReturn(projectionsSegment); tableExtractor.extractTablesFromSelect(selectStatement); assertThat(tableExtractor.getRewriteTables().size(), is(1)); }
@InvokeOnHeader(Web3jConstants.ETH_GET_BLOCK_BY_NUMBER) void ethGetBlockByNumber(Message message) throws IOException { DefaultBlockParameter atBlock = toDefaultBlockParameter(message.getHeader(Web3jConstants.AT_BLOCK, configuration::getAtBlock, String.class)); Boolean fullTransactionObjects = message.getHeader(Web3jConstants.FULL_TRANSACTION_OBJECTS, configuration::isFullTransactionObjects, Boolean.class); Request<?, EthBlock> request = web3j.ethGetBlockByNumber(atBlock, fullTransactionObjects); setRequestId(message, request); EthBlock response = request.send(); boolean hasError = checkForError(message, response); if (!hasError) { message.setBody(response.getBlock()); } }
@Test public void ethGetBlockByNumberTest() throws Exception { EthBlock response = Mockito.mock(EthBlock.class); Mockito.when(mockWeb3j.ethGetBlockByNumber(any(), anyBoolean())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getBlock()).thenReturn(Mockito.mock(EthBlock.Block.class)); Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_GET_BLOCK_BY_NUMBER); exchange.getIn().setHeader(Web3jConstants.AT_BLOCK, DefaultBlockParameterName.EARLIEST); exchange.getIn().setHeader(Web3jConstants.FULL_TRANSACTION_OBJECTS, true); template.send(exchange); EthBlock.Block body = exchange.getIn().getBody(EthBlock.Block.class); assertNotNull(body); }
public static void initializeBootstrapProperties( Properties properties, Optional<String> bootstrapServer, Optional<String> bootstrapControllers ) { if (bootstrapServer.isPresent()) { if (bootstrapControllers.isPresent()) { throw new InitializeBootstrapException("You cannot specify both " + "--bootstrap-controller and --bootstrap-server."); } properties.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer.get()); properties.remove(AdminClientConfig.BOOTSTRAP_CONTROLLERS_CONFIG); } else if (bootstrapControllers.isPresent()) { properties.remove(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG); properties.setProperty(AdminClientConfig.BOOTSTRAP_CONTROLLERS_CONFIG, bootstrapControllers.get()); } else { throw new InitializeBootstrapException("You must specify either --bootstrap-controller " + "or --bootstrap-server."); } }
@Test public void testInitializeBootstrapPropertiesWithBrokerBootstrap() { Properties props = createTestProps(); CommandLineUtils.initializeBootstrapProperties(props, Optional.of("127.0.0.2:9094"), Optional.empty()); assertEquals("127.0.0.2:9094", props.getProperty("bootstrap.servers")); assertNull(props.getProperty("bootstrap.controllers")); }
public static KafkaRoutineLoadJob fromCreateStmt(CreateRoutineLoadStmt stmt) throws UserException { // check db and table Database db = GlobalStateMgr.getCurrentState().getDb(stmt.getDBName()); if (db == null) { ErrorReport.reportDdlException(ErrorCode.ERR_BAD_DB_ERROR, stmt.getDBName()); } Table table = db.getTable(stmt.getTableName()); if (table == null) { ErrorReport.reportDdlException(ErrorCode.ERR_BAD_TABLE_ERROR, stmt.getTableName()); } long tableId = table.getId(); Locker locker = new Locker(); locker.lockTablesWithIntensiveDbLock(db, Lists.newArrayList(tableId), LockType.READ); try { unprotectedCheckMeta(db, stmt.getTableName(), stmt.getRoutineLoadDesc()); Load.checkMergeCondition(stmt.getMergeConditionStr(), (OlapTable) table, table.getFullSchema(), false); } finally { locker.unLockTablesWithIntensiveDbLock(db, Lists.newArrayList(tableId), LockType.READ); } // init kafka routine load job long id = GlobalStateMgr.getCurrentState().getNextId(); KafkaRoutineLoadJob kafkaRoutineLoadJob = new KafkaRoutineLoadJob(id, stmt.getName(), db.getId(), tableId, stmt.getKafkaBrokerList(), stmt.getKafkaTopic()); kafkaRoutineLoadJob.setOptional(stmt); kafkaRoutineLoadJob.checkCustomProperties(); return kafkaRoutineLoadJob; }
@Test public void testSerializationJson(@Mocked GlobalStateMgr globalStateMgr, @Injectable Database database, @Injectable OlapTable table) throws UserException { CreateRoutineLoadStmt createRoutineLoadStmt = initCreateRoutineLoadStmt(); Map<String, String> jobProperties = createRoutineLoadStmt.getJobProperties(); jobProperties.put("format", "json"); jobProperties.put("strip_outer_array", "true"); jobProperties.put("jsonpaths", "['$.category','$.price','$.author']"); jobProperties.put("json_root", ""); jobProperties.put("timezone", "Asia/Shanghai"); createRoutineLoadStmt.checkJobProperties(); RoutineLoadDesc routineLoadDesc = new RoutineLoadDesc(columnSeparator, null, null, null, partitionNames); Deencapsulation.setField(createRoutineLoadStmt, "routineLoadDesc", routineLoadDesc); List<Pair<Integer, Long>> partitionIdToOffset = Lists.newArrayList(); for (String s : kafkaPartitionString.split(",")) { partitionIdToOffset.add(new Pair<>(Integer.valueOf(s), 0L)); } Deencapsulation.setField(createRoutineLoadStmt, "kafkaPartitionOffsets", partitionIdToOffset); Deencapsulation.setField(createRoutineLoadStmt, "kafkaBrokerList", serverAddress); Deencapsulation.setField(createRoutineLoadStmt, "kafkaTopic", topicName); long dbId = 1L; long tableId = 2L; new Expectations() { { database.getTable(tableNameString); minTimes = 0; result = table; database.getId(); minTimes = 0; result = dbId; table.getId(); minTimes = 0; result = tableId; table.isOlapOrCloudNativeTable(); minTimes = 0; result = true; } }; new MockUp<KafkaUtil>() { @Mock public List<Integer> getAllKafkaPartitions(String brokerList, String topic, ImmutableMap<String, String> properties) throws UserException { return Lists.newArrayList(1, 2, 3); } }; String createSQL = "CREATE ROUTINE LOAD db1.job1 ON table1 " + "PROPERTIES('format' = 'json', 'strip_outer_array' = 'true') " + "FROM KAFKA('kafka_broker_list' = 'http://127.0.0.1:8080','kafka_topic' = 'topic1');"; KafkaRoutineLoadJob job = KafkaRoutineLoadJob.fromCreateStmt(createRoutineLoadStmt); job.setOrigStmt(new OriginStatement(createSQL, 0)); Assert.assertEquals("json", job.getFormat()); Assert.assertTrue(job.isStripOuterArray()); Assert.assertEquals("['$.category','$.price','$.author']", job.getJsonPaths()); Assert.assertEquals("", job.getJsonRoot()); String data = GsonUtils.GSON.toJson(job, KafkaRoutineLoadJob.class); KafkaRoutineLoadJob newJob = GsonUtils.GSON.fromJson(data, KafkaRoutineLoadJob.class); Assert.assertEquals("json", newJob.getFormat()); Assert.assertTrue(newJob.isStripOuterArray()); Assert.assertEquals("['$.category','$.price','$.author']", newJob.getJsonPaths()); Assert.assertEquals("", newJob.getJsonRoot()); }
@Override public Map<String, String> getProperties() { final List<String> properties = this.list(PROPERTIES_KEY); if(properties.isEmpty()) { return parent.getProperties(); } return properties.stream().distinct().collect(Collectors.toMap( property -> StringUtils.contains(property, '=') ? StringUtils.substringBefore(property, '=') : property, property -> StringUtils.contains(property, '=') ? substitutor.replace(StringUtils.substringAfter(property, '=')) : StringUtils.EMPTY)); }
@Test public void testEmptyProperty() { final Profile profile = new Profile(new TestProtocol(), new Deserializer<String>() { @Override public String stringForKey(final String key) { return null; } @Override public String objectForKey(final String key) { return null; } @Override public <L> List<L> listForKey(final String key) { return (List<L>) Collections.singletonList("empty.prop="); } @Override public Map<String, String> mapForKey(final String key) { return null; } @Override public boolean booleanForKey(final String key) { return false; } @Override public List<String> keys() { return null; } }); assertTrue(profile.getProperties().containsKey("empty.prop")); assertEquals(StringUtils.EMPTY, profile.getProperties().get("empty.prop")); }
public static Number getExactlyNumber(final String value, final int radix) { try { return getBigInteger(value, radix); } catch (final NumberFormatException ex) { return new BigDecimal(value); } }
@Test void assertGetExactlyNumberForInteger() { assertThat(SQLUtils.getExactlyNumber("100000", 10), is(100000)); assertThat(SQLUtils.getExactlyNumber("100000", 16), is(1048576)); assertThat(SQLUtils.getExactlyNumber(String.valueOf(Integer.MIN_VALUE), 10), is(Integer.MIN_VALUE)); assertThat(SQLUtils.getExactlyNumber(String.valueOf(Integer.MAX_VALUE), 10), is(Integer.MAX_VALUE)); }
public static Type[] getReturnTypes(Invocation invocation) { try { if (invocation != null && invocation.getInvoker() != null && invocation.getInvoker().getUrl() != null && invocation.getInvoker().getInterface() != GenericService.class && !invocation.getMethodName().startsWith("$")) { Type[] returnTypes = null; if (invocation instanceof RpcInvocation) { returnTypes = ((RpcInvocation) invocation).getReturnTypes(); if (returnTypes != null) { return returnTypes; } } String service = invocation.getInvoker().getUrl().getServiceInterface(); if (StringUtils.isNotEmpty(service)) { Method method = getMethodByService(invocation, service); if (method != null) { returnTypes = ReflectUtils.getReturnTypes(method); } } if (returnTypes != null) { return returnTypes; } } } catch (Throwable t) { logger.warn(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", t.getMessage(), t); } return null; }
@Test void testGetReturnTypesWithoutCache() throws Exception { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker( URL.valueOf( "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); RpcInvocation inv = new RpcInvocation( "testReturnType", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv.setReturnTypes(null); Type[] types = RpcUtils.getReturnTypes(inv); Assertions.assertNotNull(types); Assertions.assertEquals(2, types.length); Assertions.assertEquals(String.class, types[0]); Assertions.assertEquals(String.class, types[1]); RpcInvocation inv1 = new RpcInvocation( "testReturnType1", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv1.setReturnTypes(null); java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1); Assertions.assertNotNull(types1); Assertions.assertEquals(2, types1.length); Assertions.assertEquals(List.class, types1[0]); Assertions.assertEquals( demoServiceClass.getMethod("testReturnType1", String.class).getGenericReturnType(), types1[1]); RpcInvocation inv2 = new RpcInvocation( "testReturnType2", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv2.setReturnTypes(null); java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2); Assertions.assertNotNull(types2); Assertions.assertEquals(2, types2.length); Assertions.assertEquals(String.class, types2[0]); Assertions.assertEquals(String.class, types2[1]); RpcInvocation inv3 = new RpcInvocation( "testReturnType3", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv3.setReturnTypes(null); java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3); Assertions.assertNotNull(types3); Assertions.assertEquals(2, types3.length); Assertions.assertEquals(List.class, types3[0]); java.lang.reflect.Type genericReturnType3 = demoServiceClass.getMethod("testReturnType3", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType3).getActualTypeArguments()[0], types3[1]); RpcInvocation inv4 = new RpcInvocation( "testReturnType4", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv4.setReturnTypes(null); java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4); Assertions.assertNotNull(types4); Assertions.assertEquals(2, types4.length); Assertions.assertNull(types4[0]); Assertions.assertNull(types4[1]); RpcInvocation inv5 = new RpcInvocation( "testReturnType5", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null); inv5.setReturnTypes(null); java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5); Assertions.assertNotNull(types5); Assertions.assertEquals(2, types5.length); Assertions.assertEquals(Map.class, types5[0]); java.lang.reflect.Type genericReturnType5 = demoServiceClass.getMethod("testReturnType5", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType5).getActualTypeArguments()[0], types5[1]); }
public static String parsePath(String uri, Map<String, String> patterns) { if (uri == null) { return null; } else if (StringUtils.isBlank(uri)) { return String.valueOf(SLASH); } CharacterIterator ci = new StringCharacterIterator(uri); StringBuilder pathBuffer = new StringBuilder(); char c = ci.first(); if (c == CharacterIterator.DONE) { return String.valueOf(SLASH); } do { if (c == OPEN) { String regexBuffer = cutParameter(ci, patterns); if (regexBuffer == null) { LOGGER.warn("Operation path \"{}\" contains syntax error.", uri); return null; } pathBuffer.append(regexBuffer); } else { int length = pathBuffer.length(); if (!(c == SLASH && (length != 0 && pathBuffer.charAt(length - 1) == SLASH))) { pathBuffer.append(c); } } } while ((c = ci.next()) != CharacterIterator.DONE); return pathBuffer.toString(); }
@Test(description = "parse path with param without regex") public void parsePathWithoutRegex() { final Map<String, String> regexMap = new HashMap<String, String>(); final String path = PathUtils.parsePath("/api/{name}", regexMap); assertEquals(path, "/api/{name}"); assertEquals(regexMap.size(), 0); }
public static LookupResult multi(final CharSequence singleValue, final Map<Object, Object> multiValue) { return withoutTTL().single(singleValue).multiValue(multiValue).build(); }
@Test public void serializeMultiNumber() { final LookupResult lookupResult = LookupResult.multi(42, MULTI_VALUE); final JsonNode node = objectMapper.convertValue(lookupResult, JsonNode.class); assertThat(node.isNull()).isFalse(); assertThat(node.path("single_value").asInt()).isEqualTo(42); assertThat(node.path("multi_value").path("int").asInt()).isEqualTo(42); assertThat(node.path("multi_value").path("bool").asBoolean()).isEqualTo(true); assertThat(node.path("multi_value").path("string").asText()).isEqualTo("Foobar"); assertThat(node.path("ttl").asLong()).isEqualTo(Long.MAX_VALUE); }
@Override public void preflight(final Path workdir, final String filename) throws BackgroundException { if(workdir.isRoot() || new DeepboxPathContainerService(session).isDeepbox(workdir) || new DeepboxPathContainerService(session).isBox(workdir)) { throw new AccessDeniedException(MessageFormat.format(LocaleFactory.localizedString("Cannot create {0}", "Error"), filename)).withFile(workdir); } final Acl acl = workdir.attributes().getAcl(); if(Acl.EMPTY == acl) { // Missing initialization log.warn(String.format("Unknown ACLs on %s", workdir)); return; } if(!acl.get(new Acl.CanonicalUser()).contains(CANADDCHILDREN)) { if(log.isWarnEnabled()) { log.warn(String.format("ACL %s for %s does not include %s", acl, workdir, CANADDCHILDREN)); } throw new AccessDeniedException(MessageFormat.format(LocaleFactory.localizedString("Cannot create {0}", "Error"), filename)).withFile(workdir); } }
@Test public void testNoAddChildrenInbox() throws Exception { final DeepboxIdProvider nodeid = new DeepboxIdProvider(session); final Path folder = new Path("/ORG 1 - DeepBox Desktop App/ORG1:Box1/Inbox/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final PathAttributes attributes = new DeepboxAttributesFinderFeature(session, nodeid).find(folder); assertFalse(new BoxRestControllerApi(session.getClient()).getBox(ORG1, ORG1_BOX1).getBoxPolicy().isCanAddQueue()); assertFalse(attributes.getAcl().get(new Acl.CanonicalUser()).contains(CANADDCHILDREN)); assertThrows(AccessDeniedException.class, () -> new DeepboxTouchFeature(session, nodeid).preflight(folder.withAttributes(attributes), new AlphanumericRandomStringService().random())); assertThrows(AccessDeniedException.class, () -> new DeepboxDirectoryFeature(session, nodeid).preflight(folder.withAttributes(attributes), new AlphanumericRandomStringService().random())); }
@Override public boolean supportsCatalogsInProcedureCalls() { return false; }
@Test void assertSupportsCatalogsInProcedureCalls() { assertFalse(metaData.supportsCatalogsInProcedureCalls()); }
public static Collection<DataNode> buildDataNode(final DataNode dataNode, final Map<String, Collection<String>> dataSources) { if (!dataSources.containsKey(dataNode.getDataSourceName())) { return Collections.singletonList(dataNode); } Collection<DataNode> result = new LinkedList<>(); for (String each : dataSources.get(dataNode.getDataSourceName())) { result.add(new DataNode(each, dataNode.getTableName())); } return result; }
@Test void assertBuildDataNodeWithSameDataSource() { DataNode dataNode = new DataNode("readwrite_ds.t_order"); Collection<DataNode> dataNodes = DataNodeUtils.buildDataNode(dataNode, Collections.singletonMap("readwrite_ds", Arrays.asList("ds_0", "shadow_ds_0"))); assertThat(dataNodes.size(), is(2)); Iterator<DataNode> iterator = dataNodes.iterator(); assertThat(iterator.next().getDataSourceName(), is("ds_0")); assertThat(iterator.next().getDataSourceName(), is("shadow_ds_0")); }
public static String getOwnerFromGrpcClient(AlluxioConfiguration conf) { try { User user = AuthenticatedClientUser.get(conf); if (user == null) { return ""; } return user.getName(); } catch (IOException e) { return ""; } }
@Test public void getOwnerFromGrpcClient() throws Exception { // When security is not enabled, user and group are not set mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.NOSASL); assertEquals("", SecurityUtils.getOwnerFromGrpcClient(mConfiguration)); mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE); mConfiguration.set(PropertyKey.SECURITY_GROUP_MAPPING_CLASS, IdentityUserGroupsMapping.class.getName()); AuthenticatedClientUser.set("test_client_user"); assertEquals("test_client_user", SecurityUtils.getOwnerFromGrpcClient(mConfiguration)); }
public void validate(AlmSettingDto almSettingDto) { String bitbucketUrl = almSettingDto.getUrl(); String bitbucketToken = almSettingDto.getDecryptedPersonalAccessToken(encryption); if (bitbucketUrl == null || bitbucketToken == null) { throw new IllegalArgumentException("Your global Bitbucket Server configuration is incomplete."); } bitbucketServerRestClient.validateUrl(bitbucketUrl); bitbucketServerRestClient.validateToken(bitbucketUrl, bitbucketToken); bitbucketServerRestClient.validateReadPermission(bitbucketUrl, bitbucketToken); }
@Test public void validate_failure_on_incomplete_configuration() { AlmSettingDto almSettingDto = createNewBitbucketDto(null, "abc"); assertThatThrownBy(() -> underTest.validate(almSettingDto)) .isInstanceOf(IllegalArgumentException.class); }
static <RequestT, @Nullable ResponseT> PTransform<PCollection<RequestT>, Result<KV<RequestT, @Nullable ResponseT>>> readUsingRedis( RedisClient client, Coder<RequestT> requestTCoder, Coder<@Nullable ResponseT> responseTCoder) throws NonDeterministicException { return read( new UsingRedis<>(requestTCoder, responseTCoder, client).read(), requestTCoder, responseTCoder); }
@Test public void givenNonDeterministicCoder_readUsingRedis_throwsError() throws Coder.NonDeterministicException { URI uri = URI.create("redis://localhost:6379"); assertThrows( NonDeterministicException.class, () -> Cache.readUsingRedis( new RedisClient(uri), CallTest.NON_DETERMINISTIC_REQUEST_CODER, CallTest.DETERMINISTIC_RESPONSE_CODER)); assertThrows( NonDeterministicException.class, () -> Cache.readUsingRedis( new RedisClient(uri), CallTest.DETERMINISTIC_REQUEST_CODER, CallTest.NON_DETERMINISTIC_RESPONSE_CODER)); Cache.readUsingRedis( new RedisClient(uri), CallTest.DETERMINISTIC_REQUEST_CODER, CallTest.DETERMINISTIC_RESPONSE_CODER); }
@Override @SuppressWarnings("DuplicatedCode") public Integer cleanErrorLog(Integer exceedDay, Integer deleteLimit) { int count = 0; LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay); // 循环删除,直到没有满足条件的数据 for (int i = 0; i < Short.MAX_VALUE; i++) { int deleteCount = apiErrorLogMapper.deleteByCreateTimeLt(expireDate, deleteLimit); count += deleteCount; // 达到删除预期条数,说明到底了 if (deleteCount < deleteLimit) { break; } } return count; }
@Test public void testCleanJobLog() { // mock 数据 ApiErrorLogDO log01 = randomPojo(ApiErrorLogDO.class, o -> o.setCreateTime(addTime(Duration.ofDays(-3)))); apiErrorLogMapper.insert(log01); ApiErrorLogDO log02 = randomPojo(ApiErrorLogDO.class, o -> o.setCreateTime(addTime(Duration.ofDays(-1)))); apiErrorLogMapper.insert(log02); // 准备参数 Integer exceedDay = 2; Integer deleteLimit = 1; // 调用 Integer count = apiErrorLogService.cleanErrorLog(exceedDay, deleteLimit); // 断言 assertEquals(1, count); List<ApiErrorLogDO> logs = apiErrorLogMapper.selectList(); assertEquals(1, logs.size()); assertEquals(log02, logs.get(0)); }
public ClassificationPoliciesConfig shareClassificationsPolicies() throws BackgroundException { if(classificationPolicies.get() == null) { final Matcher matcher = Pattern.compile(SDSSession.VERSION_REGEX).matcher(this.softwareVersion().getRestApiVersion()); if(matcher.matches()) { if(new Version(matcher.group(1)).compareTo(new Version("4.30")) >= 0) { try { classificationPolicies.set(new ConfigApi(client).requestClassificationPoliciesConfigInfo(StringUtils.EMPTY)); } catch(ApiException e) { // Precondition: Right "Config Read" required. log.warn(String.format("Failure %s reading configuration", new SDSExceptionMappingService(nodeid).map(e))); throw new SDSExceptionMappingService(nodeid).map(e); } } } } return classificationPolicies.get(); }
@Test public void testClassificationConfiguration() throws Exception { final ClassificationPoliciesConfig policies = session.shareClassificationsPolicies(); assertNotNull(policies); assertNotNull(policies.getShareClassificationPolicies()); assertNotNull(policies.getShareClassificationPolicies().getClassificationRequiresSharePassword()); assertEquals(0, policies.getShareClassificationPolicies().getClassificationRequiresSharePassword().getValue().intValue()); }
public static float parseBytesIntToFloat(List data) { return parseBytesIntToFloat(data, 0); }
@Test public void parseBytesIntToFloat() { byte[] intValByte = {0x00, 0x00, 0x00, 0x0A}; Float valueExpected = 10.0f; Float valueActual = TbUtils.parseBytesIntToFloat(intValByte, 3, 1, true); Assertions.assertEquals(valueExpected, valueActual); valueActual = TbUtils.parseBytesIntToFloat(intValByte, 3, 1, false); Assertions.assertEquals(valueExpected, valueActual); valueActual = TbUtils.parseBytesIntToFloat(intValByte, 2, 2, true); Assertions.assertEquals(valueExpected, valueActual); valueExpected = 2560.0f; valueActual = TbUtils.parseBytesIntToFloat(intValByte, 2, 2, false); Assertions.assertEquals(valueExpected, valueActual); valueExpected = 10.0f; valueActual = TbUtils.parseBytesIntToFloat(intValByte, 0, 4, true); Assertions.assertEquals(valueExpected, valueActual); valueExpected = 1.6777216E8f; valueActual = TbUtils.parseBytesIntToFloat(intValByte, 0, 4, false); Assertions.assertEquals(valueExpected, valueActual); String dataAT101 = "0x01756403671B01048836BF7701F000090722050000"; List<Byte> byteAT101 = TbUtils.hexToBytes(ctx, dataAT101); float latitudeExpected = 24.62495f; int offset = 9; valueActual = TbUtils.parseBytesIntToFloat(byteAT101, offset, 4, false); Assertions.assertEquals(latitudeExpected, valueActual / 1000000); float longitudeExpected = 118.030576f; valueActual = TbUtils.parseBytesIntToFloat(byteAT101, offset + 4, 4, false); Assertions.assertEquals(longitudeExpected, valueActual / 1000000); valueExpected = 9.185175E8f; valueActual = TbUtils.parseBytesIntToFloat(byteAT101, offset); Assertions.assertEquals(valueExpected, valueActual); // 0x36BF valueExpected = 14015.0f; valueActual = TbUtils.parseBytesIntToFloat(byteAT101, offset, 2); Assertions.assertEquals(valueExpected, valueActual); // 0xBF36 valueExpected = 48950.0f; valueActual = TbUtils.parseBytesIntToFloat(byteAT101, offset, 2, false); Assertions.assertEquals(valueExpected, valueActual); valueExpected = 0.0f; valueActual = TbUtils.parseBytesIntToFloat(byteAT101, byteAT101.size()); Assertions.assertEquals(valueExpected, valueActual); try { TbUtils.parseBytesIntToFloat(byteAT101, byteAT101.size() + 1); Assertions.fail("Should throw NumberFormatException"); } catch (RuntimeException e) { Assertions.assertTrue(e.getMessage().contains("is out of bounds for array with length:")); } }
@Override public void forget(final Xid xid) throws XAException { try { delegate.forget(xid); } catch (final XAException ex) { throw mapXAException(ex); } }
@Test void assertForget() throws XAException { singleXAResource.forget(xid); verify(xaResource).forget(xid); }
public static <K, V> AsMap<K, V> asMap() { return new AsMap<>(false); }
@Test @Category({ValidatesRunner.class}) public void testWindowedMapSideInputWithNonDeterministicKeyCoder() { final PCollectionView<Map<String, Integer>> view = pipeline .apply( "CreateSideInput", Create.timestamped( TimestampedValue.of(KV.of("a", 1), new Instant(1)), TimestampedValue.of(KV.of("b", 2), new Instant(4)), TimestampedValue.of(KV.of("b", 3), new Instant(18))) .withCoder(KvCoder.of(new NonDeterministicStringCoder(), VarIntCoder.of()))) .apply("SideWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) .apply(View.asMap()); PCollection<KV<String, Integer>> output = pipeline .apply( "CreateMainInput", Create.timestamped( TimestampedValue.of("apple", new Instant(5)), TimestampedValue.of("banana", new Instant(4)), TimestampedValue.of("blackberry", new Instant(16)))) .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) .apply( "OutputSideInputs", ParDo.of( new DoFn<String, KV<String, Integer>>() { @ProcessElement public void processElement(ProcessContext c) { c.output( KV.of( c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); } }) .withSideInputs(view)); PAssert.that(output) .containsInAnyOrder(KV.of("apple", 1), KV.of("banana", 2), KV.of("blackberry", 3)); pipeline.run(); }
public static String normalizeURL(String url) { if (url == null) { return null; } ParsedUrl parsedUrl = ParsedUrl.parseUrl(url); Canonicalizer.AGGRESSIVE.canonicalize(parsedUrl); String normalized = parsedUrl.toString(); if (normalized == null) { normalized = url; } // convert to lower case, the url probably won't work in some cases // after that but we don't care we just want to compare urls to avoid // duplicates normalized = normalized.toLowerCase(); // store all urls as http if (normalized.startsWith("https")) { normalized = "http" + normalized.substring(5); } // remove the www. part normalized = normalized.replace("//www.", "//"); // feedproxy redirects to feedburner normalized = normalized.replace("feedproxy.google.com", "feeds.feedburner.com"); // feedburner feeds have a special treatment if (normalized.split(ESCAPED_QUESTION_MARK)[0].contains("feedburner.com")) { normalized = normalized.replace("feeds2.feedburner.com", "feeds.feedburner.com"); normalized = normalized.split(ESCAPED_QUESTION_MARK)[0]; normalized = StringUtils.removeEnd(normalized, "/"); } return normalized; }
@Test void testNormalization() { String urla1 = "http://example.com/hello?a=1&b=2"; String urla2 = "http://www.example.com/hello?a=1&b=2"; String urla3 = "http://EXAmPLe.com/HELLo?a=1&b=2"; String urla4 = "http://example.com/hello?b=2&a=1"; String urla5 = "https://example.com/hello?a=1&b=2"; String urlb1 = "http://ftr.fivefilters.org/makefulltextfeed.php?url=http%3A%2F%2Ffeeds.howtogeek.com%2FHowToGeek&max=10&summary=1"; String urlb2 = "http://ftr.fivefilters.org/makefulltextfeed.php?url=http://feeds.howtogeek.com/HowToGeek&max=10&summary=1"; String urlc1 = "http://feeds.feedburner.com/Frandroid"; String urlc2 = "http://feeds2.feedburner.com/frandroid"; String urlc3 = "http://feedproxy.google.com/frandroid"; String urlc4 = "http://feeds.feedburner.com/Frandroid/"; String urlc5 = "http://feeds.feedburner.com/Frandroid?format=rss"; String urld1 = "http://fivefilters.org/content-only/makefulltextfeed.php?url=http://feeds.feedburner.com/Frandroid"; String urld2 = "http://fivefilters.org/content-only/makefulltextfeed.php?url=http://feeds2.feedburner.com/Frandroid"; Assertions.assertEquals(FeedUtils.normalizeURL(urla1), FeedUtils.normalizeURL(urla2)); Assertions.assertEquals(FeedUtils.normalizeURL(urla1), FeedUtils.normalizeURL(urla3)); Assertions.assertEquals(FeedUtils.normalizeURL(urla1), FeedUtils.normalizeURL(urla4)); Assertions.assertEquals(FeedUtils.normalizeURL(urla1), FeedUtils.normalizeURL(urla5)); Assertions.assertEquals(FeedUtils.normalizeURL(urlb1), FeedUtils.normalizeURL(urlb2)); Assertions.assertEquals(FeedUtils.normalizeURL(urlc1), FeedUtils.normalizeURL(urlc2)); Assertions.assertEquals(FeedUtils.normalizeURL(urlc1), FeedUtils.normalizeURL(urlc3)); Assertions.assertEquals(FeedUtils.normalizeURL(urlc1), FeedUtils.normalizeURL(urlc4)); Assertions.assertEquals(FeedUtils.normalizeURL(urlc1), FeedUtils.normalizeURL(urlc5)); Assertions.assertNotEquals(FeedUtils.normalizeURL(urld1), FeedUtils.normalizeURL(urld2)); }
public void callEnableDataCollect() { call("enableDataCollect", null); }
@Test public void callEnableDataCollect() { }
@Override public Stream<MappingField> resolveAndValidateFields( boolean isKey, List<MappingField> userFields, Map<String, String> options, InternalSerializationService serializationService ) { Map<QueryPath, MappingField> fieldsByPath = extractFields(userFields, isKey); Class<?> typeClass = getMetadata(fieldsByPath) .<Class<?>>map(KvMetadataJavaResolver::loadClass) .orElseGet(() -> loadClass(options, isKey)); QueryDataType type = QueryDataTypeUtils.resolveTypeForClass(typeClass); if (type.getTypeFamily() != QueryDataTypeFamily.OBJECT || type.isCustomType()) { return userFields.isEmpty() ? resolvePrimitiveField(isKey, type) : resolveAndValidatePrimitiveField(isKey, fieldsByPath, type); } else { return userFields.isEmpty() ? resolveObjectFields(isKey, typeClass) : resolveAndValidateObjectFields(isKey, fieldsByPath, typeClass); } }
@Test @Parameters({ "true, __key", "false, this" }) public void when_userDeclaresPrimitiveAdditionalField_then_throws(boolean key, String prefix) { Map<String, String> options = Map.of( (key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORMAT, (key ? OPTION_KEY_CLASS : OPTION_VALUE_CLASS), int.class.getName() ); assertThatThrownBy(() -> INSTANCE.resolveAndValidateFields( key, singletonList(field("field", QueryDataType.INT, prefix + ".field")), options, null )).isInstanceOf(QueryException.class) .hasMessage("The field '" + prefix + "' is of type INTEGER, you can't map '" + prefix + ".field' too"); }
@Override public String retrieveIPfilePath(String id, String dstDir, Map<Path, List<String>> localizedResources) { // Assume .aocx IP file is distributed by DS to local dir String ipFilePath = null; LOG.info("Got environment: " + id + ", search IP file in localized resources"); if (null == id || id.isEmpty()) { LOG.warn("IP_ID environment is empty, skip downloading"); return null; } if (localizedResources != null) { Optional<Path> aocxPath = localizedResources .keySet() .stream() .filter(path -> matchesIpid(path, id)) .findFirst(); if (aocxPath.isPresent()) { ipFilePath = aocxPath.get().toString(); LOG.info("Found: {}", ipFilePath); } else { LOG.warn("Requested IP file not found"); } } else { LOG.warn("Localized resource is null!"); } return ipFilePath; }
@Test public void testLocalizedIPfileNotFound() { Map<Path, List<String>> resources = createResources(); String path = plugin.retrieveIPfilePath("dummy", "workDir", resources); assertNull("Retrieved IP file path", path); }
public static <T> T waitWithLogging( Logger log, String prefix, String action, CompletableFuture<T> future, Deadline deadline, Time time ) throws Throwable { log.info("{}Waiting for {}", prefix, action); try { T result = time.waitForFuture(future, deadline.nanoseconds()); log.info("{}Finished waiting for {}", prefix, action); return result; } catch (TimeoutException t) { log.error("{}Timed out while waiting for {}", prefix, action, t); TimeoutException timeout = new TimeoutException("Timed out while waiting for " + action); timeout.setStackTrace(t.getStackTrace()); throw timeout; } catch (Throwable t) { if (t instanceof ExecutionException) { ExecutionException executionException = (ExecutionException) t; t = executionException.getCause(); } log.error("{}Received a fatal error while waiting for {}", prefix, action, t); throw new RuntimeException("Received a fatal error while waiting for " + action, t); } }
@Test public void testWaitWithLoggingError() throws Throwable { ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1); CompletableFuture<Integer> future = new CompletableFuture<>(); executorService.schedule(() -> { future.completeExceptionally(new IllegalArgumentException("uh oh")); }, 1, TimeUnit.NANOSECONDS); assertEquals("Received a fatal error while waiting for the future to be completed", assertThrows(RuntimeException.class, () -> { FutureUtils.waitWithLogging(log, "[FutureUtilsTest] ", "the future to be completed", future, Deadline.fromDelay(Time.SYSTEM, 30, TimeUnit.SECONDS), Time.SYSTEM); }).getMessage()); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); }
public static SqlDecimal of(final int precision, final int scale) { return new SqlDecimal(precision, scale); }
@Test(expected = SchemaException.class) public void shouldThrowOnInvalidPrecision() { SqlDecimal.of(0, 2); }
public static QueryServiceResponse buildSuccessResponse(ServiceInfo serviceInfo) { return new QueryServiceResponse(serviceInfo); }
@Test void testSerializeSuccessResponse() throws JsonProcessingException { QueryServiceResponse response = QueryServiceResponse.buildSuccessResponse(new ServiceInfo()); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"serviceInfo\":{")); assertTrue(json.contains("\"resultCode\":200")); assertTrue(json.contains("\"errorCode\":0")); assertTrue(json.contains("\"success\":true")); }
public static PointList simplify(ResponsePath responsePath, RamerDouglasPeucker ramerDouglasPeucker, boolean enableInstructions) { final PointList pointList = responsePath.getPoints(); List<Partition> partitions = new ArrayList<>(); // make sure all waypoints are retained in the simplified point list // we copy the waypoint indices into temporary intervals where they will be mutated by the simplification, // afterwards we need to update the way point indices accordingly. List<Interval> intervals = new ArrayList<>(); for (int i = 0; i < responsePath.getWaypointIndices().size() - 1; i++) intervals.add(new Interval(responsePath.getWaypointIndices().get(i), responsePath.getWaypointIndices().get(i + 1))); partitions.add(new Partition() { @Override public int size() { return intervals.size(); } @Override public int getIntervalLength(int index) { return intervals.get(index).end - intervals.get(index).start; } @Override public void setInterval(int index, int start, int end) { intervals.get(index).start = start; intervals.get(index).end = end; } }); // todo: maybe this code can be simplified if path details and instructions would be merged, see #1121 if (enableInstructions) { final InstructionList instructions = responsePath.getInstructions(); partitions.add(new Partition() { @Override public int size() { return instructions.size(); } @Override public int getIntervalLength(int index) { return instructions.get(index).getLength(); } @Override public void setInterval(int index, int start, int end) { Instruction instruction = instructions.get(index); if (instruction instanceof ViaInstruction || instruction instanceof FinishInstruction) { if (start != end) { throw new IllegalStateException("via- and finish-instructions are expected to have zero length"); } // have to make sure that via instructions and finish instructions contain a single point // even though their 'instruction length' is zero. end++; } instruction.setPoints(pointList.shallowCopy(start, end, false)); } }); } for (final Map.Entry<String, List<PathDetail>> entry : responsePath.getPathDetails().entrySet()) { // If the pointList only contains one point, PathDetails have to be empty because 1 point => 0 edges final List<PathDetail> detail = entry.getValue(); if (detail.isEmpty() && pointList.size() > 1) throw new IllegalStateException("PathDetails " + entry.getKey() + " must not be empty"); partitions.add(new Partition() { @Override public int size() { return detail.size(); } @Override public int getIntervalLength(int index) { return detail.get(index).getLength(); } @Override public void setInterval(int index, int start, int end) { PathDetail pd = detail.get(index); pd.setFirst(start); pd.setLast(end); } }); } simplify(responsePath.getPoints(), partitions, ramerDouglasPeucker); List<Integer> simplifiedWaypointIndices = new ArrayList<>(); simplifiedWaypointIndices.add(intervals.get(0).start); for (Interval interval : intervals) simplifiedWaypointIndices.add(interval.end); responsePath.setWaypointIndices(simplifiedWaypointIndices); assertConsistencyOfPathDetails(responsePath.getPathDetails()); if (enableInstructions) assertConsistencyOfInstructions(responsePath.getInstructions(), responsePath.getPoints().size()); return pointList; }
@Test public void testScenario() { DecimalEncodedValue speedEnc = new DecimalEncodedValueImpl("speed", 5, 5, false); EncodingManager carManager = EncodingManager.start().add(speedEnc) .add(Roundabout.create()).add(RoadClass.create()).add(RoadClassLink.create()).add(MaxSpeed.create()).build(); BaseGraph g = new BaseGraph.Builder(carManager).create(); // 0-1-2 // | | | // 3-4-5 9-10 // | | | | // 6-7-8--* NodeAccess na = g.getNodeAccess(); na.setNode(0, 1.2, 1.0); na.setNode(1, 1.2, 1.1); na.setNode(2, 1.2, 1.2); na.setNode(3, 1.1, 1.0); na.setNode(4, 1.1, 1.1); na.setNode(5, 1.1, 1.2); na.setNode(9, 1.1, 1.3); na.setNode(10, 1.1, 1.4); na.setNode(6, 1.0, 1.0); na.setNode(7, 1.0, 1.1); na.setNode(8, 1.0, 1.2); g.edge(0, 1).set(speedEnc, 9).setDistance(10000).setKeyValues(Map.of(STREET_NAME, new KValue("0-1"))); g.edge(1, 2).set(speedEnc, 9).setDistance(11000).setKeyValues(Map.of(STREET_NAME, new KValue("1-2"))); g.edge(0, 3).set(speedEnc, 18).setDistance(11000); g.edge(1, 4).set(speedEnc, 18).setDistance(10000).setKeyValues(Map.of(STREET_NAME, new KValue("1-4"))); g.edge(2, 5).set(speedEnc, 18).setDistance(11000).setKeyValues(Map.of(STREET_NAME, new KValue("5-2"))); g.edge(3, 6).set(speedEnc, 27).setDistance(11000).setKeyValues(Map.of(STREET_NAME, new KValue("3-6"))); g.edge(4, 7).set(speedEnc, 27).setDistance(10000).setKeyValues(Map.of(STREET_NAME, new KValue("4-7"))); g.edge(5, 8).set(speedEnc, 27).setDistance(10000).setKeyValues(Map.of(STREET_NAME, new KValue("5-8"))); g.edge(6, 7).setDistance(11000).set(speedEnc, 36).setKeyValues(Map.of(STREET_NAME, new KValue("6-7"))); EdgeIteratorState tmpEdge = g.edge(7, 8).set(speedEnc, 36).setDistance(10000); PointList list = new PointList(); list.add(1.0, 1.15); list.add(1.0, 1.16); tmpEdge.setWayGeometry(list); tmpEdge.setKeyValues(Map.of(STREET_NAME, new KValue("7-8"))); // missing edge name g.edge(9, 10).set(speedEnc, 45).setDistance(10000); tmpEdge = g.edge(8, 9).set(speedEnc, 45).setDistance(20000); list.clear(); list.add(1.0, 1.3); list.add(1.0, 1.3001); list.add(1.0, 1.3002); list.add(1.0, 1.3003); tmpEdge.setKeyValues(Map.of(STREET_NAME, new KValue("8-9"))); tmpEdge.setWayGeometry(list); // Path is: [0 0-1, 3 1-4, 6 4-7, 9 7-8, 11 8-9, 10 9-10] Weighting weighting = new SpeedWeighting(speedEnc); Path p = new Dijkstra(g, weighting, tMode).calcPath(0, 10); InstructionList wayList = InstructionsFromEdges.calcInstructions(p, g, weighting, carManager, usTR); Map<String, List<PathDetail>> details = PathDetailsFromEdges.calcDetails(p, carManager, weighting, List.of(AVERAGE_SPEED), new PathDetailsBuilderFactory(), 0, g); PointList points = p.calcPoints(); PointList waypoints = new PointList(2, g.getNodeAccess().is3D()); waypoints.add(g.getNodeAccess(), 0); waypoints.add(g.getNodeAccess(), 10); List<Integer> waypointIndices = Arrays.asList(0, points.size() - 1); ResponsePath responsePath = new ResponsePath(); responsePath.setInstructions(wayList); responsePath.addPathDetails(details); responsePath.setPoints(points); responsePath.setWaypoints(waypoints); responsePath.setWaypointIndices(waypointIndices); int numberOfPoints = points.size(); RamerDouglasPeucker ramerDouglasPeucker = new RamerDouglasPeucker(); // Do not simplify anything ramerDouglasPeucker.setMaxDistance(0); PathSimplification.simplify(responsePath, ramerDouglasPeucker, true); assertEquals(numberOfPoints, responsePath.getPoints().size()); responsePath = new ResponsePath(); responsePath.setInstructions(wayList); responsePath.addPathDetails(details); responsePath.setPoints(p.calcPoints()); responsePath.setWaypoints(waypoints); responsePath.setWaypointIndices(waypointIndices); ramerDouglasPeucker.setMaxDistance(100000000); PathSimplification.simplify(responsePath, ramerDouglasPeucker, true); assertTrue(numberOfPoints > responsePath.getPoints().size()); }
public static String getGenericScenarioExceptionMessage(String exceptionMessage) { return String.format("Failure reason: %s", exceptionMessage); }
@Test public void getGenericScenarioExceptionMessage_simpleCase() { assertThat(getGenericScenarioExceptionMessage("An exception message")).isEqualTo("Failure reason: An exception message"); }
@Override public Long createLevel(MemberLevelCreateReqVO createReqVO) { // 校验配置是否有效 validateConfigValid(null, createReqVO.getName(), createReqVO.getLevel(), createReqVO.getExperience()); // 插入 MemberLevelDO level = MemberLevelConvert.INSTANCE.convert(createReqVO); memberLevelMapper.insert(level); // 返回 return level.getId(); }
@Test public void testCreateLevel_success() { // 准备参数 MemberLevelCreateReqVO reqVO = randomPojo(MemberLevelCreateReqVO.class, o -> { o.setDiscountPercent(randomInt()); o.setIcon(randomURL()); o.setBackgroundUrl(randomURL()); o.setStatus(randomCommonStatus()); }); // 调用 Long levelId = levelService.createLevel(reqVO); // 断言 assertNotNull(levelId); // 校验记录的属性是否正确 MemberLevelDO level = memberlevelMapper.selectById(levelId); assertPojoEquals(reqVO, level); }
@Override public List<Document> get() { try (var input = markdownResource.getInputStream()) { Node node = parser.parseReader(new InputStreamReader(input)); DocumentVisitor documentVisitor = new DocumentVisitor(config); node.accept(documentVisitor); return documentVisitor.getDocuments(); } catch (IOException e) { throw new RuntimeException(e); } }
@Test void testOnlyHeadersWithParagraphs() { MarkdownDocumentReader reader = new MarkdownDocumentReader("classpath:/only-headers.md"); List<Document> documents = reader.get(); assertThat(documents).hasSize(4) .extracting(Document::getMetadata, Document::getContent) .containsOnly(tuple(Map.of("category", "header_1", "title", "Header 1a"), "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur diam eros, laoreet sit amet cursus vitae, varius sed nisi. Cras sit amet quam quis velit commodo porta consectetur id nisi. Phasellus tincidunt pulvinar augue."), tuple(Map.of("category", "header_1", "title", "Header 1b"), "Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Etiam lobortis risus libero, sed sollicitudin risus cursus in. Morbi enim metus, ornare vel lacinia eget, venenatis vel nibh."), tuple(Map.of("category", "header_2", "title", "Header 2b"), "Proin vel laoreet leo, sed luctus augue. Sed et ligula commodo, commodo lacus at, consequat turpis. Maecenas eget sapien odio. Maecenas urna lectus, pellentesque in accumsan aliquam, congue eu libero."), tuple(Map.of("category", "header_2", "title", "Header 2c"), "Ut rhoncus nec justo a porttitor. Pellentesque auctor pharetra eros, viverra sodales lorem aliquet id. Curabitur semper nisi vel sem interdum suscipit.")); }
static Long replicationThrottle(CruiseControlRequestContext requestContext, KafkaCruiseControlConfig config) { Long value = getLongParam(requestContext, REPLICATION_THROTTLE_PARAM, config.getLong(ExecutorConfig.DEFAULT_REPLICATION_THROTTLE_CONFIG)); if (value != null && value < 0) { throw new UserRequestException(String.format("Requested rebalance throttle must be non-negative (Requested: %s).", value)); } return value; }
@Test public void testParseReplicationThrottleWithNoDefault() { CruiseControlRequestContext mockRequest = EasyMock.mock(CruiseControlRequestContext.class); KafkaCruiseControlConfig controlConfig = EasyMock.mock(KafkaCruiseControlConfig.class); Map<String, String[]> paramMap = Collections.singletonMap( ParameterUtils.REPLICATION_THROTTLE_PARAM, new String[]{ParameterUtils.REPLICATION_THROTTLE_PARAM}); EasyMock.expect(mockRequest.getParameterMap()).andReturn(paramMap).once(); EasyMock.expect(mockRequest.getParameter(ParameterUtils.REPLICATION_THROTTLE_PARAM)).andReturn(REPLICATION_THROTTLE_STRING).once(); // No default EasyMock.expect(controlConfig.getLong(ExecutorConfig.DEFAULT_REPLICATION_THROTTLE_CONFIG)).andReturn(null); EasyMock.replay(mockRequest, controlConfig); Long replicationThrottle = ParameterUtils.replicationThrottle(mockRequest, controlConfig); Assert.assertEquals(Long.valueOf(REPLICATION_THROTTLE_STRING), replicationThrottle); EasyMock.verify(mockRequest, controlConfig); }
public static <T> String join(Iterator<T> iterator, CharSequence conjunction) { return StrJoiner.of(conjunction).append(iterator).toString(); }
@Test public void joinWithNullTest() { final ArrayList<String> list = CollUtil.newArrayList("1", null, "3", "4"); final String join = IterUtil.join(list.iterator(), ":", String::valueOf); assertEquals("1:null:3:4", join); }
@Udf public String lpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (padding == null || padding.isEmpty() || targetLen == null || targetLen < 0) { return null; } final StringBuilder sb = new StringBuilder(targetLen + padding.length()); final int padUpTo = Math.max(targetLen - input.length(), 0); for (int i = 0; i < padUpTo; i += padding.length()) { sb.append(padding); } sb.setLength(padUpTo); sb.append(input); sb.setLength(targetLen); return sb.toString(); }
@Test public void shouldReturnNullForNullLengthBytes() { final ByteBuffer result = udf.lpad(BYTES_123, null, BYTES_45); assertThat(result, is(nullValue())); }
public static <T> CollectionCoder<T> of(Coder<T> elemCoder) { return new CollectionCoder<>(elemCoder); }
@Test public void testCoderIsSerializableWithWellKnownCoderType() throws Exception { CoderProperties.coderSerializable(CollectionCoder.of(GlobalWindow.Coder.INSTANCE)); }
public static org.apache.avro.Schema toAvroSchema( Schema beamSchema, @Nullable String name, @Nullable String namespace) { final String schemaName = Strings.isNullOrEmpty(name) ? "topLevelRecord" : name; final String schemaNamespace = namespace == null ? "" : namespace; String childNamespace = !"".equals(schemaNamespace) ? schemaNamespace + "." + schemaName : schemaName; List<org.apache.avro.Schema.Field> fields = Lists.newArrayList(); for (Field field : beamSchema.getFields()) { org.apache.avro.Schema.Field recordField = toAvroField(field, childNamespace); fields.add(recordField); } return org.apache.avro.Schema.createRecord(schemaName, null, schemaNamespace, false, fields); }
@Test public void testJdbcLogicalDateAndTimeRowDataToAvroSchema() { String expectedAvroSchemaJson = "{ " + " \"name\": \"topLevelRecord\", " + " \"type\": \"record\", " + " \"fields\": [{ " + " \"name\": \"my_date_field\", " + " \"type\": { \"type\": \"int\", \"logicalType\": \"date\" }" + " }, " + " { " + " \"name\": \"my_time_field\", " + " \"type\": { \"type\": \"int\", \"logicalType\": \"time-millis\" }" + " }" + " ] " + "}"; Schema beamSchema = Schema.builder() .addField(Field.of("my_date_field", FieldType.logicalType(JdbcType.DATE))) .addField(Field.of("my_time_field", FieldType.logicalType(JdbcType.TIME))) .build(); assertEquals( new org.apache.avro.Schema.Parser().parse(expectedAvroSchemaJson), AvroUtils.toAvroSchema(beamSchema)); }
@Override public List<String> getKeys(final String id) { return Arrays.asList((getKeyName() + ".{" + id) + "}.tokens", (getKeyName() + ".{" + id) + "}.timestamp"); }
@Test public void getKeysTest() { String prefix = abstractRateLimiterAlgorithm.getKeyName() + ".{" + ID; String tokenKey = prefix + "}.tokens"; String timestampKey = prefix + "}.timestamp"; List<String> keys = abstractRateLimiterAlgorithm.getKeys(ID); assertThat(tokenKey, is(keys.get(0))); assertThat(timestampKey, is(keys.get(1))); }
public void removeSCM(String id) { SCM scmToBeDeleted = this.find(id); if (scmToBeDeleted == null) { throw new RuntimeException(String.format("Could not find SCM with id '%s'", id)); } this.remove(scmToBeDeleted); }
@Test void shouldThrowRuntimeExceptionWhenTryingToRemoveSCMIdWhichIsNotPresent() { SCMs scms = new SCMs(); try { scms.removeSCM("id1"); fail("should not reach here"); } catch (Exception e) { assertThat(e.getMessage()).isEqualTo(String.format("Could not find SCM with id '%s'", "id1")); } }
@Override public void handle(RMContainerEvent event) { LOG.debug("Processing {} of type {}", event.getContainerId(), event.getType()); writeLock.lock(); try { RMContainerState oldState = getState(); try { stateMachine.doTransition(event.getType(), event); } catch (InvalidStateTransitionException e) { LOG.error("Can't handle this event at current state", e); onInvalidStateTransition(event.getType(), oldState); } if (oldState != getState()) { LOG.info(event.getContainerId() + " Container Transitioned from " + oldState + " to " + getState()); } } finally { writeLock.unlock(); } }
@Test(timeout = 30000) public void testContainerAcquiredAtKilled() { DrainDispatcher drainDispatcher = new DrainDispatcher(); EventHandler<RMAppAttemptEvent> appAttemptEventHandler = mock( EventHandler.class); EventHandler generic = mock(EventHandler.class); drainDispatcher.register(RMAppAttemptEventType.class, appAttemptEventHandler); drainDispatcher.register(RMNodeEventType.class, generic); drainDispatcher.init(new YarnConfiguration()); drainDispatcher.start(); NodeId nodeId = BuilderUtils.newNodeId("host", 3425); ApplicationId appId = BuilderUtils.newApplicationId(1, 1); ApplicationAttemptId appAttemptId = BuilderUtils.newApplicationAttemptId( appId, 1); ContainerId containerId = BuilderUtils.newContainerId(appAttemptId, 1); ContainerAllocationExpirer expirer = mock(ContainerAllocationExpirer.class); Resource resource = Resources.createResource(512); Priority priority = BuilderUtils.newPriority(5); Container container = BuilderUtils.newContainer(containerId, nodeId, "host:3465", resource, priority, null); ConcurrentMap<ApplicationId, RMApp> appMap = new ConcurrentHashMap<>(); RMApp rmApp = mock(RMApp.class); appMap.putIfAbsent(appId, rmApp); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); SystemMetricsPublisher publisher = mock(SystemMetricsPublisher.class); RMContext rmContext = mock(RMContext.class); when(rmContext.getDispatcher()).thenReturn(drainDispatcher); when(rmContext.getContainerAllocationExpirer()).thenReturn(expirer); when(rmContext.getRMApplicationHistoryWriter()).thenReturn(writer); when(rmContext.getSystemMetricsPublisher()).thenReturn(publisher); AllocationTagsManager ptm = mock(AllocationTagsManager.class); when(rmContext.getAllocationTagsManager()).thenReturn(ptm); YarnConfiguration conf = new YarnConfiguration(); conf.setBoolean( YarnConfiguration.APPLICATION_HISTORY_SAVE_NON_AM_CONTAINER_META_INFO, true); when(rmContext.getYarnConfiguration()).thenReturn(conf); when(rmContext.getRMApps()).thenReturn(appMap); RMContainer rmContainer = new RMContainerImpl(container, SchedulerRequestKey.extractFrom(container), appAttemptId, nodeId, "user", rmContext) { @Override protected void onInvalidStateTransition( RMContainerEventType rmContainerEventType, RMContainerState state) { Assert.fail("RMContainerImpl: can't handle " + rmContainerEventType + " at state " + state); } }; rmContainer.handle(new RMContainerEvent(containerId, RMContainerEventType.KILL)); rmContainer.handle(new RMContainerEvent(containerId, RMContainerEventType.ACQUIRED)); }
@Udf(description = "Returns the tangent of an INT value") public Double tan( @UdfParameter( value = "value", description = "The value in radians to get the tangent of." ) final Integer value ) { return tan(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleNegative() { assertThat(udf.tan(-0.43), closeTo(-0.45862102348555517, 0.000000000000001)); assertThat(udf.tan(-Math.PI), closeTo(0, 0.000000000000001)); assertThat(udf.tan(-Math.PI * 2), closeTo(0, 0.000000000000001)); assertThat(udf.tan(-Math.PI * 2), closeTo(0, 0.000000000000001)); assertThat(udf.tan(-Math.PI / 2), closeTo(-1.633123935319537E16, 0.000000000000001)); assertThat(udf.tan(-6), closeTo(0.29100619138474915, 0.000000000000001)); assertThat(udf.tan(-6L), closeTo(0.29100619138474915, 0.000000000000001)); }
@Override public <K1, V1> KGroupedTable<K1, V1> groupBy(final KeyValueMapper<? super K, ? super V, KeyValue<K1, V1>> selector) { return groupBy(selector, Grouped.with(null, null)); }
@Test public void shouldNotAllowNullSelectorOnGroupBy() { assertThrows(NullPointerException.class, () -> table.groupBy(null)); }
@Override public void destroyItem(ViewGroup container, int position, Object object) { View view = (View) object; container.removeView(view); }
@Test public void testDestroyItem() { ViewGroup container = Mockito.mock(ViewGroup.class); View child = Mockito.mock(View.class); mUnderTest.destroyItem(container, 0, child); Mockito.verify(container).removeView(child); }
public static <T> boolean contains(Collection<T> coll, T target) { if (isEmpty(coll)) { return false; } return coll.contains(target); }
@Test void testContains() { assertTrue(CollectionUtils.contains(Collections.singletonList("target"), "target")); assertFalse(CollectionUtils.contains(Collections.emptyList(), "target")); }
public static PTransform<PCollection<? extends Iterable<?>>, PCollection<String>> iterables() { return iterables(","); }
@Test @Category(NeedsRunner.class) public void testToStringIterableWithDelimiter() { ArrayList<Iterable<String>> iterables = new ArrayList<>(); iterables.add(Arrays.asList(new String[] {"one", "two", "three"})); iterables.add(Arrays.asList(new String[] {"four", "five", "six"})); ArrayList<String> expected = new ArrayList<>(); expected.add("one\ttwo\tthree"); expected.add("four\tfive\tsix"); PCollection<Iterable<String>> input = p.apply(Create.of(iterables).withCoder(IterableCoder.of(StringUtf8Coder.of()))); PCollection<String> output = input.apply(ToString.iterables("\t")); PAssert.that(output).containsInAnyOrder(expected); p.run(); }
public void updateLockedJobTriggers() { final DateTime now = clock.nowUTC(); final var filter = and( eq(FIELD_LOCK_OWNER, nodeId), eq(FIELD_STATUS, JobTriggerStatus.RUNNING) ); collection.updateMany(filter, set(FIELD_LAST_LOCK_TIME, now)); }
@Test @MongoDBFixtures("locked-job-triggers.json") public void updateLockedJobTriggers() { DateTime newLockTime = DateTime.parse("2019-01-01T02:00:00.000Z"); final JobSchedulerTestClock clock = new JobSchedulerTestClock(newLockTime); final DBJobTriggerService service = serviceWithClock(clock); service.updateLockedJobTriggers(); List<String> updatedJobTriggerIds = service.all().stream() .filter(jobTriggerDto -> newLockTime.equals(jobTriggerDto.lock().lastLockTime())) .map(JobTriggerDto::id) .collect(Collectors.toList()); assertThat(updatedJobTriggerIds).containsOnly("54e3deadbeefdeadbeef0001", "54e3deadbeefdeadbeef0002"); }
public static <T> Partition<T> of( int numPartitions, PartitionWithSideInputsFn<? super T> partitionFn, Requirements requirements) { Contextful ctfFn = Contextful.fn( (T element, Contextful.Fn.Context c) -> partitionFn.partitionFor(element, numPartitions, c), requirements); return new Partition<>(new PartitionDoFn<T>(numPartitions, ctfFn, partitionFn)); }
@Test @Category(NeedsRunner.class) public void testEvenOddPartition() { PCollectionList<Integer> outputs = pipeline .apply(Create.of(591, 11789, 1257, 24578, 24799, 307)) .apply(Partition.of(2, new ModFn())); assertTrue(outputs.size() == 2); PAssert.that(outputs.get(0)).containsInAnyOrder(24578); PAssert.that(outputs.get(1)).containsInAnyOrder(591, 11789, 1257, 24799, 307); pipeline.run(); }
@BuildStep AdditionalBeanBuildItem produce(Capabilities capabilities, JobRunrBuildTimeConfiguration jobRunrBuildTimeConfiguration) { Set<Class<?>> additionalBeans = new HashSet<>(); additionalBeans.add(JobRunrProducer.class); additionalBeans.add(JobRunrStarter.class); additionalBeans.add(jsonMapper(capabilities)); additionalBeans.addAll(storageProvider(capabilities, jobRunrBuildTimeConfiguration)); return AdditionalBeanBuildItem.builder() .setUnremovable() .addBeanClasses(additionalBeans.toArray(new Class[0])) .build(); }
@Test void jobRunrProducerUsesJacksonIfCapabilityPresent() { Mockito.reset(capabilities); lenient().when(capabilities.isPresent(Capability.JACKSON)).thenReturn(true); final AdditionalBeanBuildItem additionalBeanBuildItem = jobRunrExtensionProcessor.produce(capabilities, jobRunrBuildTimeConfiguration); assertThat(additionalBeanBuildItem.getBeanClasses()) .contains(JobRunrProducer.JobRunrJacksonJsonMapperProducer.class.getName()); }
@Override public ConfigData get(String path) { return get(path, Files::isRegularFile); }
@Test public void testEmptyPathWithKey() { ConfigData configData = provider.get("", Collections.singleton("foo")); assertTrue(configData.data().isEmpty()); assertNull(configData.ttl()); }
@SuppressWarnings("unchecked") @Udf public <T> List<T> union( @UdfParameter(description = "First array of values") final List<T> left, @UdfParameter(description = "Second array of values") final List<T> right) { if (left == null || right == null) { return null; } final Set<T> combined = Sets.newLinkedHashSet(left); combined.addAll(right); return (List<T>) Arrays.asList(combined.toArray()); }
@Test public void shouldUnionArraysOfLikeType() { final List<String> input1 = Arrays.asList("foo", " ", "bar"); final List<String> input2 = Arrays.asList("baz"); final List<String> result = udf.union(input1, input2); assertThat(result, contains("foo", " ", "bar", "baz")); }
public static Pattern buildTopicRegex(Set<String> stringsToMatch) { StringJoiner sj = new StringJoiner("|"); stringsToMatch.forEach(sj::add); return Pattern.compile(sj.toString()); }
@Test public void testBuildTopicRegex() { Set<String> topicsToMatch = Set.of(TOPIC1, TOPIC2); Pattern pattern = buildTopicRegex(topicsToMatch); assertTrue(pattern.matcher(TOPIC1).matches()); assertTrue(pattern.matcher(TOPIC2).matches()); assertFalse(pattern.matcher(TOPIC3).matches()); }
@Override public boolean addAggrConfigInfo(final String dataId, final String group, String tenant, final String datumId, String appName, final String content) { String appNameTmp = StringUtils.isBlank(appName) ? StringUtils.EMPTY : appName; String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; final Timestamp now = new Timestamp(System.currentTimeMillis()); ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_AGGR); String select = configInfoAggrMapper.select(Collections.singletonList("content"), Arrays.asList("data_id", "group_id", "tenant_id", "datum_id")); String insert = configInfoAggrMapper.insert( Arrays.asList("data_id", "group_id", "tenant_id", "datum_id", "app_name", "content", "gmt_modified")); String update = configInfoAggrMapper.update(Arrays.asList("content", "gmt_modified"), Arrays.asList("data_id", "group_id", "tenant_id", "datum_id")); try { try { String dbContent = jt.queryForObject(select, new Object[] {dataId, group, tenantTmp, datumId}, String.class); if (dbContent != null && dbContent.equals(content)) { return true; } else { return jt.update(update, content, now, dataId, group, tenantTmp, datumId) > 0; } } catch (EmptyResultDataAccessException ex) { // no data, insert return jt.update(insert, dataId, group, tenantTmp, datumId, appNameTmp, content, now) > 0; } } catch (DataAccessException e) { LogUtil.FATAL_LOG.error("[db-error] " + e, e); throw e; } }
@Test void testAddAggrConfigInfoOfUpdateNotEqualContent() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; String datumId = "datumId"; String appName = "appname1234"; String content = "content1234"; //mock query datumId String existContent = "existContent111"; when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), eq(String.class))).thenReturn( existContent); //mock update success,return 1 when(jdbcTemplate.update(anyString(), eq(content), any(Timestamp.class), eq(dataId), eq(group), eq(tenant), eq(datumId))).thenReturn(1); //mock update content boolean result = externalConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, content); assertTrue(result); }
@Override public List<String> listDatabases() throws CatalogException { if (catalog instanceof SupportsNamespaces) { List<String> databases = ((SupportsNamespaces) catalog) .listNamespaces().stream() .map(Namespace::toString) .collect(Collectors.toList()); log.info("Fetched {} namespaces.", databases.size()); return databases; } else { throw new UnsupportedOperationException( "catalog not implements SupportsNamespaces so can't list databases"); } }
@Test @Order(4) void listDatabases() { icebergCatalog.listDatabases().forEach(System.out::println); Assertions.assertTrue(icebergCatalog.listDatabases().contains(databaseName)); }
@Override public UUID generateId() { return UUID.randomUUID(); }
@Test void generates_different_non_null_uuids() { // Given UuidGenerator generator = new RandomUuidGenerator(); UUID uuid1 = generator.generateId(); // When UUID uuid2 = generator.generateId(); // Then assertNotNull(uuid1); assertNotNull(uuid2); assertNotEquals(uuid1, uuid2); }
public static <T> SerializedValue<T> fromBytes(byte[] serializedData) { return new SerializedValue<>(serializedData); }
@Test void testFromEmptyBytes() { assertThatThrownBy(() -> SerializedValue.fromBytes(new byte[0])) .isInstanceOf(IllegalArgumentException.class); }
public static Type[] getReturnTypes(Method method) { Class<?> returnType = method.getReturnType(); Type genericReturnType = method.getGenericReturnType(); if (Future.class.isAssignableFrom(returnType)) { if (genericReturnType instanceof ParameterizedType) { Type actualArgType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; if (actualArgType instanceof ParameterizedType) { returnType = (Class<?>) ((ParameterizedType) actualArgType).getRawType(); genericReturnType = actualArgType; } else if (actualArgType instanceof TypeVariable) { returnType = (Class<?>) ((TypeVariable<?>) actualArgType).getBounds()[0]; genericReturnType = actualArgType; } else { returnType = (Class<?>) actualArgType; genericReturnType = returnType; } } else { returnType = null; genericReturnType = null; } } return new Type[] {returnType, genericReturnType}; }
@Test void testGetReturnTypes() throws Exception { Class<TypeClass> clazz = TypeClass.class; Type[] types = ReflectUtils.getReturnTypes(clazz.getMethod("getFuture")); Assertions.assertEquals("java.lang.String", types[0].getTypeName()); Assertions.assertEquals("java.lang.String", types[1].getTypeName()); Type[] types1 = ReflectUtils.getReturnTypes(clazz.getMethod("getString")); Assertions.assertEquals("java.lang.String", types1[0].getTypeName()); Assertions.assertEquals("java.lang.String", types1[1].getTypeName()); Type[] types2 = ReflectUtils.getReturnTypes(clazz.getMethod("getT")); Assertions.assertEquals("java.lang.String", types2[0].getTypeName()); Assertions.assertEquals("T", types2[1].getTypeName()); Type[] types3 = ReflectUtils.getReturnTypes(clazz.getMethod("getS")); Assertions.assertEquals("java.lang.Object", types3[0].getTypeName()); Assertions.assertEquals("S", types3[1].getTypeName()); Type[] types4 = ReflectUtils.getReturnTypes(clazz.getMethod("getListFuture")); Assertions.assertEquals("java.util.List", types4[0].getTypeName()); Assertions.assertEquals("java.util.List<java.lang.String>", types4[1].getTypeName()); Type[] types5 = ReflectUtils.getReturnTypes(clazz.getMethod("getGenericWithUpperFuture")); // T extends String, the first arg should be the upper bound of param Assertions.assertEquals("java.lang.String", types5[0].getTypeName()); Assertions.assertEquals("T", types5[1].getTypeName()); Type[] types6 = ReflectUtils.getReturnTypes(clazz.getMethod("getGenericFuture")); // default upper bound is Object Assertions.assertEquals("java.lang.Object", types6[0].getTypeName()); Assertions.assertEquals("S", types6[1].getTypeName()); }
public int distanceOf(PartitionTableView partitionTableView) { int distance = 0; for (int i = 0; i < partitions.length; i++) { distance += distanceOf(partitions[i], partitionTableView.partitions[i]); } return distance; }
@Test public void testDistance_whenReplicasExchanged() throws Exception { // distanceOf([A, B, C], [B, A, C]) == 2 PartitionTableView table1 = createRandomPartitionTable(); InternalPartition[] partitions = extractPartitions(table1); PartitionReplica[] replicas = partitions[0].getReplicasCopy(); PartitionReplica temp = replicas[0]; replicas[0] = replicas[1]; replicas[1] = temp; partitions[0] = new ReadonlyInternalPartition(replicas, 0, partitions[0].version()); PartitionTableView table2 = new PartitionTableView(partitions); assertEquals(2, table2.distanceOf(table1)); }
@Config("metadata-uri") public ExampleConfig setMetadata(URI metadata) { this.metadata = metadata; return this; }
@Test public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("metadata-uri", "file://test.json") .build(); ExampleConfig expected = new ExampleConfig() .setMetadata(URI.create("file://test.json")); ConfigAssertions.assertFullMapping(properties, expected); }
public static boolean reserved(Uuid uuid) { return uuid.getMostSignificantBits() == 0 && uuid.getLeastSignificantBits() < 100; }
@Test void testMigratingIsReserved() { assertTrue(DirectoryId.reserved(DirectoryId.MIGRATING)); }
@SuppressWarnings("unchecked") public static <S, F> S visit(final Schema schema, final Visitor<S, F> visitor) { final BiFunction<Visitor<?, ?>, Schema, Object> handler = HANDLER.get(schema.type()); if (handler == null) { throw new UnsupportedOperationException("Unsupported schema type: " + schema.type()); } return (S) handler.apply(visitor, schema); }
@Test public void shouldVisitString() { // Given: final Schema schema = Schema.OPTIONAL_STRING_SCHEMA; when(visitor.visitString(any())).thenReturn("Expected"); // When: final String result = SchemaWalker.visit(schema, visitor); // Then: verify(visitor).visitString(same(schema)); assertThat(result, is("Expected")); }
@Description("current time without time zone") @ScalarFunction("localtime") @SqlType(StandardTypes.TIME) public static long localTime(SqlFunctionProperties properties) { if (properties.isLegacyTimestamp()) { return UTC_CHRONOLOGY.millisOfDay().get(properties.getSessionStartTime()); } ISOChronology localChronology = getChronology(properties.getTimeZoneKey()); return localChronology.millisOfDay().get(properties.getSessionStartTime()); }
@Test public void testLocalTime() { Session localSession = Session.builder(session) .setStartTime(new DateTime(2017, 3, 1, 14, 30, 0, 0, DATE_TIME_ZONE).getMillis()) .build(); try (FunctionAssertions localAssertion = new FunctionAssertions(localSession)) { localAssertion.assertFunctionString("LOCALTIME", TimeType.TIME, "14:30:00.000"); } }
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("pathState", pathStates) .add("activePathIndex", activePathIndex) .add("description", description) .toString(); }
@Test public void testToString() { ProtectedTransportEndpointState state1 = ProtectedTransportEndpointState .builder() .withActivePathIndex(0) .withDescription(protectedDescription) .withPathStates(pathStates) .build(); ProtectedTransportEndpointState state2 = ProtectedTransportEndpointState .builder() .copyFrom(state1) .build(); assertThat(state1.toString(), is(state2.toString())); }
public static Metric metric(String name) { return MetricsImpl.metric(name, Unit.COUNT); }
@Test public void metricInNotFusedStages() { int inputSize = 100_000; Integer[] inputs = new Integer[inputSize]; Arrays.setAll(inputs, i -> i); pipeline.readFrom(TestSources.items(inputs)) .filter(l -> { Metrics.metric("onlyInFilter").increment(); Metrics.metric("inBoth").increment(); return true; }) .groupingKey(t -> t) .aggregate(counting()) .map(t -> { Metrics.metric("onlyInMap").increment(); Metrics.metric("inBoth").increment(); return t; }) .writeTo(Sinks.noop()); Job job = runPipeline(pipeline.toDag()); JobMetricsChecker checker = new JobMetricsChecker(job); checker.assertSummedMetricValue("onlyInFilter", inputSize); checker.assertSummedMetricValue("onlyInMap", inputSize); checker.assertSummedMetricValue("inBoth", 2 * inputSize); }
ClassicGroup getOrMaybeCreateClassicGroup( String groupId, boolean createIfNotExists ) throws GroupIdNotFoundException { Group group = groups.get(groupId); if (group == null && !createIfNotExists) { throw new GroupIdNotFoundException(String.format("Classic group %s not found.", groupId)); } if (group == null) { ClassicGroup classicGroup = new ClassicGroup(logContext, groupId, ClassicGroupState.EMPTY, time, metrics); groups.put(groupId, classicGroup); metrics.onClassicGroupStateTransition(null, classicGroup.currentState()); return classicGroup; } else { if (group.type() == CLASSIC) { return (ClassicGroup) group; } else { // We don't support upgrading/downgrading between protocols at the moment so // we throw an exception if a group exists with the wrong type. throw new GroupIdNotFoundException(String.format("Group %s is not a classic group.", groupId)); } } }
@Test public void testClassicGroupJoinWithEmptyConsumerGroup() throws Exception { String consumerGroupId = "consumer-group-id"; GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .withConsumerGroup(new ConsumerGroupBuilder(consumerGroupId, 10)) .build(); JoinGroupRequestData request = new GroupMetadataManagerTestContext.JoinGroupRequestBuilder() .withGroupId(consumerGroupId) .withMemberId(UNKNOWN_MEMBER_ID) .withDefaultProtocolTypeAndProtocols() .build(); GroupMetadataManagerTestContext.JoinResult joinResult = context.sendClassicGroupJoin(request, true); List<CoordinatorRecord> expectedRecords = Arrays.asList( GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentEpochTombstoneRecord(consumerGroupId), GroupCoordinatorRecordHelpers.newConsumerGroupSubscriptionMetadataTombstoneRecord(consumerGroupId), GroupCoordinatorRecordHelpers.newConsumerGroupEpochTombstoneRecord(consumerGroupId) ); assertEquals(Errors.MEMBER_ID_REQUIRED.code(), joinResult.joinFuture.get().errorCode()); assertEquals(expectedRecords, joinResult.records.subList(0, expectedRecords.size())); assertEquals( Group.GroupType.CLASSIC, context.groupMetadataManager.getOrMaybeCreateClassicGroup(consumerGroupId, false).type() ); }
@Override public ConnectionProperties parse(final String url, final String username, final String catalog) { Matcher matcher = URL_PATTERN.matcher(url); ShardingSpherePreconditions.checkState(matcher.find(), () -> new UnrecognizedDatabaseURLException(url, URL_PATTERN.pattern())); return new StandardConnectionProperties(matcher.group(2), Strings.isNullOrEmpty(matcher.group(3)) ? DEFAULT_PORT : Integer.parseInt(matcher.group(3)), matcher.group(5), null); }
@Test void assertNewConstructorFailure() { assertThrows(UnrecognizedDatabaseURLException.class, () -> parser.parse("jdbc:sqlserver:xxxxxxxx", null, null)); }
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) { // Close the running transformation if ( getData().wasStarted ) { if ( !getData().mappingTrans.isFinished() ) { // Wait until the child transformation has finished. getData().mappingTrans.waitUntilFinished(); } // Remove it from the list of active sub-transformations... // getTrans().removeActiveSubTransformation( getStepname() ); // See if there was an error in the sub-transformation, in that case, flag error etc. if ( getData().mappingTrans.getErrors() > 0 ) { logError( BaseMessages.getString( PKG, "SimpleMapping.Log.ErrorOccurredInSubTransformation" ) ); setErrors( 1 ); } } super.dispose( smi, sdi ); }
@Test public void testDispose() throws KettleException { // Set Up TransMock to return the error when( stepMockHelper.trans.getErrors() ).thenReturn( 0 ); // The step has been already finished when( stepMockHelper.trans.isFinished() ).thenReturn( Boolean.FALSE ); // The step was started simpleMpData.wasStarted = true; smp = new SimpleMapping( stepMockHelper.stepMeta, stepMockHelper.stepDataInterface, 0, stepMockHelper.transMeta, stepMockHelper.trans ); smp.init( stepMockHelper.initStepMetaInterface, simpleMpData ); smp.dispose( stepMockHelper.processRowsStepMetaInterface, simpleMpData ); verify( stepMockHelper.trans, times( 1 ) ).isFinished(); verify( stepMockHelper.trans, times( 1 ) ).waitUntilFinished(); verify( stepMockHelper.trans, times( 1 ) ).removeActiveSubTransformation( anyString() ); }
@Override public Duration convert(String source) { try { if (ISO8601.matcher(source).matches()) { return Duration.parse(source); } Matcher matcher = SIMPLE.matcher(source); Assert.state(matcher.matches(), "'" + source + "' is not a valid duration"); long amount = Long.parseLong(matcher.group(1)); ChronoUnit unit = getUnit(matcher.group(2)); return Duration.of(amount, unit); } catch (Exception ex) { throw new IllegalStateException("'" + source + "' is not a valid duration", ex); } }
@Test public void convertWhenSimpleWithoutSuffixShouldReturnDuration() { assertThat(convert("10")).isEqualTo(Duration.ofMillis(10)); assertThat(convert("+10")).isEqualTo(Duration.ofMillis(10)); assertThat(convert("-10")).isEqualTo(Duration.ofMillis(-10)); }
public static ResourceId relativize(ResourceId base, ResourceId child) { checkArgument(child.nodeKeys().size() >= base.nodeKeys().size(), "%s path must be deeper than base prefix %s", child, base); @SuppressWarnings("rawtypes") Iterator<NodeKey> bIt = base.nodeKeys().iterator(); @SuppressWarnings("rawtypes") Iterator<NodeKey> cIt = child.nodeKeys().iterator(); while (bIt.hasNext()) { NodeKey<?> b = bIt.next(); NodeKey<?> c = cIt.next(); checkArgument(Objects.equals(b, c), "%s is not a prefix of %s.\n" + "b:%s != c:%s", base, child, b, c); } return ResourceId.builder().append(child.nodeKeys().subList(base.nodeKeys().size(), child.nodeKeys().size())).build(); }
@Test public void testRelativize() { ResourceId relDevices = ResourceIds.relativize(ResourceIds.ROOT_ID, DEVICES); assertEquals(DeviceResourceIds.DEVICES_NAME, relDevices.nodeKeys().get(0).schemaId().name()); assertEquals(DCS_NAMESPACE, relDevices.nodeKeys().get(0).schemaId().namespace()); assertEquals(1, relDevices.nodeKeys().size()); }
public static String clean(String charsetName) { try { return forName(charsetName).name(); } catch (IllegalArgumentException e) { return null; } }
@Test public void testFunkyNames() { assertEquals(null, CharsetUtils.clean("none")); assertEquals(null, CharsetUtils.clean("no")); assertEquals("UTF-8", CharsetUtils.clean("utf-8>")); assertEquals("ISO-8859-1", CharsetUtils.clean("iso-8851-1")); assertEquals("ISO-8859-15", CharsetUtils.clean("8859-15")); assertEquals("windows-1251", CharsetUtils.clean("cp-1251")); assertEquals("windows-1251", CharsetUtils.clean("win1251")); assertEquals("windows-1251", CharsetUtils.clean("WIN-1251")); assertEquals("windows-1251", CharsetUtils.clean("win-1251")); assertEquals("windows-1252", CharsetUtils.clean("Windows")); assertEquals("KOI8-R", CharsetUtils.clean("koi8r")); }
@Override public void filter(Set<String> brokers, BundleData bundleToAssign, LoadData loadData, ServiceConfiguration conf) throws BrokerFilterException { loadData.getBrokerData().forEach((key, value) -> { // The load manager class name can be null if the cluster has old version of broker. if (!Objects.equals(value.getLocalData().getLoadManagerClassName(), conf.getLoadManagerClassName())) { brokers.remove(key); } }); }
@Test public void test() throws BrokerFilterException { BrokerLoadManagerClassFilter filter = new BrokerLoadManagerClassFilter(); LoadData loadData = new LoadData(); LocalBrokerData localBrokerData = new LocalBrokerData(); localBrokerData.setLoadManagerClassName(ModularLoadManagerImpl.class.getName()); LocalBrokerData localBrokerData1 = new LocalBrokerData(); localBrokerData1.setLoadManagerClassName(ExtensibleLoadManagerImpl.class.getName()); LocalBrokerData localBrokerData2 = new LocalBrokerData(); localBrokerData2.setLoadManagerClassName(null); loadData.getBrokerData().put("broker1", new BrokerData(localBrokerData)); loadData.getBrokerData().put("broker2", new BrokerData(localBrokerData1)); loadData.getBrokerData().put("broker3", new BrokerData(localBrokerData2)); ServiceConfiguration conf = new ServiceConfiguration(); conf.setLoadManagerClassName(ModularLoadManagerImpl.class.getName()); Set<String> brokers = new HashSet<>(){{ add("broker1"); add("broker2"); add("broker3"); }}; filter.filter(brokers, null, loadData, conf); assertEquals(brokers.size(), 1); assertTrue(brokers.contains("broker1")); brokers = new HashSet<>(){{ add("broker1"); add("broker2"); add("broker3"); }}; conf.setLoadManagerClassName(ExtensibleLoadManagerImpl.class.getName()); filter.filter(brokers, null, loadData, conf); assertEquals(brokers.size(), 1); assertTrue(brokers.contains("broker2")); }
@Override public <KR> KGroupedStream<KR, V> groupBy(final KeyValueMapper<? super K, ? super V, KR> keySelector) { return groupBy(keySelector, Grouped.with(null, valueSerde)); }
@Test public void shouldNotAllowNullSelectorOnGroupByWithGrouped() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.groupBy(null, Grouped.as("name"))); assertThat(exception.getMessage(), equalTo("keySelector can't be null")); }
public static UserConfigRepo build(Element producerSpec, ConfigDefinitionStore configDefinitionStore, DeployLogger deployLogger) { Map<ConfigDefinitionKey, ConfigPayloadBuilder> builderMap = new LinkedHashMap<>(); log.log(Level.FINE, () -> "getUserConfigs for " + producerSpec); for (Element configE : XML.getChildren(producerSpec, "config")) { buildElement(configE, builderMap, configDefinitionStore, deployLogger); } return new UserConfigRepo(builderMap); }
@Test void no_exception_when_config_class_does_not_exist() { Element configRoot = getDocument("<config name=\"is.unknown\">" + " <foo>1</foo>" + "</config>"); UserConfigRepo repo = UserConfigBuilder.build(configRoot, configDefinitionStore, new BaseDeployLogger()); ConfigPayloadBuilder builder = repo.get(new ConfigDefinitionKey("unknown", "is")); assertNotNull(builder); }
@Override @CheckForNull public EmailMessage format(Notification notification) { if (!BuiltInQPChangeNotification.TYPE.equals(notification.getType())) { return null; } BuiltInQPChangeNotificationBuilder profilesNotification = parse(notification); StringBuilder message = new StringBuilder("The following built-in profiles have been updated:\n\n"); profilesNotification.getProfiles().stream() .sorted(Comparator.comparing(Profile::getLanguageName).thenComparing(Profile::getProfileName)) .forEach(profile -> { message.append("\"") .append(profile.getProfileName()) .append("\" - ") .append(profile.getLanguageName()) .append(": ") .append(server.getPublicRootUrl()).append("/profiles/changelog?language=") .append(profile.getLanguageKey()) .append("&name=") .append(encode(profile.getProfileName())) .append("&since=") .append(formatDate(new Date(profile.getStartDate()))) .append("&to=") .append(formatDate(new Date(profile.getEndDate()))) .append("\n"); int newRules = profile.getNewRules(); if (newRules > 0) { message.append(" ").append(newRules).append(" new rule") .append(plural(newRules)) .append('\n'); } int updatedRules = profile.getUpdatedRules(); if (updatedRules > 0) { message.append(" ").append(updatedRules).append(" rule") .append(updatedRules > 1 ? "s have been updated" : " has been updated") .append("\n"); } int removedRules = profile.getRemovedRules(); if (removedRules > 0) { message.append(" ").append(removedRules).append(" rule") .append(plural(removedRules)) .append(" removed\n"); } message.append("\n"); }); message.append("This is a good time to review your quality profiles and update them to benefit from the latest evolutions: "); message.append(server.getPublicRootUrl()).append("/profiles"); // And finally return the email that will be sent return new EmailMessage() .setMessageId(BuiltInQPChangeNotification.TYPE) .setSubject("Built-in quality profiles have been updated") .setPlainTextMessage(message.toString()); }
@Test public void notification_supports_grammar_for_single_rule_added_removed_or_updated() { String profileName = newProfileName(); String languageKey = newLanguageKey(); String languageName = newLanguageName(); BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder() .addProfile(Profile.newBuilder() .setProfileName(profileName) .setLanguageKey(languageKey) .setLanguageName(languageName) .setNewRules(1) .setUpdatedRules(1) .setRemovedRules(1) .build()); EmailMessage emailMessage = underTest.format(notification.build()); assertThat(emailMessage.getMessage()) .contains("\n 1 new rule\n") .contains("\n 1 rule has been updated\n") .contains("\n 1 rule removed\n"); }
public static DegraderImpl.Config toDegraderConfig(Map<String, String> properties) { DegraderImpl.Config config = new DegraderImpl.Config(); if (properties == null || properties.isEmpty()) { return config; } else { // we are not modifying config's callTracker, name, clock and overrideDropRate because // that will be set during the construction of TrackerClient config.setLogEnabled(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_LOG_ENABLED, DegraderImpl.DEFAULT_LOG_ENABLED)); config.setLogThreshold(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_LOG_THRESHOLD, DegraderImpl.DEFAULT_LOG_THRESHOLD)); if (properties.get(PropertyKeys.DEGRADER_LATENCY_TO_USE) != null) { try { config.setLatencyToUse(DegraderImpl.LatencyToUse.valueOf(properties.get(PropertyKeys. DEGRADER_LATENCY_TO_USE))); } catch (IllegalArgumentException e) { warn(_log, "Received an illegal enum for latencyToUse in the cluster properties. The enum is " + properties.get(PropertyKeys.DEGRADER_LATENCY_TO_USE), e); config.setLatencyToUse(DegraderImpl.DEFAULT_LATENCY_TO_USE); } } config.setMaxDropRate(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_MAX_DROP_RATE, DegraderImpl.DEFAULT_MAX_DROP_RATE)); config.setMaxDropDuration(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_MAX_DROP_DURATION, DegraderImpl.DEFAULT_MAX_DROP_DURATION )); config.setUpStep(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_UP_STEP, DegraderImpl.DEFAULT_UP_STEP)); config.setDownStep(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_DOWN_STEP, DegraderImpl.DEFAULT_DOWN_STEP)); config.setMinCallCount(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_MIN_CALL_COUNT, DegraderImpl.DEFAULT_MIN_CALL_COUNT)); config.setHighLatency(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_HIGH_LATENCY, DegraderImpl.DEFAULT_HIGH_LATENCY)); config.setLowLatency(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_LOW_LATENCY, DegraderImpl.DEFAULT_LOW_LATENCY)); config.setHighErrorRate(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_HIGH_ERROR_RATE, DegraderImpl.DEFAULT_HIGH_ERROR_RATE)); config.setLowErrorRate(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_LOW_ERROR_RATE, DegraderImpl.DEFAULT_LOW_ERROR_RATE)); config.setHighOutstanding(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_HIGH_OUTSTANDING, DegraderImpl.DEFAULT_HIGH_OUTSTANDING)); config.setLowOutstanding(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_LOW_OUTSTANDING, DegraderImpl.DEFAULT_LOW_OUTSTANDING)); config.setMinOutstandingCount(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_MIN_OUTSTANDING_COUNT, DegraderImpl.DEFAULT_MIN_OUTSTANDING_COUNT)); config.setOverrideMinCallCount(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_OVERRIDE_MIN_CALL_COUNT, DegraderImpl.DEFAULT_OVERRIDE_MIN_CALL_COUNT)); config.setInitialDropRate(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_INITIAL_DROP_RATE, DegraderImpl.DEFAULT_INITIAL_DROP_RATE)); config.setSlowStartThreshold(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_SLOW_START_THRESHOLD, DegraderImpl.DEFAULT_SLOW_START_THRESHOLD)); config.setPreemptiveRequestTimeoutRate(MapUtil.getWithDefault(properties, PropertyKeys.DEGRADER_PREEMPTIVE_REQUEST_TIMEOUT_RATE, DegraderImpl.DEFAULT_PREEMPTIVE_REQUEST_TIMEOUT_RATE)); } return config; }
@Test public void testToDegraderConfig() { Map<String,String> properties = new HashMap<>();; Boolean logEnabled = false; DegraderImpl.LatencyToUse latencyToUse = DegraderImpl.LatencyToUse.PCT95; Double maxDropRate = 0.33; Long maxDropDuration = 23190l; Double upStep = 0.3; Double downstep = 0.2; Integer minCallCount = 22; Long highLatency = 30000000l; Long lowLatency = 244499l; Double highErrorRate = 0.5; Double lowErrorRate = 0.1; Long highOutstanding = 10000l; Long lowOutstanding = 3000l; Integer minOutstandingCount = 10; Integer overrideMinCallCount = 5; Double logThreshold = 0.8; Double preemptiveRequestTimeoutRate = 0.5; properties.put(PropertyKeys.DEGRADER_LOG_ENABLED, logEnabled.toString()); properties.put(PropertyKeys.DEGRADER_LATENCY_TO_USE, latencyToUse.toString()); properties.put(PropertyKeys.DEGRADER_MAX_DROP_RATE, maxDropRate.toString()); properties.put(PropertyKeys.DEGRADER_MAX_DROP_DURATION, maxDropDuration.toString()); properties.put(PropertyKeys.DEGRADER_UP_STEP, upStep.toString()); properties.put(PropertyKeys.DEGRADER_DOWN_STEP, downstep.toString()); properties.put(PropertyKeys.DEGRADER_MIN_CALL_COUNT, minCallCount.toString()); properties.put(PropertyKeys.DEGRADER_HIGH_LATENCY, highLatency.toString()); properties.put(PropertyKeys.DEGRADER_LOW_LATENCY, lowLatency.toString()); properties.put(PropertyKeys.DEGRADER_HIGH_ERROR_RATE, highErrorRate.toString()); properties.put(PropertyKeys.DEGRADER_LOW_ERROR_RATE, lowErrorRate.toString()); properties.put(PropertyKeys.DEGRADER_HIGH_OUTSTANDING, highOutstanding.toString()); properties.put(PropertyKeys.DEGRADER_LOW_OUTSTANDING, lowOutstanding.toString()); properties.put(PropertyKeys.DEGRADER_MIN_OUTSTANDING_COUNT, minOutstandingCount.toString()); properties.put(PropertyKeys.DEGRADER_OVERRIDE_MIN_CALL_COUNT, overrideMinCallCount.toString()); properties.put(PropertyKeys.DEGRADER_LOG_THRESHOLD, logThreshold.toString()); properties.put(PropertyKeys.DEGRADER_PREEMPTIVE_REQUEST_TIMEOUT_RATE, preemptiveRequestTimeoutRate.toString()); DegraderImpl.Config config = DegraderConfigFactory.toDegraderConfig(properties); assertEquals(config.isLogEnabled(), logEnabled.booleanValue()); assertEquals(config.getLatencyToUse(), latencyToUse); assertEquals(config.getMaxDropRate(), maxDropRate); assertEquals(config.getMaxDropDuration(), maxDropDuration.longValue()); assertEquals(config.getUpStep(), upStep.doubleValue()); assertEquals(config.getDownStep(), downstep.doubleValue()); assertEquals(config.getMinCallCount(), minCallCount.intValue()); assertEquals(config.getHighLatency(), highLatency.longValue()); assertEquals(config.getLowLatency(), lowLatency.longValue()); assertEquals(config.getHighErrorRate(), highErrorRate.doubleValue()); assertEquals(config.getLowErrorRate(), lowErrorRate.doubleValue()); assertEquals(config.getHighOutstanding(), highOutstanding.longValue()); assertEquals(config.getLowOutstanding(), lowOutstanding.longValue()); assertEquals(config.getMinOutstandingCount(), minOutstandingCount.longValue()); assertEquals(config.getOverrideMinCallCount(), overrideMinCallCount.intValue()); assertEquals(config.getLogThreshold(), logThreshold); assertEquals(config.getPreemptiveRequestTimeoutRate(), preemptiveRequestTimeoutRate); }
@Override public SingleRuleConfiguration swapToObject(final YamlSingleRuleConfiguration yamlConfig) { SingleRuleConfiguration result = new SingleRuleConfiguration(); if (null != yamlConfig.getTables()) { result.getTables().addAll(yamlConfig.getTables()); } result.setDefaultDataSource(yamlConfig.getDefaultDataSource()); return result; }
@Test void assertSwapToObject() { YamlSingleRuleConfiguration yamlConfig = new YamlSingleRuleConfiguration(); yamlConfig.setDefaultDataSource("ds_0"); SingleRuleConfiguration ruleConfig = new YamlSingleRuleConfigurationSwapper().swapToObject(yamlConfig); assertTrue(ruleConfig.getDefaultDataSource().isPresent()); assertThat(ruleConfig.getDefaultDataSource().get(), is("ds_0")); }
@Cacheable(value = "metadata-response", key = "#samlMetadataRequest.cacheableKey()") public SamlMetadataResponse resolveSamlMetadata(SamlMetadataRequest samlMetadataRequest) { LOGGER.info("Cache not found for saml-metadata {}", samlMetadataRequest.hashCode()); Connection connection = connectionService.getConnectionByEntityId(samlMetadataRequest.getConnectionEntityId()); MetadataResponseStatus metadataResponseStatus = null; nl.logius.digid.dc.domain.service.Service service = null; if (connection == null) { metadataResponseStatus = CONNECTION_NOT_FOUND; } else if (!connection.getStatus().isAllowed()) { metadataResponseStatus = CONNECTION_INACTIVE; } else if (!connection.getOrganization().getStatus().isAllowed()) { metadataResponseStatus = ORGANIZATION_INACTIVE; } else if (Boolean.FALSE.equals(connection.getOrganizationRole().getStatus().isAllowed())) { metadataResponseStatus = ORGANIZATION_ROLE_INACTIVE; } else { String serviceUUID = samlMetadataRequest.getServiceUuid() == null ? getServiceUUID(connection, samlMetadataRequest.getServiceEntityId(), samlMetadataRequest.getServiceIdx()) : samlMetadataRequest.getServiceUuid(); samlMetadataRequest.setServiceUuid(serviceUUID); service = serviceService.serviceExists(connection, samlMetadataRequest.getServiceEntityId(), serviceUUID); if (service == null) { metadataResponseStatus = SERVICE_NOT_FOUND; } else if (!service.getStatus().isAllowed()) { metadataResponseStatus = SERVICE_INACTIVE; } } if (metadataResponseStatus != null) { return metadataResponseMapper.mapErrorResponse(metadataResponseStatus.name(), metadataResponseStatus.label); } else { String samlMetadata = generateReducedMetadataString(connection, service.getEntityId()); return metadataResponseMapper.mapSuccessResponse(samlMetadata, connection, service, STATUS_OK.name()); } }
@Test void organizationInactiveTest() { Connection connection = newConnection(SAML_COMBICONNECT, true, false, true); when(connectionServiceMock.getConnectionByEntityId(anyString())).thenReturn(connection); SamlMetadataResponse response = metadataRetrieverServiceMock.resolveSamlMetadata(newMetadataRequest()); assertEquals(ORGANIZATION_INACTIVE.name(), response.getRequestStatus()); assertEquals(ORGANIZATION_INACTIVE.label, response.getErrorDescription()); }
@Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { if (!tokenQueue.isNextTokenValue(lToken)) { return false; } int stack = 0; while (tokenQueue.peek() != null) { Token token = tokenQueue.poll(); if (lToken.equals(token.getValue())) { stack++; } else if (rToken.equals(token.getValue())) { stack--; } matchedTokenList.add(token); if (stack == 0) { return true; } } return false; }
@Test public void shouldNotMatchWhenNoLeft() { Token t1 = new Token("a", 1, 1); TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1))); List<Token> output = mock(List.class); BridgeTokenMatcher matcher = new BridgeTokenMatcher("(", ")"); assertThat(matcher.matchToken(tokenQueue, output), is(false)); verify(tokenQueue).isNextTokenValue("("); verifyNoMoreInteractions(tokenQueue); verifyNoMoreInteractions(output); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof PortFragmentId)) { return false; } PortFragmentId that = (PortFragmentId) obj; return Objects.equals(this.deviceId, that.deviceId) && Objects.equals(this.portNumber, that.portNumber) && Objects.equals(this.providerId, that.providerId); }
@Test public final void testEquals() { new EqualsTester() .addEqualityGroup(new PortFragmentId(DID1, PID, PN1), new PortFragmentId(DID1, PID, PN1)) .addEqualityGroup(new PortFragmentId(DID2, PID, PN1), new PortFragmentId(DID2, PID, PN1)) .addEqualityGroup(new PortFragmentId(DID1, PIDA, PN1), new PortFragmentId(DID1, PIDA, PN1)) .addEqualityGroup(new PortFragmentId(DID2, PIDA, PN1), new PortFragmentId(DID2, PIDA, PN1)) .addEqualityGroup(new PortFragmentId(DID1, PID, PN2), new PortFragmentId(DID1, PID, PN2)) .addEqualityGroup(new PortFragmentId(DID2, PID, PN2), new PortFragmentId(DID2, PID, PN2)) .addEqualityGroup(new PortFragmentId(DID1, PIDA, PN2), new PortFragmentId(DID1, PIDA, PN2)) .addEqualityGroup(new PortFragmentId(DID2, PIDA, PN2), new PortFragmentId(DID2, PIDA, PN2)) .testEquals(); }
public static Map<String, Properties> subProperties(Properties prop, String regex) { Map<String, Properties> subProperties = new HashMap<>(); Pattern pattern = Pattern.compile(regex); for (Map.Entry<Object, Object> entry : prop.entrySet()) { Matcher m = pattern.matcher(entry.getKey().toString()); if (m.find()) { String prefix = m.group(1); String suffix = m.group(2); if (!subProperties.containsKey(prefix)) { subProperties.put(prefix, new Properties()); } subProperties.get(prefix).put(suffix, entry.getValue()); } } return subProperties; }
@Test public void subProperties() { MetricsConfig config = new MetricsConfig(mMetricsProps); Properties properties = config.getProperties(); Map<String, Properties> sinkProps = MetricsConfig.subProperties(properties, MetricsSystem.SINK_REGEX); assertEquals(2, sinkProps.size()); assertTrue(sinkProps.containsKey("console")); assertTrue(sinkProps.containsKey("jmx")); Properties consoleProp = sinkProps.get("console"); assertEquals(3, consoleProp.size()); assertEquals("alluxio.metrics.sink.ConsoleSink", consoleProp.getProperty("class")); Properties jmxProp = sinkProps.get("jmx"); assertEquals(1, jmxProp.size()); assertEquals("alluxio.metrics.sink.JmxSink", jmxProp.getProperty("class")); }
public static Sensor getInvocationSensor( final Metrics metrics, final String sensorName, final String groupName, final String functionDescription ) { final Sensor sensor = metrics.sensor(sensorName); if (sensor.hasMetrics()) { return sensor; } final BiFunction<String, String, MetricName> metricNamer = (suffix, descPattern) -> { final String description = String.format(descPattern, functionDescription); return metrics.metricName(sensorName + "-" + suffix, groupName, description); }; sensor.add( metricNamer.apply("avg", AVG_DESC), new Avg() ); sensor.add( metricNamer.apply("max", MAX_DESC), new Max() ); sensor.add( metricNamer.apply("count", COUNT_DESC), new WindowedCount() ); sensor.add( metricNamer.apply("rate", RATE_DESC), new Rate(TimeUnit.SECONDS, new WindowedCount()) ); return sensor; }
@Test public void shouldReturnSensorOnSubsequentCalls() { // Given: when(sensor.hasMetrics()).thenReturn(true); // When: final Sensor result = FunctionMetrics .getInvocationSensor(metrics, SENSOR_NAME, GROUP_NAME, FUNC_NAME); // Then: assertThat(result, is(sensor)); }
public static void error() { err.println(); }
@Test public void errorTest2(){ Console.error("a", "b", "c"); Console.error((Object) "a", "b", "c"); }
public Map<MessageQueue, Long> parseOffsetTableFromBroker(Map<MessageQueue, Long> offsetTable, String namespace) { HashMap<MessageQueue, Long> newOffsetTable = new HashMap<>(offsetTable.size(), 1); if (StringUtils.isNotEmpty(namespace)) { for (Entry<MessageQueue, Long> entry : offsetTable.entrySet()) { MessageQueue queue = entry.getKey(); queue.setTopic(NamespaceUtil.withoutNamespace(queue.getTopic(), namespace)); newOffsetTable.put(queue, entry.getValue()); } } else { newOffsetTable.putAll(offsetTable); } return newOffsetTable; }
@Test public void testParseOffsetTableFromBroker() { Map<MessageQueue, Long> offsetTable = new HashMap<>(); offsetTable.put(new MessageQueue(), 0L); Map<MessageQueue, Long> actual = mqClientInstance.parseOffsetTableFromBroker(offsetTable, "defaultNamespace"); assertNotNull(actual); assertEquals(1, actual.size()); }
public static AbstractPredictor getCustomPredictor(DJLEndpoint endpoint) { String applicationPath = endpoint.getApplication(); // CV if (applicationPath.equals(IMAGE_CLASSIFICATION.getPath())) { return new CustomCvPredictor<Classifications>(endpoint); } else if (applicationPath.equals(OBJECT_DETECTION.getPath())) { return new CustomCvPredictor<DetectedObjects>(endpoint); } else if (SEMANTIC_SEGMENTATION.getPath().equals(applicationPath)) { return new CustomCvPredictor<CategoryMask>(endpoint); } else if (INSTANCE_SEGMENTATION.getPath().equals(applicationPath)) { return new CustomCvPredictor<DetectedObjects>(endpoint); } else if (POSE_ESTIMATION.getPath().equals(applicationPath)) { return new CustomCvPredictor<Joints>(endpoint); } else if (ACTION_RECOGNITION.getPath().equals(applicationPath)) { return new CustomCvPredictor<Classifications>(endpoint); } else if (WORD_RECOGNITION.getPath().equals(applicationPath)) { return new CustomCvPredictor<String>(endpoint); } else if (IMAGE_GENERATION.getPath().equals(applicationPath)) { return new CustomImageGenerationPredictor(endpoint); } else if (IMAGE_ENHANCEMENT.getPath().equals(applicationPath)) { return new CustomCvPredictor<Image>(endpoint); } // NLP if (FILL_MASK.getPath().equals(applicationPath)) { return new CustomNlpPredictor<String[]>(endpoint); } else if (QUESTION_ANSWER.getPath().equals(applicationPath)) { return new CustomQuestionAnswerPredictor(endpoint); } else if (TEXT_CLASSIFICATION.getPath().equals(applicationPath)) { return new CustomNlpPredictor<Classifications>(endpoint); } else if (SENTIMENT_ANALYSIS.getPath().equals(applicationPath)) { return new CustomNlpPredictor<Classifications>(endpoint); } else if (TOKEN_CLASSIFICATION.getPath().equals(applicationPath)) { return new CustomNlpPredictor<Classifications>(endpoint); } else if (WORD_EMBEDDING.getPath().equals(applicationPath)) { return new CustomWordEmbeddingPredictor(endpoint); } else if (TEXT_GENERATION.getPath().equals(applicationPath)) { return new CustomNlpPredictor<String>(endpoint); } else if (MACHINE_TRANSLATION.getPath().equals(applicationPath)) { return new CustomNlpPredictor<String>(endpoint); } else if (MULTIPLE_CHOICE.getPath().equals(applicationPath)) { return new CustomNlpPredictor<String>(endpoint); } else if (TEXT_EMBEDDING.getPath().equals(applicationPath)) { return new CustomNlpPredictor<NDArray>(endpoint); } // Tabular if (LINEAR_REGRESSION.getPath().equals(applicationPath)) { return new CustomTabularPredictor(endpoint); } else if (SOFTMAX_REGRESSION.getPath().equals(applicationPath)) { return new CustomTabularPredictor(endpoint); } // Audio if (Application.Audio.ANY.getPath().equals(applicationPath)) { return new CustomAudioPredictor(endpoint); } // Time Series if (FORECASTING.getPath().equals(applicationPath)) { return new CustomForecastingPredictor(endpoint); } throw new RuntimeCamelException("Application not supported: " + applicationPath); }
@Test void testGetCustomPredictor() { var modelName = "MyModel"; var translatorName = "MyTranslator"; // CV assertInstanceOf(CustomCvPredictor.class, getCustomPredictor(customEndpoint("cv/image_classification", modelName, translatorName))); assertInstanceOf(CustomCvPredictor.class, getCustomPredictor(customEndpoint("cv/object_detection", modelName, translatorName))); assertInstanceOf(CustomCvPredictor.class, getCustomPredictor(customEndpoint("cv/semantic_segmentation", modelName, translatorName))); assertInstanceOf(CustomCvPredictor.class, getCustomPredictor(customEndpoint("cv/instance_segmentation", modelName, translatorName))); assertInstanceOf(CustomCvPredictor.class, getCustomPredictor(customEndpoint("cv/pose_estimation", modelName, translatorName))); assertInstanceOf(CustomCvPredictor.class, getCustomPredictor(customEndpoint("cv/action_recognition", modelName, translatorName))); assertInstanceOf(CustomCvPredictor.class, getCustomPredictor(customEndpoint("cv/word_recognition", modelName, translatorName))); assertInstanceOf(CustomImageGenerationPredictor.class, getCustomPredictor(customEndpoint("cv/image_generation", modelName, translatorName))); assertInstanceOf(CustomCvPredictor.class, getCustomPredictor(customEndpoint("cv/image_enhancement", modelName, translatorName))); // NLP assertInstanceOf(CustomNlpPredictor.class, getCustomPredictor(customEndpoint("nlp/fill_mask", modelName, translatorName))); assertInstanceOf(CustomQuestionAnswerPredictor.class, getCustomPredictor(customEndpoint("nlp/question_answer", modelName, translatorName))); assertInstanceOf(CustomNlpPredictor.class, getCustomPredictor(customEndpoint("nlp/text_classification", modelName, translatorName))); assertInstanceOf(CustomNlpPredictor.class, getCustomPredictor(customEndpoint("nlp/sentiment_analysis", modelName, translatorName))); assertInstanceOf(CustomNlpPredictor.class, getCustomPredictor(customEndpoint("nlp/token_classification", modelName, translatorName))); assertInstanceOf(CustomWordEmbeddingPredictor.class, getCustomPredictor(customEndpoint("nlp/word_embedding", modelName, translatorName))); assertInstanceOf(CustomNlpPredictor.class, getCustomPredictor(customEndpoint("nlp/text_generation", modelName, translatorName))); assertInstanceOf(CustomNlpPredictor.class, getCustomPredictor(customEndpoint("nlp/machine_translation", modelName, translatorName))); assertInstanceOf(CustomNlpPredictor.class, getCustomPredictor(customEndpoint("nlp/multiple_choice", modelName, translatorName))); assertInstanceOf(CustomNlpPredictor.class, getCustomPredictor(customEndpoint("nlp/text_embedding", modelName, translatorName))); // Tabular assertInstanceOf(CustomTabularPredictor.class, getCustomPredictor(customEndpoint("tabular/linear_regression", modelName, translatorName))); assertInstanceOf(CustomTabularPredictor.class, getCustomPredictor(customEndpoint("tabular/softmax_regression", modelName, translatorName))); // Audio assertInstanceOf(CustomAudioPredictor.class, getCustomPredictor(customEndpoint("audio", modelName, translatorName))); // Time Series assertInstanceOf(CustomForecastingPredictor.class, getCustomPredictor(customEndpoint("timeseries/forecasting", modelName, translatorName))); }
public Predicate convert(ScalarOperator operator) { if (operator == null) { return null; } return operator.accept(this, null); }
@Test public void testLessThan() { ConstantOperator value = ConstantOperator.createInt(5); ScalarOperator op = new BinaryPredicateOperator(BinaryType.LT, F0, value); Predicate result = CONVERTER.convert(op); Assert.assertTrue(result instanceof LeafPredicate); LeafPredicate leafPredicate = (LeafPredicate) result; Assert.assertTrue(leafPredicate.function() instanceof LessThan); Assert.assertEquals(5, leafPredicate.literals().get(0)); }
public static Optional<String> finishUpdateCheck(Future<Optional<String>> updateMessageFuture) { if (updateMessageFuture.isDone()) { try { return updateMessageFuture.get(); } catch (InterruptedException | ExecutionException ex) { // No need to restore the interrupted status. The intention here is to silently consume any // kind of error } } updateMessageFuture.cancel(true); return Optional.empty(); }
@Test public void testFinishUpdateCheck_notDone() { @SuppressWarnings("unchecked") Future<Optional<String>> updateCheckFuture = Mockito.mock(Future.class); Mockito.when(updateCheckFuture.isDone()).thenReturn(false); Optional<String> result = UpdateChecker.finishUpdateCheck(updateCheckFuture); assertThat(result).isEmpty(); }
@AfterStartUp(order = AfterStartUp.BEFORE_TRANSPORT_SERVICE) public void init() { List<LwM2MModelConfig> models = modelStore.getAll(); log.debug("Fetched model configs: {}", models); currentModelConfigs = models.stream() .collect(Collectors.toConcurrentMap(LwM2MModelConfig::getEndpoint, m -> m, (existing, replacement) -> existing)); }
@Test void testInitWithDuplicatedModels() { LwM2MModelConfig config = new LwM2MModelConfig("urn:imei:951358811362976"); List<LwM2MModelConfig> models = List.of(config, config); willReturn(models).given(modelStore).getAll(); service.init(); assertThat(service.currentModelConfigs).containsExactlyEntriesOf(Map.of(config.getEndpoint(), config)); }
public static Map<Type, Type> get(Type type) { return CACHE.computeIfAbsent(type, (key) -> createTypeMap(type)); }
@Test public void getTypeArgumentTest(){ final Map<Type, Type> typeTypeMap = ActualTypeMapperPool.get(FinalClass.class); typeTypeMap.forEach((key, value)->{ if("A".equals(key.getTypeName())){ assertEquals(Character.class, value); } else if("B".equals(key.getTypeName())){ assertEquals(Boolean.class, value); } else if("C".equals(key.getTypeName())){ assertEquals(String.class, value); } else if("D".equals(key.getTypeName())){ assertEquals(Double.class, value); } else if("E".equals(key.getTypeName())){ assertEquals(Integer.class, value); } }); }
public static ImmutableList<SbeField> generateFields(Ir ir, IrOptions irOptions) { ImmutableList.Builder<SbeField> fields = ImmutableList.builder(); TokenIterator iterator = getIteratorForMessage(ir, irOptions); while (iterator.hasNext()) { Token token = iterator.next(); switch (token.signal()) { case BEGIN_FIELD: fields.add(processPrimitive(iterator)); break; default: // TODO(https://github.com/apache/beam/issues/21102): Support remaining field types break; } } return fields.build(); }
@Test public void testGenerateFieldsWithMessageName() throws Exception { Ir ir = getIr(OnlyPrimitivesMultiMessage.RESOURCE_PATH); IrOptions msg1Opts = IrOptions.builder().setMessageName(Primitives1.NAME).build(); IrOptions msg2Opts = IrOptions.builder().setMessageName(Primitives2.NAME).build(); ImmutableList<SbeField> actual1 = IrFieldGenerator.generateFields(ir, msg1Opts); ImmutableList<SbeField> actual2 = IrFieldGenerator.generateFields(ir, msg2Opts); assertEquals(Primitives1.FIELDS, actual1); assertEquals(Primitives2.FIELDS, actual2); }
public static String getJwt(final String authorizationHeader) { return authorizationHeader.replace(TOKEN_PREFIX, ""); }
@Test void testGetJwt_WithEmptyHeader() { // Given String authorizationHeader = ""; // When String jwt = Token.getJwt(authorizationHeader); // Then assertEquals("", jwt); }
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final byte[] payload = rawMessage.getPayload(); final JsonNode event; try { event = objectMapper.readTree(payload); if (event == null || event.isMissingNode()) { throw new IOException("null result"); } } catch (IOException e) { LOG.error("Couldn't decode raw message {}", rawMessage); return null; } return parseEvent(event); }
@Test public void decodeMessagesHandlesFilebeatMessages() throws Exception { final Message message = codec.decode(messageFromJson("filebeat.json")); assertThat(message).isNotNull(); assertThat(message.getMessage()).isEqualTo("TEST"); assertThat(message.getSource()).isEqualTo("example.local"); assertThat(message.getTimestamp()).isEqualTo(new DateTime(2016, 4, 1, 0, 0, DateTimeZone.UTC)); assertThat(message.getField("beats_type")).isEqualTo("filebeat"); assertThat(message.getField("filebeat_source")).isEqualTo("/tmp/test.log"); assertThat(message.getField("filebeat_input_type")).isEqualTo("log"); assertThat(message.getField("filebeat_count")).isEqualTo(1); assertThat(message.getField("filebeat_offset")).isEqualTo(0); assertThat(message.getField(Message.FIELD_GL2_SOURCE_COLLECTOR)).isEqualTo("1234-5678-1234-5678"); assertThat(message.getField("filebeat_message")).isNull(); //should not be duplicated from "message" assertThat(message.getField("filebeat_" + Message.FIELD_GL2_SOURCE_COLLECTOR)).isNull(); @SuppressWarnings("unchecked") final List<String> tags = (List<String>) message.getField("filebeat_tags"); assertThat(tags).containsOnly("foobar", "test"); }
@Override public JavaFileObject createSourceFile(CharSequence name, Element... originatingElements) throws IOException { return new FormattingJavaFileObject( delegate.createSourceFile(name, originatingElements), formatter, messager); }
@Test public void formatsFile() throws IOException { FormattingFiler formattingFiler = new FormattingFiler(new FakeFiler()); JavaFileObject sourceFile = formattingFiler.createSourceFile("foo.Bar"); try (Writer writer = sourceFile.openWriter()) { writer.write("package foo;class Bar{private String baz;\n\n\n\n}"); } assertThat(sourceFile.getCharContent(false).toString()) .isEqualTo( Joiner.on('\n') .join( "package foo;", "", "class Bar {", " private String baz;", "}", "")); // trailing newline }
public String getType() { return type; }
@Test void testDeserialize() throws IOException { String testChecker = "{\"type\":\"TEST\",\"testValue\":\"\"}"; TestChecker actual = objectMapper.readValue(testChecker, TestChecker.class); assertEquals("", actual.getTestValue()); assertEquals(TestChecker.TYPE, actual.getType()); }
@NonNull static LinkNavigation findPostNavigation(List<String> postNames, String target) { Assert.notNull(target, "Target post name must not be null"); for (int i = 0; i < postNames.size(); i++) { var item = postNames.get(i); if (target.equals(item)) { var prevLink = (i > 0) ? postNames.get(i - 1) : null; var nextLink = (i < postNames.size() - 1) ? postNames.get(i + 1) : null; return new LinkNavigation(prevLink, target, nextLink); } } return new LinkNavigation(null, target, null); }
@Test void postPreviousNextPair() { List<String> postNames = new ArrayList<>(); for (int i = 0; i < 10; i++) { postNames.add("post-" + i); } // post-0, post-1, post-2 var previousNextPair = PostFinderImpl.findPostNavigation(postNames, "post-0"); assertThat(previousNextPair.prev()).isNull(); assertThat(previousNextPair.next()).isEqualTo("post-1"); previousNextPair = PostFinderImpl.findPostNavigation(postNames, "post-1"); assertThat(previousNextPair.prev()).isEqualTo("post-0"); assertThat(previousNextPair.next()).isEqualTo("post-2"); // post-1, post-2, post-3 previousNextPair = PostFinderImpl.findPostNavigation(postNames, "post-2"); assertThat(previousNextPair.prev()).isEqualTo("post-1"); assertThat(previousNextPair.next()).isEqualTo("post-3"); // post-7, post-8, post-9 previousNextPair = PostFinderImpl.findPostNavigation(postNames, "post-8"); assertThat(previousNextPair.prev()).isEqualTo("post-7"); assertThat(previousNextPair.next()).isEqualTo("post-9"); previousNextPair = PostFinderImpl.findPostNavigation(postNames, "post-9"); assertThat(previousNextPair.prev()).isEqualTo("post-8"); assertThat(previousNextPair.next()).isNull(); }