focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@SuppressWarnings({"SimplifyBooleanReturn"}) public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) { if (params == null || params.isEmpty()) { return params; } Map<String, ParamDefinition> mapped = params.entrySet().stream() .collect( MapHelper.toListMap( Map.Entry::getKey, p -> { ParamDefinition param = p.getValue(); if (param.getType() == ParamType.MAP) { MapParamDefinition mapParamDef = param.asMapParamDef(); if (mapParamDef.getValue() == null && (mapParamDef.getInternalMode() == InternalParamMode.OPTIONAL)) { return mapParamDef; } return MapParamDefinition.builder() .name(mapParamDef.getName()) .value(cleanupParams(mapParamDef.getValue())) .expression(mapParamDef.getExpression()) .name(mapParamDef.getName()) .validator(mapParamDef.getValidator()) .tags(mapParamDef.getTags()) .mode(mapParamDef.getMode()) .meta(mapParamDef.getMeta()) .build(); } else { return param; } })); Map<String, ParamDefinition> filtered = mapped.entrySet().stream() .filter( p -> { ParamDefinition param = p.getValue(); if (param.getInternalMode() == InternalParamMode.OPTIONAL) { if (param.getValue() == null && param.getExpression() == null) { return false; } else if (param.getType() == ParamType.MAP && param.asMapParamDef().getValue() != null && param.asMapParamDef().getValue().isEmpty()) { return false; } else { return true; } } else { Checks.checkTrue( param.getValue() != null || param.getExpression() != null, String.format( "[%s] is a required parameter (type=[%s])", p.getKey(), param.getType())); return true; } }) .collect(MapHelper.toListMap(Map.Entry::getKey, Map.Entry::getValue)); return cleanIntermediateMetadata(filtered); }
@Test public void testCleanupOptionalNestedEmptyParams() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'map': {'type': 'MAP','value': {'optional': {'type': 'STRING', 'internal_mode': 'OPTIONAL'}}}}"); Map<String, ParamDefinition> cleanedParams = ParamsMergeHelper.cleanupParams(allParams); assertEquals(0, cleanedParams.get("map").asMapParamDef().getValue().size()); }
static ByteBuffer resetBuffer(ByteBuffer buffer, int len) { int pos = buffer.position(); buffer.put(getEmptyChunk(len), 0, len); buffer.position(pos); return buffer; }
@Test public void testResetBuffer() { ByteBuffer buf = ByteBuffer.allocate(chunkSize * 2).putInt(1234); buf.position(0); ByteBuffer ret = CoderUtil.resetBuffer(buf, chunkSize); for (int i = 0; i < chunkSize; i++) { assertEquals(0, ret.getInt(i)); } byte[] inputs = ByteBuffer.allocate(numInputs) .putInt(1234).array(); CoderUtil.resetBuffer(inputs, 0, numInputs); for (int i = 0; i < numInputs; i++) { assertEquals(0, inputs[i]); } }
@Override public T master() { List<ChildData<T>> children = getActiveChildren(); children.sort(sequenceComparator); if (children.isEmpty()) { return null; } return children.get(0).getNode(); }
@Test public void testMasterWithStaleNodes2() throws Exception { putChildData(group, PATH + "/001", "container1"); // stale putChildData(group, PATH + "/002", "container2"); putChildData(group, PATH + "/003", "container1"); putChildData(group, PATH + "/004", "container3"); // stale putChildData(group, PATH + "/005", "container3"); NodeState master = group.master(); assertThat(master, notNullValue()); assertThat(master.getContainer(), equalTo("container2")); }
@Override public InterpreterResult interpret(final String st, final InterpreterContext context) throws InterpreterException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("st:\n{}", st); } final FormType form = getFormType(); RemoteInterpreterProcess interpreterProcess = null; try { interpreterProcess = getOrCreateInterpreterProcess(); } catch (IOException e) { throw new InterpreterException(e); } if (!interpreterProcess.isRunning()) { return new InterpreterResult(InterpreterResult.Code.ERROR, "Interpreter process is not running\n" + interpreterProcess.getErrorMessage()); } return interpreterProcess.callRemoteFunction(client -> { RemoteInterpreterResult remoteResult = client.interpret( sessionId, className, st, convert(context)); Map<String, Object> remoteConfig = (Map<String, Object>) GSON.fromJson( remoteResult.getConfig(), new TypeToken<Map<String, Object>>() { }.getType()); context.getConfig().clear(); if (remoteConfig != null) { context.getConfig().putAll(remoteConfig); } GUI currentGUI = context.getGui(); GUI currentNoteGUI = context.getNoteGui(); if (form == FormType.NATIVE) { GUI remoteGui = GUI.fromJson(remoteResult.getGui()); GUI remoteNoteGui = GUI.fromJson(remoteResult.getNoteGui()); currentGUI.clear(); currentGUI.setParams(remoteGui.getParams()); currentGUI.setForms(remoteGui.getForms()); currentNoteGUI.setParams(remoteNoteGui.getParams()); currentNoteGUI.setForms(remoteNoteGui.getForms()); } else if (form == FormType.SIMPLE) { final Map<String, Input> currentForms = currentGUI.getForms(); final Map<String, Object> currentParams = currentGUI.getParams(); final GUI remoteGUI = GUI.fromJson(remoteResult.getGui()); final Map<String, Input> remoteForms = remoteGUI.getForms(); final Map<String, Object> remoteParams = remoteGUI.getParams(); currentForms.putAll(remoteForms); currentParams.putAll(remoteParams); } return convert(remoteResult); } ); }
@Test void testFIFOScheduler() throws InterruptedException, InterpreterException { interpreterSetting.getOption().setPerUser(InterpreterOption.SHARED); // by default SleepInterpreter would use FIFOScheduler final Interpreter interpreter1 = interpreterSetting.getInterpreter("user1", note1Id, "sleep"); final InterpreterContext context1 = createDummyInterpreterContext(); // run this dummy interpret method first to launch the RemoteInterpreterProcess to avoid the // time overhead of launching the process. interpreter1.interpret("1", context1); Thread thread1 = new Thread() { @Override public void run() { try { assertEquals(Code.SUCCESS, interpreter1.interpret("100", context1).code()); } catch (InterpreterException e) { e.printStackTrace(); fail(); } } }; Thread thread2 = new Thread() { @Override public void run() { try { assertEquals(Code.SUCCESS, interpreter1.interpret("100", context1).code()); } catch (InterpreterException e) { e.printStackTrace(); fail(); } } }; long start = System.currentTimeMillis(); thread1.start(); thread2.start(); thread1.join(); thread2.join(); long end = System.currentTimeMillis(); assertTrue((end - start) >= 200); }
@Override public void deleteDiyTemplate(Long id) { // 校验存在 DiyTemplateDO diyTemplateDO = validateDiyTemplateExists(id); // 校验使用中 if (BooleanUtil.isTrue(diyTemplateDO.getUsed())) { throw exception(DIY_TEMPLATE_USED_CANNOT_DELETE); } // 删除 diyTemplateMapper.deleteById(id); }
@Test public void testDeleteDiyTemplate_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> diyTemplateService.deleteDiyTemplate(id), DIY_TEMPLATE_NOT_EXISTS); }
static Result coerceUserList( final Collection<Expression> expressions, final ExpressionTypeManager typeManager ) { return coerceUserList(expressions, typeManager, Collections.emptyMap()); }
@Test public void shouldNotCoerceArrayWithDifferentExpression() { // Given: final ImmutableList<Expression> expressions = ImmutableList.of( new CreateArrayExpression( ImmutableList.of( new IntegerLiteral(10) ) ), new CreateArrayExpression( ImmutableList.of( STRING_EXPRESSION ) ) ); // When: final Exception e = assertThrows( KsqlException.class, () -> CoercionUtil.coerceUserList(expressions, typeManager) ); // Then: assertThat(e.getMessage(), startsWith("operator does not exist: ARRAY<INTEGER> = ARRAY<STRING> (ARRAY[STR])")); }
@Override public E poll() { E item = next(); if (item != null) { return item; } if (!drainPutStack()) { return null; } return next(); }
@Test public void poll() throws InterruptedException { queue.setConsumerThread(Thread.currentThread()); queue.offer("1"); queue.offer("2"); assertEquals("1", queue.poll()); assertEquals("2", queue.poll()); }
@Override public YamlProcessList swapToYamlConfiguration(final Collection<Process> data) { YamlProcessList result = new YamlProcessList(); result.setProcesses(data.stream().map(yamlProcessSwapper::swapToYamlConfiguration).collect(Collectors.toList())); return result; }
@Test void assertSwapToYamlConfiguration() { String processId = new UUID(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()).toString().replace("-", ""); ExecutionGroupReportContext reportContext = new ExecutionGroupReportContext(processId, "foo_db", new Grantee("root", "localhost")); ExecutionGroupContext<? extends SQLExecutionUnit> executionGroupContext = new ExecutionGroupContext<>(Collections.emptyList(), reportContext); Process process = new Process("SELECT 1", executionGroupContext); YamlProcessList actual = new YamlProcessListSwapper().swapToYamlConfiguration(Collections.singleton(process)); assertThat(actual.getProcesses().size(), is(1)); assertYamlProcessContext(actual.getProcesses().iterator().next()); }
public String generateInvalidPayloadExceptionMessage(final byte[] hl7Bytes) { if (hl7Bytes == null) { return "HL7 payload is null"; } return generateInvalidPayloadExceptionMessage(hl7Bytes, hl7Bytes.length); }
@Test public void testGenerateInvalidPayloadExceptionMessage() { String message = hl7util.generateInvalidPayloadExceptionMessage(TEST_MESSAGE.getBytes()); assertNull(message, "Valid payload should result in a null message"); }
@Override public String toString() { StringBuilder result = new StringBuilder(); result.append(" ORDER BY "); for (int i = 0; i < columnLabels.size(); i++) { if (0 == i) { result.append(columnLabels.get(0)).append(' ').append(orderDirections.get(i).name()); } else { result.append(',').append(columnLabels.get(i)).append(' ').append(orderDirections.get(i).name()); } } result.append(' '); return result.toString(); }
@Test void assertToString() { assertThat(orderByToken.toString(), is(" ORDER BY Test1 ASC,Test2 ASC ")); }
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) { GuardedByExpression expr = BINDER.visit(exp, context); checkGuardedBy(expr != null, String.valueOf(exp)); checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp); return expr; }
@Test public void namedClass_super() { assertThat( bind( "Test", "Super.class", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Super {}", "class Test extends Super {}"))) .isEqualTo("(CLASS_LITERAL threadsafety.Super)"); }
@Udf public <T> List<T> remove( @UdfParameter(description = "Array of values") final List<T> array, @UdfParameter(description = "Value to remove") final T victim) { if (array == null) { return null; } return array.stream() .filter(el -> !Objects.equals(el, victim)) .collect(Collectors.toList()); }
@Test public void shouldRemoveAllMatchingElements() { final List<String> input1 = Arrays.asList("foo", " ", "foo", "bar"); final String input2 = "foo"; final List<String> result = udf.remove(input1, input2); assertThat(result, is(Arrays.asList(" ", "bar"))); }
public WorkerService getWorkerService() throws UnsupportedOperationException { return functionWorkerService.orElseThrow(() -> new UnsupportedOperationException("Pulsar Function Worker " + "is not enabled, probably functionsWorkerEnabled is set to false")); }
@Test public void testGetWorkerServiceException() throws Exception { conf.setFunctionsWorkerEnabled(false); setup(); String errorMessage = "Pulsar Function Worker is not enabled, probably functionsWorkerEnabled is set to false"; int thrownCnt = 0; try { pulsar.getWorkerService(); } catch (UnsupportedOperationException e) { thrownCnt++; assertEquals(e.getMessage(), errorMessage); } try { admin.sources().listSources("my", "test"); } catch (PulsarAdminException e) { thrownCnt++; assertEquals(e.getStatusCode(), 409); assertEquals(e.getMessage(), errorMessage); } try { admin.sinks().getSinkStatus("my", "test", "test"); } catch (PulsarAdminException e) { thrownCnt++; assertEquals(e.getStatusCode(), 409); assertEquals(e.getMessage(), errorMessage); } try { admin.functions().getFunction("my", "test", "test"); } catch (PulsarAdminException e) { thrownCnt++; assertEquals(e.getStatusCode(), 409); assertEquals(e.getMessage(), errorMessage); } try { admin.worker().getClusterLeader(); } catch (PulsarAdminException e) { thrownCnt++; assertEquals(e.getStatusCode(), 409); assertEquals(e.getMessage(), errorMessage); } try { admin.worker().getFunctionsStats(); } catch (PulsarAdminException e) { thrownCnt++; assertEquals(e.getStatusCode(), 409); assertEquals(e.getMessage(), errorMessage); } assertEquals(thrownCnt, 6); }
@Override public void close() { this.displayResultExecutorService.shutdown(); }
@Test void testFailedStreamingResult() { final Configuration testConfig = new Configuration(); testConfig.set(EXECUTION_RESULT_MODE, ResultMode.TABLEAU); testConfig.set(RUNTIME_MODE, RuntimeExecutionMode.STREAMING); ResultDescriptor resultDescriptor = new ResultDescriptor(CliClientTestUtils.createTestClient(schema), testConfig); TestChangelogResult changelogResult = new TestChangelogResult( () -> { throw new SqlExecutionException("query failed"); }); CliTableauResultView view = new CliTableauResultView( terminal, resultDescriptor, changelogResult, System.currentTimeMillis()); assertThatThrownBy(view::displayResults) .satisfies(anyCauseMatches(SqlExecutionException.class, "query failed")); view.close(); assertThat(changelogResult.closed).isTrue(); }
static List<String> locateScripts(ArgsMap argsMap) { String script = argsMap.get(SCRIPT); String scriptDir = argsMap.get(SCRIPT_DIR); List<String> scripts = new ArrayList<>(); if (script != null) { StringTokenizer tokenizer = new StringTokenizer(script, ":"); if (log.isDebugEnabled()) { log.debug( ((tokenizer.countTokens() == 1) ? "initial script is {}" : "initial scripts are {}"), script); } while (tokenizer.hasMoreTokens()) { scripts.add(tokenizer.nextToken()); } } if (scriptDir != null) { File dir = new File(scriptDir); if (dir.isDirectory()) { if (log.isDebugEnabled()) { log.debug("found scriptdir: {}", dir.getAbsolutePath()); } File[] files = dir.listFiles(); if (files != null) { for (File file : files) { scripts.add(file.getAbsolutePath()); } } } } return scripts; }
@Test void locateScriptsDir() throws Exception { Path dir = Files.createTempDirectory("test-"); Path script = Files.createTempFile(dir, "script-", ".btrace"); ArgsMap argsMap = new ArgsMap(new String[] {"scriptdir=" + dir.toString()}); List<String> scripts = Main.locateScripts(argsMap); assertEquals(1, scripts.size()); }
public int format(String... args) throws UsageException { CommandLineOptions parameters = processArgs(args); if (parameters.version()) { errWriter.println(versionString()); return 0; } if (parameters.help()) { throw new UsageException(); } JavaFormatterOptions options = JavaFormatterOptions.builder() .style(parameters.aosp() ? Style.AOSP : Style.GOOGLE) .formatJavadoc(parameters.formatJavadoc()) .build(); if (parameters.stdin()) { return formatStdin(parameters, options); } else { return formatFiles(parameters, options); } }
@Test public void version() throws UsageException { StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in); assertThat(main.format("-version")).isEqualTo(0); assertThat(err.toString()).contains("google-java-format: Version "); }
public String text() { return text; }
@Test public void textOnly() { badge = NodeBadge.text(TXT); checkFields(badge, Status.INFO, false, TXT, null); }
@NonNull @Override public FileName toProviderFileName( @NonNull ConnectionFileName pvfsFileName, @NonNull T details ) throws KettleException { StringBuilder providerUriBuilder = new StringBuilder(); appendProviderUriConnectionRoot( providerUriBuilder, details ); // Examples: // providerUriBuilder: "hcp://domain.my:443/root/path" | "local:///C:/root/path" | "s3://" // getPath(): "/folder/sub-folder" | "/" appendProviderUriRestPath( providerUriBuilder, pvfsFileName.getPath(), details ); // Examples: "hcp://domain.my:443/root/path/folder/sub-folder" | "s3://folder/sub-folder" // Preserve file type information. if ( pvfsFileName.getType().hasChildren() ) { providerUriBuilder.append( SEPARATOR ); } return parseUri( providerUriBuilder.toString() ); }
@Test public void testToProviderFileNameHandlesTwoLevelPaths() throws Exception { ConnectionFileName pvfsFileName = mockPvfsFileNameWithPath( "/rest/path" ); FileName providerFileName = transformer.toProviderFileName( pvfsFileName, details1 ); assertEquals( "scheme1://rest/path", providerFileName.getURI() ); assertTrue( providerFileName.isFile() ); // Should do provider uri normalization. verify( kettleVFS, times( 1 ) ).resolveURI( any() ); }
public abstract void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception;
@Test void listHelpOnceOnArgumentOmission() throws Exception { assertThat(cli.run("test", "-h")) .isEmpty(); assertThat(stdOut) .hasToString(String.format( "usage: java -jar dw-thing.jar test [-h] {a,b,c}%n" + "%n" + "test%n" + "%n" + "positional arguments:%n" + " {a,b,c} Type to use%n" + "%n" + "named arguments:%n" + " -h, --help show this help message and exit%n" )); assertThat(stdErr.toString()) .isEmpty(); }
private CompletableFuture<Boolean> isSuperUser() { assert ctx.executor().inEventLoop(); if (service.isAuthenticationEnabled() && service.isAuthorizationEnabled()) { CompletableFuture<Boolean> isAuthRoleAuthorized = service.getAuthorizationService().isSuperUser( authRole, authenticationData); if (originalPrincipal != null) { CompletableFuture<Boolean> isOriginalPrincipalAuthorized = service.getAuthorizationService() .isSuperUser(originalPrincipal, originalAuthData != null ? originalAuthData : authenticationData); return isOriginalPrincipalAuthorized.thenCombine(isAuthRoleAuthorized, (originalPrincipal, authRole) -> originalPrincipal && authRole); } else { return isAuthRoleAuthorized; } } else { return CompletableFuture.completedFuture(true); } }
@Test(timeOut = 30000) public void testNonExistentTopic() throws Exception { AuthorizationService authorizationService = spyWithClassAndConstructorArgs(AuthorizationService.class, svcConfig, pulsar.getPulsarResources()); doReturn(authorizationService).when(brokerService).getAuthorizationService(); svcConfig.setAuthorizationEnabled(true); svcConfig.setAuthorizationEnabled(true); Field providerField = AuthorizationService.class.getDeclaredField("provider"); providerField.setAccessible(true); PulsarAuthorizationProvider authorizationProvider = spyWithClassAndConstructorArgs(PulsarAuthorizationProvider.class, svcConfig, pulsar.getPulsarResources()); providerField.set(authorizationService, authorizationProvider); doReturn(CompletableFuture.completedFuture(false)).when(authorizationProvider) .isSuperUser(Mockito.anyString(), Mockito.any(), Mockito.any()); // Test producer creation resetChannel(); setChannelConnected(); ByteBuf newProducerCmd = Commands.newProducer(nonExistentTopicName, 1 /* producer id */, 1 /* request id */, "prod-name", Collections.emptyMap(), false); channel.writeInbound(newProducerCmd); assertTrue(getResponse() instanceof CommandError); channel.finish(); // Test consumer creation resetChannel(); setChannelConnected(); ByteBuf newSubscribeCmd = Commands.newSubscribe(nonExistentTopicName, // successSubName, 1 /* consumer id */, 1 /* request id */, SubType.Exclusive, 0, "test" /* consumer name */, 0); channel.writeInbound(newSubscribeCmd); assertTrue(getResponse() instanceof CommandError); channel.finish(); }
static String lastPartOf(String string, String separator) { String[] parts = string.split(separator); return parts[parts.length - 1]; }
@Test public void lastPartOfTest() { assertEquals("us-east1-a", lastPartOf("https://www.googleapis.com/compute/v1/projects/projectId/zones/us-east1-a", "/")); assertEquals("", lastPartOf("", "")); assertEquals("", lastPartOf("", "/")); }
@Override public boolean tryLock(String name) { return tryLock(name, DEFAULT_LOCK_DURATION_SECONDS); }
@Test public void tryLock_fails_with_IAE_if_name_length_is_more_than_max_or_more() { String badLockName = RandomStringUtils.random(LOCK_NAME_MAX_LENGTH + 1 + new Random().nextInt(96)); expectBadLockNameIAE(() -> underTest.tryLock(badLockName), badLockName); }
public void ensureActiveGroup() { while (!ensureActiveGroup(time.timer(Long.MAX_VALUE))) { log.warn("still waiting to ensure active group"); } }
@Test public void testWakeupAfterSyncGroupReceivedExternalCompletion() throws Exception { setupCoordinator(); mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); mockClient.prepareResponse(joinGroupFollowerResponse(1, memberId, leaderId, Errors.NONE)); mockClient.prepareResponse(body -> { boolean isSyncGroupRequest = body instanceof SyncGroupRequest; if (isSyncGroupRequest) // wakeup after the request returns consumerClient.wakeup(); return isSyncGroupRequest; }, syncGroupResponse(Errors.NONE)); AtomicBoolean heartbeatReceived = prepareFirstHeartbeat(); assertThrows(WakeupException.class, () -> coordinator.ensureActiveGroup(), "Should have woken up from ensureActiveGroup()"); assertEquals(1, coordinator.onJoinPrepareInvokes); assertEquals(0, coordinator.onJoinCompleteInvokes); assertFalse(heartbeatReceived.get()); coordinator.ensureActiveGroup(); assertEquals(1, coordinator.onJoinPrepareInvokes); assertEquals(1, coordinator.onJoinCompleteInvokes); awaitFirstHeartbeat(heartbeatReceived); }
public static ExtensibleLoadManagerImpl get(LoadManager loadManager) { if (!(loadManager instanceof ExtensibleLoadManagerWrapper loadManagerWrapper)) { throw new IllegalArgumentException("The load manager should be 'ExtensibleLoadManagerWrapper'."); } return loadManagerWrapper.get(); }
@Test(timeOut = 10 * 1000) public void unloadTimeoutCheckTest() throws Exception { Pair<TopicName, NamespaceBundle> topicAndBundle = getBundleIsNotOwnByChangeEventTopic("unload-timeout"); String topic = topicAndBundle.getLeft().toString(); var bundle = topicAndBundle.getRight().toString(); var releasing = new ServiceUnitStateData(Releasing, pulsar2.getBrokerId(), pulsar1.getBrokerId(), 1); overrideTableView(channel1, bundle, releasing); var topicFuture = pulsar1.getBrokerService().getOrCreateTopic(topic); try { topicFuture.get(1, TimeUnit.SECONDS); } catch (Exception e) { log.info("getOrCreateTopic failed", e); if (!(e.getCause() instanceof BrokerServiceException.ServiceUnitNotReadyException && e.getMessage() .contains("Please redo the lookup"))) { fail(); } } pulsar1.getBrokerService() .unloadServiceUnit(topicAndBundle.getRight(), true, true, 5, TimeUnit.SECONDS).get(2, TimeUnit.SECONDS); }
public Watcher getWatcher() throws IOException { if (JAVA_VERSION >= 1.7) { if (IS_WINDOWS) { return new TreeWatcherNIO(); } else { return new WatcherNIO2(); } } else { throw new UnsupportedOperationException("Watcher is implemented only for Java 1.7 (NIO2). " + "JNotify implementation should be added in the future for older Java version support."); } }
@Test public void testGetWatcher() throws Exception { assertNotNull(new WatcherFactory().getWatcher()); }
public static String encodeInUtf8(String url) { String[] parts = url.split("/"); StringBuilder builder = new StringBuilder(); for (int i = 0; i < parts.length; i++) { String part = parts[i]; builder.append(URLEncoder.encode(part, StandardCharsets.UTF_8)); if (i < parts.length - 1) { builder.append('/'); } } if (url.endsWith("/")) { builder.append('/'); } return builder.toString(); }
@Test public void shouldKeepTrailingSlash() { assertThat(UrlUtil.encodeInUtf8("a%b/c%d/"), is("a%25b/c%25d/")); }
public static Map<String, Object> appendDeserializerToConfig(Map<String, Object> configs, Deserializer<?> keyDeserializer, Deserializer<?> valueDeserializer) { // validate deserializer configuration, if the passed deserializer instance is null, the user must explicitly set a valid deserializer configuration value Map<String, Object> newConfigs = new HashMap<>(configs); if (keyDeserializer != null) newConfigs.put(KEY_DESERIALIZER_CLASS_CONFIG, keyDeserializer.getClass()); else if (newConfigs.get(KEY_DESERIALIZER_CLASS_CONFIG) == null) throw new ConfigException(KEY_DESERIALIZER_CLASS_CONFIG, null, "must be non-null."); if (valueDeserializer != null) newConfigs.put(VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializer.getClass()); else if (newConfigs.get(VALUE_DESERIALIZER_CLASS_CONFIG) == null) throw new ConfigException(VALUE_DESERIALIZER_CLASS_CONFIG, null, "must be non-null."); return newConfigs; }
@Test public void testAppendDeserializerToConfigWithException() { Map<String, Object> configs = new HashMap<>(); configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, null); configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializerClass); assertThrows(ConfigException.class, () -> ConsumerConfig.appendDeserializerToConfig(configs, null, valueDeserializer)); configs.clear(); configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, keyDeserializerClass); configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, null); assertThrows(ConfigException.class, () -> ConsumerConfig.appendDeserializerToConfig(configs, keyDeserializer, null)); }
@Override public List<String> getAttributes() { return attributes; }
@Test public void testGetAttributes() throws Exception { NumberField f = new NumberField("test", "Name", 0, "foo", ConfigurationField.Optional.NOT_OPTIONAL); assertEquals(0, f.getAttributes().size()); NumberField f1 = new NumberField("test", "Name", 0, "foo", NumberField.Attribute.IS_PORT_NUMBER); assertEquals(1, f1.getAttributes().size()); assertTrue(f1.getAttributes().contains("is_port_number")); NumberField f2 = new NumberField("test", "Name", 0, "foo", NumberField.Attribute.IS_PORT_NUMBER, NumberField.Attribute.ONLY_POSITIVE); assertEquals(2, f2.getAttributes().size()); assertTrue(f2.getAttributes().contains("is_port_number")); assertTrue(f2.getAttributes().contains("only_positive")); }
public NetworkConfig setPortCount(int portCount) { if (portCount < 1) { throw new IllegalArgumentException("port count can't be smaller than 0"); } this.portCount = portCount; return this; }
@Test(expected = IllegalArgumentException.class) public void testNegativePortCount() { int portCount = -1; networkConfig.setPortCount(portCount); }
private EntityRelation doDelete(String strFromId, String strFromType, String strRelationType, String strRelationTypeGroup, String strToId, String strToType) throws ThingsboardException { checkParameter(FROM_ID, strFromId); checkParameter(FROM_TYPE, strFromType); checkParameter(RELATION_TYPE, strRelationType); checkParameter(TO_ID, strToId); checkParameter(TO_TYPE, strToType); EntityId fromId = EntityIdFactory.getByTypeAndId(strFromType, strFromId); EntityId toId = EntityIdFactory.getByTypeAndId(strToType, strToId); checkCanCreateRelation(fromId); checkCanCreateRelation(toId); RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); EntityRelation relation = new EntityRelation(fromId, toId, strRelationType, relationTypeGroup); return tbEntityRelationService.delete(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser()); }
@Test public void testDeleteRelationWithOtherFromDeviceError() throws Exception { Device device = buildSimpleDevice("Test device 1"); EntityRelation relation = createFromRelation(mainDevice, device, "CONTAINS"); doPost("/api/relation", relation).andExpect(status().isOk()); Device device2 = buildSimpleDevice("Test device 2"); String url = String.format("/api/relation?fromId=%s&fromType=%s&relationType=%s&toId=%s&toType=%s", device2.getUuidId(), EntityType.DEVICE, "CONTAINS", device.getUuidId(), EntityType.DEVICE ); Mockito.reset(tbClusterService, auditLogService); doDelete(url) .andExpect(status().isNotFound()) .andExpect(statusReason(containsString(msgErrorNotFound))); testNotifyEntityNever(mainDevice.getId(), null); }
public List<String[]> select() { return select(this.datas.length); }
@Test public void selectTest() { Arrangement arrangement = new Arrangement(new String[] { "1", "2", "3", "4" }); List<String[]> list = arrangement.select(2); assertEquals(Arrangement.count(4, 2), list.size()); assertArrayEquals(new String[] {"1", "2"}, list.get(0)); assertArrayEquals(new String[] {"1", "3"}, list.get(1)); assertArrayEquals(new String[] {"1", "4"}, list.get(2)); assertArrayEquals(new String[] {"2", "1"}, list.get(3)); assertArrayEquals(new String[] {"2", "3"}, list.get(4)); assertArrayEquals(new String[] {"2", "4"}, list.get(5)); assertArrayEquals(new String[] {"3", "1"}, list.get(6)); assertArrayEquals(new String[] {"3", "2"}, list.get(7)); assertArrayEquals(new String[] {"3", "4"}, list.get(8)); assertArrayEquals(new String[] {"4", "1"}, list.get(9)); assertArrayEquals(new String[] {"4", "2"}, list.get(10)); assertArrayEquals(new String[] {"4", "3"}, list.get(11)); List<String[]> selectAll = arrangement.selectAll(); assertEquals(Arrangement.countAll(4), selectAll.size()); List<String[]> list2 = arrangement.select(0); assertEquals(1, list2.size()); }
@Override public int compare(T o1, T o2) { if (!(o1 instanceof CharSequence) || !(o2 instanceof CharSequence)) { throw new RuntimeException("Attempted use of AvroCharSequenceComparator on non-CharSequence objects: " + o1.getClass().getName() + " and " + o2.getClass().getName()); } return compareCharSequence((CharSequence) o1, (CharSequence) o2); }
@Test void compareUtf8ToString() { assertEquals(0, mComparator.compare(new Utf8(""), "")); assertThat(mComparator.compare(new Utf8(""), "a"), lessThan(0)); assertThat(mComparator.compare(new Utf8("a"), ""), greaterThan(0)); assertEquals(0, mComparator.compare(new Utf8("a"), "a")); assertThat(mComparator.compare(new Utf8("a"), "b"), lessThan(0)); assertThat(mComparator.compare(new Utf8("b"), "a"), greaterThan(0)); assertEquals(0, mComparator.compare(new Utf8("ab"), "ab")); assertThat(mComparator.compare(new Utf8("a"), "aa"), lessThan(0)); assertThat(mComparator.compare(new Utf8("aa"), "a"), greaterThan(0)); assertThat(mComparator.compare(new Utf8("abc"), "abcdef"), lessThan(0)); assertThat(mComparator.compare(new Utf8("abcdef"), "abc"), greaterThan(0)); }
@Override public V pollFromAny(long timeout, TimeUnit unit, String... queueNames) throws InterruptedException { return commandExecutor.getInterrupted(pollFromAnyAsync(timeout, unit, queueNames)); }
@Test public void testPollFromAny() throws InterruptedException { final RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("queue:pollany"); assertThat(queue1.trySetCapacity(10)).isTrue(); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); executor.schedule(() -> { RBoundedBlockingQueue<Integer> queue2 = redisson.getBoundedBlockingQueue("queue:pollany1"); assertThat(queue2.trySetCapacity(10)).isTrue(); RBoundedBlockingQueue<Integer> queue3 = redisson.getBoundedBlockingQueue("queue:pollany2"); assertThat(queue3.trySetCapacity(10)).isTrue(); try { queue3.put(2); queue1.put(1); queue2.put(3); } catch (Exception e) { Assertions.fail(); } }, 3, TimeUnit.SECONDS); long s = System.currentTimeMillis(); int l = queue1.pollFromAny(40, TimeUnit.SECONDS, "queue:pollany1", "queue:pollany2"); Assertions.assertEquals(2, l); Assertions.assertTrue(System.currentTimeMillis() - s > 2000); executor.shutdown(); assertThat(executor.awaitTermination(1, TimeUnit.MINUTES)).isTrue(); }
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 1) { if ("dateIntToTs".equals(methodName)) { return dateIntToTs(args[0]); } else if ("tsToDateInt".equals(methodName)) { return tsToDateInt(args[0]); } } else if (args.length == 2) { if ("incrementDateInt".equals(methodName)) { return incrementDateInt(args[0], args[1]); } else if ("timeoutForDateTimeDeadline".equals(methodName)) { return timeoutForDateTimeDeadline(args[0], args[1]); } else if ("timeoutForDateIntDeadline".equals(methodName)) { return timeoutForDateIntDeadline(args[0], args[1]); } } else if (args.length == 3) { if ("dateIntsBetween".equals(methodName)) { return dateIntsBetween(args[0], args[1], args[2]); } else if ("intsBetween".equals(methodName)) { return intsBetween(args[0], args[1], args[2]); } } else if (args.length == 5 && "dateIntHourToTs".equals(methodName)) { return dateIntHourToTs(args); } throw new UnsupportedOperationException( type() + " DO NOT support calling method: " + methodName + " with args: " + Arrays.toString(args)); }
@Test(expected = IllegalArgumentException.class) public void testCallTimeoutForDateIntDeadlineInvalidInput() { SelUtilFunc.INSTANCE.call( "timeoutForDateIntDeadline", new SelType[] {SelString.of("2019010101"), SelString.of("1 day")}); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (!requestContext.getUriInfo().getPath().endsWith(targetPath)) { return; } final List<MediaType> acceptedFormats = requestContext.getAcceptableMediaTypes(); final Map<MediaType, ExportFormat> exportFormatCandidates = supportedFormats.entrySet() .stream() .filter(entry -> acceptedFormats.stream().anyMatch(acceptedFormat -> entry.getKey().isCompatible(acceptedFormat))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); if (exportFormatCandidates.isEmpty()) { requestContext.abortWith(Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).build()); return; } final Map<MediaType, Optional<String>> candidateErrors = exportFormatCandidates.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().hasError())); if (candidateErrors.values().stream().allMatch(Optional::isPresent)) { final String errorMessage = candidateErrors.values().stream() .map(optionalError -> optionalError.orElse("")) .collect(Collectors.joining("\n")); requestContext.abortWith(Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE) .entity(errorMessage) .type(MoreMediaTypes.TEXT_PLAIN_TYPE) .build()); return; } final List<String> allowedMediaTypes = candidateErrors.entrySet().stream() .filter(entry -> !entry.getValue().isPresent()) .map(Map.Entry::getKey) .map(MediaType::toString) .collect(Collectors.toList()); requestContext.getHeaders().put(HttpHeaders.ACCEPT, allowedMediaTypes); }
@Test void returns415IfNoCompatibleFormatIsFound() throws Exception { final ContainerRequestFilter filter = new MessageExportFormatFilter(Collections.singleton(() -> MoreMediaTypes.TEXT_PLAIN_TYPE)); final ContainerRequestContext requestContext = mockRequestContext(Collections.singletonList(MoreMediaTypes.APPLICATION_JSON_TYPE)); filter.filter(requestContext); verifyRequestAborted(requestContext); }
public Result parse(final String string) throws DateNotParsableException { return this.parse(string, new Date()); }
@Test public void issue1226() throws Exception { NaturalDateParser.Result result99days = naturalDateParser.parse("last 99 days"); assertThat(result99days.getFrom()).isEqualToIgnoringMillis(result99days.getTo().minusDays(100)); NaturalDateParser.Result result100days = naturalDateParser.parse("last 100 days"); assertThat(result100days.getFrom()).isEqualToIgnoringMillis(result100days.getTo().minusDays(101)); NaturalDateParser.Result result101days = naturalDateParser.parse("last 101 days"); assertThat(result101days.getFrom()).isEqualToIgnoringMillis(result101days.getTo().minusDays(102)); }
@Nonnull public static <K, V> BatchSource<Entry<K, V>> map(@Nonnull String mapName) { return batchFromProcessor("mapSource(" + mapName + ')', readMapP(mapName)); }
@Test public void map_byRef() { // Given List<Integer> input = sequence(itemCount); putToBatchSrcMap(input); // When BatchSource<Entry<String, Integer>> source = Sources.map(srcMap); // Then p.readFrom(source).writeTo(sink); execute(); List<Entry<String, Integer>> expected = input.stream() .map(i -> entry(String.valueOf(i), i)) .collect(toList()); assertEquals(toBag(expected), sinkToBag()); }
public boolean checkIfEnabled() { try { this.gitCommand = locateDefaultGit(); MutableString stdOut = new MutableString(); this.processWrapperFactory.create(null, l -> stdOut.string = l, gitCommand, "--version").execute(); return stdOut.string != null && stdOut.string.startsWith("git version") && isCompatibleGitVersion(stdOut.string); } catch (Exception e) { LOG.debug("Failed to find git native client", e); return false; } }
@Test public void git_should_not_be_enabled_if_version_command_does_not_return_string_output() { ProcessWrapperFactory mockedCmd = mockGitVersionCommand(null); NativeGitBlameCommand blameCommand = new NativeGitBlameCommand(System2.INSTANCE, mockedCmd); assertThat(blameCommand.checkIfEnabled()).isFalse(); }
public static ReduceByKey.CombineFunctionWithIdentity<Float> ofFloats() { return SUMS_OF_FLOAT; }
@Test public void testSumOfFloats() { assertEquals(6f, (float) apply(Stream.of(1f, 2f, 3f), Sums.ofFloats()), 0.001); }
public TurnServerOptions getRoutingFor( @Nonnull final UUID aci, @Nonnull final Optional<InetAddress> clientAddress, final int instanceLimit ) { try { return getRoutingForInner(aci, clientAddress, instanceLimit); } catch(Exception e) { logger.error("Failed to perform routing", e); return new TurnServerOptions(this.configTurnRouter.getHostname(), null, this.configTurnRouter.randomUrls()); } }
@Test public void testOrderedByPerformance() throws UnknownHostException { when(performanceTable.getDatacentersFor(any(), any(), any(), any())) .thenReturn(List.of("dc-performance2", "dc-performance1")); assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10)) .isEqualTo(optionsWithUrls(List.of( "turn:9.9.9.3", "turn:9.9.9.3:80?transport=tcp", "turns:9.9.9.3:443?transport=tcp", "turn:9.9.9.1", "turn:9.9.9.1:80?transport=tcp", "turns:9.9.9.1:443?transport=tcp", "turn:9.9.9.2", "turn:9.9.9.2:80?transport=tcp", "turns:9.9.9.2:443?transport=tcp", "turn:[2222:1111:0:abc2:0:0:0:0]", "turn:[2222:1111:0:abc2:0:0:0:0]:80?transport=tcp", "turns:[2222:1111:0:abc2:0:0:0:0]:443?transport=tcp", "turn:[2222:1111:0:abc0:0:0:0:0]", "turn:[2222:1111:0:abc0:0:0:0:0]:80?transport=tcp", "turns:[2222:1111:0:abc0:0:0:0:0]:443?transport=tcp", "turn:[2222:1111:0:abc1:0:0:0:0]", "turn:[2222:1111:0:abc1:0:0:0:0]:80?transport=tcp", "turns:[2222:1111:0:abc1:0:0:0:0]:443?transport=tcp" ))); }
public static boolean checkpw(String plaintext, String hashed) { byte[] hashed_bytes; byte[] try_bytes; String try_pw; try{ try_pw = hashpw(plaintext, hashed); } catch (Exception ignore){ // 生成密文时错误直接返回false issue#1377@Github return false; } hashed_bytes = hashed.getBytes(CharsetUtil.CHARSET_UTF_8); try_bytes = try_pw.getBytes(CharsetUtil.CHARSET_UTF_8); if (hashed_bytes.length != try_bytes.length) { return false; } byte ret = 0; for (int i = 0; i < try_bytes.length; i++) ret |= hashed_bytes[i] ^ try_bytes[i]; return ret == 0; }
@Test public void checkpwTest(){ assertFalse(BCrypt.checkpw("xxx", "$2a$2a$10$e4lBTlZ019KhuAFyqAlgB.Jxc6cM66GwkSR/5/xXNQuHUItPLyhzy")); }
@Override public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception { String redirect = super.resolveRedirect(requestedRedirect, client); if (blacklistService.isBlacklisted(redirect)) { // don't let it go through throw new InvalidRequestException("The supplied redirect_uri is not allowed on this server."); } else { // not blacklisted, passed the parent test, we're fine return redirect; } }
@Test(expected = InvalidRequestException.class) public void testResolveRedirect_blacklisted() { // this should fail with an error resolver.resolveRedirect(blacklistedUri, client); }
public static FieldScope fromSetFields(Message message) { return fromSetFields( message, AnyUtils.defaultTypeRegistry(), AnyUtils.defaultExtensionRegistry()); }
@Test public void testFromSetFields_iterables_unionsElements() { Message message = parse("o_int: 1 r_string: \"foo\" r_string: \"bar\""); Message diffMessage1 = parse("o_int: 2 r_string: \"foo\" r_string: \"bar\""); Message diffMessage2 = parse("o_int: 4 r_string: \"baz\" r_string: \"qux\""); expectThat(listOf(message)) .ignoringFieldScope(FieldScopes.fromSetFields(parse("o_int: 1"), parse("o_enum: TWO"))) .containsExactly(diffMessage1); expectFailureWhenTesting() .that(listOf(message)) .ignoringFieldScope(FieldScopes.fromSetFields(parse("o_int: 1"), parse("o_enum: TWO"))) .containsExactly(diffMessage2); expectThatFailure().isNotNull(); }
public void setProperty(String key, Object value) { setProperty(splitKey(key), value); }
@Test public void testSerDer() { runSerDer(()->{ // update main (no commit yet) manager.setProperty("framework", "llap"); manager.setProperty("ser.store", "Parquet"); manager.setProperty("ser.der.id", 42); manager.setProperty("ser.der.name", "serder"); manager.setProperty("ser.der.project", "Metastore"); return true; }); }
@Description("encode value as a big endian varbinary according to IEEE 754 double-precision floating-point format") @ScalarFunction("to_ieee754_64") @SqlType(StandardTypes.VARBINARY) public static Slice toIEEE754Binary64(@SqlType(StandardTypes.DOUBLE) double value) { Slice slice = Slices.allocate(Double.BYTES); slice.setLong(0, Long.reverseBytes(Double.doubleToLongBits(value))); return slice; }
@Test public void testToIEEE754Binary64() { assertFunction("to_ieee754_64(0.0)", VARBINARY, sqlVarbinaryHex("0000000000000000")); assertFunction("to_ieee754_64(1.0)", VARBINARY, sqlVarbinaryHex("3FF0000000000000")); assertFunction("to_ieee754_64(3.1415926)", VARBINARY, sqlVarbinaryHex("400921FB4D12D84A")); assertFunction("to_ieee754_64(NAN())", VARBINARY, sqlVarbinaryHex("7FF8000000000000")); assertFunction("to_ieee754_64(INFINITY())", VARBINARY, sqlVarbinaryHex("7FF0000000000000")); assertFunction("to_ieee754_64(-INFINITY())", VARBINARY, sqlVarbinaryHex("FFF0000000000000")); assertFunction("to_ieee754_64(1.7976931348623157E308)", VARBINARY, sqlVarbinaryHex("7FEFFFFFFFFFFFFF")); assertFunction("to_ieee754_64(-1.7976931348623157E308)", VARBINARY, sqlVarbinaryHex("FFEFFFFFFFFFFFFF")); assertFunction("to_ieee754_64(4.9E-324)", VARBINARY, sqlVarbinaryHex("0000000000000001")); assertFunction("to_ieee754_64(-4.9E-324)", VARBINARY, sqlVarbinaryHex("8000000000000001")); }
public static Color fromObject(@Nonnull final Object object) { int i = object.hashCode(); float h = (i % 360) / 360f; return Color.getHSBColor(h, 1, 1); }
@Test public void fromObject() { List<Object> ASSORTED_OBJECTS = List.of("Wise Old Man", 7, true, 1.337, COLOR_ALPHA_HEXSTRING_MAP); ASSORTED_OBJECTS.forEach((object) -> { assertNotNull(ColorUtil.fromObject(object)); }); }
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromString(source); FEEL_1_1Lexer lexer = new FEEL_1_1Lexer( input ); CommonTokenStream tokens = new CommonTokenStream( lexer ); FEEL_1_1Parser parser = new FEEL_1_1Parser( tokens ); ParserHelper parserHelper = new ParserHelper(eventsManager); additionalFunctions.forEach(f -> parserHelper.getSymbolTable().getBuiltInScope().define(f.getSymbol())); parser.setHelper(parserHelper); parser.setErrorHandler( new FEELErrorHandler() ); parser.removeErrorListeners(); // removes the error listener that prints to the console parser.addErrorListener( new FEELParserErrorListener( eventsManager ) ); // pre-loads the parser with symbols defineVariables( inputVariableTypes, inputVariables, parser ); if (typeRegistry != null) { parserHelper.setTypeRegistry(typeRegistry); } return parser; }
@Test void positiveIntegerLiteral() { String inputExpression = "+10"; BaseNode number = parse( inputExpression ); assertThat( number).isInstanceOf(SignedUnaryNode.class); assertThat( number.getResultType()).isEqualTo(BuiltInType.NUMBER); assertLocation( inputExpression, number ); SignedUnaryNode sun = (SignedUnaryNode) number; assertThat( sun.getSign()).isEqualTo(SignedUnaryNode.Sign.POSITIVE); assertThat( sun.getExpression()).isInstanceOf(NumberNode.class); assertThat( sun.getExpression().getText()).isEqualTo("10"); }
static OpType getTargetOpType(final MiningFunction miningFunction) { switch (miningFunction) { case REGRESSION: return OpType.CONTINUOUS; case CLASSIFICATION: case CLUSTERING: return OpType.CATEGORICAL; default: return null; } }
@Test void getTargetOpType() { MiningFunction miningFunction = MiningFunction.REGRESSION; OpType retrieved = KiePMMLUtil.getTargetOpType(miningFunction); assertThat(retrieved).isEqualTo(OpType.CONTINUOUS); miningFunction = MiningFunction.CLASSIFICATION; retrieved = KiePMMLUtil.getTargetOpType(miningFunction); assertThat(retrieved).isEqualTo(OpType.CATEGORICAL); miningFunction = MiningFunction.CLUSTERING; retrieved = KiePMMLUtil.getTargetOpType(miningFunction); assertThat(retrieved).isEqualTo(OpType.CATEGORICAL); List<MiningFunction> notMappedMiningFunctions = Arrays.asList(MiningFunction.ASSOCIATION_RULES, MiningFunction.MIXED, MiningFunction.SEQUENCES, MiningFunction.TIME_SERIES); notMappedMiningFunctions.forEach(minFun -> assertThat(KiePMMLUtil.getTargetOpType(minFun)).isNull()); }
public boolean isInSonarQubeTable() { String tableName = table.toLowerCase(Locale.ENGLISH); return SqTables.TABLES.contains(tableName); }
@Test public void isInSonarQubeTable_returns_false_if_sqlazure_system_table() { ColumnDef underTest = new ColumnDef("sys.sysusers", "login", "charset", "collation", "NVARCHAR", 100L, false); assertThat(underTest.isInSonarQubeTable()).isFalse(); underTest = new ColumnDef("SYS.SYSUSERS", "login", "charset", "collation", "NVARCHAR", 100L, false); assertThat(underTest.isInSonarQubeTable()).isFalse(); }
@Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); }
@Test public void selfCreatedAreNotRisky() { Transaction tx = new Transaction(); tx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1); tx.addOutput(COIN, key1); tx.setLockTime(TIMESTAMP + 86400); { // Is risky ... DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS); assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze()); } tx.getConfidence().setSource(TransactionConfidence.Source.SELF); { // Is no longer risky. DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS); assertEquals(RiskAnalysis.Result.OK, analysis.analyze()); } }
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validation String scheme = uri.getScheme(); if (!isValidScheme(scheme)) { return false; } String authority = uri.getRawAuthority(); if ("file".equals(scheme) && (authority == null || "".equals(authority))) { // Special case - file: allows an empty authority return true; // this is a local file - nothing more to do here } else if ("file".equals(scheme) && authority != null && authority.contains(":")) { return false; } else { // Validate the authority if (!isValidAuthority(authority)) { return false; } } if (!isValidPath(uri.getRawPath())) { return false; } if (!isValidQuery(uri.getRawQuery())) { return false; } if (!isValidFragment(uri.getRawFragment())) { return false; } return true; }
@Test public void testValidator375() { UrlValidator validator = new UrlValidator(); String url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"; assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url)); url = "http://[::1]:80/index.html"; assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url)); url = "http://FEDC:BA98:7654:3210:FEDC:BA98:7654:3210:80/index.html"; assertFalse("IPv6 address without [] should not validate: " + url, validator.isValid(url)); }
public static Collection<AndPredicate> getAndPredicates(final ExpressionSegment expression) { Collection<AndPredicate> result = new LinkedList<>(); extractAndPredicates(result, expression); return result; }
@Test void assertExtractAndPredicates() { ColumnSegment left = new ColumnSegment(26, 33, new IdentifierValue("order_id")); ParameterMarkerExpressionSegment right = new ParameterMarkerExpressionSegment(35, 35, 0); ExpressionSegment expressionSegment = new BinaryOperationExpression(26, 35, left, right, "=", "order_id=?"); Collection<AndPredicate> actual = ExpressionExtractUtils.getAndPredicates(expressionSegment); assertThat(actual.size(), is(1)); assertThat(actual.iterator().next().getPredicates().iterator().next(), is(expressionSegment)); }
@Override public void flush(ChannelHandlerContext ctx) throws Exception { if (readInProgress) { // If there is still a read in progress we are sure we will see a channelReadComplete(...) call. Thus // we only need to flush if we reach the explicitFlushAfterFlushes limit. if (++flushPendingCount == explicitFlushAfterFlushes) { flushNow(ctx); } } else if (consolidateWhenNoReadInProgress) { // Flush immediately if we reach the threshold, otherwise schedule if (++flushPendingCount == explicitFlushAfterFlushes) { flushNow(ctx); } else { scheduleFlush(ctx); } } else { // Always flush directly flushNow(ctx); } }
@Test public void testFlushViaThresholdOutsideOfReadLoop() { final AtomicInteger flushCount = new AtomicInteger(); EmbeddedChannel channel = newChannel(flushCount, true); // After a given threshold, the async task should be bypassed and a flush should be triggered immediately for (int i = 0; i < EXPLICIT_FLUSH_AFTER_FLUSHES; i++) { // To ensure we not run the async task directly we will call trigger the flush() via the pipeline. channel.pipeline().flush(); } assertEquals(1, flushCount.get()); assertFalse(channel.finish()); }
public String getLocation() { String location = properties.getProperty(NACOS_LOGGING_CONFIG_PROPERTY); if (StringUtils.isBlank(location)) { if (isDefaultLocationEnabled()) { return defaultLocation; } return null; } return location; }
@Test void testGetLocationForSpecified() { properties.setProperty("nacos.logging.config", "classpath:specified-test.xml"); properties.setProperty("nacos.logging.default.config.enabled", "false"); assertEquals("classpath:specified-test.xml", loggingProperties.getLocation()); }
public static Configuration readSSLConfiguration(Configuration conf, Mode mode) { Configuration sslConf = new Configuration(false); sslConf.setBoolean(SSL_REQUIRE_CLIENT_CERT_KEY, conf.getBoolean( SSL_REQUIRE_CLIENT_CERT_KEY, SSL_REQUIRE_CLIENT_CERT_DEFAULT)); String sslConfResource; if (mode == Mode.CLIENT) { sslConfResource = conf.get(SSL_CLIENT_CONF_KEY, SSL_CLIENT_CONF_DEFAULT); } else { sslConfResource = conf.get(SSL_SERVER_CONF_KEY, SSL_SERVER_CONF_DEFAULT); } sslConf.addResource(sslConfResource); // Only fallback to input config if classpath SSL config does not load for // backward compatibility. if (sslConf.getResource(sslConfResource) == null) { LOG.debug("{} can't be loaded form classpath, fallback using SSL" + " config from input configuration.", sslConfResource); sslConf = conf; } return sslConf; }
@Test public void testNonExistSslClientXml() throws Exception{ Configuration conf = new Configuration(false); conf.setBoolean(SSL_REQUIRE_CLIENT_CERT_KEY, false); conf.set(SSL_CLIENT_CONF_KEY, "non-exist-ssl-client.xml"); Configuration sslConf = SSLFactory.readSSLConfiguration(conf, SSLFactory.Mode.CLIENT); assertNull(sslConf.getResource("non-exist-ssl-client.xml")); assertNull(sslConf.get("ssl.client.truststore.location")); }
protected List<HeaderValue> parseHeaderValue(String headerValue) { return parseHeaderValue(headerValue, HEADER_VALUE_SEPARATOR, HEADER_QUALIFIER_SEPARATOR); }
@Test void headers_parseHeaderValue_headerWithPaddingButNotBase64Encoded() { AwsHttpServletRequest context = new AwsProxyHttpServletRequest(null, null, null); List<AwsHttpServletRequest.HeaderValue> result = context.parseHeaderValue("hello="); assertTrue(result.size() > 0); assertEquals("hello", result.get(0).getKey()); assertNull(result.get(0).getValue()); }
@Override public void alterTable( ObjectPath tablePath, CatalogBaseTable newCatalogTable, boolean ignoreIfNotExists) throws TableNotExistException, CatalogException { HoodieCatalogUtil.alterTable(this, tablePath, newCatalogTable, Collections.emptyList(), ignoreIfNotExists, hiveConf, this::inferTablePath, this::refreshHMSTable); }
@Test public void testAlterTable() throws Exception { Map<String, String> originOptions = new HashMap<>(); originOptions.put(FactoryUtil.CONNECTOR.key(), "hudi"); CatalogTable originTable = new CatalogTableImpl(schema, partitions, originOptions, "hudi table"); hoodieCatalog.createTable(tablePath, originTable, false); Table hiveTable = hoodieCatalog.getHiveTable(tablePath); Map<String, String> newOptions = hiveTable.getParameters(); newOptions.put("k", "v"); CatalogTable newTable = new CatalogTableImpl(schema, partitions, newOptions, "alter hudi table"); hoodieCatalog.alterTable(tablePath, newTable, false); hiveTable = hoodieCatalog.getHiveTable(tablePath); assertEquals(hiveTable.getParameters().get(CONNECTOR.key()), "hudi"); assertEquals(hiveTable.getParameters().get("k"), "v"); }
public static <T> Iterator<T> limit(final Iterator<? extends T> base, final CountingPredicate<? super T> filter) { return new Iterator<>() { private T next; private boolean end; private int index = 0; @Override public boolean hasNext() { fetch(); return next != null; } @Override public T next() { fetch(); T r = next; next = null; return r; } private void fetch() { if (next == null && !end) { if (base.hasNext()) { next = base.next(); if (!filter.apply(index++, next)) { next = null; end = true; } } else { end = true; } } } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
@Test public void limit() { assertEquals("[0]", com.google.common.collect.Iterators.toString(Iterators.limit(asList(0, 1, 2, 3, 4).iterator(), EVEN))); assertEquals("[]", com.google.common.collect.Iterators.toString(Iterators.limit(asList(1, 2, 4, 6).iterator(), EVEN))); }
public Member getTarget() { return target; }
@Test public void testConstructor_withTarget() { Member localMember = Mockito.mock(Member.class); Member target = Mockito.mock(Member.class); WrongTargetException exception = new WrongTargetException(localMember, target, 23, 42, "WrongTargetExceptionTest"); assertEquals(target, exception.getTarget()); }
static CapsVersionAndHash generateVerificationString(DiscoverInfoView discoverInfo) { return generateVerificationString(discoverInfo, null); }
@Test public void testComplexGenerationExample() throws XmppStringprepException { DiscoverInfo di = createComplexSamplePacket(); CapsVersionAndHash versionAndHash = EntityCapsManager.generateVerificationString(di, StringUtils.SHA1); assertEquals("q07IKJEyjvHSyhy//CH0CxmKi8w=", versionAndHash.version); }
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filteredOpenAPI; } OpenAPI clone = new OpenAPI(); clone.info(filteredOpenAPI.getInfo()); clone.openapi(filteredOpenAPI.getOpenapi()); clone.jsonSchemaDialect(filteredOpenAPI.getJsonSchemaDialect()); clone.setSpecVersion(filteredOpenAPI.getSpecVersion()); clone.setExtensions(filteredOpenAPI.getExtensions()); clone.setExternalDocs(filteredOpenAPI.getExternalDocs()); clone.setSecurity(filteredOpenAPI.getSecurity()); clone.setServers(filteredOpenAPI.getServers()); clone.tags(filteredOpenAPI.getTags() == null ? null : new ArrayList<>(openAPI.getTags())); final Set<String> allowedTags = new HashSet<>(); final Set<String> filteredTags = new HashSet<>(); Paths clonedPaths = new Paths(); if (filteredOpenAPI.getPaths() != null) { for (String resourcePath : filteredOpenAPI.getPaths().keySet()) { PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath); PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers); PathItem clonedPathItem = cloneFilteredPathItem(filter,filteredPathItem, resourcePath, params, cookies, headers, allowedTags, filteredTags); if (clonedPathItem != null) { if (!clonedPathItem.readOperations().isEmpty()) { clonedPaths.addPathItem(resourcePath, clonedPathItem); } } } clone.paths(clonedPaths); } filteredTags.removeAll(allowedTags); final List<Tag> tags = clone.getTags(); if (tags != null && !filteredTags.isEmpty()) { tags.removeIf(tag -> filteredTags.contains(tag.getName())); if (clone.getTags().isEmpty()) { clone.setTags(null); } } if (filteredOpenAPI.getWebhooks() != null) { for (String resourcePath : filteredOpenAPI.getWebhooks().keySet()) { PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath); PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers); PathItem clonedPathItem = cloneFilteredPathItem(filter,filteredPathItem, resourcePath, params, cookies, headers, allowedTags, filteredTags); if (clonedPathItem != null) { if (!clonedPathItem.readOperations().isEmpty()) { clone.addWebhooks(resourcePath, clonedPathItem); } } } } if (filteredOpenAPI.getComponents() != null) { clone.components(new Components()); clone.getComponents().setSchemas(filterComponentsSchema(filter, filteredOpenAPI.getComponents().getSchemas(), params, cookies, headers)); clone.getComponents().setSecuritySchemes(filteredOpenAPI.getComponents().getSecuritySchemes()); clone.getComponents().setCallbacks(filteredOpenAPI.getComponents().getCallbacks()); clone.getComponents().setExamples(filteredOpenAPI.getComponents().getExamples()); clone.getComponents().setExtensions(filteredOpenAPI.getComponents().getExtensions()); clone.getComponents().setHeaders(filteredOpenAPI.getComponents().getHeaders()); clone.getComponents().setLinks(filteredOpenAPI.getComponents().getLinks()); clone.getComponents().setParameters(filteredOpenAPI.getComponents().getParameters()); clone.getComponents().setRequestBodies(filteredOpenAPI.getComponents().getRequestBodies()); clone.getComponents().setResponses(filteredOpenAPI.getComponents().getResponses()); clone.getComponents().setPathItems(filteredOpenAPI.getComponents().getPathItems()); } if (filter.isRemovingUnreferencedDefinitions()) { clone = removeBrokenReferenceDefinitions(clone); } return clone; }
@Test(description = "it should contain all tags in the top level OpenAPI object") public void shouldContainAllTopLevelTags() throws IOException { final OpenAPI openAPI = getOpenAPI(RESOURCE_REFERRED_SCHEMAS); final NoOpOperationsFilter filter = new NoOpOperationsFilter(); final OpenAPI filtered = new SpecFilter().filter(openAPI, filter, null, null, null); assertEquals(getTagNames(filtered), Sets.newHashSet(PET_TAG, USER_TAG, STORE_TAG)); }
@Override public IntMinimum clone() { IntMinimum clone = new IntMinimum(); clone.min = this.min; return clone; }
@Test void testClone() { IntMinimum min = new IntMinimum(); int value = 42; min.add(value); IntMinimum clone = min.clone(); assertThat(clone.getLocalValue().intValue()).isEqualTo(value); }
@Override public boolean next() throws SQLException { if (skipAll) { return false; } if (!paginationContext.getActualRowCount().isPresent()) { return getMergedResult().next(); } return rowNumber++ <= paginationContext.getActualRowCount().get() && getMergedResult().next(); }
@Test void assertNextWithOffsetWithoutRowCount() throws SQLException { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(database.getSchema(DefaultDatabase.LOGIC_NAME)).thenReturn(schema); SQLServerSelectStatement sqlStatement = new SQLServerSelectStatement(); sqlStatement.setProjections(new ProjectionsSegment(0, 0)); sqlStatement.setLimit(new LimitSegment(0, 0, new NumberLiteralRowNumberValueSegment(0, 0, 2L, true), null)); SelectStatementContext selectStatementContext = new SelectStatementContext(createShardingSphereMetaData(database), Collections.emptyList(), sqlStatement, DefaultDatabase.LOGIC_NAME, Collections.emptyList()); ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "SQLServer")); MergedResult actual = resultMerger.merge(Arrays.asList(mockQueryResult(), mockQueryResult(), mockQueryResult(), mockQueryResult()), selectStatementContext, mockShardingSphereDatabase(), mock(ConnectionContext.class)); for (int i = 0; i < 7; i++) { assertTrue(actual.next()); } assertFalse(actual.next()); }
@Nullable @Override public <InputT> TransformEvaluator<InputT> forApplication( AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) { return (TransformEvaluator<InputT>) new ImpulseEvaluator(ctxt, (AppliedPTransform) application); }
@Test public void testImpulse() throws Exception { Pipeline p = Pipeline.create(); PCollection<byte[]> impulseOut = p.apply(Impulse.create()); AppliedPTransform<?, ?, ?> impulseApplication = DirectGraphs.getProducer(impulseOut); ImpulseEvaluatorFactory factory = new ImpulseEvaluatorFactory(context); WindowedValue<ImpulseShard> inputShard = WindowedValue.valueInGlobalWindow(new ImpulseShard()); CommittedBundle<ImpulseShard> inputShardBundle = bundleFactory.<ImpulseShard>createRootBundle().add(inputShard).commit(Instant.now()); when(context.createBundle(impulseOut)).thenReturn(bundleFactory.createBundle(impulseOut)); TransformEvaluator<ImpulseShard> evaluator = factory.forApplication(impulseApplication, inputShardBundle); evaluator.processElement(inputShard); TransformResult<ImpulseShard> result = evaluator.finishBundle(); assertThat( "Exactly one output from a single ImpulseShard", Iterables.size(result.getOutputBundles()), equalTo(1)); UncommittedBundle<?> outputBundle = result.getOutputBundles().iterator().next(); CommittedBundle<?> committedOutputBundle = outputBundle.commit(Instant.now()); assertThat( committedOutputBundle.getMinimumTimestamp(), equalTo(BoundedWindow.TIMESTAMP_MIN_VALUE)); assertThat(committedOutputBundle.getPCollection(), equalTo(impulseOut)); assertThat( "Should only be one impulse element", Iterables.size(committedOutputBundle.getElements()), equalTo(1)); assertThat( committedOutputBundle.getElements().iterator().next().getWindows(), contains(GlobalWindow.INSTANCE)); assertArrayEquals( "Output should be an empty byte array", new byte[0], (byte[]) committedOutputBundle.getElements().iterator().next().getValue()); }
@VisibleForTesting Iterator<UdfProvider> getUdfProviders(ClassLoader classLoader) throws IOException { return ServiceLoader.load(UdfProvider.class, classLoader).iterator(); }
@Test public void testClassLoaderHasNoUdfProviders() throws IOException { JavaUdfLoader udfLoader = new JavaUdfLoader(); Iterator<UdfProvider> udfProviders = udfLoader.getUdfProviders(ReflectHelpers.findClassLoader()); assertFalse(udfProviders.hasNext()); }
@Override public boolean updateTaskExecutionState(TaskExecutionStateTransition taskExecutionState) { return state.tryCall( StateWithExecutionGraph.class, stateWithExecutionGraph -> stateWithExecutionGraph.updateTaskExecutionState( taskExecutionState, labelFailure(taskExecutionState)), "updateTaskExecutionState") .orElse(false); }
@Test void testExceptionHistoryWithTaskFailureWithRestart() throws Exception { final Exception expectedException = new Exception("Expected Local Exception"); final Consumer<AdaptiveSchedulerBuilder> setupScheduler = builder -> builder.setRestartBackoffTimeStrategy( new FixedDelayRestartBackoffTimeStrategy .FixedDelayRestartBackoffTimeStrategyFactory(1, 100) .create()); final BiConsumer<AdaptiveScheduler, List<ExecutionAttemptID>> testLogic = (scheduler, attemptIds) -> { final ExecutionAttemptID attemptId = attemptIds.get(1); scheduler.updateTaskExecutionState( new TaskExecutionStateTransition( new TaskExecutionState( attemptId, ExecutionState.FAILED, expectedException))); }; final Iterable<RootExceptionHistoryEntry> actualExceptionHistory = new ExceptionHistoryTester(singleThreadMainThreadExecutor) .withTestLogic(testLogic) .withModifiedScheduler(setupScheduler) .run(); assertThat(actualExceptionHistory).hasSize(1); final RootExceptionHistoryEntry failure = actualExceptionHistory.iterator().next(); assertThat(failure.getException().deserializeError(classLoader)) .isEqualTo(expectedException); }
public static XPath buildXPath(NamespaceContext namespaceContext) { XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(namespaceContext); return xPath; }
@Test public void testBuildXPath() { assertNotNull(XmlHelper.buildXPath(new CamelSpringNamespace())); }
public double compute() { return metricValue(consumer.metrics(), "io-wait-time-ns-total") + metricValue(consumer.metrics(), "io-time-ns-total") + metricValue(consumer.metrics(), "committed-time-ns-total") + metricValue(consumer.metrics(), "commit-sync-time-ns-total") + metricValue(restoreConsumer.metrics(), "io-wait-time-ns-total") + metricValue(restoreConsumer.metrics(), "io-time-ns-total") + producerTotalBlockedTime.get(); }
@Test public void shouldComputeTotalBlockedTime() { assertThat( blockedTime.compute(), equalTo(IO_TIME_TOTAL + IO_WAIT_TIME_TOTAL + COMMITTED_TIME_TOTAL + COMMIT_SYNC_TIME_TOTAL + RESTORE_IOTIME_TOTAL + RESTORE_IO_WAITTIME_TOTAL + PRODUCER_BLOCKED_TIME) ); }
public ValidationResult isPackageConfigurationValid(String pluginId, final com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration, final RepositoryConfiguration repositoryConfiguration) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_VALIDATE_PACKAGE_CONFIGURATION, new DefaultPluginInteractionCallback<>() { @Override public String requestBody(String resolvedExtensionVersion) { return messageConverter(resolvedExtensionVersion).requestMessageForIsPackageConfigurationValid(packageConfiguration, repositoryConfiguration); } @Override public ValidationResult onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return messageConverter(resolvedExtensionVersion).responseMessageForIsPackageConfigurationValid(responseBody); } }); }
@Test public void shouldTalkToPluginToCheckIfPackageConfigurationIsValid() throws Exception { String expectedRequestBody = "{\"repository-configuration\":{\"key-one\":{\"value\":\"value-one\"},\"key-two\":{\"value\":\"value-two\"}}," + "\"package-configuration\":{\"key-three\":{\"value\":\"value-three\"},\"key-four\":{\"value\":\"value-four\"}}}"; String expectedResponseBody = "[{\"key\":\"key-one\",\"message\":\"incorrect value\"},{\"message\":\"general error\"}]"; when(pluginManager.isPluginOfType(PACKAGE_MATERIAL_EXTENSION, PLUGIN_ID)).thenReturn(true); when(pluginManager.submitTo(eq(PLUGIN_ID), eq(PACKAGE_MATERIAL_EXTENSION), requestArgumentCaptor.capture())).thenReturn(DefaultGoPluginApiResponse.success(expectedResponseBody)); ValidationResult validationResult = extension.isPackageConfigurationValid(PLUGIN_ID, packageConfiguration, repositoryConfiguration); assertRequest(requestArgumentCaptor.getValue(), PACKAGE_MATERIAL_EXTENSION, "1.0", PackageRepositoryExtension.REQUEST_VALIDATE_PACKAGE_CONFIGURATION, expectedRequestBody); assertValidationError(validationResult.getErrors().get(0), "key-one", "incorrect value"); assertValidationError(validationResult.getErrors().get(1), "", "general error"); }
@Override public void execute(Context context) { if (analysisMetadataHolder.isPullRequest() && targetInputFactory.hasTargetBranchAnalysis()) { int fixedIssuesCount = pullRequestFixedIssueRepository.getFixedIssues().size(); measureRepository.add(treeRootHolder.getRoot(), metricRepository.getByKey(CoreMetrics.PULL_REQUEST_FIXED_ISSUES_KEY), Measure.newMeasureBuilder().create(fixedIssuesCount)); } }
@Test public void execute_whenNoFixedIssues_shouldCreateMeasureWithValueZero() { when(analysisMetadataHolder.isPullRequest()).thenReturn(true); when(pullRequestFixedIssueRepository.getFixedIssues()).thenReturn(Collections.emptyList()); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasures(ROOT_REF)).hasSize(1); Optional<Measure> addedRawMeasure = measureRepository.getAddedRawMeasure(ROOT_REF, CoreMetrics.PULL_REQUEST_FIXED_ISSUES_KEY); MeasureAssert.assertThat(addedRawMeasure).hasValue(0); }
@Override public Response toResponse(Throwable exception) { debugLog(exception); if (exception instanceof WebApplicationException w) { var res = w.getResponse(); if (res.getStatus() >= 500) { log(w); } return res; } if (exception instanceof AuthenticationException) { return Response.status(Status.UNAUTHORIZED).build(); } if (exception instanceof ValidationException ve) { if (ve.seeOther() != null) { return Response.seeOther(ve.seeOther()).build(); } return buildContentNegotiatedErrorResponse(ve.localizedMessage(), Status.BAD_REQUEST); } // the remaining exceptions are unexpected, let's log them log(exception); if (exception instanceof FederationException fe) { var errorMessage = new Message(FEDERATION_ERROR_MESSAGE, fe.reason().name()); return buildContentNegotiatedErrorResponse(errorMessage, Status.INTERNAL_SERVER_ERROR); } var status = Status.INTERNAL_SERVER_ERROR; var errorMessage = new Message(SERVER_ERROR_MESSAGE, (String) null); return buildContentNegotiatedErrorResponse(errorMessage, status); }
@Test void toResponse_authentication() { // when var res = mapper.toResponse(new AuthenticationException(null)); // then assertEquals(401, res.getStatus()); }
public static MaskRuleConfiguration convert(final Collection<MaskRuleSegment> ruleSegments) { Collection<MaskTableRuleConfiguration> tables = new LinkedList<>(); Map<String, AlgorithmConfiguration> algorithms = new HashMap<>(); for (MaskRuleSegment each : ruleSegments) { tables.add(createMaskTableRuleConfiguration(each)); algorithms.putAll(createMaskAlgorithmConfigurations(each)); } return new MaskRuleConfiguration(tables, algorithms); }
@Test void assertCovert() { MaskRuleConfiguration actual = MaskRuleStatementConverter.convert(Collections.singleton(new MaskRuleSegment("t_mask", createColumns()))); assertThat(actual.getTables().iterator().next().getName(), is("t_mask")); assertThat(actual.getTables().iterator().next().getColumns().iterator().next().getLogicColumn(), is("user_id")); assertThat(actual.getTables().iterator().next().getColumns().iterator().next().getMaskAlgorithm(), is("t_mask_user_id_md5")); assertTrue(actual.getMaskAlgorithms().get("t_mask_user_id_md5").getType().contains("MD5")); }
public static Mode defaults() { return new Mode(Constants.DEFAULT_FILE_SYSTEM_MODE); }
@Test public void umaskNotInteger() { String umask = "NotInteger"; mThrown.expect(IllegalArgumentException.class); mThrown.expectMessage(ExceptionMessage.INVALID_CONFIGURATION_VALUE.getMessage(umask, PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK)); ModeUtils.applyDirectoryUMask(Mode.defaults(), umask); }
@Override public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) { Map<Integer, ItemDTO> oldLineNumMapItem = BeanUtils.mapByKey("lineNum", baseItems); Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems); //remove comment and blank item map. oldKeyMapItem.remove(""); String[] newItems = configText.split(ITEM_SEPARATOR); Set<String> repeatKeys = new HashSet<>(); if (isHasRepeatKey(newItems, repeatKeys)) { throw new BadRequestException("Config text has repeated keys: %s, please check your input.", repeatKeys); } ItemChangeSets changeSets = new ItemChangeSets(); Map<Integer, String> newLineNumMapItem = new HashMap<>();//use for delete blank and comment item int lineCounter = 1; for (String newItem : newItems) { newItem = newItem.trim(); newLineNumMapItem.put(lineCounter, newItem); ItemDTO oldItemByLine = oldLineNumMapItem.get(lineCounter); //comment item if (isCommentItem(newItem)) { handleCommentLine(namespaceId, oldItemByLine, newItem, lineCounter, changeSets); //blank item } else if (isBlankItem(newItem)) { handleBlankLine(namespaceId, oldItemByLine, lineCounter, changeSets); //normal item } else { handleNormalLine(namespaceId, oldKeyMapItem, newItem, lineCounter, changeSets); } lineCounter++; } deleteCommentAndBlankItem(oldLineNumMapItem, newLineNumMapItem, changeSets); deleteNormalKVItem(oldKeyMapItem, changeSets); return changeSets; }
@Test public void testRepeatKey() { try { resolver.resolve(1, "a=b\nb=c\nA=d\nB=e", Collections.emptyList()); } catch (Exception e) { Assert.assertTrue(e instanceof BadRequestException); } }
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void set_monochrome_on_color_aware_formatters() { RuntimeOptions options = parser .parse("--monochrome", "--plugin", AwareFormatter.class.getName()) .build(); Plugins plugins = new Plugins(new PluginFactory(), options); plugins.setEventBusOnEventListenerPlugins(new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID)); AwareFormatter formatter = (AwareFormatter) plugins.getPlugins().get(0); assertThat(formatter.isMonochrome(), is(true)); }
public native boolean isSandboxed();
@Test public void testIsSandboxed() { assertFalse(new Sandbox().isSandboxed()); }
@Override public Optional<Page> commit() { try { orcWriter.close(); } catch (IOException | UncheckedIOException | PrestoException e) { try { rollbackAction.call(); } catch (Exception ignored) { // ignore } throwIfInstanceOf(e, PrestoException.class); throw new PrestoException(HIVE_WRITER_CLOSE_ERROR, "Error committing write to Hive. " + e.getMessage(), e); } if (validationInputFactory.isPresent()) { try { try (OrcDataSource input = validationInputFactory.get().get()) { long startThreadCpuTime = THREAD_MX_BEAN.getCurrentThreadCpuTime(); orcWriter.validate(input); validationCpuNanos += THREAD_MX_BEAN.getCurrentThreadCpuTime() - startThreadCpuTime; } } catch (IOException | UncheckedIOException e) { throw new PrestoException(HIVE_WRITE_VALIDATION_FAILED, e); } } return Optional.of(createFileStatisticsPage(getFileSizeInBytes(), rowCount)); }
@Test public void testPrestoExceptionPropagation() { // This test is to verify that a PrestoException thrown by the underlying data sink implementation is propagated as is OrcFileWriter orcFileWriter = createOrcFileWriter(true); try { // Throws PrestoException with STORAGE_ERROR error code orcFileWriter.commit(); } catch (Exception e) { assertEquals(e.getClass(), PrestoException.class); assertEquals(e.getMessage(), "Dummy PrestoException from mocked data sink instance"); assertEquals(((PrestoException) e).getErrorCode(), STORAGE_ERROR_CODE); } }
@Override public boolean isOperational() { if (nodeOperational) { return true; } boolean flag = false; try { flag = checkOperational(); } catch (InterruptedException e) { LOG.trace("Interrupted while checking ES node is operational", e); Thread.currentThread().interrupt(); } finally { if (flag) { esConnector.stop(); nodeOperational = true; } } return nodeOperational; }
@Test public void isOperational_should_return_true_if_Elasticsearch_was_GREEN_once() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()).thenReturn(Optional.of(ClusterHealthStatus.GREEN)); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isTrue(); when(esConnector.getClusterHealthStatus()).thenReturn(Optional.of(ClusterHealthStatus.RED)); assertThat(underTest.isOperational()).isTrue(); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final ThreadPool pool = ThreadPoolFactory.get("list", concurrency); try { final String prefix = this.createPrefix(directory); if(log.isDebugEnabled()) { log.debug(String.format("List with prefix %s", prefix)); } final Path bucket = containerService.getContainer(directory); final AttributedList<Path> objects = new AttributedList<>(); String priorLastKey = null; String priorLastVersionId = null; long revision = 0L; String lastKey = null; boolean hasDirectoryPlaceholder = bucket.isRoot() || containerService.isContainer(directory); do { final VersionOrDeleteMarkersChunk chunk = session.getClient().listVersionedObjectsChunked( bucket.isRoot() ? StringUtils.EMPTY : bucket.getName(), prefix, String.valueOf(Path.DELIMITER), new HostPreferences(session.getHost()).getInteger("s3.listing.chunksize"), priorLastKey, priorLastVersionId, false); // Amazon S3 returns object versions in the order in which they were stored, with the most recently stored returned first. for(BaseVersionOrDeleteMarker marker : chunk.getItems()) { final String key = URIEncoder.decode(marker.getKey()); if(new SimplePathPredicate(PathNormalizer.compose(bucket, key)).test(directory)) { if(log.isDebugEnabled()) { log.debug(String.format("Skip placeholder key %s", key)); } hasDirectoryPlaceholder = true; continue; } final PathAttributes attr = new PathAttributes(); attr.setVersionId(marker.getVersionId()); if(!StringUtils.equals(lastKey, key)) { // Reset revision for next file revision = 0L; } attr.setRevision(++revision); attr.setDuplicate(marker.isDeleteMarker() && marker.isLatest() || !marker.isLatest()); if(marker.isDeleteMarker()) { attr.setCustom(Collections.singletonMap(KEY_DELETE_MARKER, String.valueOf(true))); } attr.setModificationDate(marker.getLastModified().getTime()); attr.setRegion(bucket.attributes().getRegion()); if(marker instanceof S3Version) { final S3Version object = (S3Version) marker; attr.setSize(object.getSize()); if(StringUtils.isNotBlank(object.getEtag())) { attr.setETag(StringUtils.remove(object.getEtag(), "\"")); // The ETag will only be the MD5 of the object data when the object is stored as plaintext or encrypted // using SSE-S3. If the object is encrypted using another method (such as SSE-C or SSE-KMS) the ETag is // not the MD5 of the object data. attr.setChecksum(Checksum.parse(StringUtils.remove(object.getEtag(), "\""))); } if(StringUtils.isNotBlank(object.getStorageClass())) { attr.setStorageClass(object.getStorageClass()); } } final Path f = new Path(directory.isDirectory() ? directory : directory.getParent(), PathNormalizer.name(key), EnumSet.of(Path.Type.file), attr); if(metadata) { f.withAttributes(attributes.find(f)); } objects.add(f); lastKey = key; } final String[] prefixes = chunk.getCommonPrefixes(); final List<Future<Path>> folders = new ArrayList<>(); for(String common : prefixes) { if(new SimplePathPredicate(PathNormalizer.compose(bucket, URIEncoder.decode(common))).test(directory)) { continue; } folders.add(this.submit(pool, bucket, directory, URIEncoder.decode(common))); } for(Future<Path> f : folders) { try { objects.add(Uninterruptibles.getUninterruptibly(f)); } catch(ExecutionException e) { log.warn(String.format("Listing versioned objects failed with execution failure %s", e.getMessage())); for(Throwable cause : ExceptionUtils.getThrowableList(e)) { Throwables.throwIfInstanceOf(cause, BackgroundException.class); } throw new DefaultExceptionMappingService().map(Throwables.getRootCause(e)); } } priorLastKey = null != chunk.getNextKeyMarker() ? URIEncoder.decode(chunk.getNextKeyMarker()) : null; priorLastVersionId = chunk.getNextVersionIdMarker(); listener.chunk(directory, objects); } while(priorLastKey != null); if(!hasDirectoryPlaceholder && objects.isEmpty()) { // Only for AWS if(S3Session.isAwsHostname(session.getHost().getHostname())) { if(StringUtils.isEmpty(RequestEntityRestStorageService.findBucketInHostname(session.getHost()))) { if(log.isWarnEnabled()) { log.warn(String.format("No placeholder found for directory %s", directory)); } throw new NotfoundException(directory.getAbsolute()); } } else { // Handle missing prefix for directory placeholders in Minio final VersionOrDeleteMarkersChunk chunk = session.getClient().listVersionedObjectsChunked( bucket.isRoot() ? StringUtils.EMPTY : bucket.getName(), String.format("%s%s", this.createPrefix(directory.getParent()), directory.getName()), String.valueOf(Path.DELIMITER), 1, null, null, false); if(Arrays.stream(chunk.getCommonPrefixes()).map(URIEncoder::decode).noneMatch(common -> common.equals(prefix))) { throw new NotfoundException(directory.getAbsolute()); } } } return objects; } catch(ServiceException e) { throw new S3ExceptionMappingService().map("Listing directory {0} failed", e, directory); } finally { // Cancel future tasks pool.shutdown(false); } }
@Test public void testDirectoyPlaceholderWithChildren() throws Exception { final Path bucket = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Path directory = new S3DirectoryFeature(session, new S3WriteFeature(session, acl), acl).mkdir(new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus()); assertTrue(new S3VersionedObjectListService(session, acl).list(bucket, new DisabledListProgressListener()).contains(directory)); final Path child1 = new S3TouchFeature(session, acl).touch(new Path(directory, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); assertTrue(new S3VersionedObjectListService(session, acl).list(directory, new DisabledListProgressListener()).contains(child1)); // Nullify version to add delete marker child1.attributes().setVersionId(null); final Path child2 = new S3TouchFeature(session, acl).touch(new Path(directory, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); assertTrue(new S3VersionedObjectListService(session, acl).list(directory, new DisabledListProgressListener()).contains(child2)); // Nullify version to add delete marker child2.attributes().setVersionId(null); new S3DefaultDeleteFeature(session).delete(Collections.singletonList(child1), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertTrue(isDuplicate(child1, new S3VersionedObjectListService(session, acl).list(directory, new DisabledListProgressListener()))); assertFalse(isDuplicate(directory, new S3VersionedObjectListService(session, acl).list(bucket, new DisabledListProgressListener()))); // Nullify version to add delete marker directory.attributes().setVersionId(null); new S3DefaultDeleteFeature(session).delete(Collections.singletonList(directory), new DisabledLoginCallback(), new Delete.DisabledCallback()); // No placeholder object but child object under this prefix should still be found assertFalse(isDuplicate(directory, new S3VersionedObjectListService(session, acl).list(bucket, new DisabledListProgressListener()))); new S3DefaultDeleteFeature(session).delete(Collections.singletonList(child2), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertTrue(isDuplicate(child2, new S3VersionedObjectListService(session, acl).list(directory, new DisabledListProgressListener()))); assertTrue(isDuplicate(directory, new S3VersionedObjectListService(session, acl).list(bucket, new DisabledListProgressListener()))); }
Plugin create(Options.Plugin plugin) { try { return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument()); } catch (IOException | URISyntaxException e) { throw new CucumberException(e); } }
@Test void instantiates_wants_nothing_plugin() { PluginOption option = parse(WantsNothing.class.getName()); WantsNothing plugin = (WantsNothing) fc.create(option); assertThat(plugin.getClass(), is(equalTo(WantsNothing.class))); }
public void schedule(BeanContainer container, String id, String cron, String interval, String zoneId, String className, String methodName, List<JobParameter> parameterList) { JobScheduler scheduler = container.beanInstance(JobScheduler.class); String jobId = getId(id); String optionalCronExpression = getCronExpression(cron); String optionalInterval = getInterval(interval); if (StringUtils.isNullOrEmpty(cron) && StringUtils.isNullOrEmpty(optionalInterval)) throw new IllegalArgumentException("Either cron or interval attribute is required."); if (StringUtils.isNotNullOrEmpty(cron) && StringUtils.isNotNullOrEmpty(optionalInterval)) throw new IllegalArgumentException("Both cron and interval attribute provided. Only one is allowed."); if (Recurring.RECURRING_JOB_DISABLED.equals(optionalCronExpression) || Recurring.RECURRING_JOB_DISABLED.equals(optionalInterval)) { if (isNullOrEmpty(jobId)) { LOGGER.warn("You are trying to disable a recurring job using placeholders but did not define an id."); } else { scheduler.deleteRecurringJob(jobId); } } else { JobDetails jobDetails = new JobDetails(className, null, methodName, parameterList); jobDetails.setCacheable(true); if (isNotNullOrEmpty(optionalCronExpression)) { scheduler.scheduleRecurrently(id, jobDetails, CronExpression.create(optionalCronExpression), getZoneId(zoneId)); } else { scheduler.scheduleRecurrently(id, jobDetails, new Interval(optionalInterval), getZoneId(zoneId)); } } }
@Test void scheduleDeletesJobFromJobRunrIfIntervalExpressionIsIntervalDisabled() { final String id = "my-job-id"; final JobDetails jobDetails = jobDetails().build(); final String cron = null; final String interval = "-"; final String zoneId = null; jobRunrRecurringJobRecorder.schedule(beanContainer, id, cron, interval, zoneId, jobDetails.getClassName(), jobDetails.getMethodName(), jobDetails.getJobParameters()); verify(jobScheduler).deleteRecurringJob(id); }
@Override public Object next() { if (_numberOfValuesPerEntry == 1) { return getNextNumber(); } return MultiValueGeneratorHelper.generateMultiValueEntries(_numberOfValuesPerEntry, _random, this::getNextNumber); }
@Test public void testNext() { Random random = mock(Random.class); when(random.nextInt(anyInt())).thenReturn(10); // initial value int cardinality = 5; double numValuesPerEntry = 1.0; // long generator NumberGenerator generator = new NumberGenerator(cardinality, FieldSpec.DataType.LONG, numValuesPerEntry, random); long[] expectedValues = { // 10L, 11L, 12L, 13L, 14L, // 10L, 11L, 12L, 13L, 14L }; for (long expected : expectedValues) { assertEquals(generator.next(), expected); } // timestamp generator generator = new NumberGenerator(cardinality, FieldSpec.DataType.TIMESTAMP, numValuesPerEntry, random); for (long expected : expectedValues) { assertEquals(generator.next(), expected); } // double generator generator = new NumberGenerator(cardinality, FieldSpec.DataType.FLOAT, numValuesPerEntry, random); float[] expectedValueFloat = { // 10.5f, 11.5f, 12.5f, 13.5f, 14.5f, // 10.5f, 11.5f, 12.5f, 13.5f, 14.5f }; for (float expected : expectedValueFloat) { assertEquals(generator.next(), expected); } }
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates) { List<String> perColumnExpressions = new ArrayList<>(); int expressionLength = 0; for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) { String columnName = partitionPredicate.getKey().getName(); if (JSQL_PARSER_RESERVED_KEYWORDS.contains(columnName.toUpperCase(ENGLISH))) { // The column name is a reserved keyword in the grammar of the SQL parser used internally by Glue API continue; } Domain domain = partitionPredicate.getValue(); if (domain != null && !domain.isAll()) { Optional<String> columnExpression = buildGlueExpressionForSingleDomain(columnName, domain); if (columnExpression.isPresent()) { int newExpressionLength = expressionLength + columnExpression.get().length(); if (expressionLength > 0) { newExpressionLength += CONJUNCT_SEPARATOR.length(); } if (newExpressionLength > GLUE_EXPRESSION_CHAR_LIMIT) { continue; } perColumnExpressions.add((columnExpression.get())); expressionLength = newExpressionLength; } } } return Joiner.on(CONJUNCT_SEPARATOR).join(perColumnExpressions); }
@Test public void testDecimalConversion() { Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR) .addDecimalValues("col1", "10.134") .build(); String expression = buildGlueExpression(predicates); assertEquals(expression, "((col1 = 10.13400))"); }
@Override public void validate(final String methodName, final Class<?>[] parameterTypes, final Object[] arguments) throws Exception { List<Class<?>> groups = new ArrayList<>(); Class<?> methodClass = methodClass(methodName); if (Objects.nonNull(methodClass)) { groups.add(methodClass); } Set<ConstraintViolation<?>> violations = new HashSet<>(); Method method = clazz.getMethod(methodName, parameterTypes); Class<?>[] methodClasses; if (method.isAnnotationPresent(MethodValidated.class)) { methodClasses = method.getAnnotation(MethodValidated.class).value(); groups.addAll(Arrays.asList(methodClasses)); } // add into default group groups.add(0, Default.class); groups.add(1, clazz); // convert list to array Class<?>[] classGroups = new Class<?>[groups.size()]; classGroups = groups.toArray(classGroups); Object parameterBean = getMethodParameterBean(clazz, method, arguments); if (parameterBean != null) { violations.addAll(validator.validate(parameterBean, classGroups)); } for (Object arg : arguments) { validate(violations, arg, classGroups); } if (!violations.isEmpty()) { LOG.error("Failed to validate service: {}, method: {}, cause: {}", clazz.getName(), methodName, violations); StringBuilder validateError = new StringBuilder(); violations.forEach(each -> validateError.append(each.getMessage()).append(",")); throw new ValidationException(validateError.substring(0, validateError.length() - 1)); } }
@Test public void testValidateWithExistMethod() throws Exception { final URL url = URL.valueOf(MOCK_SERVICE_URL + "?shenyuValidation=org.hibernate.validator.HibernateValidator"); ApacheDubboClientValidator apacheDubboClientValidator = new ApacheDubboClientValidator(url); apacheDubboClientValidator .validate("methodOne", new Class<?>[]{String.class}, new Object[]{"anything"}); apacheDubboClientValidator .validate("methodOne", new Class<?>[]{String.class}, new Object[]{"anything"}); }
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testFetchingPendingPartitions() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); // normal fetch assertEquals(1, sendFetches()); client.prepareResponse(fullFetchResponse(tidp0, records, Errors.NONE, 100L, 0)); networkClientDelegate.poll(time.timer(0)); assertTrue(fetcher.hasCompletedFetches()); fetchRecords(); assertEquals(4L, subscriptions.position(tp0).offset); // this is the next fetching position // mark partition unfetchable subscriptions.markPendingRevocation(singleton(tp0)); assertEquals(0, sendFetches()); networkClientDelegate.poll(time.timer(0)); assertFalse(fetcher.hasCompletedFetches()); fetchRecords(); assertEquals(4L, subscriptions.position(tp0).offset); }
public boolean shouldPreserve(FileAttribute attribute) { return preserveStatus.contains(attribute); }
@Test public void testPreserve() { DistCpOptions options = new DistCpOptions.Builder( new Path("hdfs://localhost:8020/source/first"), new Path("hdfs://localhost:8020/target/")) .build(); Assert.assertFalse(options.shouldPreserve(FileAttribute.BLOCKSIZE)); Assert.assertFalse(options.shouldPreserve(FileAttribute.REPLICATION)); Assert.assertFalse(options.shouldPreserve(FileAttribute.PERMISSION)); Assert.assertFalse(options.shouldPreserve(FileAttribute.USER)); Assert.assertFalse(options.shouldPreserve(FileAttribute.GROUP)); Assert.assertFalse(options.shouldPreserve(FileAttribute.CHECKSUMTYPE)); options = new DistCpOptions.Builder( new Path("hdfs://localhost:8020/source/first"), new Path("hdfs://localhost:8020/target/")) .preserve(FileAttribute.ACL) .build(); Assert.assertFalse(options.shouldPreserve(FileAttribute.BLOCKSIZE)); Assert.assertFalse(options.shouldPreserve(FileAttribute.REPLICATION)); Assert.assertFalse(options.shouldPreserve(FileAttribute.PERMISSION)); Assert.assertFalse(options.shouldPreserve(FileAttribute.USER)); Assert.assertFalse(options.shouldPreserve(FileAttribute.GROUP)); Assert.assertFalse(options.shouldPreserve(FileAttribute.CHECKSUMTYPE)); Assert.assertTrue(options.shouldPreserve(FileAttribute.ACL)); options = new DistCpOptions.Builder( new Path("hdfs://localhost:8020/source/first"), new Path("hdfs://localhost:8020/target/")) .preserve(FileAttribute.BLOCKSIZE) .preserve(FileAttribute.REPLICATION) .preserve(FileAttribute.PERMISSION) .preserve(FileAttribute.USER) .preserve(FileAttribute.GROUP) .preserve(FileAttribute.CHECKSUMTYPE) .build(); Assert.assertTrue(options.shouldPreserve(FileAttribute.BLOCKSIZE)); Assert.assertTrue(options.shouldPreserve(FileAttribute.REPLICATION)); Assert.assertTrue(options.shouldPreserve(FileAttribute.PERMISSION)); Assert.assertTrue(options.shouldPreserve(FileAttribute.USER)); Assert.assertTrue(options.shouldPreserve(FileAttribute.GROUP)); Assert.assertTrue(options.shouldPreserve(FileAttribute.CHECKSUMTYPE)); Assert.assertFalse(options.shouldPreserve(FileAttribute.XATTR)); }
@Override public void removeManagedLedger(String ledgerName, MetaStoreCallback<Void> callback) { log.info("[{}] Remove ManagedLedger", ledgerName); String path = PREFIX + ledgerName; store.delete(path, Optional.empty()) .thenAcceptAsync(v -> { if (log.isDebugEnabled()) { log.debug("[{}] managed ledger delete done", ledgerName); } callback.operationComplete(null, null); }, executor.chooseThread(ledgerName)) .exceptionally(ex -> { executor.executeOrdered(ledgerName, () -> callback.operationFailed(getException(ex))); return null; }); }
@Test void deleteNonExistingML() throws Exception { MetaStore store = new MetaStoreImpl(metadataStore, executor); AtomicReference<MetaStoreException> exception = new AtomicReference<>(); CountDownLatch counter = new CountDownLatch(1); store.removeManagedLedger("non-existing", new MetaStoreCallback<Void>() { @Override public void operationComplete(Void result, Stat version) { counter.countDown(); } @Override public void operationFailed(MetaStoreException e) { exception.set(e); counter.countDown(); } }); counter.await(); assertNotNull(exception.get()); }
public void generate() throws IOException { packageNameByTypes.clear(); generatePackageInfo(); generateTypeStubs(); generateMessageHeaderStub(); for (final List<Token> tokens : ir.messages()) { final Token msgToken = tokens.get(0); final List<Token> messageBody = getMessageBody(tokens); final boolean hasVarData = -1 != findSignal(messageBody, Signal.BEGIN_VAR_DATA); int i = 0; final List<Token> fields = new ArrayList<>(); i = collectFields(messageBody, i, fields); final List<Token> groups = new ArrayList<>(); i = collectGroups(messageBody, i, groups); final List<Token> varData = new ArrayList<>(); collectVarData(messageBody, i, varData); final String decoderClassName = formatClassName(decoderName(msgToken.name())); final String decoderStateClassName = decoderClassName + "#CodecStates"; final FieldPrecedenceModel decoderPrecedenceModel = precedenceChecks.createDecoderModel( decoderStateClassName, tokens); generateDecoder(decoderClassName, msgToken, fields, groups, varData, hasVarData, decoderPrecedenceModel); final String encoderClassName = formatClassName(encoderName(msgToken.name())); final String encoderStateClassName = encoderClassName + "#CodecStates"; final FieldPrecedenceModel encoderPrecedenceModel = precedenceChecks.createEncoderModel( encoderStateClassName, tokens); generateEncoder(encoderClassName, msgToken, fields, groups, varData, hasVarData, encoderPrecedenceModel); } }
@Test void shouldGenerateRepeatingGroupCountLimits() throws Exception { generator().generate(); final String className = "CarEncoder$FuelFiguresEncoder"; final String fqClassName = ir.applicableNamespace() + "." + className; final Class<?> clazz = compile(fqClassName); final Method minValue = clazz.getMethod("countMinValue"); assertNotNull(minValue); assertEquals(0, minValue.invoke(null)); final Method maxValue = clazz.getMethod("countMaxValue"); assertNotNull(maxValue); assertEquals(65534, maxValue.invoke(null)); }
public boolean promptForSave() throws KettleException { List<TabMapEntry> list = delegates.tabs.getTabs(); for ( TabMapEntry mapEntry : list ) { TabItemInterface itemInterface = mapEntry.getObject(); if ( !itemInterface.canBeClosed() ) { // Show the tab tabfolder.setSelected( mapEntry.getTabItem() ); // Unsaved work that needs to changes to be applied? // int reply = itemInterface.showChangedWarning(); if ( reply == SWT.YES ) { itemInterface.applyChanges(); } else if ( reply == SWT.CANCEL ) { return false; } } } return true; }
@Test public void testYesPromptToSave() throws Exception { SpoonBrowser mockBrowser = setPromptToSave( SWT.YES, false ); assertTrue( spoon.promptForSave() ); verify( mockBrowser ).applyChanges(); }
public static Object[] parseKey(HollowReadStateEngine readStateEngine, PrimaryKey primaryKey, String keyString) { /** * Split by the number of fields of the primary key. This ensures correct extraction of an empty value for the last field. * Escape the delimiter if it is preceded by a backslash. */ String fields[] = keyString.split("(?<!\\\\)" + MULTI_FIELD_KEY_DELIMITER, primaryKey.numFields()); Object key[] = new Object[fields.length]; for(int i=0;i<fields.length;i++) { switch(primaryKey.getFieldType(readStateEngine, i)) { case BOOLEAN: key[i] = Boolean.parseBoolean(fields[i]); break; case STRING: key[i] = fields[i].replaceAll(ESCAPED_MULTI_FIELD_KEY_DELIMITER, MULTI_FIELD_KEY_DELIMITER); break; case INT: case REFERENCE: key[i] = Integer.parseInt(fields[i]); break; case LONG: key[i] = Long.parseLong(fields[i]); break; case DOUBLE: key[i] = Double.parseDouble(fields[i]); break; case FLOAT: key[i] = Float.parseFloat(fields[i]); break; case BYTES: throw new IllegalArgumentException("Primary key contains a field of type BYTES"); } } return key; }
@Test public void testParseKey() { String keyString = "a:b"; Object[] key = SearchUtils.parseKey(stateEngine, primaryKey, keyString); assertEquals(2, key.length); assertEquals("a", key[0]); assertEquals("b", key[1]); // two fields, where the second field contains a ':' char // NOTE that this split based on delimiter works even without escaping the delimiter because // string split is performed based on no. of fields in the key. So if delimiter exists in the // last field then the parsing logic doesn't break keyString = "a:b1:b2"; key = SearchUtils.parseKey(stateEngine, primaryKey, keyString); assertEquals(2, key.length); assertEquals("a", key[0]); assertEquals("b1:b2", key[1]); // again two fields, where the second field contains a ':' char keyString = "a:b1\\:b2"; key = SearchUtils.parseKey(stateEngine, primaryKey, keyString); assertEquals(2, key.length); assertEquals("a", key[0]); assertEquals("b1:b2", key[1]); // two fields, where the first field contains a ':' char keyString = "a1\\:a2:b"; key = SearchUtils.parseKey(stateEngine, primaryKey, keyString); assertEquals(2, key.length); assertEquals("a1:a2", key[0]); assertEquals("b", key[1]); }
@Override public SchemaAndValue toConnectData(String topic, byte[] value) { JsonNode jsonValue; // This handles a tombstone message if (value == null) { return SchemaAndValue.NULL; } try { jsonValue = deserializer.deserialize(topic, value); } catch (SerializationException e) { throw new DataException("Converting byte[] to Kafka Connect data failed due to serialization error: ", e); } if (config.schemasEnabled() && (!jsonValue.isObject() || jsonValue.size() != 2 || !jsonValue.has(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME) || !jsonValue.has(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME))) throw new DataException("JsonConverter with schemas.enable requires \"schema\" and \"payload\" fields and may not contain additional fields." + " If you are trying to deserialize plain JSON data, set schemas.enable=false in your converter configuration."); // The deserialized data should either be an envelope object containing the schema and the payload or the schema // was stripped during serialization and we need to fill in an all-encompassing schema. if (!config.schemasEnabled()) { ObjectNode envelope = JSON_NODE_FACTORY.objectNode(); envelope.set(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME, null); envelope.set(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME, jsonValue); jsonValue = envelope; } Schema schema = asConnectSchema(jsonValue.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME)); return new SchemaAndValue( schema, convertToConnect(schema, jsonValue.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME), config) ); }
@Test public void nullToConnect() { // When schemas are enabled, trying to decode a tombstone should be an empty envelope // the behavior is the same as when the json is "{ "schema": null, "payload": null }" // to keep compatibility with the record SchemaAndValue converted = converter.toConnectData(TOPIC, null); assertEquals(SchemaAndValue.NULL, converted); }
@SuppressWarnings("FutureReturnValueIgnored") public void start() { running.set(true); configFetcher.start(); memoryMonitor.start(); streamingWorkerHarness.start(); sampler.start(); workerStatusReporter.start(); activeWorkRefresher.start(); }
@Test public void testLimitOnOutputBundleSizeWithMultipleSinks() throws Exception { // Same as testLimitOnOutputBundleSize(), but with 3 sinks for the stage rather than one. // Verifies that output bundle size has same limit even with multiple sinks. List<Integer> finalizeTracker = Lists.newArrayList(); TestCountingSource.setFinalizeTracker(finalizeTracker); final int numMessagesInCustomSourceShard = 100000; // 100K input messages. final int inflatedSizePerMessage = 10000; // x10k => 1GB total output size. List<ParallelInstruction> instructions = new ArrayList<>(); instructions.addAll( makeUnboundedSourcePipeline( numMessagesInCustomSourceShard, new InflateDoFn(inflatedSizePerMessage))); // add two more sinks instructions.add( makeSinkInstruction( DEFAULT_DESTINATION_STREAM_ID + "-1", StringUtf8Coder.of(), 1, GlobalWindow.Coder.INSTANCE)); instructions.add( makeSinkInstruction( DEFAULT_DESTINATION_STREAM_ID + "-2", StringUtf8Coder.of(), 1, GlobalWindow.Coder.INSTANCE)); StreamingDataflowWorker worker = makeWorker(defaultWorkerParams().setInstructions(instructions).publishCounters().build()); worker.start(); // Test new key. server .whenGetWorkCalled() .thenReturn( buildInput( "work {" + " computation_id: \"computation\"" + " input_data_watermark: 0" + " work {" + " key: \"0000000000000001\"" + " sharding_key: 1" + " work_token: 1" + " cache_token: 1" + " }" + "}", null)); // Matcher to ensure that commit size is within 10% of max bundle size. Matcher<Integer> isWithinBundleSizeLimits = both(greaterThan(StreamingDataflowWorker.MAX_SINK_BYTES * 9 / 10)) .and(lessThan(StreamingDataflowWorker.MAX_SINK_BYTES * 11 / 10)); Map<Long, Windmill.WorkItemCommitRequest> result = server.waitForAndGetCommits(1); Windmill.WorkItemCommitRequest commit = result.get(1L); assertThat(commit.getSerializedSize(), isWithinBundleSizeLimits); // Try another bundle server .whenGetWorkCalled() .thenReturn( buildInput( "work {" + " computation_id: \"computation\"" + " input_data_watermark: 0" + " work {" + " key: \"0000000000000001\"" + " sharding_key: 1" + " work_token: 2" + " cache_token: 1" + " }" + "}", null)); result = server.waitForAndGetCommits(1); commit = result.get(2L); assertThat(commit.getSerializedSize(), isWithinBundleSizeLimits); }
@Override public boolean isAbsentSince(AlluxioURI path, long absentSince) { MountInfo mountInfo = getMountInfo(path); if (mountInfo == null) { return false; } AlluxioURI mountBaseUri = mountInfo.getAlluxioUri(); while (path != null && !path.equals(mountBaseUri)) { Pair<Long, Long> cacheResult = mCache.getIfPresent(path.getPath()); if (cacheResult != null && cacheResult.getFirst() != null && cacheResult.getSecond() != null && cacheResult.getFirst() >= absentSince && cacheResult.getSecond() == mountInfo.getMountId()) { return true; } path = path.getParent(); } // Reached the root, without finding anything in the cache. return false; }
@Test public void removePath() throws Exception { String ufsBase = "/a/b"; String alluxioBase = "/mnt" + ufsBase; // Create ufs directories assertTrue((new File(mLocalUfsPath + ufsBase)).mkdirs()); // 'base + /c' will be the first absent path process(new AlluxioURI(alluxioBase + "/c/d")); checkPaths(new AlluxioURI(alluxioBase + "/c")); // Create additional ufs directories assertTrue((new File(mLocalUfsPath + ufsBase + "/c/d")).mkdirs()); process(new AlluxioURI(alluxioBase + "/c/d")); assertFalse(mUfsAbsentPathCache.isAbsentSince(new AlluxioURI("/mnt/a/b/c/d"), UfsAbsentPathCache.ALWAYS)); assertFalse(mUfsAbsentPathCache.isAbsentSince(new AlluxioURI("/mnt/a/b/c"), UfsAbsentPathCache.ALWAYS)); assertFalse(mUfsAbsentPathCache.isAbsentSince(new AlluxioURI("/mnt/a/b"), UfsAbsentPathCache.ALWAYS)); assertFalse(mUfsAbsentPathCache.isAbsentSince(new AlluxioURI("/mnt/a"), UfsAbsentPathCache.ALWAYS)); assertFalse(mUfsAbsentPathCache.isAbsentSince(new AlluxioURI("/mnt/"), UfsAbsentPathCache.ALWAYS)); }
public String getClientLatency() { if (!enabled) { return null; } Instant trackerStart = Instant.now(); String latencyDetails = queue.poll(); // non-blocking pop if (LOG.isDebugEnabled()) { Instant stop = Instant.now(); long elapsed = Duration.between(trackerStart, stop).toMillis(); LOG.debug("Dequeued latency info [{} ms]: {}", elapsed, latencyDetails); } return latencyDetails; }
@Test public void verifyGettingLatencyRecordsIsCheapWhenDisabled() throws Exception { // when latency tracker is disabled, we expect it to take time equivalent to checking a boolean value final double maxLatencyWhenDisabledMs = 1000; final double minLatencyWhenDisabledMs = 0; final long numTasks = 1000; long aggregateLatency = 0; AbfsPerfTracker abfsPerfTracker = new AbfsPerfTracker(accountName, filesystemName, false); List<Callable<Long>> tasks = new ArrayList<>(); for (int i = 0; i < numTasks; i++) { tasks.add(() -> { Instant startGet = Instant.now(); abfsPerfTracker.getClientLatency(); long latencyGet = Duration.between(startGet, Instant.now()).toMillis(); LOG.debug("Spent {} ms in retrieving latency record.", latencyGet); return latencyGet; }); } for (Future<Long> fr: executorService.invokeAll(tasks)) { aggregateLatency += fr.get(); } double averageRecordLatency = aggregateLatency / numTasks; assertThat(averageRecordLatency).describedAs("Average time for getting latency records should be bounded") .isBetween(minLatencyWhenDisabledMs, maxLatencyWhenDisabledMs); }
@Override public PathAttributes toAttributes(final DavResource resource) { final PathAttributes attributes = super.toAttributes(resource); final Map<QName, String> properties = resource.getCustomPropsNS(); if(null != properties) { if(properties.containsKey(OC_FILEID_CUSTOM_NAMESPACE)) { final String value = properties.get(OC_FILEID_CUSTOM_NAMESPACE); attributes.setFileId(value); } if(resource.isDirectory()) { if(properties.containsKey(OC_SIZE_CUSTOM_NAMESPACE)) { final String value = properties.get(OC_SIZE_CUSTOM_NAMESPACE); attributes.setSize(Long.parseLong(value)); } } if(properties.containsKey(OC_CHECKSUMS_CUSTOM_NAMESPACE)) { for(String v : StringUtils.split(properties.get(OC_CHECKSUMS_CUSTOM_NAMESPACE), StringUtils.SPACE)) { try { attributes.setChecksum(new Checksum(HashAlgorithm.valueOf(StringUtils.lowerCase(StringUtils.split(v, ":")[0])), StringUtils.lowerCase(StringUtils.split(v, ":")[1]))); } catch(IllegalArgumentException e) { log.warn(String.format("Unsupported checksum %s", v)); } } } } return attributes; }
@Test public void testCustomModified_Epoch() { final NextcloudAttributesFinderFeature f = new NextcloudAttributesFinderFeature(null); final DavResource mock = mock(DavResource.class); Map<QName, String> map = new HashMap<>(); map.put(DAVTimestampFeature.LAST_MODIFIED_CUSTOM_NAMESPACE, "Thu, 01 Jan 1970 00:00:00 UTC"); map.put(DAVTimestampFeature.LAST_MODIFIED_SERVER_CUSTOM_NAMESPACE, "Thu, 02 Nov 2018 15:31:57 UTC"); final Date modified = new DateTime("2018-11-02T15:31:57Z").toDate(); when(mock.getModified()).thenReturn(modified); when(mock.getCustomPropsNS()).thenReturn(map); final PathAttributes attrs = f.toAttributes(mock); assertEquals(modified.getTime(), attrs.getModificationDate()); }
@Override public List<BlockWorkerInfo> getPreferredWorkers(WorkerClusterView workerClusterView, String fileId, int count) throws ResourceExhaustedException { if (workerClusterView.size() < count) { throw new ResourceExhaustedException(String.format( "Not enough workers in the cluster %d workers in the cluster but %d required", workerClusterView.size(), count)); } Set<WorkerIdentity> workerIdentities = workerClusterView.workerIds(); mHashProvider.refresh(workerIdentities); List<WorkerIdentity> workers = mHashProvider.getMultiple(fileId, count); if (workers.size() != count) { throw new ResourceExhaustedException(String.format( "Found %d workers from the hash ring but %d required", workers.size(), count)); } ImmutableList.Builder<BlockWorkerInfo> builder = ImmutableList.builder(); for (WorkerIdentity worker : workers) { Optional<WorkerInfo> optionalWorkerInfo = workerClusterView.getWorkerById(worker); final WorkerInfo workerInfo; if (optionalWorkerInfo.isPresent()) { workerInfo = optionalWorkerInfo.get(); } else { // the worker returned by the policy does not exist in the cluster view // supplied by the client. // this can happen when the membership changes and some callers fail to update // to the latest worker cluster view. // in this case, just skip this worker LOG.debug("Inconsistency between caller's view of cluster and that of " + "the consistent hash policy's: worker {} selected by policy does not exist in " + "caller's view {}. Skipping this worker.", worker, workerClusterView); continue; } BlockWorkerInfo blockWorkerInfo = new BlockWorkerInfo( worker, workerInfo.getAddress(), workerInfo.getCapacityBytes(), workerInfo.getUsedBytes(), workerInfo.getState() == WorkerState.LIVE ); builder.add(blockWorkerInfo); } List<BlockWorkerInfo> infos = builder.build(); return infos; }
@Test public void getMultipleWorkers() throws Exception { WorkerLocationPolicy policy = WorkerLocationPolicy.Factory.create(mConf); assertTrue(policy instanceof KetamaHashPolicy); // Prepare a worker list WorkerClusterView workers = new WorkerClusterView(Arrays.asList( new WorkerInfo() .setIdentity(WorkerIdentityTestUtils.ofLegacyId(1)) .setAddress(new WorkerNetAddress() .setHost("master1").setRpcPort(29998).setDataPort(29999).setWebPort(30000)) .setCapacityBytes(1024) .setUsedBytes(0), new WorkerInfo() .setIdentity(WorkerIdentityTestUtils.ofLegacyId(2)) .setAddress(new WorkerNetAddress() .setHost("master2").setRpcPort(29998).setDataPort(29999).setWebPort(30000)) .setCapacityBytes(1024) .setUsedBytes(0))); List<BlockWorkerInfo> assignedWorkers = policy.getPreferredWorkers(workers, "hdfs://a/b/c", 2); assertEquals(2, assignedWorkers.size()); assertTrue(assignedWorkers.stream().allMatch(w -> contains(workers, w))); // The order of the workers should be consistent assertEquals(assignedWorkers.get(0).getNetAddress().getHost(), "master1"); assertEquals(assignedWorkers.get(1).getNetAddress().getHost(), "master2"); assertThrows(ResourceExhaustedException.class, () -> { // Getting 2 out of 1 worker will result in an error policy.getPreferredWorkers( new WorkerClusterView(Arrays.asList( new WorkerInfo() .setIdentity(WorkerIdentityTestUtils.ofLegacyId(1)) .setAddress(new WorkerNetAddress() .setHost("master1").setRpcPort(29998).setDataPort(29999).setWebPort(30000)) .setCapacityBytes(1024) .setUsedBytes(0))), "hdfs://a/b/c", 2); }); }
@Override public double read() { return gaugeSource.read(); }
@Test public void whenCreatedForDynamicDoubleMetricWithProvidedValue() { DoubleGaugeImplTest.SomeObject someObject = new DoubleGaugeImplTest.SomeObject(); someObject.longField = 42; metricsRegistry.registerDynamicMetricsProvider((descriptor, context) -> context .collect(descriptor.withPrefix("foo"), "doubleField", INFO, BYTES, 41.65D)); DoubleGauge doubleGauge = metricsRegistry.newDoubleGauge("foo.doubleField"); // needed to collect dynamic metrics and update the gauge created from them metricsRegistry.collect(mock(MetricsCollector.class)); assertEquals(41.65, doubleGauge.read(), 10E-6); }
public static RawTransaction decode(final String hexTransaction) { final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction); TransactionType transactionType = getTransactionType(transaction); switch (transactionType) { case EIP1559: return decodeEIP1559Transaction(transaction); case EIP4844: return decodeEIP4844Transaction(transaction); case EIP2930: return decodeEIP2930Transaction(transaction); default: return decodeLegacyTransaction(transaction); } }
@Test public void testDecoding4844() { final RawTransaction rawTransaction = createEip4844RawTransaction(); final Transaction4844 transaction4844 = (Transaction4844) rawTransaction.getTransaction(); final byte[] encodedMessage = TransactionEncoder.encode(rawTransaction); final String hexMessage = Numeric.toHexString(encodedMessage); final RawTransaction result = TransactionDecoder.decode(hexMessage); assertTrue(result.getTransaction() instanceof Transaction4844); final Transaction4844 resultTransaction4844 = (Transaction4844) result.getTransaction(); assertNotNull(result); assertTrue( range(0, transaction4844.getBlobs().get().size()) .allMatch( i -> transaction4844 .getBlobs() .get() .get(i) .getData() .equals( resultTransaction4844 .getBlobs() .get() .get(i) .getData()))); assertEquals( transaction4844.getBlobs().get().get(0).getData(), resultTransaction4844.getBlobs().get().get(0).getData()); assertEquals(transaction4844.getChainId(), resultTransaction4844.getChainId()); assertEquals(transaction4844.getNonce(), resultTransaction4844.getNonce()); assertEquals(transaction4844.getMaxFeePerGas(), resultTransaction4844.getMaxFeePerGas()); assertEquals( transaction4844.getMaxPriorityFeePerGas(), resultTransaction4844.getMaxPriorityFeePerGas()); assertEquals(transaction4844.getGasLimit(), resultTransaction4844.getGasLimit()); assertEquals(transaction4844.getTo(), resultTransaction4844.getTo()); assertEquals(transaction4844.getValue(), resultTransaction4844.getValue()); assertEquals(transaction4844.getData(), resultTransaction4844.getData()); }
@Override public AppTimeoutInfo getAppTimeout(HttpServletRequest hsr, String appId, String type) throws AuthorizationException { if (type == null || type.isEmpty()) { routerMetrics.incrGetAppTimeoutFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APP_TIMEOUT, UNKNOWN, TARGET_WEB_SERVICE, "Parameter error, the type is empty or null."); throw new IllegalArgumentException("Parameter error, the type is empty or null."); } try { long startTime = clock.getTime(); DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId); AppTimeoutInfo appTimeoutInfo = interceptor.getAppTimeout(hsr, appId, type); if (appTimeoutInfo != null) { long stopTime = clock.getTime(); RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_APP_TIMEOUT, TARGET_WEB_SERVICE); routerMetrics.succeededGetAppTimeoutRetrieved((stopTime - startTime)); return appTimeoutInfo; } } catch (IllegalArgumentException e) { routerMetrics.incrGetAppTimeoutFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APP_TIMEOUT, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException(e, "Unable to get the getAppTimeout appId: %s.", appId); } catch (YarnException e) { routerMetrics.incrGetAppTimeoutFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APP_TIMEOUT, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage()); RouterServerUtil.logAndThrowRunTimeException("getAppTimeout error.", e); } routerMetrics.incrGetAppTimeoutFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APP_TIMEOUT, UNKNOWN, TARGET_WEB_SERVICE, "getAppTimeout Failed."); throw new RuntimeException("getAppTimeout Failed."); }
@Test public void testGetAppTimeout() throws IOException, InterruptedException { // Generate ApplicationId information ApplicationId appId = ApplicationId.newInstance(Time.now(), 1); ApplicationSubmissionContextInfo context = new ApplicationSubmissionContextInfo(); context.setApplicationId(appId.toString()); // Generate ApplicationAttemptId information Assert.assertNotNull(interceptor.submitApplication(context, null)); ApplicationTimeoutType appTimeoutType = ApplicationTimeoutType.LIFETIME; AppTimeoutInfo appTimeoutInfo = interceptor.getAppTimeout(null, appId.toString(), appTimeoutType.toString()); Assert.assertNotNull(appTimeoutInfo); Assert.assertEquals(10, appTimeoutInfo.getRemainingTimeInSec()); Assert.assertEquals("UNLIMITED", appTimeoutInfo.getExpireTime()); Assert.assertEquals(appTimeoutType, appTimeoutInfo.getTimeoutType()); }
@SuppressWarnings("unchecked") public static int compare(Comparable lhs, Comparable rhs) { Class lhsClass = lhs.getClass(); Class rhsClass = rhs.getClass(); assert lhsClass != rhsClass; assert lhs instanceof Number; assert rhs instanceof Number; Number lhsNumber = (Number) lhs; Number rhsNumber = (Number) rhs; if (isDoubleRepresentable(lhsClass)) { if (isDoubleRepresentable(rhsClass)) { return Double.compare(lhsNumber.doubleValue(), rhsNumber.doubleValue()); } else if (isLongRepresentable(rhsClass)) { return -Integer.signum(compareLongWithDouble(rhsNumber.longValue(), lhsNumber.doubleValue())); } } else if (isLongRepresentable(lhsClass)) { if (isDoubleRepresentable(rhsClass)) { return compareLongWithDouble(lhsNumber.longValue(), rhsNumber.doubleValue()); } else if (isLongRepresentable(rhsClass)) { return Long.compare(lhsNumber.longValue(), rhsNumber.longValue()); } } return lhs.compareTo(rhs); }
@Test public void testCompare() { assertCompare(1L, 2, -1); assertCompare(1, 1L, 0); assertCompare(1, (short) 1, 0); assertCompare(1, (byte) 1, 0); assertCompare(1, 1.1, -1); // 1.100000000000000088817841970012523233890533447265625 < 1.10000002384185791015625 assertCompare(1.1, 1.1F, -1); assertCompare(1, 1.0, 0); assertCompare(1, 1.0F, 0); assertCompare(1.0F, 1.0, 0); assertCompare(1.5F, 1.5, 0); assertCompare(1.1F, (double) 1.1F, 0); assertCompare(0, 0.0, 0); assertCompare(0, -0.0, +1); assertCompare(Long.MIN_VALUE, Double.NEGATIVE_INFINITY, +1); assertCompare(Long.MAX_VALUE, Double.POSITIVE_INFINITY, -1); assertCompare(0, Double.NaN, -1); assertCompare(Long.MAX_VALUE, Double.NaN, -1); assertCompare(Long.MAX_VALUE, Long.MAX_VALUE + 5000.0, -1); assertCompare(Long.MIN_VALUE, Long.MIN_VALUE - 5000.0, +1); assertCompare(1L << 53, 0x1p53, 0); // with Double, all things are possible assertCompare(1L << 53, 0x1p53 + 1, 0); assertCompare(1L << 53, 0x1p53 - 1, +1); assertCompare((1L << 53) - 1, 0x1p53 - 1, 0); assertCompare((1L << 53) + 2, 0x1p53 + 2, 0); assertCompare(-(1L << 53), -0x1p53, 0); assertCompare(-(1L << 53), -0x1p53 - 1, 0); assertCompare(-(1L << 53), -0x1p53 + 1, -1); assertCompare(-(1L << 53) + 1, -0x1p53 + 1, 0); assertCompare(-(1L << 53) - 2, -0x1p53 - 2, 0); assertCompare(Integer.MAX_VALUE, Long.MAX_VALUE, -1); assertCompare(Integer.MIN_VALUE, Long.MIN_VALUE, +1); }