focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public BrokerService getBrokerService() { return service; }
@Test(timeOut = 30000) public void testProducerOnNotOwnedTopic() throws Exception { resetChannel(); setChannelConnected(); // Force the case where the broker doesn't own any topic doReturn(CompletableFuture.completedFuture(false)).when(namespaceService) .isServiceUnitActiveAsync(any(TopicName.class)); // test PRODUCER failure case ByteBuf clientCommand = Commands.newProducer(nonOwnedTopicName, 1 /* producer id */, 1 /* request id */, "prod-name", Collections.emptyMap(), false); channel.writeInbound(clientCommand); Object response = getResponse(); assertEquals(response.getClass(), CommandError.class); CommandError errorResponse = (CommandError) response; assertEquals(errorResponse.getError(), ServerError.ServiceNotReady); assertFalse(pulsar.getBrokerService().getTopicReference(nonOwnedTopicName).isPresent()); channel.finish(); }
@Override public HttpRestResult<String> httpGet(String path, Map<String, String> headers, Map<String, String> paramValues, String encode, long readTimeoutMs) throws Exception { final long endTime = System.currentTimeMillis() + readTimeoutMs; String currentServerAddr = serverListMgr.getCurrentServerAddr(); int maxRetry = this.maxRetry; HttpClientConfig httpConfig = HttpClientConfig.builder() .setReadTimeOutMillis(Long.valueOf(readTimeoutMs).intValue()) .setConTimeOutMillis(ConfigHttpClientManager.getInstance().getConnectTimeoutOrDefault(100)).build(); do { try { Header newHeaders = Header.newInstance(); if (headers != null) { newHeaders.addAll(headers); } Query query = Query.newInstance().initParams(paramValues); HttpRestResult<String> result = nacosRestTemplate.get(getUrl(currentServerAddr, path), httpConfig, newHeaders, query, String.class); if (isFail(result)) { LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}", serverListMgr.getCurrentServerAddr(), result.getCode()); } else { // Update the currently available server addr serverListMgr.updateCurrentServerAddr(currentServerAddr); return result; } } catch (ConnectException connectException) { LOGGER.error("[NACOS ConnectException httpGet] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), connectException.getMessage()); } catch (SocketTimeoutException socketTimeoutException) { LOGGER.error("[NACOS SocketTimeoutException httpGet] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), socketTimeoutException.getMessage()); } catch (Exception ex) { LOGGER.error("[NACOS Exception httpGet] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ex); throw ex; } if (serverListMgr.getIterator().hasNext()) { currentServerAddr = serverListMgr.getIterator().next(); } else { maxRetry--; if (maxRetry < 0) { throw new ConnectException( "[NACOS HTTP-GET] The maximum number of tolerable server reconnection errors has been reached"); } serverListMgr.refreshCurrentServerAddr(); } } while (System.currentTimeMillis() <= endTime); LOGGER.error("no available server"); throw new ConnectException("no available server"); }
@Test void testHttpWithRequestException() throws Exception { assertThrows(NacosException.class, () -> { when(nacosRestTemplate.<String>get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); }); }
@SuppressWarnings("unused") // Required for automatic type inference public static <K> Builder0<K> forClass(final Class<K> type) { return new Builder0<>(); }
@Test public void shouldNotThrowOnDuplicateHandlerR2() { HandlerMaps.forClass(BaseType.class) .withArgTypes(String.class, Integer.class) .withReturnType(Number.class) .put(LeafTypeA.class, handlerR2_1) .put(LeafTypeB.class, handlerR2_1); }
@Override public void linkNodes(K parentKey, K childKey, BiConsumer<TreeEntry<K, V>, TreeEntry<K, V>> consumer) { consumer = ObjectUtil.defaultIfNull(consumer, (parent, child) -> { }); final TreeEntryNode<K, V> parentNode = nodes.computeIfAbsent(parentKey, t -> new TreeEntryNode<>(null, t)); TreeEntryNode<K, V> childNode = nodes.get(childKey); // 1.子节点不存在 if (ObjectUtil.isNull(childNode)) { childNode = new TreeEntryNode<>(parentNode, childKey); consumer.accept(parentNode, childNode); nodes.put(childKey, childNode); return; } // 2.子节点存在,且已经是该父节点的子节点了 if (ObjectUtil.equals(parentNode, childNode.getDeclaredParent())) { consumer.accept(parentNode, childNode); return; } // 3.子节点存在,但是未与其他节点构成父子关系 if (false == childNode.hasParent()) { parentNode.addChild(childNode); } // 4.子节点存在,且已经与其他节点构成父子关系,但是允许子节点直接修改其父节点 else if (allowOverrideParent) { childNode.getDeclaredParent().removeDeclaredChild(childNode.getKey()); parentNode.addChild(childNode); } // 5.子节点存在,且已经与其他节点构成父子关系,但是不允许子节点直接修改其父节点 else { throw new IllegalArgumentException(StrUtil.format( "[{}] has been used as child of [{}], can not be overwrite as child of [{}]", childNode.getKey(), childNode.getDeclaredParent().getKey(), parentKey )); } consumer.accept(parentNode, childNode); }
@Test public void containsParentNodeTest() { final ForestMap<String, String> map = new LinkedForestMap<>(false); map.linkNodes("a", "b"); map.linkNodes("b", "c"); assertTrue(map.containsParentNode("c", "b")); assertTrue(map.containsParentNode("c", "a")); assertTrue(map.containsParentNode("b", "a")); assertFalse(map.containsParentNode("a", "a")); }
@Override public <R extends MessageResponse<?>> R chat(Prompt<R> prompt, ChatOptions options) { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("Authorization", "Bearer " + getConfig().getApiKey()); Consumer<Map<String, String>> headersConfig = config.getHeadersConfig(); if (headersConfig != null) { headersConfig.accept(headers); } String payload = OpenAiLLmUtil.promptToPayload(prompt, config, options, false); String endpoint = config.getEndpoint(); String response = httpClient.post(endpoint + "/v1/chat/completions", headers, payload); if (StringUtil.noText(response)) { return null; } if (config.isDebug()) { System.out.println(">>>>receive payload:" + response); } JSONObject jsonObject = JSON.parseObject(response); JSONObject error = jsonObject.getJSONObject("error"); AbstractBaseMessageResponse<?> messageResponse; if (prompt instanceof FunctionPrompt) { messageResponse = new FunctionMessageResponse(((FunctionPrompt) prompt).getFunctions() , functionMessageParser.parse(jsonObject)); } else { messageResponse = new AiMessageResponse(aiMessageParser.parse(jsonObject)); } if (error != null && !error.isEmpty()) { messageResponse.setError(true); messageResponse.setErrorMessage(error.getString("message")); messageResponse.setErrorType(error.getString("type")); messageResponse.setErrorCode(error.getString("code")); } //noinspection unchecked return (R) messageResponse; }
@Test() public void testChatWithImage() { OpenAiLlmConfig config = new OpenAiLlmConfig(); config.setApiKey("sk-5gqOclb****0"); config.setModel("gpt-4-turbo"); Llm llm = new OpenAiLlm(config); ImagePrompt prompt = new ImagePrompt("What's in this image?"); prompt.setImageUrl("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"); // llm.chatStream(prompt, (StreamResponseListener<AiMessageResponse, AiMessage>) // (context, response) -> System.out.println(response.getMessage().getContent()) // ); AiMessageResponse response = llm.chat(prompt); System.out.println(response); try { Thread.sleep(12000); } catch (InterruptedException e) { throw new RuntimeException(e); } }
public static String toString(RedisCommand<?> command, Object... params) { if (RedisCommands.AUTH.equals(command)) { return "command: " + command + ", params: (password masked)"; } return "command: " + command + ", params: " + LogHelper.toString(params); }
@Test public void toStringWithNestedPrimitives() { Object[] input = new Object[] { "0", 1, 2L, 3.1D, 4.2F, (byte) 5, '6' }; assertThat(LogHelper.toString(input)).isEqualTo("[0, 1, 2, 3.1, 4.2, 5, 6]"); }
static Set<Integer> parseStatusCodes(String statusCodesString) { if (statusCodesString == null || statusCodesString.isEmpty()) { return Collections.emptySet(); } Set<Integer> codes = new LinkedHashSet<Integer>(); for (String codeString : statusCodesString.split(",")) { codes.add(Integer.parseInt(codeString)); } return codes; }
@Test void parseCodes() { assertThat(LBClient.parseStatusCodes("")).isEmpty(); assertThat(LBClient.parseStatusCodes(null)).isEmpty(); assertThat(LBClient.parseStatusCodes("504")).contains(504); assertThat(LBClient.parseStatusCodes("503,504")).contains(503, 504); }
@Override public String toString() { return elapsed().toMillis() + " ms"; }
@Test public void toString_() { stopwatch.toString(); }
@VisibleForTesting static SortedMap<OffsetRange, Integer> computeOverlappingRanges(Iterable<OffsetRange> ranges) { ImmutableSortedMap.Builder<OffsetRange, Integer> rval = ImmutableSortedMap.orderedBy(OffsetRangeComparator.INSTANCE); List<OffsetRange> sortedRanges = Lists.newArrayList(ranges); if (sortedRanges.isEmpty()) { return rval.build(); } Collections.sort(sortedRanges, OffsetRangeComparator.INSTANCE); // Stores ranges in smallest 'from' and then smallest 'to' order // e.g. [2, 7), [3, 4), [3, 5), [3, 5), [3, 6), [4, 0) PriorityQueue<OffsetRange> rangesWithSameFrom = new PriorityQueue<>(OffsetRangeComparator.INSTANCE); Iterator<OffsetRange> iterator = sortedRanges.iterator(); // Stored in reverse sorted order so that when we iterate and re-add them back to // overlappingRanges they are stored in sorted order from smallest to largest range.to List<OffsetRange> rangesToProcess = new ArrayList<>(); while (iterator.hasNext()) { OffsetRange current = iterator.next(); // Skip empty ranges if (current.getFrom() == current.getTo()) { continue; } // If the current range has a different 'from' then a prior range then we must produce // ranges in [rangesWithSameFrom.from, current.from) while (!rangesWithSameFrom.isEmpty() && rangesWithSameFrom.peek().getFrom() != current.getFrom()) { rangesToProcess.addAll(rangesWithSameFrom); Collections.sort(rangesToProcess, OffsetRangeComparator.INSTANCE); rangesWithSameFrom.clear(); int i = 0; long lastTo = rangesToProcess.get(i).getFrom(); // Output all the ranges that are strictly less then current.from // e.g. current.to := 7 for [3, 4), [3, 5), [3, 5), [3, 6) will produce // [3, 4) := 4 // [4, 5) := 3 // [5, 6) := 1 for (; i < rangesToProcess.size(); ++i) { if (rangesToProcess.get(i).getTo() > current.getFrom()) { break; } // Output only the first of any subsequent duplicate ranges if (i == 0 || rangesToProcess.get(i - 1).getTo() != rangesToProcess.get(i).getTo()) { rval.put( new OffsetRange(lastTo, rangesToProcess.get(i).getTo()), rangesToProcess.size() - i); lastTo = rangesToProcess.get(i).getTo(); } } // We exitted the loop with 'to' > current.from, we must add the range [lastTo, // current.from) if it is non-empty if (lastTo < current.getFrom() && i != rangesToProcess.size()) { rval.put(new OffsetRange(lastTo, current.getFrom()), rangesToProcess.size() - i); } // The remaining ranges have a 'to' that is greater then 'current.from' and will overlap // with current so add them back to rangesWithSameFrom with the updated 'from' for (; i < rangesToProcess.size(); ++i) { rangesWithSameFrom.add( new OffsetRange(current.getFrom(), rangesToProcess.get(i).getTo())); } rangesToProcess.clear(); } rangesWithSameFrom.add(current); } // Process the last chunk of overlapping ranges while (!rangesWithSameFrom.isEmpty()) { // This range always represents the range with with the smallest 'to' OffsetRange current = rangesWithSameFrom.remove(); rangesToProcess.addAll(rangesWithSameFrom); Collections.sort(rangesToProcess, OffsetRangeComparator.INSTANCE); rangesWithSameFrom.clear(); rval.put(current, rangesToProcess.size() + 1 /* include current */); // Shorten all the remaining ranges such that they start with current.to for (OffsetRange rangeWithDifferentFrom : rangesToProcess) { // Skip any duplicates of current if (rangeWithDifferentFrom.getTo() > current.getTo()) { rangesWithSameFrom.add(new OffsetRange(current.getTo(), rangeWithDifferentFrom.getTo())); } } rangesToProcess.clear(); } return rval.build(); }
@Test public void testMultipleOverlapsForTheSameRange() { Iterable<OffsetRange> ranges = Arrays.asList( range(0, 4), range(0, 8), range(0, 12), range(0, 12), range(4, 12), range(8, 12), range(0, 4), range(0, 8), range(0, 12), range(0, 12), range(4, 12), range(8, 12)); Map<OffsetRange, Integer> nonOverlappingRangesToNumElementsPerPosition = computeOverlappingRanges(ranges); assertEquals( ImmutableMap.builder().put(range(0, 4), 8).put(range(4, 8), 8).put(range(8, 12), 8).build(), nonOverlappingRangesToNumElementsPerPosition); assertNonEmptyRangesAndPositions(ranges, nonOverlappingRangesToNumElementsPerPosition); }
@Override public Optional<ShardingConditionValue> generate(final BetweenExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) { ConditionValue betweenConditionValue = new ConditionValue(predicate.getBetweenExpr(), params); ConditionValue andConditionValue = new ConditionValue(predicate.getAndExpr(), params); Optional<Comparable<?>> betweenValue = betweenConditionValue.getValue(); Optional<Comparable<?>> andValue = andConditionValue.getValue(); List<Integer> parameterMarkerIndexes = new ArrayList<>(2); betweenConditionValue.getParameterMarkerIndex().ifPresent(parameterMarkerIndexes::add); andConditionValue.getParameterMarkerIndex().ifPresent(parameterMarkerIndexes::add); if (betweenValue.isPresent() && andValue.isPresent()) { return Optional.of(new RangeShardingConditionValue<>(column.getName(), column.getTableName(), SafeNumberOperationUtils.safeClosed(betweenValue.get(), andValue.get()), parameterMarkerIndexes)); } Timestamp timestamp = timestampServiceRule.getTimestamp(); if (!betweenValue.isPresent() && ExpressionConditionUtils.isNowExpression(predicate.getBetweenExpr())) { betweenValue = Optional.of(timestamp); } if (!andValue.isPresent() && ExpressionConditionUtils.isNowExpression(predicate.getAndExpr())) { andValue = Optional.of(timestamp); } if (!betweenValue.isPresent() || !andValue.isPresent()) { return Optional.empty(); } return Optional.of(new RangeShardingConditionValue<>(column.getName(), column.getTableName(), Range.closed(betweenValue.get(), andValue.get()), parameterMarkerIndexes)); }
@Test void assertGenerateConditionValueWithoutParameter() { ColumnSegment left = new ColumnSegment(0, 0, new IdentifierValue("id")); ParameterMarkerExpressionSegment between = new ParameterMarkerExpressionSegment(0, 0, 0); ParameterMarkerExpressionSegment and = new ParameterMarkerExpressionSegment(0, 0, 1); BetweenExpression predicate = new BetweenExpression(0, 0, left, between, and, false); Optional<ShardingConditionValue> actual = generator.generate(predicate, column, new LinkedList<>(), timestampServiceRule); assertFalse(actual.isPresent()); }
public String toLastBitString(long value, int bits) { StringBuilder sb = new StringBuilder(bits); long lastBit = 1L << bits - 1; for (int i = 0; i < bits; i++) { if ((value & lastBit) == 0) sb.append('0'); else sb.append('1'); value <<= 1; } return sb.toString(); }
@Test public void testToLastBitString() { assertEquals("1", bitUtil.toLastBitString(1L, 1)); assertEquals("01", bitUtil.toLastBitString(1L, 2)); assertEquals("001", bitUtil.toLastBitString(1L, 3)); assertEquals("010", bitUtil.toLastBitString(2L, 3)); assertEquals("011", bitUtil.toLastBitString(3L, 3)); }
public static ServiceDescriptor genericService() { return genericServiceDescriptor; }
@Test void genericService() { Assertions.assertNotNull(ServiceDescriptorInternalCache.genericService()); Assertions.assertEquals( GenericService.class, ServiceDescriptorInternalCache.genericService().getServiceInterfaceClass()); }
@PreAcquireNamespaceLock @PutMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{itemId}") public ItemDTO update(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName, @PathVariable("itemId") long itemId, @RequestBody ItemDTO itemDTO) { Item managedEntity = itemService.findOne(itemId); if (managedEntity == null) { throw NotFoundException.itemNotFound(appId, clusterName, namespaceName, itemId); } Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName); // In case someone constructs an attack scenario if (namespace == null || namespace.getId() != managedEntity.getNamespaceId()) { throw BadRequestException.namespaceNotMatch(); } Item entity = BeanUtils.transform(Item.class, itemDTO); ConfigChangeContentBuilder builder = new ConfigChangeContentBuilder(); Item beforeUpdateItem = BeanUtils.transform(Item.class, managedEntity); //protect. only value,type,comment,lastModifiedBy can be modified managedEntity.setType(entity.getType()); managedEntity.setValue(entity.getValue()); managedEntity.setComment(entity.getComment()); managedEntity.setDataChangeLastModifiedBy(entity.getDataChangeLastModifiedBy()); entity = itemService.update(managedEntity); builder.updateItem(beforeUpdateItem, entity); itemDTO = BeanUtils.transform(ItemDTO.class, entity); if (builder.hasContent()) { commitService.createCommit(appId, clusterName, namespaceName, builder.build(), itemDTO.getDataChangeLastModifiedBy()); } return itemDTO; }
@Test @Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testUpdate() { this.testCreate(); String appId = "someAppId"; AppDTO app = restTemplate.getForObject(appBaseUrl(), AppDTO.class, appId); assert app != null; ClusterDTO cluster = restTemplate.getForObject(clusterBaseUrl(), ClusterDTO.class, app.getAppId(), "default"); assert cluster != null; NamespaceDTO namespace = restTemplate.getForObject(namespaceBaseUrl(), NamespaceDTO.class, app.getAppId(), cluster.getName(), "application"); String itemKey = "test-key"; String itemValue = "test-value-updated"; long itemId = itemRepository.findByKey(itemKey, Pageable.ofSize(1)) .getContent() .get(0) .getId(); ItemDTO item = new ItemDTO(itemKey, itemValue, "", 1); item.setDataChangeLastModifiedBy("apollo"); String updateUrl = url( "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{itemId}"); assert namespace != null; restTemplate.put(updateUrl, item, app.getAppId(), cluster.getName(), namespace.getNamespaceName(), itemId); itemRepository.findById(itemId).ifPresent(item1 -> { assertThat(item1.getValue()).isEqualTo(itemValue); assertThat(item1.getKey()).isEqualTo(itemKey); }); List<Commit> commitList = commitRepository.findByAppIdAndClusterNameAndNamespaceNameOrderByIdDesc(app.getAppId(), cluster.getName(), namespace.getNamespaceName(), Pageable.ofSize(10)); assertThat(commitList).hasSize(2); }
@Override public Set<String> validSiteKeys(final Action action) { final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration(); if (!config.isAllowHCaptcha()) { logger.warn("Received request to verify an hCaptcha, but hCaptcha is not enabled"); return Collections.emptySet(); } return Optional .ofNullable(config.getHCaptchaSiteKeys().get(action)) .orElse(Collections.emptySet()); }
@Test public void badSiteKey() throws IOException { final HCaptchaClient hc = new HCaptchaClient("fake", null, mockConfig(true, 0.5)); for (Action action : Action.values()) { assertThat(hc.validSiteKeys(action)).contains(SITE_KEY); assertThat(hc.validSiteKeys(action)).doesNotContain("invalid"); } }
private static ClientAuthenticationMethod getClientAuthenticationMethod( List<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> metadataAuthMethods) { if (metadataAuthMethods == null || metadataAuthMethods .contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) { // If null, the default includes client_secret_basic return ClientAuthenticationMethod.CLIENT_SECRET_BASIC; } if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_POST)) { return ClientAuthenticationMethod.CLIENT_SECRET_POST; } if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.NONE)) { return ClientAuthenticationMethod.NONE; } return null; }
@Test public void buildWhenPasswordGrantClientAuthenticationMethodNotProvidedThenDefaultToBasic() { // @formatter:off ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID) .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.PASSWORD) .tokenUri(TOKEN_URI) .build(); // @formatter:on assertThat(clientRegistration.getClientAuthenticationMethod()) .isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC); }
public static PrivateKey parsePrivateKey(String pemRepresentation, String passPhrase) throws IOException { if (pemRepresentation == null || pemRepresentation.trim().isEmpty()) { throw new IllegalArgumentException("Argument 'pemRepresentation' cannot be null or an empty String."); } ByteArrayInputStream input = new ByteArrayInputStream(pemRepresentation.getBytes(StandardCharsets.UTF_8)); return parsePrivateKey(input, passPhrase); }
@Test public void testParsePrivateKey() throws Exception { // Setup fixture. try ( final InputStream stream = getClass().getResourceAsStream( "/privatekey.pem" ) ) { // Execute system under test. final PrivateKey result = CertificateManager.parsePrivateKey( stream, "" ); // Verify result. assertNotNull( result ); } }
@Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DescriptiveUrlBag(); if(file.attributes().getLink() != DescriptiveUrl.EMPTY) { list.add(file.attributes().getLink()); } list.add(new DescriptiveUrl(URI.create(String.format("%s%s", new HostUrlProvider().withUsername(false).get(host), URIEncoder.encode(file.getAbsolute()))), DescriptiveUrl.Type.provider, MessageFormat.format(LocaleFactory.localizedString("{0} URL"), host.getProtocol().getScheme().toString().toUpperCase(Locale.ROOT)))); list.addAll(new HostWebUrlProvider(host).toUrl(file)); return list; }
@Test public void testRelativeDocumentRoot() { Host host = new Host(new TestProtocol(), "localhost"); host.setDefaultPath("public_html"); Path path = new Path( "/usr/home/dkocher/public_html/file", EnumSet.of(Path.Type.directory)); assertEquals("http://localhost/file", new DefaultUrlProvider(host).toUrl(path).find(DescriptiveUrl.Type.http).getUrl()); host.setWebURL("http://127.0.0.1/~dkocher"); assertEquals("http://127.0.0.1/~dkocher/file", new DefaultUrlProvider(host).toUrl(path).find(DescriptiveUrl.Type.http).getUrl()); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { if(!session.getClient().changeWorkingDirectory(directory.getAbsolute())) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } if(!session.getClient().setFileType(FTPClient.ASCII_FILE_TYPE)) { // Set transfer type for traditional data socket file listings. The data transfer is over the // data connection in type ASCII or type EBCDIC. throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } final List<String> list = new DataConnectionActionExecutor(session).data(new DataConnectionAction<List<String>>() { @Override public List<String> execute() throws BackgroundException { try { return session.getClient().list(command.getCommand(), command.getArg()); } catch(IOException e) { throw new FTPExceptionMappingService().map(e); } } }); return reader.read(directory, list); } catch(IOException e) { throw new FTPExceptionMappingService().map("Listing directory {0} failed", e, directory); } }
@Test public void testListDefault() throws Exception { final ListService list = new FTPDefaultListService(session, new CompositeFileEntryParser(Collections.singletonList(new UnixFTPEntryParser())), FTPListService.Command.list); final Path directory = new FTPWorkdirService(session).find(); final Path file = new Path(directory, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new FTPTouchFeature(session).touch(file, new TransferStatus()); assertTrue(list.list(directory, new DisabledListProgressListener()).contains(file)); new FTPDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name -> { ParamDefinition paramToMerge = paramsToMerge.get(name); if (paramToMerge == null) { return; } if (paramToMerge.getType() == ParamType.MAP && paramToMerge.isLiteral()) { Map<String, ParamDefinition> baseMap = mapValueOrEmpty(params, name); Map<String, ParamDefinition> toMergeMap = mapValueOrEmpty(paramsToMerge, name); mergeParams( baseMap, toMergeMap, MergeContext.copyWithParentMode( context, params.getOrDefault(name, paramToMerge).getMode())); params.put( name, buildMergedParamDefinition( name, paramToMerge, params.get(name), context, baseMap)); } else if (paramToMerge.getType() == ParamType.STRING_MAP && paramToMerge.isLiteral()) { Map<String, String> baseMap = stringMapValueOrEmpty(params, name); Map<String, String> toMergeMap = stringMapValueOrEmpty(paramsToMerge, name); baseMap.putAll(toMergeMap); params.put( name, buildMergedParamDefinition( name, paramToMerge, params.get(name), context, baseMap)); } else { params.put( name, buildMergedParamDefinition( name, paramToMerge, params.get(name), context, paramToMerge.getValue())); } }); }
@Test public void testMergeCannotModifySource() { // Don't allow to modify the source AssertHelper.assertThrows( "Should not allow updating source", MaestroValidationException.class, "Cannot modify source for parameter [tomerge]", new Runnable() { @SneakyThrows @Override public void run() { Map<String, ParamDefinition> allParams = parseParamDefMap("{'tomerge': {'type': 'LONG','value': 2}}"); Map<String, ParamDefinition> paramsToMerge = parseParamDefMap("{'tomerge': {'type': 'LONG', 'value': 3, 'source': 'SYSTEM'}}"); ParamsMergeHelper.mergeParams(allParams, paramsToMerge, definitionContext); } }); }
private <T> RestResponse<T> get(final String path, final Class<T> type) { return executeRequestSync(HttpMethod.GET, path, null, r -> deserialize(r.getBody(), type), Optional.empty()); }
@Test public void shouldPostQueryRequest_chunkHandler_partialMessage() { ksqlTarget = new KsqlTarget(httpClient, socketAddress, localProperties, authHeader, HOST, Collections.emptyMap(), RequestOptions.DEFAULT_TIMEOUT); executor.submit(this::expectPostQueryRequestChunkHandler); assertThatEventually(requestStarted::get, is(true)); handlerCaptor.getValue().handle(Buffer.buffer("{\"row\": {\"columns\": [1.0, 12.1]}},\n")); handlerCaptor.getValue().handle(Buffer.buffer("{\"row\": {\"columns\"")); handlerCaptor.getValue().handle(Buffer.buffer(": [5.0, 10.5]}},\n")); endCaptor.getValue().handle(null); closeConnection.complete(null); assertThatEventually(response::get, notNullValue()); assertThat(response.get().getResponse(), is (2)); assertThat(rows.size(), is (2)); }
public Set<ExpiredMetadataInfo> getExpiredMetadataInfos() { return expiredMetadataInfos; }
@Test void testGetExpiredMetadataInfos() { Set<ExpiredMetadataInfo> expiredMetadataInfos = namingMetadataManager.getExpiredMetadataInfos(); assertNotNull(expiredMetadataInfos); }
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = DODGY_PROTECT_PATTERN.matcher(message); Matcher dodgyBreakMatcher = DODGY_BREAK_PATTERN.matcher(message); Matcher bindingNecklaceCheckMatcher = BINDING_CHECK_PATTERN.matcher(message); Matcher bindingNecklaceUsedMatcher = BINDING_USED_PATTERN.matcher(message); Matcher ringOfForgingCheckMatcher = RING_OF_FORGING_CHECK_PATTERN.matcher(message); Matcher amuletOfChemistryCheckMatcher = AMULET_OF_CHEMISTRY_CHECK_PATTERN.matcher(message); Matcher amuletOfChemistryUsedMatcher = AMULET_OF_CHEMISTRY_USED_PATTERN.matcher(message); Matcher amuletOfChemistryBreakMatcher = AMULET_OF_CHEMISTRY_BREAK_PATTERN.matcher(message); Matcher amuletOfBountyCheckMatcher = AMULET_OF_BOUNTY_CHECK_PATTERN.matcher(message); Matcher amuletOfBountyUsedMatcher = AMULET_OF_BOUNTY_USED_PATTERN.matcher(message); Matcher chronicleAddMatcher = CHRONICLE_ADD_PATTERN.matcher(message); Matcher chronicleUseAndCheckMatcher = CHRONICLE_USE_AND_CHECK_PATTERN.matcher(message); Matcher slaughterActivateMatcher = BRACELET_OF_SLAUGHTER_ACTIVATE_PATTERN.matcher(message); Matcher slaughterCheckMatcher = BRACELET_OF_SLAUGHTER_CHECK_PATTERN.matcher(message); Matcher expeditiousActivateMatcher = EXPEDITIOUS_BRACELET_ACTIVATE_PATTERN.matcher(message); Matcher expeditiousCheckMatcher = EXPEDITIOUS_BRACELET_CHECK_PATTERN.matcher(message); Matcher bloodEssenceCheckMatcher = BLOOD_ESSENCE_CHECK_PATTERN.matcher(message); Matcher bloodEssenceExtractMatcher = BLOOD_ESSENCE_EXTRACT_PATTERN.matcher(message); Matcher braceletOfClayCheckMatcher = BRACELET_OF_CLAY_CHECK_PATTERN.matcher(message); if (message.contains(RING_OF_RECOIL_BREAK_MESSAGE)) { notifier.notify(config.recoilNotification(), "Your Ring of Recoil has shattered"); } else if (dodgyBreakMatcher.find()) { notifier.notify(config.dodgyNotification(), "Your dodgy necklace has crumbled to dust."); updateDodgyNecklaceCharges(MAX_DODGY_CHARGES); } else if (dodgyCheckMatcher.find()) { updateDodgyNecklaceCharges(Integer.parseInt(dodgyCheckMatcher.group(1))); } else if (dodgyProtectMatcher.find()) { updateDodgyNecklaceCharges(Integer.parseInt(dodgyProtectMatcher.group(1))); } else if (amuletOfChemistryCheckMatcher.find()) { updateAmuletOfChemistryCharges(Integer.parseInt(amuletOfChemistryCheckMatcher.group(1))); } else if (amuletOfChemistryUsedMatcher.find()) { final String match = amuletOfChemistryUsedMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateAmuletOfChemistryCharges(charges); } else if (amuletOfChemistryBreakMatcher.find()) { notifier.notify(config.amuletOfChemistryNotification(), "Your amulet of chemistry has crumbled to dust."); updateAmuletOfChemistryCharges(MAX_AMULET_OF_CHEMISTRY_CHARGES); } else if (amuletOfBountyCheckMatcher.find()) { updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyCheckMatcher.group(1))); } else if (amuletOfBountyUsedMatcher.find()) { updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyUsedMatcher.group(1))); } else if (message.equals(AMULET_OF_BOUNTY_BREAK_TEXT)) { updateAmuletOfBountyCharges(MAX_AMULET_OF_BOUNTY_CHARGES); } else if (message.contains(BINDING_BREAK_TEXT)) { notifier.notify(config.bindingNotification(), BINDING_BREAK_TEXT); // This chat message triggers before the used message so add 1 to the max charges to ensure proper sync updateBindingNecklaceCharges(MAX_BINDING_CHARGES + 1); } else if (bindingNecklaceUsedMatcher.find()) { final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); if (equipment.contains(ItemID.BINDING_NECKLACE)) { updateBindingNecklaceCharges(getItemCharges(ItemChargeConfig.KEY_BINDING_NECKLACE) - 1); } } else if (bindingNecklaceCheckMatcher.find()) { final String match = bindingNecklaceCheckMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateBindingNecklaceCharges(charges); } else if (ringOfForgingCheckMatcher.find()) { final String match = ringOfForgingCheckMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateRingOfForgingCharges(charges); } else if (message.equals(RING_OF_FORGING_USED_TEXT) || message.equals(RING_OF_FORGING_VARROCK_PLATEBODY)) { final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY); final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); // Determine if the player smelted with a Ring of Forging equipped. if (equipment == null) { return; } if (equipment.contains(ItemID.RING_OF_FORGING) && (message.equals(RING_OF_FORGING_USED_TEXT) || inventory.count(ItemID.IRON_ORE) > 1)) { int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_RING_OF_FORGING) - 1, 0, MAX_RING_OF_FORGING_CHARGES); updateRingOfForgingCharges(charges); } } else if (message.equals(RING_OF_FORGING_BREAK_TEXT)) { notifier.notify(config.ringOfForgingNotification(), "Your ring of forging has melted."); // This chat message triggers before the used message so add 1 to the max charges to ensure proper sync updateRingOfForgingCharges(MAX_RING_OF_FORGING_CHARGES + 1); } else if (chronicleAddMatcher.find()) { final String match = chronicleAddMatcher.group(1); if (match.equals("one")) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1); } else { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(match)); } } else if (chronicleUseAndCheckMatcher.find()) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(chronicleUseAndCheckMatcher.group(1))); } else if (message.equals(CHRONICLE_ONE_CHARGE_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1); } else if (message.equals(CHRONICLE_EMPTY_TEXT) || message.equals(CHRONICLE_NO_CHARGES_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 0); } else if (message.equals(CHRONICLE_FULL_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1000); } else if (slaughterActivateMatcher.find()) { final String found = slaughterActivateMatcher.group(1); if (found == null) { updateBraceletOfSlaughterCharges(MAX_SLAYER_BRACELET_CHARGES); notifier.notify(config.slaughterNotification(), BRACELET_OF_SLAUGHTER_BREAK_TEXT); } else { updateBraceletOfSlaughterCharges(Integer.parseInt(found)); } } else if (slaughterCheckMatcher.find()) { updateBraceletOfSlaughterCharges(Integer.parseInt(slaughterCheckMatcher.group(1))); } else if (expeditiousActivateMatcher.find()) { final String found = expeditiousActivateMatcher.group(1); if (found == null) { updateExpeditiousBraceletCharges(MAX_SLAYER_BRACELET_CHARGES); notifier.notify(config.expeditiousNotification(), EXPEDITIOUS_BRACELET_BREAK_TEXT); } else { updateExpeditiousBraceletCharges(Integer.parseInt(found)); } } else if (expeditiousCheckMatcher.find()) { updateExpeditiousBraceletCharges(Integer.parseInt(expeditiousCheckMatcher.group(1))); } else if (bloodEssenceCheckMatcher.find()) { updateBloodEssenceCharges(Integer.parseInt(bloodEssenceCheckMatcher.group(1))); } else if (bloodEssenceExtractMatcher.find()) { updateBloodEssenceCharges(getItemCharges(ItemChargeConfig.KEY_BLOOD_ESSENCE) - Integer.parseInt(bloodEssenceExtractMatcher.group(1))); } else if (message.contains(BLOOD_ESSENCE_ACTIVATE_TEXT)) { updateBloodEssenceCharges(MAX_BLOOD_ESSENCE_CHARGES); } else if (braceletOfClayCheckMatcher.find()) { updateBraceletOfClayCharges(Integer.parseInt(braceletOfClayCheckMatcher.group(1))); } else if (message.equals(BRACELET_OF_CLAY_USE_TEXT) || message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN)) { final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); // Determine if the player mined with a Bracelet of Clay equipped. if (equipment != null && equipment.contains(ItemID.BRACELET_OF_CLAY)) { final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY); // Charge is not used if only 1 inventory slot is available when mining in Prifddinas boolean ignore = inventory != null && inventory.count() == 27 && message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN); if (!ignore) { int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_BRACELET_OF_CLAY) - 1, 0, MAX_BRACELET_OF_CLAY_CHARGES); updateBraceletOfClayCharges(charges); } } } else if (message.equals(BRACELET_OF_CLAY_BREAK_TEXT)) { notifier.notify(config.braceletOfClayNotification(), "Your bracelet of clay has crumbled to dust"); updateBraceletOfClayCharges(MAX_BRACELET_OF_CLAY_CHARGES); } } }
@Test public void testSlaughterCheck1() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_BRACELET_OF_SLAUGHTER_1, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BRACELET_OF_SLAUGHTER, 1); }
public void resolveAssertionConsumerService(AuthenticationRequest authenticationRequest) throws SamlValidationException { // set URL if set in authnRequest final String authnAcsURL = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceURL(); if (authnAcsURL != null) { authenticationRequest.setAssertionConsumerURL(authnAcsURL); return; } // search url from metadata endpoints final Integer authnAcsIdx = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceIndex(); List<Endpoint> endpoints = authenticationRequest.getConnectionEntity().getRoleDescriptors().get(0).getEndpoints(AssertionConsumerService.DEFAULT_ELEMENT_NAME); if (endpoints.isEmpty()) { throw new SamlValidationException("Authentication: Assertion Consumer Service not found in metadata"); } if (authnAcsIdx != null && endpoints.size() <= authnAcsIdx) { throw new SamlValidationException("Authentication: Assertion Consumer Index is out of bounds"); } // TODO: check if this statement is correct if (endpoints.size() == 1) { authenticationRequest.setAssertionConsumerURL(endpoints.get(0).getLocation()); return; } if(authnAcsIdx == null) { AssertionConsumerService defaultAcs = endpoints.stream() .filter(e -> e instanceof AssertionConsumerService) .map(acs -> (AssertionConsumerService) acs) .filter(IndexedEndpoint::isDefault) .findAny() .orElse(null); if (defaultAcs == null) { throw new SamlValidationException("Authentication: There is no default AssertionConsumerService"); } authenticationRequest.setAssertionConsumerURL(defaultAcs.getLocation()); return; } authenticationRequest.setAssertionConsumerURL(endpoints.get(authnAcsIdx).getLocation()); }
@Test void resolveAcsUrlWithoutIndexInSingleAcsMetadata() throws SamlValidationException { AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class); AuthenticationRequest authenticationRequest = new AuthenticationRequest(); authenticationRequest.setAuthnRequest(authnRequest); authenticationRequest.setConnectionEntity(MetadataParser.readMetadata(stubsSingleAcsMetadataFile, CONNECTION_ENTITY_ID)); assertionConsumerServiceUrlService.resolveAssertionConsumerService(authenticationRequest); assertEquals("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", authenticationRequest.getAssertionConsumerURL()); }
@Override protected String convertFromString(final String value) throws ConversionException { final Path path = Paths.get(value); if (path.getParent() != null) { throw new ConversionException( String.format("%s must be a filename only (%s)", KEY, path)); } return value; }
@Test void testJarIdWithParentDir() throws Exception { assertThatThrownBy(() -> jarIdPathParameter.convertFromString("../../test.jar")) .isInstanceOf(ConversionException.class); }
public BranchesList getBranches(String serverUrl, String token, String projectSlug, String repositorySlug) { HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/projects/%s/repos/%s/branches", projectSlug, repositorySlug)); return doGet(token, url, body -> buildGson().fromJson(body, BranchesList.class)); }
@Test public void getBranches_given0Branches_returnEmptyList() { String bodyWith0Branches = "{\n" + " \"size\": 0,\n" + " \"limit\": 25,\n" + " \"isLastPage\": true,\n" + " \"values\": [],\n" + " \"start\": 0\n" + "}"; server.enqueue(new MockResponse() .setHeader("Content-Type", "application/json;charset=UTF-8") .setBody(bodyWith0Branches)); BranchesList branches = underTest.getBranches(server.url("/").toString(), "token", "projectSlug", "repoSlug"); assertThat(branches.getBranches()).isEmpty(); }
@Override public URL select(List<URL> urls, String serviceId, String tag, String requestKey) { URL url = null; if (urls.size() > 1) { String key = tag == null ? serviceId : serviceId + "|" + tag; url = doSelect(urls, key); } else if (urls.size() == 1) { url = urls.get(0); } return url; }
@Test public void testSelect() throws Exception { List<URL> urls = new ArrayList<>(); urls.add(new URLImpl("http", "127.0.0.1", 8081, "v1", new HashMap<String, String>())); urls.add(new URLImpl("http", "127.0.0.1", 8082, "v1", new HashMap<String, String>())); urls.add(new URLImpl("http", "127.0.0.1", 8083, "v1", new HashMap<String, String>())); urls.add(new URLImpl("http", "127.0.0.1", 8084, "v1", new HashMap<String, String>())); while(true) { URL url = loadBalance.select(urls, "serviceId", "tag", null); if(url.getPort() == 8081) break; } URL url = loadBalance.select(urls, "serviceId", "tag", null); Assert.assertEquals(url, URLImpl.valueOf("http://127.0.0.1:8082/v1")); url = loadBalance.select(urls, "serviceId", "tag", null); Assert.assertEquals(url, URLImpl.valueOf("http://127.0.0.1:8083/v1")); url = loadBalance.select(urls, "serviceId", "tag", null); Assert.assertEquals(url, URLImpl.valueOf("http://127.0.0.1:8084/v1")); url = loadBalance.select(urls, "serviceId", "tag", null); Assert.assertEquals(url, URLImpl.valueOf("http://127.0.0.1:8081/v1")); url = loadBalance.select(urls, "serviceId", "tag", null); Assert.assertEquals(url, URLImpl.valueOf("http://127.0.0.1:8082/v1")); }
protected String getUserDnForSearch(String userName) { if (userSearchAttributeName == null || userSearchAttributeName.isEmpty()) { // memberAttributeValuePrefix and memberAttributeValueSuffix // were computed from memberAttributeValueTemplate return memberDn(userName); } else { return getUserDn(userName); } }
@Test void getUserDnForSearch() { LdapRealm realm = new LdapRealm(); realm.setUserSearchAttributeName("uid"); assertEquals("foo", realm.getUserDnForSearch("foo")); // using a template realm.setUserSearchAttributeName(null); realm.setMemberAttributeValueTemplate("cn={0},ou=people,dc=hadoop,dc=apache"); assertEquals("cn=foo,ou=people,dc=hadoop,dc=apache", realm.getUserDnForSearch("foo")); }
@Override public JwtAuthenticationToken convert(Jwt jwt) { Map<String, Map<String, Collection<String>>> resourceAccess = jwt .getClaim(KeycloakJwtToken.RESOURCE_ACCESS_TOKEN_CLAIM); if (resourceAccess != null) { Map<String, Collection<String>> microcksResource = resourceAccess.get(KeycloakJwtToken.MICROCKS_APP_RESOURCE); if (microcksResource != null) { Collection<String> roles = microcksResource.get("roles"); log.trace("JWT extracted roles for microcks-app: {}", roles); var grantedAuthorities = roles.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).toList(); return new JwtAuthenticationToken(jwt, grantedAuthorities); } } return new JwtAuthenticationToken(jwt, Collections.emptyList()); }
@Test void testConvert() { MicrocksJwtConverter converter = new MicrocksJwtConverter(); Jwt jwt = null; try { JWT parsedJwt = JWTParser.parse(jwtBearer); jwt = createJwt(jwtBearer, parsedJwt); } catch (Exception e) { fail("Parsing Jwt bearer should not fail"); } // Convert and assert granted authorities. JwtAuthenticationToken authenticationToken = converter.convert(jwt); assertTrue(authenticationToken.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_user"))); assertTrue(authenticationToken.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_manager"))); }
public void initializeSession(AuthenticationRequest authenticationRequest, SAMLBindingContext bindingContext) throws SamlSessionException, SharedServiceClientException { final String httpSessionId = authenticationRequest.getRequest().getSession().getId(); if (authenticationRequest.getFederationName() != null) { findOrInitializeFederationSession(authenticationRequest, httpSessionId); } findOrInitializeSamlSession(authenticationRequest, httpSessionId, bindingContext); }
@Test public void findSSOSessionForceAuthnInitializeTest() throws SamlSessionException, SharedServiceClientException { authnRequest.setForceAuthn(TRUE); authenticationRequest.setAuthnRequest(authnRequest); samlSessionService.initializeSession(authenticationRequest, bindingContext); assertFalse(authenticationRequest.isValidSsoSession()); }
@Override public ObjectNode encode(MaintenanceDomain md, CodecContext context) { checkNotNull(md, "Maintenance Domain cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(MD_NAME, md.mdId().toString()) .put(MD_NAME_TYPE, md.mdId().nameType().name()) .put(MD_LEVEL, md.mdLevel().name()); if (md.mdNumericId() > 0) { result = result.put(MD_NUMERIC_ID, md.mdNumericId()); } result.set("maList", new MaintenanceAssociationCodec() .encode(md.maintenanceAssociationList(), context)); return result; }
@Test public void testEncodeMd1() throws CfmConfigException { MaintenanceDomain md1 = DefaultMaintenanceDomain.builder(MDID1_CHAR) .mdLevel(MaintenanceDomain.MdLevel.LEVEL1) .mdNumericId((short) 1) .build(); ObjectNode node = mapper.createObjectNode(); node.set("md", context.codec(MaintenanceDomain.class).encode(md1, context)); assertEquals("{\"md\":{" + "\"mdName\":\"test-1\"," + "\"mdNameType\":\"CHARACTERSTRING\"," + "\"mdLevel\":\"LEVEL1\"," + "\"mdNumericId\":1," + "\"maList\":[]}}", node.toString()); }
@Override public Map<String, InterpreterClient> restore() throws IOException { Map<String, InterpreterClient> clients = new HashMap<>(); List<Path> paths = fs.list(new Path(recoveryDir + "/*.recovery")); for (Path path : paths) { String fileName = path.getName(); String interpreterSettingName = fileName.substring(0, fileName.length() - ".recovery".length()); String recoveryContent = fs.readFile(path); clients.putAll(RecoveryUtils.restoreFromRecoveryData( recoveryContent, interpreterSettingName, interpreterSettingManager, zConf)); } return clients; }
@Test void testSingleInterpreterProcess() throws InterpreterException, IOException { InterpreterSetting interpreterSetting = interpreterSettingManager.getByName("test"); interpreterSetting.getOption().setPerUser(InterpreterOption.SHARED); Interpreter interpreter1 = interpreterSetting.getDefaultInterpreter("user1", note1Id); RemoteInterpreter remoteInterpreter1 = (RemoteInterpreter) interpreter1; InterpreterContext context1 = InterpreterContext.builder() .setNoteId("noteId") .setParagraphId("paragraphId") .build(); remoteInterpreter1.interpret("hello", context1); assertEquals(1, interpreterSettingManager.getRecoveryStorage().restore().size()); interpreterSetting.close(); assertEquals(0, interpreterSettingManager.getRecoveryStorage().restore().size()); }
public static <T> T toObj(byte[] json, Class<T> cls) { try { return mapper.readValue(json, cls); } catch (Exception e) { throw new NacosDeserializationException(cls, e); } }
@Test void testToObject4() { assertThrows(Exception.class, () -> { JacksonUtils.toObj("{not_A}Json:String}".getBytes(), TypeUtils.parameterize(Map.class, String.class, String.class)); }); }
public void resetPositionsIfNeeded() { Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp(); if (offsetResetTimestamps.isEmpty()) return; resetPositionsAsync(offsetResetTimestamps); }
@Test public void testFetchOffsetErrors() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.LATEST); // Fail with OFFSET_NOT_AVAILABLE client.prepareResponse(listOffsetRequestMatcher(ListOffsetsRequest.LATEST_TIMESTAMP, validLeaderEpoch), listOffsetResponse(Errors.OFFSET_NOT_AVAILABLE, 1L, 5L), false); offsetFetcher.resetPositionsIfNeeded(); consumerClient.pollNoWakeup(); assertFalse(subscriptions.hasValidPosition(tp0)); assertTrue(subscriptions.isOffsetResetNeeded(tp0)); assertFalse(subscriptions.isFetchable(tp0)); // Fail with LEADER_NOT_AVAILABLE time.sleep(retryBackoffMs); client.prepareResponse(listOffsetRequestMatcher(ListOffsetsRequest.LATEST_TIMESTAMP, validLeaderEpoch), listOffsetResponse(Errors.LEADER_NOT_AVAILABLE, 1L, 5L), false); offsetFetcher.resetPositionsIfNeeded(); consumerClient.pollNoWakeup(); assertFalse(subscriptions.hasValidPosition(tp0)); assertTrue(subscriptions.isOffsetResetNeeded(tp0)); assertFalse(subscriptions.isFetchable(tp0)); // Back to normal time.sleep(retryBackoffMs); client.prepareResponse(listOffsetRequestMatcher(ListOffsetsRequest.LATEST_TIMESTAMP), listOffsetResponse(Errors.NONE, 1L, 5L), false); offsetFetcher.resetPositionsIfNeeded(); consumerClient.pollNoWakeup(); assertTrue(subscriptions.hasValidPosition(tp0)); assertFalse(subscriptions.isOffsetResetNeeded(tp0)); assertTrue(subscriptions.isFetchable(tp0)); assertEquals(subscriptions.position(tp0).offset, 5L); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void pinChatMessage() { BaseResponse response = bot.execute(new PinChatMessage(groupId, 18).disableNotification(false)); if (!response.isOk()) { assertEquals(400, response.errorCode()); assertEquals("Bad Request: CHAT_NOT_MODIFIED", response.description()); } }
@Override public <T_OTHER, OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> connectAndProcess( NonKeyedPartitionStream<T_OTHER> other, TwoInputNonBroadcastStreamProcessFunction<T, T_OTHER, OUT> processFunction) { validateStates( processFunction.usesStates(), new HashSet<>( Arrays.asList( StateDeclaration.RedistributionMode.NONE, StateDeclaration.RedistributionMode.IDENTICAL))); TypeInformation<OUT> outTypeInfo = StreamUtils.getOutputTypeForTwoInputNonBroadcastProcessFunction( processFunction, getType(), ((NonKeyedPartitionStreamImpl<T_OTHER>) other).getType()); TwoInputNonBroadcastProcessOperator<T, T_OTHER, OUT> processOperator = new TwoInputNonBroadcastProcessOperator<>(processFunction); Transformation<OUT> outTransformation = StreamUtils.getTwoInputTransformation( "TwoInput-Process", this, (NonKeyedPartitionStreamImpl<T_OTHER>) other, outTypeInfo, processOperator); environment.addOperator(outTransformation); return StreamUtils.wrapWithConfigureHandle( new NonKeyedPartitionStreamImpl<>(environment, outTransformation)); }
@Test void testStateErrorWithConnectNonKeyedStream() throws Exception { ExecutionEnvironmentImpl env = StreamTestUtils.getEnv(); NonKeyedPartitionStreamImpl<Integer> stream = new NonKeyedPartitionStreamImpl<>( env, new TestingTransformation<>("t1", Types.INT, 1)); for (StateDeclaration stateDeclaration1 : Arrays.asList(modeNoneStateDeclaration, modeIdenticalStateDeclaration)) { for (StateDeclaration stateDeclaration2 : Arrays.asList(modeNoneStateDeclaration, modeIdenticalStateDeclaration)) { assertThatThrownBy( () -> stream.connectAndProcess( new NonKeyedPartitionStreamImpl<>( env, new TestingTransformation<>( "t2", Types.LONG, 1)), new StreamTestUtils .NoOpTwoInputNonBroadcastStreamProcessFunction( new HashSet<>( Arrays.asList( stateDeclaration1, stateDeclaration2))))) .isInstanceOf(IllegalRedistributionModeException.class); } } }
@Override public OAuth2AccessTokenDO getAccessToken(String accessToken) { // 优先从 Redis 中获取 OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenRedisDAO.get(accessToken); if (accessTokenDO != null) { return accessTokenDO; } // 获取不到,从 MySQL 中获取 accessTokenDO = oauth2AccessTokenMapper.selectByAccessToken(accessToken); // 如果在 MySQL 存在,则往 Redis 中写入 if (accessTokenDO != null && !DateUtils.isExpired(accessTokenDO.getExpiresTime())) { oauth2AccessTokenRedisDAO.set(accessTokenDO); } return accessTokenDO; }
@Test public void testGetAccessToken() { // mock 数据(访问令牌) OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class) .setExpiresTime(LocalDateTime.now().plusDays(1)); oauth2AccessTokenMapper.insert(accessTokenDO); // 准备参数 String accessToken = accessTokenDO.getAccessToken(); // 调用 OAuth2AccessTokenDO result = oauth2TokenService.getAccessToken(accessToken); // 断言 assertPojoEquals(accessTokenDO, result, "createTime", "updateTime", "deleted", "creator", "updater"); assertPojoEquals(accessTokenDO, oauth2AccessTokenRedisDAO.get(accessToken), "createTime", "updateTime", "deleted", "creator", "updater"); }
public static String substitute( final String string, final Map<String, String> valueMap ) { return StringSubstitutor.replace( string, valueMap.entrySet().stream() .collect(Collectors.toMap(e -> e.getKey(), e -> sanitize(e.getValue()))) ); }
@Test public void shouldSubstituteVariablesInString() { // Given final Map<String, String> variablesMap = new ImmutableMap.Builder<String, String>() {{ put("event", "birthday"); }}.build(); // When final String substituted = VariableSubstitutor.substitute("Happy ${event} to you!", variablesMap); // Then assertThat(substituted, equalTo("Happy birthday to you!")); }
public Range<PartitionKey> handleNewSinglePartitionDesc(Map<ColumnId, Column> schema, SingleRangePartitionDesc desc, long partitionId, boolean isTemp) throws DdlException { Range<PartitionKey> range; try { range = checkAndCreateRange(schema, desc, isTemp); setRangeInternal(partitionId, isTemp, range); } catch (IllegalArgumentException e) { // Range.closedOpen may throw this if (lower > upper) throw new DdlException("Invalid key range: " + e.getMessage()); } idToDataProperty.put(partitionId, desc.getPartitionDataProperty()); idToReplicationNum.put(partitionId, desc.getReplicationNum()); idToInMemory.put(partitionId, desc.isInMemory()); idToStorageCacheInfo.put(partitionId, desc.getDataCacheInfo()); return range; }
@Test(expected = DdlException.class) public void testFixedRange5() throws DdlException, AnalysisException { //add columns int columns = 2; Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", ""); Column k2 = new Column("k2", new ScalarType(PrimitiveType.BIGINT), true, null, "", ""); partitionColumns.add(k1); partitionColumns.add(k2); //add RangePartitionDescs PartitionKeyDesc p1 = new PartitionKeyDesc( Lists.newArrayList(new PartitionValue("20190101"), new PartitionValue("100")), Lists.newArrayList(new PartitionValue("20190101"), new PartitionValue("100"))); singleRangePartitionDescs.add(new SingleRangePartitionDesc(false, "p1", p1, null)); partitionInfo = new RangePartitionInfo(partitionColumns); for (SingleRangePartitionDesc singleRangePartitionDesc : singleRangePartitionDescs) { singleRangePartitionDesc.analyze(columns, null); partitionInfo.handleNewSinglePartitionDesc(MetaUtils.buildIdToColumn(partitionColumns), singleRangePartitionDesc, 20000L, false); } }
public static boolean hasNested(LogicalType logicalType, Predicate<LogicalType> predicate) { final NestedTypeSearcher typeSearcher = new NestedTypeSearcher(predicate); return logicalType.accept(typeSearcher).isPresent(); }
@Test void testHasNested() { final DataType dataType = ROW(FIELD("f0", INT()), FIELD("f1", STRING())); assertThat( LogicalTypeChecks.hasNested( dataType.getLogicalType(), t -> t.is(LogicalTypeRoot.VARCHAR))) .isTrue(); assertThat( LogicalTypeChecks.hasNested( dataType.getLogicalType(), t -> t.is(LogicalTypeRoot.ROW))) .isTrue(); assertThat( LogicalTypeChecks.hasNested( dataType.getLogicalType(), t -> t.is(LogicalTypeRoot.BOOLEAN))) .isFalse(); }
public static Resource multiplyAndRoundDown(Resource lhs, double by) { return multiplyAndRound(clone(lhs), by, RoundingDirection.DOWN); }
@Test void testMultiplyAndRoundDown() { assertEquals(createResource(4, 1), multiplyAndRoundDown(createResource(3, 1), 1.5), INVALID_RESOURCE_MSG); assertEquals(createResource(4, 1, 0), multiplyAndRoundDown(createResource(3, 1), 1.5), INVALID_RESOURCE_MSG); assertEquals(createResource(1, 4), multiplyAndRoundDown(createResource(1, 3), 1.5), INVALID_RESOURCE_MSG); assertEquals(createResource(1, 4, 0), multiplyAndRoundDown(createResource(1, 3), 1.5), INVALID_RESOURCE_MSG); assertEquals(createResource(7, 7, 0), multiplyAndRoundDown(createResource(3, 3, 0), 2.5), INVALID_RESOURCE_MSG); assertEquals(createResource(2, 2, 7), multiplyAndRoundDown(createResource(1, 1, 3), 2.5), INVALID_RESOURCE_MSG); }
@Override public boolean remove(long key) { return super.remove0(key, 0); }
@Test(expected = AssertionError.class) @RequireAssertEnabled public void testRemove_whenDisposed() { hsa.dispose(); hsa.remove(1); }
public static BigInteger decodeQuantity(String value) { if (isLongValue(value)) { return BigInteger.valueOf(Long.parseLong(value)); } if (!isValidHexQuantity(value)) { throw new MessageDecodingException("Value must be in format 0x[0-9a-fA-F]+"); } try { return parsePaddedNumberHex(value); } catch (NumberFormatException e) { throw new MessageDecodingException("Negative ", e); } }
@Test public void testQuantityDecodeLong() { assertEquals(Numeric.decodeQuantity("1234"), BigInteger.valueOf(1234)); }
public static <T> Write<T> write() { return new Write<>(); }
@Test public void testWriteWithBackoff() throws Exception { String tableName = DatabaseTestHelper.getTestTableName("UT_WRITE_BACKOFF"); DatabaseTestHelper.createTable(DATA_SOURCE, tableName); // lock table final Connection connection = DATA_SOURCE.getConnection(); Statement lockStatement = connection.createStatement(); lockStatement.execute("ALTER TABLE " + tableName + " LOCKSIZE TABLE"); lockStatement.execute("LOCK TABLE " + tableName + " IN EXCLUSIVE MODE"); // start a first transaction connection.setAutoCommit(false); PreparedStatement insertStatement = connection.prepareStatement("insert into " + tableName + " values(?, ?)"); insertStatement.setInt(1, 1); insertStatement.setString(2, "TEST"); insertStatement.execute(); // try to write to this table pipeline .apply(Create.of(Collections.singletonList(KV.of(1, "TEST")))) .apply( JdbcIO.<KV<Integer, String>>write() .withDataSourceConfiguration(DATA_SOURCE_CONFIGURATION) .withStatement(String.format("insert into %s values(?, ?)", tableName)) .withRetryStrategy( (JdbcIO.RetryStrategy) e -> { return "40XL1" .equals(e.getSQLState()); // we fake a deadlock with a lock here }) .withPreparedStatementSetter( (element, statement) -> { statement.setInt(1, element.getKey()); statement.setString(2, element.getValue()); })); // starting a thread to perform the commit later, while the pipeline is running into the backoff final Thread commitThread = new Thread( () -> { while (true) { try { Thread.sleep(500); expectedLogs.verifyWarn("Deadlock detected, retrying"); break; } catch (AssertionError | java.lang.InterruptedException e) { // nothing to do } } try { connection.commit(); } catch (Exception e) { // nothing to do. } }); commitThread.start(); PipelineResult result = pipeline.run(); commitThread.join(); result.waitUntilFinish(); // we verify that the backoff has been called thanks to the log message expectedLogs.verifyWarn("Deadlock detected, retrying"); assertRowCount(DATA_SOURCE, tableName, 2); }
public long completeSegmentByteCount() { long result = size; if (result == 0) return 0; // Omit the tail if it's still writable. Segment tail = head.prev; if (tail.limit < Segment.SIZE && tail.owner) { result -= tail.limit - tail.pos; } return result; }
@Test public void completeSegmentByteCountOnEmptyBuffer() throws Exception { Buffer buffer = new Buffer(); assertEquals(0, buffer.completeSegmentByteCount()); }
ConnectorStatus.Listener wrapStatusListener(ConnectorStatus.Listener delegateListener) { return new ConnectorStatusListener(delegateListener); }
@Test public void testTaskFailureAfterStartupRecordedMetrics() { WorkerMetricsGroup workerMetricsGroup = new WorkerMetricsGroup(new HashMap<>(), new HashMap<>(), connectMetrics); final TaskStatus.Listener taskListener = workerMetricsGroup.wrapStatusListener(delegateTaskListener); taskListener.onStartup(task); taskListener.onFailure(task, exception); verify(delegateTaskListener).onStartup(task); verifyRecordTaskSuccess(); verify(delegateTaskListener).onFailure(task, exception); // recordTaskFailure() should not be called if failure happens after a successful startup. verify(taskStartupFailures, never()).record(anyDouble()); }
public static RedissonClient create() { Config config = new Config(); config.useSingleServer() .setAddress("redis://127.0.0.1:6379"); return create(config); }
@Test public void testClusterConnectionFail() { Awaitility.await().atLeast(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(7)).untilAsserted(() -> { Assertions.assertThrows(RedisConnectionException.class, () -> { Config config = new Config(); config.useClusterServers() .addNodeAddress("redis://127.99.0.1:1111"); Redisson.create(config); }); }); }
public static String ipAddressToUrlString(InetAddress address) { if (address == null) { throw new NullPointerException("address is null"); } else if (address instanceof Inet4Address) { return address.getHostAddress(); } else if (address instanceof Inet6Address) { return getIPv6UrlRepresentation((Inet6Address) address); } else { throw new IllegalArgumentException("Unrecognized type of InetAddress: " + address); } }
@Test void testIPv6toURL() throws UnknownHostException { final String addressString = "2001:01db8:00:0:00:ff00:42:8329"; final String normalizedAddress = "[2001:1db8::ff00:42:8329]"; InetAddress address = InetAddress.getByName(addressString); assertThat(NetUtils.ipAddressToUrlString(address)).isEqualTo(normalizedAddress); }
public static <InputT, OutputT> PTransform<PCollection<InputT>, PCollection<OutputT>> to( Class<OutputT> clazz) { return to(TypeDescriptor.of(clazz)); }
@Test @Category(NeedsRunner.class) public void testGeneralConvert() { PCollection<POJO2> pojos = pipeline.apply(Create.of(new POJO1())).apply(Convert.to(POJO2.class)); PAssert.that(pojos).containsInAnyOrder(new POJO2()); pipeline.run(); }
public void persist() throws Exception { if (!mapping.equals(initialMapping)) { state.update( mapping.entrySet().stream() .map((w) -> new Tuple2<>(w.getKey(), w.getValue())) .collect(Collectors.toList())); } }
@Test void testPersist() throws Exception { @SuppressWarnings("unchecked") ListState<Tuple2<TimeWindow, TimeWindow>> mockState = mock(ListState.class); MergingWindowSet<TimeWindow> windowSet = new MergingWindowSet<>( EventTimeSessionWindows.withGap(Time.milliseconds(3)), mockState); TestingMergeFunction mergeFunction = new TestingMergeFunction(); windowSet.addWindow(new TimeWindow(1, 2), mergeFunction); windowSet.addWindow(new TimeWindow(17, 42), mergeFunction); assertThat(windowSet.getStateWindow(new TimeWindow(1, 2))).isEqualTo(new TimeWindow(1, 2)); assertThat(windowSet.getStateWindow(new TimeWindow(17, 42))) .isEqualTo(new TimeWindow(17, 42)); windowSet.persist(); verify(mockState) .update( eq( new ArrayList<>( Arrays.asList( new Tuple2<>( new TimeWindow(1, 2), new TimeWindow(1, 2)), new Tuple2<>( new TimeWindow(17, 42), new TimeWindow(17, 42)))))); verify(mockState, times(1)).update(Matchers.anyObject()); }
public DdlCommandResult execute( final String sql, final DdlCommand ddlCommand, final boolean withQuery, final Set<SourceName> withQuerySources ) { return execute(sql, ddlCommand, withQuery, withQuerySources, false); }
@Test public void shouldDropSource() { // Given: metaStore.putSource(source, false); givenDropSourceCommand(STREAM_NAME); // When: final DdlCommandResult result = cmdExec.execute(SQL_TEXT, dropSource, false, NO_QUERY_SOURCES); // Then assertThat(result.isSuccess(), is(true)); assertThat( result.getMessage(), equalTo(String.format("Source %s (topic: %s) was dropped.", STREAM_NAME, TOPIC_NAME)) ); }
public final void isLessThan(int other) { isLessThan((double) other); }
@Test public void isLessThan_int_strictly() { expectFailureWhenTestingThat(2.0).isLessThan(1); }
public int wrapAdjustment() { return wrapAdjustment; }
@Test void shouldExposePositionAtWhichByteArrayGetsWrapped() { final UnsafeBuffer wibbleBuffer = new UnsafeBuffer( wibbleBytes, ADJUSTMENT_OFFSET, wibbleBytes.length - ADJUSTMENT_OFFSET); wibbleBuffer.putByte(0, VALUE); assertEquals(VALUE, wibbleBytes[wibbleBuffer.wrapAdjustment()]); }
public ListNode2<T> add(T value) { ListNode2<T> node = new ListNode2<T>(value); if (size++ == 0) { tail = node; } else { node.prev = head; head.next = node; } head = node; return node; }
@Test public void testAdd() { DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>(); list.add(1); assertFalse(list.isEmpty()); assertEquals(1, list.size()); assertArrayEquals(new Integer[]{1}, list.toArray()); list.add(2); assertFalse(list.isEmpty()); assertEquals(2, list.size()); assertArrayEquals(new Integer[]{1, 2}, list.toArray()); list.add(3); assertFalse(list.isEmpty()); assertEquals(3, list.size()); assertArrayEquals(new Integer[]{1, 2, 3}, list.toArray()); assertEquals(new Integer(1), list.first()); }
public static int bytesToCodePoint(ByteBuffer bytes) { bytes.mark(); byte b = bytes.get(); bytes.reset(); int extraBytesToRead = bytesFromUTF8[(b & 0xFF)]; if (extraBytesToRead < 0) return -1; // trailing byte! int ch = 0; switch (extraBytesToRead) { case 5: ch += (bytes.get() & 0xFF); ch <<= 6; /* remember, illegal UTF-8 */ case 4: ch += (bytes.get() & 0xFF); ch <<= 6; /* remember, illegal UTF-8 */ case 3: ch += (bytes.get() & 0xFF); ch <<= 6; case 2: ch += (bytes.get() & 0xFF); ch <<= 6; case 1: ch += (bytes.get() & 0xFF); ch <<= 6; case 0: ch += (bytes.get() & 0xFF); } ch -= offsetsFromUTF8[extraBytesToRead]; return ch; }
@Test public void testbytesToCodePointWithInvalidUTF() { try { Text.bytesToCodePoint(ByteBuffer.wrap(new byte[] {-2})); fail("testbytesToCodePointWithInvalidUTF error unexp exception !!!"); } catch (BufferUnderflowException ex) { } catch(Exception e) { fail("testbytesToCodePointWithInvalidUTF error unexp exception !!!"); } }
public ExternalIssueReport parse(Path reportPath) { try (Reader reader = Files.newBufferedReader(reportPath, StandardCharsets.UTF_8)) { ExternalIssueReport report = gson.fromJson(reader, ExternalIssueReport.class); externalIssueReportValidator.validate(report, reportPath); return report; } catch (JsonIOException | IOException e) { throw new IllegalStateException("Failed to read external issues report '" + reportPath + "'", e); } catch (JsonSyntaxException e) { throw new IllegalStateException("Failed to read external issues report '" + reportPath + "': invalid JSON syntax", e); } }
@Test public void parse_whenDoesntExist_shouldFail() { reportPath = Paths.get("unknown.json"); assertThatThrownBy(() -> externalIssueReportParser.parse(reportPath)) .isInstanceOf(IllegalStateException.class) .hasMessage("Failed to read external issues report 'unknown.json'"); }
@Override public Optional<String> validate(String password) { return password.matches(LOWER_CASE_REGEX) ? Optional.empty() : Optional.of(LOWER_CASE_REASONING); }
@Test public void testValidateFailure() { Optional<String> result = lowerCaseValidator.validate("PASSWORD"); Assert.assertTrue(result.isPresent()); Assert.assertEquals(result.get(), "must contain at least one lower case"); }
protected List<Message> buildMessage(ProxyContext context, List<apache.rocketmq.v2.Message> protoMessageList, Resource topic) { String topicName = topic.getName(); List<Message> messageExtList = new ArrayList<>(); for (apache.rocketmq.v2.Message protoMessage : protoMessageList) { if (!protoMessage.getTopic().equals(topic)) { throw new GrpcProxyException(Code.MESSAGE_CORRUPTED, "topic in message is not same"); } // here use topicName as producerGroup for transactional checker. messageExtList.add(buildMessage(context, protoMessage, topicName)); } return messageExtList; }
@Test public void testBuildMessage() { long deliveryTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(5); ConfigurationManager.getProxyConfig().setMessageDelayLevel("1s 5s"); ConfigurationManager.getProxyConfig().initData(); String msgId = MessageClientIDSetter.createUniqID(); org.apache.rocketmq.common.message.Message messageExt = this.sendMessageActivity.buildMessage(null, Lists.newArrayList( Message.newBuilder() .setTopic(Resource.newBuilder() .setName(TOPIC) .build()) .setSystemProperties(SystemProperties.newBuilder() .setMessageId(msgId) .setQueueId(0) .setMessageType(MessageType.DELAY) .setDeliveryTimestamp(Timestamps.fromMillis(deliveryTime)) .setBornTimestamp(Timestamps.fromMillis(System.currentTimeMillis())) .setBornHost(StringUtils.defaultString(NetworkUtil.getLocalAddress(), "127.0.0.1:1234")) .build()) .setBody(ByteString.copyFromUtf8("123")) .build() ), Resource.newBuilder().setName(TOPIC).build()).get(0); assertEquals(MessageClientIDSetter.getUniqID(messageExt), msgId); assertEquals(deliveryTime, Long.parseLong(messageExt.getProperty(MessageConst.PROPERTY_TIMER_DELIVER_MS))); }
@Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DescriptiveUrlBag(); final DescriptiveUrl base = new DefaultWebUrlProvider().toUrl(host); list.add(new DescriptiveUrl(URI.create(String.format("%s%s", base.getUrl(), URIEncoder.encode( PathNormalizer.normalize(PathRelativizer.relativize(PathNormalizer.normalize(host.getDefaultPath(), true), file.getAbsolute())) ))).normalize(), base.getType(), base.getHelp()) ); return list; }
@Test public void testCustom() { final Host host = new Host(new TestProtocol(), "test.cyberduck.ch"); host.setWebURL("customhost"); assertEquals("http://customhost/", new DefaultWebUrlProvider().toUrl(host).getUrl()); assertEquals("http://customhost/my/documentroot/f", new HostWebUrlProvider(host).toUrl(new Path("/my/documentroot/f", EnumSet.of(Path.Type.directory))).find(DescriptiveUrl.Type.http).getUrl()); host.setWebURL("https://customhost/"); assertEquals("https://customhost/", new DefaultWebUrlProvider().toUrl(host).getUrl()); assertEquals("https://customhost/my/documentroot/f", new HostWebUrlProvider(host).toUrl(new Path("/my/documentroot/f", EnumSet.of(Path.Type.directory))).find(DescriptiveUrl.Type.http).getUrl()); host.setWebURL("https://customhost"); assertEquals("https://customhost", new DefaultWebUrlProvider().toUrl(host).getUrl()); assertEquals("https://customhost/my/documentroot/f", new HostWebUrlProvider(host).toUrl(new Path("/my/documentroot/f", EnumSet.of(Path.Type.directory))).find(DescriptiveUrl.Type.http).getUrl()); }
public ArtifactResponse buildArtifactResponse(ArtifactResolveRequest artifactResolveRequest, String entityId, SignType signType) throws InstantiationException, ValidationException, ArtifactBuildException, BvdException { final var artifactResponse = OpenSAMLUtils.buildSAMLObject(ArtifactResponse.class); final var status = OpenSAMLUtils.buildSAMLObject(Status.class); final var statusCode = OpenSAMLUtils.buildSAMLObject(StatusCode.class); final var issuer = OpenSAMLUtils.buildSAMLObject(Issuer.class); return ArtifactResponseBuilder .newInstance(artifactResponse) .addID() .addIssueInstant() .addInResponseTo(artifactResolveRequest.getArtifactResolve().getID()) .addStatus(StatusBuilder .newInstance(status) .addStatusCode(statusCode, StatusCode.SUCCESS) .build()) .addIssuer(issuer, entityId) .addMessage(buildResponse(artifactResolveRequest, entityId, signType)) .addSignature(signatureService, signType) .build(); }
@Test void parseArtifactResolveSuccessBsn() throws ValidationException, SamlParseException, ArtifactBuildException, BvdException, InstantiationException { ArtifactResponse artifactResponse = artifactResponseService.buildArtifactResponse(getArtifactResolveRequest("success", true, false,SAML_COMBICONNECT, EncryptionType.BSN, ENTRANCE_ENTITY_ID), ENTRANCE_ENTITY_ID, TD); assertEquals("urn:oasis:names:tc:SAML:2.0:status:Success", ((Response) artifactResponse.getMessage()).getStatus().getStatusCode().getValue()); }
@Override public String getOperationName(Exchange exchange, Endpoint endpoint) { // OpenTracing aims to use low cardinality operation names. Ideally, a // specific span decorator should be defined for all relevant Camel // components that identify a meaningful operation name return getComponentName(endpoint); }
@Test public void testGetOperationName() { Endpoint endpoint = Mockito.mock(Endpoint.class); Mockito.when(endpoint.getEndpointUri()).thenReturn(TEST_URI); SpanDecorator decorator = new AbstractSpanDecorator() { @Override public String getComponent() { return null; } @Override public String getComponentClassName() { return null; } }; // Operation name is scheme, as no specific span decorator to // identify an appropriate name assertEquals("test", decorator.getOperationName(null, endpoint)); }
public void run(String[] args) { if (!parseArguments(args)) { showOptions(); return; } if (command == null) { System.out.println("Error: Command is empty"); System.out.println(); showOptions(); return; } if (password == null) { System.out.println("Error: Password is empty"); System.out.println(); showOptions(); return; } if (input == null) { System.out.println("Error: Input is empty"); System.out.println(); showOptions(); return; } encryptor.setPassword(password); if (algorithm != null) { encryptor.setAlgorithm(algorithm); } if (randomSaltGeneratorAlgorithm != null) { encryptor.setSaltGenerator(new RandomSaltGenerator(randomSaltGeneratorAlgorithm)); } if (randomIvGeneratorAlgorithm != null) { encryptor.setIvGenerator(new RandomIvGenerator(randomIvGeneratorAlgorithm)); } if ("encrypt".equals(command)) { System.out.println("Encrypted text: " + encryptor.encrypt(input)); } else { System.out.println("Decrypted text: " + encryptor.decrypt(input)); } }
@Test public void testMissingPassword() { Main main = new Main(); assertDoesNotThrow(() -> main.run("-c encrypt -i tiger".split(" "))); }
public static Optional<Expression> convert( org.apache.flink.table.expressions.Expression flinkExpression) { if (!(flinkExpression instanceof CallExpression)) { return Optional.empty(); } CallExpression call = (CallExpression) flinkExpression; Operation op = FILTERS.get(call.getFunctionDefinition()); if (op != null) { switch (op) { case IS_NULL: return onlyChildAs(call, FieldReferenceExpression.class) .map(FieldReferenceExpression::getName) .map(Expressions::isNull); case NOT_NULL: return onlyChildAs(call, FieldReferenceExpression.class) .map(FieldReferenceExpression::getName) .map(Expressions::notNull); case LT: return convertFieldAndLiteral(Expressions::lessThan, Expressions::greaterThan, call); case LT_EQ: return convertFieldAndLiteral( Expressions::lessThanOrEqual, Expressions::greaterThanOrEqual, call); case GT: return convertFieldAndLiteral(Expressions::greaterThan, Expressions::lessThan, call); case GT_EQ: return convertFieldAndLiteral( Expressions::greaterThanOrEqual, Expressions::lessThanOrEqual, call); case EQ: return convertFieldAndLiteral( (ref, lit) -> { if (NaNUtil.isNaN(lit)) { return Expressions.isNaN(ref); } else { return Expressions.equal(ref, lit); } }, call); case NOT_EQ: return convertFieldAndLiteral( (ref, lit) -> { if (NaNUtil.isNaN(lit)) { return Expressions.notNaN(ref); } else { return Expressions.notEqual(ref, lit); } }, call); case NOT: return onlyChildAs(call, CallExpression.class) .flatMap(FlinkFilters::convert) .map(Expressions::not); case AND: return convertLogicExpression(Expressions::and, call); case OR: return convertLogicExpression(Expressions::or, call); case STARTS_WITH: return convertLike(call); } } return Optional.empty(); }
@Test public void testEquals() { for (Pair<String, Object> pair : FIELD_VALUE_LIST) { UnboundPredicate<?> expected = org.apache.iceberg.expressions.Expressions.equal(pair.first(), pair.second()); Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.convert( resolve(Expressions.$(pair.first()).isEqual(Expressions.lit(pair.second())))); assertThat(actual).isPresent(); assertPredicatesMatch(expected, actual.get()); Optional<org.apache.iceberg.expressions.Expression> actual1 = FlinkFilters.convert( resolve(Expressions.lit(pair.second()).isEqual(Expressions.$(pair.first())))); assertThat(actual1).isPresent(); assertPredicatesMatch(expected, actual1.get()); } }
static BigtableConfig translateToBigtableConfig(BigtableConfig config, BigtableOptions options) { BigtableConfig.Builder builder = config.toBuilder(); if (options.getProjectId() != null && config.getProjectId() == null) { builder.setProjectId(ValueProvider.StaticValueProvider.of(options.getProjectId())); } if (options.getInstanceId() != null && config.getInstanceId() == null) { builder.setInstanceId(ValueProvider.StaticValueProvider.of(options.getInstanceId())); } if (options.getAppProfileId() != null && config.getAppProfileId() == null) { builder.setAppProfileId(ValueProvider.StaticValueProvider.of(options.getAppProfileId())); } if (options.getCredentialOptions().getCredentialType() == CredentialOptions.CredentialType.None && config.getEmulatorHost() == null) { builder.setEmulatorHost(String.format("%s:%s", options.getDataHost(), options.getPort())); } builder.setChannelCount(options.getChannelCount()); if (options.getCredentialOptions() != null) { try { CredentialOptions credOptions = options.getCredentialOptions(); switch (credOptions.getCredentialType()) { case DefaultCredentials: // Veneer uses default credentials, so no need to reset here break; case P12: String keyFile = ((CredentialOptions.P12CredentialOptions) credOptions).getKeyFile(); String serviceAccount = ((CredentialOptions.P12CredentialOptions) credOptions).getServiceAccount(); try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (FileInputStream fin = new FileInputStream(keyFile)) { keyStore.load(fin, "notasecret".toCharArray()); } PrivateKey privateKey = (PrivateKey) keyStore.getKey("privatekey", "notasecret".toCharArray()); if (privateKey == null) { throw new IllegalStateException("private key cannot be null"); } Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() .setClientEmail(serviceAccount) .setPrivateKey(privateKey) .build(); builder.setCredentialFactory(FixedCredentialFactory.create(credentials)); } catch (GeneralSecurityException exception) { throw new RuntimeException("exception while retrieving credentials", exception); } break; case SuppliedCredentials: Credentials credentials = ((CredentialOptions.UserSuppliedCredentialOptions) credOptions).getCredential(); builder.setCredentialFactory(FixedCredentialFactory.create(credentials)); break; case SuppliedJson: CredentialOptions.JsonCredentialsOptions jsonCredentialsOptions = (CredentialOptions.JsonCredentialsOptions) credOptions; builder.setCredentialFactory( FixedCredentialFactory.create( GoogleCredentials.fromStream(jsonCredentialsOptions.getInputStream()))); break; case None: // pipelineOptions is ignored PipelineOptions pipelineOptions = PipelineOptionsFactory.create(); builder.setCredentialFactory(NoopCredentialFactory.fromOptions(pipelineOptions)); break; } } catch (IOException e) { throw new RuntimeException("Failed to translate BigtableOptions to BigtableConfig", e); } } return builder.build(); }
@Test public void testBigtableOptionsToBigtableConfig() throws Exception { BigtableOptions options = BigtableOptions.builder() .setProjectId("project") .setInstanceId("instance") .setAppProfileId("app-profile") .setDataHost("localhost") .setPort(1234) .setCredentialOptions(CredentialOptions.nullCredential()) .build(); BigtableConfig config = BigtableConfig.builder().setValidate(true).build(); config = BigtableConfigTranslator.translateToBigtableConfig(config, options); assertNotNull(config.getProjectId()); assertNotNull(config.getInstanceId()); assertNotNull(config.getAppProfileId()); assertNotNull(config.getEmulatorHost()); assertNotNull(config.getCredentialFactory()); NoopCredentialFactory noopCredentialFactory = NoopCredentialFactory.fromOptions(PipelineOptionsFactory.as(GcpOptions.class)); assertEquals(options.getProjectId(), config.getProjectId().get()); assertEquals(options.getInstanceId(), config.getInstanceId().get()); assertEquals(options.getAppProfileId(), config.getAppProfileId().get()); assertEquals("localhost:1234", config.getEmulatorHost()); assertEquals( noopCredentialFactory.getCredential(), config.getCredentialFactory().getCredential()); }
@Nullable public static ValueReference of(Object value) { if (value instanceof Boolean) { return of((Boolean) value); } else if (value instanceof Double) { return of((Double) value); } else if (value instanceof Float) { return of((Float) value); } else if (value instanceof Integer) { return of((Integer) value); } else if (value instanceof Long) { return of((Long) value); } else if (value instanceof String) { return of((String) value); } else if (value instanceof Enum) { return of((Enum) value); } else if (value instanceof EncryptedValue encryptedValue) { return of(encryptedValue); } else { return null; } }
@Test public void deserializeInteger() throws IOException { assertThat(objectMapper.readValue("{\"@type\":\"integer\",\"@value\":1}", ValueReference.class)).isEqualTo(ValueReference.of(1)); assertThat(objectMapper.readValue("{\"@type\":\"integer\",\"@value\":42}", ValueReference.class)).isEqualTo(ValueReference.of(42)); }
@Override @SuppressWarnings("deprecation") public HttpClientOperations addHandler(ChannelHandler handler) { super.addHandler(handler); return this; }
@Test void addDecoderReplaysLastHttp() { ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8); EmbeddedChannel channel = new EmbeddedChannel(); new HttpClientOperations(() -> channel, ConnectionObserver.emptyListener(), ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT, ReactorNettyHttpMessageLogFactory.INSTANCE) .addHandler(new JsonObjectDecoder()); channel.writeInbound(new DefaultLastHttpContent(buf)); assertThat(channel.pipeline().names()).first().isEqualTo("JsonObjectDecoder$extractor"); Object content = channel.readInbound(); assertThat(content).isInstanceOf(ByteBuf.class); ((ByteBuf) content).release(); content = channel.readInbound(); assertThat(content).isInstanceOf(LastHttpContent.class); ((LastHttpContent) content).release(); content = channel.readInbound(); assertThat(content).isNull(); }
@Override public void close() throws Exception { if (aggregateLocalUsagePeriodicTask != null) { aggregateLocalUsagePeriodicTask.cancel(true); } if (calculateQuotaPeriodicTask != null) { calculateQuotaPeriodicTask.cancel(true); } resourceGroupsMap.clear(); tenantToRGsMap.clear(); namespaceToRGsMap.clear(); topicProduceStats.clear(); topicConsumeStats.clear(); }
@Test public void testClose() throws Exception { ResourceGroupService service = new ResourceGroupService(pulsar, TimeUnit.MILLISECONDS, null, null); service.close(); Assert.assertTrue(service.getAggregateLocalUsagePeriodicTask().isCancelled()); Assert.assertTrue(service.getCalculateQuotaPeriodicTask().isCancelled()); }
@Draft public ZMsg msgBinaryPicture(String picture, Object... args) { if (!BINARY_FORMAT.matcher(picture).matches()) { throw new ZMQException(picture + " is not in expected binary format " + BINARY_FORMAT.pattern(), ZError.EPROTO); } ZMsg msg = new ZMsg(); // Pass 1: calculate total size of data frame int frameSize = 0; for (int index = 0; index < picture.length(); index++) { char pattern = picture.charAt(index); switch (pattern) { case '1': { frameSize += 1; break; } case '2': { frameSize += 2; break; } case '4': { frameSize += 4; break; } case '8': { frameSize += 8; break; } case 's': { String string = (String) args[index]; frameSize += 1 + (string != null ? string.getBytes(ZMQ.CHARSET).length : 0); break; } case 'S': { String string = (String) args[index]; frameSize += 4 + (string != null ? string.getBytes(ZMQ.CHARSET).length : 0); break; } case 'b': case 'c': { byte[] block = (byte[]) args[index]; frameSize += 4 + block.length; break; } case 'f': { ZFrame frame = (ZFrame) args[index]; msg.add(frame); break; } case 'm': { ZMsg other = (ZMsg) args[index]; if (other == null) { msg.add(new ZFrame((byte[]) null)); } else { msg.addAll(other); } break; } default: assert (false) : "invalid picture element '" + pattern + "'"; } } // Pass 2: encode data into data frame ZFrame frame = new ZFrame(new byte[frameSize]); ZNeedle needle = new ZNeedle(frame); for (int index = 0; index < picture.length(); index++) { char pattern = picture.charAt(index); switch (pattern) { case '1': { needle.putNumber1((int) args[index]); break; } case '2': { needle.putNumber2((int) args[index]); break; } case '4': { needle.putNumber4((int) args[index]); break; } case '8': { needle.putNumber8((long) args[index]); break; } case 's': { needle.putString((String) args[index]); break; } case 'S': { needle.putLongString((String) args[index]); break; } case 'b': case 'c': { byte[] block = (byte[]) args[index]; needle.putNumber4(block.length); needle.putBlock(block, block.length); break; } case 'f': case 'm': break; default: assert (false) : "invalid picture element '" + pattern + "'"; } } msg.addFirst(frame); return msg; }
@Test public void testValidPictureNullMsgInTheEnd() { String picture = "fm"; ZMsg msg = pic.msgBinaryPicture(picture, new ZFrame("My frame"), null); assertThat(msg.getLast().size(), is(0)); }
public String sign(RawTransaction rawTransaction) { byte[] signedMessage = txSignService.sign(rawTransaction, chainId); return Numeric.toHexString(signedMessage); }
@Test public void testSignRawTxWithHSM() throws IOException { TransactionReceipt transactionReceipt = prepareTransfer(); prepareTransaction(transactionReceipt); OkHttpClient okHttpClient = mock(OkHttpClient.class); Call call = mock(Call.class); Response hmsResponse = new Response.Builder() .code(200) .request(new Request.Builder().url("http://test-call.com").build()) .protocol(Protocol.HTTP_1_1) .message("response message") .body( ResponseBody.create( TX_SIGN_FORMAT_DER_HEX, MediaType.parse("text/plain"))) .build(); when(call.execute()).thenReturn(hmsResponse); when(okHttpClient.newCall(any())).thenReturn(call); HSMHTTPRequestProcessor<HSMHTTPPass> hsmRequestProcessor = new HSMHTTPRequestProcessorTestImpl<>(okHttpClient); HSMHTTPPass hsmhttpPass = new HSMHTTPPass( SampleKeys.CREDENTIALS.getAddress(), SampleKeys.CREDENTIALS.getEcKeyPair().getPublicKey(), "http://mock_request_url.com"); TxSignService txHSMSignService = new TxHSMSignService<>(hsmRequestProcessor, hsmhttpPass); RawTransactionManager transactionManager = new RawTransactionManager(web3j, txHSMSignService, ChainId.NONE); String sign = transactionManager.sign(createRawTx()); assertEquals(TX_SIGN_RESULT_HEX, sign); }
public MetricsBuilder enableRpc(Boolean enableRpc) { this.enableRpc = enableRpc; return getThis(); }
@Test void enableRpc() { MetricsBuilder builder = MetricsBuilder.newBuilder(); builder.enableRpc(false); Assertions.assertFalse(builder.build().getEnableRpc()); }
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return true; } try { attributes.find(file, listener); return true; } catch(NotfoundException e) { return false; } catch(AccessDeniedException e) { // Object is inaccessible to current user, but does exist. return true; } }
@Test public void testFindDirectory() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path folder = new GoogleStorageDirectoryFeature(session).mkdir( new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus()); assertTrue(new GoogleStorageFindFeature(session).find(folder)); assertFalse(new GoogleStorageFindFeature(session).find(new Path(folder.getAbsolute(), EnumSet.of(Path.Type.file)))); new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(folder), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Override public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException { try (InputStream input = provider.open(requireNonNull(path))) { final JsonNode node = mapper.readTree(createParser(input)); if (node == null) { throw ConfigurationParsingException .builder("Configuration at " + path + " must not be empty") .build(path); } return build(node, path); } catch (JsonParseException e) { throw ConfigurationParsingException .builder("Malformed " + formatName) .setCause(e) .setLocation(e.getLocation()) .setDetail(e.getMessage()) .build(path); } }
@Test void incorrectTypeIsFound() { assertThatExceptionOfType(ConfigurationParsingException.class) .isThrownBy(() -> factory.build(configurationSourceProvider, wrongTypeFile)) .withMessage("%s has an error:%n" + " * Incorrect type of value at: age; is of type: String, expected: int%n", wrongTypeFile); }
@SuppressWarnings("unchecked") @Override public int hashCode() { return hashCode(JAVA_HASHER); }
@Test public void emptyHeadersShouldBeEqual() { TestDefaultHeaders headers1 = newInstance(); TestDefaultHeaders headers2 = newInstance(); assertNotSame(headers1, headers2); assertEquals(headers1, headers2); assertEquals(headers1.hashCode(), headers2.hashCode()); }
public static String encodeCredentials(ALM alm, String pat, @Nullable String username) { if (!alm.equals(BITBUCKET_CLOUD)) { return pat; } return Base64.getEncoder().encodeToString((username + ":" + pat).getBytes(UTF_8)); }
@Test public void encodes_credential_returns_username_and_encoded_pat_for_bitbucketcloud() { String encodedPat = Base64.getEncoder().encodeToString((USERNAME + ":" + PAT).getBytes(UTF_8)); String encodedCredential = CredentialsEncoderHelper.encodeCredentials(ALM.BITBUCKET_CLOUD, PAT, USERNAME); assertThat(encodedCredential) .doesNotContain(USERNAME) .doesNotContain(PAT) .contains(encodedPat); }
public static Write<String> writeStrings() { return Write.newBuilder( (ValueInSingleWindow<String> stringAndWindow) -> new PubsubMessage( stringAndWindow.getValue().getBytes(StandardCharsets.UTF_8), ImmutableMap.of())) .setDynamicDestinations(false) .build(); }
@Test public void testPrimitiveWriteDisplayData() { DisplayDataEvaluator evaluator = DisplayDataEvaluator.create(); PubsubIO.Write<?> write = PubsubIO.writeStrings().to("projects/project/topics/topic"); Set<DisplayData> displayData = evaluator.displayDataForPrimitiveTransforms(write); assertThat( "PubsubIO.Write should include the topic in its primitive display data", displayData, hasItem(hasDisplayItem("topic"))); }
@Override public void filter(ContainerRequestContext requestContext) { if (isInternalRequest(requestContext)) { log.trace("Skipping authentication for internal request"); return; } try { log.debug("Authenticating request"); BasicAuthCredentials credentials = new BasicAuthCredentials(requestContext.getHeaderString(AUTHORIZATION)); LoginContext loginContext = new LoginContext( CONNECT_LOGIN_MODULE, null, new BasicAuthCallBackHandler(credentials), configuration); loginContext.login(); setSecurityContextForRequest(requestContext, credentials); } catch (LoginException | ConfigException e) { // Log at debug here in order to avoid polluting log files whenever someone mistypes their credentials log.debug("Request failed authentication", e); requestContext.abortWith( Response.status(Response.Status.UNAUTHORIZED) .entity("User cannot access the resource.") .build()); } }
@Test public void testUnknownBearer() throws IOException { File credentialFile = setupPropertyLoginFile(true); JaasBasicAuthFilter jaasBasicAuthFilter = setupJaasFilter("KafkaConnect", credentialFile.getPath()); ContainerRequestContext requestContext = setMock("Unknown", "user", "password"); jaasBasicAuthFilter.filter(requestContext); verify(requestContext).abortWith(any(Response.class)); verify(requestContext, atLeastOnce()).getMethod(); verify(requestContext).getHeaderString(JaasBasicAuthFilter.AUTHORIZATION); }
@Override public Object getValue() { try { return mBeanServerConn.getAttribute(getObjectName(), attributeName); } catch (IOException | JMException e) { return null; } }
@Test public void returnsAttributeForObjectNamePattern() throws Exception { ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:name=test1,*"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); assertThat(gauge.getValue()).isInstanceOf(Long.class); assertThat((Long) gauge.getValue()).isEqualTo(Long.MAX_VALUE); }
public static String maskRegex(String input, String key, String name) { Map<String, Object> regexConfig = (Map<String, Object>) config.get(MASK_TYPE_REGEX); if (regexConfig != null) { Map<String, Object> keyConfig = (Map<String, Object>) regexConfig.get(key); if (keyConfig != null) { String regex = (String) keyConfig.get(name); if (regex != null && regex.length() > 0) { return replaceWithMask(input, MASK_REPLACEMENT_CHAR.charAt(0), regex); } } } return input; }
@Test public void testMaskResponseHeader() { String testHeader = "header"; String output = Mask.maskRegex(testHeader, "responseHeader", "header3"); System.out.println("output = " + output); Assert.assertEquals(output, "******"); }
@VisibleForTesting long getJmxCacheTTL() { return jmxCacheTTL; }
@Test public void testMetricCacheUpdateRace() throws Exception { // Create test source with a single metric counter of value 1. TestMetricsSource source = new TestMetricsSource(); MetricsSourceBuilder sourceBuilder = MetricsAnnotations.newSourceBuilder(source); final long JMX_CACHE_TTL = 250; // ms List<MetricsTag> injectedTags = new ArrayList<>(); MetricsSourceAdapter sourceAdapter = new MetricsSourceAdapter("test", "test", "test JMX cache update race condition", sourceBuilder.build(), injectedTags, null, null, JMX_CACHE_TTL, false); ScheduledExecutorService updaterExecutor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().build()); ScheduledExecutorService readerExecutor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().build()); final AtomicBoolean hasError = new AtomicBoolean(false); // Wake up every 1 JMX cache TTL to set lastRecs before updateJmxCache() is // called. SourceUpdater srcUpdater = new SourceUpdater(sourceAdapter, hasError); ScheduledFuture<?> updaterFuture = updaterExecutor.scheduleAtFixedRate(srcUpdater, sourceAdapter.getJmxCacheTTL(), sourceAdapter.getJmxCacheTTL(), TimeUnit.MILLISECONDS); srcUpdater.setFuture(updaterFuture); // Wake up every 2 JMX cache TTL so updateJmxCache() will try to update // JMX cache. SourceReader srcReader = new SourceReader(source, sourceAdapter, hasError); ScheduledFuture<?> readerFuture = readerExecutor.scheduleAtFixedRate(srcReader, 0, // set JMX info cache at the beginning 2 * sourceAdapter.getJmxCacheTTL(), TimeUnit.MILLISECONDS); srcReader.setFuture(readerFuture); // Let the threads do their work. Thread.sleep(RACE_TEST_RUNTIME); assertFalse("Hit error", hasError.get()); // cleanup updaterExecutor.shutdownNow(); readerExecutor.shutdownNow(); updaterExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS); readerExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS); }
@Override public QueryActionStats execute(Statement statement, QueryStage queryStage) { return execute(statement, queryStage, new NoResultStatementExecutor<>()); }
@Test public void testQuerySucceededWithConverter() { QueryResult<Integer> result = prestoAction.execute( sqlParser.createStatement("SELECT x FROM (VALUES (1), (2), (3)) t(x)", PARSING_OPTIONS), QUERY_STAGE, resultSet -> Optional.of(resultSet.getInt("x") * resultSet.getInt("x"))); assertEquals(result.getQueryActionStats().getQueryStats().map(QueryStats::getState).orElse(null), FINISHED.name()); assertEquals(result.getResults(), ImmutableList.of(1, 4, 9)); }
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) { if (statsEnabled) { stats.log(deviceStateServiceMsg); } stateService.onQueueMsg(deviceStateServiceMsg, callback); }
@Test public void givenStatsEnabled_whenForwardingInactivityMsgToStateService_thenStatsAreRecorded() { // GIVEN ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "stats", statsMock); ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "statsEnabled", true); var inactivityMsg = TransportProtos.DeviceInactivityProto.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setDeviceIdMSB(deviceId.getId().getMostSignificantBits()) .setDeviceIdLSB(deviceId.getId().getLeastSignificantBits()) .setLastInactivityTime(time) .build(); doCallRealMethod().when(defaultTbCoreConsumerServiceMock).forwardToStateService(inactivityMsg, tbCallbackMock); // WHEN defaultTbCoreConsumerServiceMock.forwardToStateService(inactivityMsg, tbCallbackMock); // THEN then(statsMock).should().log(inactivityMsg); }
public static List<TypedExpression> coerceCorrectConstructorArguments( final Class<?> type, List<TypedExpression> arguments, List<Integer> emptyCollectionArgumentsIndexes) { Objects.requireNonNull(type, "Type parameter cannot be null as the method searches constructors from that class!"); Objects.requireNonNull(arguments, "Arguments parameter cannot be null! Use an empty list instance if needed instead."); Objects.requireNonNull(emptyCollectionArgumentsIndexes, "EmptyListArgumentIndexes parameter cannot be null! Use an empty list instance if needed instead."); if (emptyCollectionArgumentsIndexes.size() > arguments.size()) { throw new IllegalArgumentException("There cannot be more empty collection arguments than all arguments! emptyCollectionArgumentsIndexes parameter has more items than arguments parameter. " + "(" + emptyCollectionArgumentsIndexes.size() + " > " + arguments.size() + ")"); } // Rather work only with the argumentsType and when a method is resolved, flip the arguments list based on it. final List<TypedExpression> coercedArgumentsTypesList = new ArrayList<>(arguments); Constructor<?> constructor = resolveConstructor(type, coercedArgumentsTypesList); if (constructor != null) { return coercedArgumentsTypesList; } else { // This needs to go through all possible combinations. final int indexesListSize = emptyCollectionArgumentsIndexes.size(); for (int numberOfProcessedIndexes = 0; numberOfProcessedIndexes < indexesListSize; numberOfProcessedIndexes++) { for (int indexOfEmptyListIndex = numberOfProcessedIndexes; indexOfEmptyListIndex < indexesListSize; indexOfEmptyListIndex++) { switchCollectionClassInArgumentsByIndex(coercedArgumentsTypesList, emptyCollectionArgumentsIndexes.get(indexOfEmptyListIndex)); constructor = resolveConstructor(type, coercedArgumentsTypesList); if (constructor != null) { return coercedArgumentsTypesList; } switchCollectionClassInArgumentsByIndex(coercedArgumentsTypesList, emptyCollectionArgumentsIndexes.get(indexOfEmptyListIndex)); } switchCollectionClassInArgumentsByIndex(coercedArgumentsTypesList, emptyCollectionArgumentsIndexes.get(numberOfProcessedIndexes)); } // No constructor found, return the original arguments. return arguments; } }
@Test public void coerceCorrectConstructorArgumentsCoerceList() { final List<TypedExpression> arguments = List.of( new MapExprT(new MapCreationLiteralExpression(null, NodeList.nodeList())), new MapExprT(new MapCreationLiteralExpression(null, NodeList.nodeList()))); final List<Class<?>> expectedArgumentClasses = List.of(ListExprT.class, MapExprT.class); final List<TypedExpression> coercedArguments = MethodResolutionUtils.coerceCorrectConstructorArguments( Person.class, arguments, List.of(0)); Assertions.assertThat(getTypedExpressionsClasses(coercedArguments)) .containsExactlyElementsOf(expectedArgumentClasses); }
public static StructType partitionType(Table table) { Collection<PartitionSpec> specs = table.specs().values(); return buildPartitionProjectionType("table partition", specs, allFieldIds(specs)); }
@Test public void testPartitionTypeWithRenamesInV1Table() { PartitionSpec initialSpec = PartitionSpec.builderFor(SCHEMA).identity("data", "p1").build(); TestTables.TestTable table = TestTables.create(tableDir, "test", SCHEMA, initialSpec, V1_FORMAT_VERSION); table.updateSpec().addField("category").commit(); table.updateSpec().renameField("p1", "p2").commit(); StructType expectedType = StructType.of( NestedField.optional(1000, "p2", Types.StringType.get()), NestedField.optional(1001, "category", Types.StringType.get())); StructType actualType = Partitioning.partitionType(table); assertThat(actualType).isEqualTo(expectedType); }
@Deprecated public static String getJwt(JwtClaims claims) throws JoseException { String jwt; RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey( jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName()); // A JWT is a JWS and/or a JWE with JSON claims as the payload. // In this example it is a JWS nested inside a JWE // So we first create a JsonWebSignature object. JsonWebSignature jws = new JsonWebSignature(); // The payload of the JWS is JSON content of the JWT Claims jws.setPayload(claims.toJson()); // The JWT is signed using the sender's private key jws.setKey(privateKey); // Get provider from security config file, it should be two digit // And the provider id will set as prefix for keyid in the token header, for example: 05100 // if there is no provider id, we use "00" for the default value String provider_id = ""; if (jwtConfig.getProviderId() != null) { provider_id = jwtConfig.getProviderId(); if (provider_id.length() == 1) { provider_id = "0" + provider_id; } else if (provider_id.length() > 2) { logger.error("provider_id defined in the security.yml file is invalid; the length should be 2"); provider_id = provider_id.substring(0, 2); } } jws.setKeyIdHeaderValue(provider_id + jwtConfig.getKey().getKid()); // Set the signature algorithm on the JWT/JWS that will integrity protect the claims jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS // representation, which is a string consisting of three dot ('.') separated // base64url-encoded parts in the form Header.Payload.Signature jwt = jws.getCompactSerialization(); return jwt; }
@Test public void longLivedHelloWorldJwt() throws Exception { JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("world.r", "world.w", "server.info.r"), "user"); claims.setExpirationTimeMinutesInTheFuture(5256000); String jwt = JwtIssuer.getJwt(claims, long_kid, KeyUtil.deserializePrivateKey(long_key, KeyUtil.RSA)); System.out.println("***LongLived HelloWorld JWT***: " + jwt); }
@VisibleForTesting public static void addUserAgentEnvironments(List<String> info) { info.add(String.format(OS_FORMAT, OSUtils.OS_NAME)); if (EnvironmentUtils.isDocker()) { info.add(DOCKER_KEY); } if (EnvironmentUtils.isKubernetes()) { info.add(KUBERNETES_KEY); } if (EnvironmentUtils.isGoogleComputeEngine()) { info.add(GCE_KEY); } else { addEC2Info(info); } }
@Test public void userAgentEnvironmentStringGCP() { Mockito.when(EnvironmentUtils.isGoogleComputeEngine()).thenReturn(true); Mockito.when(EC2MetadataUtils.getUserData()) .thenThrow(new SdkClientException("Unable to contact EC2 metadata service.")); List<String> info = new ArrayList<>(); UpdateCheckUtils.addUserAgentEnvironments(info); Assert.assertEquals(2, info.size()); Assert.assertEquals(String.format(UpdateCheckUtils.OS_FORMAT, OSUtils.OS_NAME), info.get(0)); Assert.assertEquals(UpdateCheckUtils.GCE_KEY, info.get(1)); }
@Converter(fallback = true) public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) throws MessagingException, IOException { if (Multipart.class.isAssignableFrom(value.getClass())) { TypeConverter tc = registry.lookup(type, String.class); if (tc != null) { String s = toString((Multipart) value); if (s != null) { return tc.convertTo(type, s); } } } return null; }
@Test public void testMultipartToInputStream() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); template.send("direct:a", new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody("Hello World"); exchange.getIn().setHeader(MailConstants.MAIL_ALTERNATIVE_BODY, "Alternative World"); } }); MockEndpoint.assertIsSatisfied(context); Message mailMessage = mock.getReceivedExchanges().get(0).getIn().getBody(MailMessage.class).getMessage(); assertNotNull(mailMessage); Object content = mailMessage.getContent(); assertIsInstanceOf(Multipart.class, content); InputStream is = mock.getReceivedExchanges().get(0).getIn().getBody(InputStream.class); assertNotNull(is); assertEquals("Alternative World", context.getTypeConverter().convertTo(String.class, is)); }
@Override public void onStateElection(Job job, JobState newState) { if (isNotFailed(newState) || isJobNotFoundException(newState) || isProblematicExceptionAndMustNotRetry(newState) || maxAmountOfRetriesReached(job)) return; job.scheduleAt(now().plusSeconds(getSecondsToAdd(job)), String.format("Retry %d of %d", getFailureCount(job), getMaxNumberOfRetries(job))); }
@Test void retryFilterKeepsDefaultGivenRetryFilterValueIfRetriesOnJobAnnotationIsNotProvided() { retryFilter = new RetryFilter(0); final Job job = aJob() .<TestService>withJobDetails(ts -> ts.doWork()) .withState(new FailedState("a message", new RuntimeException("boom"))) .build(); applyDefaultJobFilter(job); int beforeVersion = job.getJobStates().size(); retryFilter.onStateElection(job, job.getJobState()); int afterVersion = job.getJobStates().size(); assertThat(afterVersion).isEqualTo(beforeVersion); assertThat(job.getState()).isEqualTo(FAILED); }
public ActionResult apply(Agent agent, Map<String, String> request) { log.debug("Searching web with query {}", request.get("query")); String query = request.get("query"); if (query == null || query.isEmpty()) { return ActionResult.builder() .status(ActionResult.Status.FAILURE) .summary("The query parameter is missing or has an empty value.") .error("The query parameter is missing or has an empty value.") .build(); } try { List<SearchResult> searchResults = getSearchResults(query); return ActionResult.builder() .status(ActionResult.Status.SUCCESS) .result(searchResults) .summary(String.format("Searched the web for \"%s\" and returned multiple results.", query)) .build(); } catch (Exception e) { return ActionResult.builder() .status(ActionResult.Status.FAILURE) .summary("The web search did not return any results.") .error(e.getMessage()) .build(); } }
@Test void testApplyWithEmptyQuery() { Map<String, String> request = new HashMap<>(); request.put("query", ""); ActionResult result = searchWebAction.apply(agent, request); assertEquals(ActionResult.Status.FAILURE, result.getStatus()); assertEquals("The query parameter is missing or has an empty value.", result.getSummary()); assertEquals("The query parameter is missing or has an empty value.", result.getError()); }
@ConstantFunction(name = "bitor", argTypes = {BIGINT, BIGINT}, returnType = BIGINT) public static ConstantOperator bitorBigint(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createBigint(first.getBigint() | second.getBigint()); }
@Test public void bitorBigint() { assertEquals(100, ScalarOperatorFunctions.bitorBigint(O_BI_100, O_BI_100).getBigint()); }
public static <T> Read<T> readMessagesWithCoderAndParseFn( Coder<T> coder, SimpleFunction<PubsubMessage, T> parseFn) { return Read.newBuilder(parseFn).setCoder(coder).build(); }
@Test public void testReadMessagesWithCoderAndParseFn() { Coder<PubsubMessage> coder = PubsubMessagePayloadOnlyCoder.of(); List<PubsubMessage> inputs = ImmutableList.of( new PubsubMessage("foo".getBytes(StandardCharsets.UTF_8), new HashMap<>()), new PubsubMessage("bar".getBytes(StandardCharsets.UTF_8), new HashMap<>())); setupTestClient(inputs, coder); PCollection<String> read = pipeline.apply( PubsubIO.readMessagesWithCoderAndParseFn( StringUtf8Coder.of(), new StringPayloadParseFn()) .fromSubscription(SUBSCRIPTION.getPath()) .withClock(CLOCK) .withClientFactory(clientFactory)); List<String> outputs = ImmutableList.of("foo", "bar"); PAssert.that(read).containsInAnyOrder(outputs); pipeline.run(); }
@Override protected void respondAsLeader( ChannelHandlerContext ctx, RoutedRequest routedRequest, T gateway) { HttpRequest httpRequest = routedRequest.getRequest(); if (log.isTraceEnabled()) { log.trace("Received request " + httpRequest.uri() + '.'); } FileUploads uploadedFiles = null; try { if (!inFlightRequestTracker.registerRequest()) { log.debug( "The handler instance for {} had already been closed.", untypedResponseMessageHeaders.getTargetRestEndpointURL()); ctx.channel().close(); return; } if (!(httpRequest instanceof FullHttpRequest)) { // The RestServerEndpoint defines a HttpObjectAggregator in the pipeline that always // returns // FullHttpRequests. log.error( "Implementation error: Received a request that wasn't a FullHttpRequest."); throw new RestHandlerException( "Bad request received.", HttpResponseStatus.BAD_REQUEST); } final ByteBuf msgContent = ((FullHttpRequest) httpRequest).content(); uploadedFiles = FileUploadHandler.getMultipartFileUploads(ctx); if (!untypedResponseMessageHeaders.acceptsFileUploads() && !uploadedFiles.getUploadedFiles().isEmpty()) { throw new RestHandlerException( "File uploads not allowed.", HttpResponseStatus.BAD_REQUEST); } R request; if (msgContent.capacity() == 0) { try { request = MAPPER.readValue("{}", untypedResponseMessageHeaders.getRequestClass()); } catch (JsonParseException | JsonMappingException je) { throw new RestHandlerException( "Bad request received. Request did not conform to expected format.", HttpResponseStatus.BAD_REQUEST, je); } } else { try { InputStream in = new ByteBufInputStream(msgContent); request = MAPPER.readValue(in, untypedResponseMessageHeaders.getRequestClass()); } catch (JsonParseException | JsonMappingException je) { throw new RestHandlerException( String.format( "Request did not match expected format %s.", untypedResponseMessageHeaders .getRequestClass() .getSimpleName()), HttpResponseStatus.BAD_REQUEST, je); } } final HandlerRequest<R> handlerRequest; try { handlerRequest = HandlerRequest.resolveParametersAndCreate( request, untypedResponseMessageHeaders.getUnresolvedMessageParameters(), routedRequest.getRouteResult().pathParams(), routedRequest.getRouteResult().queryParams(), uploadedFiles.getUploadedFiles()); } catch (HandlerRequestException hre) { log.error("Could not create the handler request.", hre); throw new RestHandlerException( String.format( "Bad request, could not parse parameters: %s", hre.getMessage()), HttpResponseStatus.BAD_REQUEST, hre); } log.trace("Starting request processing."); CompletableFuture<Void> requestProcessingFuture = respondToRequest(ctx, httpRequest, handlerRequest, gateway); final FileUploads finalUploadedFiles = uploadedFiles; requestProcessingFuture .handle( (Void ignored, Throwable throwable) -> { if (throwable != null) { return handleException( ExceptionUtils.stripCompletionException(throwable), ctx, httpRequest); } return CompletableFuture.<Void>completedFuture(null); }) .thenCompose(Function.identity()) .whenComplete( (Void ignored, Throwable throwable) -> { if (throwable != null) { log.warn( "An exception occurred while handling another exception.", throwable); } finalizeRequestProcessing(finalUploadedFiles); }); } catch (Throwable e) { final FileUploads finalUploadedFiles = uploadedFiles; handleException(e, ctx, httpRequest) .whenComplete( (Void ignored, Throwable throwable) -> finalizeRequestProcessing(finalUploadedFiles)); } }
@Test void testIgnoringUnknownFields() { RestfulGateway mockRestfulGateway = new TestingRestfulGateway.Builder().build(); CompletableFuture<Void> requestProcessingCompleteFuture = new CompletableFuture<>(); TestHandler handler = new TestHandler(requestProcessingCompleteFuture, mockGatewayRetriever); RouteResult<?> routeResult = new RouteResult<>("", "", Collections.emptyMap(), Collections.emptyMap(), ""); String requestBody = "{\"unknown_field_should_be_ignore\": true}"; HttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, TestHandler.TestHeaders.INSTANCE.getTargetRestEndpointURL(), Unpooled.wrappedBuffer(requestBody.getBytes(StandardCharsets.UTF_8))); RoutedRequest<?> routerRequest = new RoutedRequest<>(routeResult, request); AtomicReference<HttpResponse> response = new AtomicReference<>(); FlinkHttpObjectAggregator aggregator = new FlinkHttpObjectAggregator( RestOptions.SERVER_MAX_CONTENT_LENGTH.defaultValue(), Collections.emptyMap()); ChannelPipeline pipeline = mock(ChannelPipeline.class); when(pipeline.get(eq(FlinkHttpObjectAggregator.class))).thenReturn(aggregator); ChannelFuture succeededFuture = mock(ChannelFuture.class); when(succeededFuture.isSuccess()).thenReturn(true); Attribute<FileUploads> attribute = new SimpleAttribute(); Channel channel = mock(Channel.class); when(channel.attr(any(AttributeKey.class))).thenReturn(attribute); ChannelHandlerContext context = mock(ChannelHandlerContext.class); when(context.pipeline()).thenReturn(pipeline); when(context.channel()).thenReturn(channel); when(context.write(any())) .thenAnswer( invocation -> { if (invocation.getArguments().length > 0 && invocation.getArgument(0) instanceof HttpResponse) { response.set(invocation.getArgument(0)); } return succeededFuture; }); when(context.writeAndFlush(any())).thenReturn(succeededFuture); handler.respondAsLeader(context, routerRequest, mockRestfulGateway); assertThat( response.get() == null || response.get().status().codeClass() == HttpStatusClass.SUCCESS) .isTrue(); }
@Override public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException { if(workdir.isRoot()) { final AttributedList<Path> result = new AttributedList<>(); final AttributedList<Path> buckets = new GoogleStorageBucketListService(session).list(workdir, listener); for(Path bucket : buckets) { result.addAll(filter(regex, new GoogleStorageObjectListService(session).list(bucket, listener, null))); } result.addAll(filter(regex, buckets)); return result; } try { return filter(regex, new GoogleStorageObjectListService(session).list(workdir, listener, null)); } catch(NotfoundException e) { return AttributedList.emptyList(); } }
@Test public void testSearchInBucket() throws Exception { final String name = new AlphanumericRandomStringService().random(); final Path bucket = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new GoogleStorageTouchFeature(session).touch(new Path(bucket, name, EnumSet.of(Path.Type.file)), new TransferStatus()); final GoogleStorageSearchFeature feature = new GoogleStorageSearchFeature(session); assertNotNull(feature.search(bucket, new SearchFilter(name), new DisabledListProgressListener()).find(new SimplePathPredicate(file))); assertNotNull(feature.search(bucket, new SearchFilter(StringUtils.upperCase(name)), new DisabledListProgressListener()).find(new SimplePathPredicate(file))); assertNotNull(feature.search(bucket, new SearchFilter(StringUtils.substring(name, 2)), new DisabledListProgressListener()).find(new SimplePathPredicate(file))); assertNotNull(feature.search(bucket, new SearchFilter(StringUtils.substring(name, 0, name.length() - 2)), new DisabledListProgressListener()).find(new SimplePathPredicate(file))); final Path subdir = new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); assertNull(feature.search(subdir, new SearchFilter(name), new DisabledListProgressListener()).find(new SimplePathPredicate(file))); new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public static Expression parseExpression(final String expressionText) { final ParserRuleContext parseTree = GrammarParseUtil.getParseTree( expressionText, SqlBaseParser::singleExpression ); return new AstBuilder(TypeRegistry.EMPTY).buildExpression(parseTree); }
@Test public void shouldParseExpression() { // When: final Expression parsed = ExpressionParser.parseExpression("1 + 2"); // Then: assertThat( parsed, equalTo(new ArithmeticBinaryExpression(parsed.getLocation(), Operator.ADD, ONE, TWO)) ); }
@Override protected boolean doProcess(TbActorMsg msg) { if (cantFindTenant) { log.info("[{}] Processing missing Tenant msg: {}", tenantId, msg); if (msg.getMsgType().equals(MsgType.QUEUE_TO_RULE_ENGINE_MSG)) { QueueToRuleEngineMsg queueMsg = (QueueToRuleEngineMsg) msg; queueMsg.getMsg().getCallback().onSuccess(); } else if (msg.getMsgType().equals(MsgType.TRANSPORT_TO_DEVICE_ACTOR_MSG)) { TransportToDeviceActorMsgWrapper transportMsg = (TransportToDeviceActorMsgWrapper) msg; transportMsg.getCallback().onSuccess(); } return true; } switch (msg.getMsgType()) { case PARTITION_CHANGE_MSG: onPartitionChangeMsg((PartitionChangeMsg) msg); break; case COMPONENT_LIFE_CYCLE_MSG: onComponentLifecycleMsg((ComponentLifecycleMsg) msg); break; case QUEUE_TO_RULE_ENGINE_MSG: onQueueToRuleEngineMsg((QueueToRuleEngineMsg) msg); break; case TRANSPORT_TO_DEVICE_ACTOR_MSG: onToDeviceActorMsg((DeviceAwareMsg) msg, false); break; case DEVICE_ATTRIBUTES_UPDATE_TO_DEVICE_ACTOR_MSG: case DEVICE_CREDENTIALS_UPDATE_TO_DEVICE_ACTOR_MSG: case DEVICE_NAME_OR_TYPE_UPDATE_TO_DEVICE_ACTOR_MSG: case DEVICE_EDGE_UPDATE_TO_DEVICE_ACTOR_MSG: case DEVICE_RPC_REQUEST_TO_DEVICE_ACTOR_MSG: case DEVICE_RPC_RESPONSE_TO_DEVICE_ACTOR_MSG: case SERVER_RPC_RESPONSE_TO_DEVICE_ACTOR_MSG: case REMOVE_RPC_TO_DEVICE_ACTOR_MSG: onToDeviceActorMsg((DeviceAwareMsg) msg, true); break; case SESSION_TIMEOUT_MSG: ctx.broadcastToChildrenByType(msg, EntityType.DEVICE); break; case RULE_CHAIN_INPUT_MSG: case RULE_CHAIN_OUTPUT_MSG: case RULE_CHAIN_TO_RULE_CHAIN_MSG: onRuleChainMsg((RuleChainAwareMsg) msg); break; case EDGE_EVENT_UPDATE_TO_EDGE_SESSION_MSG: case EDGE_SYNC_REQUEST_TO_EDGE_SESSION_MSG: case EDGE_SYNC_RESPONSE_FROM_EDGE_SESSION_MSG: onToEdgeSessionMsg((EdgeSessionMsg) msg); break; default: return false; } return true; }
@Test public void deleteDeviceTest() { TbActorRef deviceActorRef = mock(TbActorRef.class); when(systemContext.resolve(ServiceType.TB_CORE, tenantId, deviceId)).thenReturn(new TopicPartitionInfo("Main", tenantId, 0,true)); when(ctx.getOrCreateChildActor(any(), any(), any(), any())).thenReturn(deviceActorRef); ComponentLifecycleMsg componentLifecycleMsg = new ComponentLifecycleMsg(tenantId, deviceId, ComponentLifecycleEvent.DELETED); tenantActor.doProcess(componentLifecycleMsg); verify(deviceActorRef).tellWithHighPriority(eq(new DeviceDeleteMsg(tenantId, deviceId))); reset(ctx, deviceActorRef); when(systemContext.resolve(ServiceType.TB_CORE, tenantId, deviceId)).thenReturn(new TopicPartitionInfo("Main", tenantId, 1,false)); tenantActor.doProcess(componentLifecycleMsg); verify(ctx, never()).getOrCreateChildActor(any(), any(), any(), any()); verify(deviceActorRef, never()).tellWithHighPriority(any()); }
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state if (transactionManager.hasFatalError()) { if (lastError != null) maybeAbortBatches(lastError); client.poll(retryBackoffMs, time.milliseconds()); return; } if (transactionManager.hasAbortableError() && shouldHandleAuthorizationError(lastError)) { return; } // Check whether we need a new producerId. If so, we will enqueue an InitProducerId // request which will be sent below transactionManager.bumpIdempotentEpochAndResetIdIfNeeded(); if (maybeSendAndPollTransactionalRequest()) { return; } } catch (AuthenticationException e) { // This is already logged as error, but propagated here to perform any clean ups. log.trace("Authentication exception while processing transactional request", e); transactionManager.authenticationFailed(e); } } long currentTimeMs = time.milliseconds(); long pollTimeout = sendProducerData(currentTimeMs); client.poll(pollTimeout, currentTimeMs); }
@Test public void testTransactionalUnknownProducerHandlingWhenRetentionLimitReached() throws Exception { final long producerId = 343434L; TransactionManager transactionManager = new TransactionManager(logContext, "testUnresolvedSeq", 60000, 100, apiVersions); setupWithTransactionState(transactionManager); doInitTransactions(transactionManager, new ProducerIdAndEpoch(producerId, (short) 0)); assertTrue(transactionManager.hasProducerId()); transactionManager.beginTransaction(); transactionManager.maybeAddPartition(tp0); client.prepareResponse(buildAddPartitionsToTxnResponseData(0, Collections.singletonMap(tp0, Errors.NONE))); sender.runOnce(); // Receive AddPartitions response assertEquals(0, transactionManager.sequenceNumber(tp0)); // Send first ProduceRequest Future<RecordMetadata> request1 = appendToAccumulator(tp0); sender.runOnce(); assertEquals(1, client.inFlightRequestCount()); assertEquals(1, transactionManager.sequenceNumber(tp0)); assertEquals(OptionalInt.empty(), transactionManager.lastAckedSequence(tp0)); sendIdempotentProducerResponse(0, tp0, Errors.NONE, 1000L, 10L); sender.runOnce(); // receive the response. assertTrue(request1.isDone()); assertEquals(1000L, request1.get().offset()); assertEquals(OptionalInt.of(0), transactionManager.lastAckedSequence(tp0)); assertEquals(OptionalLong.of(1000L), transactionManager.lastAckedOffset(tp0)); // Send second ProduceRequest, a single batch with 2 records. appendToAccumulator(tp0); Future<RecordMetadata> request2 = appendToAccumulator(tp0); sender.runOnce(); assertEquals(3, transactionManager.sequenceNumber(tp0)); assertEquals(OptionalInt.of(0), transactionManager.lastAckedSequence(tp0)); assertFalse(request2.isDone()); sendIdempotentProducerResponse(1, tp0, Errors.UNKNOWN_PRODUCER_ID, -1L, 1010L); sender.runOnce(); // receive response 0, should be retried since the logStartOffset > lastAckedOffset. // We should have reset the sequence number state of the partition because the state was lost on the broker. assertEquals(OptionalInt.empty(), transactionManager.lastAckedSequence(tp0)); assertEquals(2, transactionManager.sequenceNumber(tp0)); assertFalse(request2.isDone()); assertFalse(client.hasInFlightRequests()); sender.runOnce(); // should retry request 1 // resend the request. Note that the expected sequence is 0, since we have lost producer state on the broker. sendIdempotentProducerResponse(0, tp0, Errors.NONE, 1011L, 1010L); sender.runOnce(); // receive response 1 assertEquals(OptionalInt.of(1), transactionManager.lastAckedSequence(tp0)); assertEquals(2, transactionManager.sequenceNumber(tp0)); assertFalse(client.hasInFlightRequests()); assertTrue(request2.isDone()); assertEquals(1012L, request2.get().offset()); assertEquals(OptionalLong.of(1012L), transactionManager.lastAckedOffset(tp0)); }
public SalesforceInputMeta() { super(); // allocate BaseStepMeta }
@Test public void testSalesforceInputMeta() throws KettleException { List<String> attributes = new ArrayList<String>(); attributes.addAll( SalesforceMetaTest.getDefaultAttributes() ); attributes.addAll( Arrays.asList( "inputFields", "condition", "query", "specifyQuery", "includeTargetURL", "targetURLField", "includeModule", "moduleField", "includeRowNumber", "includeDeletionDate", "deletionDateField", "rowNumberField", "includeSQL", "sqlField", "includeTimestamp", "timestampField", "readFrom", "readTo", "recordsFilter", "queryAll", "rowLimit" ) ); Map<String, String> getterMap = new HashMap<String, String>(); Map<String, String> setterMap = new HashMap<String, String>(); getterMap.put( "includeTargetURL", "includeTargetURL" ); getterMap.put( "includeModule", "includeModule" ); getterMap.put( "includeRowNumber", "includeRowNumber" ); getterMap.put( "includeDeletionDate", "includeDeletionDate" ); getterMap.put( "includeSQL", "includeSQL" ); getterMap.put( "sqlField", "getSQLField" ); setterMap.put( "sqlField", "setSQLField" ); getterMap.put( "includeTimestamp", "includeTimestamp" ); Map<String, FieldLoadSaveValidator<?>> fieldLoadSaveValidators = new HashMap<String, FieldLoadSaveValidator<?>>(); fieldLoadSaveValidators.put( "inputFields", new ArrayLoadSaveValidator<SalesforceInputField>( new SalesforceInputFieldLoadSaveValidator(), 50 ) ); fieldLoadSaveValidators.put( "recordsFilter", new RecordsFilterLoadSaveValidator() ); LoadSaveTester loadSaveTester = new LoadSaveTester( SalesforceInputMeta.class, attributes, getterMap, setterMap, fieldLoadSaveValidators, new HashMap<String, FieldLoadSaveValidator<?>>() ); loadSaveTester.testRepoRoundTrip(); loadSaveTester.testXmlRoundTrip(); }
@Override public long getCreationTime() { return creationTime; }
@Test public void testCreationTime() { long beforeCreationTime = Clock.currentTimeMillis(); LocalSetStatsImpl localSetStats = createTestStats(); long afterCreationTime = Clock.currentTimeMillis(); assertBetween("creationTime", localSetStats.getCreationTime(), beforeCreationTime, afterCreationTime); }
@Override protected FileStatus[] listStatus(JobConf job) throws IOException { FileStatus[] status = super.listStatus(job); if (job.getBoolean(IGNORE_FILES_WITHOUT_EXTENSION_KEY, IGNORE_INPUTS_WITHOUT_EXTENSION_DEFAULT)) { List<FileStatus> result = new ArrayList<>(status.length); for (FileStatus file : status) if (file.getPath().getName().endsWith(AvroOutputFormat.EXT)) result.add(file); status = result.toArray(new FileStatus[0]); } return status; }
@SuppressWarnings("rawtypes") @Test void ignoreFilesWithoutExtension() throws Exception { fs.mkdirs(inputDir); Path avroFile = new Path(inputDir, "somefile.avro"); Path textFile = new Path(inputDir, "someotherfile.txt"); fs.create(avroFile).close(); fs.create(textFile).close(); FileInputFormat.setInputPaths(conf, inputDir); AvroInputFormat inputFormat = new AvroInputFormat(); FileStatus[] statuses = inputFormat.listStatus(conf); assertEquals(1, statuses.length); assertEquals("somefile.avro", statuses[0].getPath().getName()); conf.setBoolean(AvroInputFormat.IGNORE_FILES_WITHOUT_EXTENSION_KEY, false); statuses = inputFormat.listStatus(conf); assertEquals(2, statuses.length); Set<String> names = new HashSet<>(); names.add(statuses[0].getPath().getName()); names.add(statuses[1].getPath().getName()); assertTrue(names.contains("somefile.avro")); assertTrue(names.contains("someotherfile.txt")); }
@Override public void itemDelete(String itemType, String itemId) { }
@Test public void itemDelete() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } }); mSensorsAPI.itemDelete("item", "123"); }
@Override public boolean checkPidPgrpidForMatch() { return checkPidPgrpidForMatch(pid, PROCFS); }
@Test @Timeout(30000) void testDestroyProcessTree() throws IOException { // test process String pid = "100"; // create the fake procfs root directory. File procfsRootDir = new File(TEST_ROOT_DIR, "proc"); try { setupProcfsRootDir(procfsRootDir); // crank up the process tree class. createProcessTree(pid, procfsRootDir.getAbsolutePath(), SystemClock.getInstance()); // Let us not create stat file for pid 100. assertTrue(ProcfsBasedProcessTree.checkPidPgrpidForMatch(pid, procfsRootDir.getAbsolutePath())); } finally { FileUtil.fullyDelete(procfsRootDir); } }
@Override public boolean next() throws SQLException { if (skipAll) { return false; } if (!paginationContext.getActualRowCount().isPresent()) { return getMergedResult().next(); } return rowNumber++ < paginationContext.getActualRowCount().get() && getMergedResult().next(); }
@Test void assertNextWithoutOffsetWithoutRowCount() throws SQLException { ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "Oracle")); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); OracleSelectStatement selectStatement = new OracleSelectStatement(); selectStatement.setProjections(new ProjectionsSegment(0, 0)); SelectStatementContext selectStatementContext = new SelectStatementContext(createShardingSphereMetaData(database), null, selectStatement, DefaultDatabase.LOGIC_NAME, Collections.emptyList()); when(database.getName()).thenReturn(DefaultDatabase.LOGIC_NAME); MergedResult actual = resultMerger.merge(Arrays.asList(mockQueryResult(), mockQueryResult(), mockQueryResult(), mockQueryResult()), selectStatementContext, database, mock(ConnectionContext.class)); for (int i = 0; i < 8; i++) { assertTrue(actual.next()); } assertFalse(actual.next()); }