focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static List<Path> getQualifiedRemoteProvidedLibDirs( org.apache.flink.configuration.Configuration configuration, YarnConfiguration yarnConfiguration) throws IOException { return getRemoteSharedLibPaths( configuration, pathStr -> { final Path path = new Path(pathStr); return path.getFileSystem(yarnConfiguration).makeQualified(path); }); }
@Test void testSharedLibWithNonQualifiedPath() throws Exception { final String sharedLibPath = "/flink/sharedLib"; final String nonQualifiedPath = "hdfs://" + sharedLibPath; final String defaultFs = "hdfs://localhost:9000"; final String qualifiedPath = defaultFs + sharedLibPath; final Configuration flinkConfig = new Configuration(); flinkConfig.set( YarnConfigOptions.PROVIDED_LIB_DIRS, Collections.singletonList(nonQualifiedPath)); final YarnConfiguration yarnConfig = new YarnConfiguration(); yarnConfig.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, defaultFs); final List<org.apache.hadoop.fs.Path> sharedLibs = Utils.getQualifiedRemoteProvidedLibDirs(flinkConfig, yarnConfig); assertThat(sharedLibs).hasSize(1); assertThat(sharedLibs.get(0).toUri()).hasToString(qualifiedPath); }
@Override public ParamCheckResponse checkParamInfoList(List<ParamInfo> paramInfos) { ParamCheckResponse paramCheckResponse = new ParamCheckResponse(); if (paramInfos == null) { paramCheckResponse.setSuccess(true); return paramCheckResponse; } for (ParamInfo paramInfo : paramInfos) { paramCheckResponse = checkParamInfoFormat(paramInfo); if (!paramCheckResponse.isSuccess()) { return paramCheckResponse; } } paramCheckResponse.setSuccess(true); return paramCheckResponse; }
@Test void testCheckParamInfoForServiceName() { ParamInfo paramInfo = new ParamInfo(); ArrayList<ParamInfo> paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); // Max Length String serviceName = buildStringLength(513); paramInfo.setServiceName(serviceName); ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); assertEquals("Param 'serviceName' is illegal, the param length should not exceed 512.", actual.getMessage()); // Pattern paramInfo.setServiceName("@hsbfkj$@@!#khdkad啊"); actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); assertEquals("Param 'serviceName' is illegal, illegal characters should not appear in the param.", actual.getMessage()); // Success paramInfo.setServiceName("com.aaa@bbb#_{}-b:v1.2.2"); actual = paramChecker.checkParamInfoList(paramInfos); assertTrue(actual.isSuccess()); }
public static ParseResult parse(String text) { Map<String, String> localProperties = new HashMap<>(); String intpText = ""; String scriptText = null; Matcher matcher = REPL_PATTERN.matcher(text); if (matcher.find()) { String headingSpace = matcher.group(1); intpText = matcher.group(2); int startPos = headingSpace.length() + intpText.length() + 1; if (startPos < text.length() && text.charAt(startPos) == '(') { startPos = parseLocalProperties(text, startPos, localProperties); } scriptText = text.substring(startPos); } else { intpText = ""; scriptText = text; } return new ParseResult(intpText, removeLeadingWhiteSpaces(scriptText), localProperties); }
@Test void testParagraphTextLocalPropertyNoValueNoText() { ParagraphTextParser.ParseResult parseResult = ParagraphTextParser.parse("%spark.pyspark(pool)"); assertEquals("spark.pyspark", parseResult.getIntpText()); assertEquals(1, parseResult.getLocalProperties().size()); assertEquals("pool", parseResult.getLocalProperties().get("pool")); assertEquals("", parseResult.getScriptText()); }
public static <K> KTableHolder<K> build( final KTableHolder<K> left, final KTableHolder<K> right, final TableTableJoin<K> join ) { final LogicalSchema leftSchema; final LogicalSchema rightSchema; if (join.getJoinType().equals(RIGHT)) { leftSchema = right.getSchema(); rightSchema = left.getSchema(); } else { leftSchema = left.getSchema(); rightSchema = right.getSchema(); } final JoinParams joinParams = JoinParamsFactory .create(join.getKeyColName(), leftSchema, rightSchema); final KTable<K, GenericRow> result; switch (join.getJoinType()) { case INNER: result = left.getTable().join(right.getTable(), joinParams.getJoiner()); break; case LEFT: result = left.getTable().leftJoin(right.getTable(), joinParams.getJoiner()); break; case RIGHT: result = right.getTable().leftJoin(left.getTable(), joinParams.getJoiner()); break; case OUTER: result = left.getTable().outerJoin(right.getTable(), joinParams.getJoiner()); break; default: throw new IllegalStateException("invalid join type: " + join.getJoinType()); } return KTableHolder.unmaterialized( result, joinParams.getSchema(), left.getExecutionKeyFactory()); }
@Test public void shouldReturnCorrectLegacySchema() { // Given: join = new TableTableJoin<>( new ExecutionStepPropertiesV1(ctx), JoinType.INNER, ColumnName.of(LEGACY_KEY_COL), left, right ); // When: final KTableHolder<Struct> result = join.build(planBuilder, planInfo); // Then: assertThat( result.getSchema(), is(LogicalSchema.builder() .keyColumn(ROWKEY_NAME, SqlTypes.STRING) .valueColumns(LEFT_SCHEMA.value()) .valueColumns(RIGHT_SCHEMA.value()) .valueColumn(ROWKEY_NAME, SqlTypes.STRING) .build()) ); }
public static String getFullGcsPath(String... pathParts) { checkArgument(pathParts.length != 0, "Must provide at least one path part"); checkArgument( stream(pathParts).noneMatch(Strings::isNullOrEmpty), "No path part can be null or empty"); return String.format("gs://%s", String.join("/", pathParts)); }
@Test public void testGetFullGcsPath() { assertThat(ArtifactUtils.getFullGcsPath("bucket", "dir1", "dir2", "file")) .isEqualTo("gs://bucket/dir1/dir2/file"); }
public List<KinesisRecord> apply(List<KinesisRecord> records, ShardCheckpoint checkpoint) { List<KinesisRecord> filteredRecords = newArrayList(); for (KinesisRecord record : records) { if (checkpoint.isBeforeOrAt(record)) { filteredRecords.add(record); } } return filteredRecords; }
@Test public void shouldFilterOutRecordsBeforeOrAtCheckpoint() { when(checkpoint.isBeforeOrAt(record1)).thenReturn(false); when(checkpoint.isBeforeOrAt(record2)).thenReturn(true); when(checkpoint.isBeforeOrAt(record3)).thenReturn(true); when(checkpoint.isBeforeOrAt(record4)).thenReturn(false); when(checkpoint.isBeforeOrAt(record5)).thenReturn(true); List<KinesisRecord> records = Lists.newArrayList(record1, record2, record3, record4, record5); RecordFilter underTest = new RecordFilter(); List<KinesisRecord> retainedRecords = underTest.apply(records, checkpoint); Assertions.assertThat(retainedRecords).containsOnly(record2, record3, record5); }
@Override public String getColumnName(int columnIndex) { return _columnNamesArray.get(columnIndex).asText(); }
@Test public void testGetColumnName() { // Run the test final String result = _resultTableResultSetUnderTest.getColumnName(0); // Verify the results assertEquals("column1", result); }
public static L3ModificationInstruction modArpSha(MacAddress addr) { checkNotNull(addr, "Src l3 ARP address cannot be null"); return new ModArpEthInstruction(L3SubType.ARP_SHA, addr); }
@Test public void testModArpShaMethod() { final Instruction instruction = Instructions.modArpSha(mac1); final L3ModificationInstruction.ModArpEthInstruction modArpEthInstruction = checkAndConvert(instruction, Instruction.Type.L3MODIFICATION, L3ModificationInstruction.ModArpEthInstruction.class); assertThat(modArpEthInstruction.subtype(), is(L3ModificationInstruction.L3SubType.ARP_SHA)); assertThat(modArpEthInstruction.mac(), is(mac1)); }
public static <T> Map<String, T> translateDeprecatedConfigs(Map<String, T> configs, String[][] aliasGroups) { return translateDeprecatedConfigs(configs, Stream.of(aliasGroups) .collect(Collectors.toMap(x -> x[0], x -> Stream.of(x).skip(1).collect(Collectors.toList())))); }
@Test public void testMultipleDeprecations() { Map<String, String> config = new HashMap<>(); config.put("foo.bar.deprecated", "derp"); config.put("foo.bar.even.more.deprecated", "very old configuration"); Map<String, String> newConfig = ConfigUtils.translateDeprecatedConfigs(config, new String[][]{ {"foo.bar", "foo.bar.deprecated", "foo.bar.even.more.deprecated"} }); assertNotNull(newConfig); assertEquals("derp", newConfig.get("foo.bar")); assertNull(newConfig.get("foo.bar.deprecated")); assertNull(newConfig.get("foo.bar.even.more.deprecated")); }
public static WorkerIdentity fromProto(alluxio.grpc.WorkerIdentity proto) throws ProtoParsingException { return Parsers.fromProto(proto); }
@Test public void parserFromProto() throws Exception { WorkerIdentity identity = WorkerIdentity.Parsers.fromProto( alluxio.grpc.WorkerIdentity.newBuilder() .setVersion(0) .setIdentifier(ByteString.copyFrom(Longs.toByteArray(1L))) .build()); assertEquals(new WorkerIdentity(Longs.toByteArray(1L), 0), identity); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { if(containerService.isContainer(file)) { final PathAttributes attributes = new PathAttributes(); final CloudBlobContainer container = session.getClient().getContainerReference(containerService.getContainer(file).getName()); container.downloadAttributes(null, null, context); final BlobContainerProperties properties = container.getProperties(); attributes.setETag(properties.getEtag()); attributes.setModificationDate(properties.getLastModified().getTime()); return attributes; } if(file.isFile() || file.isPlaceholder()) { try { final CloudBlob blob = session.getClient().getContainerReference(containerService.getContainer(file).getName()) .getBlobReferenceFromServer(containerService.getKey(file)); final BlobRequestOptions options = new BlobRequestOptions(); blob.downloadAttributes(AccessCondition.generateEmptyCondition(), options, context); return this.toAttributes(blob); } catch(StorageException e) { switch(e.getHttpStatusCode()) { case HttpStatus.SC_NOT_FOUND: if(file.isPlaceholder()) { // Ignore failure and look for common prefix break; } default: throw e; } } } // Check for common prefix try { new AzureObjectListService(session, context).list(file, new CancellingListProgressListener()); return PathAttributes.EMPTY; } catch(ListCanceledException l) { // Found common prefix return PathAttributes.EMPTY; } } catch(StorageException e) { throw new AzureExceptionMappingService().map("Failure to read attributes of {0}", e, file); } catch(URISyntaxException e) { throw new NotfoundException(e.getMessage(), e); } }
@Test(expected = NotfoundException.class) public void testNotFound() throws Exception { final Path container = new Path(StringUtils.lowerCase(new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.directory, Path.Type.volume)); final AzureAttributesFinderFeature f = new AzureAttributesFinderFeature(session, null); f.find(new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file))); }
public static RawTransaction decode(final String hexTransaction) { final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction); TransactionType transactionType = getTransactionType(transaction); switch (transactionType) { case EIP1559: return decodeEIP1559Transaction(transaction); case EIP4844: return decodeEIP4844Transaction(transaction); case EIP2930: return decodeEIP2930Transaction(transaction); default: return decodeLegacyTransaction(transaction); } }
@Test public void testRSize31() throws Exception { String hexTransaction = "0xf883370183419ce09433c98f20dd73d7bb1d533c4aa3371f2b30c6ebde80a45093dc7d00000000000000000000000000000000000000000000000000000000000000351c9fb90996c836fb34b782ee3d6efa9e2c79a75b277c014e353b51b23b00524d2da07435ebebca627a51a863bf590aff911c4746ab8386a0477c8221bb89671a5d58"; RawTransaction result = TransactionDecoder.decode(hexTransaction); SignedRawTransaction signedResult = (SignedRawTransaction) result; assertEquals("0x1b609b03e2e9b0275a61fa5c69a8f32550285536", signedResult.getFrom()); }
public static <K, V> PerKey<K, V> perKey() { return new AutoValue_ApproximateCountDistinct_PerKey.Builder<K, V>() .setPrecision(HllCount.DEFAULT_PRECISION) .build(); }
@Test @Category(NeedsRunner.class) public void testStandardTypesPerKeyForBytes() { List<KV<Integer, byte[]>> bytes = new ArrayList<>(); for (int i = 0; i < 3; i++) { for (int k : INTS1) { bytes.add(KV.of(i, ByteBuffer.allocate(4).putInt(k).array())); } } PCollection<KV<Integer, Long>> result = p.apply("BytesHLL", Create.of(bytes)).apply(ApproximateCountDistinct.perKey()); PAssert.that(result) .containsInAnyOrder( ImmutableList.of( KV.of(0, INTS1_ESTIMATE), KV.of(1, INTS1_ESTIMATE), KV.of(2, INTS1_ESTIMATE))); p.run(); }
@Override public void updateUserPassword(String username, String password) { try { jt.update("UPDATE users SET password = ? WHERE username=?", password, username); } catch (CannotGetJdbcConnectionException e) { LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e); throw e; } }
@Test void testUpdateUserPassword() { externalUserPersistService.updateUserPassword("username", "password"); String sql = "UPDATE users SET password = ? WHERE username=?"; Mockito.verify(jdbcTemplate).update(sql, "password", "username"); }
@Override protected SubChannelCopy pick(final List<SubChannelCopy> list) { if (CollectionUtils.isEmpty(list)) { return null; } if (list.size() == 1) { return list.get(0); } int index = getRandomIndexByWeight(list); return list.get(index); }
@Test public void testPick() { SubChannelCopy firstSubChannelCopy = mock(SubChannelCopy.class); SubChannelCopy secondSubChannelCopy = mock(SubChannelCopy.class); when(secondSubChannelCopy.getWeight()).thenReturn(10); List<SubChannelCopy> list = Arrays.asList(firstSubChannelCopy, secondSubChannelCopy); assertNotNull(randomPicker.pick(list)); assertEquals(firstSubChannelCopy, randomPicker.pick(Collections.singletonList(firstSubChannelCopy))); assertEquals(firstSubChannelCopy, randomPicker.pick(Arrays.asList(firstSubChannelCopy, firstSubChannelCopy))); assertNull(randomPicker.pick(null)); }
public Principal getOriginalPrincipal() { return principal; }
@Test public void shouldReturnOriginalPrincipal() { assertThat(wrappedKsqlPrincipal.getOriginalPrincipal(), is(ksqlPrincipal)); assertThat(wrappedOtherPrincipal.getOriginalPrincipal(), is(otherPrincipal)); }
protected boolean isSimpleTypeNode(JsonNode jsonNode) { if (!jsonNode.isObject()) { return false; } ObjectNode objectNode = (ObjectNode) jsonNode; int numberOfFields = objectNode.size(); return numberOfFields == 1 && objectNode.has(VALUE); }
@Test public void isSimpleTypeNode_emptyNode() { assertThat(expressionEvaluator.isSimpleTypeNode(new ArrayNode(factory))).isFalse(); }
@Override public void trash(final Local file) throws LocalAccessDeniedException { synchronized(NSWorkspace.class) { if(log.isDebugEnabled()) { log.debug(String.format("Move %s to Trash", file)); } // Asynchronous operation. 0 if the operation is performed synchronously and succeeds, and a positive // integer if the operation is performed asynchronously and succeeds if(!workspace.performFileOperation( NSWorkspace.RecycleOperation, new NFDNormalizer().normalize(file.getParent().getAbsolute()).toString(), StringUtils.EMPTY, NSArray.arrayWithObject(new NFDNormalizer().normalize(file.getName()).toString()))) { throw new LocalAccessDeniedException(String.format("Failed to move %s to Trash", file.getName())); } } }
@Test public void testTrash() throws Exception { Local l = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); new DefaultLocalTouchFeature().touch(l); assertTrue(l.exists()); new WorkspaceTrashFeature().trash(l); assertFalse(l.exists()); }
@Override public boolean match(Message msg, StreamRule rule) { final boolean inverted = rule.getInverted(); final Object field = msg.getField(rule.getField()); if (field != null) { final String value = field.toString(); return inverted ^ value.contains(rule.getValue()); } else { return inverted; } }
@Test public void testInvertedNullFieldShouldMatch() { final String fieldName = "nullfield"; rule.setField(fieldName); rule.setInverted(true); msg.addField(fieldName, null); final StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, rule)); }
@SuppressWarnings("") @Nonnull public static Number parse(@Nonnull String input) { String text = input.trim().toUpperCase(); Number value; if (text.indexOf('.') > 0) { value = parseDecimal(text); } else { if (text.endsWith("L") && text.startsWith("0X")) { String substring = text.substring(2, text.indexOf("L")); if (substring.isEmpty()) return 0L; value = Long.parseLong(substring, 16); } else if (text.endsWith("L")) value = Long.parseLong(text.substring(0, text.indexOf("L"))); else if (text.startsWith("0X")) { String substring = text.substring(2); if (substring.isEmpty()) return 0; value = Integer.parseInt(substring, 16); } else if (text.endsWith("F")) value = Float.parseFloat(text.substring(0, text.indexOf("F"))); else if (text.endsWith("D") || text.contains(".")) value = Double.parseDouble(text.substring(0, text.indexOf("D"))); else value = Integer.parseInt(text); } return value; }
@Test void testParse() { assertEquals(0, NumberUtil.parse("0")); assertEquals(0L, NumberUtil.parse("0L")); assertEquals(0D, NumberUtil.parse("0.0")); assertEquals(0D, NumberUtil.parse("0.0d")); assertEquals(0D, NumberUtil.parse("0.0D")); assertEquals(0F, NumberUtil.parse("0.0f")); assertEquals(0F, NumberUtil.parse("0.0F")); assertEquals(0D, NumberUtil.parse("0.")); assertEquals(0F, NumberUtil.parse("0.F")); assertEquals(0, NumberUtil.parse("0x")); assertEquals(0L, NumberUtil.parse("0xL")); assertEquals(0, NumberUtil.parse("0x0")); assertEquals(0L, NumberUtil.parse("0x0L")); }
public boolean isIn(Number toEvaluate) { switch (closure) { case OPEN_OPEN: return isInsideOpenOpen(toEvaluate); case OPEN_CLOSED: return isInsideOpenClosed(toEvaluate); case CLOSED_OPEN: return isInsideClosedOpen(toEvaluate); case CLOSED_CLOSED: return isInsideClosedClosed(toEvaluate); default: throw new IllegalArgumentException("Unexpected closure: " + closure); } }
@Test void isIn() { KiePMMLInterval kiePMMLInterval = new KiePMMLInterval(20, 40, CLOSURE.OPEN_OPEN); assertThat(kiePMMLInterval.isIn(30)).isTrue(); assertThat(kiePMMLInterval.isIn(10)).isFalse(); assertThat(kiePMMLInterval.isIn(20)).isFalse(); assertThat(kiePMMLInterval.isIn(40)).isFalse(); assertThat(kiePMMLInterval.isIn(50)).isFalse(); kiePMMLInterval = new KiePMMLInterval(20, 40, CLOSURE.OPEN_CLOSED); assertThat(kiePMMLInterval.isIn(30)).isTrue(); assertThat(kiePMMLInterval.isIn(10)).isFalse(); assertThat(kiePMMLInterval.isIn(20)).isFalse(); assertThat(kiePMMLInterval.isIn(40)).isTrue(); assertThat(kiePMMLInterval.isIn(50)).isFalse(); kiePMMLInterval = new KiePMMLInterval(20, 40, CLOSURE.CLOSED_OPEN); assertThat(kiePMMLInterval.isInsideClosedOpen(30)).isTrue(); assertThat(kiePMMLInterval.isInsideClosedOpen(10)).isFalse(); assertThat(kiePMMLInterval.isInsideClosedOpen(20)).isTrue(); assertThat(kiePMMLInterval.isInsideClosedOpen(40)).isFalse(); assertThat(kiePMMLInterval.isInsideClosedOpen(50)).isFalse(); kiePMMLInterval = new KiePMMLInterval(20, 40, CLOSURE.CLOSED_CLOSED); assertThat(kiePMMLInterval.isIn(30)).isTrue(); assertThat(kiePMMLInterval.isIn(10)).isFalse(); assertThat(kiePMMLInterval.isIn(20)).isTrue(); assertThat(kiePMMLInterval.isIn(40)).isTrue(); assertThat(kiePMMLInterval.isIn(50)).isFalse(); }
@Override public Map<String, String> evaluate(FunctionArgs args, EvaluationContext context) { final String value = valueParam.required(args, context); if (Strings.isNullOrEmpty(value)) { return Collections.emptyMap(); } final CharMatcher kvPairsMatcher = splitParam.optional(args, context).orElse(CharMatcher.whitespace()); final CharMatcher kvDelimMatcher = valueSplitParam.optional(args, context).orElse(CharMatcher.anyOf("=")); Splitter outerSplitter = Splitter.on(DelimiterCharMatcher.withQuoteHandling(kvPairsMatcher)) .omitEmptyStrings() .trimResults(); final Splitter entrySplitter = Splitter.on(kvDelimMatcher) .omitEmptyStrings() .limit(2) .trimResults(); return new MapSplitter(outerSplitter, entrySplitter, ignoreEmptyValuesParam.optional(args, context).orElse(true), trimCharactersParam.optional(args, context).orElse(CharMatcher.none()), trimValueCharactersParam.optional(args, context).orElse(CharMatcher.none()), allowDupeKeysParam.optional(args, context).orElse(true), duplicateHandlingParam.optional(args, context).orElse(TAKE_FIRST)) .split(value); }
@Test void testDisableDuplicateKeys() { final Map<String, Expression> arguments = Map.of("value", valueExpression, "allow_dup_keys", new BooleanExpression(new CommonToken(0), false)); Assertions.assertThrows(IllegalArgumentException.class, () -> classUnderTest.evaluate(new FunctionArgs(classUnderTest, arguments), evaluationContext)); }
@Override public void execute(Runnable runnable) { // run the task synchronously runnable.run(); }
@Test public void testSynchronousExecutorService() { String name1 = Thread.currentThread().getName(); ExecutorService service = new SynchronousExecutorService(); service.execute(new Runnable() { public void run() { invoked = true; name2 = Thread.currentThread().getName(); } }); assertTrue(invoked, "Should have been invoked"); assertEquals(name1, name2, "Should use same thread"); }
public static VersionedBytesStoreSupplier persistentVersionedKeyValueStore(final String name, final Duration historyRetention) { Objects.requireNonNull(name, "name cannot be null"); final String hrMsgPrefix = prepareMillisCheckFailMsgPrefix(historyRetention, "historyRetention"); final long historyRetentionMs = validateMillisecondDuration(historyRetention, hrMsgPrefix); if (historyRetentionMs < 0L) { throw new IllegalArgumentException("historyRetention cannot be negative"); } return new RocksDbVersionedKeyValueBytesStoreSupplier(name, historyRetentionMs); }
@Test public void shouldThrowIfPersistentVersionedKeyValueStoreSegmentIntervalIsZeroOrNegative() { Exception e = assertThrows(IllegalArgumentException.class, () -> Stores.persistentVersionedKeyValueStore("anyName", ZERO, ZERO)); assertEquals("segmentInterval cannot be zero or negative", e.getMessage()); e = assertThrows(IllegalArgumentException.class, () -> Stores.persistentVersionedKeyValueStore("anyName", ZERO, ofMillis(-1))); assertEquals("segmentInterval cannot be zero or negative", e.getMessage()); }
@Override public void register(String path, ServiceRecord record) throws IOException { op(path, record, addRecordCommand); }
@Test public void testAAAALookup() throws Exception { ServiceRecord record = getMarshal().fromBytes("somepath", CONTAINER_RECORD.getBytes()); getRegistryDNS().register( "/registry/users/root/services/org-apache-slider/test1/components/" + "ctr-e50-1451931954322-0016-01-000002", record); // start assessing whether correct records are available List<Record> recs = assertDNSQuery( "ctr-e50-1451931954322-0016-01-000002.dev.test.", Type.AAAA, 1); assertEquals("wrong result", "172.17.0.19", ((AAAARecord) recs.get(0)).getAddress().getHostAddress()); recs = assertDNSQuery("httpd-1.test1.root.dev.test.", Type.AAAA, 1); assertTrue("not an ARecord", recs.get(0) instanceof AAAARecord); }
public static String md5Hex (String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return hex (md.digest(message.getBytes("CP1252"))); } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return null; }
@Test public void testMd5Hex() { String md5 = HashUtil.md5Hex("stevehu@gmail.com"); Assert.assertEquals(md5, "417bed6d9644f12d8bc709059c225c27"); }
public void clear() { mUserProps.clear(); mSources.clear(); }
@Test public void clear() { mProperties.put(mKeyWithValue, "ignored1", Source.RUNTIME); mProperties.put(mKeyWithoutValue, "ignored2", Source.RUNTIME); mProperties.clear(); assertEquals(null, mProperties.get(mKeyWithoutValue)); assertEquals("value", mProperties.get(mKeyWithValue)); }
public static DeviceKey createDeviceKeyUsingCommunityName(DeviceKeyId id, String label, String name) { DefaultAnnotations annotations = builder().set(AnnotationKeys.NAME, name).build(); return new DeviceKey(id, label, Type.COMMUNITY_NAME, annotations); }
@Test public void testCreateDeviceKeyUsingCommunityName() { DeviceKeyId deviceKeyId = DeviceKeyId.deviceKeyId(deviceKeyIdValue); DeviceKey deviceKey = DeviceKey.createDeviceKeyUsingCommunityName(deviceKeyId, deviceKeyLabel, deviceKeySnmpName); assertNotNull("The deviceKey should not be null.", deviceKey); assertEquals("The deviceKeyId should match as expected", deviceKeyId, deviceKey.deviceKeyId()); assertEquals("The label should match as expected", deviceKeyLabel, deviceKey.label()); assertEquals("The type should match as expected", DeviceKey.Type.COMMUNITY_NAME, deviceKey.type()); CommunityName communityName = deviceKey.asCommunityName(); assertNotNull("The communityName should not be null.", communityName); assertEquals("The name should match as expected", deviceKeySnmpName, communityName.name()); }
public String getHost() { return host; }
@Test public void testGetHost() { shenyuRequestLog.setHost("test"); Assertions.assertEquals(shenyuRequestLog.getHost(), "test"); }
@Deprecated public static BoundedSource<Long> upTo(long numElements) { checkArgument( numElements >= 0, "numElements (%s) must be greater than or equal to 0", numElements); return new BoundedCountingSource(0, numElements); }
@Test @Category(NeedsRunner.class) public void testBoundedSource() { long numElements = 1000; PCollection<Long> input = p.apply(Read.from(CountingSource.upTo(numElements))); addCountingAsserts(input, numElements); p.run(); }
@Override public void verify(X509Certificate certificate, Date date) { logger.debug("Verifying {} issued by {}", certificate.getSubjectX500Principal(), certificate.getIssuerX500Principal()); // Create trustAnchors final Set<TrustAnchor> trustAnchors = getTrusted().stream().map( c -> new TrustAnchor(c, null) ).collect(Collectors.toSet()); if (trustAnchors.isEmpty()) { throw new VerificationException("No trust anchors available"); } // Create the selector that specifies the starting certificate final X509CertSelector selector = new X509CertSelector(); selector.setCertificate(certificate); // Configure the PKIX certificate builder algorithm parameters try { final PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector); // Set assume date if (date != null) { pkixParams.setDate(date); } // Add cert store with certificate to check pkixParams.addCertStore(CertStore.getInstance( "Collection", new CollectionCertStoreParameters(ImmutableList.of(certificate)), "BC")); // Add cert store with intermediates pkixParams.addCertStore(CertStore.getInstance( "Collection", new CollectionCertStoreParameters(getIntermediates()), "BC")); // Add cert store with CRLs pkixParams.addCertStore(CertStore.getInstance( "Collection", new CollectionCertStoreParameters(getCRLs()), "BC")); // Toggle to check revocation list pkixParams.setRevocationEnabled(checkRevocation()); // Build and verify the certification chain final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); builder.build(pkixParams); } catch (CertPathBuilderException e) { throw new VerificationException( String.format("Invalid certificate %s issued by %s", certificate.getSubjectX500Principal(), certificate.getIssuerX500Principal() ), e ); } catch (GeneralSecurityException e) { throw new CryptoException( String.format("Could not verify certificate %s issued by %s", certificate.getSubjectX500Principal(), certificate.getIssuerX500Principal() ), e ); } }
@Test public void shouldThrowExceptionIfCertificateIsRevoked() { thrown.expect(VerificationException.class); thrown.expectMessage("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"); createCertificateService( new String[] { "root.crt" }, new String[] { "intermediate.crt"}, new String[] { "root.crl", "intermediate.crl" }, true ).verify(readCert("revoked.crt")); }
public Exporter getCompatibleExporter(TransferExtension extension, DataVertical jobType) { Exporter<?, ?> exporter = getExporterOrNull(extension, jobType); if (exporter != null) { return exporter; } switch (jobType) { case MEDIA: exporter = getMediaExporter(extension); break; case PHOTOS: exporter = getPhotosExporter(extension); break; case VIDEOS: exporter = getVideosExporter(extension); break; } if (exporter == null) { return extension.getExporter(jobType); // preserve original exception } return exporter; }
@Test public void shouldConstructPhotoAndVideoExportersFromMedia() { TransferExtension ext = mock(TransferExtension.class); when(ext.getExporter(eq(MEDIA))).thenReturn(mock(Exporter.class)); assertThat(compatibilityProvider.getCompatibleExporter(ext, PHOTOS)) .isInstanceOf(AnyToAnyExporter.class); assertThat(compatibilityProvider.getCompatibleExporter(ext, VIDEOS)) .isInstanceOf(AnyToAnyExporter.class); }
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException { if (userSession.hasSession() && userSession.isLoggedIn() && userSession.shouldResetPassword()) { redirectTo(response, request.getContextPath() + RESET_PASSWORD_PATH); } chain.doFilter(request, response); }
@Test public void redirect_if_reset_password_set() throws Exception { underTest.doFilter(request, response, chain); verify(response).sendRedirect("/account/reset_password"); }
public static Combine.CombineFn<Boolean, ?, Long> combineFn() { return new CountIfFn(); }
@Test public void testCreatesAccumulatorCoder() throws CannotProvideCoderException { assertNotNull( CountIf.combineFn().getAccumulatorCoder(CoderRegistry.createDefault(), BooleanCoder.of())); }
@Override public Map<String, String> getMetadata(final Path file) throws BackgroundException { return new S3AttributesFinderFeature(session, acl).find(file).getMetadata(); }
@Test public void testGetMetadataBucket() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session)).getMetadata(container); assertTrue(metadata.isEmpty()); }
@Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { startQosServer(url, false); return protocol.refer(type, url); }
@Test void testRefer() throws Exception { wrapper.refer(BaseCommand.class, url); assertThat(server.isStarted(), is(true)); assertThat(server.getHost(), is("localhost")); assertThat(server.getPort(), is(12345)); assertThat(server.isAcceptForeignIp(), is(false)); verify(protocol).refer(BaseCommand.class, url); }
public static Optional<PfxOptions> getPfxKeyStoreOptions(final Map<String, String> props) { // PFX key stores do not have a Private key password final String location = getKeyStoreLocation(props); final String password = getKeyStorePassword(props); if (!Strings.isNullOrEmpty(location)) { return Optional.of(buildPfxOptions(location, password)); } return Optional.empty(); }
@Test public void shouldReturnEmptyKeyStorePfxOptionsIfLocationIsEmpty() { // When final Optional<PfxOptions> pfxOptions = VertxSslOptionsFactory.getPfxKeyStoreOptions( ImmutableMap.of() ); // Then assertThat(pfxOptions, is(Optional.empty())); }
public static ParameterizedType parameterizedType(Class<?> rawType, Type... typeArguments) { var typeParamsCount = rawType.getTypeParameters().length; if (typeParamsCount == 0) { throw new IllegalArgumentException( String.format( "Cannot parameterize `%s` because it does not have any type parameters.", rawType.getTypeName())); } if (typeArguments.length != typeParamsCount) { throw new IllegalArgumentException( String.format( "Expected %d type arguments for `%s`, but got %d.", typeParamsCount, rawType.getTypeName(), typeArguments.length)); } for (Type arg : typeArguments) { if (arg instanceof Class<?> clazz) { if (clazz.isPrimitive()) { throw new IllegalArgumentException( String.format( "`%s.class` is not a valid type argument. Did you mean `%s.class`?", clazz, Reflection.toWrapperType(clazz).getSimpleName())); } } } try { return (ParameterizedType) TypeFactory.parameterizedClass(rawType, typeArguments); } catch (TypeArgumentNotInBoundException e) { throw new IllegalArgumentException( String.format( "Type argument `%s` for type parameter `%s` is not within bound `%s`.", e.getArgument().getTypeName(), e.getParameter().getTypeName(), e.getBound().getTypeName())); } }
@Test public void createParameterizedTypeWithIncompatibleTypeArgument() { Throwable t = catchThrowable(() -> Types.parameterizedType(Foo.class, String.class)); assertThat(t) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "Type argument `java.lang.String` for type parameter `T` is " + "not within bound `org.pkl.config.java.mapper.TypesTest$Bar`."); }
public void setClickHouseLogConfig(final ClickHouseLogConfig clickHouseLogConfig) { this.clickHouseLogConfig = clickHouseLogConfig; }
@Test public void testSetClickHouseLogConfig() { clickHouseLogCollectConfig.setClickHouseLogConfig(clickHouseLogConfig); Assertions.assertNull(null); }
@Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("BatchEventData{"); for (QueryCacheEventData event : events) { stringBuilder.append(event); } stringBuilder.append("}"); return stringBuilder.toString(); }
@Test public void testToString() { assertContains(batchEventData.toString(), "BatchEventData"); }
@Deprecated public static SegwitAddress fromBech32(@Nullable NetworkParameters params, String bech32) throws AddressFormatException { return (SegwitAddress) AddressParser.getLegacy(params).parseAddress(bech32); }
@Test(expected = AddressFormatException.InvalidDataLength.class) public void fromBech32m_taprootTooShort() { // Taproot, valid bech32m encoding, checksum ok, padding ok, but no valid Segwit v1 program // (this program is 20 bytes long, but only 32 bytes program length are valid for Segwit v1/Taproot) String taprootAddressWith20BytesWitnessProgram = "bc1pqypqzqspqgqsyqgzqypqzqspqgqsyqgzzezy58"; SegwitAddress.fromBech32(taprootAddressWith20BytesWitnessProgram, MAINNET); }
@Override public TCreatePartitionResult createPartition(TCreatePartitionRequest request) throws TException { LOG.info("Receive create partition: {}", request); TCreatePartitionResult result; try { if (partitionRequestNum.incrementAndGet() >= Config.thrift_server_max_worker_threads / 4) { result = new TCreatePartitionResult(); TStatus errorStatus = new TStatus(SERVICE_UNAVAILABLE); errorStatus.setError_msgs(Lists.newArrayList( String.format("Too many create partition requests, please try again later txn_id=%d", request.getTxn_id()))); result.setStatus(errorStatus); return result; } result = createPartitionProcess(request); } catch (Exception t) { LOG.warn(DebugUtil.getStackTrace(t)); result = new TCreatePartitionResult(); TStatus errorStatus = new TStatus(RUNTIME_ERROR); errorStatus.setError_msgs(Lists.newArrayList(String.format("txn_id=%d failed. %s", request.getTxn_id(), t.getMessage()))); result.setStatus(errorStatus); } finally { partitionRequestNum.decrementAndGet(); } return result; }
@Test public void testCreatePartitionApiSlice() throws TException { new MockUp<GlobalTransactionMgr>() { @Mock public TransactionState getTransactionState(long dbId, long transactionId) { return new TransactionState(); } }; Database db = GlobalStateMgr.getCurrentState().getDb("test"); Table table = db.getTable("site_access_slice"); List<List<String>> partitionValues = Lists.newArrayList(); List<String> values = Lists.newArrayList(); values.add("1990-04-24"); partitionValues.add(values); FrontendServiceImpl impl = new FrontendServiceImpl(exeEnv); TCreatePartitionRequest request = new TCreatePartitionRequest(); request.setDb_id(db.getId()); request.setTable_id(table.getId()); request.setPartition_values(partitionValues); TCreatePartitionResult partition = impl.createPartition(request); Assert.assertEquals(partition.getStatus().getStatus_code(), TStatusCode.OK); Partition p19900424 = table.getPartition("p19900424"); Assert.assertNotNull(p19900424); partition = impl.createPartition(request); Assert.assertEquals(1, partition.partitions.size()); }
void doSyntaxCheck(NamespaceTextModel model) { if (StringUtils.isBlank(model.getConfigText())) { return; } // only support yaml syntax check if (model.getFormat() != ConfigFileFormat.YAML && model.getFormat() != ConfigFileFormat.YML) { return; } // use YamlPropertiesFactoryBean to check the yaml syntax TypeLimitedYamlPropertiesFactoryBean yamlPropertiesFactoryBean = new TypeLimitedYamlPropertiesFactoryBean(); yamlPropertiesFactoryBean.setResources(new ByteArrayResource(model.getConfigText().getBytes())); try { // this call converts yaml to properties and will throw exception if the conversion fails yamlPropertiesFactoryBean.getObject(); }catch (Exception ex){ throw new BadRequestException(ex.getMessage()); } }
@Test public void yamlSyntaxCheckOK() throws Exception { String yaml = loadYaml("case1.yaml"); itemController.doSyntaxCheck(assemble(ConfigFileFormat.YAML.getValue(), yaml)); }
private Collection<Integer> transform(Transformation<?> transform) { if (alreadyTransformed.containsKey(transform)) { return alreadyTransformed.get(transform); } LOG.debug("Transforming " + transform); if (transform.getMaxParallelism() <= 0) { // if the max parallelism hasn't been set, then first use the job wide max parallelism // from the ExecutionConfig. int globalMaxParallelismFromConfig = executionConfig.getMaxParallelism(); if (globalMaxParallelismFromConfig > 0) { transform.setMaxParallelism(globalMaxParallelismFromConfig); } } transform .getSlotSharingGroup() .ifPresent( slotSharingGroup -> { final ResourceSpec resourceSpec = SlotSharingGroupUtils.extractResourceSpec(slotSharingGroup); if (!resourceSpec.equals(ResourceSpec.UNKNOWN)) { slotSharingGroupResources.compute( slotSharingGroup.getName(), (name, profile) -> { if (profile == null) { return ResourceProfile.fromResourceSpec( resourceSpec, MemorySize.ZERO); } else if (!ResourceProfile.fromResourceSpec( resourceSpec, MemorySize.ZERO) .equals(profile)) { throw new IllegalArgumentException( "The slot sharing group " + slotSharingGroup.getName() + " has been configured with two different resource spec."); } else { return profile; } }); } }); // call at least once to trigger exceptions about MissingTypeInfo transform.getOutputType(); @SuppressWarnings("unchecked") final TransformationTranslator<?, Transformation<?>> translator = (TransformationTranslator<?, Transformation<?>>) translatorMap.get(transform.getClass()); Collection<Integer> transformedIds; if (translator != null) { transformedIds = translate(translator, transform); } else { transformedIds = legacyTransform(transform); } // need this check because the iterate transformation adds itself before // transforming the feedback edges if (!alreadyTransformed.containsKey(transform)) { alreadyTransformed.put(transform, transformedIds); } return transformedIds; }
@Test void testOutputTypeConfigurationWithUdfStreamOperator() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); OutputTypeConfigurableFunction<Integer> function = new OutputTypeConfigurableFunction<>(); DataStream<Integer> source = env.fromData(1, 10); NoOpUdfOperator<Integer> udfOperator = new NoOpUdfOperator<>(function); source.transform("no-op udf operator", BasicTypeInfo.INT_TYPE_INFO, udfOperator) .sinkTo(new DiscardingSink<>()); env.getStreamGraph(); assertThat(udfOperator).isInstanceOf(AbstractUdfStreamOperator.class); assertThat(function.getTypeInformation()).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); }
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMapPutIfAbsentNoReadSucceeds() throws Exception { StateTag<MapState<String, Integer>> addr = StateTags.map("map", StringUtf8Coder.of(), VarIntCoder.of()); MapState<String, Integer> mapState = underTest.state(NAMESPACE, addr); final String tag1 = "tag1"; SettableFuture<Integer> future = SettableFuture.create(); when(mockReader.valueFuture( protoKeyFromUserKey(tag1, StringUtf8Coder.of()), STATE_FAMILY, VarIntCoder.of())) .thenReturn(future); waitAndSet(future, null, 50); ReadableState<Integer> readableState = mapState.putIfAbsent(tag1, 42); assertEquals(42, (int) mapState.get(tag1).read()); assertNull(readableState.read()); }
@Override public TreeEntryNode<K, V> putNode(K key, V value) { TreeEntryNode<K, V> target = nodes.get(key); if (ObjectUtil.isNotNull(target)) { final V oldVal = target.getValue(); target.setValue(value); return target.copy(oldVal); } target = new TreeEntryNode<>(null, key, value); nodes.put(key, target); return null; }
@Test public void getNodeValueTest() { final ForestMap<String, String> map = new LinkedForestMap<>(false); map.putNode("a", "aaa"); assertEquals("aaa", map.getNodeValue("a")); assertNull(map.getNodeValue("b")); }
public boolean eval(StructLike data) { return new EvalVisitor().eval(data); }
@Test public void testGreaterThan() { Evaluator evaluator = new Evaluator(STRUCT, greaterThan("x", 7)); assertThat(evaluator.eval(TestHelpers.Row.of(7, 8, null))).as("7 > 7 => false").isFalse(); assertThat(evaluator.eval(TestHelpers.Row.of(6, 8, null))).as("6 > 7 => false").isFalse(); assertThat(evaluator.eval(TestHelpers.Row.of(8, 8, null))).as("8 > 7 => true").isTrue(); Evaluator structEvaluator = new Evaluator(STRUCT, greaterThan("s1.s2.s3.s4.i", 7)); assertThat( structEvaluator.eval( TestHelpers.Row.of( 7, 8, null, TestHelpers.Row.of( TestHelpers.Row.of(TestHelpers.Row.of(TestHelpers.Row.of(7))))))) .as("7 > 7 => false") .isFalse(); assertThat( structEvaluator.eval( TestHelpers.Row.of( 7, 8, null, TestHelpers.Row.of( TestHelpers.Row.of(TestHelpers.Row.of(TestHelpers.Row.of(6))))))) .as("6 > 7 => false") .isFalse(); assertThat( structEvaluator.eval( TestHelpers.Row.of( 7, 8, null, TestHelpers.Row.of( TestHelpers.Row.of(TestHelpers.Row.of(TestHelpers.Row.of(8))))))) .as("8 > 7 => true") .isTrue(); }
@Override public void lock() { try { lock(-1, null, false); } catch (InterruptedException e) { throw new IllegalStateException(); } }
@Test public void testConcurrency_MultiInstance() throws InterruptedException { int iterations = 100; final AtomicInteger lockedCounter = new AtomicInteger(); testMultiInstanceConcurrency(iterations, r -> { Lock lock = r.getLock("testConcurrency_MultiInstance2"); lock.lock(); lockedCounter.incrementAndGet(); lock.unlock(); }); Assertions.assertEquals(iterations, lockedCounter.get()); }
public long parseForStore(TimelineDataManager tdm, Path appDirPath, boolean appCompleted, JsonFactory jsonFactory, ObjectMapper objMapper, FileSystem fs) throws IOException { LOG.debug("Parsing for log dir {} on attempt {}", appDirPath, attemptDirName); Path logPath = getPath(appDirPath); FileStatus status = fs.getFileStatus(logPath); long numParsed = 0; if (status != null) { long curModificationTime = status.getModificationTime(); if (curModificationTime > getLastProcessedTime()) { long startTime = Time.monotonicNow(); try { LOG.info("Parsing {} at offset {}", logPath, offset); long count = parsePath(tdm, logPath, appCompleted, jsonFactory, objMapper, fs); setLastProcessedTime(curModificationTime); LOG.info("Parsed {} entities from {} in {} msec", count, logPath, Time.monotonicNow() - startTime); numParsed += count; } catch (RuntimeException e) { // If AppLogs cannot parse this log, it may be corrupted or just empty if (e.getCause() instanceof JsonParseException && (status.getLen() > 0 || offset > 0)) { // log on parse problems if the file as been read in the past or // is visibly non-empty LOG.info("Log {} appears to be corrupted. Skip. ", logPath); } else { LOG.error("Failed to parse " + logPath + " from offset " + offset, e); } } } else { LOG.info("Skip Parsing {} as there is no change", logPath); } } else { LOG.warn("{} no longer exists. Skip for scanning. ", logPath); } return numParsed; }
@Test void testParseBrokenEntity() throws Exception { // Load test data TimelineDataManager tdm = PluginStoreTestUtils.getTdmWithMemStore(config); EntityLogInfo testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, TEST_BROKEN_FILE_NAME, UserGroupInformation.getLoginUser().getUserName()); DomainLogInfo domainLogInfo = new DomainLogInfo(TEST_ATTEMPT_DIR_NAME, TEST_BROKEN_FILE_NAME, UserGroupInformation.getLoginUser().getUserName()); // Try parse, should not fail testLogInfo.parseForStore(tdm, getTestRootPath(), true, jsonFactory, objMapper, fs); domainLogInfo.parseForStore(tdm, getTestRootPath(), true, jsonFactory, objMapper, fs); tdm.close(); }
public static SerdeFeatures of(final SerdeFeature... features) { return new SerdeFeatures(ImmutableSet.copyOf(features)); }
@Test public void shouldSerializeAsValue() throws Exception { // Given: final SerdeFeatures features = SerdeFeatures.of(WRAP_SINGLES); // When: final String json = MAPPER.writeValueAsString(features); // Then: assertThat(json, is("[\"WRAP_SINGLES\"]")); }
public void initNewOpenIssue(DefaultIssue issue) { Preconditions.checkArgument(issue.isFromExternalRuleEngine() != (issue.type() == null), "At this stage issue type should be set for and only for external issues"); Rule rule = ruleRepository.getByKey(issue.ruleKey()); issue.setKey(Uuids.create()); issue.setCreationDate(changeContext.date()); issue.setUpdateDate(changeContext.date()); issue.setEffort(debtCalculator.calculate(issue)); setType(issue, rule); setStatus(issue, rule); setCleanCodeAttribute(issue, rule); }
@Test public void initNewOpenIssue() { DefaultIssue issue = new DefaultIssue() .setRuleKey(XOO_X1); when(debtCalculator.calculate(issue)).thenReturn(DEFAULT_DURATION); underTest.initNewOpenIssue(issue); assertThat(issue.key()).isNotNull(); assertThat(issue.creationDate()).isNotNull(); assertThat(issue.updateDate()).isNotNull(); assertThat(issue.status()).isEqualTo(STATUS_OPEN); assertThat(issue.effort()).isEqualTo(DEFAULT_DURATION); assertThat(issue.isNew()).isTrue(); assertThat(issue.isCopied()).isFalse(); assertThat(issue.getCleanCodeAttribute()).isEqualTo(CleanCodeAttribute.CONVENTIONAL); }
public static boolean shouldLoadInIsolation(String name) { return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches()); }
@Test public void testConnectRuntimeClasses() { // Only list packages, because there are too many classes. List<String> runtimeClasses = Arrays.asList( "org.apache.kafka.connect.cli.", //"org.apache.kafka.connect.connector.policy.", isolated by default //"org.apache.kafka.connect.converters.", isolated by default "org.apache.kafka.connect.runtime.", "org.apache.kafka.connect.runtime.distributed", "org.apache.kafka.connect.runtime.errors", "org.apache.kafka.connect.runtime.health", "org.apache.kafka.connect.runtime.isolation", "org.apache.kafka.connect.runtime.rest.", "org.apache.kafka.connect.runtime.rest.entities.", "org.apache.kafka.connect.runtime.rest.errors.", "org.apache.kafka.connect.runtime.rest.resources.", "org.apache.kafka.connect.runtime.rest.util.", "org.apache.kafka.connect.runtime.standalone.", "org.apache.kafka.connect.runtime.rest.", "org.apache.kafka.connect.storage.", "org.apache.kafka.connect.tools.", "org.apache.kafka.connect.util." ); for (String clazz : runtimeClasses) { assertFalse(PluginUtils.shouldLoadInIsolation(clazz), clazz + " from 'runtime' is loaded in isolation but should not be"); } }
@Override public boolean put(K key, V value) { return get(putAsync(key, value)); }
@Test public void testReadAllKeySet() { RListMultimap<String, String> map = redisson.getListMultimap("test1"); map.put("1", "4"); map.put("2", "5"); map.put("3", "6"); assertThat(map.readAllKeySet()).containsExactly("1", "2", "3"); }
public static Builder builder() { return new Builder(); }
@Test void whenReturnTypeIsResponseNoErrorHandling() { Map<String, Collection<String>> headers = new LinkedHashMap<>(); headers.put("Location", Collections.singletonList("http://bar.com")); final Response response = Response.builder().status(302).reason("Found").headers(headers) .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8)) .body(new byte[0]).build(); // fake client as Client.Default follows redirects. TestInterface api = Feign.builder().client((request, options) -> response).target(TestInterface.class, "http://localhost:" + server.getPort()); assertThat(api.response().headers()).hasEntrySatisfying("Location", value -> { assertThat(value).contains("http://bar.com"); }); }
@Override public DarkClusterConfigMap getDarkClusterConfigMap(String clusterName) throws ServiceUnavailableException { FutureCallback<DarkClusterConfigMap> darkClusterConfigMapFutureCallback = new FutureCallback<>(); getDarkClusterConfigMap(clusterName, darkClusterConfigMapFutureCallback); try { return darkClusterConfigMapFutureCallback.get(_timeout, _unit); } catch (ExecutionException | TimeoutException | IllegalStateException | InterruptedException e) { if (e instanceof TimeoutException || e.getCause() instanceof TimeoutException) { DarkClusterConfigMap darkClusterConfigMap = getDarkClusterConfigMapFromCache(clusterName); if (darkClusterConfigMap != null) { _log.info("Got dark cluster config map for {} timed out, used cached value instead.", clusterName); return darkClusterConfigMap; } } die("ClusterInfo", "PEGA_1018, unable to retrieve dark cluster info for cluster: " + clusterName + ", exception" + ": " + e); return new DarkClusterConfigMap(); } }
@Test public void testClusterInfoProviderGetDarkClustersNoUris() throws InterruptedException, ExecutionException, ServiceUnavailableException { MockStore<ServiceProperties> serviceRegistry = new MockStore<>(); MockStore<ClusterProperties> clusterRegistry = new MockStore<>(); MockStore<UriProperties> uriRegistry = new MockStore<>(); SimpleLoadBalancer loadBalancer = setupLoadBalancer(serviceRegistry, clusterRegistry, uriRegistry); DarkClusterConfig darkClusterConfig = new DarkClusterConfig() .setMultiplier(1.0f) .setDispatcherOutboundTargetRate(1) .setDispatcherMaxRequestsToBuffer(1) .setDispatcherBufferedRequestExpiryInSeconds(1); DarkClusterConfigMap darkClusterConfigMap = new DarkClusterConfigMap(); darkClusterConfigMap.put(DARK_CLUSTER1_NAME, darkClusterConfig); clusterRegistry.put(CLUSTER1_NAME, new ClusterProperties(CLUSTER1_NAME, Collections.emptyList(), Collections.emptyMap(), Collections.emptySet(), NullPartitionProperties.getInstance(), Collections.emptyList(), DarkClustersConverter.toProperties(darkClusterConfigMap), false)); loadBalancer.getDarkClusterConfigMap(CLUSTER1_NAME, new Callback<DarkClusterConfigMap>() { @Override public void onError(Throwable e) { Assert.fail("getDarkClusterConfigMap threw exception", e); } @Override public void onSuccess(DarkClusterConfigMap returnedDarkClusterConfigMap) { Assert.assertEquals(returnedDarkClusterConfigMap, darkClusterConfigMap, "dark cluster configs should be equal"); Assert.assertEquals(returnedDarkClusterConfigMap.get(DARK_CLUSTER1_NAME).getMultiplier(), 1.0f, "multiplier should match"); } }); }
public static <T> void swapElement(List<T> list, T element, T targetElement) { if (CollUtil.isNotEmpty(list)) { final int targetIndex = list.indexOf(targetElement); if (targetIndex >= 0) { swapTo(list, element, targetIndex); } } }
@Test public void swapElement() { final Map<String, String> map1 = new HashMap<>(); map1.put("1", "张三"); final Map<String, String> map2 = new HashMap<>(); map2.put("2", "李四"); final Map<String, String> map3 = new HashMap<>(); map3.put("3", "王五"); final List<Map<String, String>> list = Arrays.asList(map1, map2, map3); ListUtil.swapElement(list, map2, map3); Map<String, String> map = list.get(2); assertEquals("李四", map.get("2")); ListUtil.swapElement(list, map2, map1); map = list.get(0); assertEquals("李四", map.get("2")); }
public IndexRecord getIndexInformation(String mapId, int reduce, Path fileName, String expectedIndexOwner) throws IOException { IndexInformation info = cache.get(mapId); if (info == null) { info = readIndexFileToCache(fileName, mapId, expectedIndexOwner); } else { synchronized(info) { while (isUnderConstruction(info)) { try { info.wait(); } catch (InterruptedException e) { throw new IOException("Interrupted waiting for construction", e); } } } LOG.debug("IndexCache HIT: MapId " + mapId + " found"); } if (info.mapSpillRecord.size() == 0 || info.mapSpillRecord.size() <= reduce) { throw new IOException("Invalid request " + " Map Id = " + mapId + " Reducer = " + reduce + " Index Info Length = " + info.mapSpillRecord.size()); } return info.mapSpillRecord.getIndex(reduce); }
@Test public void testBadIndex() throws Exception { final int parts = 30; fs.delete(p, true); conf.setInt(MRJobConfig.SHUFFLE_INDEX_CACHE, 1); IndexCache cache = new IndexCache(conf); Path f = new Path(p, "badindex"); FSDataOutputStream out = fs.create(f, false); CheckedOutputStream iout = new CheckedOutputStream(out, new CRC32()); DataOutputStream dout = new DataOutputStream(iout); for (int i = 0; i < parts; ++i) { for (int j = 0; j < MapTask.MAP_OUTPUT_INDEX_RECORD_LENGTH / 8; ++j) { if (0 == (i % 3)) { dout.writeLong(i); } else { out.writeLong(i); } } } out.writeLong(iout.getChecksum().getValue()); dout.close(); try { cache.getIndexInformation("badindex", 7, f, UserGroupInformation.getCurrentUser().getShortUserName()); fail("Did not detect bad checksum"); } catch (IOException e) { if (!(e.getCause() instanceof ChecksumException)) { throw e; } } }
public static GSBlobIdentifier parseUri(URI uri) { Preconditions.checkArgument( uri.getScheme().equals(GSFileSystemFactory.SCHEME), String.format("URI scheme for %s must be %s", uri, GSFileSystemFactory.SCHEME)); String finalBucketName = uri.getAuthority(); if (StringUtils.isNullOrWhitespaceOnly(finalBucketName)) { throw new IllegalArgumentException(String.format("Bucket name in %s is invalid", uri)); } String path = uri.getPath(); if (StringUtils.isNullOrWhitespaceOnly(path)) { throw new IllegalArgumentException(String.format("Object name in %s is invalid", uri)); } String finalObjectName = path.substring(1); // remove leading slash from path if (StringUtils.isNullOrWhitespaceOnly(finalObjectName)) { throw new IllegalArgumentException(String.format("Object name in %s is invalid", uri)); } return new GSBlobIdentifier(finalBucketName, finalObjectName); }
@Test public void shouldParseValidUri() { GSBlobIdentifier blobIdentifier = BlobUtils.parseUri(URI.create("gs://bucket/foo/bar")); assertEquals("bucket", blobIdentifier.bucketName); assertEquals("foo/bar", blobIdentifier.objectName); }
@Override public String getBucketId(IN element, BucketAssigner.Context context) { if (dateTimeFormatter == null) { dateTimeFormatter = DateTimeFormatter.ofPattern(formatString).withZone(zoneId); } return dateTimeFormatter.format(Instant.ofEpochMilli(context.currentProcessingTime())); }
@Test void testGetBucketPathWithSpecifiedTimezone() { DateTimeBucketAssigner bucketAssigner = new DateTimeBucketAssigner(ZoneId.of("America/Los_Angeles")); assertThat(bucketAssigner.getBucketId(null, mockedContext)).isEqualTo("2018-08-03--23"); }
public static SortDir sortDir(String s) { return !DESC.equals(s) ? SortDir.ASC : SortDir.DESC; }
@Test public void sortDirOther() { assertEquals("other sort dir", SortDir.ASC, TableModel.sortDir("other")); }
public synchronized Map<String, Object> getSubtaskProgress(String taskName, @Nullable String subtaskNames, Executor executor, HttpClientConnectionManager connMgr, Map<String, String> workerEndpoints, Map<String, String> requestHeaders, int timeoutMs) throws Exception { return getSubtaskProgress(taskName, subtaskNames, new CompletionServiceHelper(executor, connMgr, HashBiMap.create(0)), workerEndpoints, requestHeaders, timeoutMs); }
@Test public void testGetSubtaskProgressNoResponse() throws Exception { TaskDriver taskDriver = mock(TaskDriver.class); JobConfig jobConfig = mock(JobConfig.class); when(taskDriver.getJobConfig(anyString())).thenReturn(jobConfig); JobContext jobContext = mock(JobContext.class); when(taskDriver.getJobContext(anyString())).thenReturn(jobContext); PinotHelixTaskResourceManager mgr = new PinotHelixTaskResourceManager(mock(PinotHelixResourceManager.class), taskDriver); CompletionServiceHelper httpHelper = mock(CompletionServiceHelper.class); CompletionServiceHelper.CompletionServiceResponse httpResp = new CompletionServiceHelper.CompletionServiceResponse(); when(httpHelper.doMultiGetRequest(any(), any(), anyBoolean(), any(), anyInt())).thenReturn(httpResp); // Three workers to run 3 subtasks but got no progress status from workers. httpResp._failedResponseCount = 3; String[] workers = new String[]{"worker0", "worker1", "worker2"}; Map<String, String> workerEndpoints = new HashMap<>(); for (String worker : workers) { workerEndpoints.put(worker, "http://" + worker + ":9000"); } String taskName = "Task_SegmentGenerationAndPushTask_someone"; String[] subtaskNames = new String[3]; Map<String, Integer> taskIdPartitionMap = new HashMap<>(); for (int i = 0; i < 3; i++) { String subtaskName = taskName + "_" + i; subtaskNames[i] = subtaskName; taskIdPartitionMap.put(subtaskName, i); } Map<String, TaskConfig> taskConfigMap = new HashMap<>(); for (String subtaskName : subtaskNames) { taskConfigMap.put(subtaskName, mock(TaskConfig.class)); } when(jobConfig.getTaskConfigMap()).thenReturn(taskConfigMap); TaskPartitionState[] helixStates = new TaskPartitionState[]{TaskPartitionState.INIT, TaskPartitionState.RUNNING, TaskPartitionState.TASK_ERROR}; when(jobContext.getTaskIdPartitionMap()).thenReturn(taskIdPartitionMap); when(jobContext.getAssignedParticipant(anyInt())).thenAnswer( invocation -> workers[(int) invocation.getArgument(0)]); when(jobContext.getPartitionState(anyInt())).thenAnswer(invocation -> helixStates[(int) invocation.getArgument(0)]); Map<String, Object> progress = mgr.getSubtaskProgress(taskName, StringUtils.join(subtaskNames, ','), httpHelper, workerEndpoints, Collections.emptyMap(), 1000); for (int i = 0; i < 3; i++) { String taskProgress = (String) progress.get(subtaskNames[i]); assertTrue(taskProgress.contains(helixStates[i].name()), subtaskNames[i] + ":" + taskProgress); } }
public static StreamDecoder create(Decoder iteratorDecoder) { return new StreamDecoder(iteratorDecoder, null); }
@Test void simpleDeleteDecoderTest() { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo\nbar")); StreamInterface api = Feign.builder() .decoder(StreamDecoder.create((r, t) -> { BufferedReader bufferedReader = new BufferedReader(r.body().asReader(UTF_8)); return bufferedReader.lines().iterator(); }, (r, t) -> "str")) .doNotCloseAfterDecode() .target(StreamInterface.class, server.url("/").toString()); String str = api.str(); assertThat(str).isEqualTo("str"); }
@Override public boolean isActive(CommandLine commandLine) { return configuration.getOptional(DeploymentOptions.TARGET).isPresent() || commandLine.hasOption(executorOption.getOpt()) || commandLine.hasOption(targetOption.getOpt()); }
@Test void isActiveWhenTargetOnlyInConfig() throws CliArgsException { final String expectedExecutorName = "test-executor"; final Configuration loadedConfig = new Configuration(); loadedConfig.set(DeploymentOptions.TARGET, expectedExecutorName); final GenericCLI cliUnderTest = new GenericCLI(loadedConfig, tmp.toAbsolutePath().toString()); final CommandLine emptyCommandLine = CliFrontendParser.parse(testOptions, new String[0], true); assertThat(cliUnderTest.isActive(emptyCommandLine)).isTrue(); }
@Override public TStreamLoadPutResult streamLoadPut(TStreamLoadPutRequest request) { String clientAddr = getClientAddrAsString(); LOG.info("receive stream load put request. db:{}, tbl: {}, txn_id: {}, load id: {}, backend: {}", request.getDb(), request.getTbl(), request.getTxnId(), DebugUtil.printId(request.getLoadId()), clientAddr); LOG.debug("stream load put request: {}", request); TStreamLoadPutResult result = new TStreamLoadPutResult(); TStatus status = new TStatus(TStatusCode.OK); result.setStatus(status); try { result.setParams(streamLoadPutImpl(request)); } catch (LockTimeoutException e) { LOG.warn("failed to get stream load plan: {}", e.getMessage()); status.setStatus_code(TStatusCode.TIMEOUT); status.addToError_msgs(e.getMessage()); } catch (UserException | StarRocksPlannerException e) { LOG.warn("failed to get stream load plan: {}", e.getMessage()); status.setStatus_code(TStatusCode.ANALYSIS_ERROR); status.addToError_msgs(e.getMessage()); } catch (Throwable e) { LOG.warn("catch unknown result.", e); status.setStatus_code(TStatusCode.INTERNAL_ERROR); status.addToError_msgs(Strings.nullToEmpty(e.getMessage())); return result; } return result; }
@Test public void testStreamLoadPutColumnMapException() { FrontendServiceImpl impl = new FrontendServiceImpl(exeEnv); TStreamLoadPutRequest request = new TStreamLoadPutRequest(); request.setDb("test"); request.setTbl("site_access_hour"); request.setUser("root"); request.setTxnId(1024); request.setColumnSeparator(","); request.setSkipHeader(1); request.setFileType(TFileType.FILE_STREAM); // wrong format of str_to_date() request.setColumns("col1,event_day=str_to_date(col1)"); TStreamLoadPutResult result = impl.streamLoadPut(request); TStatus status = result.getStatus(); request.setFileType(TFileType.FILE_STREAM); Assert.assertEquals(TStatusCode.ANALYSIS_ERROR, status.getStatus_code()); List<String> errMsg = status.getError_msgs(); Assert.assertEquals(1, errMsg.size()); Assert.assertEquals( "Expr 'str_to_date(`col1`)' analyze error: No matching function with signature: str_to_date(varchar), " + "derived column is 'event_day'", errMsg.get(0)); }
public SemanticRules(List<RuleBase> ruleBases) { this.ruleBases = ruleBases; }
@Test void semanticRulesTest() throws ParseException, IOException { SemanticRuleBuilder ruleBuilder = new SemanticRuleBuilder(); SemanticRules rules = ruleBuilder.build(FilesApplicationPackage.fromFile(new File(root))); SemanticRulesConfig.Builder configBuilder = new SemanticRulesConfig.Builder(); rules.getConfig(configBuilder); SemanticRulesConfig config = new SemanticRulesConfig(configBuilder); Map<String, RuleBase> ruleBases = SemanticRuleBuilder.toMap(config); assertEquals(2, ruleBases.size()); assertTrue(ruleBases.containsKey("common")); assertTrue(ruleBases.containsKey("other")); assertFalse(ruleBases.get("common").isDefault()); assertTrue(ruleBases.get("other").isDefault()); assertTrue(ruleBases.get("other").includes("common")); assertNotNull(ruleBases.get("other").getCondition("stopword")); }
private static Schema optional(Schema original) { // null is first in the union because Parquet's default is always null return Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), original)); }
@Test public void testOptionalFields() throws Exception { Schema schema = Schema.createRecord("record1", null, null, false); Schema optionalInt = optional(Schema.create(INT)); schema.setFields( Collections.singletonList(new Schema.Field("myint", optionalInt, null, JsonProperties.NULL_VALUE))); testRoundTripConversion(schema, "message record1 {\n" + " optional int32 myint;\n" + "}\n"); }
@Override public void validateRoleList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return; } // 获得角色信息 List<RoleDO> roles = roleMapper.selectBatchIds(ids); Map<Long, RoleDO> roleMap = convertMap(roles, RoleDO::getId); // 校验 ids.forEach(id -> { RoleDO role = roleMap.get(id); if (role == null) { throw exception(ROLE_NOT_EXISTS); } if (!CommonStatusEnum.ENABLE.getStatus().equals(role.getStatus())) { throw exception(ROLE_IS_DISABLE, role.getName()); } }); }
@Test public void testValidateRoleList_success() { // mock 数据 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); roleMapper.insert(roleDO); // 准备参数 List<Long> ids = singletonList(roleDO.getId()); // 调用,无需断言 roleService.validateRoleList(ids); }
@Operation(summary = "verifyNamespaceK8s", description = "VERIFY_NAMESPACE_K8S_NOTES") @Parameters({ @Parameter(name = "namespace", description = "NAMESPACE", required = true, schema = @Schema(implementation = String.class)), @Parameter(name = "clusterCode", description = "CLUSTER_CODE", required = true, schema = @Schema(implementation = long.class)), }) @PostMapping(value = "/verify") @ResponseStatus(HttpStatus.OK) @ApiException(VERIFY_K8S_NAMESPACE_ERROR) public Result verifyNamespace(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "namespace") String namespace, @RequestParam(value = "clusterCode") Long clusterCode) { return k8sNamespaceService.verifyNamespaceK8s(namespace, clusterCode); }
@Test public void verifyNamespace() throws Exception { // queue value exist MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("namespace", "NAMESPACE_CREATE_STRING"); paramsMap.add("clusterCode", "100"); // success MvcResult mvcResult = mockMvc.perform(post("/k8s-namespace/verify") .header(SESSION_ID, sessionId) .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); logger.info("verify namespace return result:{}", mvcResult.getResponse().getContentAsString()); // error paramsMap.clear(); paramsMap.add("namespace", null); paramsMap.add("clusterCode", "100"); mvcResult = mockMvc.perform(post("/k8s-namespace/verify") .header(SESSION_ID, sessionId) .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); Assertions.assertEquals(Status.VERIFY_K8S_NAMESPACE_ERROR.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); logger.info("verify namespace return result:{}", mvcResult.getResponse().getContentAsString()); }
@VisibleForTesting List<MessageSummary> getMessageBacklog(EventNotificationContext ctx, TeamsEventNotificationConfigV2 config) { List<MessageSummary> backlog = notificationCallbackService.getBacklogForEvent(ctx); if (config.backlogSize() > 0 && backlog != null) { return backlog.stream().limit(config.backlogSize()).collect(Collectors.toList()); } return backlog; }
@Test public void testBacklogMessageLimitWhenEventNotificationContextIsNull() { TeamsEventNotificationConfigV2 config = TeamsEventNotificationConfigV2.builder() .backlogSize(0) .build(); // Global setting is at 50 and the eventNotificationContext is null then the message summaries is null List<MessageSummary> messageSummaries = teamsEventNotification.getMessageBacklog(null, config); assertThat(messageSummaries).isNull(); }
public synchronized long nextGtid() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { timestamp = lastTimestamp; } if (lastTimestamp == timestamp) { sequence = (sequence + 1) & MAX_SEQUENCE; if (sequence == 0) { timestamp += 1; } } else { sequence = 0L; } if (timestamp - EPOCH >= (1L << 42)) { throw new IllegalStateException("Timestamp overflow"); } lastTimestamp = timestamp; return ((timestamp - EPOCH) << TIMESTAMP_SHIFT) | (CLUSTER_ID << CLUSTER_ID_SHIFT) | sequence; }
@Test public void testNextGtidIncrementsSequenceOnSameMillisecond() { long firstGtid = gtidGenerator.nextGtid(); long secondGtid = gtidGenerator.nextGtid(); Assertions.assertNotEquals(firstGtid, secondGtid, "GTIDs should be unique"); Assertions.assertEquals((firstGtid & GtidGenerator.MAX_SEQUENCE) + 1, secondGtid & GtidGenerator.MAX_SEQUENCE, "Sequence should increment by 1 on the same millisecond"); }
public static ParseFiles parseFiles() { return new AutoValue_TikaIO_ParseFiles.Builder().build(); }
@Test public void testParseFilesDisplayData() { TikaIO.ParseFiles parseFiles = TikaIO.parseFiles() .withTikaConfigPath("/tikaConfigPath") .withContentTypeHint("application/pdf"); DisplayData displayData = DisplayData.from(parseFiles); assertThat(displayData, hasDisplayItem("tikaConfigPath", "/tikaConfigPath")); assertThat(displayData, hasDisplayItem("contentTypeHint", "application/pdf")); }
@VisibleForTesting static DefaultIssue toDefaultIssue(IssueCache.Issue next) { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setKey(next.getKey()); defaultIssue.setType(RuleType.valueOf(next.getRuleType())); defaultIssue.setComponentUuid(next.hasComponentUuid() ? next.getComponentUuid() : null); defaultIssue.setComponentKey(next.getComponentKey()); defaultIssue.setProjectUuid(next.getProjectUuid()); defaultIssue.setProjectKey(next.getProjectKey()); defaultIssue.setRuleKey(RuleKey.parse(next.getRuleKey())); defaultIssue.setLanguage(next.hasLanguage() ? next.getLanguage() : null); defaultIssue.setSeverity(next.hasSeverity() ? next.getSeverity() : null); defaultIssue.setManualSeverity(next.getManualSeverity()); defaultIssue.setMessage(next.hasMessage() ? next.getMessage() : null); defaultIssue.setMessageFormattings(next.hasMessageFormattings() ? next.getMessageFormattings() : null); defaultIssue.setLine(next.hasLine() ? next.getLine() : null); defaultIssue.setGap(next.hasGap() ? next.getGap() : null); defaultIssue.setEffort(next.hasEffort() ? Duration.create(next.getEffort()) : null); defaultIssue.setStatus(next.getStatus()); defaultIssue.setResolution(next.hasResolution() ? next.getResolution() : null); defaultIssue.setAssigneeUuid(next.hasAssigneeUuid() ? next.getAssigneeUuid() : null); defaultIssue.setAssigneeLogin(next.hasAssigneeLogin() ? next.getAssigneeLogin() : null); defaultIssue.setChecksum(next.hasChecksum() ? next.getChecksum() : null); defaultIssue.setAuthorLogin(next.hasAuthorLogin() ? next.getAuthorLogin() : null); next.getCommentsList().forEach(c -> defaultIssue.addComment(toDefaultIssueComment(c))); defaultIssue.setTags(ImmutableSet.copyOf(STRING_LIST_SPLITTER.split(next.getTags()))); defaultIssue.setCodeVariants(ImmutableSet.copyOf(STRING_LIST_SPLITTER.split(next.getCodeVariants()))); defaultIssue.setRuleDescriptionContextKey(next.hasRuleDescriptionContextKey() ? next.getRuleDescriptionContextKey() : null); defaultIssue.setLocations(next.hasLocations() ? next.getLocations() : null); defaultIssue.setIsFromExternalRuleEngine(next.getIsFromExternalRuleEngine()); defaultIssue.setCreationDate(new Date(next.getCreationDate())); defaultIssue.setUpdateDate(next.hasUpdateDate() ? new Date(next.getUpdateDate()) : null); defaultIssue.setCloseDate(next.hasCloseDate() ? new Date(next.getCloseDate()) : null); defaultIssue.setCurrentChangeWithoutAddChange(next.hasCurrentChanges() ? toDefaultIssueChanges(next.getCurrentChanges()) : null); defaultIssue.setNew(next.getIsNew()); defaultIssue.setIsOnChangedLine(next.getIsOnChangedLine()); defaultIssue.setIsNewCodeReferenceIssue(next.getIsNewCodeReferenceIssue()); defaultIssue.setCopied(next.getIsCopied()); defaultIssue.setBeingClosed(next.getBeingClosed()); defaultIssue.setOnDisabledRule(next.getOnDisabledRule()); defaultIssue.setChanged(next.getIsChanged()); defaultIssue.setSendNotifications(next.getSendNotifications()); defaultIssue.setSelectedAt(next.hasSelectedAt() ? next.getSelectedAt() : null); defaultIssue.setQuickFixAvailable(next.getQuickFixAvailable()); defaultIssue.setPrioritizedRule(next.getIsPrioritizedRule()); defaultIssue.setIsNoLongerNewCodeReferenceIssue(next.getIsNoLongerNewCodeReferenceIssue()); defaultIssue.setCleanCodeAttribute(next.hasCleanCodeAttribute() ? CleanCodeAttribute.valueOf(next.getCleanCodeAttribute()) : null); if (next.hasAnticipatedTransitionUuid()) { defaultIssue.setAnticipatedTransitionUuid(next.getAnticipatedTransitionUuid()); } for (IssueCache.Impact impact : next.getImpactsList()) { defaultIssue.addImpact(SoftwareQuality.valueOf(impact.getSoftwareQuality()), Severity.valueOf(impact.getSeverity())); } for (IssueCache.FieldDiffs protoFieldDiffs : next.getChangesList()) { defaultIssue.addChange(toDefaultIssueChanges(protoFieldDiffs)); } return defaultIssue; }
@Test public void toDefaultIssue_whenCleanCodeAttributeIsSet_shouldSetItInDefaultIssue() { IssueCache.Issue issue = prepareIssueWithCompulsoryFields() .setCleanCodeAttribute(CleanCodeAttribute.FOCUSED.name()) .build(); DefaultIssue defaultIssue = ProtobufIssueDiskCache.toDefaultIssue(issue); assertThat(defaultIssue.getCleanCodeAttribute()).isEqualTo(CleanCodeAttribute.FOCUSED); }
@Override public AddToClusterNodeLabelsResponse addToClusterNodeLabels( AddToClusterNodeLabelsRequest request) throws YarnException, IOException { // parameter verification. if (request == null) { routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterServerUtil.logAndThrowException("Missing AddToClusterNodeLabels request.", null); } String subClusterId = request.getSubClusterId(); if (StringUtils.isBlank(subClusterId)) { routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterServerUtil.logAndThrowException("Missing AddToClusterNodeLabels SubClusterId.", null); } try { long startTime = clock.getTime(); RMAdminProtocolMethod remoteMethod = new RMAdminProtocolMethod( new Class[]{AddToClusterNodeLabelsRequest.class}, new Object[]{request}); Collection<AddToClusterNodeLabelsResponse> addToClusterNodeLabelsResps = remoteMethod.invokeConcurrent(this, AddToClusterNodeLabelsResponse.class, subClusterId); if (CollectionUtils.isNotEmpty(addToClusterNodeLabelsResps)) { long stopTime = clock.getTime(); routerMetrics.succeededAddToClusterNodeLabelsRetrieved(stopTime - startTime); return AddToClusterNodeLabelsResponse.newInstance(); } } catch (YarnException e) { routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterServerUtil.logAndThrowException(e, "Unable to addToClusterNodeLabels due to exception. " + e.getMessage()); } routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); throw new YarnException("Unable to addToClusterNodeLabels."); }
@Test public void testAddToClusterNodeLabelsEmptyRequest() throws Exception { // null request1. LambdaTestUtils.intercept(YarnException.class, "Missing AddToClusterNodeLabels request.", () -> interceptor.addToClusterNodeLabels(null)); // null request2. AddToClusterNodeLabelsRequest request = AddToClusterNodeLabelsRequest.newInstance(null, null); LambdaTestUtils.intercept(YarnException.class, "Missing AddToClusterNodeLabels SubClusterId.", () -> interceptor.addToClusterNodeLabels(request)); }
@Override public void checkBeforeUpdate(final CreateReadwriteSplittingRuleStatement sqlStatement) { ReadwriteSplittingRuleStatementChecker.checkCreation(database, sqlStatement.getRules(), null == rule ? null : rule.getConfiguration(), sqlStatement.isIfNotExists()); }
@Test void assertCheckSQLStatementWithDuplicateReadResourceNames() { ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class); when(rule.getConfiguration()).thenReturn(createCurrentRuleConfiguration()); executor.setRule(rule); assertThrows(DuplicateReadwriteSplittingActualDataSourceException.class, () -> executor.checkBeforeUpdate(createSQLStatement("readwrite_ds_1", "write_ds_1", Arrays.asList("read_ds_0", "read_ds_1"), "TEST"))); }
@Override public IndexType.IndexMainType getMainType() { return mainType; }
@Test public void getMainType_returns_main_type_of_authorization_for_index_of_constructor() { NewAuthorizedIndex underTest = new NewAuthorizedIndex(someIndex, defaultSettingsConfiguration); assertThat(underTest.getMainType()).isEqualTo(IndexType.main(someIndex, "auth")); }
public static boolean isContent(ServiceCluster cluster) { return isContent(cluster.serviceType()); }
@Test public void verifyContentClusterIsRecognized() { ServiceCluster cluster = createServiceCluster(ServiceType.DISTRIBUTOR); assertTrue(VespaModelUtil.isContent(cluster)); cluster = createServiceCluster(ServiceType.STORAGE); assertTrue(VespaModelUtil.isContent(cluster)); cluster = createServiceCluster(ServiceType.SEARCH); assertTrue(VespaModelUtil.isContent(cluster)); }
static SortKey[] rangeBounds( int numPartitions, Comparator<StructLike> comparator, SortKey[] samples) { // sort the keys first Arrays.sort(samples, comparator); int numCandidates = numPartitions - 1; SortKey[] candidates = new SortKey[numCandidates]; int step = (int) Math.ceil((double) samples.length / numPartitions); int position = step - 1; int numChosen = 0; while (position < samples.length && numChosen < numCandidates) { SortKey candidate = samples[position]; // skip duplicate values if (numChosen > 0 && candidate.equals(candidates[numChosen - 1])) { // linear probe for the next distinct value position += 1; } else { candidates[numChosen] = candidate; position += step; numChosen += 1; } } return candidates; }
@Test public void testRangeBoundsSkipDuplicates() { // step is 3 = ceiling(11/4) assertThat( SketchUtil.rangeBounds( 4, SORT_ORDER_COMPARTOR, new SortKey[] { CHAR_KEYS.get("a"), CHAR_KEYS.get("b"), CHAR_KEYS.get("c"), CHAR_KEYS.get("c"), CHAR_KEYS.get("c"), CHAR_KEYS.get("c"), CHAR_KEYS.get("g"), CHAR_KEYS.get("h"), CHAR_KEYS.get("i"), CHAR_KEYS.get("j"), CHAR_KEYS.get("k"), })) // skipped duplicate c's .containsExactly(CHAR_KEYS.get("c"), CHAR_KEYS.get("g"), CHAR_KEYS.get("j")); }
@Override public List<Intent> compile(LinkCollectionIntent intent, List<Intent> installable) { SetMultimap<DeviceId, PortNumber> inputPorts = HashMultimap.create(); SetMultimap<DeviceId, PortNumber> outputPorts = HashMultimap.create(); Map<ConnectPoint, Identifier<?>> labels = ImmutableMap.of(); Optional<EncapsulationConstraint> encapConstraint = this.getIntentEncapConstraint(intent); computePorts(intent, inputPorts, outputPorts); if (encapConstraint.isPresent()) { labels = labelAllocator.assignLabelToPorts(intent.links(), intent.key(), encapConstraint.get().encapType(), encapConstraint.get().suggestedIdentifier()); } ImmutableList.Builder<Intent> intentList = ImmutableList.builder(); if (this.isDomainProcessingEnabled(intent)) { intentList.addAll(this.getDomainIntents(intent, domainService)); } List<Objective> objectives = new ArrayList<>(); List<DeviceId> devices = new ArrayList<>(); for (DeviceId deviceId : outputPorts.keySet()) { // add only objectives that are not inside of a domain if (LOCAL.equals(domainService.getDomain(deviceId))) { List<Objective> deviceObjectives = createRules(intent, deviceId, inputPorts.get(deviceId), outputPorts.get(deviceId), labels); deviceObjectives.forEach(objective -> { objectives.add(objective); devices.add(deviceId); }); } } // if any objectives have been created if (!objectives.isEmpty()) { intentList.add(new FlowObjectiveIntent(appId, intent.key(), devices, objectives, intent.resources(), intent.resourceGroup())); } return intentList.build(); }
@Test public void testFilteredConnectPointForMpWithEncap() throws Exception { LinkCollectionCompiler.labelAllocator.setLabelSelection(LABEL_SELECTION); Set<Link> testLinks = ImmutableSet.of( DefaultLink.builder().providerId(PID).src(of1p2).dst(of2p1).type(DIRECT).build(), DefaultLink.builder().providerId(PID).src(of3p2).dst(of2p3).type(DIRECT).build(), DefaultLink.builder().providerId(PID).src(of2p2).dst(of4p1).type(DIRECT).build() ); Set<FilteredConnectPoint> ingress = ImmutableSet.of( new FilteredConnectPoint(of3p1, vlan100Selector), new FilteredConnectPoint(of1p1, vlan100Selector) ); Set<FilteredConnectPoint> egress = ImmutableSet.of( new FilteredConnectPoint(of4p2, vlan100Selector) ); EncapsulationConstraint constraint = new EncapsulationConstraint(EncapsulationType.VLAN); LinkCollectionIntent intent = LinkCollectionIntent.builder() .appId(appId) .selector(ethDstSelector) .treatment(treatment) .links(testLinks) .filteredIngressPoints(ingress) .filteredEgressPoints(egress) .constraints(ImmutableList.of(constraint)) .build(); List<Intent> result = compiler.compile(intent, Collections.emptyList()); assertThat(result, hasSize(1)); assertThat(result.get(0), instanceOf(FlowObjectiveIntent.class)); FlowObjectiveIntent foIntent = (FlowObjectiveIntent) result.get(0); List<Objective> objectives = foIntent.objectives(); assertThat(objectives, hasSize(15)); TrafficSelector expectSelector = DefaultTrafficSelector .builder(ethDstSelector) .matchInPort(PortNumber.portNumber(1)) .matchVlanId(VLAN_100) .build(); TrafficSelector filteringSelector = vlan100Selector; TrafficTreatment expectTreatment = DefaultTrafficTreatment.builder() .setVlanId(VLAN_1) .setOutput(PortNumber.portNumber(2)) .build(); /* * First set of objective */ filteringObjective = (FilteringObjective) objectives.get(0); forwardingObjective = (ForwardingObjective) objectives.get(1); nextObjective = (NextObjective) objectives.get(2); PortCriterion inPortCriterion = (PortCriterion) expectSelector.getCriterion(Criterion.Type.IN_PORT); // test case for first filtering objective checkFiltering(filteringObjective, inPortCriterion, intent.priority(), null, appId, true, filteringSelector.criteria()); // test case for first next objective checkNext(nextObjective, SIMPLE, expectTreatment, expectSelector, ADD); // test case for first forwarding objective checkForward(forwardingObjective, ADD, expectSelector, nextObjective.id(), SPECIFIC); /* * Second set of objective */ filteringObjective = (FilteringObjective) objectives.get(3); forwardingObjective = (ForwardingObjective) objectives.get(4); nextObjective = (NextObjective) objectives.get(5); expectSelector = DefaultTrafficSelector .builder() .matchInPort(PortNumber.portNumber(1)) .matchVlanId(VLAN_1) .build(); filteringSelector = vlan1Selector; expectTreatment = DefaultTrafficTreatment .builder() .setVlanId(VLAN_100) .setOutput(PortNumber.portNumber(2)) .build(); // test case for second filtering objective checkFiltering(filteringObjective, inPortCriterion, intent.priority(), null, appId, true, filteringSelector.criteria()); // test case for second next objective checkNext(nextObjective, SIMPLE, expectTreatment, expectSelector, ADD); // test case for second forwarding objective checkForward(forwardingObjective, ADD, expectSelector, nextObjective.id(), SPECIFIC); /* * 3rd set of objective */ filteringObjective = (FilteringObjective) objectives.get(6); forwardingObjective = (ForwardingObjective) objectives.get(7); nextObjective = (NextObjective) objectives.get(8); filteringSelector = vlan100Selector; expectTreatment = DefaultTrafficTreatment .builder() .setVlanId(VLAN_1) .setOutput(PortNumber.portNumber(2)) .build(); expectSelector = DefaultTrafficSelector .builder(ethDstSelector) .matchInPort(PortNumber.portNumber(1)) .matchVlanId(VLAN_100) .build(); // test case for 3rd filtering objective checkFiltering(filteringObjective, inPortCriterion, intent.priority(), null, appId, true, filteringSelector.criteria()); // test case for 3rd next objective checkNext(nextObjective, SIMPLE, expectTreatment, expectSelector, ADD); // test case for 3rd forwarding objective checkForward(forwardingObjective, ADD, expectSelector, nextObjective.id(), SPECIFIC); /* * 4th set of objective */ filteringObjective = (FilteringObjective) objectives.get(9); forwardingObjective = (ForwardingObjective) objectives.get(10); nextObjective = (NextObjective) objectives.get(11); filteringSelector = vlan1Selector; expectSelector = DefaultTrafficSelector .builder() .matchInPort(PortNumber.portNumber(1)) .matchVlanId(VLAN_1) .build(); // test case for 4th filtering objective checkFiltering(filteringObjective, inPortCriterion, intent.priority(), null, appId, true, filteringSelector.criteria()); // test case for 4th next objective checkNext(nextObjective, SIMPLE, expectTreatment, expectSelector, ADD); // test case for 4th forwarding objective checkForward(forwardingObjective, ADD, expectSelector, nextObjective.id(), SPECIFIC); /* * 5th set of objective */ filteringObjective = (FilteringObjective) objectives.get(12); forwardingObjective = (ForwardingObjective) objectives.get(13); nextObjective = (NextObjective) objectives.get(14); expectSelector = DefaultTrafficSelector.builder() .matchVlanId(VlanId.vlanId("1")) .matchInPort(PortNumber.portNumber(3)) .build(); inPortCriterion = (PortCriterion) expectSelector.getCriterion(Criterion.Type.IN_PORT); // test case for 5th filtering objective checkFiltering(filteringObjective, inPortCriterion, intent.priority(), null, appId, true, filteringSelector.criteria()); // test case for 5th next objective checkNext(nextObjective, SIMPLE, expectTreatment, expectSelector, ADD); // test case for 5th forwarding objective checkForward(forwardingObjective, ADD, expectSelector, nextObjective.id(), SPECIFIC); }
public static GlobalTransaction reload(String xid) throws TransactionException { return new DefaultGlobalTransaction(xid, GlobalStatus.UnKnown, GlobalTransactionRole.Launcher) { @Override public void begin(int timeout, String name) throws TransactionException { throw new IllegalStateException("Never BEGIN on a RELOADED GlobalTransaction. "); } }; }
@Test void reloadTest() throws TransactionException { GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate(); tx = GlobalTransactionContext.reload(DEFAULT_XID); GlobalTransaction finalTx = tx; Assertions.assertThrows(IllegalStateException.class, finalTx::begin); }
static <T extends Comparable<? super T>> int compareListWithFillValue( List<T> left, List<T> right, T fillValue) { int longest = Math.max(left.size(), right.size()); for (int i = 0; i < longest; i++) { T leftElement = fillValue; T rightElement = fillValue; if (i < left.size()) { leftElement = left.get(i); } if (i < right.size()) { rightElement = right.get(i); } int compareResult = leftElement.compareTo(rightElement); if (compareResult != 0) { return compareResult; } } return 0; }
@Test public void compareWithFillValue_oneEmptyListAndLargeFillValue_returnsPositive() { assertThat( ComparisonUtility.compareListWithFillValue( Lists.newArrayList(), Lists.newArrayList(1, 2, 3), 100)) .isGreaterThan(0); }
@Override public ByteBuffer read(long offset, long length) throws IOException { if (length == 0 || offset >= mFileSize) { return EMPTY_BYTE_BUFFER; } // cap length to the remaining of block, as the caller may pass in a longer length than what // is left in the block, but expect as many bytes as there is length = Math.min(length, mFileSize - offset); ensureReadable(offset, length); // must not use pooled buffer, see interface implementation note ByteBuffer buffer = ByteBuffer.allocateDirect((int) length); ByteBuf buf = Unpooled.wrappedBuffer(buffer); // Unpooled.wrappedBuffer returns a buffer with writer index set to capacity, so writable // bytes is 0, needs explicit clear buf.clear(); ReadTargetBuffer targetBuffer = new NettyBufTargetBuffer(buf); int bytesRead = mPositionReader.read(offset, targetBuffer, (int) length); if (bytesRead < 0) { return EMPTY_BYTE_BUFFER; } buffer.position(0); buffer.limit(bytesRead); return buffer; }
@Test public void read() throws IOException { int testNum = Math.min(mFileLen, mMinTestNum); for (int i = 0; i < testNum; i++) { int offset = mRandom.nextInt(mFileLen); int readLength = mRandom.nextInt(mFileLen - offset); byte[] tmpBytes = Files.readAllBytes(Paths.get(mTestFileName)); byte[] bytes = Arrays.copyOfRange(tmpBytes, offset, offset + readLength); ByteBuffer realByteBuffer = ByteBuffer.wrap(bytes); ByteBuffer byteBuffer = mPagedFileReader.read(offset, readLength); Assert.assertEquals(realByteBuffer, byteBuffer); } }
public String getMetricsByConfigId(String configId) { List<VespaService> services = vespaServices.getInstancesById(configId); vespaServices.updateServices(services); return vespaMetrics.getMetricsAsString(services); }
@Test public void verify_expected_output_from_getMetricsById() { String dummy0Metrics = metricsManager.getMetricsByConfigId(SERVICE_0_ID); assertTrue(dummy0Metrics.contains("'dummy.id.0'.val=1.050")); assertTrue(dummy0Metrics.contains("'dummy.id.0'.c_test=1")); String dummy1Metrics = metricsManager.getMetricsByConfigId(SERVICE_1_ID); assertTrue(dummy1Metrics.contains("'dummy.id.1'.val=2.350")); assertTrue(dummy1Metrics.contains("'dummy.id.1'.c_test=6")); }
public List<Instance> findInstancesByIds(Set<Long> instanceIds) { Iterable<Instance> instances = instanceRepository.findAllById(instanceIds); return Lists.newArrayList(instances); }
@Test @Rollback public void testFindInstancesByIds() throws Exception { String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someDataCenter = "someDataCenter"; String someIp = "someIp"; String anotherIp = "anotherIp"; Instance someInstance = instanceService.createInstance(assembleInstance(someAppId, someClusterName, someDataCenter, someIp)); Instance anotherInstance = instanceService.createInstance(assembleInstance(someAppId, someClusterName, someDataCenter, anotherIp)); List<Instance> instances = instanceService.findInstancesByIds(Sets.newHashSet(someInstance .getId(), anotherInstance.getId())); Set<String> ips = instances.stream().map(Instance::getIp).collect(Collectors.toSet()); assertEquals(2, instances.size()); assertEquals(Sets.newHashSet(someIp, anotherIp), ips); }
@Override public SelType binaryOps(SelOp op, SelType rhs) { if (rhs.type() == SelTypes.NULL) { if (op == SelOp.EQUAL || op == SelOp.NOT_EQUAL) { return rhs.binaryOps(op, this); } else { throw new UnsupportedOperationException( this.type() + " DO NOT support " + op + " for rhs with NULL value"); } } if (rhs.type() == SelTypes.STRING) { return SelString.of(String.valueOf(this.val)).binaryOps(op, rhs); } double another = ((Number) rhs.getInternalVal()).doubleValue(); switch (op) { case EQUAL: return SelBoolean.of(this.val == another); case NOT_EQUAL: return SelBoolean.of(this.val != another); case LT: return SelBoolean.of(this.val < another); case GT: return SelBoolean.of(this.val > another); case LTE: return SelBoolean.of(this.val <= another); case GTE: return SelBoolean.of(this.val >= another); case ADD: return new SelDouble(this.val + another); case SUB: return new SelDouble(this.val - another); case MUL: return new SelDouble(this.val * another); case DIV: return new SelDouble(this.val / another); case MOD: return new SelDouble(this.val % another); case PLUS: return new SelDouble(this.val); case MINUS: return new SelDouble(-this.val); default: throw new UnsupportedOperationException( "float/Float/double/Doubles DO NOT support expression operation " + op); } }
@Test(expected = UnsupportedOperationException.class) public void testInvalidBinaryOpType() { one.binaryOps(SelOp.ADD, SelType.NULL); }
@Override public final void mark(int readlimit) { mark = pos; }
@Test public void testMark() { in.position(1); in.mark(1); assertEquals(1, in.mark); }
public static void delete(final File rootFile) throws IOException { if (rootFile == null) return; Files.walkFileTree(rootFile.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFileFailed(Path path, IOException exc) throws IOException { if (exc instanceof NoSuchFileException) { if (path.toFile().equals(rootFile)) { // If the root path did not exist, ignore the error and terminate; return FileVisitResult.TERMINATE; } else { // Otherwise, just continue walking as the file might already be deleted by other threads. return FileVisitResult.CONTINUE; } } throw exc; } @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { Files.deleteIfExists(path); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path path, IOException exc) throws IOException { // KAFKA-8999: if there's an exception thrown previously already, we should throw it if (exc != null) { throw exc; } Files.deleteIfExists(path); return FileVisitResult.CONTINUE; } }); }
@Timeout(120) @Test public void testRecursiveDelete() throws IOException { Utils.delete(null); // delete of null does nothing. // Test that deleting a temporary file works. File tempFile = TestUtils.tempFile(); Utils.delete(tempFile); assertFalse(Files.exists(tempFile.toPath())); // Test recursive deletes File tempDir = TestUtils.tempDirectory(); File tempDir2 = TestUtils.tempDirectory(tempDir.toPath(), "a"); TestUtils.tempDirectory(tempDir.toPath(), "b"); TestUtils.tempDirectory(tempDir2.toPath(), "c"); Utils.delete(tempDir); assertFalse(Files.exists(tempDir.toPath())); assertFalse(Files.exists(tempDir2.toPath())); // Test that deleting a non-existent directory hierarchy works. Utils.delete(tempDir); assertFalse(Files.exists(tempDir.toPath())); }
public void handleEventFromOperator(int subtask, int attemptNumber, OperatorEvent event) throws Exception { mainThreadExecutor.assertRunningInMainThread(); if (event instanceof AcknowledgeCheckpointEvent) { subtaskGatewayMap .get(subtask) .openGatewayAndUnmarkCheckpoint( ((AcknowledgeCheckpointEvent) event).getCheckpointID()); return; } coordinator.handleEventFromOperator(subtask, attemptNumber, event); }
@Test void takeCheckpointAfterSuccessfulCheckpoint() throws Exception { final EventReceivingTasks tasks = EventReceivingTasks.createForRunningTasks(); final OperatorCoordinatorHolder holder = createCoordinatorHolder(tasks, TestingOperatorCoordinator::new); getCoordinator(holder).getSubtaskGateway(0).sendEvent(new TestOperatorEvent(0)); triggerAndCompleteCheckpoint(holder, 22L); getCoordinator(holder).getSubtaskGateway(0).sendEvent(new TestOperatorEvent(1)); holder.handleEventFromOperator(0, 0, new AcknowledgeCheckpointEvent(22L)); holder.handleEventFromOperator(1, 0, new AcknowledgeCheckpointEvent(22L)); holder.handleEventFromOperator(2, 0, new AcknowledgeCheckpointEvent(22L)); getCoordinator(holder).getSubtaskGateway(0).sendEvent(new TestOperatorEvent(2)); triggerAndCompleteCheckpoint(holder, 23L); getCoordinator(holder).getSubtaskGateway(0).sendEvent(new TestOperatorEvent(3)); holder.handleEventFromOperator(0, 0, new AcknowledgeCheckpointEvent(23L)); holder.handleEventFromOperator(1, 0, new AcknowledgeCheckpointEvent(23L)); holder.handleEventFromOperator(2, 0, new AcknowledgeCheckpointEvent(23L)); assertThat(tasks.getSentEventsForSubtask(0)) .containsExactly( new TestOperatorEvent(0), new TestOperatorEvent(1), new TestOperatorEvent(2), new TestOperatorEvent(3)); }
public static <T> T fillBeanWithMapIgnoreCase(Map<?, ?> map, T bean, boolean isIgnoreError) { return fillBeanWithMap(map, bean, CopyOptions.create().setIgnoreCase(true).setIgnoreError(isIgnoreError)); }
@Test public void fillBeanWithMapIgnoreCaseTest() { final Map<String, Object> map = MapBuilder.<String, Object>create() .put("Name", "Joe") .put("aGe", 12) .put("openId", "DFDFSDFWERWER") .build(); final SubPerson person = BeanUtil.fillBeanWithMapIgnoreCase(map, new SubPerson(), false); assertEquals("Joe", person.getName()); assertEquals(12, person.getAge()); assertEquals("DFDFSDFWERWER", person.getOpenid()); }
@Override public ExecuteContext before(ExecuteContext context) { Set<String> matchKeys = configService.getMatchKeys(); Set<String> injectTags = configService.getInjectTags(); if (CollectionUtils.isEmpty(matchKeys) && CollectionUtils.isEmpty(injectTags)) { // The staining mark is empty, which means that there are no staining rules, and it is returned directly return context; } Object[] arguments = context.getArguments(); handlers.forEach(handler -> ThreadLocalUtils.addRequestTag(handler.getRequestTag( arguments[0], arguments[1], DubboReflectUtils.getAttachments(arguments[1]), matchKeys, injectTags))); return context; }
@Test public void testBefore() { // Test before method interceptor.before(context); RequestTag requestTag = ThreadLocalUtils.getRequestTag(); Map<String, List<String>> header = requestTag.getTag(); Assert.assertNotNull(header); Assert.assertEquals(2, header.size()); Assert.assertEquals("bar1", header.get("bar").get(0)); Assert.assertEquals("foo1", header.get("foo").get(0)); }
public static boolean isNoneBlank(final CharSequence... css) { return !isAnyBlank(css); }
@Test void testIsNoneBlank() { assertFalse(StringUtils.isNoneBlank(null)); assertFalse(StringUtils.isNoneBlank(null, "foo")); assertFalse(StringUtils.isNoneBlank(null, null)); assertFalse(StringUtils.isNoneBlank("", "bar")); assertFalse(StringUtils.isNoneBlank("bob", "")); assertFalse(StringUtils.isNoneBlank(" bob ", null)); assertFalse(StringUtils.isNoneBlank(" ", "bar")); assertTrue(StringUtils.isNoneBlank("foo", "bar")); }
public DLQEntry pollEntry(long timeout) throws IOException, InterruptedException { byte[] bytes = pollEntryBytes(timeout); if (bytes == null) { return null; } return DLQEntry.deserialize(bytes); }
@Test public void testReaderWhenAllRemaningSegmentsAreRemoved() throws IOException, InterruptedException { int remainingEventsInSegment = prepareFilledSegmentFiles(3); try (DeadLetterQueueReader reader = new DeadLetterQueueReader(dir)) { // read the first event to initialize reader structures final DLQEntry dlqEntry = reader.pollEntry(1_000); assertEquals("00000", dlqEntry.getReason()); remainingEventsInSegment--; // simulate a retention policy clean, that drops the remaining segments Files.list(dir) .sorted() .skip(1) .forEach(DeadLetterQueueReaderTest::deleteSegment); // consume the first segment for (int i = 0; i < remainingEventsInSegment; i++) { reader.pollEntry(1_000); } // Exercise // consume the first event after the hole final DLQEntry entryAfterHole = reader.pollEntry(1_000); assertNull(entryAfterHole); } }
public void setDepth(int depth) { int[] allowedValues = {2, 4, 8, 16, 32, 64, 256, 4096}; for (int allowedValue : allowedValues) { if (depth == allowedValue) { this.depth = depth; userConfigured.add("depth"); return; } } throw new IllegalArgumentException( "Invalid depth value. Valid values are 2, 4, 8, 16, 32, 64, 256, 4096."); }
@Test public void testValidateDepth() { TesseractOCRConfig config = new TesseractOCRConfig(); config.setDepth(4); config.setDepth(8); assertTrue(true, "Couldn't set valid values"); assertThrows(IllegalArgumentException.class, () -> { config.setDepth(6); }); }
@Override public long readLong(@Nonnull String fieldName) throws IOException { FieldDefinition fd = cd.getField(fieldName); if (fd == null) { return 0L; } switch (fd.getType()) { case LONG: return super.readLong(fieldName); case INT: return super.readInt(fieldName); case BYTE: return super.readByte(fieldName); case CHAR: return super.readChar(fieldName); case SHORT: return super.readShort(fieldName); default: throw createIncompatibleClassChangeError(fd, LONG); } }
@Test(expected = IncompatibleClassChangeError.class) public void testReadLong_IncompatibleClass() throws Exception { reader.readLong("string"); }
@Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { var msgDataAsJsonNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null; processFieldsData(ctx, msg, msg.getOriginator(), msgDataAsJsonNode, config.isIgnoreNullStrings()); }
@Test public void givenValidMsgAndFetchToMetaData_whenOnMsg_thenShouldTellSuccessAndFetchToMetaData() throws TbNodeException, ExecutionException, InterruptedException { // GIVEN var device = new Device(); device.setId(DUMMY_DEVICE_ORIGINATOR); device.setName("Test device"); device.setType("Test device type"); config.setDataMapping(Map.of( "name", "originatorName", "type", "originatorType", "label", "originatorLabel")); config.setIgnoreNullStrings(true); config.setFetchTo(TbMsgSource.METADATA); node.config = config; node.fetchTo = TbMsgSource.METADATA; var msgMetaData = new TbMsgMetaData(Map.of( "testKey1", "testValue1", "testKey2", "123")); var msgData = "[\"value1\",\"value2\"]"; msg = TbMsg.newMsg(TbMsgType.POST_TELEMETRY_REQUEST, DUMMY_DEVICE_ORIGINATOR, msgMetaData, msgData); when(ctxMock.getDeviceService()).thenReturn(deviceServiceMock); when(ctxMock.getTenantId()).thenReturn(DUMMY_TENANT_ID); when(deviceServiceMock.findDeviceById(eq(DUMMY_TENANT_ID), eq(device.getId()))).thenReturn(device); when(ctxMock.getDbCallbackExecutor()).thenReturn(DB_EXECUTOR); // WHEN node.onMsg(ctxMock, msg); // THEN var actualMessageCaptor = ArgumentCaptor.forClass(TbMsg.class); verify(ctxMock, times(1)).tellSuccess(actualMessageCaptor.capture()); verify(ctxMock, never()).tellFailure(any(), any()); var expectedMsgMetaData = new TbMsgMetaData(Map.of( "testKey1", "testValue1", "testKey2", "123", "originatorName", "Test device", "originatorType", "Test device type" )); assertThat(actualMessageCaptor.getValue().getData()).isEqualTo(msgData); assertThat(actualMessageCaptor.getValue().getMetaData()).isEqualTo(expectedMsgMetaData); }
public static UParens create(UExpression expression) { return new AutoValue_UParens(expression); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(UParens.create(ULiteral.longLit(5L))) .addEqualityGroup(UParens.create(ULiteral.intLit(5))) .addEqualityGroup(UParens.create(UUnary.create(Kind.UNARY_MINUS, ULiteral.intLit(5)))) .addEqualityGroup( UParens.create(UBinary.create(Kind.PLUS, ULiteral.intLit(5), ULiteral.intLit(1)))) .testEquals(); }
@Override public LogicalSchema getSchema() { return schema; }
@Test public void shouldBuildCorrectVarArgAggregateSchema() { // When: final SchemaKStream<?> stream = buildQuery("SELECT col0, var_arg(col0, col1, col2) FROM test1 " + "window TUMBLING (size 2 second) " + "WHERE col0 > 100 GROUP BY col0 EMIT CHANGES;"); // Then: assertThat(stream.getSchema(), is(LogicalSchema.builder() .keyColumn(ColumnName.of("COL0"), SqlTypes.BIGINT) .valueColumn(ColumnName.of("COL0"), SqlTypes.BIGINT) .valueColumn(ColumnName.of("KSQL_COL_0"), SqlTypes.BIGINT) .build() )); }
public String deserialize(String password, String encryptedPassword, Validatable config) { if (isNotBlank(password) && isNotBlank(encryptedPassword)) { config.addError(PASSWORD, "You may only specify `password` or `encrypted_password`, not both!"); config.addError(ScmMaterialConfig.ENCRYPTED_PASSWORD, "You may only specify `password` or `encrypted_password`, not both!"); } if (isNotBlank(password)) { try { return goCipher.encrypt(password); } catch (CryptoException e) { config.addError(PASSWORD, "Could not encrypt the password. This usually happens when the cipher text is invalid"); } } else if (isNotBlank(encryptedPassword)) { try { goCipher.decrypt(encryptedPassword); } catch (Exception e) { config.addError(ENCRYPTED_PASSWORD, "Encrypted value for password is invalid. This usually happens when the cipher text is invalid."); } return encryptedPassword; } return null; }
@Test public void shouldEncryptClearTextPasswordSentByUser() throws CryptoException { SvnMaterialConfig svnMaterialConfig = svn(); PasswordDeserializer passwordDeserializer = new PasswordDeserializer(); String encrypted = passwordDeserializer.deserialize("password", null, svnMaterialConfig); assertThat(encrypted, is(new GoCipher().encrypt("password"))); }
void addFunction(final T function) { final List<ParameterInfo> parameters = function.parameterInfo(); if (allFunctions.put(function.parameters(), function) != null) { throw new KsqlFunctionException( "Can't add function " + function.name() + " with parameters " + function.parameters() + " as a function with the same name and parameter types already exists " + allFunctions.get(function.parameters()) ); } /* Build the tree for non-variadic functions, or build the tree that includes one variadic argument for variadic functions. */ final Pair<Node, Integer> variadicParentAndOffset = buildTree( root, parameters, function, false, false ); final Node variadicParent = variadicParentAndOffset.getLeft(); if (variadicParent != null) { final int offset = variadicParentAndOffset.getRight(); // Build a branch of the tree that handles var args given as list. buildTree(variadicParent, parameters, function, true, false); // Determine which side the variadic parameter is on. final boolean isLeftVariadic = parameters.get(offset).isVariadic(); /* Build a branch of the tree that handles no var args by excluding the variadic param. Note that non-variadic parameters that are always paired with another non-variadic parameter are not included in paramsWithoutVariadic. For example, if the function signature is (int, boolean..., double, bigint, decimal), then paramsWithoutVariadic will be [double, bigint]. The (int, decimal) edge will be in a node above the variadicParent, so we need to only include parameters that might be paired with a variadic parameter. */ final List<ParameterInfo> paramsWithoutVariadic = isLeftVariadic ? parameters.subList(offset + 1, parameters.size() - offset) : parameters.subList(offset, parameters.size() - offset - 1); buildTree( variadicParent, paramsWithoutVariadic, function, false, false ); // Build branches of the tree that handles more than two var args. final ParameterInfo variadicParam = isLeftVariadic ? parameters.get(offset) : parameters.get(parameters.size() - offset - 1); // Create copies of the variadic parameter that will be used to build the tree. final int maxAddedVariadics = paramsWithoutVariadic.size() + 1; final List<ParameterInfo> addedVariadics = Collections.nCopies( maxAddedVariadics, variadicParam ); // Add the copies of the variadic parameter on the same side as the variadic parameter. final List<ParameterInfo> combinedAllParams = new ArrayList<>(); int fromIndex; int toIndex; if (isLeftVariadic) { combinedAllParams.addAll(addedVariadics); combinedAllParams.addAll(paramsWithoutVariadic); fromIndex = maxAddedVariadics - 1; toIndex = combinedAllParams.size(); } else { combinedAllParams.addAll(paramsWithoutVariadic); combinedAllParams.addAll(addedVariadics); fromIndex = 0; toIndex = combinedAllParams.size() - maxAddedVariadics + 1; } /* Successively build branches of the tree that include one additional variadic parameter until maxAddedVariadics have been processed. During the first iteration, buildTree() iterates through the already-created branch for the case where there is one variadic parameter. This is necessary because the variadic loop was not added when that branch was built, but it needs to be added if there are no non-variadic parameters (i.e. paramsWithoutVariadic.size() == 0 and maxAddedVariadics == 1). The number of nodes added here is quadratic with respect to paramsWithoutVariadic.size(). However, this tree is only built on ksql startup, and this tree structure allows resolving functions with variadic arguments in the middle in linear time. The number of node generated as a function of paramsWithoutVariadic.size() is roughly 0.25x^2 + 1.5x + 3, which is not excessive for reasonable numbers of arguments. */ while (fromIndex >= 0 && toIndex <= combinedAllParams.size()) { buildTree( variadicParent, combinedAllParams.subList(fromIndex, toIndex), function, false, /* Add the variadic loop after longest branch to handle variadic parameters not paired with a non-variadic parameter. */ toIndex - fromIndex == combinedAllParams.size() ); // Increment the size of the sublist in the direction of the variadic parameters. if (isLeftVariadic) { fromIndex--; } else { toIndex++; } } } }
@Test public void shouldThrowOnAddFunctionSameParamsExceptOneVariadic() { // Given: givenFunctions( function(EXPECTED, -1, STRING_VARARGS) ); // When: final Exception e = assertThrows( KsqlFunctionException.class, () -> udfIndex.addFunction(function(EXPECTED, 0, STRING_VARARGS)) ); // Then: assertThat(e.getMessage(), startsWith("Can't add function `expected` with parameters" + " [ARRAY<VARCHAR>] as a function with the same name and parameter types already" + " exists")); }
static List<String> parse(String cmdline) { List<String> matchList = new ArrayList<>(); Matcher shellwordsMatcher = SHELLWORDS_PATTERN.matcher(cmdline); while (shellwordsMatcher.find()) { if (shellwordsMatcher.group(1) != null) { matchList.add(shellwordsMatcher.group(1)); } else { String shellword = shellwordsMatcher.group(); if (shellword.startsWith("\"") && shellword.endsWith("\"") && shellword.length() > 2) { shellword = shellword.substring(1, shellword.length() - 1); } matchList.add(shellword); } } return matchList; }
@Test void parses_single_quoted_strings() { assertThat(ShellWords.parse("--name 'The Fox'"), is(equalTo(asList("--name", "The Fox")))); }
@Udf public String extractProtocol( @UdfParameter(description = "a valid URL to extract a protocl from") final String input) { return UrlParser.extract(input, URI::getScheme); }
@Test public void shouldExtractProtocolIfPresent() { assertThat( extractUdf.extractProtocol("https://docs.confluent.io/current/ksql/docs/syntax-reference.html#scalar-functions"), equalTo("https")); }