focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void run() { try { PushDataWrapper wrapper = generatePushData(); ClientManager clientManager = delayTaskEngine.getClientManager(); for (String each : getTargetClientIds()) { Client client = clientManager.getClient(each); if (null == client) { // means this client has disconnect continue; } Subscriber subscriber = client.getSubscriber(service); // skip if null if (subscriber == null) { continue; } delayTaskEngine.getPushExecutor().doPushWithCallback(each, subscriber, wrapper, new ServicePushCallback(each, subscriber, wrapper.getOriginalData(), delayTask.isPushToAll())); } } catch (Exception e) { Loggers.PUSH.error("Push task for service" + service.getGroupedServiceName() + " execute failed ", e); delayTaskEngine.addTask(service, new PushDelayTask(service, 1000L)); } }
@Test void testRunFailedWithRetry() { PushDelayTask delayTask = new PushDelayTask(service, 0L); PushExecuteTask executeTask = new PushExecuteTask(service, delayTaskExecuteEngine, delayTask); pushExecutor.setShouldSuccess(false); pushExecutor.setFailedException(new RuntimeException()); executeTask.run(); assertEquals(1, MetricsMonitor.getFailedPushMonitor().get()); verify(delayTaskExecuteEngine).addTask(eq(service), any(PushDelayTask.class)); }
@Override protected void notifyFirstSampleAfterLoopRestart() { log.debug("notifyFirstSampleAfterLoopRestart called " + "with config(httpclient.reset_state_on_thread_group_iteration={})", RESET_STATE_ON_THREAD_GROUP_ITERATION); JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables(); if (jMeterVariables.isSameUserOnNextIteration()) { log.debug("Thread Group is configured to simulate a returning visitor on each iteration, ignoring property value {}", RESET_STATE_ON_THREAD_GROUP_ITERATION); resetStateOnThreadGroupIteration.set(false); } else { log.debug("Thread Group is configured to simulate a new visitor on each iteration, using property value {}", RESET_STATE_ON_THREAD_GROUP_ITERATION); resetStateOnThreadGroupIteration.set(RESET_STATE_ON_THREAD_GROUP_ITERATION); } log.debug("Thread state will be reset ?: {}", RESET_STATE_ON_THREAD_GROUP_ITERATION); }
@Test public void testNotifyFirstSampleAfterLoopRestartWhenThreadIterationIsSameUser() { jmvars.putObject(SAME_USER, true); jmctx.setVariables(jmvars); HTTPSamplerBase sampler = (HTTPSamplerBase) new HttpTestSampleGui().createTestElement(); sampler.setThreadContext(jmctx); HTTPHC4Impl hc = new HTTPHC4Impl(sampler); hc.notifyFirstSampleAfterLoopRestart(); Assertions.assertFalse(HTTPHC4Impl.resetStateOnThreadGroupIteration.get(), "User is the same, the state shouldn't be reset"); }
@VisibleForTesting static Duration parseToDuration(String timeStr) { final Matcher matcher = Pattern.compile("(?<value>\\d+)\\s*(?<time>[dhms])").matcher(timeStr); if (!matcher.matches()) { throw new IllegalArgumentException("Expected a time specification in the form <number>[d,h,m,s], e.g. 3m, but found [" + timeStr + "]"); } final int value = Integer.parseInt(matcher.group("value")); final String timeSpecifier = matcher.group("time"); final TemporalUnit unit; switch (timeSpecifier) { case "d": unit = ChronoUnit.DAYS; break; case "h": unit = ChronoUnit.HOURS; break; case "m": unit = ChronoUnit.MINUTES; break; case "s": unit = ChronoUnit.SECONDS; break; default: throw new IllegalStateException("Expected a time unit specification from d,h,m,s but found: [" + timeSpecifier + "]"); } return Duration.of(value, unit); }
@Test(expected = IllegalArgumentException.class) public void testParseToDurationWithBadDurationFormatThrowsAnError() { AbstractPipelineExt.parseToDuration("+3m"); }
@ExecuteOn(TaskExecutors.IO) @Put(uri = "{namespace}/files") @Operation(tags = {"Files"}, summary = "Move a file or directory") public void move( @Parameter(description = "The namespace id") @PathVariable String namespace, @Parameter(description = "The internal storage uri to move from") @QueryValue URI from, @Parameter(description = "The internal storage uri to move to") @QueryValue URI to ) throws IOException, URISyntaxException { ensureWritableNamespaceFile(from); ensureWritableNamespaceFile(to); storageInterface.move(tenantService.resolveTenant(), NamespaceFile.of(namespace, from).uri(),NamespaceFile.of(namespace, to).uri()); }
@Test void move() throws IOException { storageInterface.createDirectory(null, toNamespacedStorageUri(NAMESPACE, URI.create("/test"))); client.toBlocking().exchange(HttpRequest.PUT("/api/v1/namespaces/" + NAMESPACE + "/files?from=/test&to=/foo", null)); FileAttributes res = storageInterface.getAttributes(null, toNamespacedStorageUri(NAMESPACE, URI.create("/foo"))); assertThat(res.getFileName(), is("foo")); assertThat(res.getType(), is(FileAttributes.FileType.Directory)); }
public static Method getApplyMethod(ScalarFn scalarFn) { Class<? extends ScalarFn> clazz = scalarFn.getClass(); Collection<Method> matches = ReflectHelpers.declaredMethodsWithAnnotation( ScalarFn.ApplyMethod.class, clazz, ScalarFn.class); if (matches.isEmpty()) { throw new IllegalArgumentException( String.format( "No method annotated with @%s found in class %s.", ScalarFn.ApplyMethod.class.getSimpleName(), clazz.getName())); } // If we have at least one match, then either it should be the only match // or it should be an extension of the other matches (which came from parent // classes). Method first = matches.iterator().next(); for (Method other : matches) { if (!first.getName().equals(other.getName()) || !Arrays.equals(first.getParameterTypes(), other.getParameterTypes())) { throw new IllegalArgumentException( String.format( "Found multiple methods annotated with @%s. [%s] and [%s]", ScalarFn.ApplyMethod.class.getSimpleName(), ReflectHelpers.formatMethod(first), ReflectHelpers.formatMethod(other))); } } // Method must be public. if ((first.getModifiers() & Modifier.PUBLIC) == 0) { throw new IllegalArgumentException( String.format("Method %s is not public.", ReflectHelpers.formatMethod(first))); } return first; }
@Test public void testNonPublicMethodThrowsIllegalArgumentException() { thrown.expect(instanceOf(IllegalArgumentException.class)); thrown.expectMessage("not public"); ScalarFnReflector.getApplyMethod(new IncrementFnWithProtectedMethod()); }
@Override public String toString() { return name; }
@Test void testToString() { List.of("Gandalf", "Dumbledore", "Oz", "Merlin") .forEach(name -> assertEquals(name, new Wizard(name).toString())); }
@VisibleForTesting void doClean(String rootUuid, List<Filter> filters, DbSession session) { List<PurgeableAnalysisDto> history = new ArrayList<>(selectAnalysesOfComponent(rootUuid, session)); for (Filter filter : filters) { filter.log(); List<PurgeableAnalysisDto> toDelete = filter.filter(history); List<PurgeableAnalysisDto> deleted = delete(rootUuid, toDelete, session); history.removeAll(deleted); } }
@Test void doClean() { PurgeDao dao = mock(PurgeDao.class); DbSession session = mock(DbSession.class); when(dao.selectProcessedAnalysisByComponentUuid("uuid_123", session)).thenReturn(Arrays.asList( new PurgeableAnalysisDto().setAnalysisUuid("u999").setDate(System2.INSTANCE.now()), new PurgeableAnalysisDto().setAnalysisUuid("u456").setDate(System2.INSTANCE.now()) )); Filter filter1 = newFirstSnapshotInListFilter(); Filter filter2 = newFirstSnapshotInListFilter(); PurgeProfiler profiler = new PurgeProfiler(); DefaultPeriodCleaner cleaner = new DefaultPeriodCleaner(dao, profiler); cleaner.doClean("uuid_123", Arrays.asList(filter1, filter2), session); InOrder inOrder = Mockito.inOrder(dao, filter1, filter2); inOrder.verify(filter1).log(); inOrder.verify(dao, times(1)).deleteAnalyses(session, profiler, ImmutableList.of("u999")); inOrder.verify(filter2).log(); inOrder.verify(dao, times(1)).deleteAnalyses(session, profiler, ImmutableList.of("u456")); inOrder.verifyNoMoreInteractions(); }
public int controlledPoll(final ControlledFragmentHandler handler, final int fragmentLimit) { if (isClosed) { return 0; } int fragmentsRead = 0; long initialPosition = subscriberPosition.get(); int initialOffset = (int)initialPosition & termLengthMask; int offset = initialOffset; final UnsafeBuffer termBuffer = activeTermBuffer(initialPosition); final int capacity = termBuffer.capacity(); final Header header = this.header; header.buffer(termBuffer); try { while (fragmentsRead < fragmentLimit && offset < capacity) { final int length = frameLengthVolatile(termBuffer, offset); if (length <= 0) { break; } final int frameOffset = offset; final int alignedLength = BitUtil.align(length, FRAME_ALIGNMENT); offset += alignedLength; if (isPaddingFrame(termBuffer, frameOffset)) { continue; } ++fragmentsRead; header.offset(frameOffset); final Action action = handler.onFragment( termBuffer, frameOffset + HEADER_LENGTH, length - HEADER_LENGTH, header); if (ABORT == action) { --fragmentsRead; offset -= alignedLength; break; } if (BREAK == action) { break; } if (COMMIT == action) { initialPosition += (offset - initialOffset); initialOffset = offset; subscriberPosition.setOrdered(initialPosition); } } } catch (final Exception ex) { errorHandler.onError(ex); } finally { final long resultingPosition = initialPosition + (offset - initialOffset); if (resultingPosition > initialPosition) { subscriberPosition.setOrdered(resultingPosition); } } return fragmentsRead; }
@Test void shouldPollFragmentsToControlledFragmentHandlerOnContinue() { final long initialPosition = computePosition(INITIAL_TERM_ID, 0, POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID); position.setOrdered(initialPosition); final Image image = createImage(); insertDataFrame(INITIAL_TERM_ID, offsetForFrame(0)); insertDataFrame(INITIAL_TERM_ID, offsetForFrame(1)); when(mockControlledFragmentHandler.onFragment(any(DirectBuffer.class), anyInt(), anyInt(), any(Header.class))) .thenReturn(Action.CONTINUE); final int fragmentsRead = image.controlledPoll(mockControlledFragmentHandler, Integer.MAX_VALUE); assertThat(fragmentsRead, is(2)); final InOrder inOrder = Mockito.inOrder(position, mockControlledFragmentHandler); inOrder.verify(mockControlledFragmentHandler).onFragment( any(UnsafeBuffer.class), eq(HEADER_LENGTH), eq(DATA.length), any(Header.class)); inOrder.verify(mockControlledFragmentHandler).onFragment( any(UnsafeBuffer.class), eq(ALIGNED_FRAME_LENGTH + HEADER_LENGTH), eq(DATA.length), any(Header.class)); inOrder.verify(position).setOrdered(initialPosition + (ALIGNED_FRAME_LENGTH * 2L)); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof MirroringName) { final MirroringName that = (MirroringName) obj; return this.getClass() == that.getClass() && Objects.equals(this.name, that.name); } return false; }
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(name1, sameAsName1) .addEqualityGroup(name2) .testEquals(); }
@Override public boolean isTenantIdSet() { return tenantId.get() != null; }
@Test void isTenantIdSet() { assertThat(underTest.isTenantIdSet()).isFalse(); underTest.setTenantId("flowable"); assertThat(underTest.isTenantIdSet()).isTrue(); underTest.clearTenantId(); assertThat(underTest.isTenantIdSet()).isFalse(); underTest.setTenantId(null); assertThat(underTest.isTenantIdSet()).isTrue(); }
public boolean eval(StructLike data) { return new EvalVisitor().eval(data); }
@Test public void testLessThan() { Evaluator evaluator = new Evaluator(STRUCT, lessThan("x", 7)); assertThat(evaluator.eval(TestHelpers.Row.of(7, 8, null, null))).as("7 < 7 => false").isFalse(); assertThat(evaluator.eval(TestHelpers.Row.of(6, 8, null, null))).as("6 < 7 => true").isTrue(); Evaluator structEvaluator = new Evaluator(STRUCT, lessThan("s1.s2.s3.s4.i", 7)); assertThat( structEvaluator.eval( TestHelpers.Row.of( 7, 8, null, TestHelpers.Row.of( TestHelpers.Row.of(TestHelpers.Row.of(TestHelpers.Row.of(7))))))) .as("7 < 7 => false") .isFalse(); assertThat( structEvaluator.eval( TestHelpers.Row.of( 6, 8, null, TestHelpers.Row.of( TestHelpers.Row.of(TestHelpers.Row.of(TestHelpers.Row.of(6))))))) .as("6 < 7 => true") .isTrue(); }
@Override public Map<String, String> getHeaders(ConnectorSession session) { if (isUseIdentityThriftHeader(session)) { return ImmutableMap.of(PRESTO_CONNECTOR_IDENTITY_USER, session.getUser()); } return ImmutableMap.of(); }
@Test public void testWithIdentityHeaders() { ThriftConnectorConfig config = new ThriftConnectorConfig() .setUseIdentityThriftHeader(true); ThriftSessionProperties properties = new ThriftSessionProperties(config); TestingConnectorSession session = new TestingConnectorSession(properties.getSessionProperties()); DefaultThriftHeaderProvider headerProvider = new DefaultThriftHeaderProvider(); Map<String, String> headers = headerProvider.getHeaders(session); assertEquals(headers.get("presto_connector_user"), session.getUser()); }
public static URI getURIFromRequestUrl(String source) { // try without encoding the URI try { return new URI(source); } catch (URISyntaxException ignore) { System.out.println("Source is not encoded, encoding now"); } try { URL url = new URL(source); return new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); } catch (MalformedURLException | URISyntaxException e) { throw new IllegalArgumentException(e); } }
@Test public void testGetURIFromRequestUrlShouldEncode() { final String testUrl = "http://example.com/this is not encoded"; final String expected = "http://example.com/this%20is%20not%20encoded"; assertEquals(expected, UriUtil.getURIFromRequestUrl(testUrl).toString()); }
public Map<Service, ServiceMetadata> getServiceMetadataSnapshot() { ConcurrentMap<Service, ServiceMetadata> result = new ConcurrentHashMap<>(serviceMetadataMap.size()); result.putAll(serviceMetadataMap); return result; }
@Test void testGetServiceMetadataSnapshot() { Map<Service, ServiceMetadata> serviceMetadataSnapshot = namingMetadataManager.getServiceMetadataSnapshot(); assertEquals(1, serviceMetadataSnapshot.size()); }
@Override public Response cancelDelegationToken(HttpServletRequest hsr) throws AuthorizationException, IOException, InterruptedException, Exception { try { // get Caller UserGroupInformation Configuration conf = federationFacade.getConf(); UserGroupInformation callerUGI = getKerberosUserGroupInformation(conf, hsr); // parse Token Data Token<RMDelegationTokenIdentifier> token = extractToken(hsr); org.apache.hadoop.yarn.api.records.Token dToken = BuilderUtils .newDelegationToken(token.getIdentifier(), token.getKind().toString(), token.getPassword(), token.getService().toString()); // cancelDelegationToken callerUGI.doAs((PrivilegedExceptionAction<CancelDelegationTokenResponse>) () -> { CancelDelegationTokenRequest req = CancelDelegationTokenRequest.newInstance(dToken); return this.getRouterClientRMService().cancelDelegationToken(req); }); RouterAuditLogger.logSuccess(getUser().getShortUserName(), CANCEL_DELEGATIONTOKEN, TARGET_WEB_SERVICE); return Response.status(Status.OK).build(); } catch (YarnException e) { LOG.error("Cancel delegation token request failed.", e); RouterAuditLogger.logFailure(getUser().getShortUserName(), CANCEL_DELEGATIONTOKEN, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); return Response.status(Status.FORBIDDEN).entity(e.getMessage()).build(); } }
@Test public void testCancelDelegationToken() throws Exception { DelegationToken token = new DelegationToken(); token.setRenewer(TEST_RENEWER); Principal principal = mock(Principal.class); when(principal.getName()).thenReturn(TEST_RENEWER); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getRemoteUser()).thenReturn(TEST_RENEWER); when(request.getUserPrincipal()).thenReturn(principal); when(request.getAuthType()).thenReturn("kerberos"); Response response = interceptor.postDelegationToken(token, request); Assert.assertNotNull(response); Object entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertTrue(entity instanceof DelegationToken); DelegationToken dtoken = (DelegationToken) entity; final String yarnTokenHeader = "Hadoop-YARN-RM-Delegation-Token"; when(request.getHeader(yarnTokenHeader)).thenReturn(dtoken.getToken()); Response cancelResponse = interceptor.cancelDelegationToken(request); Assert.assertNotNull(cancelResponse); Assert.assertEquals(response.getStatus(), Status.OK.getStatusCode()); }
@Override public Page<PermissionInfo> getPermissions(String role, int pageNo, int pageSize) { AuthPaginationHelper<PermissionInfo> helper = createPaginationHelper(); String sqlCountRows = "SELECT count(*) FROM permissions WHERE "; String sqlFetchRows = "SELECT role,resource,action FROM permissions WHERE "; String where = " role= ? "; List<String> params = new ArrayList<>(); if (StringUtils.isNotBlank(role)) { params = Collections.singletonList(role); } else { where = " 1=1 "; } try { Page<PermissionInfo> pageInfo = helper.fetchPage(sqlCountRows + where, sqlFetchRows + where, params.toArray(), pageNo, pageSize, PERMISSION_ROW_MAPPER); if (pageInfo == null) { pageInfo = new Page<>(); pageInfo.setTotalCount(0); pageInfo.setPageItems(new ArrayList<>()); } return pageInfo; } catch (CannotGetJdbcConnectionException e) { LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e); throw e; } }
@Test void testGetPermissions() { Page<PermissionInfo> role = externalPermissionPersistService.getPermissions("role", 1, 10); assertNotNull(role); }
@Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) { double priority = edgeToPriorityMapping.get(edgeState, reverse); if (priority == 0) return Double.POSITIVE_INFINITY; final double distance = edgeState.getDistance(); double seconds = calcSeconds(distance, edgeState, reverse); if (Double.isInfinite(seconds)) return Double.POSITIVE_INFINITY; // add penalty at start/stop/via points if (edgeState.get(EdgeIteratorState.UNFAVORED_EDGE)) seconds += headingPenaltySeconds; double distanceCosts = distance * distanceInfluence; if (Double.isInfinite(distanceCosts)) return Double.POSITIVE_INFINITY; return seconds / priority + distanceCosts; }
@Test public void speedOnly() { // 50km/h -> 72s per km, 100km/h -> 36s per km EdgeIteratorState edge = graph.edge(0, 1).setDistance(1000).set(avSpeedEnc, 50, 100); CustomModel customModel = createSpeedCustomModel(avSpeedEnc) .setDistanceInfluence(0d); Weighting weighting = createWeighting(customModel); assertEquals(72, weighting.calcEdgeWeight(edge, false), 1.e-6); assertEquals(36, weighting.calcEdgeWeight(edge, true), 1.e-6); }
public static ParseResult parse(String text) { Map<String, String> localProperties = new HashMap<>(); String intpText = ""; String scriptText = null; Matcher matcher = REPL_PATTERN.matcher(text); if (matcher.find()) { String headingSpace = matcher.group(1); intpText = matcher.group(2); int startPos = headingSpace.length() + intpText.length() + 1; if (startPos < text.length() && text.charAt(startPos) == '(') { startPos = parseLocalProperties(text, startPos, localProperties); } scriptText = text.substring(startPos); } else { intpText = ""; scriptText = text; } return new ParseResult(intpText, removeLeadingWhiteSpaces(scriptText), localProperties); }
@Test void testCassandra() { ParagraphTextParser.ParseResult parseResult = ParagraphTextParser.parse( "%cassandra(locale=ru_RU, timeFormat=\"E, d MMM yy\", floatPrecision = 5, output=cql)\n" + "select * from system_auth.roles;"); assertEquals("cassandra", parseResult.getIntpText()); assertEquals(4, parseResult.getLocalProperties().size()); assertEquals("E, d MMM yy", parseResult.getLocalProperties().get("timeFormat")); assertEquals("\nselect * from system_auth.roles;", parseResult.getScriptText()); }
public static void refreshTargetServiceInstances(String serviceName) { refreshTargetServiceInstances(serviceName, null); }
@Test public void refreshTargetServiceInstances() { try (final MockedStatic<PluginConfigManager> pluginConfigManagerMockedStatic = Mockito.mockStatic(PluginConfigManager.class);){ pluginConfigManagerMockedStatic.when(() -> PluginConfigManager.getPluginConfig(GraceConfig.class)) .thenReturn(new GraceConfig()); testRibbon(); testSpringLb(); } }
public static Class<?> getLiteral(String className, String literal) { LiteralAnalyzer analyzer = ANALYZERS.get( className ); Class result = null; if ( analyzer != null ) { analyzer.validate( literal ); result = analyzer.getLiteral(); } return result; }
@Test public void testCharLiteralFromJLS() { assertThat( getLiteral( char.class.getCanonicalName(), "'a'" ) ).isNotNull(); assertThat( getLiteral( char.class.getCanonicalName(), "'%'" ) ).isNotNull(); assertThat( getLiteral( char.class.getCanonicalName(), "'\t'" ) ).isNotNull(); assertThat( getLiteral( char.class.getCanonicalName(), "'\\'" ) ).isNotNull(); assertThat( getLiteral( char.class.getCanonicalName(), "'\''" ) ).isNotNull(); assertThat( getLiteral( char.class.getCanonicalName(), "'\u03a9'" ) ).isNotNull(); assertThat( getLiteral( char.class.getCanonicalName(), "'\uFFFF'" ) ).isNotNull(); assertThat( getLiteral( char.class.getCanonicalName(), "'\177'" ) ).isNotNull(); assertThat( getLiteral( char.class.getCanonicalName(), "'Ω'" ) ).isNotNull(); }
public final Logger getLogger(final Class<?> clazz) { return getLogger(clazz.getName()); }
@Test public void testStatusWithUnconfiguredContext() { Logger logger = lc.getLogger(LoggerContextTest.class); for (int i = 0; i < 3; i++) { logger.debug("test"); } logger = lc.getLogger("x.y.z"); for (int i = 0; i < 3; i++) { logger.debug("test"); } StatusManager sm = lc.getStatusManager(); assertTrue(sm.getCount() == 1, "StatusManager has recieved too many messages"); }
@GetMapping("/apps") public List<AppDTO> find(@RequestParam(value = "name", required = false) String name, Pageable pageable) { List<App> app = null; if (StringUtils.isBlank(name)) { app = appService.findAll(pageable); } else { app = appService.findByName(name); } return BeanUtils.batchTransform(AppDTO.class, app); }
@Test @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testFind() { AppDTO dto = generateSampleDTOData(); App app = BeanUtils.transform(App.class, dto); app = appRepository.save(app); AppDTO result = restTemplate.getForObject(getBaseAppUrl() + dto.getAppId(), AppDTO.class); Assert.assertEquals(dto.getAppId(), result.getAppId()); Assert.assertEquals(dto.getName(), result.getName()); }
@Override public DefaultLogicalVertex getProducer() { return vertexRetriever.apply(intermediateDataSet.getProducer().getID()); }
@Test public void testGetProducer() { assertVertexInfoEquals(producerVertex, logicalResult.getProducer()); }
public static Class<?> getLiteral(String className, String literal) { LiteralAnalyzer analyzer = ANALYZERS.get( className ); Class result = null; if ( analyzer != null ) { analyzer.validate( literal ); result = analyzer.getLiteral(); } return result; }
@Test public void testUnderscorePlacement1() { assertThat( getLiteral( long.class.getCanonicalName(), "1234_5678_9012_3456L" ) ).isNotNull(); assertThat( getLiteral( long.class.getCanonicalName(), "999_99_9999L" ) ).isNotNull(); assertThat( getLiteral( float.class.getCanonicalName(), "3.14_15F" ) ).isNotNull(); assertThat( getLiteral( long.class.getCanonicalName(), "0xFF_EC_DE_5EL" ) ).isNotNull(); assertThat( getLiteral( long.class.getCanonicalName(), "0xCAFE_BABEL" ) ).isNotNull(); assertThat( getLiteral( long.class.getCanonicalName(), "0x7fff_ffff_ffff_ffffL" ) ).isNotNull(); assertThat( getLiteral( byte.class.getCanonicalName(), "0b0010_0101" ) ).isNotNull(); assertThat( getLiteral( long.class.getCanonicalName(), "0b11010010_01101001_10010100_10010010L" ) ) .isNotNull(); }
public static <T> CompressedSerializedValue<T> fromBytes(byte[] compressedSerializedData) { return new CompressedSerializedValue<>(compressedSerializedData); }
@Test void testFromEmptyBytes() { assertThatThrownBy(() -> CompressedSerializedValue.fromBytes(new byte[0])) .isInstanceOf(IllegalArgumentException.class); }
@Override public short getTypeCode() { return MessageType.TYPE_SEATA_MERGE; }
@Test public void getTypeCode() { MergedWarpMessage mergedWarpMessage = new MergedWarpMessage(); assertThat(mergedWarpMessage.getTypeCode()).isEqualTo(MessageType.TYPE_SEATA_MERGE); }
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry existingEntry: existingAcl) { AclEntry aclSpecEntry = aclSpec.findByKey(existingEntry); if (aclSpecEntry != null) { foundAclSpecEntries.add(aclSpecEntry); scopeDirty.add(aclSpecEntry.getScope()); if (aclSpecEntry.getType() == MASK) { providedMask.put(aclSpecEntry.getScope(), aclSpecEntry); maskDirty.add(aclSpecEntry.getScope()); } else { aclBuilder.add(aclSpecEntry); } } else { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } // ACL spec entries that were not replacements are new additions. for (AclEntry newEntry: aclSpec) { if (Collections.binarySearch(foundAclSpecEntries, newEntry, ACL_ENTRY_COMPARATOR) < 0) { scopeDirty.add(newEntry.getScope()); if (newEntry.getType() == MASK) { providedMask.put(newEntry.getScope(), newEntry); maskDirty.add(newEntry.getScope()); } else { aclBuilder.add(newEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); }
@Test public void testMergeAclEntriesEmptyAclSpec() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, USER, "bruce", READ_WRITE)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, MASK, ALL)) .add(aclEntry(ACCESS, OTHER, READ)) .add(aclEntry(DEFAULT, USER, ALL)) .add(aclEntry(DEFAULT, USER, "bruce", READ_WRITE)) .add(aclEntry(DEFAULT, GROUP, READ)) .add(aclEntry(DEFAULT, MASK, ALL)) .add(aclEntry(DEFAULT, OTHER, READ)) .build(); List<AclEntry> aclSpec = Lists.newArrayList(); assertEquals(existing, mergeAclEntries(existing, aclSpec)); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final CloudBlobContainer container = session.getClient().getContainerReference(containerService.getContainer(directory).getName()); final AttributedList<Path> children = new AttributedList<>(); ResultContinuation token = null; ResultSegment<ListBlobItem> result; String prefix = StringUtils.EMPTY; if(!containerService.isContainer(directory)) { prefix = containerService.getKey(directory); if(!prefix.endsWith(String.valueOf(Path.DELIMITER))) { prefix += Path.DELIMITER; } } boolean hasDirectoryPlaceholder = containerService.isContainer(directory); do { final BlobRequestOptions options = new BlobRequestOptions(); result = container.listBlobsSegmented(prefix, false, EnumSet.noneOf(BlobListingDetails.class), new HostPreferences(session.getHost()).getInteger("azure.listing.chunksize"), token, options, context); for(ListBlobItem object : result.getResults()) { if(new SimplePathPredicate(new Path(object.getUri().getPath(), EnumSet.of(Path.Type.directory))).test(directory)) { if(log.isDebugEnabled()) { log.debug(String.format("Skip placeholder key %s", object)); } hasDirectoryPlaceholder = true; continue; } final PathAttributes attributes = new PathAttributes(); if(object instanceof CloudBlob) { final CloudBlob blob = (CloudBlob) object; attributes.setSize(blob.getProperties().getLength()); attributes.setModificationDate(blob.getProperties().getLastModified().getTime()); attributes.setETag(blob.getProperties().getEtag()); if(StringUtils.isNotBlank(blob.getProperties().getContentMD5())) { attributes.setChecksum(Checksum.parse(Hex.encodeHexString(Base64.decodeBase64(blob.getProperties().getContentMD5())))); } } // A directory is designated by a delimiter character. final EnumSet<Path.Type> types = object instanceof CloudBlobDirectory ? EnumSet.of(Path.Type.directory, Path.Type.placeholder) : EnumSet.of(Path.Type.file); final Path child = new Path(directory, PathNormalizer.name(object.getUri().getPath()), types, attributes); children.add(child); } listener.chunk(directory, children); token = result.getContinuationToken(); } while(result.getHasMoreResults()); if(!hasDirectoryPlaceholder && children.isEmpty()) { if(log.isWarnEnabled()) { log.warn(String.format("No placeholder found for directory %s", directory)); } throw new NotfoundException(directory.getAbsolute()); } return children; } catch(StorageException e) { throw new AzureExceptionMappingService().map("Listing directory {0} failed", e, directory); } catch(URISyntaxException e) { throw new NotfoundException(e.getMessage(), e); } }
@Test public void testListLexicographicSortOrderAssumption() throws Exception { final Path container = new Path("cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final Path directory = new AzureDirectoryFeature(session, null).mkdir( new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus()); assertTrue(new AzureObjectListService(session, null).list(directory, new DisabledListProgressListener()).isEmpty()); final List<String> files = Arrays.asList( "Z", "aa", "0a", "a", "AAA", "B", "~$a", ".c" ); for(String f : files) { new AzureTouchFeature(session, null).touch(new Path(directory, f, EnumSet.of(Path.Type.file)), new TransferStatus()); } files.sort(session.getHost().getProtocol().getListComparator()); final AttributedList<Path> list = new AzureObjectListService(session, null).list(directory, new IndexedListProgressListener() { @Override public void message(final String message) { // } @Override public void visit(final AttributedList<Path> list, final int index, final Path file) { assertEquals(files.get(index), file.getName()); } }); for(int i = 0; i < list.size(); i++) { assertEquals(files.get(i), list.get(i).getName()); new AzureDeleteFeature(session, null).delete(Collections.singletonList(list.get(i)), new DisabledLoginCallback(), new Delete.DisabledCallback()); } new AzureDeleteFeature(session, null).delete(Collections.singletonList(directory), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public static String normalizeUri(String uri) throws URISyntaxException { // try to parse using the simpler and faster Camel URI parser String[] parts = CamelURIParser.fastParseUri(uri); if (parts != null) { // we optimized specially if an empty array is returned if (parts == URI_ALREADY_NORMALIZED) { return uri; } // use the faster and more simple normalizer return doFastNormalizeUri(parts); } else { // use the legacy normalizer as the uri is complex and may have unsafe URL characters return doComplexNormalizeUri(uri); } }
@Test public void testNormalizeEndpointUriNoParam() throws Exception { String out1 = URISupport.normalizeUri("direct:foo"); String out2 = URISupport.normalizeUri("direct:foo"); assertEquals(out1, out2); out1 = URISupport.normalizeUri("direct://foo"); out2 = URISupport.normalizeUri("direct://foo"); assertEquals(out1, out2); out1 = URISupport.normalizeUri("direct:foo"); out2 = URISupport.normalizeUri("direct://foo"); assertEquals(out1, out2); out1 = URISupport.normalizeUri("direct://foo"); out2 = URISupport.normalizeUri("direct:foo"); assertEquals(out1, out2); out1 = URISupport.normalizeUri("direct://foo"); out2 = URISupport.normalizeUri("direct:bar"); assertNotSame(out1, out2); }
Flux<Post> allPosts() { return client.get() .uri("/posts") .accept(MediaType.APPLICATION_JSON) .exchangeToFlux(response -> response.bodyToFlux(Post.class)); }
@SneakyThrows @Test public void testGetAllPosts() { var data = List.of( new Post(UUID.randomUUID(), "title1", "content1", Status.DRAFT, LocalDateTime.now()), new Post(UUID.randomUUID(), "title2", "content2", Status.PUBLISHED, LocalDateTime.now()) ); stubFor(get("/posts") .willReturn( aResponse() .withHeader("Content-Type", "application/json") .withResponseBody(Body.fromJsonBytes(Json.toByteArray(data))) ) ); postClient.allPosts() .as(StepVerifier::create) .expectNextCount(2) .verifyComplete(); verify(getRequestedFor(urlEqualTo("/posts")) .withHeader("Accept", equalTo("application/json"))); }
@Override public Boolean update(List<ModifyRequest> modifyRequests, BiConsumer<Boolean, Throwable> consumer) { return update(transactionTemplate, jdbcTemplate, modifyRequests, consumer); }
@Test void testUpdate3() { List<ModifyRequest> modifyRequests = new ArrayList<>(); ModifyRequest modifyRequest1 = new ModifyRequest(); String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;"; modifyRequest1.setSql(sql); Object[] args = new Object[] {1}; modifyRequest1.setArgs(args); modifyRequests.add(modifyRequest1); when(transactionTemplate.execute(any(TransactionCallback.class))).thenReturn(true); assertTrue(operate.update(transactionTemplate, jdbcTemplate, modifyRequests)); }
@PublicAPI(usage = ACCESS) public JavaClasses importClasses(Class<?>... classes) { return importClasses(Arrays.asList(classes)); }
@Test public void imports_enclosing_method_of_local_class() throws ClassNotFoundException { @SuppressWarnings("unused") class ClassCreatingLocalClassInMethod { void someMethod() { class SomeLocalClass { } } } String localClassName = ClassCreatingLocalClassInMethod.class.getName() + "$1SomeLocalClass"; JavaClasses classes = new ClassFileImporter().importClasses( ClassCreatingLocalClassInMethod.class, Class.forName(localClassName) ); JavaClass enclosingClass = classes.get(ClassCreatingLocalClassInMethod.class); JavaClass localClass = classes.get(localClassName); assertThat(localClass.getEnclosingCodeUnit()).contains(enclosingClass.getMethod("someMethod")); assertThat(localClass.getEnclosingClass()).contains(enclosingClass); }
public final <KIn, VIn, KOut, VOut> void addProcessor(final String name, final ProcessorSupplier<KIn, VIn, KOut, VOut> supplier, final String... predecessorNames) { Objects.requireNonNull(name, "name must not be null"); Objects.requireNonNull(supplier, "supplier must not be null"); Objects.requireNonNull(predecessorNames, "predecessor names must not be null"); ApiUtils.checkSupplier(supplier); if (nodeFactories.containsKey(name)) { throw new TopologyException("Processor " + name + " is already added."); } if (predecessorNames.length == 0) { throw new TopologyException("Processor " + name + " must have at least one parent"); } for (final String predecessor : predecessorNames) { Objects.requireNonNull(predecessor, "predecessor name must not be null"); if (predecessor.equals(name)) { throw new TopologyException("Processor " + name + " cannot be a predecessor of itself."); } if (!nodeFactories.containsKey(predecessor)) { throw new TopologyException("Predecessor processor " + predecessor + " is not added yet for " + name); } } nodeFactories.put(name, new ProcessorNodeFactory<>(name, predecessorNames, supplier)); nodeGrouper.add(name); nodeGrouper.unite(name, predecessorNames); nodeGroups = null; }
@Test public void testAddProcessorWithBadSupplier() { final Processor<Object, Object, Object, Object> processor = new MockApiProcessor<>(); final IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> builder.addProcessor("processor", () -> processor, (String) null) ); assertThat(exception.getMessage(), containsString("#get() must return a new object each time it is called.")); }
Converter<E> compile() { head = tail = null; for (Node n = top; n != null; n = n.next) { switch (n.type) { case Node.LITERAL: addToList(new LiteralConverter<E>((String) n.getValue())); break; case Node.COMPOSITE_KEYWORD: CompositeNode cn = (CompositeNode) n; CompositeConverter<E> compositeConverter = createCompositeConverter(cn); if(compositeConverter == null) { addError("Failed to create converter for [%"+cn.getValue()+"] keyword"); addToList(new LiteralConverter<E>("%PARSER_ERROR["+cn.getValue()+"]")); break; } compositeConverter.setFormattingInfo(cn.getFormatInfo()); compositeConverter.setOptionList(cn.getOptions()); Compiler<E> childCompiler = new Compiler<E>(cn.getChildNode(), converterMap); childCompiler.setContext(context); Converter<E> childConverter = childCompiler.compile(); compositeConverter.setChildConverter(childConverter); addToList(compositeConverter); break; case Node.SIMPLE_KEYWORD: SimpleKeywordNode kn = (SimpleKeywordNode) n; DynamicConverter<E> dynaConverter = createConverter(kn); if (dynaConverter != null) { dynaConverter.setFormattingInfo(kn.getFormatInfo()); dynaConverter.setOptionList(kn.getOptions()); addToList(dynaConverter); } else { // if the appropriate dynaconverter cannot be found, then replace // it with a dummy LiteralConverter indicating an error. Converter<E> errConveter = new LiteralConverter<E>("%PARSER_ERROR[" + kn.getValue() + "]"); addStatus(new ErrorStatus("[" + kn.getValue() + "] is not a valid conversion word", this)); addToList(errConveter); } } } return head; }
@Test public void testUnknownWord() throws Exception { Parser<Object> p = new Parser<Object>("%unknown"); p.setContext(context); Node t = p.parse(); p.compile(t, converterMap); StatusChecker checker = new StatusChecker(context.getStatusManager()); checker .assertContainsMatch("\\[unknown] is not a valid conversion word"); }
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefine.isNullable()) .defaultValue(typeDefine.getDefaultValue()) .comment(typeDefine.getComment()); String hanaType = typeDefine.getDataType().toUpperCase(); if (typeDefine.getColumnType().endsWith(" ARRAY")) { typeDefine.setColumnType(typeDefine.getColumnType().replace(" ARRAY", "")); typeDefine.setDataType(removeColumnSizeIfNeed(typeDefine.getColumnType())); Column arrayColumn = convert(typeDefine); SeaTunnelDataType<?> newType; switch (arrayColumn.getDataType().getSqlType()) { case STRING: newType = ArrayType.STRING_ARRAY_TYPE; break; case BOOLEAN: newType = ArrayType.BOOLEAN_ARRAY_TYPE; break; case TINYINT: newType = ArrayType.BYTE_ARRAY_TYPE; break; case SMALLINT: newType = ArrayType.SHORT_ARRAY_TYPE; break; case INT: newType = ArrayType.INT_ARRAY_TYPE; break; case BIGINT: newType = ArrayType.LONG_ARRAY_TYPE; break; case FLOAT: newType = ArrayType.FLOAT_ARRAY_TYPE; break; case DOUBLE: newType = ArrayType.DOUBLE_ARRAY_TYPE; break; case DATE: newType = ArrayType.LOCAL_DATE_ARRAY_TYPE; break; case TIME: newType = ArrayType.LOCAL_TIME_ARRAY_TYPE; break; case TIMESTAMP: newType = ArrayType.LOCAL_DATE_TIME_ARRAY_TYPE; break; default: throw CommonError.unsupportedDataType( "SeaTunnel", arrayColumn.getDataType().getSqlType().toString(), typeDefine.getName()); } return new PhysicalColumn( arrayColumn.getName(), newType, arrayColumn.getColumnLength(), arrayColumn.getScale(), arrayColumn.isNullable(), arrayColumn.getDefaultValue(), arrayColumn.getComment(), arrayColumn.getSourceType() + " ARRAY", arrayColumn.getOptions()); } switch (hanaType) { case HANA_BINARY: case HANA_VARBINARY: builder.dataType(PrimitiveByteArrayType.INSTANCE); if (typeDefine.getLength() == null || typeDefine.getLength() == 0) { builder.columnLength(MAX_BINARY_LENGTH); } else { builder.columnLength(typeDefine.getLength()); } break; case HANA_BOOLEAN: builder.dataType(BasicType.BOOLEAN_TYPE); break; case HANA_VARCHAR: case HANA_ALPHANUM: case HANA_CLOB: case HANA_NCLOB: case HANA_TEXT: case HANA_BINTEXT: builder.dataType(BasicType.STRING_TYPE); if (typeDefine.getLength() == null || typeDefine.getLength() == 0) { builder.columnLength(MAX_LOB_LENGTH); } else { builder.columnLength(typeDefine.getLength()); } break; case HANA_NVARCHAR: case HANA_SHORTTEXT: builder.dataType(BasicType.STRING_TYPE); builder.columnLength(TypeDefineUtils.charTo4ByteLength(typeDefine.getLength())); break; case HANA_DATE: builder.dataType(LocalTimeType.LOCAL_DATE_TYPE); break; case HANA_TIME: builder.dataType(LocalTimeType.LOCAL_TIME_TYPE); builder.scale(0); break; case HANA_SECONDDATE: builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE); builder.scale(0); break; case HANA_TIMESTAMP: builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE); if (typeDefine.getScale() == null) { builder.scale(TIMESTAMP_DEFAULT_SCALE); } else { builder.scale(typeDefine.getScale()); } break; case HANA_BLOB: builder.dataType(PrimitiveByteArrayType.INSTANCE); builder.columnLength(typeDefine.getLength()); break; case HANA_TINYINT: case HANA_SMALLINT: builder.dataType(BasicType.SHORT_TYPE); break; case HANA_INTEGER: builder.dataType(BasicType.INT_TYPE); break; case HANA_BIGINT: builder.dataType(BasicType.LONG_TYPE); break; case HANA_DECIMAL: Integer scale = typeDefine.getScale(); long precision = typeDefine.getLength() != null ? typeDefine.getLength().intValue() : MAX_PRECISION - 4; if (scale == null) { builder.dataType(new DecimalType((int) precision, MAX_SCALE)); builder.columnLength(precision); builder.scale(MAX_SCALE); } else if (scale < 0) { int newPrecision = (int) (precision - scale); if (newPrecision == 1) { builder.dataType(BasicType.SHORT_TYPE); } else if (newPrecision <= 9) { builder.dataType(BasicType.INT_TYPE); } else if (newPrecision <= 18) { builder.dataType(BasicType.LONG_TYPE); } else if (newPrecision < 38) { builder.dataType(new DecimalType(newPrecision, 0)); builder.columnLength((long) newPrecision); } else { builder.dataType(new DecimalType(DEFAULT_PRECISION, 0)); builder.columnLength((long) DEFAULT_PRECISION); } } else { builder.dataType(new DecimalType((int) precision, scale)); builder.columnLength(precision); builder.scale(scale); } break; case HANA_SMALLDECIMAL: if (typeDefine.getPrecision() == null) { builder.dataType(new DecimalType(DEFAULT_PRECISION, MAX_SMALL_DECIMAL_SCALE)); builder.columnLength((long) DEFAULT_PRECISION); builder.scale(MAX_SMALL_DECIMAL_SCALE); } else { builder.dataType( new DecimalType( typeDefine.getPrecision().intValue(), MAX_SMALL_DECIMAL_SCALE)); builder.columnLength(typeDefine.getPrecision()); builder.scale(MAX_SMALL_DECIMAL_SCALE); } break; case HANA_REAL: builder.dataType(BasicType.FLOAT_TYPE); break; case HANA_DOUBLE: builder.dataType(BasicType.DOUBLE_TYPE); break; case HANA_ST_POINT: case HANA_ST_GEOMETRY: builder.dataType(PrimitiveByteArrayType.INSTANCE); break; default: throw CommonError.convertToSeaTunnelTypeError( DatabaseIdentifier.SAP_HANA, hanaType, typeDefine.getName()); } return builder.build(); }
@Test public void testConvertChar() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("VARCHAR") .dataType("VARCHAR") .length(1L) .build(); Column column = SapHanaTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), column.getName()); Assertions.assertEquals(BasicType.STRING_TYPE, column.getDataType()); Assertions.assertEquals(typeDefine.getLength(), column.getColumnLength()); Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType()); typeDefine = BasicTypeDefine.builder() .name("test") .columnType("NVARCHAR") .dataType("NVARCHAR") .length(1L) .build(); column = SapHanaTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), column.getName()); Assertions.assertEquals(BasicType.STRING_TYPE, column.getDataType()); Assertions.assertEquals(4, column.getColumnLength()); Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType()); typeDefine = BasicTypeDefine.builder() .name("test") .columnType("ALPHANUM") .dataType("ALPHANUM") .length(1L) .build(); column = SapHanaTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), column.getName()); Assertions.assertEquals(BasicType.STRING_TYPE, column.getDataType()); Assertions.assertEquals(typeDefine.getLength(), column.getColumnLength()); Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType()); typeDefine = BasicTypeDefine.builder() .name("test") .columnType("SHORTTEXT") .dataType("SHORTTEXT") .length(1L) .build(); column = SapHanaTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), column.getName()); Assertions.assertEquals(BasicType.STRING_TYPE, column.getDataType()); Assertions.assertEquals(typeDefine.getLength() * 4, column.getColumnLength()); Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType()); }
public Encoding encode(String text) { return encode(text, Language.UNKNOWN); }
@Test void pads_to_max_length() throws IOException { var builder = new HuggingFaceTokenizer.Builder() .setTruncation(true) .addDefaultModel(decompressModelFile(tmp, "bert-base-uncased")) .addSpecialTokens(true).setMaxLength(32); String input = "what was the impact of the manhattan project"; try (var tokenizerWithDefaultPadding = builder.build(); var tokenizerWithPaddingDisabled = builder.setPadding(false).build(); var tokenizerWithPaddingEnabled = builder.setPadding(true).build()) { assertMaxLengthRespected(10, tokenizerWithDefaultPadding.encode(input)); assertMaxLengthRespected(10, tokenizerWithPaddingDisabled.encode(input)); assertMaxLengthRespected(32, tokenizerWithPaddingEnabled.encode(input)); } }
@Override public void dropPartition(String dbName, String tableName, List<String> partValues, boolean deleteData) { client.dropPartition(dbName, tableName, partValues, deleteData); }
@Test public void testDropPartition() { HiveMetaClient client = new MockedHiveMetaClient(); HiveMetastore metastore = new HiveMetastore(client, "hive_catalog", MetastoreType.HMS); metastore.dropPartition("db", "table", Lists.newArrayList("k1=1"), false); }
@Override public RLESparseResourceAllocation getAvailableResourceOverTime(String user, ReservationId oldId, long start, long end, long period) throws PlanningException { readLock.lock(); try { // for non-periodic return simple available resources if (period == 0) { // create RLE of totCapacity TreeMap<Long, Resource> totAvailable = new TreeMap<Long, Resource>(); totAvailable.put(start, Resources.clone(totalCapacity)); RLESparseResourceAllocation totRLEAvail = new RLESparseResourceAllocation(totAvailable, resCalc); // subtract used from available RLESparseResourceAllocation netAvailable; netAvailable = RLESparseResourceAllocation.merge(resCalc, Resources.clone(totalCapacity), totRLEAvail, rleSparseVector, RLEOperator.subtractTestNonNegative, start, end); // remove periodic component netAvailable = RLESparseResourceAllocation.merge(resCalc, Resources.clone(totalCapacity), netAvailable, periodicRle, RLEOperator.subtractTestNonNegative, start, end); // add back in old reservation used resources if any ReservationAllocation old = reservationTable.get(oldId); if (old != null) { RLESparseResourceAllocation addBackPrevious = old.getResourcesOverTime(start, end); netAvailable = RLESparseResourceAllocation.merge(resCalc, Resources.clone(totalCapacity), netAvailable, addBackPrevious, RLEOperator.add, start, end); } // lower it if this is needed by the sharing policy netAvailable = getSharingPolicy().availableResources(netAvailable, this, user, oldId, start, end); return netAvailable; } else { if (periodicRle.getTimePeriod() % period != 0) { throw new PlanningException("The reservation periodicity (" + period + ") must be" + " an exact divider of the system maxPeriod (" + periodicRle.getTimePeriod() + ")"); } if (period < (end - start)) { throw new PlanningException( "Invalid input: (end - start) = (" + end + " - " + start + ") = " + (end - start) + " > period = " + period); } // find the minimum resources available among all the instances that fit // in the LCM long numInstInLCM = periodicRle.getTimePeriod() / period; RLESparseResourceAllocation minOverLCM = getAvailableResourceOverTime(user, oldId, start, end, 0); for (int i = 1; i < numInstInLCM; i++) { long rStart = start + i * period; long rEnd = end + i * period; // recursive invocation of non-periodic range (to pick raw-info) RLESparseResourceAllocation snapShot = getAvailableResourceOverTime(user, oldId, rStart, rEnd, 0); // time-align on start snapShot.shift(-(i * period)); // pick the minimum amount of resources in each time interval minOverLCM = RLESparseResourceAllocation.merge(resCalc, getTotalCapacity(), minOverLCM, snapShot, RLEOperator.min, start, end); } return minOverLCM; } } finally { readLock.unlock(); } }
@Test(expected = PlanningException.class) public void testOutOfRange() throws PlanningException { maxPeriodicity = 100; Plan plan = new InMemoryPlan(queueMetrics, policy, agent, totalCapacity, 1L, resCalc, minAlloc, maxAlloc, planName, replanner, true, maxPeriodicity, context, new UTCClock()); // we expect the plan to complaint as the range 330-150 > 50 RLESparseResourceAllocation availableBefore = plan.getAvailableResourceOverTime(user, null, 150, 330, 50); }
@Override public V remove(Object key) { return execute(key, this::removeKey, null /* default value */); }
@Test public void testRemove() { PartitionMap<String> map = PartitionMap.create(SPECS); map.put(BY_DATA_SPEC.specId(), Row.of("aaa"), "v1"); map.put(BY_DATA_SPEC.specId(), Row.of("bbb"), "v2"); map.removeKey(BY_DATA_SPEC.specId(), Row.of("aaa")); assertThat(map).doesNotContainKey(Pair.of(BY_DATA_SPEC.specId(), Row.of("aaa"))); assertThat(map.get(BY_DATA_SPEC.specId(), Row.of("aaa"))).isNull(); assertThat(map).containsKey(Pair.of(BY_DATA_SPEC.specId(), Row.of("bbb"))); assertThat(map.get(BY_DATA_SPEC.specId(), Row.of("bbb"))).isEqualTo("v2"); }
@Override protected void updateData(SummaryInfo info, Sample sample) { // Initialize overall data if they don't exist SummaryInfo overallInfo = getOverallInfo(); Long overallData = overallInfo.getData(); if (overallData == null) { overallData = ZERO; } overallInfo.setData(overallData + 1); // Process only failed samples if (!sample.getSuccess()) { errorCount++; Long data = info.getData(); if (data == null) { data = ZERO; } info.setData(data + 1); } }
@Test public void testErrorSampleCounter() { ErrorsSummaryConsumer consumer = new ErrorsSummaryConsumer(); Sample sample = createSample(false); AbstractSummaryConsumer<Long>.SummaryInfo info = consumer.new SummaryInfo(false); assertNull(info.getData()); consumer.updateData(info, sample); assertEquals(Long.valueOf(1), info.getData()); consumer.updateData(info, sample); assertEquals(Long.valueOf(2), info.getData()); }
@VisibleForTesting public Path getAllocationFile(Configuration conf) throws UnsupportedFileSystemException { String allocFilePath = conf.get(FairSchedulerConfiguration.ALLOCATION_FILE, FairSchedulerConfiguration.DEFAULT_ALLOCATION_FILE); Path allocPath = new Path(allocFilePath); String allocPathScheme = allocPath.toUri().getScheme(); if(allocPathScheme != null && !allocPathScheme.matches(SUPPORTED_FS_REGEX)){ throw new UnsupportedFileSystemException("Allocation file " + allocFilePath + " uses an unsupported filesystem"); } else if (!allocPath.isAbsolute()) { URL url = Thread.currentThread().getContextClassLoader() .getResource(allocFilePath); if (url == null) { LOG.warn(allocFilePath + " not found on the classpath."); allocPath = null; } else if (!url.getProtocol().equalsIgnoreCase("file")) { throw new RuntimeException("Allocation file " + url + " found on the classpath is not on the local filesystem."); } else { allocPath = new Path(url.getProtocol(), null, url.getPath()); } } else if (allocPath.isAbsoluteAndSchemeAuthorityNull()){ allocPath = new Path("file", null, allocFilePath); } return allocPath; }
@Test public void testGetAllocationFileFromClasspath() { try { FileSystem fs = FileSystem.get(conf); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, TEST_FAIRSCHED_XML); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(scheduler); Path allocationFile = allocLoader.getAllocationFile(conf); assertEquals(TEST_FAIRSCHED_XML, allocationFile.getName()); assertTrue(fs.exists(allocationFile)); } catch (IOException e) { fail("Unable to access allocation file from classpath: " + e); } }
public Plan validateReservationSubmissionRequest( ReservationSystem reservationSystem, ReservationSubmissionRequest request, ReservationId reservationId) throws YarnException { String message; if (reservationId == null) { message = "Reservation id cannot be null. Please try again specifying " + " a valid reservation id by creating a new reservation id."; throw RPCUtil.getRemoteException(message); } // Check if it is a managed queue String queue = request.getQueue(); Plan plan = getPlanFromQueue(reservationSystem, queue, AuditConstants.SUBMIT_RESERVATION_REQUEST); validateReservationDefinition(reservationId, request.getReservationDefinition(), plan, AuditConstants.SUBMIT_RESERVATION_REQUEST); return plan; }
@Test public void testSubmitReservationInvalidRR() { ReservationSubmissionRequest request = createSimpleReservationSubmissionRequest(0, 0, 1, 5, 3); Plan plan = null; try { plan = rrValidator.validateReservationSubmissionRequest(rSystem, request, ReservationSystemTestUtil.getNewReservationId()); Assert.fail(); } catch (YarnException e) { Assert.assertNull(plan); String message = e.getMessage(); Assert.assertTrue(message .startsWith("No resources have been specified to reserve")); LOG.info(message); } }
static boolean willCreateNewThreadPool(CamelContext camelContext, DynamicRouterConfiguration cfg, boolean useDefault) { ObjectHelper.notNull(camelContext.getExecutorServiceManager(), ESM_NAME, camelContext); return Optional.ofNullable(cfg.getExecutorServiceBean()) .map(esb -> false) .or(() -> Optional.ofNullable(cfg.getExecutorService()) .map(es -> lookupByNameAndType(camelContext, es, ExecutorService.class).isEmpty())) .orElse(useDefault); }
@Test void testWillCreateNewThreadPoolWithExecutorServiceBean() { when(camelContext.getExecutorServiceManager()).thenReturn(manager); when(mockConfig.getExecutorServiceBean()).thenReturn(existingThreadPool); assertFalse(DynamicRouterRecipientListHelper.willCreateNewThreadPool(camelContext, mockConfig, true)); }
@Override public void seek(long position) throws IOException { throw new IOException(getClass().getName() + ".seek isn't supported."); }
@Test void testSeekEOF() throws IOException { byte[] inputValues = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; ByteArrayInputStream bais = new ByteArrayInputStream(inputValues); try (NonSeekableRandomAccessReadInputStream randomAccessSource = new NonSeekableRandomAccessReadInputStream( bais)) { Assertions.assertThrows(IOException.class, () -> randomAccessSource.seek(3), "seek should have thrown an IOException"); } }
public String getRuntimeAndMaybeAddRuntime(final QueryId queryId, final Collection<String> sourceTopics, final KsqlConfig config) { if (idToRuntime.containsKey(queryId)) { return idToRuntime.get(queryId); } final List<String> possibleRuntimes = runtimesToSourceTopics.entrySet() .stream() .filter(t -> t.getValue().stream().noneMatch(sourceTopics::contains)) .map(Map.Entry::getKey) .collect(Collectors.toList()); final String runtime; if (possibleRuntimes.isEmpty()) { runtime = makeNewRuntime(config); } else { runtime = possibleRuntimes.get(Math.abs(queryId.hashCode() % possibleRuntimes.size())); } runtimesToSourceTopics.get(runtime).addAll(sourceTopics); idToRuntime.put(queryId, runtime); log.info("Assigning query {} to runtime {}", queryId, runtime); return runtime; }
@Test public void shouldNotGetSameRuntimeForDifferentQueryIdAndSameSources() { final String runtime = runtimeAssignor.getRuntimeAndMaybeAddRuntime( query2, sourceTopics1, KSQL_CONFIG ); assertThat(runtime, not(equalTo(firstRuntime))); }
public String getName() { return name; }
@Test public void testGetName() { Model instance = new Model(); instance.setName(""); String expResult = ""; String result = instance.getName(); assertEquals(expResult, result); }
@Override public void setSpool(final Writer writer) { spool.ifPresent(ignored -> { throw new KsqlException("Cannot set two spools! Please issue SPOOL OFF."); }); spool = Optional.of(new Spool(writer, terminal.writer())); }
@Test public void shouldThrowOnTwoSpools() { // Given: final Writer spool = mock(Writer.class); terminal.setSpool(spool); // When: final KsqlException e = assertThrows( KsqlException.class, () -> terminal.setSpool(spool) ); // Then: assertThat(e.getMessage(), containsString("Cannot set two spools!")); }
@Override public void initialize(ServiceConfiguration config) throws IOException { this.allowedAudiences = validateAllowedAudiences(getConfigValueAsSet(config, ALLOWED_AUDIENCES)); this.roleClaim = getConfigValueAsString(config, ROLE_CLAIM, ROLE_CLAIM_DEFAULT); this.isRoleClaimNotSubject = !ROLE_CLAIM_DEFAULT.equals(roleClaim); this.acceptedTimeLeewaySeconds = getConfigValueAsInt(config, ACCEPTED_TIME_LEEWAY_SECONDS, ACCEPTED_TIME_LEEWAY_SECONDS_DEFAULT); boolean requireHttps = getConfigValueAsBoolean(config, REQUIRE_HTTPS, REQUIRE_HTTPS_DEFAULT); this.fallbackDiscoveryMode = FallbackDiscoveryMode.valueOf(getConfigValueAsString(config, FALLBACK_DISCOVERY_MODE, FallbackDiscoveryMode.DISABLED.name())); this.issuers = validateIssuers(getConfigValueAsSet(config, ALLOWED_TOKEN_ISSUERS), requireHttps, fallbackDiscoveryMode != FallbackDiscoveryMode.DISABLED); int connectionTimeout = getConfigValueAsInt(config, HTTP_CONNECTION_TIMEOUT_MILLIS, HTTP_CONNECTION_TIMEOUT_MILLIS_DEFAULT); int readTimeout = getConfigValueAsInt(config, HTTP_READ_TIMEOUT_MILLIS, HTTP_READ_TIMEOUT_MILLIS_DEFAULT); String trustCertsFilePath = getConfigValueAsString(config, ISSUER_TRUST_CERTS_FILE_PATH, null); SslContext sslContext = null; // When config is in the conf file but is empty, it defaults to the empty string, which is not meaningful and // should be ignored. if (StringUtils.isNotBlank(trustCertsFilePath)) { // Use default settings for everything but the trust store. sslContext = SslContextBuilder.forClient() .trustManager(new File(trustCertsFilePath)) .build(); } AsyncHttpClientConfig clientConfig = new DefaultAsyncHttpClientConfig.Builder() .setConnectTimeout(connectionTimeout) .setReadTimeout(readTimeout) .setSslContext(sslContext) .build(); httpClient = new DefaultAsyncHttpClient(clientConfig); k8sApiClient = fallbackDiscoveryMode != FallbackDiscoveryMode.DISABLED ? Config.defaultClient() : null; this.openIDProviderMetadataCache = new OpenIDProviderMetadataCache(config, httpClient, k8sApiClient); this.jwksCache = new JwksCache(config, httpClient, k8sApiClient); }
@Test public void ensureEmptyIssuersWithK8sTrustedIssuerEnabledPassesInitialization() throws Exception { @Cleanup AuthenticationProviderOpenID provider = new AuthenticationProviderOpenID(); Properties props = new Properties(); props.setProperty(AuthenticationProviderOpenID.ALLOWED_AUDIENCES, "my-audience"); props.setProperty(AuthenticationProviderOpenID.ALLOWED_TOKEN_ISSUERS, ""); props.setProperty(AuthenticationProviderOpenID.FALLBACK_DISCOVERY_MODE, "KUBERNETES_DISCOVER_TRUSTED_ISSUER"); ServiceConfiguration config = new ServiceConfiguration(); config.setProperties(props); provider.initialize(config); }
public long getEndOffset() { return getEndOffsetFromTopicPartition(commandConsumer, commandTopicPartition); }
@Test public void shouldGetEndOffsetCorrectly() { // Given: when(commandConsumer.endOffsets(any())) .thenReturn(Collections.singletonMap(TOPIC_PARTITION, 123L)); // When: final long endOff = commandTopic.getEndOffset(); // Then: assertThat(endOff, equalTo(123L)); verify(commandConsumer).endOffsets(Collections.singletonList(TOPIC_PARTITION)); }
@Override public Optional<ErrorResponse> filter(DiscFilterRequest request) { try { Optional<ResourceNameAndAction> resourceMapping = requestResourceMapper.getResourceNameAndAction(request); log.log(Level.FINE, () -> String.format("Resource mapping for '%s': %s", request, resourceMapping)); if (resourceMapping.isEmpty()) { incrementAcceptedMetrics(request, false, Optional.empty()); return Optional.empty(); } Result result = checkAccessAllowed(request, resourceMapping.get()); AuthorizationResult.Type resultType = result.zpeResult.type(); setAttribute(request, RESULT_ATTRIBUTE, resultType.name()); if (resultType == AuthorizationResult.Type.ALLOW) { populateRequestWithResult(request, result); incrementAcceptedMetrics(request, true, Optional.of(result)); return Optional.empty(); } log.log(Level.FINE, () -> String.format("Forbidden (403) for '%s': %s", request, resultType.name())); incrementRejectedMetrics(request, FORBIDDEN, resultType.name(), Optional.of(result)); return Optional.of(new ErrorResponse(FORBIDDEN, "Access forbidden: " + resultType.getDescription())); } catch (IllegalArgumentException e) { log.log(Level.FINE, () -> String.format("Unauthorized (401) for '%s': %s", request, e.getMessage())); incrementRejectedMetrics(request, UNAUTHORIZED, "Unauthorized", Optional.empty()); return Optional.of(new ErrorResponse(UNAUTHORIZED, e.getMessage())); } }
@Test void reports_metrics_for_rejected_requests() { MetricMock metric = new MetricMock(); AthenzAuthorizationFilter filter = createFilter(new DenyingZpe(), List.of(), metric, null); MockResponseHandler responseHandler = new MockResponseHandler(); DiscFilterRequest request = createRequest(null, ACCESS_TOKEN, USER_IDENTITY_CERTIFICATE); filter.filter(request, responseHandler); assertMetrics(metric, REJECTED_METRIC_NAME, Map.of("zpe-status", "DENY", "status-code", "403")); }
@Override public synchronized String toString() { return toStringHelper(ByteKeyRangeTracker.class) .add("range", range) .add("position", position) .toString(); }
@Test public void testToString() { ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); String expected = String.format("ByteKeyRangeTracker{range=%s, position=null}", INITIAL_RANGE); assertEquals(expected, tracker.toString()); tracker.tryReturnRecordAt(true, INITIAL_START_KEY); tracker.tryReturnRecordAt(true, INITIAL_MIDDLE_KEY); expected = String.format( "ByteKeyRangeTracker{range=%s, position=%s}", INITIAL_RANGE, INITIAL_MIDDLE_KEY); assertEquals(expected, tracker.toString()); }
@Override public void doAlarm(List<AlarmMessage> alarmMessages) throws Exception { Map<String, FeishuSettings> settingsMap = alarmRulesWatcher.getFeishuSettings(); if (settingsMap == null || settingsMap.isEmpty()) { return; } Map<String, List<AlarmMessage>> groupedMessages = groupMessagesByHook(alarmMessages); for (Map.Entry<String, List<AlarmMessage>> entry : groupedMessages.entrySet()) { var hookName = entry.getKey(); var messages = entry.getValue(); var setting = settingsMap.get(hookName); if (setting == null || CollectionUtils.isEmpty(setting.getWebhooks()) || CollectionUtils.isEmpty( messages)) { continue; } for (final var webHookUrl : setting.getWebhooks()) { for (final var alarmMessage : messages) { final var requestBody = getRequestBody(webHookUrl, alarmMessage, setting.getTextTemplate()); try { post(URI.create(webHookUrl.getUrl()), requestBody, Map.of()); } catch (Exception e) { log.error("Failed to send alarm message to Feishu: {}", webHookUrl.getUrl(), e); } } } } }
@Test public void testFeishuWebhookWithSign() throws Exception { CHECK_SIGN.set(true); List<FeishuSettings.WebHookUrl> webHooks = new ArrayList<>(); webHooks.add(new FeishuSettings.WebHookUrl(secret, "http://127.0.0.1:" + SERVER.httpPort() + "/feishuhook/receiveAlarm?token=dummy_token")); Rules rules = new Rules(); String template = "{\"msg_type\":\"text\",\"content\":{\"text\":\"Skywaling alarm: %s\"}}"; FeishuSettings setting1 = new FeishuSettings("setting1", AlarmHooksType.feishu, true); setting1.setWebhooks(webHooks); setting1.setTextTemplate(template); FeishuSettings setting2 = new FeishuSettings("setting2", AlarmHooksType.feishu, false); setting2.setWebhooks(webHooks); setting2.setTextTemplate(template); rules.getFeishuSettingsMap().put(setting1.getFormattedName(), setting1); rules.getFeishuSettingsMap().put(setting2.getFormattedName(), setting2); AlarmRulesWatcher alarmRulesWatcher = new AlarmRulesWatcher(rules, null); FeishuHookCallback feishuHookCallback = new FeishuHookCallback(alarmRulesWatcher); List<AlarmMessage> alarmMessages = new ArrayList<>(2); AlarmMessage alarmMessage = new AlarmMessage(); alarmMessage.setScopeId(DefaultScopeDefine.SERVICE); alarmMessage.setRuleName("service_resp_time_rule"); alarmMessage.setAlarmMessage("alarmMessage with [DefaultScopeDefine.All]"); alarmMessage.getHooks().add(setting1.getFormattedName()); alarmMessages.add(alarmMessage); AlarmMessage anotherAlarmMessage = new AlarmMessage(); anotherAlarmMessage.setRuleName("service_resp_time_rule_2"); anotherAlarmMessage.setScopeId(DefaultScopeDefine.ENDPOINT); anotherAlarmMessage.setAlarmMessage("anotherAlarmMessage with [DefaultScopeDefine.Endpoint]"); anotherAlarmMessage.getHooks().add(setting2.getFormattedName()); alarmMessages.add(anotherAlarmMessage); feishuHookCallback.doAlarm(alarmMessages); Assertions.assertTrue(IS_SUCCESS.get()); }
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; } String message = chatMessage.getMessage(); Matcher matcher = KILLCOUNT_PATTERN.matcher(message); if (matcher.find()) { final String boss = matcher.group("boss"); final int kc = Integer.parseInt(matcher.group("kc")); final String pre = matcher.group("pre"); final String post = matcher.group("post"); if (Strings.isNullOrEmpty(pre) && Strings.isNullOrEmpty(post)) { unsetKc(boss); return; } String renamedBoss = KILLCOUNT_RENAMES .getOrDefault(boss, boss) // The config service doesn't support keys with colons in them .replace(":", ""); if (boss != renamedBoss) { // Unset old TOB kc unsetKc(boss); unsetPb(boss); unsetKc(boss.replace(":", ".")); unsetPb(boss.replace(":", ".")); // Unset old story mode unsetKc("Theatre of Blood Story Mode"); unsetPb("Theatre of Blood Story Mode"); } setKc(renamedBoss, kc); // We either already have the pb, or need to remember the boss for the upcoming pb if (lastPb > -1) { log.debug("Got out-of-order personal best for {}: {}", renamedBoss, lastPb); if (renamedBoss.contains("Theatre of Blood")) { // TOB team size isn't sent in the kill message, but can be computed from varbits int tobTeamSize = tobTeamSize(); lastTeamSize = tobTeamSize == 1 ? "Solo" : (tobTeamSize + " players"); } else if (renamedBoss.contains("Tombs of Amascut")) { // TOA team size isn't sent in the kill message, but can be computed from varbits int toaTeamSize = toaTeamSize(); lastTeamSize = toaTeamSize == 1 ? "Solo" : (toaTeamSize + " players"); } final double pb = getPb(renamedBoss); // If a raid with a team size, only update the pb if it is lower than the existing pb // so that the pb is the overall lowest of any team size if (lastTeamSize == null || pb == 0 || lastPb < pb) { log.debug("Setting overall pb (old: {})", pb); setPb(renamedBoss, lastPb); } if (lastTeamSize != null) { log.debug("Setting team size pb: {}", lastTeamSize); setPb(renamedBoss + " " + lastTeamSize, lastPb); } lastPb = -1; lastTeamSize = null; } else { lastBossKill = renamedBoss; lastBossTime = client.getTickCount(); } return; } matcher = DUEL_ARENA_WINS_PATTERN.matcher(message); if (matcher.find()) { final int oldWins = getKc("Duel Arena Wins"); final int wins = matcher.group(2).equals("one") ? 1 : Integer.parseInt(matcher.group(2).replace(",", "")); final String result = matcher.group(1); int winningStreak = getKc("Duel Arena Win Streak"); int losingStreak = getKc("Duel Arena Lose Streak"); if (result.equals("won") && wins > oldWins) { losingStreak = 0; winningStreak += 1; } else if (result.equals("were defeated")) { losingStreak += 1; winningStreak = 0; } else { log.warn("unrecognized duel streak chat message: {}", message); } setKc("Duel Arena Wins", wins); setKc("Duel Arena Win Streak", winningStreak); setKc("Duel Arena Lose Streak", losingStreak); } matcher = DUEL_ARENA_LOSSES_PATTERN.matcher(message); if (matcher.find()) { int losses = matcher.group(1).equals("one") ? 1 : Integer.parseInt(matcher.group(1).replace(",", "")); setKc("Duel Arena Losses", losses); } matcher = KILL_DURATION_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = NEW_PB_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = RAIDS_PB_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = RAIDS_DURATION_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = HS_PB_PATTERN.matcher(message); if (matcher.find()) { int floor = Integer.parseInt(matcher.group("floor")); String floortime = matcher.group("floortime"); String floorpb = matcher.group("floorpb"); String otime = matcher.group("otime"); String opb = matcher.group("opb"); String pb = MoreObjects.firstNonNull(floorpb, floortime); setPb("Hallowed Sepulchre Floor " + floor, timeStringToSeconds(pb)); if (otime != null) { pb = MoreObjects.firstNonNull(opb, otime); setPb("Hallowed Sepulchre", timeStringToSeconds(pb)); } } matcher = HS_KC_FLOOR_PATTERN.matcher(message); if (matcher.find()) { int floor = Integer.parseInt(matcher.group(1)); int kc = Integer.parseInt(matcher.group(2).replaceAll(",", "")); setKc("Hallowed Sepulchre Floor " + floor, kc); } matcher = HS_KC_GHC_PATTERN.matcher(message); if (matcher.find()) { int kc = Integer.parseInt(matcher.group(1).replaceAll(",", "")); setKc("Hallowed Sepulchre", kc); } matcher = HUNTER_RUMOUR_KC_PATTERN.matcher(message); if (matcher.find()) { int kc = Integer.parseInt(matcher.group(1).replaceAll(",", "")); setKc("Hunter Rumours", kc); } if (lastBossKill != null && lastBossTime != client.getTickCount()) { lastBossKill = null; lastBossTime = -1; } matcher = COLLECTION_LOG_ITEM_PATTERN.matcher(message); if (matcher.find()) { String item = matcher.group(1); int petId = findPet(item); if (petId != -1) { final List<Integer> petList = new ArrayList<>(getPetList()); if (!petList.contains(petId)) { log.debug("New pet added: {}/{}", item, petId); petList.add(petId); setPetList(petList); } } } matcher = GUARDIANS_OF_THE_RIFT_PATTERN.matcher(message); if (matcher.find()) { int kc = Integer.parseInt(matcher.group(1)); setKc("Guardians of the Rift", kc); } }
@Test public void testToaPbEntry() { when(client.getVarbitValue(Varbits.TOA_MEMBER_1_HEALTH)).thenReturn(24); when(client.getVarbitValue(Varbits.TOA_MEMBER_2_HEALTH)).thenReturn(15); ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Challenge complete: The Wardens. Duration: <col=ef1020>9:40</col><br>Tombs of Amascut: Entry Mode challenge completion time: <col=ef1020>9:40</col>. Personal best: 20:31", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Tombs of Amascut total completion time: <col=ef1020>0:01</col> (new personal best)", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your completed Tombs of Amascut: Entry Mode count is: <col=ff0000>9</col>.", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration("killcount", "tombs of amascut entry mode", 9); verify(configManager).setRSProfileConfiguration("personalbest", "tombs of amascut entry mode", 20 * 60 + 31.); verify(configManager).setRSProfileConfiguration("personalbest", "tombs of amascut entry mode 2 players", 20 * 60 + 31.); }
protected void mergeAndRevive(ConsumeReviveObj consumeReviveObj) throws Throwable { ArrayList<PopCheckPoint> sortList = consumeReviveObj.genSortList(); POP_LOGGER.info("reviveQueueId={}, ck listSize={}", queueId, sortList.size()); if (sortList.size() != 0) { POP_LOGGER.info("reviveQueueId={}, 1st ck, startOffset={}, reviveOffset={}; last ck, startOffset={}, reviveOffset={}", queueId, sortList.get(0).getStartOffset(), sortList.get(0).getReviveOffset(), sortList.get(sortList.size() - 1).getStartOffset(), sortList.get(sortList.size() - 1).getReviveOffset()); } long newOffset = consumeReviveObj.oldOffset; for (PopCheckPoint popCheckPoint : sortList) { if (!shouldRunPopRevive) { POP_LOGGER.info("slave skip ck process, revive topic={}, reviveQueueId={}", reviveTopic, queueId); break; } if (consumeReviveObj.endTime - popCheckPoint.getReviveTime() <= (PopAckConstants.ackTimeInterval + PopAckConstants.SECOND)) { break; } // check normal topic, skip ck , if normal topic is not exist String normalTopic = KeyBuilder.parseNormalTopic(popCheckPoint.getTopic(), popCheckPoint.getCId()); if (brokerController.getTopicConfigManager().selectTopicConfig(normalTopic) == null) { POP_LOGGER.warn("reviveQueueId={}, can not get normal topic {}, then continue", queueId, popCheckPoint.getTopic()); newOffset = popCheckPoint.getReviveOffset(); continue; } if (null == brokerController.getSubscriptionGroupManager().findSubscriptionGroupConfig(popCheckPoint.getCId())) { POP_LOGGER.warn("reviveQueueId={}, can not get cid {}, then continue", queueId, popCheckPoint.getCId()); newOffset = popCheckPoint.getReviveOffset(); continue; } while (inflightReviveRequestMap.size() > 3) { waitForRunning(100); Pair<Long, Boolean> pair = inflightReviveRequestMap.firstEntry().getValue(); if (!pair.getObject2() && System.currentTimeMillis() - pair.getObject1() > 1000 * 30) { PopCheckPoint oldCK = inflightReviveRequestMap.firstKey(); rePutCK(oldCK, pair); inflightReviveRequestMap.remove(oldCK); POP_LOGGER.warn("stay too long, remove from reviveRequestMap, {}, {}, {}, {}", popCheckPoint.getTopic(), popCheckPoint.getBrokerName(), popCheckPoint.getQueueId(), popCheckPoint.getStartOffset()); } } reviveMsgFromCk(popCheckPoint); newOffset = popCheckPoint.getReviveOffset(); } if (newOffset > consumeReviveObj.oldOffset) { if (!shouldRunPopRevive) { POP_LOGGER.info("slave skip commit, revive topic={}, reviveQueueId={}", reviveTopic, queueId); return; } this.brokerController.getConsumerOffsetManager().commitOffset(PopAckConstants.LOCAL_HOST, PopAckConstants.REVIVE_GROUP, reviveTopic, queueId, newOffset); } reviveOffset = newOffset; consumeReviveObj.newOffset = newOffset; }
@Test public void testReviveMsgFromCk_messageFound_writeRetryFailed_rewriteCK_end() throws Throwable { brokerConfig.setSkipWhenCKRePutReachMaxTimes(true); PopCheckPoint ck = buildPopCheckPoint(0, 0, 0); ck.setRePutTimes("17"); PopReviveService.ConsumeReviveObj reviveObj = new PopReviveService.ConsumeReviveObj(); reviveObj.map.put("", ck); reviveObj.endTime = System.currentTimeMillis(); StringBuilder actualRetryTopic = new StringBuilder(); when(escapeBridge.getMessageAsync(anyString(), anyLong(), anyInt(), anyString(), anyBoolean())) .thenReturn(CompletableFuture.completedFuture(Triple.of(new MessageExt(), "", false))); when(escapeBridge.putMessageToSpecificQueue(any(MessageExtBrokerInner.class))).thenAnswer(invocation -> { MessageExtBrokerInner msg = invocation.getArgument(0); actualRetryTopic.append(msg.getTopic()); return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, new AppendMessageResult(AppendMessageStatus.MESSAGE_SIZE_EXCEEDED)); }); popReviveService.mergeAndRevive(reviveObj); Assert.assertEquals(KeyBuilder.buildPopRetryTopic(TOPIC, GROUP, false), actualRetryTopic.toString()); verify(escapeBridge, times(1)).putMessageToSpecificQueue(any(MessageExtBrokerInner.class)); // write retry verify(messageStore, times(0)).putMessage(any(MessageExtBrokerInner.class)); // rewrite CK }
public void playbackMovie(String movie) { VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie); videoStreamingService.doProcessing(); }
@Test void testBusinessDelegate() { // setup a client object var client = new MobileClient(businessDelegate); // action client.playbackMovie("Die hard"); // verifying that the businessDelegate was used by client during playbackMovie() method. verify(businessDelegate).playbackMovie(anyString()); verify(netflixService).doProcessing(); // action client.playbackMovie("Maradona"); // verifying that the businessDelegate was used by client during doTask() method. verify(businessDelegate, times(2)).playbackMovie(anyString()); verify(youTubeService).doProcessing(); }
public BranchStatus branchCommit(String xid, long branchId, String resourceId) { Phase2Context context = new Phase2Context(xid, branchId, resourceId); addToCommitQueue(context); return BranchStatus.PhaseTwo_Committed; }
@Test void branchCommit() { BranchStatus status = worker.branchCommit("test", 0, null); assertEquals(BranchStatus.PhaseTwo_Committed, status, "should return PhaseTwo_Committed"); }
@Override public Column convert(BasicTypeDefine typeDefine) { Long typeDefineLength = typeDefine.getLength(); PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .columnLength(typeDefineLength) .scale(typeDefine.getScale()) .nullable(typeDefine.isNullable()) .defaultValue(typeDefine.getDefaultValue()) .comment(typeDefine.getComment()); String irisDataType = typeDefine.getDataType().toUpperCase(); long charOrBinaryLength = Objects.nonNull(typeDefineLength) && typeDefineLength > 0 ? typeDefineLength : 1; switch (irisDataType) { case IRIS_NULL: builder.dataType(BasicType.VOID_TYPE); break; case IRIS_BIT: builder.dataType(BasicType.BOOLEAN_TYPE); break; case IRIS_NUMERIC: case IRIS_MONEY: case IRIS_SMALLMONEY: case IRIS_NUMBER: case IRIS_DEC: case IRIS_DECIMAL: DecimalType decimalType; if (typeDefine.getPrecision() != null && typeDefine.getPrecision() > 0) { decimalType = new DecimalType( typeDefine.getPrecision().intValue(), typeDefine.getScale()); } else { decimalType = new DecimalType(DEFAULT_PRECISION, DEFAULT_SCALE); } builder.dataType(decimalType); builder.columnLength(Long.valueOf(decimalType.getPrecision())); builder.scale(decimalType.getScale()); break; case IRIS_INT: case IRIS_INTEGER: case IRIS_MEDIUMINT: builder.dataType(BasicType.INT_TYPE); break; case IRIS_ROWVERSION: case IRIS_BIGINT: case IRIS_SERIAL: builder.dataType(BasicType.LONG_TYPE); break; case IRIS_TINYINT: builder.dataType(BasicType.BYTE_TYPE); break; case IRIS_SMALLINT: builder.dataType(BasicType.SHORT_TYPE); break; case IRIS_FLOAT: builder.dataType(BasicType.FLOAT_TYPE); break; case IRIS_DOUBLE: case IRIS_REAL: case IRIS_DOUBLE_PRECISION: builder.dataType(BasicType.DOUBLE_TYPE); break; case IRIS_CHAR: case IRIS_CHAR_VARYING: case IRIS_CHARACTER_VARYING: case IRIS_NATIONAL_CHAR: case IRIS_NATIONAL_CHAR_VARYING: case IRIS_NATIONAL_CHARACTER: case IRIS_NATIONAL_CHARACTER_VARYING: case IRIS_NATIONAL_VARCHAR: case IRIS_NCHAR: case IRIS_SYSNAME: case IRIS_VARCHAR2: case IRIS_VARCHAR: case IRIS_NVARCHAR: case IRIS_UNIQUEIDENTIFIER: case IRIS_GUID: case IRIS_CHARACTER: builder.dataType(BasicType.STRING_TYPE); builder.columnLength(charOrBinaryLength); break; case IRIS_NTEXT: case IRIS_CLOB: case IRIS_LONG_VARCHAR: case IRIS_LONG: case IRIS_LONGTEXT: case IRIS_MEDIUMTEXT: case IRIS_TEXT: case IRIS_LONGVARCHAR: builder.dataType(BasicType.STRING_TYPE); builder.columnLength(Long.valueOf(Integer.MAX_VALUE)); break; case IRIS_DATE: builder.dataType(LocalTimeType.LOCAL_DATE_TYPE); break; case IRIS_TIME: builder.dataType(LocalTimeType.LOCAL_TIME_TYPE); break; case IRIS_DATETIME: case IRIS_DATETIME2: case IRIS_SMALLDATETIME: case IRIS_TIMESTAMP: case IRIS_TIMESTAMP2: case IRIS_POSIXTIME: builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE); break; case IRIS_BINARY: case IRIS_BINARY_VARYING: case IRIS_RAW: case IRIS_VARBINARY: builder.dataType(PrimitiveByteArrayType.INSTANCE); builder.columnLength(charOrBinaryLength); break; case IRIS_LONGVARBINARY: case IRIS_BLOB: case IRIS_IMAGE: case IRIS_LONG_BINARY: case IRIS_LONG_RAW: builder.dataType(PrimitiveByteArrayType.INSTANCE); builder.columnLength(Long.valueOf(Integer.MAX_VALUE)); break; default: throw CommonError.convertToSeaTunnelTypeError( DatabaseIdentifier.IRIS, irisDataType, typeDefine.getName()); } return builder.build(); }
@Test public void testConvertInt() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("int").dataType("int").build(); Column column = IrisTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), column.getName()); Assertions.assertEquals(BasicType.INT_TYPE, column.getDataType()); Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType()); }
@Override public String toString() { String str = null; if (allAllowed) { str = "All users are allowed"; } else if (users.isEmpty() && groups.isEmpty()) { str = "No users are allowed"; } else { String usersStr = null; String groupsStr = null; if (!users.isEmpty()) { usersStr = users.toString(); } if (!groups.isEmpty()) { groupsStr = groups.toString(); } if (!users.isEmpty() && !groups.isEmpty()) { str = "Users " + usersStr + " and members of the groups " + groupsStr + " are allowed"; } else if (!users.isEmpty()) { str = "Users " + usersStr + " are allowed"; } else {// users is empty array and groups is nonempty str = "Members of the groups " + groupsStr + " are allowed"; } } return str; }
@Test public void testAclString() { AccessControlList acl; acl = new AccessControlList("*"); assertThat(acl.toString()).isEqualTo("All users are allowed"); validateGetAclString(acl); acl = new AccessControlList(" "); assertThat(acl.toString()).isEqualTo("No users are allowed"); acl = new AccessControlList("user1,user2"); assertThat(acl.toString()).isEqualTo("Users [user1, user2] are allowed"); validateGetAclString(acl); acl = new AccessControlList("user1,user2 ");// with space assertThat(acl.toString()).isEqualTo("Users [user1, user2] are allowed"); validateGetAclString(acl); acl = new AccessControlList(" group1,group2"); assertThat(acl.toString()).isEqualTo( "Members of the groups [group1, group2] are allowed"); validateGetAclString(acl); acl = new AccessControlList("user1,user2 group1,group2"); assertThat(acl.toString()).isEqualTo( "Users [user1, user2] and " + "members of the groups [group1, group2] are allowed"); validateGetAclString(acl); }
@InvokeOnHeader(Web3jConstants.ETH_NEW_BLOCK_FILTER) void ethNewBlockFilter(Message message) throws IOException { Request<?, EthFilter> request = web3j.ethNewBlockFilter(); setRequestId(message, request); EthFilter response = request.send(); boolean hasError = checkForError(message, response); if (!hasError) { message.setBody(response.getFilterId()); } }
@Test public void ethNewBlockFilterTest() throws Exception { EthFilter response = Mockito.mock(EthFilter.class); Mockito.when(mockWeb3j.ethNewBlockFilter()).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getFilterId()).thenReturn(BigInteger.ONE); Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.ETH_NEW_BLOCK_FILTER); template.send(exchange); BigInteger body = exchange.getIn().getBody(BigInteger.class); assertEquals(BigInteger.ONE, body); }
@Override public E next(E reuse) throws IOException { /* There are three ways to handle object reuse: * 1) reuse and return the given object * 2) ignore the given object and return a new object * 3) exchange the given object for an existing object * * The first option is not available here as the return value has * already been deserialized from the heap's top iterator. The second * option avoids object reuse. The third option is implemented below * by passing the given object to the heap's top iterator into which * the next value will be deserialized. */ if (this.heap.size() > 0) { // get the smallest element final HeadStream<E> top = this.heap.peek(); E result = top.getHead(); // read an element if (!top.nextHead(reuse)) { this.heap.poll(); } else { this.heap.adjustTop(); } return result; } else { return null; } }
@Test void testMergeOfTenStreams() throws Exception { // iterators List<MutableObjectIterator<Tuple2<Integer, String>>> iterators = new ArrayList<>(); iterators.add( newIterator(new int[] {1, 2, 17, 23, 23}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator(new int[] {2, 6, 7, 8, 9}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator(new int[] {4, 10, 11, 11, 12}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator(new int[] {3, 6, 7, 10, 12}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator(new int[] {7, 10, 15, 19, 44}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator(new int[] {6, 6, 11, 17, 18}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator(new int[] {1, 2, 4, 5, 10}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator(new int[] {5, 10, 19, 23, 29}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator(new int[] {9, 9, 9, 9, 9}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator(new int[] {8, 8, 14, 14, 15}, new String[] {"A", "B", "C", "D", "E"})); // comparator TypeComparator<Integer> comparator = new IntComparator(true); // merge iterator MutableObjectIterator<Tuple2<Integer, String>> iterator = new MergeIterator<>(iterators, this.comparator); int elementsFound = 1; // check expected order Tuple2<Integer, String> rec1 = new Tuple2<>(); Tuple2<Integer, String> rec2 = new Tuple2<>(); assertThat(rec1 = iterator.next(rec1)).isNotNull(); while ((rec2 = iterator.next(rec2)) != null) { elementsFound++; assertThat(comparator.compare(rec1.f0, rec2.f0)).isLessThanOrEqualTo(0); Tuple2<Integer, String> tmp = rec1; rec1 = rec2; rec2 = tmp; } assertThat(elementsFound) .withFailMessage("Too few elements returned from stream.") .isEqualTo(50); }
@Override protected Map<Region, AccountInfo> operate(final PasswordCallback callback, final Path file) throws BackgroundException { final Map<Region, AccountInfo> accounts = new ConcurrentHashMap<>(); for(Region region : session.getClient().getRegions()) { try { final AccountInfo info = session.getClient().getAccountInfo(region); if(log.isInfoEnabled()) { log.info(String.format("Signing key is %s", info.getTempUrlKey())); } if(StringUtils.isBlank(info.getTempUrlKey())) { // Update account info setting temporary URL key try { final String key = new AsciiRandomStringService().random(); if(log.isDebugEnabled()) { log.debug(String.format("Set acccount temp URL key to %s", key)); } session.getClient().updateAccountMetadata(region, Collections.singletonMap("X-Account-Meta-Temp-URL-Key", key)); info.setTempUrlKey(key); } catch(GenericException e) { log.warn(String.format("Ignore failure %s updating account metadata", e)); } } accounts.put(region, info); } catch(GenericException e) { if(e.getHttpStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) { log.warn(String.format("Ignore failure %s for region %s", e, region)); continue; } throw new SwiftExceptionMappingService().map(e); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e); } } return accounts; }
@Test public void testOperate() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); assertFalse(new SwiftAccountLoader(session).operate(new DisabledLoginCallback(), container).isEmpty()); }
@Override public void swap(int i, int j) { final int segmentNumberI = i / this.recordsPerSegment; final int segmentOffsetI = (i % this.recordsPerSegment) * this.recordSize; final int segmentNumberJ = j / this.recordsPerSegment; final int segmentOffsetJ = (j % this.recordsPerSegment) * this.recordSize; swap(segmentNumberI, segmentOffsetI, segmentNumberJ, segmentOffsetJ); }
@Test void testSwap() throws Exception { final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE; final List<MemorySegment> memory = this.memoryManager.allocatePages(new DummyInvokable(), numSegments); FixedLengthRecordSorter<IntPair> sorter = newSortBuffer(memory); RandomIntPairGenerator generator = new RandomIntPairGenerator(SEED); // write the records IntPair record = new IntPair(); int num = -1; do { generator.next(record); num++; } while (sorter.write(record) && num < 3354624); // swap the records int start = 0, end = num - 1; while (start < end) { sorter.swap(start++, end--); } // re-read the records generator.reset(); IntPair readTarget = new IntPair(); int i = num - 1; while (i >= 0) { generator.next(record); readTarget = sorter.getRecord(readTarget, i--); int rk = readTarget.getKey(); int gk = record.getKey(); int rv = readTarget.getValue(); int gv = record.getValue(); assertThat(rk).withFailMessage("The re-read key is wrong %d", i).isEqualTo(gk); assertThat(rv).withFailMessage("The re-read value is wrong %d", i).isEqualTo(gv); } // release the memory occupied by the buffers sorter.dispose(); this.memoryManager.release(memory); }
@Override @MethodNotAvailable public void set(K key, V value) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testSet() { adapter.set(23, "test"); }
public static ConfigProperty defineProperty(String name, Type type, String defaultValue, String description) { return new ConfigProperty(name, type, description, defaultValue, defaultValue, false); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(defineProperty("foo", STRING, "bar", "Desc"), defineProperty("foo", STRING, "goo", "Desc")) .addEqualityGroup(defineProperty("bar", STRING, "bar", "Desc"), defineProperty("bar", STRING, "goo", "Desc")) .testEquals(); }
public static String generateApplyOrDefault( final String inputCode, final String mapperCode, final String defaultValueCode, final Class<?> returnType ) { return "(" + returnType.getSimpleName() + ")" + NullSafe.class.getSimpleName() + ".applyOrDefault(" + inputCode + "," + mapperCode + ", " + defaultValueCode + ")"; }
@Test public void shouldGenerateApplyOrDefault() { // Given: final String mapperCode = LambdaUtil .toJavaCode("val", Long.class, "val.longValue() + 1"); // When: final String javaCode = NullSafe .generateApplyOrDefault("arguments.get(\"input\")", mapperCode, "99L", Long.class); // Then: final Evaluator evaluator = CodeGenTestUtil.cookCode(javaCode, Long.class); assertThat(evaluator.evaluate("input", 10L), is(11L)); assertThat(evaluator.evaluate("input", null), is(99L)); }
@Operation(summary = "Get single certificate") @GetMapping(value = "{id}", produces = "application/json") @ResponseBody public Certificate getById(@PathVariable("id") Long id) { return certificateService.getCertificate(id); }
@Test public void getCertificateById() { when(certificateServiceMock.getCertificate(anyLong())).thenReturn(getCertificate()); Certificate result = controllerMock.getById(anyLong()); verify(certificateServiceMock, times(1)).getCertificate(anyLong()); assertEquals("test", result.getCachedCertificate()); }
@Override public R get(Object key) { if (key instanceof Integer) { int n = (Integer) key; return get(n); } return super.get(key); }
@Test public void lookupWithBogusKeyType() { assertNull(a.get(null)); // don't inline, otherwise some IDEs will immediately complain about the wrong key type Object badKey = "foo"; assertNull(a.get(badKey)); badKey = this; assertNull(a.get(badKey)); }
public static double find(Function func, double x1, double x2, double tol, int maxIter) { if (tol <= 0.0) { throw new IllegalArgumentException("Invalid tolerance: " + tol); } if (maxIter <= 0) { throw new IllegalArgumentException("Invalid maximum number of iterations: " + maxIter); } double a = x1, b = x2, c = x2, d = 0, e = 0, fa = func.apply(a), fb = func.apply(b), fc, p, q, r, s, xm; if ((fa > 0.0 && fb > 0.0) || (fa < 0.0 && fb < 0.0)) { throw new IllegalArgumentException("Root must be bracketed."); } fc = fb; for (int iter = 1; iter <= maxIter; iter++) { if ((fb > 0.0 && fc > 0.0) || (fb < 0.0 && fc < 0.0)) { c = a; fc = fa; e = d = b - a; } if (Math.abs(fc) < Math.abs(fb)) { a = b; b = c; c = a; fa = fb; fb = fc; fc = fa; } tol = 2.0 * MathEx.EPSILON * Math.abs(b) + 0.5 * tol; xm = 0.5 * (c - b); if (iter % 10 == 0) { logger.info(String.format("Brent: the root after %3d iterations: %.5g, error = %.5g", iter, b, xm)); } if (Math.abs(xm) <= tol || fb == 0.0) { logger.info(String.format("Brent finds the root after %d iterations: %.5g, error = %.5g", iter, b, xm)); return b; } if (Math.abs(e) >= tol && Math.abs(fa) > Math.abs(fb)) { s = fb / fa; if (a == c) { p = 2.0 * xm * s; q = 1.0 - s; } else { q = fa / fc; r = fb / fc; p = s * (2.0 * xm * q * (q - r) - (b - a) * (r - 1.0)); q = (q - 1.0) * (r - 1.0) * (s - 1.0); } if (p > 0.0) { q = -q; } p = Math.abs(p); double min1 = 3.0 * xm * q - Math.abs(tol * q); double min2 = Math.abs(e * q); if (2.0 * p < Math.min(min1, min2)) { e = d; d = p / q; } else { d = xm; e = d; } } else { d = xm; e = d; } a = b; fa = fb; if (Math.abs(d) > tol) { b += d; } else { b += Math.copySign(tol, xm); } fb = func.apply(b); } logger.error("Brent exceeded the maximum number of iterations."); return b; }
@Test public void testNewton() { System.out.println("Newton"); Function func = new DifferentiableFunction() { @Override public double f(double x) { return x * x * x + x * x - 5 * x + 3; } @Override public double g(double x) { return 3 * x * x + 2 * x - 5; } }; double result = Root.find(func, -4, -2, 1E-7, 500); assertEquals(-3, result, 1E-7); }
public void useBundles(List<String> bundlePaths) { if (hasLoadedBundles) { log.log(Level.FINE, () -> "Platform bundles have already been installed." + "\nInstalled bundles: " + installedBundles + "\nGiven files: " + bundlePaths); return; } installedBundles = install(bundlePaths); BundleStarter.startBundles(installedBundles); hasLoadedBundles = true; }
@Test void bundles_are_installed_and_started() { bundleLoader.useBundles(List.of(BUNDLE_1_REF)); assertEquals(1, osgi.getInstalledBundles().size()); // The bundle is installed and started TestBundle installedBundle = (TestBundle) osgi.getInstalledBundles().get(0); assertEquals(BUNDLE_1.getSymbolicName(), installedBundle.getSymbolicName()); assertTrue(installedBundle.started); }
public Mono<Void> createProducerAcl(KafkaCluster cluster, CreateProducerAclDTO request) { return adminClientService.get(cluster) .flatMap(ac -> createAclsWithLogging(ac, createProducerBindings(request))) .then(); }
@Test void createsProducerDependantAcls() { ArgumentCaptor<Collection<AclBinding>> createdCaptor = ArgumentCaptor.forClass(Collection.class); when(adminClientMock.createAcls(createdCaptor.capture())) .thenReturn(Mono.empty()); var principal = UUID.randomUUID().toString(); var host = UUID.randomUUID().toString(); aclsService.createProducerAcl( CLUSTER, new CreateProducerAclDTO() .principal(principal) .host(host) .topics(List.of("t1")) .idempotent(true) .transactionalId("txId1") ).block(); //Write, Describe, Create permission on topics, Write, Describe on transactionalIds //IDEMPOTENT_WRITE on cluster if idempotent is enabled (true) Collection<AclBinding> createdBindings = createdCaptor.getValue(); assertThat(createdBindings) .hasSize(6) .contains(new AclBinding( new ResourcePattern(ResourceType.TOPIC, "t1", PatternType.LITERAL), new AccessControlEntry(principal, host, AclOperation.WRITE, AclPermissionType.ALLOW))) .contains(new AclBinding( new ResourcePattern(ResourceType.TOPIC, "t1", PatternType.LITERAL), new AccessControlEntry(principal, host, AclOperation.DESCRIBE, AclPermissionType.ALLOW))) .contains(new AclBinding( new ResourcePattern(ResourceType.TOPIC, "t1", PatternType.LITERAL), new AccessControlEntry(principal, host, AclOperation.CREATE, AclPermissionType.ALLOW))) .contains(new AclBinding( new ResourcePattern(ResourceType.TRANSACTIONAL_ID, "txId1", PatternType.LITERAL), new AccessControlEntry(principal, host, AclOperation.WRITE, AclPermissionType.ALLOW))) .contains(new AclBinding( new ResourcePattern(ResourceType.TRANSACTIONAL_ID, "txId1", PatternType.LITERAL), new AccessControlEntry(principal, host, AclOperation.DESCRIBE, AclPermissionType.ALLOW))) .contains(new AclBinding( new ResourcePattern(ResourceType.CLUSTER, Resource.CLUSTER_NAME, PatternType.LITERAL), new AccessControlEntry(principal, host, AclOperation.IDEMPOTENT_WRITE, AclPermissionType.ALLOW))); }
public Map<String, String> parse(String body) { final ImmutableMap.Builder<String, String> newLookupBuilder = ImmutableMap.builder(); final String[] lines = body.split(lineSeparator); for (String line : lines) { if (line.startsWith(this.ignorechar)) { continue; } final String[] values = line.split(this.splitPattern); if (values.length <= Math.max(keyColumn, keyOnly ? 0 : valueColumn)) { continue; } final String key = this.caseInsensitive ? values[keyColumn].toLowerCase(Locale.ENGLISH) : values[keyColumn]; final String value = this.keyOnly ? "" : values[valueColumn].trim(); final String finalKey = Strings.isNullOrEmpty(quoteChar) ? key.trim() : key.trim().replaceAll("^" + quoteChar + "|" + quoteChar + "$", ""); final String finalValue = Strings.isNullOrEmpty(quoteChar) ? value.trim() : value.trim().replaceAll("^" + quoteChar + "|" + quoteChar + "$", ""); newLookupBuilder.put(finalKey, finalValue); } return newLookupBuilder.build(); }
@Test public void parseQuotedStrings() throws Exception { final String input = "# Sample file for testing\n" + "\"foo\":\"23\"\n" + "\"bar\":\"42\"\n" + "\"baz\":\"17\"\n" + "\"qux\":\"42:23\"\n" + "\"qu:ux\":\"42\""; final DSVParser dsvParser = new DSVParser("#", "\n", ":", "\"", false, false, 0, Optional.of(1)); final Map<String, String> result = dsvParser.parse(input); assertThat(result) .isNotNull() .isNotEmpty() .hasSize(5) .containsExactly( new AbstractMap.SimpleEntry<>("foo", "23"), new AbstractMap.SimpleEntry<>("bar", "42"), new AbstractMap.SimpleEntry<>("baz", "17"), new AbstractMap.SimpleEntry<>("qux", "42:23"), new AbstractMap.SimpleEntry<>("qu:ux", "42") ); }
@Override public void truncate(SequenceNumber to) { LOG.debug("truncate {} to sqn {} (excl.)", logId, to); checkArgument(to.compareTo(activeSequenceNumber) <= 0); lowestSequenceNumber = to; notUploaded.headMap(lowestSequenceNumber, false).clear(); Map<SequenceNumber, UploadResult> toDiscard = uploaded.headMap(to); notifyStateNotUsed(toDiscard); toDiscard.clear(); }
@Test void testTruncate() { assertThatThrownBy( () -> withWriter( (writer, uploader) -> { SequenceNumber sqn = append(writer, getBytes()); writer.truncate(sqn.next()); writer.persist(sqn, 1L); })) .isInstanceOf(IllegalArgumentException.class); }
static String getConfigValueAsString(ServiceConfiguration conf, String configProp) throws IllegalArgumentException { String value = getConfigValueAsStringImpl(conf, configProp); log.info("Configuration for [{}] is [{}]", configProp, value); return value; }
@Test public void testGetConfigValueAsStringWithDefaultWorks() { Properties props = new Properties(); props.setProperty("prop1", "audience"); ServiceConfiguration config = new ServiceConfiguration(); config.setProperties(props); String actual = ConfigUtils.getConfigValueAsString(config, "prop1", "default"); assertEquals("audience", actual); }
public int positionBitsToShift() { return positionBitsToShift; }
@Test void shouldOverridePositionBitsToShift() { final int positionBitsToShift = -6; final int newPositionBitsToShift = 20; final Header header = new Header(42, positionBitsToShift); assertEquals(positionBitsToShift, header.positionBitsToShift()); header.positionBitsToShift(newPositionBitsToShift); assertEquals(newPositionBitsToShift, header.positionBitsToShift()); }
@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 shouldCloseIterator() { // When: table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS); // Then: verify(fetchIterator).close(); }
static int readHeapBuffer(InputStream f, ByteBuffer buf) throws IOException { int bytesRead = f.read(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining()); if (bytesRead < 0) { // if this resulted in EOF, don't update position return bytesRead; } else { buf.position(buf.position() + bytesRead); return bytesRead; } }
@Test public void testHeapRead() throws Exception { ByteBuffer readBuffer = ByteBuffer.allocate(20); MockInputStream stream = new MockInputStream(); int len = DelegatingSeekableInputStream.readHeapBuffer(stream, readBuffer); Assert.assertEquals(10, len); Assert.assertEquals(10, readBuffer.position()); Assert.assertEquals(20, readBuffer.limit()); len = DelegatingSeekableInputStream.readHeapBuffer(stream, readBuffer); Assert.assertEquals(-1, len); readBuffer.flip(); Assert.assertEquals("Buffer contents should match", ByteBuffer.wrap(TEST_ARRAY), readBuffer); }
@Override public Expression getExpression(String tableName, Alias tableAlias) { // 只有有登陆用户的情况下,才进行数据权限的处理 LoginUser loginUser = SecurityFrameworkUtils.getLoginUser(); if (loginUser == null) { return null; } // 只有管理员类型的用户,才进行数据权限的处理 if (ObjectUtil.notEqual(loginUser.getUserType(), UserTypeEnum.ADMIN.getValue())) { return null; } // 获得数据权限 DeptDataPermissionRespDTO deptDataPermission = loginUser.getContext(CONTEXT_KEY, DeptDataPermissionRespDTO.class); // 从上下文中拿不到,则调用逻辑进行获取 if (deptDataPermission == null) { deptDataPermission = permissionApi.getDeptDataPermission(loginUser.getId()); if (deptDataPermission == null) { log.error("[getExpression][LoginUser({}) 获取数据权限为 null]", JsonUtils.toJsonString(loginUser)); throw new NullPointerException(String.format("LoginUser(%d) Table(%s/%s) 未返回数据权限", loginUser.getId(), tableName, tableAlias.getName())); } // 添加到上下文中,避免重复计算 loginUser.setContext(CONTEXT_KEY, deptDataPermission); } // 情况一,如果是 ALL 可查看全部,则无需拼接条件 if (deptDataPermission.getAll()) { return null; } // 情况二,即不能查看部门,又不能查看自己,则说明 100% 无权限 if (CollUtil.isEmpty(deptDataPermission.getDeptIds()) && Boolean.FALSE.equals(deptDataPermission.getSelf())) { return new EqualsTo(null, null); // WHERE null = null,可以保证返回的数据为空 } // 情况三,拼接 Dept 和 User 的条件,最后组合 Expression deptExpression = buildDeptExpression(tableName,tableAlias, deptDataPermission.getDeptIds()); Expression userExpression = buildUserExpression(tableName, tableAlias, deptDataPermission.getSelf(), loginUser.getId()); if (deptExpression == null && userExpression == null) { // TODO 芋艿:获得不到条件的时候,暂时不抛出异常,而是不返回数据 log.warn("[getExpression][LoginUser({}) Table({}/{}) DeptDataPermission({}) 构建的条件为空]", JsonUtils.toJsonString(loginUser), tableName, tableAlias, JsonUtils.toJsonString(deptDataPermission)); // throw new NullPointerException(String.format("LoginUser(%d) Table(%s/%s) 构建的条件为空", // loginUser.getId(), tableName, tableAlias.getName())); return EXPRESSION_NULL; } if (deptExpression == null) { return userExpression; } if (userExpression == null) { return deptExpression; } // 目前,如果有指定部门 + 可查看自己,采用 OR 条件。即,WHERE (dept_id IN ? OR user_id = ?) return new Parenthesis(new OrExpression(deptExpression, userExpression)); }
@Test // 全部数据权限 public void testGetExpression_allDeptDataPermission() { try (MockedStatic<SecurityFrameworkUtils> securityFrameworkUtilsMock = mockStatic(SecurityFrameworkUtils.class)) { // 准备参数 String tableName = "t_user"; Alias tableAlias = new Alias("u"); // mock 方法(LoginUser) LoginUser loginUser = randomPojo(LoginUser.class, o -> o.setId(1L) .setUserType(UserTypeEnum.ADMIN.getValue())); securityFrameworkUtilsMock.when(SecurityFrameworkUtils::getLoginUser).thenReturn(loginUser); // mock 方法(DeptDataPermissionRespDTO) DeptDataPermissionRespDTO deptDataPermission = new DeptDataPermissionRespDTO().setAll(true); when(permissionApi.getDeptDataPermission(same(1L))).thenReturn(deptDataPermission); // 调用 Expression expression = rule.getExpression(tableName, tableAlias); // 断言 assertNull(expression); assertSame(deptDataPermission, loginUser.getContext(DeptDataPermissionRule.CONTEXT_KEY, DeptDataPermissionRespDTO.class)); } }
public static List<String> fromPartitionKey(PartitionKey key) { // get string value from partitionKey List<LiteralExpr> literalValues = key.getKeys(); List<String> values = new ArrayList<>(literalValues.size()); for (LiteralExpr value : literalValues) { if (value instanceof NullLiteral) { values.add(key.getNullPartitionValue()); } else if (value instanceof BoolLiteral) { BoolLiteral boolValue = ((BoolLiteral) value); values.add(String.valueOf(boolValue.getValue())); } else if (key instanceof HivePartitionKey && value instanceof DateLiteral) { // Special handle Hive timestamp partition key values.add(getHiveFormatStringValue((DateLiteral) value)); } else { values.add(value.getStringValue()); } } return values; }
@Test public void testFromPartitionKey() { PartitionKey partitionKey = new PartitionKey(); LiteralExpr boolTrue1 = new BoolLiteral(true); partitionKey.pushColumn(boolTrue1, PrimitiveType.BOOLEAN); Assert.assertEquals(Lists.newArrayList("true"), fromPartitionKey(partitionKey)); }
@Override public boolean isGenerateSQLToken(final SQLStatementContext sqlStatementContext) { if (!(sqlStatementContext instanceof InsertStatementContext)) { return false; } Optional<InsertColumnsSegment> insertColumnsSegment = ((InsertStatementContext) sqlStatementContext).getSqlStatement().getInsertColumns(); return insertColumnsSegment.isPresent() && !insertColumnsSegment.get().getColumns().isEmpty(); }
@Test void assertIsNotGenerateSQLTokenWithNotInsertStatement() { assertFalse(generator.isGenerateSQLToken(mock(SelectStatementContext.class))); }
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException { ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null")); if (null == value) { return convertNullValue(convertType); } if (value.getClass() == convertType) { return value; } if (value instanceof LocalDateTime) { return convertLocalDateTimeValue((LocalDateTime) value, convertType); } if (value instanceof Timestamp) { return convertTimestampValue((Timestamp) value, convertType); } if (URL.class.equals(convertType)) { return convertURL(value); } if (value instanceof Number) { return convertNumberValue(value, convertType); } if (value instanceof Date) { return convertDateValue((Date) value, convertType); } if (value instanceof byte[]) { return convertByteArrayValue((byte[]) value, convertType); } if (boolean.class.equals(convertType)) { return convertBooleanValue(value); } if (String.class.equals(convertType)) { return value.toString(); } try { return convertType.cast(value); } catch (final ClassCastException ignored) { throw new SQLFeatureNotSupportedException("getObject with type"); } }
@Test void assertConvertDateValueSuccess() throws SQLException { Date now = new Date(); assertThat(ResultSetUtils.convertValue(now, Date.class), is(now)); assertThat(ResultSetUtils.convertValue(now, java.sql.Date.class), is(now)); assertThat(ResultSetUtils.convertValue(now, Time.class), is(now)); assertThat(ResultSetUtils.convertValue(now, Timestamp.class), is(new Timestamp(now.getTime()))); assertThat(ResultSetUtils.convertValue(now, String.class), is(now.toString())); }
public MailConfiguration getConfiguration() { if (configuration == null) { configuration = new MailConfiguration(getCamelContext()); } return configuration; }
@Test public void testDefaultPOP3Configuration() { MailEndpoint endpoint = checkEndpoint("pop3://james@myhost?password=secret"); MailConfiguration config = endpoint.getConfiguration(); assertEquals("pop3", config.getProtocol(), "getProtocol()"); assertEquals("myhost", config.getHost(), "getHost()"); assertEquals(MailUtils.DEFAULT_PORT_POP3, config.getPort(), "getPort()"); assertEquals("james", config.getUsername(), "getUsername()"); assertEquals("james@myhost", config.getRecipients().get(Message.RecipientType.TO), "getRecipients().get(Message.RecipientType.TO)"); assertEquals("INBOX", config.getFolderName(), "folder"); assertEquals("camel@localhost", config.getFrom(), "from"); assertEquals("secret", config.getPassword(), "password"); assertFalse(config.isDelete()); assertFalse(config.isIgnoreUriScheme()); assertEquals(-1, config.getFetchSize(), "fetchSize"); assertEquals("text/plain", config.getContentType(), MailConstants.MAIL_CONTENT_TYPE); assertEquals(true, config.isUnseen(), "unseen"); assertFalse(config.isDebugMode()); }
@Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { if (executor.isShutdown()) { return; } BlockingQueue<Runnable> workQueue = executor.getQueue(); Runnable firstWork = workQueue.poll(); boolean newTaskAdd = workQueue.offer(r); if (firstWork != null) { firstWork.run(); } if (!newTaskAdd) { executor.execute(r); } }
@Test public void testRejectedExecutionWhenATaskIsInTheQueueTheExecutorShouldNotExecute() { when(threadPoolExecutor.isShutdown()).thenReturn(false); when(threadPoolExecutor.getQueue()).thenReturn(workQueue); when(workQueue.poll()).thenReturn(runnableInTheQueue); when(workQueue.offer(runnable)).thenReturn(true); runsOldestTaskPolicy.rejectedExecution(runnable, threadPoolExecutor); verify(runnableInTheQueue).run(); verify(threadPoolExecutor, never()).execute(runnable); verify(runnable, never()).run(); }
public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.InstructionRequest request) throws Exception { BeamFnApi.ProcessBundleResponse.Builder response = BeamFnApi.ProcessBundleResponse.newBuilder(); BundleProcessor bundleProcessor = bundleProcessorCache.get( request, () -> { try { return createBundleProcessor( request.getProcessBundle().getProcessBundleDescriptorId(), request.getProcessBundle()); } catch (IOException e) { throw new RuntimeException(e); } }); try { PTransformFunctionRegistry startFunctionRegistry = bundleProcessor.getStartFunctionRegistry(); PTransformFunctionRegistry finishFunctionRegistry = bundleProcessor.getFinishFunctionRegistry(); ExecutionStateTracker stateTracker = bundleProcessor.getStateTracker(); try (HandleStateCallsForBundle beamFnStateClient = bundleProcessor.getBeamFnStateClient()) { stateTracker.start(request.getInstructionId()); try { // Already in reverse topological order so we don't need to do anything. for (ThrowingRunnable startFunction : startFunctionRegistry.getFunctions()) { LOG.debug("Starting function {}", startFunction); startFunction.run(); } if (request.getProcessBundle().hasElements()) { boolean inputFinished = bundleProcessor .getInboundObserver() .multiplexElements(request.getProcessBundle().getElements()); if (!inputFinished) { throw new RuntimeException( "Elements embedded in ProcessBundleRequest do not contain stream terminators for " + "all data and timer inputs. Unterminated endpoints: " + bundleProcessor.getInboundObserver().getUnfinishedEndpoints()); } } else if (!bundleProcessor.getInboundEndpointApiServiceDescriptors().isEmpty()) { BeamFnDataInboundObserver observer = bundleProcessor.getInboundObserver(); beamFnDataClient.registerReceiver( request.getInstructionId(), bundleProcessor.getInboundEndpointApiServiceDescriptors(), observer); observer.awaitCompletion(); beamFnDataClient.unregisterReceiver( request.getInstructionId(), bundleProcessor.getInboundEndpointApiServiceDescriptors()); } // Need to reverse this since we want to call finish in topological order. for (ThrowingRunnable finishFunction : Lists.reverse(finishFunctionRegistry.getFunctions())) { LOG.debug("Finishing function {}", finishFunction); finishFunction.run(); } // If bundleProcessor has not flushed any elements, embed them in response. embedOutboundElementsIfApplicable(response, bundleProcessor); // Add all checkpointed residuals to the response. response.addAllResidualRoots(bundleProcessor.getSplitListener().getResidualRoots()); // Add all metrics to the response. bundleProcessor.getProgressRequestLock().lock(); Map<String, ByteString> monitoringData = finalMonitoringData(bundleProcessor); if (runnerAcceptsShortIds) { response.putAllMonitoringData(monitoringData); } else { for (Map.Entry<String, ByteString> metric : monitoringData.entrySet()) { response.addMonitoringInfos( shortIds.get(metric.getKey()).toBuilder().setPayload(metric.getValue())); } } if (!bundleProcessor.getBundleFinalizationCallbackRegistrations().isEmpty()) { finalizeBundleHandler.registerCallbacks( bundleProcessor.getInstructionId(), ImmutableList.copyOf(bundleProcessor.getBundleFinalizationCallbackRegistrations())); response.setRequiresFinalization(true); } } finally { // We specifically deactivate state tracking while we are holding the progress request and // sampling locks. stateTracker.reset(); } } // Mark the bundle processor as re-usable. bundleProcessorCache.release( request.getProcessBundle().getProcessBundleDescriptorId(), bundleProcessor); return BeamFnApi.InstructionResponse.newBuilder().setProcessBundle(response); } catch (Exception e) { // Make sure we clean-up from the active set of bundle processors. bundleProcessorCache.discard(bundleProcessor); throw e; } }
@Test public void testInstructionIsUnregisteredFromBeamFnDataClientOnSuccess() throws Exception { BeamFnApi.ProcessBundleDescriptor processBundleDescriptor = BeamFnApi.ProcessBundleDescriptor.newBuilder() .putTransforms( "2L", RunnerApi.PTransform.newBuilder() .setSpec(RunnerApi.FunctionSpec.newBuilder().setUrn(DATA_INPUT_URN).build()) .build()) .build(); Map<String, BeamFnApi.ProcessBundleDescriptor> fnApiRegistry = ImmutableMap.of("1L", processBundleDescriptor); Mockito.doAnswer( (invocation) -> { String instructionId = invocation.getArgument(0, String.class); CloseableFnDataReceiver<BeamFnApi.Elements> data = invocation.getArgument(2, CloseableFnDataReceiver.class); data.accept( BeamFnApi.Elements.newBuilder() .addData( BeamFnApi.Elements.Data.newBuilder() .setInstructionId(instructionId) .setTransformId("2L") .setIsLast(true)) .build()); return null; }) .when(beamFnDataClient) .registerReceiver(any(), any(), any()); ProcessBundleHandler handler = new ProcessBundleHandler( PipelineOptionsFactory.create(), Collections.emptySet(), fnApiRegistry::get, beamFnDataClient, null /* beamFnStateGrpcClientCache */, null /* finalizeBundleHandler */, new ShortIdMap(), executionStateSampler, ImmutableMap.of( DATA_INPUT_URN, (PTransformRunnerFactory<Object>) (context) -> { context.addIncomingDataEndpoint( ApiServiceDescriptor.getDefaultInstance(), StringUtf8Coder.of(), (input) -> {}); return null; }), Caches.noop(), new BundleProcessorCache(), null /* dataSampler */); handler.processBundle( BeamFnApi.InstructionRequest.newBuilder() .setInstructionId("instructionId") .setProcessBundle( BeamFnApi.ProcessBundleRequest.newBuilder().setProcessBundleDescriptorId("1L")) .build()); // Ensure that we unregister during successful processing verify(beamFnDataClient).registerReceiver(eq("instructionId"), any(), any()); verify(beamFnDataClient).unregisterReceiver(eq("instructionId"), any()); verifyNoMoreInteractions(beamFnDataClient); }
public boolean eval(StructLike data) { return new EvalVisitor().eval(data); }
@Test public void testCharSeqValue() { StructType struct = StructType.of(required(34, "s", Types.StringType.get())); Evaluator evaluator = new Evaluator(struct, equal("s", "abc")); assertThat(evaluator.eval(TestHelpers.Row.of(new Utf8("abc")))) .as("string(abc) == utf8(abc) => true") .isTrue(); assertThat(evaluator.eval(TestHelpers.Row.of(new Utf8("abcd")))) .as("string(abc) == utf8(abcd) => false") .isFalse(); }
public static TransformerFactory getTransformerFactory() { TransformerFactory transformerFactory = TransformerFactory.newInstance(); setAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_DTD); setAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_STYLESHEET); return transformerFactory; }
@Test public void testGetTransformerFactory() { TransformerFactory transformerFactory = XmlUtil.getTransformerFactory(); assertNotNull(transformerFactory); assertThrows(IllegalArgumentException.class, () -> XmlUtil.setAttribute(transformerFactory, "test://no-such-property")); ignoreXxeFailureProp.setOrClearProperty("false"); assertThrows(IllegalArgumentException.class, () -> XmlUtil.setAttribute(transformerFactory, "test://no-such-property")); ignoreXxeFailureProp.setOrClearProperty("true"); XmlUtil.setAttribute(transformerFactory, "test://no-such-property"); }
public static boolean isStrictProjectionOf(Schema sourceSchema, Schema targetSchema) { return isProjectionOfInternal(sourceSchema, targetSchema, Objects::equals); }
@Test public void testIsStrictProjection() { Schema sourceSchema = new Schema.Parser().parse(SOURCE_SCHEMA); Schema projectedNestedSchema = new Schema.Parser().parse(PROJECTED_NESTED_SCHEMA_STRICT); // Case #1: Validate proper (nested) projected record schema assertTrue(AvroSchemaUtils.isStrictProjectionOf(sourceSchema, sourceSchema)); assertTrue(AvroSchemaUtils.isStrictProjectionOf(sourceSchema, projectedNestedSchema)); // NOTE: That the opposite have to be false: if schema B is a projection of A, // then A could be a projection of B iff A == B assertFalse(AvroSchemaUtils.isStrictProjectionOf(projectedNestedSchema, sourceSchema)); // Case #2: Validate proper (nested) projected array schema assertTrue( AvroSchemaUtils.isStrictProjectionOf( Schema.createArray(sourceSchema), Schema.createArray(projectedNestedSchema))); // Case #3: Validate proper (nested) projected map schema assertTrue( AvroSchemaUtils.isStrictProjectionOf( Schema.createMap(sourceSchema), Schema.createMap(projectedNestedSchema))); // Case #4: Validate proper (nested) projected union schema assertTrue( AvroSchemaUtils.isStrictProjectionOf( Schema.createUnion(Schema.create(Schema.Type.NULL), sourceSchema), Schema.createUnion(Schema.create(Schema.Type.NULL), projectedNestedSchema))); }
@SuppressWarnings("unchecked") void unite(final T id1, final T... idList) { for (final T id2 : idList) { unitePair(id1, id2); } }
@Test public void testUnite() { final QuickUnion<Long> qu = new QuickUnion<>(); final long[] ids = { 1L, 2L, 3L, 4L, 5L }; for (final long id : ids) { qu.add(id); } assertEquals(5, roots(qu, ids).size()); qu.unite(1L, 2L); assertEquals(4, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); qu.unite(3L, 4L); assertEquals(3, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); assertEquals(qu.root(3L), qu.root(4L)); qu.unite(1L, 5L); assertEquals(2, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); assertEquals(qu.root(2L), qu.root(5L)); assertEquals(qu.root(3L), qu.root(4L)); qu.unite(3L, 5L); assertEquals(1, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); assertEquals(qu.root(2L), qu.root(3L)); assertEquals(qu.root(3L), qu.root(4L)); assertEquals(qu.root(4L), qu.root(5L)); }
public PullResult processPullResult(final MessageQueue mq, final PullResult pullResult, final SubscriptionData subscriptionData) { PullResultExt pullResultExt = (PullResultExt) pullResult; this.updatePullFromWhichNode(mq, pullResultExt.getSuggestWhichBrokerId()); if (PullStatus.FOUND == pullResult.getPullStatus()) { ByteBuffer byteBuffer = ByteBuffer.wrap(pullResultExt.getMessageBinary()); List<MessageExt> msgList = MessageDecoder.decodesBatch( byteBuffer, this.mQClientFactory.getClientConfig().isDecodeReadBody(), this.mQClientFactory.getClientConfig().isDecodeDecompressBody(), true ); boolean needDecodeInnerMessage = false; for (MessageExt messageExt: msgList) { if (MessageSysFlag.check(messageExt.getSysFlag(), MessageSysFlag.INNER_BATCH_FLAG) && MessageSysFlag.check(messageExt.getSysFlag(), MessageSysFlag.NEED_UNWRAP_FLAG)) { needDecodeInnerMessage = true; break; } } if (needDecodeInnerMessage) { List<MessageExt> innerMsgList = new ArrayList<>(); try { for (MessageExt messageExt: msgList) { if (MessageSysFlag.check(messageExt.getSysFlag(), MessageSysFlag.INNER_BATCH_FLAG) && MessageSysFlag.check(messageExt.getSysFlag(), MessageSysFlag.NEED_UNWRAP_FLAG)) { MessageDecoder.decodeMessage(messageExt, innerMsgList); } else { innerMsgList.add(messageExt); } } msgList = innerMsgList; } catch (Throwable t) { log.error("Try to decode the inner batch failed for {}", pullResult.toString(), t); } } List<MessageExt> msgListFilterAgain = msgList; if (!subscriptionData.getTagsSet().isEmpty() && !subscriptionData.isClassFilterMode()) { msgListFilterAgain = new ArrayList<>(msgList.size()); for (MessageExt msg : msgList) { if (msg.getTags() != null) { if (subscriptionData.getTagsSet().contains(msg.getTags())) { msgListFilterAgain.add(msg); } } } } if (this.hasHook()) { FilterMessageContext filterMessageContext = new FilterMessageContext(); filterMessageContext.setUnitMode(unitMode); filterMessageContext.setMsgList(msgListFilterAgain); this.executeHook(filterMessageContext); } for (MessageExt msg : msgListFilterAgain) { String traFlag = msg.getProperty(MessageConst.PROPERTY_TRANSACTION_PREPARED); if (Boolean.parseBoolean(traFlag)) { msg.setTransactionId(msg.getProperty(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX)); } MessageAccessor.putProperty(msg, MessageConst.PROPERTY_MIN_OFFSET, Long.toString(pullResult.getMinOffset())); MessageAccessor.putProperty(msg, MessageConst.PROPERTY_MAX_OFFSET, Long.toString(pullResult.getMaxOffset())); msg.setBrokerName(mq.getBrokerName()); msg.setQueueId(mq.getQueueId()); if (pullResultExt.getOffsetDelta() != null) { msg.setQueueOffset(pullResultExt.getOffsetDelta() + msg.getQueueOffset()); } } pullResultExt.setMsgFoundList(msgListFilterAgain); } pullResultExt.setMessageBinary(null); return pullResult; }
@Test public void testProcessPullResult() throws Exception { PullResultExt pullResult = mock(PullResultExt.class); when(pullResult.getPullStatus()).thenReturn(PullStatus.FOUND); when(pullResult.getMessageBinary()).thenReturn(MessageDecoder.encode(createMessageExt(), false)); SubscriptionData subscriptionData = mock(SubscriptionData.class); PullResult actual = pullAPIWrapper.processPullResult(createMessageQueue(), pullResult, subscriptionData); assertNotNull(actual); assertEquals(0, actual.getNextBeginOffset()); assertEquals(0, actual.getMsgFoundList().size()); }
public SymbolTableMetadata extractMetadata(String fullName) { int index = fullName.indexOf(SERVER_NODE_URI_PREFIX_TABLENAME_SEPARATOR); // If no separator char was found, we assume it's a local table. if (index == -1) { return new SymbolTableMetadata(null, fullName, false); } if (index == 0 || index == fullName.length() - 1) { throw new RuntimeException("Unexpected name format for name: " + fullName); } String serverNodeUri = fullName.substring(0, index); String tableName = fullName.substring(index + 1); return createMetadata(serverNodeUri, tableName); }
@Test public void testExtractTableInfoRemoteTable() { SymbolTableMetadata metadata = new SymbolTableMetadataExtractor().extractMetadata("https://Host:100/service|Prefix-1000"); Assert.assertEquals(metadata.getServerNodeUri(), "https://Host:100/service"); Assert.assertEquals(metadata.getSymbolTableName(), "Prefix-1000"); Assert.assertTrue(metadata.isRemote()); }
public static GestureTrailTheme fromThemeResource( @NonNull Context askContext, @NonNull Context themeContext, @NonNull AddOn.AddOnResourceMapping mapper, @StyleRes int resId) { // filling in the defaults TypedArray defaultValues = askContext.obtainStyledAttributes( R.style.AnyKeyboardGestureTrailTheme, R.styleable.GestureTypingTheme); int maxTrailLength = defaultValues.getInt(R.styleable.GestureTypingTheme_gestureTrailMaxSectionsLength, 32); @ColorInt int trailStartColor = defaultValues.getColor(R.styleable.GestureTypingTheme_gestureTrailStartColor, Color.BLUE); @ColorInt int trailEndColor = defaultValues.getColor(R.styleable.GestureTypingTheme_gestureTrailEndColor, Color.BLACK); float startStrokeSize = defaultValues.getDimension(R.styleable.GestureTypingTheme_gestureTrailStartStrokeSize, 0f); float endStrokeSize = defaultValues.getDimension(R.styleable.GestureTypingTheme_gestureTrailEndStrokeSize, 0f); defaultValues.recycle(); final int[] remoteStyleableArray = mapper.getRemoteStyleableArrayFromLocal(R.styleable.GestureTypingTheme); TypedArray a = themeContext.obtainStyledAttributes(resId, remoteStyleableArray); final int resolvedAttrsCount = a.getIndexCount(); for (int attrIndex = 0; attrIndex < resolvedAttrsCount; attrIndex++) { final int remoteIndex = a.getIndex(attrIndex); try { int localAttrId = mapper.getLocalAttrId(remoteStyleableArray[remoteIndex]); if (localAttrId == R.attr.gestureTrailMaxSectionsLength) maxTrailLength = a.getInt(remoteIndex, maxTrailLength); else if (localAttrId == R.attr.gestureTrailStartColor) trailStartColor = a.getColor(remoteIndex, trailStartColor); else if (localAttrId == R.attr.gestureTrailEndColor) trailEndColor = a.getColor(remoteIndex, trailEndColor); else if (localAttrId == R.attr.gestureTrailStartStrokeSize) startStrokeSize = a.getDimension(remoteIndex, startStrokeSize); else if (localAttrId == R.attr.gestureTrailEndStrokeSize) endStrokeSize = a.getDimension(remoteIndex, endStrokeSize); } catch (Exception e) { Logger.w("ASK_GESTURE_THEME", "Got an exception while reading gesture theme data", e); } } a.recycle(); return new GestureTrailTheme( trailStartColor, trailEndColor, startStrokeSize, endStrokeSize, maxTrailLength); }
@Test public void testFromThemeResource() { GestureTrailTheme underTest = GestureTrailTheme.fromThemeResource( ApplicationProvider.getApplicationContext(), ApplicationProvider.getApplicationContext(), new AddOn.AddOnResourceMapping() { @Override public int[] getRemoteStyleableArrayFromLocal(int[] localStyleableArray) { return localStyleableArray; } @Override public int getApiVersion() { return 10; } @Override public int getLocalAttrId(int remoteAttrId) { return remoteAttrId; } }, R.style.AnyKeyboardGestureTrailTheme); Assert.assertEquals(64, underTest.maxTrailLength); Assert.assertEquals(Color.parseColor("#5555ddff"), underTest.mTrailStartColor); Assert.assertEquals(Color.parseColor("#11116622"), underTest.mTrailEndColor); Assert.assertEquals(8f, underTest.mStartStrokeSize, 0.1f); Assert.assertEquals(2f, underTest.mEndStrokeSize, 0.1f); Assert.assertEquals(1 / 64f, underTest.mTrailFraction, 0.1f); }
@Nonnull @Override public Optional<Mode> parse( @Nullable final String str, @Nonnull final DetectionLocation detectionLocation) { if (str == null) { return Optional.empty(); } // get explicit block size Optional<BlockSize> optionalBlockSize = Utils.extractNumberFormString(str) .map(blockSizeStr -> new BlockSize(blockSizeStr, detectionLocation)); // remove numeric values String modeString = str.replaceAll("\\d", ""); return map(modeString, detectionLocation) .map( mode -> { optionalBlockSize.ifPresent(mode::put); return mode; }); }
@Test void base() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); JcaModeMapper jcaModeMapper = new JcaModeMapper(); Optional<Mode> modeOptional = jcaModeMapper.parse("CCM", testDetectionLocation); assertThat(modeOptional).isPresent(); assertThat(modeOptional.get()).isInstanceOf(CCM.class); assertThat(modeOptional.get().getBlockSize()).isEmpty(); }
static ClassDef buildClassDef( ClassResolver classResolver, Class<?> type, List<Field> fields, boolean isObjectType) { List<FieldInfo> fieldInfos = buildFieldsInfo(classResolver, fields); Map<String, List<FieldInfo>> classLayers = getClassFields(type, fieldInfos); fieldInfos = new ArrayList<>(fieldInfos.size()); classLayers.values().forEach(fieldInfos::addAll); MemoryBuffer encodeClassDef = encodeClassDef(classResolver, type, classLayers, isObjectType); byte[] classDefBytes = encodeClassDef.getBytes(0, encodeClassDef.writerIndex()); return new ClassDef( Encoders.buildClassSpec(type), fieldInfos, isObjectType, encodeClassDef.getInt64(0), classDefBytes); }
@Test public void testBigMetaEncoding() { for (Class<?> type : new Class[] { MapFields.class, BeanA.class, Struct.createStructClass("TestBigMetaEncoding", 5) }) { Fury fury = Fury.builder().withMetaShare(true).build(); ClassDef classDef = ClassDef.buildClassDef(fury, type); ClassDef classDef1 = ClassDef.readClassDef( fury.getClassResolver(), MemoryBuffer.fromByteArray(classDef.getEncoded())); Assert.assertEquals(classDef1, classDef); } }
@SuppressWarnings("unchecked") @Override public final void remove() { remove(InternalThreadLocalMap.getIfSet()); }
@Test void testRemove() { final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>(); internalThreadLocal.set(1); Assertions.assertEquals(1, (int) internalThreadLocal.get(), "get method false!"); internalThreadLocal.remove(); Assertions.assertNull(internalThreadLocal.get(), "remove failed!"); }
@CheckForNull @Override public Map<Path, Set<Integer>> branchChangedLines(String targetBranchName, Path projectBaseDir, Set<Path> changedFiles) { return branchChangedLinesWithFileMovementDetection(targetBranchName, projectBaseDir, toChangedFileByPathsMap(changedFiles)); }
@Test public void branchChangedLines_returns_empty_set_for_files_with_lines_removed_only() throws GitAPIException, IOException { String fileName = "file-in-first-commit.xoo"; git.branchCreate().setName("b1").call(); git.checkout().setName("b1").call(); removeLineInFile(fileName, 2); commit(fileName); Path filePath = worktree.resolve(fileName); Map<Path, Set<Integer>> changedLines = newScmProvider().branchChangedLines("master", worktree, Collections.singleton(filePath)); // both lines appear correctly assertThat(changedLines).containsExactly(entry(filePath, emptySet())); }
public static ShardingSphereDatabase create(final String databaseName, final DatabaseConfiguration databaseConfig, final ConfigurationProperties props, final ComputeNodeInstanceContext computeNodeInstanceContext) throws SQLException { return ShardingSphereDatabase.create(databaseName, DatabaseTypeEngine.getProtocolType(databaseConfig, props), DatabaseTypeEngine.getStorageTypes(databaseConfig), databaseConfig, props, computeNodeInstanceContext); }
@Test void assertCreateSingleDatabase() throws SQLException { DatabaseConfiguration databaseConfig = new DataSourceProvidedDatabaseConfiguration(Collections.emptyMap(), Collections.emptyList()); ShardingSphereDatabase actual = ExternalMetaDataFactory.create("foo_db", databaseConfig, new ConfigurationProperties(new Properties()), mock(ComputeNodeInstanceContext.class)); assertThat(actual.getName(), is("foo_db")); assertTrue(actual.getResourceMetaData().getStorageUnits().isEmpty()); }
public GroupInformation createGroup(DbSession dbSession, String name, @Nullable String description) { validateGroupName(name); checkNameDoesNotExist(dbSession, name); GroupDto group = new GroupDto() .setUuid(uuidFactory.create()) .setName(name) .setDescription(description); return groupDtoToGroupInformation(dbClient.groupDao().insert(dbSession, group), dbSession); }
@Test public void createGroup_whenGroupExist_throws() { GroupDto group = mockGroupDto(); when(dbClient.groupDao().selectByName(dbSession, GROUP_NAME)).thenReturn(Optional.of(group)); assertThatExceptionOfType(BadRequestException.class) .isThrownBy(() -> groupService.createGroup(dbSession, GROUP_NAME, "New Description")) .withMessage("Group '" + GROUP_NAME + "' already exists"); }
public static List<String> split(@Nullable String input, String delimiter) { if (isNullOrEmpty(input)) { return Collections.emptyList(); } return Stream.of(input.split(delimiter)).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toList()); }
@Test public void testSplit() { assertEquals(new ArrayList<>(), StringUtils.split(null, ",")); assertEquals(new ArrayList<>(), StringUtils.split("", ",")); assertEquals(Arrays.asList("a", "b", "c"), StringUtils.split("a,b, c", ",")); assertEquals(Arrays.asList("a", "b", "c"), StringUtils.split("a,b,, c ", ",")); }
public boolean cleanupExpiredOffsets(String groupId, List<CoordinatorRecord> records) { TimelineHashMap<String, TimelineHashMap<Integer, OffsetAndMetadata>> offsetsByTopic = offsets.offsetsByGroup.get(groupId); if (offsetsByTopic == null) { return true; } // We expect the group to exist. Group group = groupMetadataManager.group(groupId); Set<String> expiredPartitions = new HashSet<>(); long currentTimestampMs = time.milliseconds(); Optional<OffsetExpirationCondition> offsetExpirationCondition = group.offsetExpirationCondition(); if (!offsetExpirationCondition.isPresent()) { return false; } AtomicBoolean allOffsetsExpired = new AtomicBoolean(true); OffsetExpirationCondition condition = offsetExpirationCondition.get(); offsetsByTopic.forEach((topic, partitions) -> { if (!group.isSubscribedToTopic(topic)) { partitions.forEach((partition, offsetAndMetadata) -> { // We don't expire the offset yet if there is a pending transactional offset for the partition. if (condition.isOffsetExpired(offsetAndMetadata, currentTimestampMs, config.offsetsRetentionMs()) && !hasPendingTransactionalOffsets(groupId, topic, partition)) { expiredPartitions.add(appendOffsetCommitTombstone(groupId, topic, partition, records).toString()); log.debug("[GroupId {}] Expired offset for partition={}-{}", groupId, topic, partition); } else { allOffsetsExpired.set(false); } }); } else { allOffsetsExpired.set(false); } }); metrics.record(OFFSET_EXPIRED_SENSOR_NAME, expiredPartitions.size()); // We don't want to remove the group if there are ongoing transactions. return allOffsetsExpired.get() && !openTransactionsByGroup.containsKey(groupId); }
@Test public void testCleanupExpiredOffsets() { GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class); Group group = mock(Group.class); OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder() .withGroupMetadataManager(groupMetadataManager) .withOffsetsRetentionMinutes(1) .build(); long commitTimestamp = context.time.milliseconds(); context.commitOffset("group-id", "firstTopic", 0, 100L, 0, commitTimestamp); context.commitOffset("group-id", "secondTopic", 0, 100L, 0, commitTimestamp); context.commitOffset("group-id", "secondTopic", 1, 100L, 0, commitTimestamp + 500); context.time.sleep(Duration.ofMinutes(1).toMillis()); // firstTopic-0: group is still subscribed to firstTopic. Do not expire. // secondTopic-0: should expire as offset retention has passed. // secondTopic-1: has not passed offset retention. Do not expire. List<CoordinatorRecord> expectedRecords = Collections.singletonList( GroupCoordinatorRecordHelpers.newOffsetCommitTombstoneRecord("group-id", "secondTopic", 0) ); when(groupMetadataManager.group("group-id")).thenReturn(group); when(group.offsetExpirationCondition()).thenReturn(Optional.of( new OffsetExpirationConditionImpl(offsetAndMetadata -> offsetAndMetadata.commitTimestampMs))); when(group.isSubscribedToTopic("firstTopic")).thenReturn(true); when(group.isSubscribedToTopic("secondTopic")).thenReturn(false); List<CoordinatorRecord> records = new ArrayList<>(); assertFalse(context.cleanupExpiredOffsets("group-id", records)); assertEquals(expectedRecords, records); // Expire secondTopic-1. context.time.sleep(500); expectedRecords = Collections.singletonList( GroupCoordinatorRecordHelpers.newOffsetCommitTombstoneRecord("group-id", "secondTopic", 1) ); records = new ArrayList<>(); assertFalse(context.cleanupExpiredOffsets("group-id", records)); assertEquals(expectedRecords, records); // Add 2 more commits, then expire all. when(group.isSubscribedToTopic("firstTopic")).thenReturn(false); context.commitOffset("group-id", "firstTopic", 1, 100L, 0, commitTimestamp + 500); context.commitOffset("group-id", "secondTopic", 0, 101L, 0, commitTimestamp + 500); expectedRecords = Arrays.asList( GroupCoordinatorRecordHelpers.newOffsetCommitTombstoneRecord("group-id", "firstTopic", 0), GroupCoordinatorRecordHelpers.newOffsetCommitTombstoneRecord("group-id", "firstTopic", 1), GroupCoordinatorRecordHelpers.newOffsetCommitTombstoneRecord("group-id", "secondTopic", 0) ); records = new ArrayList<>(); assertTrue(context.cleanupExpiredOffsets("group-id", records)); assertEquals(expectedRecords, records); }
@Override public boolean revokeToken(String clientId, String accessToken) { // 先查询,保证 clientId 时匹配的 OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.getAccessToken(accessToken); if (accessTokenDO == null || ObjectUtil.notEqual(clientId, accessTokenDO.getClientId())) { return false; } // 再删除 return oauth2TokenService.removeAccessToken(accessToken) != null; }
@Test public void testRevokeToken_success() { // 准备参数 String clientId = randomString(); String accessToken = randomString(); // mock 方法(访问令牌) OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class).setClientId(clientId); when(oauth2TokenService.getAccessToken(eq(accessToken))).thenReturn(accessTokenDO); // mock 方法(移除) when(oauth2TokenService.removeAccessToken(eq(accessToken))).thenReturn(accessTokenDO); // 调用,并断言 assertTrue(oauth2GrantService.revokeToken(clientId, accessToken)); }
public static void hookIntentGetBroadcast(Context context, int requestCode, Intent intent, int flags) { hookIntent(intent); }
@Test public void hookIntentGetBroadcast() { PushAutoTrackHelper.hookIntentGetBroadcast(mApplication, 100, MockDataTest.mockJPushIntent(), 100); }