focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public boolean isReasonablyCertain() { return distance < CERTAINTY_LIMIT; }
@Test public void testMixedLanguages() throws IOException { for (String language : languages) { for (String other : languages) { if (!language.equals(other)) { if (language.equals("lt") || other.equals("lt")) { continue; } ProfilingWriter writer = new ProfilingWriter(); writeTo(language, writer); writeTo(other, writer); LanguageIdentifier identifier = null; identifier = new LanguageIdentifier(writer.getProfile()); assertFalse(identifier.isReasonablyCertain(), "mix of " + language + " and " + other + " incorrectly detected as " + identifier); } } } }
public static <T> T[] getBeans(Class<T> interfaceClass) { Object object = serviceMap.get(interfaceClass.getName()); if(object == null) return null; if(object instanceof Object[]) { return (T[])object; } else { Object array = Array.newInstance(interfaceClass, 1); Array.set(array, 0, object); return (T[])array; } }
@Test public void testMultipleToMultiple() { E[] e = SingletonServiceFactory.getBeans(E.class); Arrays.stream(e).forEach(o -> logger.debug(o.e())); F[] f = SingletonServiceFactory.getBeans(F.class); Arrays.stream(f).forEach(o -> logger.debug(o.f())); }
public TbMsgMetaData copy() { return new TbMsgMetaData(this.data); }
@Test public void testScript_whenMetadataWithPropertiesValueNull_returnMetadataWithoutPropertiesValueEqualsNull() { metadataExpected.put("deviceName", null); TbMsgMetaData tbMsgMetaData = new TbMsgMetaData(metadataExpected); Map<String, String> dataActual = tbMsgMetaData.copy().getData(); assertEquals(metadataExpected.size() - 1, dataActual.size()); }
private SelectorData buildDefaultSelectorData(final SelectorData selectorData) { if (StringUtils.isEmpty(selectorData.getId())) { selectorData.setId(UUIDUtils.getInstance().generateShortUuid()); } if (StringUtils.isEmpty(selectorData.getName())) { selectorData.setName(selectorData.getPluginName() + ":selector" + RandomUtils.nextInt(1, 1000)); } if (Objects.isNull(selectorData.getMatchMode())) { selectorData.setMatchMode(MatchModeEnum.AND.getCode()); } if (Objects.isNull(selectorData.getType())) { selectorData.setType(SelectorTypeEnum.FULL_FLOW.getCode()); } if (Objects.isNull(selectorData.getSort())) { selectorData.setSort(10); } if (Objects.isNull(selectorData.getEnabled())) { selectorData.setEnabled(true); } if (Objects.isNull(selectorData.getLogged())) { selectorData.setLogged(false); } if (Objects.isNull(selectorData.getMatchRestful())) { selectorData.setMatchRestful(false); } return selectorData; }
@Test public void testBuildDefaultSelectorData() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method buildDefaultSelectorData = LocalPluginController.class.getDeclaredMethod("buildDefaultSelectorData", SelectorData.class); buildDefaultSelectorData.setAccessible(true); LocalPluginController localPluginController = mock(LocalPluginController.class); SelectorData selectorData = SelectorData.builder().id("id").name("name").sort(1) .enabled(true) .logged(true) .build(); buildDefaultSelectorData.invoke(localPluginController, selectorData); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest httpRequest) { HttpServletResponse httpResponse = (HttpServletResponse) response; try { chain.doFilter(new ServletRequestWrapper(httpRequest), httpResponse); } catch (Throwable e) { if (httpResponse.isCommitted()) { // Request has been aborted by the client, nothing can been done as Tomcat has committed the response LOGGER.debug(format("Processing of request %s failed", toUrl(httpRequest)), e); return; } LOGGER.error(format("Processing of request %s failed", toUrl(httpRequest)), e); httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { // Not an HTTP request, not profiled chain.doFilter(request, response); } }
@Test public void throwable_in_doFilter_is_caught_and_500_error_returned_if_response_is_not_committed() throws Exception { doThrow(new RuntimeException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); HttpServletResponse response = mockHttpResponse(false); underTest.doFilter(request("POST", "/context/service/call", "param=value"), response, chain); verify(response).sendError(500); }
public void removeJobMetricsGroup(JobID jobId) { if (jobId != null) { TaskManagerJobMetricGroup groupToClose; synchronized (this) { // synchronization isn't strictly necessary as of FLINK-24864 groupToClose = jobs.remove(jobId); } if (groupToClose != null) { groupToClose.close(); } } }
@Test void testRemoveNullJobID() { metricGroup.removeJobMetricsGroup(null); }
public static boolean isContentType(String contentType, Message message) { if (contentType == null) { return message.getContentType() == null; } else { return contentType.equals(message.getContentType()); } }
@Test public void testIsContentTypeWithNonNullStringValueAndNonNullMessageContentTypeNotEqual() { Message message = Proton.message(); message.setContentType("fails"); assertFalse(AmqpMessageSupport.isContentType("test", message)); }
List<MethodSpec> buildEventFunctions( AbiDefinition functionDefinition, TypeSpec.Builder classBuilder) throws ClassNotFoundException { String functionName = functionDefinition.getName(); List<AbiDefinition.NamedType> inputs = functionDefinition.getInputs(); String responseClassName = Strings.capitaliseFirstLetter(functionName) + "EventResponse"; List<NamedTypeName> parameters = new ArrayList<>(); List<NamedTypeName> indexedParameters = new ArrayList<>(); List<NamedTypeName> nonIndexedParameters = new ArrayList<>(); for (AbiDefinition.NamedType namedType : inputs) { final TypeName typeName; if (namedType.getType().equals("tuple")) { typeName = structClassNameMap.get(namedType.structIdentifier()); } else if (namedType.getType().startsWith("tuple") && namedType.getType().contains("[")) { typeName = buildStructArrayTypeName(namedType, false); } else { typeName = buildTypeName(namedType.getType(), useJavaPrimitiveTypes); } NamedTypeName parameter = new NamedTypeName(namedType, typeName); if (namedType.isIndexed()) { indexedParameters.add(parameter); } else { nonIndexedParameters.add(parameter); } parameters.add(parameter); } classBuilder.addField(createEventDefinition(functionName, parameters)); classBuilder.addType( buildEventResponseObject( responseClassName, indexedParameters, nonIndexedParameters)); List<MethodSpec> methods = new ArrayList<>(); methods.add( buildEventTransactionReceiptFunction( responseClassName, functionName, indexedParameters, nonIndexedParameters)); methods.add( buildEventLogFunction( responseClassName, functionName, indexedParameters, nonIndexedParameters)); methods.add( buildEventFlowableFunction( responseClassName, functionName, indexedParameters, nonIndexedParameters)); methods.add(buildDefaultEventFlowableFunction(responseClassName, functionName)); return methods; }
@Test public void testBuildEventConstantMultipleValueReturn() throws Exception { NamedType id = new NamedType("id", "string", true); NamedType fromAddress = new NamedType("from", "address"); NamedType toAddress = new NamedType("to", "address"); NamedType value = new NamedType("value", "uint256"); NamedType message = new NamedType("message", "string"); fromAddress.setIndexed(true); toAddress.setIndexed(true); AbiDefinition functionDefinition = new AbiDefinition( false, Arrays.asList(id, fromAddress, toAddress, value, message), "Transfer", new ArrayList<>(), "event", false); TypeSpec.Builder builder = TypeSpec.classBuilder("testClass"); builder.addMethods( solidityFunctionWrapper.buildEventFunctions(functionDefinition, builder)); String expected = "class testClass {\n" + " public static final org.web3j.abi.datatypes.Event TRANSFER_EVENT = new org.web3j.abi.datatypes.Event(\"Transfer\", \n" + " java.util.Arrays.<org.web3j.abi.TypeReference<?>>asList(new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.Utf8String>(true) {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.Address>(true) {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.Address>(true) {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.generated.Uint256>() {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.Utf8String>() {}));\n ;\n\n" + " public static java.util.List<TransferEventResponse> getTransferEvents(\n" + " org.web3j.protocol.core.methods.response.TransactionReceipt transactionReceipt) {\n" + " java.util.List<org.web3j.tx.Contract.EventValuesWithLog> valueList = staticExtractEventParametersWithLog(TRANSFER_EVENT, transactionReceipt);\n" + " java.util.ArrayList<TransferEventResponse> responses = new java.util.ArrayList<TransferEventResponse>(valueList.size());\n" + " for (org.web3j.tx.Contract.EventValuesWithLog eventValues : valueList) {\n" + " TransferEventResponse typedResponse = new TransferEventResponse();\n" + " typedResponse.log = eventValues.getLog();\n" + " typedResponse.id = (byte[]) eventValues.getIndexedValues().get(0).getValue();\n" + " typedResponse.from = (java.lang.String) eventValues.getIndexedValues().get(1).getValue();\n" + " typedResponse.to = (java.lang.String) eventValues.getIndexedValues().get(2).getValue();\n" + " typedResponse.value = (java.math.BigInteger) eventValues.getNonIndexedValues().get(0).getValue();\n" + " typedResponse.message = (java.lang.String) eventValues.getNonIndexedValues().get(1).getValue();\n" + " responses.add(typedResponse);\n" + " }\n" + " return responses;\n" + " }\n" + "\n" + " public static TransferEventResponse getTransferEventFromLog(\n" + " org.web3j.protocol.core.methods.response.Log log) {\n" + " org.web3j.tx.Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(TRANSFER_EVENT, log);\n" + " TransferEventResponse typedResponse = new TransferEventResponse();\n" + " typedResponse.log = log;\n" + " typedResponse.id = (byte[]) eventValues.getIndexedValues().get(0).getValue();\n" + " typedResponse.from = (java.lang.String) eventValues.getIndexedValues().get(1).getValue();\n" + " typedResponse.to = (java.lang.String) eventValues.getIndexedValues().get(2).getValue();\n" + " typedResponse.value = (java.math.BigInteger) eventValues.getNonIndexedValues().get(0).getValue();\n" + " typedResponse.message = (java.lang.String) eventValues.getNonIndexedValues().get(1).getValue();\n" + " return typedResponse;\n" + " }\n" + "\n" + " public io.reactivex.Flowable<TransferEventResponse> transferEventFlowable(\n" + " org.web3j.protocol.core.methods.request.EthFilter filter) {\n" + " return web3j.ethLogFlowable(filter).map(log -> getTransferEventFromLog(log));\n" + " }\n" + "\n" + " public io.reactivex.Flowable<TransferEventResponse> transferEventFlowable(\n" + " org.web3j.protocol.core.DefaultBlockParameter startBlock,\n" + " org.web3j.protocol.core.DefaultBlockParameter endBlock) {\n" + " org.web3j.protocol.core.methods.request.EthFilter filter = new org.web3j.protocol.core.methods.request.EthFilter(startBlock, endBlock, getContractAddress());\n" + " filter.addSingleTopic(org.web3j.abi.EventEncoder.encode(TRANSFER_EVENT));\n" + " return transferEventFlowable(filter);\n" + " }\n" + "\n" + " public static class TransferEventResponse extends org.web3j.protocol.core.methods.response.BaseEventResponse {\n" + " public byte[] id;\n" + "\n" + " public java.lang.String from;\n" + "\n" + " public java.lang.String to;\n" + "\n" + " public java.math.BigInteger value;\n" + "\n" + " public java.lang.String message;\n" + " }\n" + "}\n"; assertEquals(expected, builder.build().toString()); }
synchronized Optional<ExecutableWork> completeWorkAndGetNextWorkForKey( ShardedKey shardedKey, WorkId workId) { @Nullable Queue<ExecutableWork> workQueue = activeWork.get(shardedKey); if (workQueue == null) { // Work may have been completed due to clearing of stuck commits. LOG.warn("Unable to complete inactive work for key {} and token {}.", shardedKey, workId); return Optional.empty(); } removeCompletedWorkFromQueue(workQueue, shardedKey, workId); return getNextWork(workQueue, shardedKey); }
@Test public void testCompleteWorkAndGetNextWorkForKey_noWorkQueueForKey() { assertEquals( Optional.empty(), activeWorkState.completeWorkAndGetNextWorkForKey( shardedKey("someKey", 1L), workId(1L, 1L))); }
public static Thread daemonThread(Runnable r, Class<?> context, String description) { return daemonThread(r, "hollow", context, description); }
@Test public void nullRunnable() { try { daemonThread(null, getClass(), "boom"); fail("expected an exception"); } catch (NullPointerException e) { assertEquals("runnable required", e.getMessage()); } }
public synchronized <K, V> KStream<K, V> stream(final String topic) { return stream(Collections.singleton(topic)); }
@Test public void shouldThrowWhenSubscribedToATopicWithUnsetAndSetResetPolicies() { builder.stream("another-topic"); builder.stream("another-topic", Consumed.with(AutoOffsetReset.LATEST)); assertThrows(TopologyException.class, builder::build); }
@Override public long getSetOperationCount() { throw new UnsupportedOperationException("Set operation on replicated maps is not supported."); }
@Test(expected = UnsupportedOperationException.class) public void testSetOperationCount() { localReplicatedMapStats.getSetOperationCount(); }
@Override public void checkBeforeUpdate(final AlterReadwriteSplittingRuleStatement sqlStatement) { ReadwriteSplittingRuleStatementChecker.checkAlteration(database, sqlStatement.getRules(), rule.getConfiguration()); }
@Test void assertCheckSQLStatementWithoutToBeAlteredRules() { ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class); when(rule.getConfiguration()).thenReturn(new ReadwriteSplittingRuleConfiguration(Collections.emptyList(), Collections.emptyMap())); executor.setRule(rule); assertThrows(MissingRequiredRuleException.class, () -> executor.checkBeforeUpdate(createSQLStatement("TEST"))); }
public static long getNextScheduledTime(final String cronEntry, long currentTime) throws MessageFormatException { long result = 0; if (cronEntry == null || cronEntry.length() == 0) { return result; } // Handle the once per minute case "* * * * *" // starting the next event at the top of the minute. if (cronEntry.equals("* * * * *")) { result = currentTime + 60 * 1000; result = result / 60000 * 60000; return result; } List<String> list = tokenize(cronEntry); List<CronEntry> entries = buildCronEntries(list); Calendar working = Calendar.getInstance(); working.setTimeInMillis(currentTime); working.set(Calendar.SECOND, 0); CronEntry minutes = entries.get(MINUTES); CronEntry hours = entries.get(HOURS); CronEntry dayOfMonth = entries.get(DAY_OF_MONTH); CronEntry month = entries.get(MONTH); CronEntry dayOfWeek = entries.get(DAY_OF_WEEK); // Start at the top of the next minute, cron is only guaranteed to be // run on the minute. int timeToNextMinute = 60 - working.get(Calendar.SECOND); working.add(Calendar.SECOND, timeToNextMinute); // If its already to late in the day this will roll us over to tomorrow // so we'll need to check again when done updating month and day. int currentMinutes = working.get(Calendar.MINUTE); if (!isCurrent(minutes, currentMinutes)) { int nextMinutes = getNext(minutes, currentMinutes, working); working.add(Calendar.MINUTE, nextMinutes); } int currentHours = working.get(Calendar.HOUR_OF_DAY); if (!isCurrent(hours, currentHours)) { int nextHour = getNext(hours, currentHours, working); working.add(Calendar.HOUR_OF_DAY, nextHour); } // We can roll into the next month here which might violate the cron setting // rules so we check once then recheck again after applying the month settings. doUpdateCurrentDay(working, dayOfMonth, dayOfWeek); // Start by checking if we are in the right month, if not then calculations // need to start from the beginning of the month to ensure that we don't end // up on the wrong day. (Can happen when DAY_OF_WEEK is set and current time // is ahead of the day of the week to execute on). doUpdateCurrentMonth(working, month); // Now Check day of week and day of month together since they can be specified // together in one entry, if both "day of month" and "day of week" are restricted // (not "*"), then either the "day of month" field (3) or the "day of week" field // (5) must match the current day or the Calenday must be advanced. doUpdateCurrentDay(working, dayOfMonth, dayOfWeek); // Now we can chose the correct hour and minute of the day in question. currentHours = working.get(Calendar.HOUR_OF_DAY); if (!isCurrent(hours, currentHours)) { int nextHour = getNext(hours, currentHours, working); working.add(Calendar.HOUR_OF_DAY, nextHour); } currentMinutes = working.get(Calendar.MINUTE); if (!isCurrent(minutes, currentMinutes)) { int nextMinutes = getNext(minutes, currentMinutes, working); working.add(Calendar.MINUTE, nextMinutes); } result = working.getTimeInMillis(); if (result <= currentTime) { throw new ArithmeticException("Unable to compute next scheduled exection time."); } return result; }
@Test public void testgetNextTimeHoursZeroMin() throws MessageFormatException { String test = "0 1 * * *"; Calendar calender = Calendar.getInstance(); calender.set(1972, 2, 2, 17, 10, 0); long current = calender.getTimeInMillis(); long next = CronParser.getNextScheduledTime(test, current); calender.setTimeInMillis(next); long result = next - current; long expected = 60*1000*60*7 + 60*1000*50; assertEquals(expected,result); }
@Override public Integer call() throws Exception { return this.call( Flow.class, yamlFlowParser, modelValidator, (Object object) -> { Flow flow = (Flow) object; return flow.getNamespace() + " / " + flow.getId(); }, (Object object) -> { Flow flow = (Flow) object; List<String> warnings = new ArrayList<>(); warnings.addAll(flowService.deprecationPaths(flow).stream().map(deprecation -> deprecation + " is deprecated").toList()); warnings.addAll(flowService.relocations(flow.generateSource()).stream().map(relocation -> relocation.from() + " is replaced by " + relocation.to()).toList()); warnings.addAll(flowService.warnings(flow)); return warnings; } ); }
@Test void warning() { ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); try (ApplicationContext ctx = ApplicationContext.builder().deduceEnvironment(false).start()) { String[] args = { "--local", "src/test/resources/warning/flow-with-warning.yaml" }; Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args); assertThat(call, is(0)); assertThat(out.toString(), containsString("tasks[0] is deprecated")); assertThat(out.toString(), containsString("The system namespace is reserved for background workflows")); } }
public MailConfiguration getConfiguration() { if (configuration == null) { configuration = new MailConfiguration(getCamelContext()); } return configuration; }
@Test public void testConnectionTimeout() { MailEndpoint endpoint = checkEndpoint("smtp://james@myhost?password=secret&connectionTimeout=2500"); MailConfiguration config = endpoint.getConfiguration(); assertEquals(2500, config.getConnectionTimeout()); }
@Override public void increment(@Nonnull UUID txnId, boolean backup) { if (txnId.equals(NULL_UUID)) { return; } reservedCapacityCountByTxId.compute(txnId, (ignored, currentCapacityCount) -> { if (backup) { nodeWideUsedCapacityCounter.add(1L); } else { nodeWideUsedCapacityCounter.checkAndAddCapacityOrThrowException(1); } return currentCapacityCount == null ? 1L : (currentCapacityCount + 1L); }); }
@Test public void increment() { UUID txnId = UuidUtil.newSecureUUID(); for (int i = 0; i < 11; i++) { counter.increment(txnId, false); } Map<UUID, Long> countPerTxnId = counter.getReservedCapacityCountPerTxnId(); long count = countPerTxnId.get(txnId); assertEquals(11L, count); assertEquals(11L, nodeWideUsedCapacityCounter.currentValue()); }
public String getTopicName() { return topicName == null ? INVALID_TOPIC_NAME : topicName; }
@Test public void shouldUseNameFromWithClause() { // When: final TopicProperties properties = new TopicProperties.Builder() .withWithClause( Optional.of("name"), Optional.of(1), Optional.empty(), Optional.of((long) 100) ) .build(); // Then: assertThat(properties.getTopicName(), equalTo("name")); }
@Override public <T> Optional<List<T>> getListProperty(String key, Class<T> itemType) { var targetKey = targetPropertyName(key); var listResult = binder.bind(targetKey, Bindable.listOf(itemType)); return listResult.isBound() ? Optional.of(listResult.get()) : Optional.empty(); }
@Test void resolvesListProperties() { env.setProperty("prop.0.strLst", "v1,v2,v3"); env.setProperty("prop.0.intLst", "1,2,3"); var resolver = new PropertyResolverImpl(env); assertThat(resolver.getListProperty("prop.0.strLst", String.class)) .hasValue(List.of("v1", "v2", "v3")); assertThat(resolver.getListProperty("prop.0.intLst", Integer.class)) .hasValue(List.of(1, 2, 3)); }
@Override public String execute(CommandContext commandContext, String[] args) { if (ArrayUtils.isEmpty(args)) { return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" + "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" + "invoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})"; } Channel channel = commandContext.getRemote(); String service = channel.attr(ChangeTelnet.SERVICE_KEY) != null ? channel.attr(ChangeTelnet.SERVICE_KEY).get() : null; String message = args[0]; int i = message.indexOf("("); if (i < 0 || !message.endsWith(")")) { return "Invalid parameters, format: service.method(args)"; } String method = message.substring(0, i).trim(); String param = message.substring(i + 1, message.length() - 1).trim(); i = method.lastIndexOf("."); if (i >= 0) { service = method.substring(0, i).trim(); method = method.substring(i + 1).trim(); } if (StringUtils.isEmpty(service)) { return "If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first," + " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]"; } List<Object> list; try { list = JsonUtils.toJavaList("[" + param + "]", Object.class); } catch (Throwable t) { return "Invalid json argument, cause: " + t.getMessage(); } StringBuilder buf = new StringBuilder(); Method invokeMethod = null; ProviderModel selectedProvider = null; if (isInvokedSelectCommand(channel)) { selectedProvider = channel.attr(INVOKE_METHOD_PROVIDER_KEY).get(); invokeMethod = channel.attr(SelectTelnet.SELECT_METHOD_KEY).get(); } else { for (ProviderModel provider : frameworkModel.getServiceRepository().allProviderModels()) { if (!isServiceMatch(service, provider)) { continue; } selectedProvider = provider; List<Method> methodList = findSameSignatureMethod(provider.getAllMethods(), method, list); if (CollectionUtils.isEmpty(methodList)) { break; } if (methodList.size() == 1) { invokeMethod = methodList.get(0); } else { List<Method> matchMethods = findMatchMethods(methodList, list); if (CollectionUtils.isEmpty(matchMethods)) { break; } if (matchMethods.size() == 1) { invokeMethod = matchMethods.get(0); } else { // exist overridden method channel.attr(INVOKE_METHOD_PROVIDER_KEY).set(provider); channel.attr(INVOKE_METHOD_LIST_KEY).set(matchMethods); channel.attr(INVOKE_MESSAGE_KEY).set(message); printSelectMessage(buf, matchMethods); return buf.toString(); } } break; } } if (!StringUtils.isEmpty(service)) { buf.append("Use default service ").append(service).append('.'); } if (selectedProvider == null) { buf.append("\r\nNo such service ").append(service); return buf.toString(); } if (invokeMethod == null) { buf.append("\r\nNo such method ") .append(method) .append(" in service ") .append(service); return buf.toString(); } try { Object[] array = realize(list.toArray(), invokeMethod.getParameterTypes(), invokeMethod.getGenericParameterTypes()); long start = System.currentTimeMillis(); AppResponse result = new AppResponse(); try { Object o = invokeMethod.invoke(selectedProvider.getServiceInstance(), array); boolean setValueDone = false; if (RpcContext.getServerAttachment().isAsyncStarted()) { AsyncContext asyncContext = RpcContext.getServerAttachment().getAsyncContext(); if (asyncContext instanceof AsyncContextImpl) { CompletableFuture<Object> internalFuture = ((AsyncContextImpl) asyncContext).getInternalFuture(); result.setValue(internalFuture.get()); setValueDone = true; } } if (!setValueDone) { result.setValue(o); } } catch (Throwable t) { result.setException(t); if (t instanceof InterruptedException) { Thread.currentThread().interrupt(); } } finally { RpcContext.removeContext(); } long end = System.currentTimeMillis(); buf.append("\r\nresult: "); buf.append(JsonUtils.toJson(result.recreate())); buf.append("\r\nelapsed: "); buf.append(end - start); buf.append(" ms."); } catch (Throwable t) { return "Failed to invoke method " + invokeMethod.getName() + ", cause: " + StringUtils.toString(t); } return buf.toString(); }
@Test void testInvokeMethodWithMapParameter() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = "{1:\"Dubbo\",2:\"test\"}"; String result = invoke.execute(mockCommandContext, new String[] {"getMap(" + param + ")"}); assertTrue(result.contains("result: {1:\"Dubbo\",2:\"test\"}")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); }
public static void rename( List<ResourceId> srcResourceIds, List<ResourceId> destResourceIds, MoveOptions... moveOptions) throws IOException { validateSrcDestLists(srcResourceIds, destResourceIds); if (srcResourceIds.isEmpty()) { return; } renameInternal( getFileSystemInternal(srcResourceIds.iterator().next().getScheme()), srcResourceIds, destResourceIds, moveOptions); }
@Test public void testRenameIgnoreMissingFiles() throws Exception { Path srcPath1 = temporaryFolder.newFile().toPath(); Path nonExistentPath = srcPath1.resolveSibling("non-existent"); Path srcPath3 = temporaryFolder.newFile().toPath(); Path destPath1 = srcPath1.resolveSibling("dest1"); Path destPath2 = nonExistentPath.resolveSibling("dest2"); Path destPath3 = srcPath1.resolveSibling("dest3"); createFileWithContent(srcPath1, "content1"); createFileWithContent(srcPath3, "content3"); FileSystems.rename( toResourceIds( ImmutableList.of(srcPath1, nonExistentPath, srcPath3), false /* isDirectory */), toResourceIds(ImmutableList.of(destPath1, destPath2, destPath3), false /* isDirectory */), MoveOptions.StandardMoveOptions.IGNORE_MISSING_FILES); assertFalse(srcPath1.toFile().exists()); assertFalse(srcPath3.toFile().exists()); assertThat( Files.readLines(destPath1.toFile(), StandardCharsets.UTF_8), containsInAnyOrder("content1")); assertFalse(destPath2.toFile().exists()); assertThat( Files.readLines(destPath3.toFile(), StandardCharsets.UTF_8), containsInAnyOrder("content3")); }
public String abbreviate(String fqClassName) { if (fqClassName == null) { throw new IllegalArgumentException("Class name may not be null"); } int inLen = fqClassName.length(); if (inLen < targetLength) { return fqClassName; } StringBuilder buf = new StringBuilder(inLen); int rightMostDotIndex = fqClassName.lastIndexOf(DOT); if (rightMostDotIndex == -1) return fqClassName; // length of last segment including the dot int lastSegmentLength = inLen - rightMostDotIndex; int leftSegments_TargetLen = targetLength - lastSegmentLength; if (leftSegments_TargetLen < 0) leftSegments_TargetLen = 0; int leftSegmentsLen = inLen - lastSegmentLength; // maxPossibleTrim denotes the maximum number of characters we aim to trim // the actual number of character trimmed may be higher since segments, when // reduced, are reduced to just one character int maxPossibleTrim = leftSegmentsLen - leftSegments_TargetLen; int trimmed = 0; boolean inDotState = true; int i = 0; for (; i < rightMostDotIndex; i++) { char c = fqClassName.charAt(i); if (c == DOT) { // if trimmed too many characters, let us stop if (trimmed >= maxPossibleTrim) break; buf.append(c); inDotState = true; } else { if (inDotState) { buf.append(c); inDotState = false; } else { trimmed++; } } } // append from the position of i which may include the last seen DOT buf.append(fqClassName.substring(i)); return buf.toString(); }
@Test public void testTwoDot() { { TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); String name = "com.logback.Foobar"; assertEquals("c.l.Foobar", abbreviator.abbreviate(name)); } { TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); String name = "c.logback.Foobar"; assertEquals("c.l.Foobar", abbreviator.abbreviate(name)); } { TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); String name = "c..Foobar"; assertEquals("c..Foobar", abbreviator.abbreviate(name)); } { TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); String name = "..Foobar"; assertEquals("..Foobar", abbreviator.abbreviate(name)); } }
public static List<AclEntry> filterAclEntriesByAclSpec( List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry existingEntry: existingAcl) { if (aclSpec.containsKey(existingEntry)) { scopeDirty.add(existingEntry.getScope()); if (existingEntry.getType() == MASK) { maskDirty.add(existingEntry.getScope()); } } else { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); }
@Test public void testFilterAclEntriesByAclSpecAutomaticDefaultGroup() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, READ)) .add(aclEntry(DEFAULT, USER, READ_WRITE)) .add(aclEntry(DEFAULT, GROUP, READ_WRITE)) .add(aclEntry(DEFAULT, OTHER, NONE)) .build(); List<AclEntry> aclSpec = Lists.newArrayList( aclEntry(DEFAULT, GROUP)); List<AclEntry> expected = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, READ)) .add(aclEntry(DEFAULT, USER, READ_WRITE)) .add(aclEntry(DEFAULT, GROUP, READ)) .add(aclEntry(DEFAULT, OTHER, NONE)) .build(); assertEquals(expected, filterAclEntriesByAclSpec(existing, aclSpec)); }
long useService(int value) { var result = serviceAmbassador.doRemoteFunction(value); LOGGER.info("Service result: {}", result); return result; }
@Test void test() { Client client = new Client(); var result = client.useService(10); assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue()); }
public Node parse() throws ScanException { return E(); }
@Test public void testNested() throws Exception { { Parser<Object> p = new Parser("%top %(%child%(%h))"); Node t = p.parse(); Node witness = new SimpleKeywordNode("top"); Node w = witness.next = new Node(Node.LITERAL, " "); CompositeNode composite = new CompositeNode(BARE); w = w.next = composite; Node child = new SimpleKeywordNode("child"); composite.setChildNode(child); composite = new CompositeNode(BARE); child.next = composite; composite.setChildNode(new SimpleKeywordNode("h")); assertEquals(witness, t); } }
@VisibleForTesting public Set<NodeAttribute> parseAttributes(String config) throws IOException { if (Strings.isNullOrEmpty(config)) { return ImmutableSet.of(); } Set<NodeAttribute> attributeSet = new HashSet<>(); // Configuration value should be in one line, format: // "ATTRIBUTE_NAME,ATTRIBUTE_TYPE,ATTRIBUTE_VALUE", // multiple node-attributes are delimited by ":". // Each attribute str should not container any space. String[] attributeStrs = config.split(NODE_ATTRIBUTES_DELIMITER); for (String attributeStr : attributeStrs) { String[] fields = attributeStr.split(NODE_ATTRIBUTE_DELIMITER); if (fields.length != 3) { throw new IOException("Invalid value for " + YarnConfiguration.NM_PROVIDER_CONFIGURED_NODE_ATTRIBUTES + "=" + config); } // We don't allow user config to overwrite our dist prefix, // so disallow any prefix set in the configuration. if (fields[0].contains("/")) { throw new IOException("Node attribute set in " + YarnConfiguration.NM_PROVIDER_CONFIGURED_NODE_ATTRIBUTES + " should not contain any prefix."); } // Make sure attribute type is valid. if (!EnumUtils.isValidEnum(NodeAttributeType.class, fields[1])) { throw new IOException("Invalid node attribute type: " + fields[1] + ", valid values are " + Arrays.asList(NodeAttributeType.values())); } // Automatically setup prefix for collected attributes NodeAttribute na = NodeAttribute.newInstance( NodeAttribute.PREFIX_DISTRIBUTED, fields[0], NodeAttributeType.valueOf(fields[1]), fields[2]); // Since a NodeAttribute is identical with another one as long as // their prefix and name are same, to avoid attributes getting // overwritten by ambiguous attribute, make sure it fails in such // case. if (!attributeSet.add(na)) { throw new IOException("Ambiguous node attribute is found: " + na.toString() + ", a same attribute already exists"); } } // Before updating the attributes to the provider, // verify if they are valid try { NodeLabelUtil.validateNodeAttributes(attributeSet); } catch (IOException e) { throw new IOException("Node attributes set by configuration property: " + YarnConfiguration.NM_PROVIDER_CONFIGURED_NODE_ATTRIBUTES + " is not valid. Detail message: " + e.getMessage()); } return attributeSet; }
@Test public void testDisableFetchNodeAttributes() throws IOException, InterruptedException { Set<NodeAttribute> expectedAttributes1 = new HashSet<>(); expectedAttributes1.add(NodeAttribute .newInstance("test.io", "host", NodeAttributeType.STRING, "host1")); Configuration conf = new Configuration(); // Set fetch interval to -1 to disable refresh. conf.setLong( YarnConfiguration.NM_NODE_ATTRIBUTES_PROVIDER_FETCH_INTERVAL_MS, -1); ConfigurationNodeAttributesProvider spyProvider = Mockito.spy(nodeAttributesProvider); Mockito.when(spyProvider.parseAttributes(Mockito.any())) .thenReturn(expectedAttributes1); spyProvider.init(conf); spyProvider.start(); Assert.assertEquals(expectedAttributes1, spyProvider.getDescriptors()); // The configuration added another attribute, // as we disabled the fetch interval, this value cannot be // updated to the provider. Set<NodeAttribute> expectedAttributes2 = new HashSet<>(); expectedAttributes2.add(NodeAttribute .newInstance("test.io", "os", NodeAttributeType.STRING, "windows")); Mockito.when(spyProvider.parseAttributes(Mockito.anyString())) .thenReturn(expectedAttributes2); // Wait a few seconds until we get the value update, expecting a failure. try { GenericTestUtils.waitFor(() -> { Set<NodeAttribute> attributes = spyProvider.getDescriptors(); return "os".equalsIgnoreCase(attributes .iterator().next().getAttributeKey().getAttributeName()); }, 500, 1000); } catch (Exception e) { // Make sure we get the timeout exception. Assert.assertTrue(e instanceof TimeoutException); return; } Assert.fail("Expecting a failure in previous check!"); }
@Override public String toString() { StringBuilder b = new StringBuilder(); if (StringUtils.isNotBlank(protocol)) { b.append(protocol); b.append("://"); } if (StringUtils.isNotBlank(host)) { b.append(host); } if (!isPortDefault() && port != -1) { b.append(':'); b.append(port); } if (StringUtils.isNotBlank(path)) { // If no scheme/host/port, leave the path as is if (b.length() > 0 && !path.startsWith("/")) { b.append('/'); } b.append(encodePath(path)); } if (queryString != null && !queryString.isEmpty()) { b.append(queryString.toString()); } if (fragment != null) { b.append("#"); b.append(encodePath(fragment)); } return b.toString(); }
@Test public void testHttpProtocolNoPort() { s = "http://www.example.com/blah"; t = "http://www.example.com/blah"; assertEquals(t, new HttpURL(s).toString()); }
public static LogExceptionBehaviourInterface getExceptionStrategy( LogTableCoreInterface table ) { return getExceptionStrategy( table, null ); }
@Test public void testExceptionStrategyWithMysqlDataTruncationException() { DatabaseMeta databaseMeta = mock( DatabaseMeta.class ); DatabaseInterface databaseInterface = new MySQLDatabaseMeta(); MysqlDataTruncation e = new MysqlDataTruncation(); when( logTable.getDatabaseMeta() ).thenReturn( databaseMeta ); when( databaseMeta.getDatabaseInterface() ).thenReturn( databaseInterface ); LogExceptionBehaviourInterface exceptionStrategy = DatabaseLogExceptionFactory.getExceptionStrategy( logTable, new KettleDatabaseException( e ) ); String strategyName = exceptionStrategy.getClass().getName(); assertEquals( SUPPRESSABLE_WITH_SHORT_MESSAGE, strategyName ); }
@Override public CompletableFuture<Void> deleteKvConfig(String address, DeleteKVConfigRequestHeader requestHeader, long timeoutMillis) { CompletableFuture<Void> future = new CompletableFuture<>(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_KV_CONFIG, requestHeader); remotingClient.invoke(address, request, timeoutMillis).thenAccept(response -> { if (response.getCode() == ResponseCode.SUCCESS) { future.complete(null); } else { log.warn("deleteKvConfig getResponseCommand failed, {} {}, header={}", response.getCode(), response.getRemark(), requestHeader); future.completeExceptionally(new MQClientException(response.getCode(), response.getRemark())); } }); return future; }
@Test public void assertDeleteKvConfigWithError() { setResponseError(); DeleteKVConfigRequestHeader requestHeader = mock(DeleteKVConfigRequestHeader.class); CompletableFuture<Void> actual = mqClientAdminImpl.deleteKvConfig(defaultBrokerAddr, requestHeader, defaultTimeout); Throwable thrown = assertThrows(ExecutionException.class, actual::get); assertTrue(thrown.getCause() instanceof MQClientException); MQClientException mqException = (MQClientException) thrown.getCause(); assertEquals(ResponseCode.SYSTEM_ERROR, mqException.getResponseCode()); assertTrue(mqException.getMessage().contains("CODE: 1 DESC: null")); }
public void parseFile(final InputStream inStream) { final BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, IoUtils.UTF8_CHARSET)); try { startSheet(); processRows(reader); finishSheet(); } catch (final IOException e) { throw new DecisionTableParseException( "An error occurred reading the CSV data.", e); } }
@Test public void testCsv() { final MockSheetListener listener = new MockSheetListener(); final CsvLineParser lineParser = new CsvLineParser(); final CsvParser parser = new CsvParser(listener, lineParser); parser.parseFile(getClass().getResourceAsStream("/data/TestCsv.drl.csv")); assertThat(listener.getCell(0, 0)).isEqualTo("A"); assertThat(listener.getCell(0, 1)).isEqualTo("B"); assertThat(listener.getCell(2, 0)).isEqualTo(""); assertThat(listener.getCell(1, 0)).isEqualTo("C"); assertThat(listener.getCell(1, 1)).isEqualTo("D"); assertThat(listener.getCell(1, 3)).isEqualTo("E"); }
public static int chineseToNumber(String chinese) { final int length = chinese.length(); int result = 0; // ่Š‚ๆ€ปๅ’Œ int section = 0; int number = 0; ChineseUnit unit = null; char c; for (int i = 0; i < length; i++) { c = chinese.charAt(i); final int num = chineseToNumber(c); if (num >= 0) { if (num == 0) { // ้‡ๅˆฐ้›ถๆ—ถ่Š‚็ป“ๆŸ๏ผŒๆƒไฝๅคฑๆ•ˆ๏ผŒๆฏ”ๅฆ‚ไธคไธ‡ไบŒ้›ถไธ€ๅ if (number > 0 && null != unit) { section += number * (unit.value / 10); } unit = null; } else if (number > 0) { // ๅคšไธชๆ•ฐๅญ—ๅŒๆ—ถๅ‡บ็Žฐ๏ผŒๆŠฅ้”™ throw new IllegalArgumentException(StrUtil.format("Bad number '{}{}' at: {}", chinese.charAt(i - 1), c, i)); } // ๆ™ฎ้€šๆ•ฐๅญ— number = num; } else { unit = chineseToUnit(c); if (null == unit) { // ๅ‡บ็Žฐ้žๆณ•ๅญ—็ฌฆ throw new IllegalArgumentException(StrUtil.format("Unknown unit '{}' at: {}", c, i)); } //ๅ•ไฝ if (unit.secUnit) { // ่Š‚ๅ•ไฝ๏ผŒๆŒ‰็…ง่Š‚ๆฑ‚ๅ’Œ section = (section + number) * unit.value; result += section; section = 0; } else { // ้ž่Š‚ๅ•ไฝ๏ผŒๅ’Œๅ•ไฝๅ‰็š„ๅ•ๆ•ฐๅญ—็ป„ๅˆไธบๅ€ผ int unitNumber = number; if (0 == number && 0 == i) { // issue#1726๏ผŒๅฏนไบŽๅ•ไฝๅผ€ๅคด็š„ๆ•ฐ็ป„๏ผŒ้ป˜่ฎค่ต‹ไบˆ1 // ๅไบŒ -> ไธ€ๅไบŒ // ็™พไบŒ -> ไธ€็™พไบŒ unitNumber = 1; } section += (unitNumber * unit.value); } number = 0; } } if (number > 0 && null != unit) { number = number * (unit.value / 10); } return result + section + number; }
@Test public void chineseToNumberTest3() { // issue#1726๏ผŒๅฏนไบŽๅ•ไฝๅผ€ๅคด็š„ๆ•ฐ็ป„๏ผŒ้ป˜่ฎค่ต‹ไบˆ1 // ๅไบŒ -> ไธ€ๅไบŒ // ็™พไบŒ -> ไธ€็™พไบŒ assertEquals(12, NumberChineseFormatter.chineseToNumber("ๅไบŒ")); assertEquals(120, NumberChineseFormatter.chineseToNumber("็™พไบŒ")); assertEquals(1300, NumberChineseFormatter.chineseToNumber("ๅƒไธ‰")); }
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 coerceCorrectConstructorArgumentsArgumentsAreNull() { Assertions.assertThatThrownBy( () -> MethodResolutionUtils.coerceCorrectConstructorArguments( Person.class, null, null)) .isInstanceOf(NullPointerException.class); }
@Override public boolean isOutput() { return false; }
@Test public void testIsOutput() throws Exception { assertFalse( analyzer.isOutput() ); }
static String getMessageForInvalidTag(String paramName) { return String.format( "@%1$s is not a valid tag, but is a parameter name. " + "Use {@code %1$s} to refer to parameter names inline.", paramName); }
@Test public void invalidTagMessage() { assertEquals( "@type is not a valid tag, but is a parameter name. Use {@code type} to refer to parameter" + " names inline.", InvalidInlineTag.getMessageForInvalidTag("type")); }
PartitionsOnReplicaIterator iterator(int brokerId, boolean leadersOnly) { Map<Uuid, int[]> topicMap = isrMembers.get(brokerId); if (topicMap == null) { topicMap = Collections.emptyMap(); } return new PartitionsOnReplicaIterator(topicMap, leadersOnly); }
@Test public void testIterator() { SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext()); BrokersToIsrs brokersToIsrs = new BrokersToIsrs(snapshotRegistry); assertEquals(toSet(), toSet(brokersToIsrs.iterator(1, false))); brokersToIsrs.update(UUIDS[0], 0, null, new int[] {1, 2, 3}, -1, 1); brokersToIsrs.update(UUIDS[1], 1, null, new int[] {2, 3, 4}, -1, 4); assertEquals(toSet(new TopicIdPartition(UUIDS[0], 0)), toSet(brokersToIsrs.iterator(1, false))); assertEquals(toSet(new TopicIdPartition(UUIDS[0], 0), new TopicIdPartition(UUIDS[1], 1)), toSet(brokersToIsrs.iterator(2, false))); assertEquals(toSet(new TopicIdPartition(UUIDS[1], 1)), toSet(brokersToIsrs.iterator(4, false))); assertEquals(toSet(), toSet(brokersToIsrs.iterator(5, false))); brokersToIsrs.update(UUIDS[1], 2, null, new int[] {3, 2, 1}, -1, 3); assertEquals(toSet(new TopicIdPartition(UUIDS[0], 0), new TopicIdPartition(UUIDS[1], 1), new TopicIdPartition(UUIDS[1], 2)), toSet(brokersToIsrs.iterator(2, false))); }
boolean shouldReplicateTopic(String topic) { return (topicFilter.shouldReplicateTopic(topic) || replicationPolicy.isHeartbeatsTopic(topic)) && !replicationPolicy.isInternalTopic(topic) && !isCycle(topic); }
@Test public void testReplicatesHeartbeatsDespiteFilter() { DefaultReplicationPolicy defaultReplicationPolicy = new DefaultReplicationPolicy(); MirrorSourceConnector connector = new MirrorSourceConnector(new SourceAndTarget("source", "target"), defaultReplicationPolicy, x -> false, new DefaultConfigPropertyFilter()); assertTrue(connector.shouldReplicateTopic("heartbeats"), "should replicate heartbeats"); assertTrue(connector.shouldReplicateTopic("us-west.heartbeats"), "should replicate upstream heartbeats"); Map<String, ?> configs = Collections.singletonMap(DefaultReplicationPolicy.SEPARATOR_CONFIG, "_"); defaultReplicationPolicy.configure(configs); assertTrue(connector.shouldReplicateTopic("heartbeats"), "should replicate heartbeats"); assertFalse(connector.shouldReplicateTopic("us-west.heartbeats"), "should not consider this topic as a heartbeats topic"); }
@Override public void setOnKeyboardActionListener(OnKeyboardActionListener keyboardActionListener) { FrameKeyboardViewClickListener frameKeyboardViewClickListener = new FrameKeyboardViewClickListener(keyboardActionListener); frameKeyboardViewClickListener.registerOnViews(this); final Context context = getContext(); final List<QuickTextKey> list = new ArrayList<>(); // always starting with Recent final HistoryQuickTextKey historyQuickTextKey = new HistoryQuickTextKey(context, mQuickKeyHistoryRecords); list.add(historyQuickTextKey); // then all the rest list.addAll(AnyApplication.getQuickTextKeyFactory(context).getEnabledAddOns()); final QuickTextUserPrefs quickTextUserPrefs = new QuickTextUserPrefs(context); final ViewPagerWithDisable pager = findViewById(R.id.quick_text_keyboards_pager); final QuickKeysKeyboardPagerAdapter adapter = new QuickKeysKeyboardPagerAdapter( context, pager, list, new RecordHistoryKeyboardActionListener(historyQuickTextKey, keyboardActionListener), mDefaultSkinTonePrefTracker, mDefaultGenderPrefTracker, mKeyboardTheme, mBottomPadding); final ImageView clearEmojiHistoryIcon = findViewById(R.id.quick_keys_popup_delete_recently_used_smileys); ViewPager.SimpleOnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { super.onPageSelected(position); QuickTextKey selectedKey = list.get(position); quickTextUserPrefs.setLastSelectedAddOnId(selectedKey.getId()); // if this is History, we need to show clear icon // else, hide the clear icon clearEmojiHistoryIcon.setVisibility(position == 0 ? View.VISIBLE : View.GONE); } }; int startPageIndex = quickTextUserPrefs.getStartPageIndex(list); setupSlidingTab( this, mTabTitleTextSize, mTabTitleTextColor, pager, adapter, onPageChangeListener, startPageIndex); // setting up icons from theme ((ImageView) findViewById(R.id.quick_keys_popup_close)).setImageDrawable(mCloseKeyboardIcon); ((ImageView) findViewById(R.id.quick_keys_popup_backspace)).setImageDrawable(mBackspaceIcon); ((ImageView) findViewById(R.id.quick_keys_popup_quick_keys_insert_media)) .setImageDrawable(mMediaInsertionDrawable); clearEmojiHistoryIcon.setImageDrawable(mDeleteRecentlyUsedDrawable); ((ImageView) findViewById(R.id.quick_keys_popup_quick_keys_settings)) .setImageDrawable(mSettingsIcon); final View actionsLayout = findViewById(R.id.quick_text_actions_layout); actionsLayout.setPadding( actionsLayout.getPaddingLeft(), actionsLayout.getPaddingTop(), actionsLayout.getPaddingRight(), // this will support the case were we have navigation-bar offset actionsLayout.getPaddingBottom() + mBottomPadding); }
@Test public void testPassesOnlyEnabledAddOns() throws Exception { final QuickTextKeyFactory quickTextKeyFactory = AnyApplication.getQuickTextKeyFactory(getApplicationContext()); Assert.assertEquals(17, quickTextKeyFactory.getAllAddOns().size()); Assert.assertEquals(17, quickTextKeyFactory.getEnabledAddOns().size()); quickTextKeyFactory.setAddOnEnabled(quickTextKeyFactory.getAllAddOns().get(0).getId(), false); Assert.assertEquals(17, quickTextKeyFactory.getAllAddOns().size()); Assert.assertEquals(16, quickTextKeyFactory.getEnabledAddOns().size()); OnKeyboardActionListener listener = Mockito.mock(OnKeyboardActionListener.class); mUnderTest.setOnKeyboardActionListener(listener); ViewPagerWithDisable pager = mUnderTest.findViewById(R.id.quick_text_keyboards_pager); Assert.assertEquals(16 + 1 /*history*/, pager.getAdapter().getCount()); quickTextKeyFactory.setAddOnEnabled(quickTextKeyFactory.getAllAddOns().get(1).getId(), false); mUnderTest.setOnKeyboardActionListener(listener); pager = mUnderTest.findViewById(R.id.quick_text_keyboards_pager); Assert.assertEquals(15 + 1 /*history*/, pager.getAdapter().getCount()); }
@Override public int size() { return count(members, selector); }
@Test public void testSizeWhenDataMembersSelected() { Collection<MemberImpl> collection = new MemberSelectingCollection<>(members, DATA_MEMBER_SELECTOR); assertEquals(1, collection.size()); }
public static Page createFileStatisticsPage(long fileSize, long rowCount) { // FileStatistics page layout: // // fileSize rowCount // X X PageBuilder statsPageBuilder = new PageBuilder(ImmutableList.of(BIGINT, BIGINT)); statsPageBuilder.declarePosition(); BIGINT.writeLong(statsPageBuilder.getBlockBuilder(FILE_SIZE_CHANNEL), fileSize); BIGINT.writeLong(statsPageBuilder.getBlockBuilder(ROW_COUNT_CHANNEL), rowCount); return statsPageBuilder.build(); }
@Test public void testCreateFileStatisticsPage() { Page statisticsPage = createFileStatisticsPage(FILE_SIZE, ROW_COUNT); assertEquals(statisticsPage.getPositionCount(), 1); assertEquals(statisticsPage.getChannelCount(), 2); }
@Override public boolean start() throws IOException { LOG.info("Starting reader using {}", initialCheckpointGenerator); try { shardReadersPool = createShardReadersPool(); shardReadersPool.start(); } catch (TransientKinesisException e) { throw new IOException(e); } return advance(); }
@Test public void startReturnsTrueIfSomeDataAvailable() throws IOException { when(shardReadersPool.nextRecord()) .thenReturn(CustomOptional.of(a)) .thenReturn(CustomOptional.absent()); assertThat(reader.start()).isTrue(); }
@Override public void afterComponent(Component component) { componentsWithUnprocessedIssues.remove(component.getUuid()); Optional<MovedFilesRepository.OriginalFile> originalFile = movedFilesRepository.getOriginalFile(component); if (originalFile.isPresent()) { componentsWithUnprocessedIssues.remove(originalFile.get().uuid()); } }
@Test public void also_remove_moved_files() { String uuid2 = "uuid2"; OriginalFile movedFile = new OriginalFile(uuid2, "key"); when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.of(movedFile)); underTest.afterComponent(component); verify(movedFilesRepository).getOriginalFile(component); verify(componentsWithUnprocessedIssues).remove(UUID); verify(componentsWithUnprocessedIssues).remove(uuid2); verifyNoMoreInteractions(componentsWithUnprocessedIssues); }
@Override public CoordinatorRecord deserialize( ByteBuffer keyBuffer, ByteBuffer valueBuffer ) throws RuntimeException { final short recordType = readVersion(keyBuffer, "key"); final ApiMessage keyMessage = apiMessageKeyFor(recordType); readMessage(keyMessage, keyBuffer, recordType, "key"); if (valueBuffer == null) { return new CoordinatorRecord(new ApiMessageAndVersion(keyMessage, recordType), null); } final ApiMessage valueMessage = apiMessageValueFor(recordType); final short valueVersion = readVersion(valueBuffer, "value"); readMessage(valueMessage, valueBuffer, valueVersion, "value"); return new CoordinatorRecord( new ApiMessageAndVersion(keyMessage, recordType), new ApiMessageAndVersion(valueMessage, valueVersion) ); }
@Test public void testDeserialize() { GroupCoordinatorRecordSerde serde = new GroupCoordinatorRecordSerde(); ApiMessageAndVersion key = new ApiMessageAndVersion( new ConsumerGroupMetadataKey().setGroupId("foo"), (short) 3 ); ByteBuffer keyBuffer = MessageUtil.toVersionPrefixedByteBuffer(key.version(), key.message()); ApiMessageAndVersion value = new ApiMessageAndVersion( new ConsumerGroupMetadataValue().setEpoch(10), (short) 0 ); ByteBuffer valueBuffer = MessageUtil.toVersionPrefixedByteBuffer(value.version(), value.message()); CoordinatorRecord record = serde.deserialize(keyBuffer, valueBuffer); assertEquals(key, record.key()); assertEquals(value, record.value()); }
@Override public void validatePostList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return; } // ่Žทๅพ—ๅฒ—ไฝไฟกๆฏ List<PostDO> posts = postMapper.selectBatchIds(ids); Map<Long, PostDO> postMap = convertMap(posts, PostDO::getId); // ๆ ก้ชŒ ids.forEach(id -> { PostDO post = postMap.get(id); if (post == null) { throw exception(POST_NOT_FOUND); } if (!CommonStatusEnum.ENABLE.getStatus().equals(post.getStatus())) { throw exception(POST_NOT_ENABLE, post.getName()); } }); }
@Test public void testValidatePostList_notEnable() { // mock ๆ•ฐๆฎ PostDO postDO = randomPostDO().setStatus(CommonStatusEnum.DISABLE.getStatus()); postMapper.insert(postDO); // ๅ‡†ๅค‡ๅ‚ๆ•ฐ List<Long> ids = singletonList(postDO.getId()); // ่ฐƒ็”จ, ๅนถๆ–ญ่จ€ๅผ‚ๅธธ assertServiceException(() -> postService.validatePostList(ids), POST_NOT_ENABLE, postDO.getName()); }
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@TestTemplate public void testPartitionedDays() throws Exception { createPartitionedTable(spark, tableName, "days(ts)"); SparkScanBuilder builder = scanBuilder(); DaysFunction.TimestampToDaysFunction function = new DaysFunction.TimestampToDaysFunction(); UserDefinedScalarFunc udf = toUDF(function, expressions(fieldRef("ts"))); Predicate predicate = new Predicate( "<", expressions( udf, dateLit(timestampStrToDayOrdinal("2018-11-20T00:00:00.000000+00:00")))); pushFilters(builder, predicate); Batch scan = builder.build().toBatch(); assertThat(scan.planInputPartitions().length).isEqualTo(5); // NOT LT builder = scanBuilder(); predicate = new Not(predicate); pushFilters(builder, predicate); scan = builder.build().toBatch(); assertThat(scan.planInputPartitions().length).isEqualTo(5); }
public boolean rollbackOn(Throwable ex) { RollbackRule winner = null; int deepest = Integer.MAX_VALUE; if (CollectionUtils.isNotEmpty(rollbackRules)) { winner = NoRollbackRule.DEFAULT_NO_ROLLBACK_RULE; for (RollbackRule rule : this.rollbackRules) { int depth = rule.getDepth(ex); if (depth >= 0 && depth < deepest) { deepest = depth; winner = rule; } } } return !(winner instanceof NoRollbackRule); }
@Test public void testRollBackOn() { TransactionInfo txInfo = new TransactionInfo(); //default true assertThat(txInfo.rollbackOn(new IllegalArgumentException())).isTrue(); assertThat(txInfo.rollbackOn(new Exception())).isTrue(); assertThat(txInfo.rollbackOn(new IOException())).isTrue(); assertThat(txInfo.rollbackOn(new NullPointerException())).isTrue(); Set<RollbackRule> sets = getRollbackRules(); txInfo.setRollbackRules(sets); assertThat(txInfo.rollbackOn(new IllegalArgumentException())).isTrue(); assertThat(txInfo.rollbackOn(new IllegalStateException())).isTrue(); assertThat(txInfo.rollbackOn(new IOException())).isFalse(); assertThat(txInfo.rollbackOn(new NullPointerException())).isFalse(); // not found return false assertThat(txInfo.rollbackOn(new MyRuntimeException("test"))).isFalse(); assertThat(txInfo.rollbackOn(new RuntimeException())).isFalse(); assertThat(txInfo.rollbackOn(new Throwable())).isFalse(); }
@Override public void restore(final Path file, final LoginCallback prompt) throws BackgroundException { final String nodeId = fileid.getFileId(file); try { new CoreRestControllerApi(session.getClient()).revertNode(nodeId); this.fileid.cache(file, null); } catch(ApiException e) { throw new DeepboxExceptionMappingService(fileid).map(e); } }
@Test public void restoreDirectory() throws Exception { final DeepboxIdProvider fileid = new DeepboxIdProvider(session); final Path documents = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path trash = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Trash/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path folder = new Path(documents, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); final Path subfolderWithContent = new Path(folder, new AlphanumericRandomStringService().random().toLowerCase(), EnumSet.of(Path.Type.directory)); final Path file = new Path(subfolderWithContent, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final Path folderInTrash = new Path(trash, folder.getName(), folder.getType()); final Path subfolderWithContentInTrash = new Path(folderInTrash, subfolderWithContent.getName(), EnumSet.of(Path.Type.directory)); final Path fileInTrash = new Path(subfolderWithContentInTrash, file.getName(), EnumSet.of(Path.Type.file)); new DeepboxDirectoryFeature(session, fileid).mkdir(folder, new TransferStatus()); final String folderId = new DeepboxAttributesFinderFeature(session, fileid).find(folder).getFileId(); assertTrue(new DeepboxFindFeature(session, fileid).find(folder)); new CoreRestControllerApi(session.getClient()).getNodeInfo(folderId, null, null, null); // assert no fail final String subFolderId = new DeepboxDirectoryFeature(session, fileid).mkdir(subfolderWithContent, new TransferStatus()).attributes().getFileId(); assertTrue(new DeepboxFindFeature(session, fileid).find(subfolderWithContent)); new DeepboxTouchFeature(session, fileid).touch(file, new TransferStatus()); final String nodeId = new DeepboxAttributesFinderFeature(session, fileid).find(file).getFileId(); assertTrue(new DeepboxFindFeature(session, fileid).find(folder.withAttributes(new PathAttributes()))); assertTrue(new DeepboxFindFeature(session, fileid).find(subfolderWithContent.withAttributes(new PathAttributes()))); assertTrue(new DeepboxFindFeature(session, fileid).find(file)); assertFalse(new DeepboxFindFeature(session, fileid).find(folderInTrash.withAttributes(new PathAttributes()))); assertFalse(new DeepboxFindFeature(session, fileid).find(subfolderWithContentInTrash.withAttributes(new PathAttributes()))); assertFalse(new DeepboxFindFeature(session, fileid).find(fileInTrash.withAttributes(new PathAttributes()))); new DeepboxTrashFeature(session, fileid).delete(Collections.singletonList(folder), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertThrows(NotfoundException.class, () -> fileid.getFileId(folder.withAttributes(new PathAttributes()))); assertThrows(NotfoundException.class, () -> fileid.getFileId(subfolderWithContent.withAttributes(new PathAttributes()))); assertThrows(NotfoundException.class, () -> fileid.getFileId(file.withAttributes(new PathAttributes()))); assertFalse(new DeepboxFindFeature(session, fileid).find(folder.withAttributes(new PathAttributes()))); assertFalse(new DeepboxFindFeature(session, fileid).find(subfolderWithContent.withAttributes(new PathAttributes()))); assertFalse(new DeepboxFindFeature(session, fileid).find(file.withAttributes(new PathAttributes()))); assertTrue(new DeepboxFindFeature(session, fileid).find(folderInTrash.withAttributes(new PathAttributes()))); assertTrue(new DeepboxFindFeature(session, fileid).find(subfolderWithContentInTrash.withAttributes(new PathAttributes()))); assertTrue(new DeepboxFindFeature(session, fileid).find(fileInTrash.withAttributes(new PathAttributes()))); assertEquals(folderId, new DeepboxAttributesFinderFeature(session, fileid).find(folderInTrash.withAttributes(new PathAttributes())).getFileId()); assertEquals(subFolderId, new DeepboxAttributesFinderFeature(session, fileid).find(subfolderWithContentInTrash.withAttributes(new PathAttributes())).getFileId()); assertEquals(nodeId, new DeepboxAttributesFinderFeature(session, fileid).find(fileInTrash.withAttributes(new PathAttributes())).getFileId()); final DeepboxRestoreFeature restore = new DeepboxRestoreFeature(session, fileid); restore.restore(folderInTrash, new DisabledLoginCallback()); assertTrue(new DeepboxFindFeature(session, fileid).find(folder.withAttributes(new PathAttributes()))); assertTrue(new DeepboxFindFeature(session, fileid).find(subfolderWithContent.withAttributes(new PathAttributes()))); assertTrue(new DeepboxFindFeature(session, fileid).find(file.withAttributes(new PathAttributes()))); assertFalse(new DeepboxFindFeature(session, fileid).find(folderInTrash.withAttributes(new PathAttributes()))); assertFalse(new DeepboxFindFeature(session, fileid).find(subfolderWithContentInTrash.withAttributes(new PathAttributes()))); assertFalse(new DeepboxFindFeature(session, fileid).find(fileInTrash.withAttributes(new PathAttributes()))); assertEquals(folderId, new DeepboxAttributesFinderFeature(session, fileid).find(folder.withAttributes(new PathAttributes())).getFileId()); assertEquals(subFolderId, new DeepboxAttributesFinderFeature(session, fileid).find(subfolderWithContent.withAttributes(new PathAttributes())).getFileId()); assertEquals(nodeId, new DeepboxAttributesFinderFeature(session, fileid).find(file.withAttributes(new PathAttributes())).getFileId()); new DeepboxDeleteFeature(session, fileid).delete(Collections.singletonList(folder.withAttributes(new PathAttributes())), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public static DataMap convertToDataMap(Map<String, Object> queryParams) { return convertToDataMap(queryParams, Collections.<String, Class<?>>emptyMap(), AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), RestLiProjectionDataMapSerializer.DEFAULT_SERIALIZER); }
@Test public void testCustomProjectionDataMapSerializer() { Map<String, Object> queryParams = new HashMap<>(); Set<PathSpec> specSet = new HashSet<>(); specSet.add(new PathSpec("random")); queryParams.put(RestConstants.FIELDS_PARAM, specSet); queryParams.put(RestConstants.PAGING_FIELDS_PARAM, specSet); queryParams.put(RestConstants.METADATA_FIELDS_PARAM, specSet); DataMap dataMap = QueryParamsUtil.convertToDataMap(queryParams, Collections.emptyMap(), AllProtocolVersions.LATEST_PROTOCOL_VERSION, (paramName, pathSpecs) -> { DataMap dataMap1 = new DataMap(); dataMap1.put("random", 2); return dataMap1; }); DataMap expectedMap = new DataMap(); expectedMap.put("random", 2); Assert.assertEquals(dataMap.getDataMap(RestConstants.FIELDS_PARAM), expectedMap); Assert.assertEquals(dataMap.getDataMap(RestConstants.PAGING_FIELDS_PARAM), expectedMap); Assert.assertEquals(dataMap.getDataMap(RestConstants.METADATA_FIELDS_PARAM), expectedMap); }
private void migrateV1toV2() throws BlockStoreException, IOException { long currentLength = randomAccessFile.length(); long currentBlocksLength = currentLength - FILE_PROLOGUE_BYTES; if (currentBlocksLength % RECORD_SIZE_V1 != 0) throw new BlockStoreException( "File size on disk indicates this is not a V1 block store: " + currentLength); int currentCapacity = (int) (currentBlocksLength / RECORD_SIZE_V1); randomAccessFile.setLength(fileLength); // Map it into memory again because of the length change. buffer.force(); buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, fileLength); // migrate magic header ((Buffer) buffer).rewind(); buffer.put(HEADER_MAGIC_V2); // migrate headers final byte[] zeroPadding = new byte[20]; // 32 (V2 work) - 12 (V1 work) for (int i = currentCapacity - 1; i >= 0; i--) { byte[] record = new byte[RECORD_SIZE_V1]; buffer.position(FILE_PROLOGUE_BYTES + i * RECORD_SIZE_V1); buffer.get(record); buffer.position(FILE_PROLOGUE_BYTES + i * RECORD_SIZE_V2); buffer.put(record, 0, 32); // hash buffer.put(zeroPadding); buffer.put(record, 32, RECORD_SIZE_V1 - 32); // work, height, block header } // migrate cursor int cursorRecord = (getRingCursor() - FILE_PROLOGUE_BYTES) / RECORD_SIZE_V1; setRingCursor(FILE_PROLOGUE_BYTES + cursorRecord * RECORD_SIZE_V2); }
@Test public void migrateV1toV2() throws Exception { // create V1 format RandomAccessFile raf = new RandomAccessFile(blockStoreFile, "rw"); FileChannel channel = raf.getChannel(); ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, SPVBlockStore.FILE_PROLOGUE_BYTES + SPVBlockStore.RECORD_SIZE_V1 * 3); buffer.put(SPVBlockStore.HEADER_MAGIC_V1); // header magic Block genesisBlock = TESTNET.getGenesisBlock(); StoredBlock storedGenesisBlock = new StoredBlock(genesisBlock.cloneAsHeader(), genesisBlock.getWork(), 0); Sha256Hash genesisHash = storedGenesisBlock.getHeader().getHash(); ((Buffer) buffer).position(SPVBlockStore.FILE_PROLOGUE_BYTES); buffer.put(genesisHash.getBytes()); storedGenesisBlock.serializeCompact(buffer); buffer.putInt(4, buffer.position()); // ring cursor ((Buffer) buffer).position(8); buffer.put(genesisHash.getBytes()); // chain head raf.close(); // migrate to V2 format SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile); // check block is the same assertEquals(genesisHash, store.getChainHead().getHeader().getHash()); // check ring cursor assertEquals(SPVBlockStore.FILE_PROLOGUE_BYTES + SPVBlockStore.RECORD_SIZE_V2 * 1, store.getRingCursor()); store.close(); }
@Override public Map<String, String> run(final Session<?> session) throws BackgroundException { final Metadata feature = session.getFeature(Metadata.class); if(log.isDebugEnabled()) { log.debug(String.format("Run with feature %s", feature)); } // Map for metadata entry key > File & Metadata Values final Map<String, Map<Path, String>> graphMetadata = new HashMap<>(); for(Path next : files) { // Read online metadata next.attributes().setMetadata(feature.getMetadata(next)); // take every entry of current metadata and store it in metaGraph for(Map.Entry<String, String> entry : next.attributes().getMetadata().entrySet()) { if(graphMetadata.containsKey(entry.getKey())) { // if existing, get map, put value graphMetadata.get(entry.getKey()).put(next, entry.getValue()); } else { // if not existent create hashmap and put it back Map<Path, String> map = new HashMap<>(); graphMetadata.put(entry.getKey(), map); map.put(next, entry.getValue()); } } } // Store result metadata in hashmap Map<String, String> metadata = new HashMap<>(); for(Map.Entry<String, Map<Path, String>> entry : graphMetadata.entrySet()) { if(entry.getValue().size() != files.size()) { metadata.put(entry.getKey(), null); } else { // single use of streams, reason: distinct is easier in Streams than it would be writing it manually Stream<String> values = entry.getValue().values().stream().distinct(); // Use reducing collector, that returns null on non-unique values final String value = values.collect(Collectors.reducing((a, v) -> null)).orElse(null); // store it metadata.put(entry.getKey(), value); } } return metadata; }
@Test public void testRun() throws Exception { final List<Path> files = new ArrayList<>(); files.add(new Path("a", EnumSet.of(Path.Type.file))); files.add(new Path("b", EnumSet.of(Path.Type.file))); files.add(new Path("c", EnumSet.of(Path.Type.file))); ReadMetadataWorker worker = new ReadMetadataWorker(files) { @Override public void cleanup(final Map<String, String> result) { fail(); } }; final Map<String, String> map = worker.run(new NullSession(new Host(new TestProtocol())) { @Override @SuppressWarnings("unchecked") public <T> T _getFeature(final Class<T> type) { if(type == Metadata.class) { return (T) new Metadata() { @Override public Map<String, String> getDefault(final Local local) { return Collections.emptyMap(); } @Override public Map<String, String> getMetadata(final Path file) { final HashMap<String, String> map = new HashMap<>(); switch(file.getName()) { case "a": map.put("key1", "v1"); map.put("key2", "v"); map.put("key3", "v"); return map; case "b": map.put("key2", "v"); map.put("key3", "v"); return map; case "c": map.put("key2", "v2"); map.put("key3", "v"); return map; default: fail(); break; } return map; } @Override public void setMetadata(final Path file, final TransferStatus status) { throw new UnsupportedOperationException(); } }; } return super._getFeature(type); } }); assertTrue(map.containsKey("key1")); assertTrue(map.containsKey("key2")); assertNull(map.get("key1")); assertNull(map.get("key2")); assertNotNull(map.get("key3")); }
public static FusedPipeline fuse(Pipeline p) { return new GreedyPipelineFuser(p).fusedPipeline; }
@Test public void sideInputRootsNewStage() { Components components = Components.newBuilder() .putCoders("coder", Coder.newBuilder().build()) .putCoders("windowCoder", Coder.newBuilder().build()) .putWindowingStrategies( "ws", WindowingStrategy.newBuilder().setWindowCoderId("windowCoder").build()) .putTransforms( "mainImpulse", PTransform.newBuilder() .setUniqueName("MainImpulse") .putOutputs("output", "mainImpulse.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.IMPULSE_TRANSFORM_URN)) .build()) .putPcollections("mainImpulse.out", pc("mainImpulse.out")) .putTransforms( "read", PTransform.newBuilder() .setUniqueName("Read") .putInputs("input", "mainImpulse.out") .putOutputs("output", "read.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.PAR_DO_TRANSFORM_URN) .setPayload( ParDoPayload.newBuilder() .setDoFn(FunctionSpec.newBuilder()) .build() .toByteString())) .setEnvironmentId("py") .build()) .putPcollections("read.out", pc("read.out")) .putTransforms( "sideImpulse", PTransform.newBuilder() .setUniqueName("SideImpulse") .putOutputs("output", "sideImpulse.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.IMPULSE_TRANSFORM_URN)) .build()) .putPcollections("sideImpulse.out", pc("sideImpulse.out")) .putTransforms( "sideRead", PTransform.newBuilder() .setUniqueName("SideRead") .putInputs("input", "sideImpulse.out") .putOutputs("output", "sideRead.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.PAR_DO_TRANSFORM_URN) .setPayload( ParDoPayload.newBuilder() .setDoFn(FunctionSpec.newBuilder()) .build() .toByteString())) .setEnvironmentId("py") .build()) .putPcollections("sideRead.out", pc("sideRead.out")) .putTransforms( "leftParDo", PTransform.newBuilder() .setUniqueName("LeftParDo") .putInputs("main", "read.out") .putOutputs("output", "leftParDo.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.PAR_DO_TRANSFORM_URN) .setPayload( ParDoPayload.newBuilder() .setDoFn(FunctionSpec.newBuilder()) .build() .toByteString()) .build()) .setEnvironmentId("py") .build()) .putPcollections("leftParDo.out", pc("leftParDo.out")) .putTransforms( "rightParDo", PTransform.newBuilder() .setUniqueName("RightParDo") .putInputs("main", "read.out") .putOutputs("output", "rightParDo.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.PAR_DO_TRANSFORM_URN) .setPayload( ParDoPayload.newBuilder() .setDoFn(FunctionSpec.newBuilder()) .build() .toByteString()) .build()) .setEnvironmentId("py") .build()) .putPcollections("rightParDo.out", pc("rightParDo.out")) .putTransforms( "sideParDo", PTransform.newBuilder() .setUniqueName("SideParDo") .putInputs("main", "read.out") .putInputs("side", "sideRead.out") .putOutputs("output", "sideParDo.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.PAR_DO_TRANSFORM_URN) .setPayload( ParDoPayload.newBuilder() .setDoFn(FunctionSpec.newBuilder()) .putSideInputs("side", SideInput.getDefaultInstance()) .build() .toByteString()) .build()) .setEnvironmentId("py") .build()) .putPcollections("sideParDo.out", pc("sideParDo.out")) .putEnvironments("py", Environments.createDockerEnvironment("py")) .build(); FusedPipeline fused = GreedyPipelineFuser.fuse(Pipeline.newBuilder().setComponents(components).build()); assertThat( fused.getRunnerExecutedTransforms(), containsInAnyOrder( PipelineNode.pTransform("mainImpulse", components.getTransformsOrThrow("mainImpulse")), PipelineNode.pTransform( "sideImpulse", components.getTransformsOrThrow("sideImpulse")))); assertThat( fused.getFusedStages(), containsInAnyOrder( ExecutableStageMatcher.withInput("mainImpulse.out") .withOutputs("read.out") .withTransforms("read"), ExecutableStageMatcher.withInput("read.out") .withNoOutputs() .withTransforms("leftParDo", "rightParDo"), ExecutableStageMatcher.withInput("read.out") .withSideInputs( RunnerApi.ExecutableStagePayload.SideInputId.newBuilder() .setTransformId("sideParDo") .setLocalName("side") .build()) .withNoOutputs() .withTransforms("sideParDo"), ExecutableStageMatcher.withInput("sideImpulse.out") .withOutputs("sideRead.out") .withTransforms("sideRead"))); }
public boolean check() { // the dependency com.sonarsource:sonarsource-branding is shaded to webapp // during official build (see sonar-web pom) File brandingFile = new File(serverFileSystem.getHomeDir(), BRANDING_FILE_PATH); // no need to check that the file exists. java.io.File#length() returns zero in this case. return brandingFile.length() > 0L; }
@Test public void official_distribution() throws Exception { File rootDir = temp.newFolder(); FileUtils.write(new File(rootDir, OfficialDistribution.BRANDING_FILE_PATH), "1.2"); when(serverFileSystem.getHomeDir()).thenReturn(rootDir); assertThat(underTest.check()).isTrue(); }
public Pair<Long, Jwts> refresh(String refreshToken) { JwtClaims claims = refreshTokenProvider.getJwtClaimsFromToken(refreshToken); Long userId = JwtClaimsParserUtil.getClaimsValue(claims, RefreshTokenClaimKeys.USER_ID.getValue(), Long::parseLong); String role = JwtClaimsParserUtil.getClaimsValue(claims, RefreshTokenClaimKeys.ROLE.getValue(), String.class); log.debug("refresh token userId : {}, role : {}", userId, role); RefreshToken newRefreshToken; try { newRefreshToken = refreshTokenService.refresh(userId, refreshToken, refreshTokenProvider.generateToken(RefreshTokenClaim.of(userId, role))); log.debug("new refresh token : {}", newRefreshToken.getToken()); } catch (IllegalArgumentException e) { throw new JwtErrorException(JwtErrorCode.EXPIRED_TOKEN); } catch (IllegalStateException e) { throw new JwtErrorException(JwtErrorCode.TAKEN_AWAY_TOKEN); } String newAccessToken = accessTokenProvider.generateToken(AccessTokenClaim.of(userId, role)); log.debug("new access token : {}", newAccessToken); return Pair.of(userId, Jwts.of(newAccessToken, newRefreshToken.getToken())); }
@Test @DisplayName("์‚ฌ์šฉ์ž ์•„์ด๋””์— ํ•ด๋‹นํ•˜๋Š” ๋‹ค๋ฅธ ๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ์ด ์ €์žฅ๋˜์–ด ์žˆ์„ ์‹œ, ํƒˆ์ทจ๋˜์—ˆ๋‹ค๊ณ  ํŒ๋‹จํ•˜๊ณ  ํ† ํฐ์„ ์ œ๊ฑฐํ•œ ํ›„ JwtErrorException์„ ๋ฐœ์ƒ์‹œํ‚จ๋‹ค.") public void RefreshTokenRefreshFail() { // given RefreshToken refreshToken = RefreshToken.builder() .userId(1L) .token("refreshToken") .ttl(1000L) .build(); refreshTokenRepository.save(refreshToken); given(refreshTokenProvider.getJwtClaimsFromToken("anotherRefreshToken")).willReturn(RefreshTokenClaim.of(refreshToken.getUserId(), Role.USER.toString())); given(refreshTokenProvider.generateToken(any())).willReturn("newRefreshToken"); // when JwtErrorException jwtErrorException = assertThrows(JwtErrorException.class, () -> jwtAuthHelper.refresh("anotherRefreshToken")); // then assertEquals("ํƒˆ์ทจ ์‹œ๋‚˜๋ฆฌ์˜ค ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.", JwtErrorCode.TAKEN_AWAY_TOKEN, jwtErrorException.getErrorCode()); assertFalse("๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ์ด ์‚ญ์ œ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.", refreshTokenRepository.existsById(refreshToken.getUserId())); }
@Override public void properties(SAPropertiesFetcher fetcher) { if (mCustomProperties != null) { JSONUtils.mergeJSONObject(mCustomProperties, fetcher.getProperties()); mCustomProperties = null; } }
@Test public void properties() { InternalCustomPropertyPlugin customPropertyPlugin = new InternalCustomPropertyPlugin(); JSONObject libProperty = new JSONObject(); try { libProperty.put("custom", "customAndroid"); } catch (JSONException e) { e.printStackTrace(); } customPropertyPlugin.saveCustom(libProperty); JSONObject property = new JSONObject(); SAPropertiesFetcher propertiesFetcher = new SAPropertiesFetcher(); propertiesFetcher.setProperties(property); customPropertyPlugin.properties(propertiesFetcher); Assert.assertEquals("customAndroid", property.optString("custom")); }
@Override public void open(Map<String, Object> config, SourceContext sourceContext) throws Exception { this.config = config; this.sourceContext = sourceContext; this.intermediateTopicName = SourceConfigUtils.computeBatchSourceIntermediateTopicName(sourceContext.getTenant(), sourceContext.getNamespace(), sourceContext.getSourceName()).toString(); this.discoveryThread = Executors.newSingleThreadExecutor( new DefaultThreadFactory( String.format("%s-batch-source-discovery", FunctionCommon.getFullyQualifiedName( sourceContext.getTenant(), sourceContext.getNamespace(), sourceContext.getSourceName())))); this.getBatchSourceConfigs(config); this.initializeBatchSource(); this.start(); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Batch Configs cannot be found") public void testPushWithoutRightConfig() throws Exception { pushConfig.clear(); batchSourceExecutor.open(pushConfig, context); }
@Override public WebSocketExtensionData newRequestData() { return new WebSocketExtensionData( useWebkitExtensionName ? X_WEBKIT_DEFLATE_FRAME_EXTENSION : DEFLATE_FRAME_EXTENSION, Collections.<String, String>emptyMap()); }
@Test public void testWebkitDeflateFrameData() { DeflateFrameClientExtensionHandshaker handshaker = new DeflateFrameClientExtensionHandshaker(true); WebSocketExtensionData data = handshaker.newRequestData(); assertEquals(X_WEBKIT_DEFLATE_FRAME_EXTENSION, data.name()); assertTrue(data.parameters().isEmpty()); }
public static void main(String[] args) { var queue = new SimpleMessageQueue(10000); final var producer = new Producer("PRODUCER_1", queue); final var consumer = new Consumer("CONSUMER_1", queue); new Thread(consumer::consume).start(); new Thread(() -> { producer.send("hand shake"); producer.send("some very important information"); producer.send("bye!"); producer.stop(); }).start(); }
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public int compareTo(EipAttribute o) { if (o == null) { return 1; } return index - o.index; }
@Test public void testCompareTo() { EipAttribute attribute1 = getInstance(); EipAttribute attribute2 = getInstance(); int result = attribute1.compareTo(attribute2); assertEquals(0, result); result = attribute1.compareTo(null); assertNotEquals(0, result); attribute2.setIndex(5); result = attribute1.compareTo(attribute2); assertNotEquals(0, result); }
@Override public double variance() { return variance; }
@Test public void testVariance() { System.out.println("variance"); LogNormalDistribution instance = new LogNormalDistribution(1.0, 1.0); instance.rand(); assertEquals(34.51261, instance.variance(), 1E-5); }
public static Write write() { return new AutoValue_RedisIO_Write.Builder() .setConnectionConfiguration(RedisConnectionConfiguration.create()) .setMethod(Write.Method.APPEND) .build(); }
@Test public void testWriteUsingINCRBY() { String key = "key_incr"; List<String> values = Arrays.asList("0", "1", "2", "-3", "2", "4", "0", "5"); List<KV<String, String>> data = buildConstantKeyList(key, values); PCollection<KV<String, String>> write = p.apply(Create.of(data)); write.apply(RedisIO.write().withEndpoint(REDIS_HOST, port).withMethod(Method.INCRBY)); p.run(); long count = Long.parseLong(client.get(key)); assertEquals(11, count); }
public Matrix tm(Matrix B) { if (m != B.m) { throw new IllegalArgumentException(String.format("Matrix multiplication A' * B: %d x %d vs %d x %d", m, n, B.m, B.n)); } Matrix C = new Matrix(n, B.n); C.mm(TRANSPOSE, this, NO_TRANSPOSE, B); return C; }
@Test public void testTm() { System.out.println("tm"); float[][] A = { {4.0f, 1.2f, 0.8f}, {1.2f, 9.0f, 1.2f}, {0.8f, 1.2f, 16.0f} }; float[] B = {-4.0f, 1.0f, -3.0f}; float[] C = {-1.0505f, 0.2719f, -0.1554f}; Matrix a = Matrix.of(A).inverse(); Matrix b = Matrix.column(B); assertTrue(MathEx.equals((b.tm(a)).toArray()[0], C, 1E-4f)); assertTrue(MathEx.equals((b.transpose().mm(a)).toArray()[0], C, 1E-4f)); assertTrue(MathEx.equals((b.transpose(false).mm(a)).toArray()[0], C, 1E-4f)); }
@Override public void execute(SensorContext context) { analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY); analyse(context, Xoo2.KEY, XooRulesDefinition.XOO2_REPOSITORY); }
@Test public void testForceSeverity() throws IOException { DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo") .setLanguage(Xoo.KEY) .initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n") .build(); SensorContextTester context = SensorContextTester.create(temp.newFolder()); context.fileSystem().add(inputFile); context.setSettings(new MapSettings().setProperty(OneIssuePerLineSensor.FORCE_SEVERITY_PROPERTY, "MINOR")); sensor.execute(context); assertThat(context.allIssues()).hasSize(10); // One issue per line for (Issue issue : context.allIssues()) { assertThat(issue.overriddenSeverity()).isEqualTo(Severity.MINOR); assertThat(issue.ruleDescriptionContextKey()).contains(XooRulesDefinition.AVAILABLE_CONTEXTS[0]); } }
public static <T> T getItemAtPositionOrNull(T[] array, int position) { if (position >= 0 && array.length > position) { return array[position]; } return null; }
@Test public void getItemAtPositionOrNull_whenPositionExist_thenReturnTheItem() { Object obj = new Object(); Object[] src = new Object[1]; src[0] = obj; Object result = ArrayUtils.getItemAtPositionOrNull(src, 0); assertSame(obj, result); }
public static void free(final DirectBuffer buffer) { if (null != buffer) { free(buffer.byteBuffer()); } }
@Test void freeShouldReleaseByteBufferResources() { final ByteBuffer buffer = ByteBuffer.allocateDirect(4); buffer.put((byte)1); buffer.put((byte)2); buffer.put((byte)3); buffer.position(0); BufferUtil.free(buffer); }
public String printFlags() { return flags().stream().sorted().map(Enum::toString).collect(Collectors.joining("|")); }
@Test void printFlags() { ADUserAccountControl allFlagsAccountcontrol = ADUserAccountControl.create( ADUserAccountControl.Flags.NORMAL_ACCOUNT.getFlagValue() | ADUserAccountControl.Flags.ACCOUNTDISABLE.getFlagValue() | ADUserAccountControl.Flags.PASSWORD_EXPIRED.getFlagValue()); assertThat(allFlagsAccountcontrol.printFlags()).isEqualTo("ACCOUNTDISABLE|NORMAL_ACCOUNT|PASSWORD_EXPIRED"); }
@Override public String getUriForDisplay() { return String.format("%s / %s", pipelineName, stageName); }
@Test void shouldUseACombinationOfPipelineAndStageNameAsURI() { Material material = new DependencyMaterial(new CaseInsensitiveString("pipeline-foo"), new CaseInsensitiveString("stage-bar")); assertThat(material.getUriForDisplay()).isEqualTo("pipeline-foo / stage-bar"); }
public boolean submitProcessingErrors(Message message) { return submitProcessingErrorsInternal(message, message.processingErrors()); }
@Test public void submitProcessingErrors_allProcessingErrorsSubmittedToQueueAndMessageNotFilteredOut_ifSubmissionEnabledAndDuplicatesAreKept() throws Exception { // given final Message msg = Mockito.mock(Message.class); when(msg.getMessageId()).thenReturn("msg-x"); when(msg.supportsFailureHandling()).thenReturn(true); when(msg.processingErrors()).thenReturn(List.of( new Message.ProcessingError(() -> "Cause 1", "Message 1", "Details 1"), new Message.ProcessingError(() -> "Cause 2", "Message 2", "Details 2") )); when(failureHandlingConfiguration.submitProcessingFailures()).thenReturn(true); when(failureHandlingConfiguration.keepFailedMessageDuplicate()).thenReturn(true); // when final boolean notFilterOut = underTest.submitProcessingErrors(msg); // then assertThat(notFilterOut).isTrue(); verify(failureSubmissionQueue, times(2)).submitBlocking(failureBatchCaptor.capture()); assertThat(failureBatchCaptor.getAllValues().get(0)).satisfies(fb -> { assertThat(fb.containsProcessingFailures()).isTrue(); assertThat(fb.size()).isEqualTo(1); assertThat(fb.getFailures().get(0)).satisfies(processingFailure -> { assertThat(processingFailure.failureType()).isEqualTo(FailureType.PROCESSING); assertThat(processingFailure.failureCause().label()).isEqualTo("Cause 1"); assertThat(processingFailure.message()).isEqualTo("Failed to process message with id 'msg-x': Message 1"); assertThat(processingFailure.failureDetails()).isEqualTo("Details 1"); assertThat(processingFailure.failureTimestamp()).isNotNull(); assertThat(processingFailure.failedMessage()).isEqualTo(msg); assertThat(processingFailure.targetIndex()).isNull(); assertThat(processingFailure.requiresAcknowledgement()).isFalse(); }); }); assertThat(failureBatchCaptor.getAllValues().get(1)).satisfies(fb -> { assertThat(fb.containsProcessingFailures()).isTrue(); assertThat(fb.size()).isEqualTo(1); assertThat(fb.getFailures().get(0)).satisfies(processingFailure -> { assertThat(processingFailure.failureType()).isEqualTo(FailureType.PROCESSING); assertThat(processingFailure.failureCause().label()).isEqualTo("Cause 2"); assertThat(processingFailure.message()).isEqualTo("Failed to process message with id 'msg-x': Message 2"); assertThat(processingFailure.failureDetails()).isEqualTo("Details 2"); assertThat(processingFailure.failureTimestamp()).isNotNull(); assertThat(processingFailure.failedMessage()).isEqualTo(msg); assertThat(processingFailure.targetIndex()).isNull(); assertThat(processingFailure.requiresAcknowledgement()).isFalse(); }); }); }
public synchronized void flush() { try { StringBuffer buffer = this.buffer.getBuffer(); logFileOutputStream.write( buffer.toString().getBytes() ); logFileOutputStream.flush(); } catch ( Exception e ) { exception = new KettleException( "There was an error logging to file '" + logFile + "'", e ); } }
@Test public void test() throws Exception { LogChannelFileWriter writer = new LogChannelFileWriter( id, fileObject, false ); LoggingRegistry.getInstance().getLogChannelFileWriterBuffer( id ).addEvent( new KettleLoggingEvent( logMessage, System.currentTimeMillis(), LogLevel.BASIC ) ); writer.flush(); verify( outputStream ).write( captor.capture() ); String arguments = new String( captor.getValue() ); assertTrue( arguments.contains( logMessage ) ); }
@Override public boolean createTable(String tableName, JDBCSchema schema) { // Check table ID checkValidTableName(tableName); // Check if table already exists if (tableIds.containsKey(tableName)) { throw new IllegalStateException( "Table " + tableName + " already exists for database " + databaseName + "."); } LOG.info("Creating table using tableName '{}'.", tableName); StringBuilder sql = new StringBuilder(); try (Connection con = driver.getConnection(getUri(), username, password)) { Statement stmt = con.createStatement(); sql.append("CREATE TABLE ") .append(tableName) .append(" (") .append(schema.toSqlStatement()) .append(")"); stmt.executeUpdate(sql.toString()); stmt.close(); } catch (Exception e) { throw new JDBCResourceManagerException( "Error creating table with SQL statement: " + sql + " (for connection with URL " + getUri() + ")", e); } tableIds.put(tableName, schema.getIdColumn()); LOG.info("Successfully created table {}.{}", databaseName, tableName); return true; }
@Test public void testCreateTableShouldReturnTrueIfJDBCDoesNotThrowAnyError() throws SQLException { when(container.getHost()).thenReturn(HOST); when(container.getMappedPort(JDBC_PORT)).thenReturn(MAPPED_PORT); assertTrue( testManager.createTable( TABLE_NAME, new JDBCResourceManager.JDBCSchema(ImmutableMap.of("id", "INTEGER"), "id"))); verify(driver.getConnection(any(), any(), any()).createStatement()).executeUpdate(anyString()); }
private void fail(long frameLength) { if (frameLength > 0) { throw new TooLongFrameException( "Adjusted frame length exceeds " + maxFrameLength + ": " + frameLength + " - discarded"); } else { throw new TooLongFrameException( "Adjusted frame length exceeds " + maxFrameLength + " - discarding"); } }
@Test public void testDiscardTooLongFrame1() { ByteBuf buf = Unpooled.buffer(); buf.writeInt(32); for (int i = 0; i < 32; i++) { buf.writeByte(i); } buf.writeInt(1); buf.writeByte('a'); EmbeddedChannel channel = new EmbeddedChannel(new LengthFieldBasedFrameDecoder(16, 0, 4)); try { channel.writeInbound(buf); fail(); } catch (TooLongFrameException e) { // expected } assertTrue(channel.finish()); ByteBuf b = channel.readInbound(); assertEquals(5, b.readableBytes()); assertEquals(1, b.readInt()); assertEquals('a', b.readByte()); b.release(); assertNull(channel.readInbound()); channel.finish(); }
@Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { var originator = msg.getOriginator(); var msgDataAsObjectNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null; if (!EntityType.DEVICE.equals(originator.getEntityType())) { ctx.tellFailure(msg, new RuntimeException("Unsupported originator type: " + originator.getEntityType() + "!")); return; } var deviceId = new DeviceId(msg.getOriginator().getId()); var deviceCredentials = ctx.getDeviceCredentialsService().findDeviceCredentialsByDeviceId(ctx.getTenantId(), deviceId); if (deviceCredentials == null) { ctx.tellFailure(msg, new RuntimeException("Failed to get Device Credentials for device: " + deviceId + "!")); return; } var credentialsType = deviceCredentials.getCredentialsType(); var credentialsInfo = ctx.getDeviceCredentialsService().toCredentialsInfo(deviceCredentials); var metaData = msg.getMetaData().copy(); if (TbMsgSource.METADATA.equals(fetchTo)) { metaData.putValue(CREDENTIALS_TYPE, credentialsType.name()); if (credentialsType.equals(DeviceCredentialsType.ACCESS_TOKEN) || credentialsType.equals(DeviceCredentialsType.X509_CERTIFICATE)) { metaData.putValue(CREDENTIALS, credentialsInfo.asText()); } else { metaData.putValue(CREDENTIALS, JacksonUtil.toString(credentialsInfo)); } } else if (TbMsgSource.DATA.equals(fetchTo)) { msgDataAsObjectNode.put(CREDENTIALS_TYPE, credentialsType.name()); msgDataAsObjectNode.set(CREDENTIALS, credentialsInfo); } TbMsg transformedMsg = transformMessage(msg, msgDataAsObjectNode, metaData); ctx.tellSuccess(transformedMsg); }
@Test void givenUnsupportedOriginatorType_whenOnMsg_thenShouldTellFailure() throws Exception { // GIVEN var randomCustomerId = new CustomerId(UUID.randomUUID()); // WHEN node.onMsg(ctxMock, getTbMsg(randomCustomerId)); // THEN var newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class); var exceptionCaptor = ArgumentCaptor.forClass(Exception.class); verify(ctxMock, never()).tellSuccess(any()); verify(ctxMock, times(1)).tellFailure(newMsgCaptor.capture(), exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).isInstanceOf(RuntimeException.class); }
@Override protected Result check() throws Exception { long expiration = clock.getTime() - result.getTime() - healthyTtl; if (expiration > 0) { return Result.builder() .unhealthy() .usingClock(clock) .withMessage("Result was %s but it expired %d milliseconds ago", result.isHealthy() ? "healthy" : "unhealthy", expiration) .build(); } return result; }
@Test public void unhealthyAsyncHealthCheckTriggersSuccessfulInstantiationWithUnhealthyState() throws Exception { HealthCheck asyncHealthCheck = new UnhealthyAsyncHealthCheck(); AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); assertThat(asyncDecorator.check().isHealthy()).isFalse(); }
public static String idCardNum(String idCardNum, int front, int end) { //่บซไปฝ่ฏไธ่ƒฝไธบ็ฉบ if (StrUtil.isBlank(idCardNum)) { return StrUtil.EMPTY; } //้œ€่ฆๆˆชๅ–็š„้•ฟๅบฆไธ่ƒฝๅคงไบŽ่บซไปฝ่ฏๅท้•ฟๅบฆ if ((front + end) > idCardNum.length()) { return StrUtil.EMPTY; } //้œ€่ฆๆˆชๅ–็š„ไธ่ƒฝๅฐไบŽ0 if (front < 0 || end < 0) { return StrUtil.EMPTY; } return StrUtil.hide(idCardNum, front, idCardNum.length() - end); }
@Test public void idCardNumTest() { assertEquals("5***************1X", DesensitizedUtil.idCardNum("51343620000320711X", 1, 2)); }
protected static List<LastOpenedDTO> filterForExistingIdAndCapAtMaximum(final LastOpenedForUserDTO loi, final GRN grn, final long max) { return loi.items().stream().filter(i -> !i.grn().equals(grn)).limit(max - 1).toList(); }
@Test public void testRemoveItemFromTheMiddle() { var list = List.of( new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "1"), DateTime.now(DateTimeZone.UTC)), new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "2"), DateTime.now(DateTimeZone.UTC)), new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "3"), DateTime.now(DateTimeZone.UTC)), new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "4"), DateTime.now(DateTimeZone.UTC)), new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "5"), DateTime.now(DateTimeZone.UTC)), new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "6"), DateTime.now(DateTimeZone.UTC)), new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "7"), DateTime.now(DateTimeZone.UTC)), new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "8"), DateTime.now(DateTimeZone.UTC)), new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "9"), DateTime.now(DateTimeZone.UTC)) ); LastOpenedForUserDTO dto = new LastOpenedForUserDTO("userId", list); var result = StartPageService.filterForExistingIdAndCapAtMaximum(dto, grnRegistry.newGRN(GRNTypes.DASHBOARD, "5"), MAX); assertThat(result.size()).isEqualTo(8); }
@Transactional public void create(String uuid, long attendeeId, ScheduleCreateRequest request) { Meeting meeting = meetingRepository.findByUuid(uuid) .orElseThrow(() -> new MomoException(MeetingErrorCode.INVALID_UUID)); validateMeetingUnLocked(meeting); Attendee attendee = attendeeRepository.findByIdAndMeeting(attendeeId, meeting) .orElseThrow(() -> new MomoException(AttendeeErrorCode.INVALID_ATTENDEE)); scheduleRepository.deleteAllByAttendee(attendee); List<Schedule> schedules = createSchedules(request, meeting, attendee); scheduleRepository.saveAll(schedules); }
@DisplayName("์Šค์ผ€์ค„ ์ƒ์„ฑ ์‹œ ์‚ฌ์šฉ์ž์˜ ๊ธฐ์กด ์Šค์ผ€์ค„๋“ค์„ ๋ชจ๋‘ ์‚ญ์ œํ•˜๊ณ  ์ƒˆ๋กœ์šด ์Šค์ผ€์ค„์„ ์ €์žฅํ•œ๋‹ค.") @Test void createSchedulesReplacesOldSchedules() { ScheduleCreateRequest request = new ScheduleCreateRequest(dateTimes); scheduleRepository.saveAll(List.of( new Schedule(attendee, today, Timeslot.TIME_0130), new Schedule(attendee, tomorrow, Timeslot.TIME_0130) )); scheduleService.create(meeting.getUuid(), attendee.getId(), request); long scheduleCount = scheduleRepository.count(); assertThat(scheduleCount).isEqualTo(4); }
static long sizeForField(@Nonnull String key, @Nonnull Object value) { return key.length() + sizeForValue(value); }
@Test public void fieldTest() { assertThat(Message.sizeForField("", true)).isEqualTo(4); assertThat(Message.sizeForField("", (byte) 1)).isEqualTo(1); assertThat(Message.sizeForField("", (char) 1)).isEqualTo(2); assertThat(Message.sizeForField("", (short) 1)).isEqualTo(2); assertThat(Message.sizeForField("", 1)).isEqualTo(4); assertThat(Message.sizeForField("", 1L)).isEqualTo(8); assertThat(Message.sizeForField("", 1.0f)).isEqualTo(4); assertThat(Message.sizeForField("", 1.0d)).isEqualTo(8); }
public long readIntLenenc() { int firstByte = readInt1(); if (firstByte < 0xfb) { return firstByte; } if (0xfb == firstByte) { return 0L; } if (0xfc == firstByte) { return readInt2(); } if (0xfd == firstByte) { return readInt3(); } return byteBuf.readLongLE(); }
@Test void assertReadIntLenencWithTwoBytes() { when(byteBuf.readUnsignedByte()).thenReturn((short) 0xfc); when(byteBuf.readUnsignedShortLE()).thenReturn(100); assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readIntLenenc(), is(100L)); }
@SuppressWarnings({"checkstyle:CyclomaticComplexity", "checkstyle:MethodLength"}) public static Expression convert(Predicate predicate) { Operation op = FILTERS.get(predicate.name()); if (op != null) { switch (op) { case TRUE: return Expressions.alwaysTrue(); case FALSE: return Expressions.alwaysFalse(); case IS_NULL: return isRef(child(predicate)) ? isNull(SparkUtil.toColumnName(child(predicate))) : null; case NOT_NULL: return isRef(child(predicate)) ? notNull(SparkUtil.toColumnName(child(predicate))) : null; case LT: if (isRef(leftChild(predicate)) && isLiteral(rightChild(predicate))) { String columnName = SparkUtil.toColumnName(leftChild(predicate)); return lessThan(columnName, convertLiteral(rightChild(predicate))); } else if (isRef(rightChild(predicate)) && isLiteral(leftChild(predicate))) { String columnName = SparkUtil.toColumnName(rightChild(predicate)); return greaterThan(columnName, convertLiteral(leftChild(predicate))); } else { return null; } case LT_EQ: if (isRef(leftChild(predicate)) && isLiteral(rightChild(predicate))) { String columnName = SparkUtil.toColumnName(leftChild(predicate)); return lessThanOrEqual(columnName, convertLiteral(rightChild(predicate))); } else if (isRef(rightChild(predicate)) && isLiteral(leftChild(predicate))) { String columnName = SparkUtil.toColumnName(rightChild(predicate)); return greaterThanOrEqual(columnName, convertLiteral(leftChild(predicate))); } else { return null; } case GT: if (isRef(leftChild(predicate)) && isLiteral(rightChild(predicate))) { String columnName = SparkUtil.toColumnName(leftChild(predicate)); return greaterThan(columnName, convertLiteral(rightChild(predicate))); } else if (isRef(rightChild(predicate)) && isLiteral(leftChild(predicate))) { String columnName = SparkUtil.toColumnName(rightChild(predicate)); return lessThan(columnName, convertLiteral(leftChild(predicate))); } else { return null; } case GT_EQ: if (isRef(leftChild(predicate)) && isLiteral(rightChild(predicate))) { String columnName = SparkUtil.toColumnName(leftChild(predicate)); return greaterThanOrEqual(columnName, convertLiteral(rightChild(predicate))); } else if (isRef(rightChild(predicate)) && isLiteral(leftChild(predicate))) { String columnName = SparkUtil.toColumnName(rightChild(predicate)); return lessThanOrEqual(columnName, convertLiteral(leftChild(predicate))); } else { return null; } case EQ: // used for both eq and null-safe-eq Object value; String columnName; if (isRef(leftChild(predicate)) && isLiteral(rightChild(predicate))) { columnName = SparkUtil.toColumnName(leftChild(predicate)); value = convertLiteral(rightChild(predicate)); } else if (isRef(rightChild(predicate)) && isLiteral(leftChild(predicate))) { columnName = SparkUtil.toColumnName(rightChild(predicate)); value = convertLiteral(leftChild(predicate)); } else { return null; } if (predicate.name().equals(EQ)) { // comparison with null in normal equality is always null. this is probably a mistake. Preconditions.checkNotNull( value, "Expression is always false (eq is not null-safe): %s", predicate); return handleEqual(columnName, value); } else { // "<=>" if (value == null) { return isNull(columnName); } else { return handleEqual(columnName, value); } } case IN: if (isSupportedInPredicate(predicate)) { return in( SparkUtil.toColumnName(childAtIndex(predicate, 0)), Arrays.stream(predicate.children()) .skip(1) .map(val -> convertLiteral(((Literal<?>) val))) .filter(Objects::nonNull) .collect(Collectors.toList())); } else { return null; } case NOT: Not notPredicate = (Not) predicate; Predicate childPredicate = notPredicate.child(); if (childPredicate.name().equals(IN) && isSupportedInPredicate(childPredicate)) { // infer an extra notNull predicate for Spark NOT IN filters // as Iceberg expressions don't follow the 3-value SQL boolean logic // col NOT IN (1, 2) in Spark is equal to notNull(col) && notIn(col, 1, 2) in Iceberg Expression notIn = notIn( SparkUtil.toColumnName(childAtIndex(childPredicate, 0)), Arrays.stream(childPredicate.children()) .skip(1) .map(val -> convertLiteral(((Literal<?>) val))) .filter(Objects::nonNull) .collect(Collectors.toList())); return and(notNull(SparkUtil.toColumnName(childAtIndex(childPredicate, 0))), notIn); } else if (hasNoInFilter(childPredicate)) { Expression child = convert(childPredicate); if (child != null) { return not(child); } } return null; case AND: { And andPredicate = (And) predicate; Expression left = convert(andPredicate.left()); Expression right = convert(andPredicate.right()); if (left != null && right != null) { return and(left, right); } return null; } case OR: { Or orPredicate = (Or) predicate; Expression left = convert(orPredicate.left()); Expression right = convert(orPredicate.right()); if (left != null && right != null) { return or(left, right); } return null; } case STARTS_WITH: String colName = SparkUtil.toColumnName(leftChild(predicate)); return startsWith(colName, convertLiteral(rightChild(predicate)).toString()); } } return null; }
@Test public void testDateFilterConversion() { LocalDate localDate = LocalDate.parse("2018-10-18"); long epochDay = localDate.toEpochDay(); NamedReference namedReference = FieldReference.apply("x"); LiteralValue ts = new LiteralValue(epochDay, DataTypes.DateType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, ts}; Predicate predicate = new Predicate(">", attrAndValue); Expression dateExpression = SparkV2Filters.convert(predicate); Expression rawExpression = Expressions.greaterThan("x", epochDay); Assert.assertEquals( "Generated date expression should be correct", rawExpression.toString(), dateExpression.toString()); }
@Override public Set<Tuple> zRangeWithScores(byte[] key, long start, long end) { if (executorService.getServiceManager().isResp3()) { return read(key, ByteArrayCodec.INSTANCE, ZRANGE_ENTRY_V2, key, start, end, "WITHSCORES"); } return read(key, ByteArrayCodec.INSTANCE, ZRANGE_ENTRY, key, start, end, "WITHSCORES"); }
@Test public void testZRangeWithScores() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boundZSetOps("test").add("2", 20); redisTemplate.boundZSetOps("test").add("3", 30); Set<ZSetOperations.TypedTuple<String>> objs = redisTemplate.boundZSetOps("test").rangeWithScores(0, 100); assertThat(objs).hasSize(3); assertThat(objs).containsExactlyInAnyOrder(ZSetOperations.TypedTuple.of("1", 10D), ZSetOperations.TypedTuple.of("2", 20D), ZSetOperations.TypedTuple.of("3", 30D)); }
@Override public ValidationError validate(Exchange exchange, ValidationContext validationContent) { OpenAPI openAPI = exchange.getProperty(Exchange.REST_OPENAPI, OpenAPI.class); if (openAPI == null) { return null; } String method = exchange.getMessage().getHeader(Exchange.HTTP_METHOD, String.class); String path = exchange.getMessage().getHeader(Exchange.HTTP_PATH, String.class); String accept = exchange.getMessage().getHeader("Accept", String.class); String contentType = ExchangeHelper.getContentType(exchange); String body = MessageHelper.extractBodyAsString(exchange.getIn()); SimpleRequest.Builder builder = new SimpleRequest.Builder(method, path, false); if (contentType != null) { builder.withContentType(contentType); } if (accept != null) { builder.withAccept(accept); } if (body != null) { builder.withBody(body); } OpenApiInteractionValidator validator = OpenApiInteractionValidator.createFor(openAPI).build(); ValidationReport report = validator.validateRequest(builder.build()); if (report.hasErrors()) { String msg; if (accept != null && accept.contains("application/json")) { msg = JsonValidationReportFormat.getInstance().apply(report); } else { msg = SimpleValidationReportFormat.getInstance().apply(report); } return new ValidationError(400, msg); } return null; }
@Test public void testValidator() throws Exception { String data = IOHelper.loadText(OpenApiRestClientRequestValidatorTest.class.getResourceAsStream("/petstore-v3.json")); OpenAPIV3Parser parser = new OpenAPIV3Parser(); SwaggerParseResult out = parser.readContents(data); OpenAPI openAPI = out.getOpenAPI(); exchange.setProperty(Exchange.REST_OPENAPI, openAPI); exchange.setProperty(Exchange.CONTENT_TYPE, "application/json"); exchange.getMessage().setHeader(Exchange.HTTP_METHOD, "PUT"); exchange.getMessage().setHeader(Exchange.HTTP_PATH, "pet"); exchange.getMessage().setHeader("Accept", "application/json"); exchange.getMessage().setBody(""); OpenApiRestClientRequestValidator validator = new OpenApiRestClientRequestValidator(); RestClientRequestValidator.ValidationError error = validator.validate(exchange, new RestClientRequestValidator.ValidationContext( "application/json", "application/json", true, null, null, null, null)); Assertions.assertNotNull(error); Assertions.assertTrue(error.body().contains("A request body is required but none found")); exchange.getMessage().setBody("{ some body here }"); error = validator.validate(exchange, new RestClientRequestValidator.ValidationContext( "application/json", "application/json", true, null, null, null, null)); Assertions.assertNull(error); }
@Override public void process(Exchange exchange) throws Exception { String operation = getOperation(exchange); switch (operation) { case GlanceConstants.RESERVE: doReserve(exchange); break; case OpenstackConstants.CREATE: doCreate(exchange); break; case OpenstackConstants.UPDATE: doUpdate(exchange); break; case GlanceConstants.UPLOAD: doUpload(exchange); break; case OpenstackConstants.GET: doGet(exchange); break; case OpenstackConstants.GET_ALL: doGetAll(exchange); break; case OpenstackConstants.DELETE: doDelete(exchange); break; default: throw new IllegalArgumentException("Unsupported operation " + operation); } }
@Test public void reserveWithHeadersTest() throws Exception { when(endpoint.getOperation()).thenReturn(GlanceConstants.RESERVE); msg.setHeader(OpenstackConstants.NAME, dummyImage.getName()); msg.setHeader(GlanceConstants.CONTAINER_FORMAT, dummyImage.getContainerFormat()); msg.setHeader(GlanceConstants.DISK_FORMAT, dummyImage.getDiskFormat()); msg.setHeader(GlanceConstants.CHECKSUM, dummyImage.getChecksum()); msg.setHeader(GlanceConstants.MIN_DISK, dummyImage.getMinDisk()); msg.setHeader(GlanceConstants.MIN_RAM, dummyImage.getMinRam()); msg.setHeader(GlanceConstants.OWNER, dummyImage.getOwner()); producer.process(exchange); verify(imageService).reserve(captor.capture()); assertEqualsImages(dummyImage, captor.getValue()); final Image result = msg.getBody(Image.class); assertNotNull(result.getId()); assertEqualsImages(dummyImage, result); }
@NonNull public String processShownotes() { String shownotes = rawShownotes; if (TextUtils.isEmpty(shownotes)) { Log.d(TAG, "shownotesProvider contained no shownotes. Returning 'no shownotes' message"); shownotes = "<html><head></head><body><p id='apNoShownotes'>" + noShownotesLabel + "</p></body></html>"; } // replace ASCII line breaks with HTML ones if shownotes don't contain HTML line breaks already if (!LINE_BREAK_REGEX.matcher(shownotes).find() && !shownotes.contains("<p>")) { shownotes = shownotes.replace("\n", "<br />"); } Document document = Jsoup.parse(shownotes); cleanCss(document); document.head().appendElement("style").attr("type", "text/css").text(webviewStyle); addTimecodes(document); return document.toString(); }
@Test public void testProcessShownotesAddTimecodeParentheses() { final String timeStr = "10:11"; final long time = 3600 * 1000 * 10 + 60 * 1000 * 11; String shownotes = "<p> Some test text with a timecode (" + timeStr + ") here.</p>"; ShownotesCleaner t = new ShownotesCleaner(context, shownotes, Integer.MAX_VALUE); String res = t.processShownotes(); checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); }
void sendNextRpc() { this.lock.lock(); try { this.timer = null; final long offset = this.requestBuilder.getOffset() + this.requestBuilder.getCount(); final long maxCount = this.destBuf == null ? this.raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = this.snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); final RpcRequests.GetFileRequest request = this.requestBuilder.build(); LOG.debug("Send get file request {} to peer {}", request, this.endpoint); this.rpcCall = this.rpcService.getFile(this.endpoint, request, this.copyOptions.getTimeoutMs(), this.done); } finally { this.lock.unlock(); } }
@Test public void testSendNextRpc() { final int maxCount = this.raftOpts.getMaxByteCountPerRpc(); sendNextRpc(maxCount); }
public static byte[] generateContractAddress(byte[] address, BigInteger nonce) { List<RlpType> values = new ArrayList<>(); values.add(RlpString.create(address)); values.add(RlpString.create(nonce)); RlpList rlpList = new RlpList(values); byte[] encoded = RlpEncoder.encode(rlpList); byte[] hashed = Hash.sha3(encoded); return Arrays.copyOfRange(hashed, 12, hashed.length); }
@Test public void testCreateContractAddress() { String address = "0x19e03255f667bdfd50a32722df860b1eeaf4d635"; assertEquals( generateContractAddress(address, BigInteger.valueOf(209)), ("0xe41e694d8fa4337b7bffc7483d3609ae1ea068d5")); assertEquals( generateContractAddress(address, BigInteger.valueOf(257)), ("0x59c21d36fbe415218e834683cb6616f2bc971ca9")); }
public static ExpansionServer create(ExpansionService service, String host, int port) throws IOException { return new ExpansionServer(service, host, port); }
@Test public void testEmptyFilesToStageIsOK() { String[] args = {"--filesToStage="}; ExpansionService service = new ExpansionService(args); assertThat( service .createPipeline(PipelineOptionsFactory.create()) .getOptions() .as(PortablePipelineOptions.class) .getFilesToStage(), equalTo(Arrays.asList(""))); }
public InputFormat<RowData, ?> getInputFormat() { return getInputFormat(false); }
@Test void testGetInputFormat() throws Exception { beforeEach(); // write some data to let the TableSchemaResolver get the right instant TestData.writeData(TestData.DATA_SET_INSERT, conf); HoodieTableSource tableSource = new HoodieTableSource( SerializableSchema.create(TestConfigurations.TABLE_SCHEMA), new StoragePath(tempFile.getPath()), Arrays.asList(conf.getString(FlinkOptions.PARTITION_PATH_FIELD).split(",")), "default-par", conf); InputFormat<RowData, ?> inputFormat = tableSource.getInputFormat(); assertThat(inputFormat, is(instanceOf(FileInputFormat.class))); conf.setString(FlinkOptions.TABLE_TYPE, FlinkOptions.TABLE_TYPE_MERGE_ON_READ); inputFormat = tableSource.getInputFormat(); assertThat(inputFormat, is(instanceOf(MergeOnReadInputFormat.class))); conf.setString(FlinkOptions.QUERY_TYPE.key(), FlinkOptions.QUERY_TYPE_INCREMENTAL); assertDoesNotThrow( (ThrowingSupplier<? extends InputFormat<RowData, ?>>) tableSource::getInputFormat, "Query type: 'incremental' should be supported"); }
static String getErrorKey(Sample sample) { if (sample.getSuccess()) { return ""; } String responseCode = sample.getResponseCode(); String responseMessage = sample.getResponseMessage(); String key = responseCode + (!StringUtils.isEmpty(responseMessage) ? "/" + escapeJson(responseMessage) : ""); if (MetricUtils.isSuccessCode(responseCode) || (StringUtils.isEmpty(responseCode) && StringUtils.isNotBlank(sample.getFailureMessage()))) { key = MetricUtils.ASSERTION_FAILED; if (ASSERTION_RESULTS_FAILURE_MESSAGE) { String msg = sample.getFailureMessage(); if (StringUtils.isNotBlank(msg)) { key = escapeJson(msg); } } } return key; }
@Test public void testGetErrorKey() { SampleMetadata metadata = new SampleMetadata(',', new String[] { CSVSaveService.SUCCESSFUL, CSVSaveService.RESPONSE_CODE, CSVSaveService.RESPONSE_MESSAGE, CSVSaveService.FAILURE_MESSAGE }); Sample sample = new Sample(0, metadata, new String[] { "false", "", "", "FailureMessage" }); assertEquals("FailureMessage", ErrorsSummaryConsumer.getErrorKey(sample)); sample = new Sample(0, metadata, new String[] { "false", "200", "", "FailureMessage" }); assertEquals("FailureMessage", ErrorsSummaryConsumer.getErrorKey(sample)); sample = new Sample(0, metadata, new String[] { "false", "200", "", "" }); assertEquals(MetricUtils.ASSERTION_FAILED, ErrorsSummaryConsumer.getErrorKey(sample)); sample = new Sample(0, metadata, new String[] { "false", "200", "", "Test failed: text expected to contain /<title>Some html text</title>/" }); assertEquals("Test failed: text expected to contain /&lt;title&gt;Some html text&lt;/title&gt;/", ErrorsSummaryConsumer.getErrorKey(sample)); sample = new Sample(0, metadata, new String[] { "false", "200", "", "Test failed: text expected to contain /{\"glossary\": { \"title\": \"example glossary\"}}/" }); assertEquals("Test failed: text expected to contain /{&quot;glossary&quot;: { &quot;title&quot;: &quot;example glossary&quot;}}/", ErrorsSummaryConsumer.getErrorKey(sample)); sample = new Sample(0, metadata, new String[] { "true", "200", "", "" }); assertEquals("", ErrorsSummaryConsumer.getErrorKey(sample)); sample = new Sample(0, metadata, new String[] { "false", "403", "", "" }); assertEquals("403", ErrorsSummaryConsumer.getErrorKey(sample)); sample = new Sample(0, metadata, new String[] { "false", "500", "Server Error", "" }); assertEquals("500/Server Error", ErrorsSummaryConsumer.getErrorKey(sample)); }
@Override public <KR> KGroupedStream<KR, V> groupBy(final KeyValueMapper<? super K, ? super V, KR> keySelector) { return groupBy(keySelector, Grouped.with(null, valueSerde)); }
@Test public void shouldNotAllowNullGroupedOnGroupBy() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.groupBy((k, v) -> k, (Grouped<String, String>) null)); assertThat(exception.getMessage(), equalTo("grouped can't be null")); }
public String get(String key, String defaultValue) { String v = get(key); if (v == null) v = defaultValue; return v; }
@Test public void caseInsensitive() { EnvVars ev = new EnvVars(Map.of("Path", "A:B:C")); assertTrue(ev.containsKey("PATH")); assertEquals("A:B:C", ev.get("PATH")); }
public double p50() { return getLinearInterpolation(0.50); }
@Test public void testP50() { HistogramData histogramData1 = HistogramData.linear(0, 0.2, 50); histogramData1.record(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); assertThat(String.format("%.3f", histogramData1.p50()), equalTo("4.200")); HistogramData histogramData2 = HistogramData.linear(0, 0.02, 50); histogramData2.record(0, 0, 0); assertThat(String.format("%.3f", histogramData2.p50()), equalTo("0.010")); }
public static boolean isMatchGlobPattern(String pattern, String value, URL param) { if (param != null && pattern.startsWith("$")) { pattern = param.getRawParameter(pattern.substring(1)); } return isMatchGlobPattern(pattern, value); }
@Test void testIsMatchGlobPattern() throws Exception { assertTrue(UrlUtils.isMatchGlobPattern("*", "value")); assertTrue(UrlUtils.isMatchGlobPattern("", null)); assertFalse(UrlUtils.isMatchGlobPattern("", "value")); assertTrue(UrlUtils.isMatchGlobPattern("value", "value")); assertTrue(UrlUtils.isMatchGlobPattern("v*", "value")); assertTrue(UrlUtils.isMatchGlobPattern("*e", "value")); assertTrue(UrlUtils.isMatchGlobPattern("v*e", "value")); assertTrue(UrlUtils.isMatchGlobPattern("$key", "value", URL.valueOf("dubbo://localhost:8080/Foo?key=v*e"))); }
public boolean setTriggerError(JobTriggerDto trigger) { requireNonNull(trigger, "trigger cannot be null"); final var filter = and( // Make sure that the owner still owns the trigger eq(FIELD_LOCK_OWNER, nodeId), idEq(getId(trigger)) ); final var update = combine( unset(FIELD_LOCK_OWNER), set(FIELD_STATUS, JobTriggerStatus.ERROR)); return collection.updateOne(filter, update).getModifiedCount() > 0; }
@Test public void setTriggerError() { final JobTriggerDto trigger1 = dbJobTriggerService.create(JobTriggerDto.Builder.create(clock) .jobDefinitionId("abc-123") .jobDefinitionType("event-processor-execution-v1") .schedule(IntervalJobSchedule.builder() .interval(1) .unit(TimeUnit.SECONDS) .build()) .build()); // Lock the trigger assertThat(dbJobTriggerService.nextRunnableTrigger()) .isNotEmpty() .get() .satisfies(trigger -> assertThat(trigger.id()).isEqualTo(trigger1.id())); assertThat(dbJobTriggerService.setTriggerError(trigger1)).isTrue(); assertThat(dbJobTriggerService.get(trigger1.id())) .isPresent() .get() .satisfies(trigger -> { // Make sure the lock is gone assertThat(trigger.lock().owner()).isNull(); assertThat(trigger.status()).isEqualTo(JobTriggerStatus.ERROR); }); assertThatCode(() -> dbJobTriggerService.setTriggerError(null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("trigger"); }
void setReplicas(PartitionReplica[] newReplicas) { PartitionReplica[] oldReplicas = replicas; replicas = newReplicas; onReplicasChange(newReplicas, oldReplicas); }
@Test public void testSetReplicaAddresses_multipleTimes() { replicaOwners[0] = localReplica; partition.setReplicas(replicaOwners); partition.setReplicas(replicaOwners); }
@Override public void store(Measure newMeasure) { saveMeasure(newMeasure.inputComponent(), (DefaultMeasure<?>) newMeasure); }
@Test public void should_merge_coverage() { DefaultInputFile file = new TestInputFileBuilder("foo", "src/Foo.php").setLines(5).build(); DefaultCoverage coverage = new DefaultCoverage(underTest); coverage.onFile(file).lineHits(3, 1); DefaultCoverage coverage2 = new DefaultCoverage(underTest); coverage2.onFile(file).lineHits(1, 1); underTest.store(coverage); underTest.store(coverage2); List<ScannerReport.LineCoverage> lineCoverage = new ArrayList<>(); reportReader.readComponentCoverage(file.scannerId()).forEachRemaining(lineCoverage::add); assertThat(lineCoverage).containsExactly( // should be sorted by line ScannerReport.LineCoverage.newBuilder().setLine(1).setHits(true).build(), ScannerReport.LineCoverage.newBuilder().setLine(3).setHits(true).build()); }
public static FlinkJobServerDriver fromConfig(FlinkServerConfiguration configuration) { return create( configuration, createJobServerFactory(configuration), createArtifactServerFactory(configuration), () -> FlinkJobInvoker.create(configuration)); }
@Test public void testConfigurationDefaults() { FlinkJobServerDriver.FlinkServerConfiguration config = new FlinkJobServerDriver.FlinkServerConfiguration(); assertThat(config.getHost(), is("localhost")); assertThat(config.getPort(), is(8099)); assertThat(config.getArtifactPort(), is(8098)); assertThat(config.getExpansionPort(), is(8097)); assertThat(config.getFlinkMaster(), is("[auto]")); assertThat(config.isCleanArtifactsPerJob(), is(true)); FlinkJobServerDriver flinkJobServerDriver = FlinkJobServerDriver.fromConfig(config); assertThat(flinkJobServerDriver, is(not(nullValue()))); }
@Override public double p(double x) { int start = Arrays.binarySearch(this.x, x-5*h); if (start < 0) { start = -start - 1; } int end = Arrays.binarySearch(this.x, x+5*h); if (end < 0) { end = -end - 1; } double p = 0.0; for (int i = start; i < end; i++) { p += gaussian.p(this.x[i] - x); } return p / this.x.length; }
@Test public void testP() { System.out.println("p"); KernelDensity instance = new KernelDensity(x); double expResult = 0.10122; double result = instance.p(3.5); assertEquals(expResult, result, 1E-5); }
public static DescribeAclsRequest parse(ByteBuffer buffer, short version) { return new DescribeAclsRequest(new DescribeAclsRequestData(new ByteBufferAccessor(buffer), version), version); }
@Test public void shouldRoundTripLiteralV0() { final DescribeAclsRequest original = new DescribeAclsRequest.Builder(LITERAL_FILTER).build(V0); final DescribeAclsRequest result = DescribeAclsRequest.parse(original.serialize(), V0); assertRequestEquals(original, result); }
public ClusterSerdes init(Environment env, ClustersProperties clustersProperties, int clusterIndex) { ClustersProperties.Cluster clusterProperties = clustersProperties.getClusters().get(clusterIndex); log.debug("Configuring serdes for cluster {}", clusterProperties.getName()); var globalPropertiesResolver = new PropertyResolverImpl(env); var clusterPropertiesResolver = new PropertyResolverImpl(env, "kafka.clusters." + clusterIndex); Map<String, SerdeInstance> registeredSerdes = new LinkedHashMap<>(); // initializing serdes from config if (clusterProperties.getSerde() != null) { for (int i = 0; i < clusterProperties.getSerde().size(); i++) { ClustersProperties.SerdeConfig serdeConfig = clusterProperties.getSerde().get(i); if (Strings.isNullOrEmpty(serdeConfig.getName())) { throw new ValidationException("'name' property not set for serde: " + serdeConfig); } if (registeredSerdes.containsKey(serdeConfig.getName())) { throw new ValidationException("Multiple serdes with same name: " + serdeConfig.getName()); } var instance = createSerdeFromConfig( serdeConfig, new PropertyResolverImpl(env, "kafka.clusters." + clusterIndex + ".serde." + i + ".properties"), clusterPropertiesResolver, globalPropertiesResolver ); registeredSerdes.put(serdeConfig.getName(), instance); } } // initializing remaining built-in serdes with empty selection patters builtInSerdeClasses.forEach((name, clazz) -> { if (!registeredSerdes.containsKey(name)) { BuiltInSerde serde = createSerdeInstance(clazz); if (autoConfigureSerde(serde, clusterPropertiesResolver, globalPropertiesResolver)) { registeredSerdes.put(name, new SerdeInstance(name, serde, null, null, null)); } } }); registerTopicRelatedSerde(registeredSerdes); return new ClusterSerdes( registeredSerdes, Optional.ofNullable(clusterProperties.getDefaultKeySerde()) .map(name -> Preconditions.checkNotNull(registeredSerdes.get(name), "Default key serde not found")) .orElse(null), Optional.ofNullable(clusterProperties.getDefaultValueSerde()) .map(name -> Preconditions.checkNotNull(registeredSerdes.get(name), "Default value serde not found")) .or(() -> Optional.ofNullable(registeredSerdes.get(SchemaRegistrySerde.name()))) .or(() -> Optional.ofNullable(registeredSerdes.get(ProtobufFileSerde.name()))) .orElse(null), createFallbackSerde() ); }
@Test void serdeWithBuiltInNameAndSetPropertiesAreExplicitlyConfigured() { ClustersProperties.SerdeConfig serdeConfig = new ClustersProperties.SerdeConfig(); serdeConfig.setName("BuiltIn1"); serdeConfig.setProperties(Map.of("any", "property")); serdeConfig.setTopicKeysPattern("keys"); serdeConfig.setTopicValuesPattern("vals"); var serdes = init(serdeConfig); SerdeInstance explicitlyConfiguredSerde = serdes.serdes.get("BuiltIn1"); verifyExplicitlyConfigured(explicitlyConfiguredSerde); verifyPatternsMatch(serdeConfig, explicitlyConfiguredSerde); }
@Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { ClassLoader stagedClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader effectiveClassLoader; if (invocation.getServiceModel() != null) { effectiveClassLoader = invocation.getServiceModel().getClassLoader(); } else { effectiveClassLoader = invoker.getClass().getClassLoader(); } if (effectiveClassLoader != null) { invocation.put(STAGED_CLASSLOADER_KEY, stagedClassLoader); invocation.put(WORKING_CLASSLOADER_KEY, effectiveClassLoader); Thread.currentThread().setContextClassLoader(effectiveClassLoader); } try { return invoker.invoke(invocation); } finally { Thread.currentThread().setContextClassLoader(stagedClassLoader); } }
@Test void testInvoke() throws Exception { URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1"); String path = DemoService.class.getResource("/").getPath(); final URLClassLoader cl = new URLClassLoader(new java.net.URL[] {new java.net.URL("file:" + path)}) { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { try { return findClass(name); } catch (ClassNotFoundException e) { return super.loadClass(name); } } }; final Class<?> clazz = cl.loadClass(DemoService.class.getCanonicalName()); Invoker invoker = new MyInvoker(url) { @Override public Class getInterface() { return clazz; } @Override public Result invoke(Invocation invocation) throws RpcException { Assertions.assertEquals(cl, Thread.currentThread().getContextClassLoader()); return null; } }; Invocation invocation = Mockito.mock(Invocation.class); ServiceModel serviceModel = Mockito.mock(ServiceModel.class); Mockito.when(serviceModel.getClassLoader()).thenReturn(cl); Mockito.when(invocation.getServiceModel()).thenReturn(serviceModel); classLoaderFilter.invoke(invoker, invocation); }
public Certificate add(X509Certificate cert) { final Certificate db; try { db = Certificate.from(cert); } catch (CertificateEncodingException e) { logger.error("Encoding error in certificate", e); throw new ClientException("Encoding error in certificate", e); } try { // Special case for first CSCA certificate for this document type if (repository.countByDocumentTypeAndType(db.getDocumentType(), db.getType()) == 0) { cert.verify(cert.getPublicKey()); logger.warn("Added first CSCA certificate for {}, set trusted flag manually", db.getDocumentType()); } else { verify(cert, allowAddingExpired ? cert.getNotAfter() : null); } } catch (GeneralSecurityException | VerificationException e) { logger.error( String.format("Could not verify certificate of %s issued by %s", cert.getSubjectX500Principal(), cert.getIssuerX500Principal() ), e ); throw new ClientException("Could not verify certificate", e); } return repository.saveAndFlush(db); }
@Test public void shouldDisallowToAddCertificateIfTrustedByExistingIfExpiredAndNotAllowed() throws CertificateException, IOException { certificateRepo.saveAndFlush(loadCertificate("test/root.crt", true)); certificateRepo.saveAndFlush(loadCertificate("test/intermediate.crt", false)); final X509Certificate cert = readCertificate("test/expired.crt"); assertThrows(ClientException.class, () -> service.add(cert)); }
public static URI getServerAddress(final KsqlRestConfig restConfig) { final List<String> listeners = restConfig.getList(KsqlRestConfig.LISTENERS_CONFIG); final String address = listeners.stream() .map(String::trim) .findFirst() .orElseThrow(() -> new ConfigException(KsqlRestConfig.LISTENERS_CONFIG, listeners, "value cannot be empty")); try { return new URL(address).toURI(); } catch (final Exception e) { throw new ConfigException(KsqlRestConfig.LISTENERS_CONFIG, listeners, e.getMessage()); } }
@Test public void shouldReturnServerAddress() { // Given: final KsqlRestConfig restConfig = new KsqlRestConfig( Collections.singletonMap(KsqlRestConfig.LISTENERS_CONFIG, "http://localhost:8088, http://localhost:9099")); // Then: ServerUtil.getServerAddress(restConfig); }