focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static String initNamespaceForNaming(NacosClientProperties properties) { String tmpNamespace = null; String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, properties.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, String.valueOf(Constants.DEFAULT_USE_CLOUD_NAMESPACE_PARSING))); if (Boolean.parseBoolean(isUseCloudNamespaceParsing)) { tmpNamespace = TenantUtil.getUserTenantForAns(); LogUtils.NAMING_LOGGER.info("initializer namespace from ans.namespace attribute : {}", tmpNamespace); tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> { String namespace = properties.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE); LogUtils.NAMING_LOGGER.info("initializer namespace from ALIBABA_ALIWARE_NAMESPACE attribute :" + namespace); return namespace; }); } tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> { String namespace = properties.getPropertyFrom(SourceType.JVM, PropertyKeyConst.NAMESPACE); LogUtils.NAMING_LOGGER.info("initializer namespace from namespace attribute :" + namespace); return namespace; }); if (StringUtils.isEmpty(tmpNamespace)) { tmpNamespace = properties.getProperty(PropertyKeyConst.NAMESPACE); } tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> UtilAndComs.DEFAULT_NAMESPACE_ID); return tmpNamespace; }
@Test void testInitNamespaceFromJvmNamespaceWithCloudParsing() { String expect = "jvm_namespace"; System.setProperty(PropertyKeyConst.NAMESPACE, expect); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String ns = InitUtils.initNamespaceForNaming(properties); assertEquals(expect, ns); }
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } return results; }
@Test public void fabricMissingMinecraft() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/fabric-minecraft.txt")), CrashReportAnalyzer.Rule.MOD_RESOLUTION_MISSING_MINECRAFT); assertEquals("fabric", result.getMatcher().group("mod")); assertEquals("[~1.16.2-alpha.20.28.a]", result.getMatcher().group("version")); }
public static List<String> validateJsonMessage(JsonNode specificationNode, JsonNode jsonNode, String messagePathPointer) { return validateJsonMessage(specificationNode, jsonNode, messagePathPointer, null); }
@Test void testFullProcedureFromSwaggerResource() { String openAPIText = null; String jsonText = "{\n" + " \"name\": \"Rodenbach\",\n" + " \"country\": \"Belgium\",\n" + " \"type\": \"Fruit\",\n" + " \"rating\": 4.3,\n" + " \"status\": \"available\"\n" + "}"; JsonNode openAPISpec = null; JsonNode contentNode = null; try { // Load full specification from file. openAPIText = FileUtils.readFileToString( new File("target/test-classes/io/github/microcks/util/openapi/beer-catalog-api-swagger.yaml")); // Extract JSON nodes using OpenAPISchemaValidator methods. openAPISpec = OpenAPISchemaValidator.getJsonNodeForSchema(openAPIText); contentNode = OpenAPISchemaValidator.getJsonNode(jsonText); } catch (Exception e) { fail("Exception should not be thrown"); } // Validate the content for Get /beer/{name} response message. List<String> errors = SwaggerSchemaValidator.validateJsonMessage(openAPISpec, contentNode, "/paths/~1beer~1{name}/get/responses/200"); assertTrue(errors.isEmpty()); }
@VisibleForTesting static void checkAuthorization(ReqContext reqContext, IAuthorizer auth, String operation, String function) throws AuthorizationException { checkAuthorization(reqContext, auth, operation, function, true); }
@Test public void testNotStrict() throws Exception { ReqContext jt = new ReqContext(new Subject()); SingleUserPrincipal jumpTopo = new SingleUserPrincipal("jump_topo"); jt.subject().getPrincipals().add(jumpTopo); ReqContext jc = new ReqContext(new Subject()); SingleUserPrincipal jumpClient = new SingleUserPrincipal("jump_client"); jc.subject().getPrincipals().add(jumpClient); ReqContext other = new ReqContext(new Subject()); SingleUserPrincipal otherUser = new SingleUserPrincipal("other"); other.subject().getPrincipals().add(otherUser); Map<String, AclFunctionEntry> acl = new HashMap<>(); acl.put("jump", new AclFunctionEntry(Collections.singletonList(jumpClient.getName()), jumpTopo.getName())); Map<String, Object> conf = new HashMap<>(); conf.put(Config.DRPC_AUTHORIZER_ACL_STRICT, false); conf.put(Config.STORM_PRINCIPAL_TO_LOCAL_PLUGIN, DefaultPrincipalToLocal.class.getName()); DRPCSimpleACLAuthorizer auth = new DRPCSimpleACLAuthorizer() { @Override protected Map<String, AclFunctionEntry> readAclFromConfig() { return acl; } }; auth.prepare(conf); //JUMP DRPC.checkAuthorization(jt, auth, "fetchRequest", "jump"); assertThrows(() -> DRPC.checkAuthorization(jc, auth, "fetchRequest", "jump"), AuthorizationException.class); assertThrows(() -> DRPC.checkAuthorization(other, auth, "fetchRequest", "jump"), AuthorizationException.class); DRPC.checkAuthorization(jt, auth, "result", "jump"); assertThrows(() -> DRPC.checkAuthorization(jc, auth, "result", "jump"), AuthorizationException.class); assertThrows(() -> DRPC.checkAuthorization(other, auth, "result", "jump"), AuthorizationException.class); assertThrows(() -> DRPC.checkAuthorization(jt, auth, "execute", "jump"), AuthorizationException.class); DRPC.checkAuthorization(jc, auth, "execute", "jump"); assertThrows(() -> DRPC.checkAuthorization(other, auth, "execute", "jump"), AuthorizationException.class); //not_jump (open in not strict mode) DRPC.checkAuthorization(jt, auth, "fetchRequest", "not_jump"); DRPC.checkAuthorization(jc, auth, "fetchRequest", "not_jump"); DRPC.checkAuthorization(other, auth, "fetchRequest", "not_jump"); DRPC.checkAuthorization(jt, auth, "result", "not_jump"); DRPC.checkAuthorization(jc, auth, "result", "not_jump"); DRPC.checkAuthorization(other, auth, "result", "not_jump"); DRPC.checkAuthorization(jt, auth, "execute", "not_jump"); DRPC.checkAuthorization(jc, auth, "execute", "not_jump"); DRPC.checkAuthorization(other, auth, "execute", "not_jump"); }
@Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); boolean shouldAuth = url.getParameter(Constants.SERVICE_AUTH, false); if (shouldAuth) { Authenticator authenticator = applicationModel .getExtensionLoader(Authenticator.class) .getExtension(url.getParameter(Constants.AUTHENTICATOR, Constants.DEFAULT_AUTHENTICATOR)); try { authenticator.authenticate(invocation, url); } catch (Exception e) { return AsyncRpcResult.newDefaultAsyncResult(e, invocation); } } return invoker.invoke(invocation); }
@Test void testAuthSuccessfully() { String service = "org.apache.dubbo.DemoService"; String method = "test"; long currentTimeMillis = System.currentTimeMillis(); URL url = URL.valueOf("dubbo://10.10.10.10:2181") .setServiceInterface(service) .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk") .addParameter(CommonConstants.APPLICATION_KEY, "test-provider") .addParameter(Constants.SERVICE_AUTH, true); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(RpcInvocation.class); when(invocation.getAttachment(Constants.AK_KEY)).thenReturn("ak"); when(invocation.getAttachment(CommonConstants.CONSUMER)).thenReturn("test-consumer"); when(invocation.getAttachment(Constants.REQUEST_TIMESTAMP_KEY)).thenReturn(String.valueOf(currentTimeMillis)); when(invocation.getMethodName()).thenReturn(method); when(invoker.getUrl()).thenReturn(url); String requestString = String.format( Constants.SIGNATURE_STRING_FORMAT, url.getColonSeparatedKey(), invocation.getMethodName(), "sk", currentTimeMillis); String sign = SignatureUtils.sign(requestString, "sk"); when(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(sign); ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel()); Result result = providerAuthFilter.invoke(invoker, invocation); assertNull(result); }
public static <T> KNN<T> fit(T[] x, int[] y, Distance<T> distance) { return fit(x, y, 1, distance); }
@Test public void testBreastCancer() { System.out.println("Breast Cancer"); MathEx.setSeed(19650218); // to get repeatable results. ClassificationValidations<KNN<double[]>> result = CrossValidation.classification(10, BreastCancer.x, BreastCancer.y, (x, y) -> KNN.fit(x, y, 3)); System.out.println(result); assertEquals(0.9232, result.avg.accuracy, 1E-4); }
@Override public ByteBuf slice() { return slice(readerIndex, readableBytes()); }
@Test public void testSliceAfterRelease2() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().slice(0, 1); } }); }
public static Map<String, ServiceInfo> read(String cacheDir) { Map<String, ServiceInfo> domMap = new HashMap<>(16); try { File[] files = makeSureCacheDirExists(cacheDir).listFiles(); if (files == null || files.length == 0) { return domMap; } for (File file : files) { if (!file.isFile()) { continue; } domMap.putAll(parseServiceInfoFromCache(file)); } } catch (Throwable e) { NAMING_LOGGER.error("[NA] failed to read cache file", e); } return domMap; }
@Test void testReadCacheForAllSituation() { String dir = DiskCacheTest.class.getResource("/").getPath() + "/disk_cache_test"; Map<String, ServiceInfo> actual = DiskCache.read(dir); assertEquals(2, actual.size()); assertTrue(actual.containsKey("legal@@no_name@@file")); assertEquals("1.1.1.1", actual.get("legal@@no_name@@file").getHosts().get(0).getIp()); assertTrue(actual.containsKey("legal@@with_name@@file")); assertEquals("1.1.1.1", actual.get("legal@@with_name@@file").getHosts().get(0).getIp()); }
public static <InputT, OutputT> Growth<InputT, OutputT, OutputT> growthOf( Growth.PollFn<InputT, OutputT> pollFn, Requirements requirements) { return new AutoValue_Watch_Growth.Builder<InputT, OutputT, OutputT>() .setTerminationPerInput(Growth.never()) .setPollFn(Contextful.of(pollFn, requirements)) // use null as a signal that this is the identity function and output coder can be // reused as key coder .setOutputKeyFn(null) .build(); }
@Test public void testPollingGrowthTrackerUsesElementTimestampIfNoWatermarkProvided() throws Exception { Instant now = Instant.now(); Watch.Growth<String, String, String> growth = Watch.growthOf( new Watch.Growth.PollFn<String, String>() { @Override public PollResult<String> apply(String element, Context c) throws Exception { // We specifically test an unsorted list. return PollResult.incomplete( Arrays.asList( TimestampedValue.of("d", now.plus(standardSeconds(4))), TimestampedValue.of("c", now.plus(standardSeconds(3))), TimestampedValue.of("a", now.plus(standardSeconds(1))), TimestampedValue.of("b", now.plus(standardSeconds(2))))); } }) .withPollInterval(standardSeconds(10)); WatchGrowthFn<String, String, String, Integer> growthFn = new WatchGrowthFn( growth, StringUtf8Coder.of(), SerializableFunctions.identity(), StringUtf8Coder.of()); GrowthTracker<String, Integer> tracker = newPollingGrowthTracker(); DoFn.ProcessContext context = mock(DoFn.ProcessContext.class); ManualWatermarkEstimator<Instant> watermarkEstimator = new WatermarkEstimators.Manual(BoundedWindow.TIMESTAMP_MIN_VALUE); ProcessContinuation processContinuation = growthFn.process(context, tracker, watermarkEstimator); assertEquals(now.plus(standardSeconds(1)), watermarkEstimator.currentWatermark()); assertTrue(processContinuation.shouldResume()); }
@SneakyThrows // compute() doesn't throw checked exceptions public static String sha256Hex(String string) { return sha256DigestCache.get(string, () -> compute(string, DigestObjectPools.SHA_256)); }
@Test public void shouldComputeForAGivenStringUsingSHA_256() { String fingerprint = "Some String"; String digest = sha256Hex(fingerprint); assertEquals(DigestUtils.sha256Hex(fingerprint), digest); }
public static byte[] compress(byte[] bytes) { if (bytes == null) { throw new NullPointerException("bytes is null"); } return Zstd.compress(bytes); }
@Test public void test_compress() { Assertions.assertThrows(NullPointerException.class, () -> { ZstdUtil.compress(null); }); }
public boolean isGlobalOrderingEnabled() { return globalOrderingEnabled; }
@Test public void testIsGlobalOrderingEnabled() { TopicConfig topicConfig = new TopicConfig(); assertFalse(topicConfig.isGlobalOrderingEnabled()); }
public abstract void broadcastEmit(T record) throws IOException;
@TestTemplate void testBroadcastEmitRecord(@TempDir Path tempPath) throws Exception { final int numberOfSubpartitions = 4; final int bufferSize = 32; final int numValues = 8; final int serializationLength = 4; final ResultPartition partition = createResultPartition(bufferSize, numberOfSubpartitions); final RecordWriter<SerializationTestType> writer = createRecordWriter(partition); final RecordDeserializer<SerializationTestType> deserializer = new SpillingAdaptiveSpanningRecordDeserializer<>( new String[] {tempPath.toString()}); final ArrayDeque<SerializationTestType> serializedRecords = new ArrayDeque<>(); final Iterable<SerializationTestType> records = Util.randomRecords(numValues, SerializationTestTypeFactory.INT); for (SerializationTestType record : records) { serializedRecords.add(record); writer.broadcastEmit(record); } final int numRequiredBuffers = numValues / (bufferSize / (4 + serializationLength)); if (isBroadcastWriter) { assertThat(partition.getBufferPool().bestEffortGetNumOfUsedBuffers()) .isEqualTo(numRequiredBuffers); } else { assertThat(partition.getBufferPool().bestEffortGetNumOfUsedBuffers()) .isEqualTo(numRequiredBuffers * numberOfSubpartitions); } for (int i = 0; i < numberOfSubpartitions; i++) { assertThat(partition.getNumberOfQueuedBuffers(i)).isEqualTo(numRequiredBuffers); ResultSubpartitionView view = partition.createSubpartitionView( new ResultSubpartitionIndexSet(i), new NoOpBufferAvailablityListener()); verifyDeserializationResults( view, deserializer, serializedRecords.clone(), numRequiredBuffers, numValues); } }
public StatusInfo getStatusInfo() { StatusInfo.Builder builder = StatusInfo.Builder.newBuilder(); // Add application level status int upReplicasCount = 0; StringBuilder upReplicas = new StringBuilder(); StringBuilder downReplicas = new StringBuilder(); StringBuilder replicaHostNames = new StringBuilder(); for (PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) { if (replicaHostNames.length() > 0) { replicaHostNames.append(", "); } replicaHostNames.append(node.getServiceUrl()); if (isReplicaAvailable(node.getServiceUrl())) { upReplicas.append(node.getServiceUrl()).append(','); upReplicasCount++; } else { downReplicas.append(node.getServiceUrl()).append(','); } } builder.add("registered-replicas", replicaHostNames.toString()); builder.add("available-replicas", upReplicas.toString()); builder.add("unavailable-replicas", downReplicas.toString()); // Only set the healthy flag if a threshold has been configured. if (peerEurekaNodes.getMinNumberOfAvailablePeers() > -1) { builder.isHealthy(upReplicasCount >= peerEurekaNodes.getMinNumberOfAvailablePeers()); } builder.withInstanceInfo(this.instanceInfo); return builder.build(); }
@Test public void testGetStatusInfoUnhealthy() { StatusUtil statusUtil = getStatusUtil(5, 3, 4); assertFalse(statusUtil.getStatusInfo().isHealthy()); }
public Database getDb(String dbName) { return metastore.getDb(dbName); }
@Test public void testGetDb() { Database database = hmsOps.getDb("db1"); Assert.assertEquals("db1", database.getFullName()); try { hmsOps.getDb("db2"); Assert.fail(); } catch (Exception e) { Assert.assertTrue(e instanceof StarRocksConnectorException); } }
@Override public AppResponse process(Flow flow, ActivateAppRequest body) { String decodedPin = ChallengeService.decodeMaskedPin(appSession.getIv(), appAuthenticator.getSymmetricKey(), body.getMaskedPincode()); if ((decodedPin == null || !Pattern.compile("\\d{5}").matcher(decodedPin).matches())) { return flow.setFailedStateAndReturnNOK(appSession); } else if (!appAuthenticator.getUserAppId().equals(body.getUserAppId())){ digidClient.remoteLog("754", Map.of(lowerUnderscore(ACCOUNT_ID) ,appAuthenticator.getAccountId())); return flow.setFailedStateAndReturnNOK(appSession); } appAuthenticator.setMaskedPin(decodedPin); appAuthenticator.setLastSignInAt(ZonedDateTime.now()); if (!switchService.digidAppSwitchEnabled() ) { digidClient.remoteLog("824", Map.of(lowerUnderscore(ACCOUNT_ID), appAuthenticator.getAccountId())); throw new SwitchDisabledException(); } if (flow instanceof RequestAccountAndAppFlow || flow instanceof ActivateAppWithPasswordLetterFlow) { Map<String, String> result = digidClient.finishRegistration(appSession.getRegistrationId(), appSession.getAccountId(), flow.getName()); if (result.get(lowerUnderscore(STATUS)).equals("PENDING") && result.get(lowerUnderscore(ACTIVATION_CODE)) != null && result.get(lowerUnderscore(GELDIGHEIDSTERMIJN)) != null) { appAuthenticator.setStatus("pending"); appAuthenticator.setActivationCode(result.get(lowerUnderscore(ACTIVATION_CODE))); appAuthenticator.setGeldigheidstermijn(result.get(lowerUnderscore(GELDIGHEIDSTERMIJN))); appAuthenticator.setRequestedAt(ZonedDateTime.now()); return new StatusResponse("PENDING"); } else { return new NokResponse(); } } else { return ((ActivationFlow) flow).activateApp(appAuthenticator, appSession); } }
@Test void processNOKRequestAccountAndAppFlow(){ Map<String, String> finishRegistrationResponse = Map.of(lowerUnderscore(STATUS), "ERROR"); when(switchService.digidAppSwitchEnabled()).thenReturn(true); when(digidClientMock.finishRegistration(TEST_REGISTRATION_ID, TEST_ACCOUNT_ID, RequestAccountAndAppFlow.NAME)).thenReturn(finishRegistrationResponse); AppResponse appResponse = pincodeSet.process(mockedRequestFlow, mockedActivateAppRequest); assertTrue(appResponse instanceof NokResponse); assertEquals("initial", mockedAppAuthenticator.getStatus()); }
public static ResourceModel processResource(final Class<?> resourceClass) { return processResource(resourceClass, null); }
@Test(expectedExceptions = ResourceConfigException.class) public void failsOnInvalidQueryParamAnnotationTypeRef() { @RestLiCollection(name = "brokenParam") class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord> { @Finder("brokenParam") public void brokenParam(@QueryParam(value = "someId", typeref = BrokenTypeRef.class) BrokenTypeRef typeRef) { } } RestLiAnnotationReader.processResource(LocalClass.class); Assert.fail("#buildQueryParam should fail throwing a ResourceConfigException"); }
public static void main(String[] args) { LOGGER.info("Librarian begins their work."); // Defining genre book functions Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY); Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR); Book.AddAuthor scifiBookFunc = Book.builder().withGenre(Genre.SCIFI); // Defining author book functions Book.AddTitle kingFantasyBooksFunc = fantasyBookFunc.withAuthor("Stephen King"); Book.AddTitle kingHorrorBooksFunc = horrorBookFunc.withAuthor("Stephen King"); Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling"); // Creates books by Stephen King (horror and fantasy genres) Book shining = kingHorrorBooksFunc.withTitle("The Shining") .withPublicationDate(LocalDate.of(1977, 1, 28)); Book darkTower = kingFantasyBooksFunc.withTitle("The Dark Tower: Gunslinger") .withPublicationDate(LocalDate.of(1982, 6, 10)); // Creates fantasy books by J.K. Rowling Book chamberOfSecrets = rowlingFantasyBooksFunc.withTitle("Harry Potter and the Chamber of Secrets") .withPublicationDate(LocalDate.of(1998, 7, 2)); // Create sci-fi books Book dune = scifiBookFunc.withAuthor("Frank Herbert") .withTitle("Dune") .withPublicationDate(LocalDate.of(1965, 8, 1)); Book foundation = scifiBookFunc.withAuthor("Isaac Asimov") .withTitle("Foundation") .withPublicationDate(LocalDate.of(1942, 5, 1)); LOGGER.info("Stephen King Books:"); LOGGER.info(shining.toString()); LOGGER.info(darkTower.toString()); LOGGER.info("J.K. Rowling Books:"); LOGGER.info(chamberOfSecrets.toString()); LOGGER.info("Sci-fi Books:"); LOGGER.info(dune.toString()); LOGGER.info(foundation.toString()); }
@Test void executesWithoutExceptions() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public <T> boolean execute(final Predicate<T> predicate, final T arg) { do { if (predicate.test(arg)) { return true; } } while (!isTimeout()); return false; }
@Test void assertExecute() { assertTrue(new RetryExecutor(5L, 2L).execute(value -> value > 0, 1)); }
public String register(Namespace ns) { return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns), "register"); }
@Test public void testRegister() { Namespace ns = Namespace.of("ns"); assertThat(withPrefix.register(ns)).isEqualTo("v1/ws/catalog/namespaces/ns/register"); assertThat(withoutPrefix.register(ns)).isEqualTo("v1/namespaces/ns/register"); }
@Override protected void doUpdate(final List<AppAuthData> dataList) { dataList.forEach(appAuthData -> authDataSubscribers.forEach(authDataSubscriber -> authDataSubscriber.onSubscribe(appAuthData))); }
@Test public void testDoUpdate() { List<AppAuthData> appAuthDataList = createFakerAppAuthDataObjects(4); authDataHandler.doUpdate(appAuthDataList); appAuthDataList.forEach(appAuthData -> authDataSubscribers.forEach(authDataSubscriber -> verify(authDataSubscriber).onSubscribe(appAuthData))); }
public static String prepareDomain(final String domain) { // A typical issue is regular expressions that also capture a whitespace at the beginning or the end. String trimmedDomain = domain.trim(); // Some systems will capture DNS requests with a trailing '.'. Remove that for the lookup. if(trimmedDomain.endsWith(".")) { trimmedDomain = trimmedDomain.substring(0, trimmedDomain.length()-1); } return trimmedDomain; }
@Test public void testPrepareDomain() throws Exception { // Trimming. assertEquals("example.org", Domain.prepareDomain("example.org ")); assertEquals("example.org", Domain.prepareDomain(" example.org")); assertEquals("example.org", Domain.prepareDomain(" example.org ")); // Getting rid of that last dot some systems will include in domain names. assertEquals("example.org", Domain.prepareDomain("example.org. ")); assertEquals("example.org", Domain.prepareDomain(" example.org.")); assertEquals("example.org", Domain.prepareDomain(" example.org. ")); }
static void setEntryValue( StepInjectionMetaEntry entry, RowMetaAndData row, SourceStepField source ) throws KettleValueException { // A standard attribute, a single row of data... // Object value = null; switch ( entry.getValueType() ) { case ValueMetaInterface.TYPE_STRING: value = row.getString( source.getField(), null ); break; case ValueMetaInterface.TYPE_BOOLEAN: value = row.getBoolean( source.getField(), false ); break; case ValueMetaInterface.TYPE_INTEGER: value = row.getInteger( source.getField(), 0L ); break; case ValueMetaInterface.TYPE_NUMBER: value = row.getNumber( source.getField(), 0.0D ); break; case ValueMetaInterface.TYPE_DATE: value = row.getDate( source.getField(), null ); break; case ValueMetaInterface.TYPE_BIGNUMBER: value = row.getBigNumber( source.getField(), null ); break; default: break; } entry.setValue( value ); }
@Test public void setEntryValue_number() throws KettleValueException { StepInjectionMetaEntry entry = mock( StepInjectionMetaEntry.class ); doReturn( ValueMetaInterface.TYPE_NUMBER ).when( entry ).getValueType(); RowMetaAndData row = createRowMetaAndData( new ValueMetaNumber( TEST_FIELD ), 1D ); SourceStepField sourceField = new SourceStepField( TEST_SOURCE_STEP_NAME, TEST_FIELD ); MetaInject.setEntryValue( entry, row, sourceField ); verify( entry ).setValue( 1.0D ); }
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n, @ParameterName( "scale" ) BigDecimal scale) { if ( n == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "n", "cannot be null")); } if ( scale == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "scale", "cannot be null")); } // Based on Table 76: Semantics of numeric functions, the scale is in range −6111 .. 6176 if (scale.compareTo(BigDecimal.valueOf(-6111)) < 0 || scale.compareTo(BigDecimal.valueOf(6176)) > 0) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "scale", "must be in range between -6111 to 6176.")); } return FEELFnResult.ofResult( n.setScale( scale.intValue(), RoundingMode.HALF_EVEN ) ); }
@Test void invokeNull() { FunctionTestUtil.assertResultError(decimalFunction.invoke((BigDecimal) null, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(decimalFunction.invoke(BigDecimal.ONE, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(decimalFunction.invoke(null, BigDecimal.ONE), InvalidParametersEvent.class); }
@Override public synchronized NMResourceInfo getNMResourceInfo() throws YarnException { final GpuDeviceInformation gpuDeviceInformation; if (gpuDiscoverer.isAutoDiscoveryEnabled()) { //At this point the gpu plugin is already enabled checkGpuResourceHandler(); checkErrorCount(); try{ gpuDeviceInformation = gpuDiscoverer.getGpuDeviceInformation(); numOfErrorExecutionSinceLastSucceed = 0; } catch (YarnException e) { LOG.error(e.getMessage(), e); numOfErrorExecutionSinceLastSucceed++; throw e; } } else { gpuDeviceInformation = null; } GpuResourceAllocator gpuResourceAllocator = gpuResourceHandler.getGpuAllocator(); List<GpuDevice> totalGpus = gpuResourceAllocator.getAllowedGpus(); List<AssignedGpuDevice> assignedGpuDevices = gpuResourceAllocator.getAssignedGpus(); return new NMGpuResourceInfo(gpuDeviceInformation, totalGpus, assignedGpuDevices); }
@Test(expected = YarnException.class) public void testResourceHandlerNotInitialized() throws YarnException { GpuDiscoverer gpuDiscoverer = createMockDiscoverer(); GpuNodeResourceUpdateHandler gpuNodeResourceUpdateHandler = mock(GpuNodeResourceUpdateHandler.class); GpuResourcePlugin target = new GpuResourcePlugin(gpuNodeResourceUpdateHandler, gpuDiscoverer); target.getNMResourceInfo(); }
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromString(source); FEEL_1_1Lexer lexer = new FEEL_1_1Lexer( input ); CommonTokenStream tokens = new CommonTokenStream( lexer ); FEEL_1_1Parser parser = new FEEL_1_1Parser( tokens ); ParserHelper parserHelper = new ParserHelper(eventsManager); additionalFunctions.forEach(f -> parserHelper.getSymbolTable().getBuiltInScope().define(f.getSymbol())); parser.setHelper(parserHelper); parser.setErrorHandler( new FEELErrorHandler() ); parser.removeErrorListeners(); // removes the error listener that prints to the console parser.addErrorListener( new FEELParserErrorListener( eventsManager ) ); // pre-loads the parser with symbols defineVariables( inputVariableTypes, inputVariables, parser ); if (typeRegistry != null) { parserHelper.setTypeRegistry(typeRegistry); } return parser; }
@Test void parensWithLiteral() { String inputExpression = "(10.5 )"; BaseNode number = parse( inputExpression ); assertThat( number).isInstanceOf(NumberNode.class); assertThat( number.getResultType()).isEqualTo(BuiltInType.NUMBER); assertThat( number.getText()).isEqualTo("10.5"); }
public ConnectionFactory connectionFactory(ConnectionFactory connectionFactory) { // It is common to implement both interfaces if (connectionFactory instanceof XAConnectionFactory) { return (ConnectionFactory) xaConnectionFactory((XAConnectionFactory) connectionFactory); } return TracingConnectionFactory.create(connectionFactory, this); }
@Test void connectionFactory_wrapsInput() { assertThat(jmsTracing.connectionFactory(mock(ConnectionFactory.class))) .isInstanceOf(TracingConnectionFactory.class); }
public static CloseableIterable<CombinedScanTask> planTasks( CloseableIterable<FileScanTask> splitFiles, long splitSize, int lookback, long openFileCost) { validatePlanningArguments(splitSize, lookback, openFileCost); // Check the size of delete file as well to avoid unbalanced bin-packing Function<FileScanTask, Long> weightFunc = file -> Math.max( file.length() + file.deletes().stream().mapToLong(ContentFile::fileSizeInBytes).sum(), (1 + file.deletes().size()) * openFileCost); return CloseableIterable.transform( CloseableIterable.combine( new BinPacking.PackingIterable<>(splitFiles, splitSize, lookback, weightFunc, true), splitFiles), BaseCombinedScanTask::new); }
@Test public void testPlanTaskWithDeleteFiles() { List<FileScanTask> testFiles = tasksWithDataAndDeleteSizes( Arrays.asList( Pair.of(150L, new Long[] {50L, 100L}), Pair.of(50L, new Long[] {1L, 50L}), Pair.of(50L, new Long[] {100L}), Pair.of(1L, new Long[] {1L, 1L}), Pair.of(75L, new Long[] {75L}))); List<CombinedScanTask> combinedScanTasks = Lists.newArrayList( TableScanUtil.planTasks(CloseableIterable.withNoopClose(testFiles), 300L, 3, 50L)); List<CombinedScanTask> expectedCombinedTasks = Arrays.asList( new BaseCombinedScanTask(Collections.singletonList(testFiles.get(0))), new BaseCombinedScanTask(Arrays.asList(testFiles.get(1), testFiles.get(2))), new BaseCombinedScanTask(Arrays.asList(testFiles.get(3), testFiles.get(4)))); assertThat(combinedScanTasks) .as("Should plan 3 Combined tasks since there is delete files to be considered") .hasSize(3); for (int i = 0; i < expectedCombinedTasks.size(); ++i) { assertThat(combinedScanTasks.get(i).files()) .as("Scan tasks detail in combined task check failed") .isEqualTo(expectedCombinedTasks.get(i).files()); } }
@VisibleForTesting void validateNameUnique(List<MemberLevelDO> list, Long id, String name) { for (MemberLevelDO levelDO : list) { if (ObjUtil.notEqual(levelDO.getName(), name)) { continue; } if (id == null || !id.equals(levelDO.getId())) { throw exception(LEVEL_NAME_EXISTS, levelDO.getName()); } } }
@Test public void testCreateLevel_nameUnique() { // 准备参数 String name = randomString(); // mock 数据 memberlevelMapper.insert(randomLevelDO(o -> o.setName(name))); // 调用,校验异常 List<MemberLevelDO> list = memberlevelMapper.selectList(); assertServiceException(() -> levelService.validateNameUnique(list, null, name), LEVEL_NAME_EXISTS, name); }
@Override public ServerGroup servers() { return cache.get(); }
@Test public void one_down_endpoint_is_up() { NginxHealthClient service = createClient("nginx-health-output-policy-up.json"); assertTrue(service.servers().isHealthy("gateway.prod.music.vespa.us-east-2.prod")); }
public boolean isFound() { return found; }
@Test public void testCalcInstructionsRoundaboutDirectExit() { roundaboutGraph.inverse3to9(); Weighting weighting = new SpeedWeighting(mixedCarSpeedEnc); Path p = new Dijkstra(roundaboutGraph.g, weighting, TraversalMode.NODE_BASED) .calcPath(6, 8); assertTrue(p.isFound()); InstructionList wayList = InstructionsFromEdges.calcInstructions(p, p.graph, weighting, mixedEncodingManager, tr); List<String> tmpList = getTurnDescriptions(wayList); assertEquals(List.of("continue onto 3-6", "At roundabout, take exit 3 onto 5-8", "arrive at destination"), tmpList); roundaboutGraph.inverse3to9(); }
@Override public Optional<Track<T>> clean(Track<T> track) { TreeSet<Point<T>> points = new TreeSet<>(track.points()); Optional<Point<T>> firstNonNull = firstPointWithAltitude(points); if (!firstNonNull.isPresent()) { return Optional.empty(); } SortedSet<Point<T>> pointsMissingAltitude = points.headSet(firstNonNull.get()); TreeSet<Point<T>> fixedPoints = extrapolateAltitudes(pointsMissingAltitude, firstNonNull.get()); pointsMissingAltitude.clear(); points.addAll(fixedPoints); Optional<Point<T>> gapStart; Optional<Point<T>> gapEnd = firstNonNull; while (gapEnd.isPresent()) { gapStart = firstPointWithoutAltitude(points.tailSet(gapEnd.get())); if (!gapStart.isPresent()) { break; } gapEnd = firstPointWithAltitude(points.tailSet(gapStart.get())); if (!gapEnd.isPresent()) { pointsMissingAltitude = points.tailSet(gapStart.get()); fixedPoints = extrapolateAltitudes(pointsMissingAltitude, points.lower(gapStart.get())); pointsMissingAltitude.clear(); points.addAll(fixedPoints); // extrapolateAltitudes(points.tailSet(gapStart.get()), points.lower(gapStart.get())); } else { pointsMissingAltitude = points.subSet(gapStart.get(), gapEnd.get()); fixedPoints = interpolateAltitudes(pointsMissingAltitude, points.lower(gapStart.get()), gapEnd.get()); pointsMissingAltitude.clear(); points.addAll(fixedPoints); // interpolateAltitudes(points.subSet(gapStart.get(), gapEnd.get()), points.lower(gapStart.get()), gapEnd.get()); } } return Optional.of(Track.of(points)); }
@Test public void testFillingMissingAltitude() { Track<NoRawData> testTrack = trackWithSingleMissingAltitude(); Track<NoRawData> cleanedTrack = (new FillMissingAltitudes<NoRawData>()).clean(testTrack).get(); ArrayList<Point<NoRawData>> points = new ArrayList<>(cleanedTrack.points()); assertTrue( points.get(1).altitude().inFeet() == 130.0, "The middle point's altitude should be filled based on its neighbors" ); }
@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 givenValidMsgAndFetchToData_whenOnMsg_thenShouldTellSuccessAndFetchToData() 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.DATA); node.config = config; node.fetchTo = TbMsgSource.DATA; var msgMetaData = new TbMsgMetaData(); var msgData = "{\"temp\":42,\"humidity\":77}"; 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 expectedMsgData = "{\"temp\":42,\"humidity\":77,\"originatorName\":\"Test device\",\"originatorType\":\"Test device type\"}"; assertThat(actualMessageCaptor.getValue().getData()).isEqualTo(expectedMsgData); assertThat(actualMessageCaptor.getValue().getMetaData()).isEqualTo(msgMetaData); }
public static AuthorizationsCollector parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return AuthorizationsCollector.emptyImmutableCollector(); } if (!file.exists()) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); return AuthorizationsCollector.emptyImmutableCollector(); } try { Reader reader = Files.newBufferedReader(file.toPath(), UTF_8); return parse(reader); } catch (IOException fex) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); return AuthorizationsCollector.emptyImmutableCollector(); } }
@Test public void testParseValidComment() throws ParseException { Reader conf = new StringReader("#simple comment"); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); // Verify assertTrue(authorizations.isEmpty()); }
public MethodBuilder reliable(Boolean reliable) { this.reliable = reliable; return getThis(); }
@Test void reliable() { MethodBuilder builder = MethodBuilder.newBuilder(); builder.reliable(true); Assertions.assertTrue(builder.build().isReliable()); }
private void wrapCorsResponse(final HttpServletResponse response) { response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "1800"); }
@Test public void testWrapCorsResponse() { try { Method testMethod = statelessAuthFilter.getClass().getDeclaredMethod("wrapCorsResponse", HttpServletResponse.class); testMethod.setAccessible(true); testMethod.invoke(statelessAuthFilter, httpServletResponse); verify(httpServletResponse).addHeader("Access-Control-Allow-Origin", "*"); verify(httpServletResponse).addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); verify(httpServletResponse).addHeader("Access-Control-Allow-Headers", "Content-Type"); verify(httpServletResponse).addHeader("Access-Control-Max-Age", "1800"); } catch (Exception e) { throw new ShenyuException(e.getCause()); } }
@Override protected int poll() throws Exception { // must reset for each poll shutdownRunningTask = null; pendingExchanges = 0; List<software.amazon.awssdk.services.sqs.model.Message> messages = pollingTask.call(); // okay we have some response from aws so lets mark the consumer as ready forceConsumerAsReady(); Queue<Exchange> exchanges = createExchanges(messages); return processBatch(CastUtils.cast(exchanges)); }
@Test void shouldRequest18MessagesWithTwoReceiveRequestWithoutSorting() throws Exception { // given generateSequenceNumber = false; var expectedMessages = IntStream.range(0, 18).mapToObj(Integer::toString).toList(); expectedMessages.stream().map(this::message).forEach(sqsClientMock::addMessage); try (var tested = createConsumer(18)) { // when var polledMessagesCount = tested.poll(); // then assertThat(polledMessagesCount).isEqualTo(18); assertThat(receiveMessageBodies()).containsExactlyInAnyOrderElementsOf(expectedMessages); assertThat(sqsClientMock.getReceiveRequests()).containsExactlyInAnyOrder( expectedReceiveRequest(10), expectedReceiveRequest(8)); assertThat(sqsClientMock.getQueues()).isEmpty(); } }
@Override public void deleteAll() { }
@Test public void deleteAll() { mSensorsAPI.deleteAll(); }
public static <T> CloseableIterator<T> from(Iterator<T> iterator) { // early fail requireNonNull(iterator); checkArgument(!(iterator instanceof AutoCloseable), "This method does not support creating a CloseableIterator from an Iterator which is Closeable"); return new RegularIteratorWrapper<>(iterator); }
@Test(expected = IllegalArgumentException.class) public void from_iterator_throws_IAE_if_arg_is_a_CloseableIterator() { CloseableIterator.from(new SimpleCloseableIterator()); }
@Override public SQLXML getSQLXML(final int columnIndex) throws SQLException { return (SQLXML) mergeResultSet.getValue(columnIndex, SQLXML.class); }
@Test void assertGetSQLXMLWithColumnIndex() throws SQLException { SQLXML sqlxml = mock(SQLXML.class); when(mergeResultSet.getValue(1, SQLXML.class)).thenReturn(sqlxml); assertThat(shardingSphereResultSet.getSQLXML(1), is(sqlxml)); }
public DecisionTree prune(DataFrame test) { return prune(test, formula, classes); }
@Test public void testPrune() { System.out.println("USPS"); // Overfitting with very large maxNodes and small nodeSize DecisionTree model = DecisionTree.fit(USPS.formula, USPS.train, SplitRule.ENTROPY, 20, 3000, 1); System.out.println(model); double[] importance = model.importance(); for (int i = 0; i < importance.length; i++) { System.out.format("%-15s %.4f%n", model.schema().name(i), importance[i]); } int[] prediction = model.predict(USPS.test); int error = Error.of(USPS.testy, prediction); System.out.println("Error = " + error); assertEquals(897, model.size()); assertEquals(324, error); DecisionTree lean = model.prune(USPS.test); System.out.println(lean); importance = lean.importance(); for (int i = 0; i < importance.length; i++) { System.out.format("%-15s %.4f%n", lean.schema().name(i), importance[i]); } // The old model should not be modified. prediction = model.predict(USPS.test); error = Error.of(USPS.testy, prediction); System.out.println("Error of old model after pruning = " + error); assertEquals(897, model.size()); assertEquals(324, error); prediction = lean.predict(USPS.test); error = Error.of(USPS.testy, prediction); System.out.println("Error of pruned model after pruning = " + error); assertEquals(743, lean.size()); assertEquals(273, error); }
@Override public void importData(JsonReader reader) throws IOException { logger.info("Reading configuration for 1.3"); // this *HAS* to start as an object reader.beginObject(); while (reader.hasNext()) { JsonToken tok = reader.peek(); switch (tok) { case NAME: String name = reader.nextName(); // find out which member it is if (name.equals(CLIENTS)) { readClients(reader); } else if (name.equals(GRANTS)) { readGrants(reader); } else if (name.equals(WHITELISTEDSITES)) { readWhitelistedSites(reader); } else if (name.equals(BLACKLISTEDSITES)) { readBlacklistedSites(reader); } else if (name.equals(AUTHENTICATIONHOLDERS)) { readAuthenticationHolders(reader); } else if (name.equals(ACCESSTOKENS)) { readAccessTokens(reader); } else if (name.equals(REFRESHTOKENS)) { readRefreshTokens(reader); } else if (name.equals(SYSTEMSCOPES)) { readSystemScopes(reader); } else { boolean processed = false; for (MITREidDataServiceExtension extension : extensions) { if (extension.supportsVersion(THIS_VERSION)) { processed = extension.importExtensionData(name, reader); if (processed) { // if the extension processed data, break out of this inner loop // (only the first extension to claim an extension point gets it) break; } } } if (!processed) { // unknown token, skip it reader.skipValue(); } } break; case END_OBJECT: // the object ended, we're done here reader.endObject(); continue; default: logger.debug("Found unexpected entry"); reader.skipValue(); continue; } } fixObjectReferences(); for (MITREidDataServiceExtension extension : extensions) { if (extension.supportsVersion(THIS_VERSION)) { extension.fixExtensionObjectReferences(maps); break; } } maps.clearAll(); }
@Test public void testImportAuthenticationHolders() throws IOException { OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1", new ArrayList<GrantedAuthority>(), true, new HashSet<String>(), new HashSet<String>(), "http://foo.com", new HashSet<String>(), null); Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); holder1.setId(1L); holder1.setAuthentication(auth1); OAuth2Request req2 = new OAuth2Request(new HashMap<String, String>(), "client2", new ArrayList<GrantedAuthority>(), true, new HashSet<String>(), new HashSet<String>(), "http://bar.com", new HashSet<String>(), null); Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); holder2.setId(2L); holder2.setAuthentication(auth2); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" + "{\"id\":1,\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"," + "\"savedUserAuthentication\":null}," + "{\"id\":2,\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"," + "\"savedUserAuthentication\":null}" + " ]" + "}"; logger.debug(configJson); JsonReader reader = new JsonReader(new StringReader(configJson)); final Map<Long, AuthenticationHolderEntity> fakeDb = new HashMap<>(); when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() { Long id = 243L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _site = (AuthenticationHolderEntity) invocation.getArguments()[0]; if(_site.getId() == null) { _site.setId(id++); } fakeDb.put(_site.getId(), _site); return _site; } }); dataService.importData(reader); verify(authHolderRepository, times(2)).save(capturedAuthHolders.capture()); List<AuthenticationHolderEntity> savedAuthHolders = capturedAuthHolders.getAllValues(); assertThat(savedAuthHolders.size(), is(2)); assertThat(savedAuthHolders.get(0).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder1.getAuthentication().getOAuth2Request().getClientId())); assertThat(savedAuthHolders.get(1).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder2.getAuthentication().getOAuth2Request().getClientId())); }
@Override public long count() { return coll.count(); }
@Test @MongoDBFixtures("OutputServiceImplTest.json") public void countReturnsNumberOfOutputs() { assertThat(outputService.count()).isEqualTo(2L); }
@Override public int getRowCount() { return _rowsArray.size(); }
@Test public void testGetRowCount() { // Run the test final int result = _resultTableResultSetUnderTest.getRowCount(); // Verify the results assertEquals(2, result); }
public boolean isInstalled() { return mTrigger != null; }
@Test public void testImeInstalledWhenMixedVoice() { addInputMethodInfo(List.of("keyboard", "keyboard", "handwriting")); addInputMethodInfo(List.of("handwriting")); addInputMethodInfo(List.of("handwriting", "keyboard", "voice", "keyboard", "keyboard")); Assert.assertTrue(ImeTrigger.isInstalled(mMockInputMethodService)); }
@Override public boolean supportsTableCorrelationNames() { return false; }
@Test void assertSupportsTableCorrelationNames() { assertFalse(metaData.supportsTableCorrelationNames()); }
public void setConstructor(boolean constructor) { this.constructor = constructor; }
@Test void testSetConstructor() { Method method = new Method("Bar"); assertFalse(method.isConstructor()); method.setConstructor(true); assertTrue(method.isConstructor()); }
public void checkExecutePrerequisites(final ExecutionContext executionContext) { ShardingSpherePreconditions.checkState(isValidExecutePrerequisites(executionContext), () -> new TableModifyInTransactionException(getTableName(executionContext))); }
@Test void assertCheckExecutePrerequisitesWhenExecuteDDLInBaseTransaction() { when(transactionRule.getDefaultType()).thenReturn(TransactionType.BASE); ExecutionContext executionContext = new ExecutionContext( new QueryContext(createMySQLCreateTableStatementContext(), "", Collections.emptyList(), new HintValueContext(), mockConnectionContext(), mock(ShardingSphereMetaData.class)), Collections.emptyList(), mock(RouteContext.class)); new ProxySQLExecutor(JDBCDriverType.STATEMENT, databaseConnectionManager, mock(DatabaseConnector.class), mockQueryContext()).checkExecutePrerequisites(executionContext); }
@SuppressWarnings({"unchecked", "rawtypes"}) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format( "CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } if (type == BigInteger.class) { return new BigInteger(string); } if (type == BigDecimal.class) { return new BigDecimal(string); } if (type == Short.class || type == short.class) { return new Short(string); } if (type == Integer.class || type == int.class) { return new Integer(string); } if (type == Long.class || type == long.class) { return new Long(string); } if (type == Double.class || type == double.class) { return new Double(string); } if (type == Float.class || type == float.class) { return new Float(string); } if (type == Byte.class || type == byte.class) { return new Byte(string); } if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } if (type == Date.class || type == java.sql.Date.class || type == java.sql.Timestamp.class || type == java.sql.Time.class) { try { Date date = new SimpleDateFormat(DATE_FORMAT).parse(string); if (type == java.sql.Date.class) { return new java.sql.Date(date.getTime()); } if (type == java.sql.Timestamp.class) { return new java.sql.Timestamp(date.getTime()); } if (type == java.sql.Time.class) { return new java.sql.Time(date.getTime()); } return date; } catch (ParseException e) { throw new IllegalStateException( "Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } if (type == java.time.LocalDateTime.class) { if (StringUtils.isEmpty(string)) { return null; } return LocalDateTime.parse(string); } if (type == java.time.LocalDate.class) { if (StringUtils.isEmpty(string)) { return null; } return LocalDate.parse(string); } if (type == java.time.LocalTime.class) { if (StringUtils.isEmpty(string)) { return null; } if (string.length() >= ISO_LOCAL_DATE_TIME_MIN_LEN) { return LocalDateTime.parse(string).toLocalTime(); } else { return LocalTime.parse(string); } } if (type == Class.class) { try { return ReflectUtils.name2class(string); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } if (char[].class.equals(type)) { // Process string to char array for generic invoke // See // - https://github.com/apache/dubbo/issues/2003 int len = string.length(); char[] chars = new char[len]; string.getChars(0, len, chars, 0); return chars; } } if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } if (type == short.class || type == Short.class) { return number.shortValue(); } if (type == int.class || type == Integer.class) { return number.intValue(); } if (type == long.class || type == Long.class) { return number.longValue(); } if (type == float.class || type == Float.class) { return number.floatValue(); } if (type == double.class || type == Double.class) { return number.doubleValue(); } if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } if (type == BigDecimal.class) { return new BigDecimal(number.toString()); } if (type == Date.class) { return new Date(number.longValue()); } if (type == boolean.class || type == Boolean.class) { return 0 != number.intValue(); } } if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } if (!type.isInterface()) { try { Collection result = (Collection) type.getDeclaredConstructor().newInstance(); result.addAll(collection); return result; } catch (Throwable ignored) { } } if (type == List.class) { return new ArrayList<Object>(collection); } if (type == Set.class) { return new HashSet<Object>(collection); } } if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { int length = Array.getLength(value); Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.getDeclaredConstructor().newInstance(); } catch (Exception e) { collection = new ArrayList<Object>(length); } } else if (type == Set.class) { collection = new HashSet<Object>(Math.max((int) (length / .75f) + 1, 16)); } else { collection = new ArrayList<Object>(length); } for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; }
@SuppressWarnings("unchecked") @Test void testCompatibleTypeConvert() throws Exception { Object result; { Object input = new Object(); result = CompatibleTypeUtils.compatibleTypeConvert(input, Date.class); assertSame(input, result); result = CompatibleTypeUtils.compatibleTypeConvert(input, null); assertSame(input, result); result = CompatibleTypeUtils.compatibleTypeConvert(null, Date.class); assertNull(result); } { result = CompatibleTypeUtils.compatibleTypeConvert("a", char.class); assertEquals(Character.valueOf('a'), (Character) result); result = CompatibleTypeUtils.compatibleTypeConvert("A", MyEnum.class); assertEquals(MyEnum.A, (MyEnum) result); result = CompatibleTypeUtils.compatibleTypeConvert("3", BigInteger.class); assertEquals(new BigInteger("3"), (BigInteger) result); result = CompatibleTypeUtils.compatibleTypeConvert("3", BigDecimal.class); assertEquals(new BigDecimal("3"), (BigDecimal) result); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", Date.class); assertEquals(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2011-12-11 12:24:12"), (Date) result); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Date.class); assertEquals(new SimpleDateFormat("yyyy-MM-dd").format((java.sql.Date) result), "2011-12-11"); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Time.class); assertEquals(new SimpleDateFormat("HH:mm:ss").format((java.sql.Time) result), "12:24:12"); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Timestamp.class); assertEquals( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((java.sql.Timestamp) result), "2011-12-11 12:24:12"); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11T12:24:12.047", java.time.LocalDateTime.class); assertEquals( DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format((java.time.LocalDateTime) result), "2011-12-11 12:24:12"); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11T12:24:12.047", java.time.LocalTime.class); assertEquals(DateTimeFormatter.ofPattern("HH:mm:ss").format((java.time.LocalTime) result), "12:24:12"); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11", java.time.LocalDate.class); assertEquals(DateTimeFormatter.ofPattern("yyyy-MM-dd").format((java.time.LocalDate) result), "2011-12-11"); result = CompatibleTypeUtils.compatibleTypeConvert("ab", char[].class); assertEquals(2, ((char[]) result).length); assertEquals('a', ((char[]) result)[0]); assertEquals('b', ((char[]) result)[1]); result = CompatibleTypeUtils.compatibleTypeConvert("", char[].class); assertEquals(0, ((char[]) result).length); result = CompatibleTypeUtils.compatibleTypeConvert(null, char[].class); assertNull(result); } { result = CompatibleTypeUtils.compatibleTypeConvert(3, byte.class); assertEquals(Byte.valueOf((byte) 3), (Byte) result); result = CompatibleTypeUtils.compatibleTypeConvert((byte) 3, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3, short.class); assertEquals(Short.valueOf((short) 3), (Short) result); result = CompatibleTypeUtils.compatibleTypeConvert((short) 3, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3, long.class); assertEquals(Long.valueOf(3), (Long) result); result = CompatibleTypeUtils.compatibleTypeConvert(3L, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3L, BigInteger.class); assertEquals(BigInteger.valueOf(3L), (BigInteger) result); result = CompatibleTypeUtils.compatibleTypeConvert(BigInteger.valueOf(3L), int.class); assertEquals(Integer.valueOf(3), (Integer) result); } { result = CompatibleTypeUtils.compatibleTypeConvert(3D, float.class); assertEquals(Float.valueOf(3), (Float) result); result = CompatibleTypeUtils.compatibleTypeConvert(3F, double.class); assertEquals(Double.valueOf(3), (Double) result); result = CompatibleTypeUtils.compatibleTypeConvert(3D, double.class); assertEquals(Double.valueOf(3), (Double) result); result = CompatibleTypeUtils.compatibleTypeConvert(3D, BigDecimal.class); assertEquals(BigDecimal.valueOf(3D), (BigDecimal) result); result = CompatibleTypeUtils.compatibleTypeConvert(BigDecimal.valueOf(3D), double.class); assertEquals(Double.valueOf(3), (Double) result); } { List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); Set<String> set = new HashSet<String>(); set.add("a"); set.add("b"); String[] array = new String[] {"a", "b"}; result = CompatibleTypeUtils.compatibleTypeConvert(array, List.class); assertEquals(ArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(set, List.class); assertEquals(ArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(array, CopyOnWriteArrayList.class); assertEquals(CopyOnWriteArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(set, CopyOnWriteArrayList.class); assertEquals(CopyOnWriteArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(set, String[].class); assertEquals(String[].class, result.getClass()); assertEquals(2, ((String[]) result).length); assertTrue(((String[]) result)[0].equals("a") || ((String[]) result)[0].equals("b")); assertTrue(((String[]) result)[1].equals("a") || ((String[]) result)[1].equals("b")); result = CompatibleTypeUtils.compatibleTypeConvert(array, Set.class); assertEquals(HashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(list, Set.class); assertEquals(HashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(array, ConcurrentHashSet.class); assertEquals(ConcurrentHashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(list, ConcurrentHashSet.class); assertEquals(ConcurrentHashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(list, String[].class); assertEquals(String[].class, result.getClass()); assertEquals(2, ((String[]) result).length); assertTrue(((String[]) result)[0].equals("a")); assertTrue(((String[]) result)[1].equals("b")); } }
public static List<GsonEmail> parse(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<GsonEmail>>() { }); }
@Test public void parse() { List<GsonEmail> underTest = GsonEmail.parse( "[\n" + " {\n" + " \"email\": \"octocat@github.com\",\n" + " \"verified\": true,\n" + " \"primary\": true\n" + " },\n" + " {\n" + " \"email\": \"support@github.com\",\n" + " \"verified\": false,\n" + " \"primary\": false\n" + " }\n" + "]"); assertThat(underTest).hasSize(2); assertThat(underTest.get(0).getEmail()).isEqualTo("octocat@github.com"); assertThat(underTest.get(0).isVerified()).isTrue(); assertThat(underTest.get(0).isPrimary()).isTrue(); assertThat(underTest.get(1).getEmail()).isEqualTo("support@github.com"); assertThat(underTest.get(1).isVerified()).isFalse(); assertThat(underTest.get(1).isPrimary()).isFalse(); }
public static Node build(final List<JoinInfo> joins) { Node root = null; for (final JoinInfo join : joins) { if (root == null) { root = new Leaf(join.getLeftSource()); } if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) { throw new KsqlException("Cannot perform circular join - both " + join.getRightSource() + " and " + join.getLeftJoinExpression() + " are already included in the current join tree: " + root.debugString(0)); } else if (root.containsSource(join.getLeftSource())) { root = new Join(root, new Leaf(join.getRightSource()), join); } else if (root.containsSource(join.getRightSource())) { root = new Join(root, new Leaf(join.getLeftSource()), join.flip()); } else { throw new KsqlException( "Cannot build JOIN tree; neither source in the join is the FROM source or included " + "in a previous JOIN: " + join + ". The current join tree is " + root.debugString(0) ); } } return root; }
@Test public void shouldThrowOnMissingSource() { // Given: when(j1.getLeftSource()).thenReturn(a); when(j1.getRightSource()).thenReturn(b); when(j2.getLeftSource()).thenReturn(c); when(j2.getRightSource()).thenReturn(d); final List<JoinInfo> joins = ImmutableList.of(j1, j2); // When: final KsqlException e = assertThrows(KsqlException.class, () -> JoinTree.build(joins)); // Then: assertThat(e.getMessage(), containsString("neither source in the join is the FROM source")); }
public static String getKeyTenant(String dataId, String group, String tenant) { return doGetKey(dataId, group, tenant); }
@Test void testGetKeyTenantByPlusThreeParams() { // Act final String actual = GroupKey.getKeyTenant("3", "1", ","); // Assert result assertEquals("3+1+,", actual); }
@Override public String decryptAES(String content) { return AESSecretManager.getInstance().decryptAES(content); }
@Test public void decryptAES() { SAHelper.initSensors(mApplication); SAEncryptAPIImpl encryptAPIImpl = new SAEncryptAPIImpl(SensorsDataAPI.sharedInstance(mApplication).getSAContextManager()); final String Identity = "Identity"; String encrypt = encryptAPIImpl.encryptAES(Identity); Assert.assertEquals(encryptAPIImpl.decryptAES(encrypt), Identity); }
@Override public JobStatus getState() { return jobStatus; }
@Test void getState() { final JobStatusStore store = new JobStatusStore(0L); store.jobStatusChanges(new JobID(), JobStatus.RUNNING, 1L); assertThat(store.getState(), is(JobStatus.RUNNING)); }
public static byte[] copyOf(byte[] src, int length) { byte[] dest = new byte[length]; System.arraycopy(src, 0, dest, 0, Math.min(src.length, length)); return dest; }
@Test public void copyOf() { byte[] bs = new byte[] { 1, 2, 3, 5 }; byte[] cp = CodecUtils.copyOf(bs, 3); Assert.assertArrayEquals(cp, new byte[] { 1, 2, 3 }); cp = CodecUtils.copyOf(bs, 5); Assert.assertArrayEquals(cp, new byte[] { 1, 2, 3, 5, 0 }); }
@Override public Void execute(Context context) { KieSession ksession = ((RegistryContext) context).lookup(KieSession.class); Collection<?> objects = ksession.getObjects(new ConditionFilter(factToCheck)); if (!objects.isEmpty()) { factToCheck.forEach(fact -> fact.getScenarioResult().setResult(true)); } else { factToCheck.forEach(fact -> fact.getScenarioResult().getFactMappingValue().setExceptionMessage("There is no instance which satisfies the expected conditions")); } return null; }
@Test public void execute_setResultIsCalled() { when(kieSession.getObjects(any(ObjectFilter.class))).thenReturn(Collections.singleton(null)); validateFactCommand.execute(registryContext); verify(scenarioResult, times(1)).setResult(anyBoolean()); }
@Override public String getName() { return name; }
@Test public void testEqualsAndHashCode() { assumeDifferentHashCodes(); EqualsVerifier.forClass(ReplicatedMapConfig.class) .suppress(Warning.NONFINAL_FIELDS) .withPrefabValues(MergePolicyConfig.class, new MergePolicyConfig(PutIfAbsentMergePolicy.class.getName(), 100), new MergePolicyConfig(DiscardMergePolicy.class.getName(), 200)) .withPrefabValues(ReplicatedMapConfigReadOnly.class, new ReplicatedMapConfigReadOnly(new ReplicatedMapConfig("red")), new ReplicatedMapConfigReadOnly(new ReplicatedMapConfig("black"))) .verify(); }
private static int getNumSlots(final Configuration config) { return config.get(TaskManagerOptions.NUM_TASK_SLOTS); }
@Test void testConfigNumSlots() { final int numSlots = 5; Configuration conf = new Configuration(); conf.set(TaskManagerOptions.NUM_TASK_SLOTS, numSlots); validateInAllConfigurations( conf, taskExecutorProcessSpec -> assertThat(taskExecutorProcessSpec.getNumSlots()).isEqualTo(numSlots)); }
@Override public void init(Properties config) throws ServletException { acceptAnonymous = Boolean.parseBoolean(config.getProperty(ANONYMOUS_ALLOWED, "false")); }
@Test public void testInit() throws Exception { PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler(); try { Properties props = new Properties(); props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "false"); handler.init(props); Assert.assertEquals(false, handler.getAcceptAnonymous()); } finally { handler.destroy(); } }
@Override @CacheEvict(cacheNames = RedisKeyConstants.MAIL_TEMPLATE, allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理 public void deleteMailTemplate(Long id) { // 校验是否存在 validateMailTemplateExists(id); // 删除 mailTemplateMapper.deleteById(id); }
@Test public void testDeleteMailTemplate_success() { // mock 数据 MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class); mailTemplateMapper.insert(dbMailTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbMailTemplate.getId(); // 调用 mailTemplateService.deleteMailTemplate(id); // 校验数据不存在了 assertNull(mailTemplateMapper.selectById(id)); }
public List<String> scanPlugins(ClassLoader classLoader, String path) throws IOException { final List<String> files = new LinkedList<>(); scanner.scan(classLoader, path, new ScannerVisitor() { @Override public void visit(InputStream file) throws IOException { ClassFile cf; try { DataInputStream dstream = new DataInputStream(file); cf = new ClassFile(dstream); } catch (IOException e) { throw new IOException("Stream not a valid classFile", e); } if (hasAnnotation(cf)) files.add(cf.getName()); } }); return files; }
@Test public void testScanPlugins() throws Exception { ClassPathAnnotationScanner scanner = new ClassPathAnnotationScanner(Plugin.class.getName(), new ClassPathScanner()); assertArrayEquals("Plugin discovered", new String[]{SimplePlugin.class.getName()}, scanner.scanPlugins(getClass().getClassLoader(), "org/hotswap/agent/testData").toArray()); }
private void initializePartition(Set<TrackerClient> trackerClients, int partitionId, long clusterGenerationId) { if (!_partitionLoadBalancerStateMap.containsKey(partitionId)) { PartitionState partitionState = new PartitionState(partitionId, new DelegatingRingFactory<>(_relativeStrategyProperties.getRingProperties()), _relativeStrategyProperties.getRingProperties().getPointsPerWeight(), _listenerFactories.stream().map(factory -> factory.create(partitionId)).collect(Collectors.toList())); updateStateForPartition(trackerClients, partitionId, partitionState, clusterGenerationId, false); if (_firstPartitionId < 0) { _firstPartitionId = partitionId; } } }
@Test(dataProvider = "partitionId") public void testInitializePartition(int partitionId) { setup(new D2RelativeStrategyProperties(), new ConcurrentHashMap<>()); List<TrackerClient> trackerClients = TrackerClientMockHelper.mockTrackerClients(2, Arrays.asList(20, 20), Arrays.asList(10, 10), Arrays.asList(200L, 500L), Arrays.asList(100L, 200L), Arrays.asList(0, 0)); assertTrue(_stateUpdater.getPointsMap(partitionId).isEmpty(), "There should be no state before initialization"); _stateUpdater.updateState(new HashSet<>(trackerClients), partitionId, DEFAULT_CLUSTER_GENERATION_ID, false); assertEquals(_stateUpdater.getPointsMap(partitionId).get(trackerClients.get(0).getUri()).intValue(), HEALTHY_POINTS); assertEquals(_stateUpdater.getPointsMap(partitionId).get(trackerClients.get(1).getUri()).intValue(), HEALTHY_POINTS); assertEquals(_stateUpdater.getFirstValidPartitionId(), partitionId); }
@Override public void validatePostList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return; } // 获得岗位信息 List<PostDO> posts = postMapper.selectBatchIds(ids); Map<Long, PostDO> postMap = convertMap(posts, PostDO::getId); // 校验 ids.forEach(id -> { PostDO post = postMap.get(id); if (post == null) { throw exception(POST_NOT_FOUND); } if (!CommonStatusEnum.ENABLE.getStatus().equals(post.getStatus())) { throw exception(POST_NOT_ENABLE, post.getName()); } }); }
@Test public void testValidatePostList_notFound() { // 准备参数 List<Long> ids = singletonList(randomLongId()); // 调用, 并断言异常 assertServiceException(() -> postService.validatePostList(ids), POST_NOT_FOUND); }
@Override public <T> List<T> getExtensions(Class<T> type) { return getExtensions(type, currentPluginId); }
@Test public void getExtensions() { pluginManager.loadPlugins(); pluginManager.startPlugins(); assertEquals(1, wrappedPluginManager.getExtensions(TestExtensionPoint.class).size()); assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.getExtensions(TestExtensionPoint.class, OTHER_PLUGIN_ID)); assertEquals(1, wrappedPluginManager.getExtensions(TestExtensionPoint.class, THIS_PLUGIN_ID).size()); assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.getExtensions(OTHER_PLUGIN_ID)); assertEquals(1, wrappedPluginManager.getExtensions(THIS_PLUGIN_ID).size()); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final ThreadPool pool = ThreadPoolFactory.get("list", concurrency); try { final String prefix = this.createPrefix(directory); if(log.isDebugEnabled()) { log.debug(String.format("List with prefix %s", prefix)); } final Path bucket = containerService.getContainer(directory); final AttributedList<Path> objects = new AttributedList<>(); String priorLastKey = null; String priorLastVersionId = null; long revision = 0L; String lastKey = null; boolean hasDirectoryPlaceholder = bucket.isRoot() || containerService.isContainer(directory); do { final VersionOrDeleteMarkersChunk chunk = session.getClient().listVersionedObjectsChunked( bucket.isRoot() ? StringUtils.EMPTY : bucket.getName(), prefix, String.valueOf(Path.DELIMITER), new HostPreferences(session.getHost()).getInteger("s3.listing.chunksize"), priorLastKey, priorLastVersionId, false); // Amazon S3 returns object versions in the order in which they were stored, with the most recently stored returned first. for(BaseVersionOrDeleteMarker marker : chunk.getItems()) { final String key = URIEncoder.decode(marker.getKey()); if(new SimplePathPredicate(PathNormalizer.compose(bucket, key)).test(directory)) { if(log.isDebugEnabled()) { log.debug(String.format("Skip placeholder key %s", key)); } hasDirectoryPlaceholder = true; continue; } final PathAttributes attr = new PathAttributes(); attr.setVersionId(marker.getVersionId()); if(!StringUtils.equals(lastKey, key)) { // Reset revision for next file revision = 0L; } attr.setRevision(++revision); attr.setDuplicate(marker.isDeleteMarker() && marker.isLatest() || !marker.isLatest()); if(marker.isDeleteMarker()) { attr.setCustom(Collections.singletonMap(KEY_DELETE_MARKER, String.valueOf(true))); } attr.setModificationDate(marker.getLastModified().getTime()); attr.setRegion(bucket.attributes().getRegion()); if(marker instanceof S3Version) { final S3Version object = (S3Version) marker; attr.setSize(object.getSize()); if(StringUtils.isNotBlank(object.getEtag())) { attr.setETag(StringUtils.remove(object.getEtag(), "\"")); // The ETag will only be the MD5 of the object data when the object is stored as plaintext or encrypted // using SSE-S3. If the object is encrypted using another method (such as SSE-C or SSE-KMS) the ETag is // not the MD5 of the object data. attr.setChecksum(Checksum.parse(StringUtils.remove(object.getEtag(), "\""))); } if(StringUtils.isNotBlank(object.getStorageClass())) { attr.setStorageClass(object.getStorageClass()); } } final Path f = new Path(directory.isDirectory() ? directory : directory.getParent(), PathNormalizer.name(key), EnumSet.of(Path.Type.file), attr); if(metadata) { f.withAttributes(attributes.find(f)); } objects.add(f); lastKey = key; } final String[] prefixes = chunk.getCommonPrefixes(); final List<Future<Path>> folders = new ArrayList<>(); for(String common : prefixes) { if(new SimplePathPredicate(PathNormalizer.compose(bucket, URIEncoder.decode(common))).test(directory)) { continue; } folders.add(this.submit(pool, bucket, directory, URIEncoder.decode(common))); } for(Future<Path> f : folders) { try { objects.add(Uninterruptibles.getUninterruptibly(f)); } catch(ExecutionException e) { log.warn(String.format("Listing versioned objects failed with execution failure %s", e.getMessage())); for(Throwable cause : ExceptionUtils.getThrowableList(e)) { Throwables.throwIfInstanceOf(cause, BackgroundException.class); } throw new DefaultExceptionMappingService().map(Throwables.getRootCause(e)); } } priorLastKey = null != chunk.getNextKeyMarker() ? URIEncoder.decode(chunk.getNextKeyMarker()) : null; priorLastVersionId = chunk.getNextVersionIdMarker(); listener.chunk(directory, objects); } while(priorLastKey != null); if(!hasDirectoryPlaceholder && objects.isEmpty()) { // Only for AWS if(S3Session.isAwsHostname(session.getHost().getHostname())) { if(StringUtils.isEmpty(RequestEntityRestStorageService.findBucketInHostname(session.getHost()))) { if(log.isWarnEnabled()) { log.warn(String.format("No placeholder found for directory %s", directory)); } throw new NotfoundException(directory.getAbsolute()); } } else { // Handle missing prefix for directory placeholders in Minio final VersionOrDeleteMarkersChunk chunk = session.getClient().listVersionedObjectsChunked( bucket.isRoot() ? StringUtils.EMPTY : bucket.getName(), String.format("%s%s", this.createPrefix(directory.getParent()), directory.getName()), String.valueOf(Path.DELIMITER), 1, null, null, false); if(Arrays.stream(chunk.getCommonPrefixes()).map(URIEncoder::decode).noneMatch(common -> common.equals(prefix))) { throw new NotfoundException(directory.getAbsolute()); } } } return objects; } catch(ServiceException e) { throw new S3ExceptionMappingService().map("Listing directory {0} failed", e, directory); } finally { // Cancel future tasks pool.shutdown(false); } }
@Test public void testList() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new S3TouchFeature(session, new S3AccessControlListFeature(session)).touch(new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); file.attributes().withVersionId("null"); final AttributedList<Path> list = new S3VersionedObjectListService(session, new S3AccessControlListFeature(session)).list(container, new DisabledListProgressListener()); final Path lookup = list.find(new DefaultPathPredicate(file)); assertNotNull(lookup); assertEquals(file, lookup); assertSame(container, lookup.getParent()); assertEquals("d41d8cd98f00b204e9800998ecf8427e", lookup.attributes().getChecksum().hash); assertEquals("d41d8cd98f00b204e9800998ecf8427e", Checksum.parse(lookup.attributes().getETag()).hash); }
int sendBackups0(BackupAwareOperation backupAwareOp) { int requestedSyncBackups = requestedSyncBackups(backupAwareOp); int requestedAsyncBackups = requestedAsyncBackups(backupAwareOp); int requestedTotalBackups = requestedTotalBackups(backupAwareOp); if (requestedTotalBackups == 0) { return 0; } Operation op = (Operation) backupAwareOp; PartitionReplicaVersionManager versionManager = node.getPartitionService().getPartitionReplicaVersionManager(); ServiceNamespace namespace = versionManager.getServiceNamespace(op); long[] replicaVersions = versionManager.incrementPartitionReplicaVersions(op.getPartitionId(), namespace, requestedTotalBackups); boolean syncForced = backpressureRegulator.isSyncForced(backupAwareOp); int syncBackups = syncBackups(requestedSyncBackups, requestedAsyncBackups, syncForced); int asyncBackups = asyncBackups(requestedSyncBackups, requestedAsyncBackups, syncForced); // TODO: This could cause a problem with back pressure if (!op.returnsResponse()) { asyncBackups += syncBackups; syncBackups = 0; } if (syncBackups + asyncBackups == 0) { return 0; } return makeBackups(backupAwareOp, op.getPartitionId(), replicaVersions, syncBackups, asyncBackups); }
@Test(expected = IllegalArgumentException.class) public void backup_whenNegativeAsyncBackupCount() { setup(BACKPRESSURE_ENABLED); BackupAwareOperation op = makeOperation(0, -1); backupHandler.sendBackups0(op); }
public ExecutionStateTracker create() { return new ExecutionStateTracker(); }
@Test public void testTrackerReuse() throws Exception { MillisProvider clock = mock(MillisProvider.class); ExecutionStateSampler sampler = new ExecutionStateSampler( PipelineOptionsFactory.fromArgs("--experiments=state_sampling_period_millis=10") .create(), clock); ExecutionStateTracker tracker = sampler.create(); MetricsEnvironment.setCurrentContainer(tracker.getMetricsContainer()); ExecutionState state = tracker.create("shortId", "ptransformId", "ptransformIdName", "process"); CountDownLatch waitTillActive = new CountDownLatch(1); CountDownLatch waitTillSecondStateActive = new CountDownLatch(1); CountDownLatch waitForSamples = new CountDownLatch(1); CountDownLatch waitForMoreSamples = new CountDownLatch(1); Thread testThread = Thread.currentThread(); Mockito.when(clock.getMillis()) .thenAnswer( new Answer<Long>() { private long currentTime; @Override public Long answer(InvocationOnMock invocation) throws Throwable { if (Thread.currentThread().equals(testThread)) { return 0L; } else { // Block the state sampling thread till the state is active // and unblock the state transition once a certain number of samples // have been taken. if (currentTime < 1000L) { waitTillActive.await(); currentTime += 100L; } else if (currentTime < 1500L) { waitForSamples.countDown(); waitTillSecondStateActive.await(); currentTime += 100L; } else { waitForMoreSamples.countDown(); } return currentTime; } } }); { tracker.start("bundleId1"); state.activate(); waitTillActive.countDown(); waitForSamples.await(); TEST_USER_COUNTER.inc(); state.deactivate(); Map<String, ByteString> finalResults = new HashMap<>(); tracker.updateFinalMonitoringData(finalResults); assertThat( MonitoringInfoEncodings.decodeInt64Counter(finalResults.get("shortId")), // Because we are using lazySet, we aren't guaranteed to see the latest value. // The CountDownLatch ensures that we will see either the prior value or // the latest value. anyOf(equalTo(900L), equalTo(1000L))); assertEquals( 1L, (long) tracker .getMetricsContainerRegistry() .getContainer("ptransformId") .getCounter(TEST_USER_COUNTER.getName()) .getCumulative()); tracker.reset(); } { tracker.start("bundleId2"); state.activate(); waitTillSecondStateActive.countDown(); waitForMoreSamples.await(); TEST_USER_COUNTER.inc(); state.deactivate(); Map<String, ByteString> finalResults = new HashMap<>(); tracker.updateFinalMonitoringData(finalResults); assertThat( MonitoringInfoEncodings.decodeInt64Counter(finalResults.get("shortId")), // Because we are using lazySet, we aren't guaranteed to see the latest value. // The CountDownLatch ensures that we will see either the prior value or // the latest value. anyOf(equalTo(400L), equalTo(500L))); assertEquals( 1L, (long) tracker .getMetricsContainerRegistry() .getContainer("ptransformId") .getCounter(TEST_USER_COUNTER.getName()) .getCumulative()); tracker.reset(); } expectedLogs.verifyNotLogged("Operation ongoing"); }
public static Optional<URLArgumentLine> parse(final String line) { Matcher matcher = PLACEHOLDER_PATTERN.matcher(line); if (!matcher.find()) { return Optional.empty(); } String[] parsedArg = matcher.group(1).split(KV_SEPARATOR, 2); return Optional.of(new URLArgumentLine(parsedArg[0], parsedArg[1], matcher)); }
@Test void assertParseWithInvalidPattern() { assertFalse(URLArgumentLine.parse("invalid").isPresent()); }
public static String byte2FitMemoryString(final long byteNum) { if (byteNum < 0) { return "shouldn't be less than zero!"; } else if (byteNum < MemoryConst.KB) { return String.format("%d B", byteNum); } else if (byteNum < MemoryConst.MB) { return String.format("%d KB", byteNum / MemoryConst.KB); } else if (byteNum < MemoryConst.GB) { return String.format("%d MB", byteNum / MemoryConst.MB); } else { return String.format("%d GB", byteNum / MemoryConst.GB); } }
@Test public void byte2FitMemoryStringKB() { Assert.assertEquals( "1 KB", ConvertKit.byte2FitMemoryString(1024) ); }
@Override public String getAnonymousId() { return null; }
@Test public void getAnonymousId() { Assert.assertNull(mSensorsAPI.getAnonymousId()); }
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStart, final Range<Instant> windowEnd, final Optional<Position> position ) { try { final WindowRangeQuery<GenericKey, GenericRow> query = WindowRangeQuery.withKey(key); StateQueryRequest<KeyValueIterator<Windowed<GenericKey>, GenericRow>> request = inStore(stateStore.getStateStoreName()).withQuery(query); if (position.isPresent()) { request = request.withPositionBound(PositionBound.at(position.get())); } final StateQueryResult<KeyValueIterator<Windowed<GenericKey>, GenericRow>> result = stateStore.getKafkaStreams().query(request); final QueryResult<KeyValueIterator<Windowed<GenericKey>, GenericRow>> queryResult = result.getPartitionResults().get(partition); if (queryResult.isFailure()) { throw failedQueryException(queryResult); } try (KeyValueIterator<Windowed<GenericKey>, GenericRow> it = queryResult.getResult()) { final Builder<WindowedRow> builder = ImmutableList.builder(); while (it.hasNext()) { final KeyValue<Windowed<GenericKey>, GenericRow> next = it.next(); final Window wnd = next.key.window(); if (!windowStart.contains(wnd.startTime())) { continue; } if (!windowEnd.contains(wnd.endTime())) { continue; } final long rowTime = wnd.end(); final WindowedRow row = WindowedRow.of( stateStore.schema(), next.key, next.value, rowTime ); builder.add(row); } return KsMaterializedQueryResult.rowIteratorWithPosition( builder.build().iterator(), queryResult.getPosition()); } } catch (final NotUpToBoundException | MaterializationException e) { throw e; } catch (final Exception e) { throw new MaterializationException("Failed to get value from materialized table", e); } }
@Test public void shouldIgnoreSessionsThatStartAtUpperBoundIfUpperBoundOpen() { // Given: final Range<Instant> startBounds = Range.closedOpen( LOWER_INSTANT, UPPER_INSTANT ); givenSingleSession(UPPER_INSTANT, UPPER_INSTANT.plusMillis(1)); // When: final Iterator<WindowedRow> rowIterator = table.get(A_KEY, PARTITION, startBounds, Range.all()).rowIterator; // Then: assertThat(rowIterator.hasNext(), is(false)); }
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { if (tradingRecord != null && !tradingRecord.isClosed()) { Num entryPrice = tradingRecord.getCurrentPosition().getEntry().getNetPrice(); Num currentPrice = this.referencePrice.getValue(index); Num threshold = this.stopLossThreshold.getValue(index); if (tradingRecord.getCurrentPosition().getEntry().isBuy()) { return currentPrice.isLessThan(entryPrice.minus(threshold)); } else { return currentPrice.isGreaterThan(entryPrice.plus(threshold)); } } return false; }
@Test public void testLongPositionStopLoss() { ZonedDateTime initialEndDateTime = ZonedDateTime.now(); for (int i = 0; i < 10; i++) { series.addBar(initialEndDateTime.plusDays(i), 100, 105, 95, 100); } AverageTrueRangeStopLossRule rule = new AverageTrueRangeStopLossRule(series, 5, 1); // Enter long position TradingRecord tradingRecord = new BaseTradingRecord(Trade.TradeType.BUY, new LinearTransactionCostModel(0.01), new ZeroCostModel()); tradingRecord.enter(0, series.numOf(100), series.numOf(1)); // Price remains above stop loss series.addBar(series.getLastBar().getEndTime().plusDays(1), 90, 95, 85, 90); assertFalse(rule.isSatisfied(series.getEndIndex(), tradingRecord)); // Price drops below stop loss series.addBar(series.getLastBar().getEndTime().plusDays(1), 90, 95, 85, 89); assertTrue(rule.isSatisfied(series.getEndIndex(), tradingRecord)); }
public WriteResult<T, K> update(Bson filter, T object, boolean upsert, boolean multi) { return update(filter, object, upsert, multi, delegate.getWriteConcern()); }
@Test void updateWithBsonVariants() { final var collection = spy(jacksonCollection("simple", Simple.class)); final DBQuery.Query query = DBQuery.empty(); final DBUpdate.Builder update = new DBUpdate.Builder().set("name", "foo"); collection.update(query, update); verify(collection).update(eq(query), eq(update), eq(false), eq(false)); }
void removeWatchers() { List<NamespaceWatcher> localEntries = Lists.newArrayList(entries); while (localEntries.size() > 0) { NamespaceWatcher watcher = localEntries.remove(0); if (entries.remove(watcher)) { try { log.debug("Removing watcher for path: " + watcher.getUnfixedPath()); RemoveWatchesBuilderImpl builder = new RemoveWatchesBuilderImpl(client); builder.internalRemoval(watcher, watcher.getUnfixedPath()); } catch (Exception e) { log.error("Could not remove watcher for path: " + watcher.getUnfixedPath()); } } } }
@Test public void testSameWatcherDifferentPaths1Triggered() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); final CountDownLatch latch = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { latch.countDown(); } }; removerClient.checkExists().usingWatcher(watcher).forPath("/a/b/c"); removerClient.checkExists().usingWatcher(watcher).forPath("/d/e/f"); removerClient.create().creatingParentsIfNeeded().forPath("/d/e/f"); Timing timing = new Timing(); assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); removerClient.removeWatchers(); } finally { TestCleanState.closeAndTestClean(client); } }
boolean contains(DatanodeDescriptor node) { if (node==null) { return false; } String ipAddr = node.getIpAddr(); hostmapLock.readLock().lock(); try { DatanodeDescriptor[] nodes = map.get(ipAddr); if (nodes != null) { for(DatanodeDescriptor containedNode:nodes) { if (node==containedNode) { return true; } } } } finally { hostmapLock.readLock().unlock(); } return false; }
@Test public void testContains() throws Exception { DatanodeDescriptor nodeNotInMap = DFSTestUtil.getDatanodeDescriptor("3.3.3.3", "/d1/r4"); for (int i = 0; i < dataNodes.length; i++) { assertTrue(map.contains(dataNodes[i])); } assertFalse(map.contains(null)); assertFalse(map.contains(nodeNotInMap)); }
@ConstantFunction(name = "bitShiftRightLogical", argTypes = {INT, BIGINT}, returnType = INT) public static ConstantOperator bitShiftRightLogicalInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createInt(first.getInt() >>> second.getBigint()); }
@Test public void bitShiftRightLogicalInt() { assertEquals(1, ScalarOperatorFunctions.bitShiftRightLogicalInt(O_INT_10, O_BI_3).getInt()); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { // {"code":400,"message":"Bad Request","debugInfo":"Node ID must be positive.","errorCode":-80001} final PathAttributes attributes = new PathAttributes(); if(session.userAccount().isUserInRole(SDSPermissionsFeature.ROOM_MANAGER_ROLE)) { // We need to map user roles to ACLs in order to decide if creating a top-level room is allowed final Acl acl = new Acl(); acl.addAll(new Acl.CanonicalUser(), SDSPermissionsFeature.CREATE_ROLE); attributes.setAcl(acl); } return attributes; } // Throw failure if looking up file fails final String id = nodeid.getVersionId(file); try { return this.findNode(file, id); } catch(NotfoundException e) { if(log.isWarnEnabled()) { log.warn(String.format("Previously cached node id %s no longer found for file %s", id, file)); } // Try with reset cache after failure finding node id return this.findNode(file, nodeid.getVersionId(file)); } }
@Test public void testFindRoot() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final SDSAttributesFinderFeature f = new SDSAttributesFinderFeature(session, nodeid); final PathAttributes attributes = f.find(new Path("/", EnumSet.of(Path.Type.volume, Path.Type.directory))); assertNotEquals(PathAttributes.EMPTY, attributes); assertNotEquals(Acl.EMPTY, attributes.getAcl()); }
public List<String> build() { if (columnDefs.isEmpty()) { throw new IllegalStateException("No column has been defined"); } switch (dialect.getId()) { case PostgreSql.ID: return createPostgresQuery(); case Oracle.ID: return createOracleQuery(); default: return createMsSqlAndH2Queries(); } }
@Test public void update_columns_on_h2() { assertThat(createSampleBuilder(new H2()).build()) .containsOnly( "ALTER TABLE issues ALTER COLUMN value DOUBLE NULL", "ALTER TABLE issues ALTER COLUMN name VARCHAR (10) NULL"); }
@Override public List<TypeInfo> getColumnTypes(Configuration conf) throws HiveJdbcDatabaseAccessException { return getColumnMetadata(conf, typeInfoTranslator); }
@Test public void testGetColumnTypes_fieldListQuery() throws HiveJdbcDatabaseAccessException { Configuration conf = buildConfiguration(); conf.set(JdbcStorageConfig.QUERY.getPropertyName(), "select name,referrer from test_strategy"); DatabaseAccessor accessor = DatabaseAccessorFactory.getAccessor(conf); List<TypeInfo> expectedTypes = new ArrayList<>(2); expectedTypes.add(TypeInfoFactory.getVarcharTypeInfo(50)); expectedTypes.add(TypeInfoFactory.getVarcharTypeInfo(1024)); Assert.assertEquals(expectedTypes, accessor.getColumnTypes(conf)); }
public MetricsBuilder collectorSyncPeriod(Integer collectorSyncPeriod) { this.collectorSyncPeriod = collectorSyncPeriod; return getThis(); }
@Test void collectorSyncPeriod() { MetricsBuilder builder = MetricsBuilder.newBuilder(); builder.collectorSyncPeriod(10); Assertions.assertEquals(10, builder.build().getCollectorSyncPeriod()); }
@Override public Stream<ColumnName> resolveSelectStar( final Optional<SourceName> sourceName ) { return getSource().resolveSelectStar(sourceName) .map(name -> aliases.getOrDefault(name, name)); }
@Test public void shouldNotAddAliasOnResolveSelectStarWhenNotAliased() { // Given: final ColumnName unknown = ColumnName.of("unknown"); when(source.resolveSelectStar(any())) .thenReturn(ImmutableList.of(K, unknown).stream()); // When: final Stream<ColumnName> result = projectNode.resolveSelectStar(Optional.empty()); // Then: final List<ColumnName> columns = result.collect(Collectors.toList()); assertThat(columns, contains(K, unknown)); }
@PutMapping @Secured(resource = AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, action = ActionTypes.WRITE) public Object updateUser(@RequestParam String username, @RequestParam String newPassword, HttpServletResponse response, HttpServletRequest request) throws IOException { // admin or same user try { if (!hasPermission(username, request)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "authorization failed!"); return null; } } catch (HttpSessionRequiredException e) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "session expired!"); return null; } catch (AccessException exception) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "authorization failed!"); return null; } User user = userDetailsService.getUserFromDatabase(username); if (user == null) { throw new IllegalArgumentException("user " + username + " not exist!"); } userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword)); return RestResultUtils.success("update user ok!"); }
@Test void testUpdateUser6() throws IOException, AccessException { RequestContextHolder.getContext().getAuthContext().getIdentityContext() .setParameter(AuthConstants.NACOS_USER_KEY, null); when(authConfigs.isAuthEnabled()).thenReturn(true); when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenReturn(null); MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); assertNull(result); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus()); }
public static void checkMetaDir() throws InvalidMetaDirException, IOException { // check meta dir // if metaDir is the default config: StarRocksFE.STARROCKS_HOME_DIR + "/meta", // we should check whether both the new default dir (STARROCKS_HOME_DIR + "/meta") // and the old default dir (DORIS_HOME_DIR + "/doris-meta") are present. If both are present, // we need to let users keep only one to avoid starting from outdated metadata. Path oldDefaultMetaDir = Paths.get(System.getenv("DORIS_HOME") + "/doris-meta"); Path newDefaultMetaDir = Paths.get(System.getenv("STARROCKS_HOME") + "/meta"); Path metaDir = Paths.get(Config.meta_dir); if (metaDir.equals(newDefaultMetaDir)) { File oldMeta = new File(oldDefaultMetaDir.toUri()); File newMeta = new File(newDefaultMetaDir.toUri()); if (oldMeta.exists() && newMeta.exists()) { LOG.error("New default meta dir: {} and Old default meta dir: {} are both present. " + "Please make sure {} has the latest data, and remove the another one.", newDefaultMetaDir, oldDefaultMetaDir, newDefaultMetaDir); throw new InvalidMetaDirException(); } } File meta = new File(metaDir.toUri()); if (!meta.exists()) { // If metaDir is not the default config, it means the user has specified the other directory // We should not use the oldDefaultMetaDir. // Just exit in this case if (!metaDir.equals(newDefaultMetaDir)) { LOG.error("meta dir {} dose not exist", metaDir); throw new InvalidMetaDirException(); } File oldMeta = new File(oldDefaultMetaDir.toUri()); if (oldMeta.exists()) { // For backward compatible Config.meta_dir = oldDefaultMetaDir.toString(); } else { LOG.error("meta dir {} does not exist", meta.getAbsolutePath()); throw new InvalidMetaDirException(); } } long lowerFreeDiskSize = Long.parseLong(EnvironmentParams.FREE_DISK.getDefault()); FileStore store = Files.getFileStore(Paths.get(Config.meta_dir)); if (store.getUsableSpace() < lowerFreeDiskSize) { LOG.error("Free capacity left for meta dir: {} is less than {}", Config.meta_dir, new ByteSizeValue(lowerFreeDiskSize)); throw new InvalidMetaDirException(); } Path imageDir = Paths.get(Config.meta_dir + GlobalStateMgr.IMAGE_DIR); Path bdbDir = Paths.get(BDBEnvironment.getBdbDir()); boolean haveImageData = false; if (Files.exists(imageDir)) { try (Stream<Path> stream = Files.walk(imageDir)) { haveImageData = stream.anyMatch(path -> path.getFileName().toString().startsWith("image.")); } } boolean haveBDBData = false; if (Files.exists(bdbDir)) { try (Stream<Path> stream = Files.walk(bdbDir)) { haveBDBData = stream.anyMatch(path -> path.getFileName().toString().endsWith(".jdb")); } } if (haveImageData && !haveBDBData && !Config.start_with_incomplete_meta) { LOG.error("image exists, but bdb dir is empty, " + "set start_with_incomplete_meta to true if you want to forcefully recover from image data, " + "this may end with stale meta data, so please be careful."); throw new InvalidMetaDirException(); } }
@Test public void testUseOldMetaDir() throws IOException, InvalidMetaDirException { Config.start_with_incomplete_meta = false; new MockUp<System>() { @Mock public String getenv(String name) { return testDir; } }; mkdir(testDir + "/doris-meta/"); Config.meta_dir = testDir + "/meta"; try { MetaHelper.checkMetaDir(); } finally { deleteDir(new File(testDir)); } Assert.assertEquals(Config.meta_dir, testDir + "/doris-meta"); }
public int ndots() { return ndots; }
@Test void ndotsBadValues() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> builder.ndots(-2)) .withMessage("ndots must be greater or equal to -1"); }
public DateTime getStartedAt() { return startedAt; }
@Test public void testGetStartedAt() throws Exception { assertNotNull(status.getStartedAt()); }
@Override public void clear() { history.clear(); }
@Test void testClear() { TreeMapLogHistory<String> history = new TreeMapLogHistory<>(); history.addAt(100, "100"); history.addAt(200, "200"); history.clear(); assertEquals(Optional.empty(), history.lastEntry()); }
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) { return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature); }
@Test public void testOnWindowExpirationMultipleAnnotation() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Found multiple methods annotated with @OnWindowExpiration"); thrown.expectMessage("bar()"); thrown.expectMessage("baz()"); thrown.expectMessage(getClass().getName() + "$"); DoFnSignatures.getSignature( new DoFn<String, String>() { @ProcessElement public void foo() {} @OnWindowExpiration public void bar() {} @OnWindowExpiration public void baz() {} }.getClass()); }
public void publishExpired(Cache<K, V> cache, K key, V value) { publish(cache, EventType.EXPIRED, key, /* hasOldValue */ true, /* oldValue */ value, /* newValue */ value, /* quiet */ false); }
@Test public void publishExpired() { var dispatcher = new EventDispatcher<Integer, Integer>(Runnable::run); registerAll(dispatcher); dispatcher.publishExpired(cache, 1, 2); verify(expiredListener, times(4)).onExpired(any()); assertThat(dispatcher.pending.get()).hasSize(2); assertThat(dispatcher.dispatchQueues.values().stream() .flatMap(queue -> queue.entrySet().stream())).isEmpty(); }
public void setTransactionAnnotation(GlobalTransactional transactionAnnotation) { this.transactionAnnotation = transactionAnnotation; }
@Test public void testSetTransactionAnnotation() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { MethodDesc methodDesc = getMethodDesc(); assertThat(methodDesc.getTransactionAnnotation()).isNotNull(); methodDesc.setTransactionAnnotation(null); assertThat(methodDesc.getTransactionAnnotation()).isNull(); }
public String getLocation() { String location = properties.getProperty(NACOS_LOGGING_CONFIG_PROPERTY); if (StringUtils.isBlank(location)) { if (isDefaultLocationEnabled()) { return defaultLocation; } return null; } return location; }
@Test void testGetLocationForSpecifiedWithDefault() { properties.setProperty("nacos.logging.config", "classpath:specified-test.xml"); assertEquals("classpath:specified-test.xml", loggingProperties.getLocation()); }
public URLNormalizer secureScheme() { Matcher m = PATTERN_SCHEMA.matcher(url); if (m.find()) { String schema = m.group(1); if ("http".equalsIgnoreCase(schema)) { url = m.replaceFirst(schema + "s$2"); } } return this; }
@Test public void testSecureScheme() { s = "https://www.example.com/secure.html"; t = "https://www.example.com/secure.html"; assertEquals(t, n(s).secureScheme().toString()); s = "HTtP://www.example.com/secure.html"; t = "HTtPs://www.example.com/secure.html"; assertEquals(t, n(s).secureScheme().toString()); s = "HTTP://www.example.com/nonsecure.html"; t = "HTTPs://www.example.com/nonsecure.html"; assertEquals(t, n(s).secureScheme().toString()); }
public CoercedExpressionResult coerce() { final Class<?> leftClass = left.getRawClass(); final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass); final Class<?> rightClass = right.getRawClass(); final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass); boolean sameClass = leftClass == rightClass; boolean isUnificationExpression = left instanceof UnificationTypedExpression || right instanceof UnificationTypedExpression; if (sameClass || isUnificationExpression) { return new CoercedExpressionResult(left, right); } if (!canCoerce()) { throw new CoercedExpressionException(new InvalidExpressionErrorResult("Comparison operation requires compatible types. Found " + leftClass + " and " + rightClass)); } if ((nonPrimitiveLeftClass == Integer.class || nonPrimitiveLeftClass == Long.class) && nonPrimitiveRightClass == Double.class) { CastExpr castExpression = new CastExpr(PrimitiveType.doubleType(), this.left.getExpression()); return new CoercedExpressionResult( new TypedExpression(castExpression, double.class, left.getType()), right, false); } final boolean leftIsPrimitive = leftClass.isPrimitive() || Number.class.isAssignableFrom( leftClass ); final boolean canCoerceLiteralNumberExpr = canCoerceLiteralNumberExpr(leftClass); boolean rightAsStaticField = false; final Expression rightExpression = right.getExpression(); final TypedExpression coercedRight; if (leftIsPrimitive && canCoerceLiteralNumberExpr && rightExpression instanceof LiteralStringValueExpr) { final Expression coercedLiteralNumberExprToType = coerceLiteralNumberExprToType((LiteralStringValueExpr) right.getExpression(), leftClass); coercedRight = right.cloneWithNewExpression(coercedLiteralNumberExprToType); coercedRight.setType( leftClass ); } else if (shouldCoerceBToString(left, right)) { coercedRight = coerceToString(right); } else if (isNotBinaryExpression(right) && canBeNarrowed(leftClass, rightClass) && right.isNumberLiteral()) { coercedRight = castToClass(leftClass); } else if (leftClass == long.class && rightClass == int.class) { coercedRight = right.cloneWithNewExpression(new CastExpr(PrimitiveType.longType(), right.getExpression())); } else if (leftClass == Date.class && rightClass == String.class) { coercedRight = coerceToDate(right); rightAsStaticField = true; } else if (leftClass == LocalDate.class && rightClass == String.class) { coercedRight = coerceToLocalDate(right); rightAsStaticField = true; } else if (leftClass == LocalDateTime.class && rightClass == String.class) { coercedRight = coerceToLocalDateTime(right); rightAsStaticField = true; } else if (shouldCoerceBToMap()) { coercedRight = castToClass(toNonPrimitiveType(leftClass)); } else if (isBoolean(leftClass) && !isBoolean(rightClass)) { coercedRight = coerceBoolean(right); } else { coercedRight = right; } final TypedExpression coercedLeft; if (nonPrimitiveLeftClass == Character.class && shouldCoerceBToString(right, left)) { coercedLeft = coerceToString(left); } else { coercedLeft = left; } return new CoercedExpressionResult(coercedLeft, coercedRight, rightAsStaticField); }
@Test public void testStringToBooleanRandomStringError() { final TypedExpression left = expr(THIS_PLACEHOLDER + ".getBooleanValue", Boolean.class); final TypedExpression right = expr("\"randomString\"", String.class); assertThatThrownBy(() -> new CoercedExpression(left, right, false).coerce()) .isInstanceOf(CoercedExpression.CoercedExpressionException.class); }
public boolean canRebalance() { return PREPARING_REBALANCE.validPreviousStates().contains(state); }
@Test public void testCanRebalanceWhenStable() { assertTrue(group.canRebalance()); }
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testParseNewStyleResourceMemoryNegativeWithSpaces() throws Exception { expectNegativeValueOfResource("memory"); parseResourceConfigValue("memory-mb=-5120, vcores=2"); }
public void changeStrategy(DragonSlayingStrategy strategy) { this.strategy = strategy; }
@Test void testChangeStrategy() { final var initialStrategy = mock(DragonSlayingStrategy.class); final var dragonSlayer = new DragonSlayer(initialStrategy); dragonSlayer.goToBattle(); verify(initialStrategy).execute(); final var newStrategy = mock(DragonSlayingStrategy.class); dragonSlayer.changeStrategy(newStrategy); dragonSlayer.goToBattle(); verify(newStrategy).execute(); verifyNoMoreInteractions(initialStrategy, newStrategy); }
DataTableType lookupTableTypeByType(Type type) { return lookupTableTypeByType(type, Function.identity()); }
@Test void null_string_transformed_to_null() { DataTableTypeRegistry registry = new DataTableTypeRegistry(Locale.ENGLISH); DataTableType dataTableType = registry.lookupTableTypeByType(LIST_OF_LIST_OF_STRING); assertEquals( singletonList(singletonList(null)), dataTableType.transform(singletonList(singletonList(null)))); }
@Override public List<String> findConfigInfoTags(final String dataId, final String group, final String tenant) { String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; ConfigInfoTagMapper configInfoTagMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_TAG); String selectSql = configInfoTagMapper.select(Collections.singletonList("tag_id"), Arrays.asList("data_id", "group_id", "tenant_id")); return jt.queryForList(selectSql, new Object[] {dataId, group, tenantTmp}, String.class); }
@Test void testFindConfigInfoTags() { String dataId = "dataId1112222"; String group = "group22"; String tenant = "tenant2"; List<String> mockedTags = Arrays.asList("tags1", "tags11", "tags111"); Mockito.when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))) .thenReturn(mockedTags); List<String> configInfoTags = externalConfigInfoTagPersistService.findConfigInfoTags(dataId, group, tenant); assertEquals(mockedTags, configInfoTags); }
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_containsExactly_primitiveFloatArray_success() { assertThat(array(1.0f, 2.0f, 3.0f)) .usingExactEquality() .containsExactly(array(2.0f, 1.0f, 3.0f)); }
public static Object getFieldValue(Object obj, String fieldName) { try { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); return field.get(obj); } catch (Exception e) { throw new RuntimeException(e); } }
@Test void testGetFieldValue() { Object elementData = ReflectUtils.getFieldValue(listStr, "elementData"); assertTrue(elementData instanceof Object[]); assertEquals(2, ((Object[]) elementData).length); }
public static <T> Inner<T> create() { return new Inner<>(); }
@Test @Category(NeedsRunner.class) public void addDuplicateField() { Schema schema = Schema.builder().addStringField("field1").build(); thrown.expect(IllegalArgumentException.class); pipeline .apply(Create.of(Row.withSchema(schema).addValue("value").build()).withRowSchema(schema)) .apply(AddFields.<Row>create().field("field1", Schema.FieldType.INT32)); pipeline.run(); }