focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@VisibleForTesting protected Path maybeDownloadJars(String sName, String className, String remoteFile, AuxServiceFile.TypeEnum type, Configuration conf) throws IOException { // load AuxiliaryService from remote classpath FileContext localLFS = getLocalFileContext(conf); // create NM aux-service dir in NM localdir if it does not exist. Path nmAuxDir = dirsHandler.getLocalPathForWrite("." + Path.SEPARATOR + NM_AUX_SERVICE_DIR); if (!localLFS.util().exists(nmAuxDir)) { try { localLFS.mkdir(nmAuxDir, NM_AUX_SERVICE_DIR_PERM, true); } catch (IOException ex) { throw new YarnRuntimeException("Fail to create dir:" + nmAuxDir.toString(), ex); } } Path src = new Path(remoteFile); FileContext remoteLFS = getRemoteFileContext(src.toUri(), conf); FileStatus scFileStatus = remoteLFS.getFileStatus(src); if (!scFileStatus.getOwner().equals( this.userUGI.getShortUserName())) { throw new YarnRuntimeException("The remote jarfile owner:" + scFileStatus.getOwner() + " is not the same as the NM user:" + this.userUGI.getShortUserName() + "."); } if ((scFileStatus.getPermission().toShort() & 0022) != 0) { throw new YarnRuntimeException("The remote jarfile should not " + "be writable by group or others. " + "The current Permission is " + scFileStatus.getPermission().toShort()); } Path downloadDest = new Path(nmAuxDir, className + "_" + scFileStatus.getModificationTime()); // check whether we need to re-download the jar // from remote directory Path targetDirPath = new Path(downloadDest, scFileStatus.getPath().getName()); FileStatus[] allSubDirs = localLFS.util().listStatus(nmAuxDir); for (FileStatus sub : allSubDirs) { if (sub.getPath().getName().equals(downloadDest.getName())) { return targetDirPath; } else { if (sub.getPath().getName().contains(className) && !sub.getPath().getName().endsWith(DEL_SUFFIX)) { Path delPath = new Path(sub.getPath().getParent(), sub.getPath().getName() + DEL_SUFFIX); localLFS.rename(sub.getPath(), delPath); LOG.info("delete old aux service jar dir:" + delPath.toString()); FileDeletionTask deletionTask = new FileDeletionTask( this.delService, null, delPath, null); this.delService.delete(deletionTask); } } } LocalResourceType srcType; if (type == AuxServiceFile.TypeEnum.STATIC) { srcType = LocalResourceType.FILE; } else if (type == AuxServiceFile.TypeEnum.ARCHIVE) { srcType = LocalResourceType.ARCHIVE; } else { throw new YarnRuntimeException( "Cannot unpack file of type " + type + " from remote-file-path:" + src + "for aux-service:" + ".\n"); } LocalResource scRsrc = LocalResource.newInstance( URL.fromURI(src.toUri()), srcType, LocalResourceVisibility.PRIVATE, scFileStatus.getLen(), scFileStatus.getModificationTime()); FSDownload download = new FSDownload(localLFS, null, conf, downloadDest, scRsrc, null); try { // don't need to convert downloaded path into a dir // since it's already a jar path. return download.call(); } catch (Exception ex) { throw new YarnRuntimeException( "Exception happend while downloading files " + "for aux-service:" + sName + " and remote-file-path:" + src + ".\n" + ex.getMessage()); } }
@Test (timeout = 15000) public void testReuseLocalizedAuxiliaryJar() throws Exception { File testJar = null; AuxServices aux = null; Configuration conf = new YarnConfiguration(); FileSystem fs = FileSystem.get(conf); String root = "target/LocalDir"; try { testJar = JarFinder.makeClassLoaderTestJar(this.getClass(), rootDir, "test-runjar.jar", 2048, ServiceB.class.getName(), LightService .class.getName()); Context mockContext = mock(Context.class); LocalDirsHandlerService mockDirsHandler = mock( LocalDirsHandlerService.class); Path rootAuxServiceDirPath = new Path(root, "nmAuxService"); when(mockDirsHandler.getLocalPathForWrite(anyString())).thenReturn( rootAuxServiceDirPath); when(mockContext.getLocalDirsHandler()).thenReturn(mockDirsHandler); aux = new AuxServices(MOCK_AUX_PATH_HANDLER, mockContext, MOCK_DEL_SERVICE); // First Time the jar gets localized Path path = aux.maybeDownloadJars("ServiceB", ServiceB.class.getName(), testJar.getAbsolutePath(), AuxServiceFile.TypeEnum.STATIC, conf); // Validate the path on reuse of localized jar path = aux.maybeDownloadJars("ServiceB", ServiceB.class.getName(), testJar.getAbsolutePath(), AuxServiceFile.TypeEnum.STATIC, conf); assertFalse("Failed to reuse the localized jar", path.toString().endsWith("/*")); } finally { if (testJar != null) { testJar.delete(); } if (fs.exists(new Path(root))) { fs.delete(new Path(root), true); } } }
@Override protected String query(final Path directory, final ListProgressListener listener) throws BackgroundException { // The contains operator only performs prefix matching for a name. return String.format("name contains '%s'", query); }
@Test public void testQuery() throws Exception { final DriveFileIdProvider fileid = new DriveFileIdProvider(session); final Path directory = new DriveDirectoryFeature(session, fileid).mkdir(new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus()); final String name = new AlphanumericRandomStringService().random(); final Drive.Files.Create insert = session.getClient().files().create(new File() .setName(name) .setParents(Collections.singletonList(fileid.getFileId(directory)))); final File execute = insert.execute(); execute.setVersion(1L); final Path file = new Path(directory, name, EnumSet.of(Path.Type.file), new DriveAttributesFinderFeature(session, fileid).toAttributes(execute)); { final Path subdirectory = new DriveDirectoryFeature(session, fileid).mkdir(new Path(directory, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus()); assertTrue(new DriveSearchListService(session, fileid, name).list(subdirectory, new DisabledListProgressListener()).isEmpty()); new DriveDeleteFeature(session, fileid).delete(Collections.singletonList(subdirectory), new DisabledPasswordCallback(), new Delete.DisabledCallback()); } { final AttributedList<Path> list = new DriveSearchListService(session, fileid, name).list(DriveHomeFinderService.MYDRIVE_FOLDER, new DisabledListProgressListener()); assertEquals(1, list.size()); assertEquals(file, list.get(0)); } { assertTrue(new DriveSearchListService(session, fileid, name).list(DriveHomeFinderService.SHARED_FOLDER_NAME, new DisabledListProgressListener()).isEmpty()); } { final AttributedList<Path> list = new DriveSearchListService(session, fileid, name).list(directory, new DisabledListProgressListener()); assertEquals(1, list.size()); assertEquals(file, list.get(0)); } new DriveDeleteFeature(session, fileid).delete(Arrays.asList(file, directory), new DisabledPasswordCallback(), new Delete.DisabledCallback()); }
public int getDeregisterSubClusterFailedRetrieved() { return numDeregisterSubClusterFailedRetrieved.value(); }
@Test public void testDeregisterSubClusterRetrievedFailed() { long totalBadBefore = metrics.getDeregisterSubClusterFailedRetrieved(); badSubCluster.getDeregisterSubClusterFailed(); Assert.assertEquals(totalBadBefore + 1, metrics.getDeregisterSubClusterFailedRetrieved()); }
@Override public short getTypeCode() { return MessageType.TYPE_SEATA_MERGE_RESULT; }
@Test public void getTypeCode() { MergeResultMessage mergeResultMessage = new MergeResultMessage(); assertThat(MessageType.TYPE_SEATA_MERGE_RESULT).isEqualTo(mergeResultMessage.getTypeCode()); }
public static String join(String delimiter, String wrap, Iterable<?> objs) { Iterator<?> iter = objs.iterator(); if (!iter.hasNext()) { return ""; } StringBuilder buffer = new StringBuilder(); buffer.append(wrap).append(iter.next()).append(wrap); while (iter.hasNext()) { buffer.append(delimiter).append(wrap).append(iter.next()).append(wrap); } return buffer.toString(); }
@Test public void testJoin() { ArrayList<String> strings = new ArrayList<String>(); strings.add("foo"); strings.add("bar"); strings.add("baz"); Assertions.assertEquals("foo,bar,baz", Utils.join(",", strings)); Assertions.assertEquals("", Utils.join(",", new ArrayList<String>())); }
public static FileCollection generatePathingJar(final Project project, final String taskName, final FileCollection classpath, boolean alwaysUsePathingJar) throws IOException { //There is a bug in the Scala nsc compiler that does not parse the dependencies of JARs in the JAR manifest //As such, we disable pathing for any libraries compiling docs for Scala resources if (!alwaysUsePathingJar && !classpath.filter(f -> f.getAbsolutePath().contains("restli-tools-scala")).isEmpty()) { LOG.info("Compiling Scala resource classes. Disabling pathing jar for " + taskName + " to avoid breaking Scala compilation"); return classpath; } //We extract the classpath from the target task here, in the configuration phase //Note that we don't invoke getFiles() here because that would trigger dependency resolution in configuration phase FileCollection filteredClasspath = classpath.filter(f -> !f.isDirectory()); File destinationDir = new File(project.getBuildDir(), taskName); destinationDir.mkdirs(); File pathingJarPath = new File(destinationDir, project.getName() + "-pathing.jar"); OutputStream pathingJar = new FileOutputStream(pathingJarPath); //Classpath manifest does not support directories and needs to contain relative paths String cp = ClasspathManifest.relativeClasspathManifest(destinationDir, filteredClasspath.getFiles()); //Create the JAR Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, cp); JarOutputStream jarOutputStream = new JarOutputStream(pathingJar, manifest); jarOutputStream.close(); return classpath.filter(File::isDirectory).plus(project.files(pathingJarPath)); }
@Test public void testDoesNotCreatePathingJar() throws IOException { //setup createTempDir(); Project project = ProjectBuilder.builder().withProjectDir(temp).build(); String taskName = "myTaskName"; project.getBuildDir().mkdir(); File tempFile = new File(project.getBuildDir(), "temp.class"); File restliTools = new File(project.getBuildDir(), "restli-tools-scala"); GFileUtils.touch(tempFile); GFileUtils.touch(restliTools); FileCollection files = project.files(tempFile, restliTools); //when File pathingJar = new File(project.getBuildDir(), taskName + '/' + project.getName() + "-pathing.jar"); PathingJarUtil.generatePathingJar(project, taskName, files, false); assertFalse(pathingJar.exists()); cleanupTempDir(); }
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public HistoryInfo get() { return getHistoryInfo(); }
@Test public void testInvalidAccept() throws JSONException, Exception { WebResource r = resource(); String responseStr = ""; try { responseStr = r.path("ws").path("v1").path("history") .accept(MediaType.TEXT_PLAIN).get(String.class); fail("should have thrown exception on invalid uri"); } catch (UniformInterfaceException ue) { ClientResponse response = ue.getResponse(); assertResponseStatusCode(Status.INTERNAL_SERVER_ERROR, response.getStatusInfo()); WebServicesTestUtils.checkStringMatch( "error string exists and shouldn't", "", responseStr); } }
public static long btcToSatoshi(BigDecimal coins) throws ArithmeticException { return coins.movePointRight(SMALLEST_UNIT_EXPONENT).longValueExact(); }
@Test(expected = ArithmeticException.class) public void testBtcToSatoshi_tooPrecise1() { btcToSatoshi(new BigDecimal("0.000000001")); // More than SMALLEST_UNIT_EXPONENT precision }
@Operation(summary = "queryList", description = "QUERY_QUEUE_LIST_NOTES") @GetMapping(value = "/list") @ResponseStatus(HttpStatus.OK) @ApiException(QUERY_QUEUE_LIST_ERROR) public Result<List<Queue>> queryList(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser) { List<Queue> queues = queueService.queryList(loginUser); return Result.success(queues); }
@Test public void testQueryList() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/queues/list") .header(SESSION_ID, sessionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); Assertions.assertNotNull(result); Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info("query list queue return result:{}", mvcResult.getResponse().getContentAsString()); }
public AMSimulator() { this.responseQueue = new LinkedBlockingQueue<>(); }
@Test public void testAMSimulator() throws Exception { // Register one app MockAMSimulator app = new MockAMSimulator(); String appId = "app1"; String queue = "default"; List<ContainerSimulator> containers = new ArrayList<>(); HashMap<ApplicationId, AMSimulator> map = new HashMap<>(); UserName mockUser = mock(UserName.class); when(mockUser.getValue()).thenReturn("user1"); AMDefinitionRumen amDef = AMDefinitionRumen.Builder.create() .withUser(mockUser) .withQueue(queue) .withJobId(appId) .withJobStartTime(0) .withJobFinishTime(1000000L) .withAmResource(SLSConfiguration.getAMContainerResource(conf)) .withTaskContainers(containers) .build(); app.init(amDef, rm, null, true, 0, 1000, map); app.firstStep(); verifySchedulerMetrics(appId); Assert.assertEquals(1, rm.getRMContext().getRMApps().size()); Assert.assertNotNull(rm.getRMContext().getRMApps().get(app.appId)); // Finish this app app.lastStep(); }
public SearchJob executeSync(String searchId, SearchUser searchUser, ExecutionState executionState) { return searchDomain.getForUser(searchId, searchUser) .map(s -> executeSync(s, searchUser, executionState)) .orElseThrow(() -> new NotFoundException("No search found with id <" + searchId + ">.")); }
@Test void appliesQueryStringDecoratorsOnSearchTypes() { final SearchUser searchUser = TestSearchUser.builder() .allowStream("foo") .build(); final SearchType searchType = MessageList.builder() .id("searchType1") .query(ElasticsearchQueryString.of("*")) .build(); final Search search = Search.builder() .queries(ImmutableSet.of( Query.builder() .query(ElasticsearchQueryString.of("*")) .searchTypes(Collections.singleton(searchType)) .build() )) .build(); final SearchJob searchJob = this.searchExecutor.executeSync(search, searchUser, ExecutionState.empty()); final Query query = searchJob.getSearch().queries().stream().findFirst() .orElseThrow(() -> new AssertionError("Search unexpectedly contains no queries.")); final SearchType resultingSearchType = query.searchTypes().stream().findFirst() .orElseThrow(() -> new AssertionError("Query unexpectedly contains no search types.")); assertThat(resultingSearchType.query()) .isPresent() .contains(ElasticsearchQueryString.of("decorated")); }
public void registerNodeHeartbeat(NodeStatus nodeStatus) { requireNonNull(nodeStatus, "nodeStatus is null"); InternalNodeState nodeState = nodeStatuses.get(nodeStatus.getNodeId()); if (nodeState == null) { nodeStatuses.put(nodeStatus.getNodeId(), new InternalNodeState(nodeStatus)); } else { nodeState.updateNodeStatus(nodeStatus); } }
@Test(timeOut = 20_000) public void testWorkerMemoryInfo() throws Exception { ResourceManagerClusterStateProvider provider = new ResourceManagerClusterStateProvider(new InMemoryNodeManager(), new SessionPropertyManager(), 10, Duration.valueOf("4s"), Duration.valueOf("8s"), Duration.valueOf("5s"), Duration.valueOf("0s"), Duration.valueOf("4s"), true, newSingleThreadScheduledExecutor()); assertWorkerMemoryInfo(provider, 0); provider.registerNodeHeartbeat(createNodeStatus("nodeId", GENERAL_POOL, createMemoryPoolInfo(100, 2, 1))); assertWorkerMemoryInfo(provider, 1); provider.registerNodeHeartbeat(createNodeStatus("nodeId2", GENERAL_POOL, createMemoryPoolInfo(200, 20, 10))); assertWorkerMemoryInfo(provider, 2); // Node expiration timeout was set as 4 seconds // Waiting for the expiration to cross the threshold + adding buffer to avoid flakiness Thread.sleep(SECONDS.toMillis(10)); assertWorkerMemoryInfo(provider, 0); }
@SuppressWarnings("unchecked") @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { if (!(statement.getStatement() instanceof CreateSource) && !(statement.getStatement() instanceof CreateAsSelect)) { return statement; } try { if (statement.getStatement() instanceof CreateSource) { final ConfiguredStatement<CreateSource> createStatement = (ConfiguredStatement<CreateSource>) statement; return (ConfiguredStatement<T>) forCreateStatement(createStatement).orElse(createStatement); } else { final ConfiguredStatement<CreateAsSelect> createStatement = (ConfiguredStatement<CreateAsSelect>) statement; return (ConfiguredStatement<T>) forCreateAsStatement(createStatement).orElse( createStatement); } } catch (final KsqlStatementException e) { throw e; } catch (final KsqlException e) { throw new KsqlStatementException( ErrorMessageUtil.buildErrorMessage(e), statement.getMaskedStatementText(), e.getCause()); } }
@Test public void shouldThrowWhenTableElementsAndValueSchemaIdPresent() { // Given: givenFormatsAndProps( "protobuf", "avro", ImmutableMap.of("VALUE_SCHEMA_ID", new IntegerLiteral(42))); when(ct.getElements()).thenReturn(SOME_VALUE_ELEMENTS); // When: final Exception e = assertThrows( KsqlException.class, () -> injector.inject(ctStatement) ); // Then: assertThat(e.getMessage(), containsString("Table elements and VALUE_SCHEMA_ID cannot both exist for create statement.")); }
public List<JobInfo> getRecentFailures() { return Collections.unmodifiableList(mRecentFailures); }
@Test public void testRecentFailures() { Collection<JobInfo> recentFailures = mSummary.getRecentFailures(); assertEquals("Unexpected length of last activities", 3, recentFailures.size()); JobInfo[] recentFailuresArray = new JobInfo[3]; recentFailures.toArray(recentFailuresArray); assertEquals(1, recentFailuresArray[0].getId()); assertEquals(6, recentFailuresArray[1].getId()); assertEquals(4, recentFailuresArray[2].getId()); }
@VisibleForTesting public static void normalizeRequest( ResourceRequest ask, ResourceCalculator resourceCalculator, Resource minimumResource, Resource maximumResource) { ask.setCapability( getNormalizedResource(ask.getCapability(), resourceCalculator, minimumResource, maximumResource, minimumResource)); }
@Test(timeout = 30000) public void testNormalizeRequestWithDominantResourceCalculator() { ResourceCalculator resourceCalculator = new DominantResourceCalculator(); Resource minResource = Resources.createResource(1024, 1); Resource maxResource = Resources.createResource(10240, 10); Resource clusterResource = Resources.createResource(10 * 1024, 10); ResourceRequest ask = new ResourceRequestPBImpl(); // case negative memory/vcores ask.setCapability(Resources.createResource(-1024, -1)); SchedulerUtils.normalizeRequest( ask, resourceCalculator, minResource, maxResource); assertEquals(minResource, ask.getCapability()); // case zero memory/vcores ask.setCapability(Resources.createResource(0, 0)); SchedulerUtils.normalizeRequest( ask, resourceCalculator, minResource, maxResource); assertEquals(minResource, ask.getCapability()); assertEquals(1, ask.getCapability().getVirtualCores()); assertEquals(1024, ask.getCapability().getMemorySize()); // case non-zero memory & zero cores ask.setCapability(Resources.createResource(1536, 0)); SchedulerUtils.normalizeRequest( ask, resourceCalculator, minResource, maxResource); assertEquals(Resources.createResource(2048, 1), ask.getCapability()); assertEquals(1, ask.getCapability().getVirtualCores()); assertEquals(2048, ask.getCapability().getMemorySize()); }
public Config setConfigPatternMatcher(ConfigPatternMatcher configPatternMatcher) { if (configPatternMatcher == null) { throw new IllegalArgumentException("ConfigPatternMatcher is not allowed to be null!"); } this.configPatternMatcher = configPatternMatcher; return this; }
@Test(expected = IllegalArgumentException.class) public void testConfigThrow_whenConfigPatternMatcherIsNull() { config.setConfigPatternMatcher(null); }
public static String getContentIdentity(String content) { int index = content.indexOf(WORD_SEPARATOR); if (index == -1) { throw new IllegalArgumentException("content does not contain separator"); } return content.substring(0, index); }
@Test void testGetContentIdentity() { String content = "aa" + WORD_SEPARATOR + "bbb"; String content1 = ContentUtils.getContentIdentity(content); assertEquals("aa", content1); }
protected String createTempDirString() { return createTempDirString( System.getProperty( "java.io.tmpdir" ) ); }
@Test public void testCreateTempDirString_TmpDir() { String systemTmpDir = System.getProperty("java.io.tmpdir" ); String tempDir = servlet.createTempDirString(); assertTrue( tempDir.contains( systemTmpDir ) ); }
public static ECKeyPair decrypt(String password, WalletFile walletFile) throws CipherException { validate(walletFile); WalletFile.Crypto crypto = walletFile.getCrypto(); byte[] mac = Numeric.hexStringToByteArray(crypto.getMac()); byte[] iv = Numeric.hexStringToByteArray(crypto.getCipherparams().getIv()); byte[] cipherText = Numeric.hexStringToByteArray(crypto.getCiphertext()); byte[] derivedKey; WalletFile.KdfParams kdfParams = crypto.getKdfparams(); if (kdfParams instanceof WalletFile.ScryptKdfParams) { WalletFile.ScryptKdfParams scryptKdfParams = (WalletFile.ScryptKdfParams) crypto.getKdfparams(); int dklen = scryptKdfParams.getDklen(); int n = scryptKdfParams.getN(); int p = scryptKdfParams.getP(); int r = scryptKdfParams.getR(); byte[] salt = Numeric.hexStringToByteArray(scryptKdfParams.getSalt()); derivedKey = generateDerivedScryptKey(password.getBytes(UTF_8), salt, n, r, p, dklen); } else if (kdfParams instanceof WalletFile.Aes128CtrKdfParams) { WalletFile.Aes128CtrKdfParams aes128CtrKdfParams = (WalletFile.Aes128CtrKdfParams) crypto.getKdfparams(); int c = aes128CtrKdfParams.getC(); String prf = aes128CtrKdfParams.getPrf(); byte[] salt = Numeric.hexStringToByteArray(aes128CtrKdfParams.getSalt()); derivedKey = generateAes128CtrDerivedKey(password.getBytes(UTF_8), salt, c, prf); } else { throw new CipherException("Unable to deserialize params: " + crypto.getKdf()); } byte[] derivedMac = generateMac(derivedKey, cipherText); if (!Arrays.equals(derivedMac, mac)) { throw new CipherException("Invalid password provided"); } byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16); byte[] privateKey = performCipherOperation(Cipher.DECRYPT_MODE, iv, encryptKey, cipherText); return ECKeyPair.create(privateKey); }
@Test public void testDecryptScrypt() throws Exception { WalletFile walletFile = load(SCRYPT); ECKeyPair ecKeyPair = Wallet.decrypt(PASSWORD, walletFile); assertEquals(Numeric.toHexStringNoPrefix(ecKeyPair.getPrivateKey()), (SECRET)); }
@Override protected CloudBlobClient connect(final ProxyFinder proxyfinder, final HostKeyCallback callback, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { try { // Client configured with no credentials final URI uri = new URI(String.format("%s://%s", Scheme.https, host.getHostname())); final CloudBlobClient client = new CloudBlobClient(uri, new StorageCredentialsAccountAndKey(host.getCredentials().getUsername(), "null")); client.setDirectoryDelimiter(String.valueOf(Path.DELIMITER)); context.setLoggingEnabled(true); context.setLogger(LoggerFactory.getLogger(log.getName())); context.setUserHeaders(new HashMap<>(Collections.singletonMap( HttpHeaders.USER_AGENT, new PreferencesUseragentProvider().get())) ); context.getSendingRequestEventHandler().addListener(listener = new StorageEvent<SendingRequestEvent>() { @Override public void eventOccurred(final SendingRequestEvent event) { if(event.getConnectionObject() instanceof HttpsURLConnection) { final HttpsURLConnection connection = (HttpsURLConnection) event.getConnectionObject(); connection.setSSLSocketFactory(new CustomTrustSSLProtocolSocketFactory(trust, key)); connection.setHostnameVerifier(new DisabledX509HostnameVerifier()); } } }); final Proxy proxy = proxyfinder.find(new ProxyHostUrlProvider().get(host)); switch(proxy.getType()) { case SOCKS: { if(log.isInfoEnabled()) { log.info(String.format("Configured to use SOCKS proxy %s", proxyfinder)); } final java.net.Proxy socksProxy = new java.net.Proxy( java.net.Proxy.Type.SOCKS, new InetSocketAddress(proxy.getHostname(), proxy.getPort())); context.setProxy(socksProxy); break; } case HTTP: case HTTPS: { if(log.isInfoEnabled()) { log.info(String.format("Configured to use HTTP proxy %s", proxyfinder)); } final java.net.Proxy httpProxy = new java.net.Proxy( java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHostname(), proxy.getPort())); context.setProxy(httpProxy); break; } } return client; } catch(URISyntaxException e) { throw new LoginFailureException(e.getMessage(), e); } }
@Test public void testConnect() throws Exception { assertTrue(session.isConnected()); }
@Override public final Object getValue(final int columnIndex, final Class<?> type) throws SQLException { ShardingSpherePreconditions.checkNotContains(INVALID_MEMORY_TYPES, type, () -> new SQLFeatureNotSupportedException(String.format("Get value from `%s`", type.getName()))); Object result = currentResultSetRow.getCell(columnIndex); wasNull = null == result; return result; }
@Test void assertGetValueForClob() { assertThrows(SQLFeatureNotSupportedException.class, () -> memoryMergedResult.getValue(1, Clob.class)); }
@Override public void responseAvailable(SearchInvoker from) { if (availableForProcessing != null) { availableForProcessing.add(from); } }
@Test void requireThatGroupingsAreMerged() throws IOException { List<SearchInvoker> invokers = new ArrayList<>(); Grouping grouping1 = new Grouping(0); grouping1.setRoot(new com.yahoo.searchlib.aggregation.Group() .addChild(new com.yahoo.searchlib.aggregation.Group() .setId(new StringResultNode("uniqueA")) .addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(6)).setTag(4))) .addChild(new com.yahoo.searchlib.aggregation.Group() .setId(new StringResultNode("common")) .addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4)))); invokers.add(new MockInvoker(0).setHits(List.of(new GroupingListHit(List.of(grouping1))))); Grouping grouping2 = new Grouping(0); grouping2.setRoot(new com.yahoo.searchlib.aggregation.Group() .addChild(new com.yahoo.searchlib.aggregation.Group() .setId(new StringResultNode("uniqueB")) .addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4))) .addChild(new com.yahoo.searchlib.aggregation.Group() .setId(new StringResultNode("common")) .addAggregationResult(new MinAggregationResult().setMin(new IntegerResultNode(6)).setTag(3)))); invokers.add(new MockInvoker(0).setHits(List.of(new GroupingListHit(List.of(grouping2))))); try (InterleavedSearchInvoker invoker = new InterleavedSearchInvoker(Timer.monotonic, invokers, hitEstimator, dispatchConfig, new Group(0, List.of()), Set.of())) { invoker.responseAvailable(invokers.get(0)); invoker.responseAvailable(invokers.get(1)); Result result = invoker.search(query); assertEquals(1, ((GroupingListHit) result.hits().get(0)).getGroupingList().size()); } for (SearchInvoker invoker : invokers) { invoker.close(); } }
public boolean eval(StructLike data) { return new EvalVisitor().eval(data); }
@Test public void testStartsWith() { StructType struct = StructType.of(required(24, "s", Types.StringType.get())); Evaluator evaluator = new Evaluator(struct, startsWith("s", "abc")); assertThat(evaluator.eval(TestHelpers.Row.of("abc"))) .as("abc startsWith abc should be true") .isTrue(); assertThat(evaluator.eval(TestHelpers.Row.of("xabc"))) .as("xabc startsWith abc should be false") .isFalse(); assertThat(evaluator.eval(TestHelpers.Row.of("Abc"))) .as("Abc startsWith abc should be false") .isFalse(); assertThat(evaluator.eval(TestHelpers.Row.of("a"))) .as("a startsWith abc should be false") .isFalse(); assertThat(evaluator.eval(TestHelpers.Row.of("abcd"))) .as("abcd startsWith abc should be true") .isTrue(); assertThat(evaluator.eval(TestHelpers.Row.of((String) null))) .as("null startsWith abc should be false") .isFalse(); }
@Override public void add(long key, String value) { // fix https://github.com/crossoverJie/cim/issues/79 sortArrayMap.clear(); for (int i = 0; i < VIRTUAL_NODE_SIZE; i++) { Long hash = super.hash("vir" + key + i); sortArrayMap.add(hash,value); } sortArrayMap.add(key, value); }
@Test public void getFirstNodeValue3() { AbstractConsistentHash map = new SortArrayMapConsistentHash() ; List<String> strings = new ArrayList<String>(); for (int i = 0; i < 10; i++) { strings.add("127.0.0." + i) ; } String process = map.process(strings,"1551253899106"); System.out.println(process); Assert.assertEquals("127.0.0.6",process); }
@Override public V remove(Object key) { // will throw UnsupportedOperationException; delegate anyway for testability return underlying().remove(key); }
@Test public void testDelegationOfUnsupportedFunctionRemoveByKey() { new PCollectionsHashMapWrapperDelegationChecker<>() .defineMockConfigurationForUnsupportedFunction(mock -> mock.remove(eq(this))) .defineWrapperUnsupportedFunctionInvocation(wrapper -> wrapper.remove(this)) .doUnsupportedFunctionDelegationCheck(); }
@GetMapping( path = "/admin/namespace/{namespaceName}/members", produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<NamespaceMembershipListJson> getNamespaceMembers(@PathVariable String namespaceName) { try{ admins.checkAdminUser(); var memberships = repositories.findMemberships(namespaceName); var membershipList = new NamespaceMembershipListJson(); membershipList.namespaceMemberships = memberships.stream().map(NamespaceMembership::toJson).toList(); return ResponseEntity.ok(membershipList); } catch (ErrorResultException exc) { return exc.toResponseEntity(NamespaceMembershipListJson.class); } }
@Test public void testGetNamespaceMembers() throws Exception { mockAdminUser(); var namespace = mockNamespace(); var user = new UserData(); user.setLoginName("other_user"); var membership1 = new NamespaceMembership(); membership1.setNamespace(namespace); membership1.setUser(user); membership1.setRole(NamespaceMembership.ROLE_OWNER); Mockito.when(repositories.findMemberships(namespace.getName())) .thenReturn(List.of(membership1)); mockMvc.perform(get("/admin/namespace/{namespace}/members", "foobar") .with(user("admin_user").authorities(new SimpleGrantedAuthority(("ROLE_ADMIN")))) .with(csrf().asHeader())) .andExpect(status().isOk()) .andExpect(content().json(namespaceMemberJson(nml -> { var m = new NamespaceMembershipJson(); m.namespace = "foobar"; m.user = new UserJson(); m.user.loginName = "other_user"; m.role = "owner"; nml.namespaceMemberships = Arrays.asList(m); }))); }
@Override public void validateDeptList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return; } // 获得科室信息 Map<Long, DeptDO> deptMap = getDeptMap(ids); // 校验 ids.forEach(id -> { DeptDO dept = deptMap.get(id); if (dept == null) { throw exception(DEPT_NOT_FOUND); } if (!CommonStatusEnum.ENABLE.getStatus().equals(dept.getStatus())) { throw exception(DEPT_NOT_ENABLE, dept.getName()); } }); }
@Test public void testValidateDeptList_notEnable() { // mock 数据 DeptDO deptDO = randomPojo(DeptDO.class).setStatus(CommonStatusEnum.DISABLE.getStatus()); deptMapper.insert(deptDO); // 准备参数 List<Long> ids = singletonList(deptDO.getId()); // 调用, 并断言异常 assertServiceException(() -> deptService.validateDeptList(ids), DEPT_NOT_ENABLE, deptDO.getName()); }
public void initialize(Configuration config) throws YarnException { setConf(config); this.plugin.initPlugin(config); // Try to diagnose FPGA LOG.info("Trying to diagnose FPGA information ..."); if (!diagnose()) { LOG.warn("Failed to pass FPGA devices diagnose"); } }
@Test public void testExecutablePathWhenFileDoesNotExist() throws YarnException { conf.set(YarnConfiguration.NM_FPGA_PATH_TO_EXEC, getTestParentFolder() + "/aocl"); fpgaDiscoverer.initialize(conf); assertEquals("File doesn't exists - expected a single binary name", "aocl", openclPlugin.getPathToExecutable()); }
@Override public void isEqualTo(@Nullable Object expected) { @SuppressWarnings("UndefinedEquals") // method contract requires testing iterables for equality boolean equal = Objects.equal(actual, expected); if (equal) { return; } // Fail but with a more descriptive message: if (actual instanceof List && expected instanceof List) { containsExactlyElementsIn((List<?>) expected).inOrder(); } else if ((actual instanceof Set && expected instanceof Set) || (actual instanceof Multiset && expected instanceof Multiset)) { containsExactlyElementsIn((Collection<?>) expected); } else { /* * TODO(b/18430105): Consider a special message if comparing incompatible collection types * (similar to what MultimapSubject has). */ super.isEqualTo(expected); } }
@Test public void isEqualToNotConsistentWithEquals_failure() { TreeSet<String> actual = new TreeSet<>(CASE_INSENSITIVE_ORDER); TreeSet<String> expected = new TreeSet<>(CASE_INSENSITIVE_ORDER); actual.add("one"); expected.add("ONE"); actual.add("two"); expectFailureWhenTestingThat(actual).isEqualTo(expected); // The exact message generated is unspecified. }
@Override public int length() { return 2; }
@Test public void testLength() { System.out.println("length"); BetaDistribution instance = new BetaDistribution(2, 5); instance.rand(); assertEquals(2, instance.length()); }
public void addRequest(String requestName, long duration, int cpuTime, int allocatedKBytes, boolean systemError, long responseSize) { addRequest(requestName, duration, cpuTime, allocatedKBytes, systemError, null, responseSize); }
@Test public void testAddRequest() { final CounterRequest request = createCounterRequest(); // ce bindContext pour tester le cas où une requête est ajoutée avec un contexte et un contexte parent // puis une requête ajoutée avec un contexte sans contexte parent counter.bindContext(request.getName(), request.getName(), null, -1, -1); counter.addRequest(request.getName(), request.getMean(), 0, 0, false, request.getResponseSizeMean()); final List<CounterRequest> before = counter.getOrderedRequests(); counter.addRequest(request.getName(), request.getMean(), 0, 0, false, request.getResponseSizeMean()); counter.setRequestTransformPattern(Pattern.compile("aaaaa")); counter.addRequest(request.getName(), request.getMean(), 0, 0, false, request.getResponseSizeMean()); final List<CounterRequest> after = counter.getOrderedRequests(); after.get(0).removeHits(request); after.get(0).removeHits(request); // on teste le contenu des CounterRequest par le contenu de toString assertEquals("requests", before.toString(), after.toString()); // test addChildRequest dans addRequest final Counter sqlCounter = new Counter("sql", null); final Counter httpCounter = new Counter("http", null, sqlCounter); httpCounter.bindContext("http request", "http request", null, -1, -1); final String sqlRequest = "sql request"; sqlCounter.bindContext(sqlRequest, sqlRequest, null, -1, -1); sqlCounter.addRequest(sqlRequest, 0, 0, 0, false, -1); // ici context.addChildRequest sqlCounter.addRequest(sqlRequest, 0, 0, 0, false, -1); // 2ème pour passer dans le else de addChildRequestForDrillDown httpCounter.addRequest("http request", 10, 2, 2, false, 100); }
static void obtainTokensForNamenodesInternal(Credentials credentials, Path[] ps, Configuration conf) throws IOException { Set<FileSystem> fsSet = new HashSet<FileSystem>(); for(Path p: ps) { fsSet.add(p.getFileSystem(conf)); } String masterPrincipal = Master.getMasterPrincipal(conf); for (FileSystem fs : fsSet) { obtainTokensForNamenodesInternal(fs, credentials, conf, masterPrincipal); } }
@Test public void testObtainTokens() throws Exception { Credentials credentials = new Credentials(); FileSystem fs = mock(FileSystem.class); TokenCache.obtainTokensForNamenodesInternal(fs, credentials, conf, renewer); verify(fs).addDelegationTokens(eq(renewer), eq(credentials)); }
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { // Load the codec by message type. final AWSMessageType awsMessageType = AWSMessageType.valueOf(configuration.getString(CK_AWS_MESSAGE_TYPE)); final Codec.Factory<? extends Codec> codecFactory = this.availableCodecs.get(awsMessageType.getCodecName()); if (codecFactory == null) { LOG.error("A codec with name [{}] could not be found.", awsMessageType.getCodecName()); return null; } final Codec codec = codecFactory.create(configuration); // Parse the message with the specified codec. final Message message = codec.decode(new RawMessage(rawMessage.getPayload())); if (message == null) { LOG.error("Failed to decode message for codec [{}].", codec.getName()); return null; } return message; }
@Test public void testKinesisRawCodec() throws JsonProcessingException { final HashMap<String, Object> configMap = new HashMap<>(); configMap.put(AWSCodec.CK_AWS_MESSAGE_TYPE, AWSMessageType.KINESIS_RAW.toString()); final Configuration configuration = new Configuration(configMap); final AWSCodec codec = new AWSCodec(configuration, AWSTestingUtils.buildTestCodecs()); final DateTime timestamp = DateTime.now(DateTimeZone.UTC); final KinesisLogEntry kinesisLogEntry = KinesisLogEntry.create("a-stream", "log-group", "log-stream", timestamp, "This a raw message"); Message message = codec.decode(new RawMessage(objectMapper.writeValueAsBytes(kinesisLogEntry))); Assert.assertEquals("log-group", message.getField(AbstractKinesisCodec.FIELD_LOG_GROUP)); Assert.assertEquals("log-stream", message.getField(AbstractKinesisCodec.FIELD_LOG_STREAM)); Assert.assertEquals("a-stream", message.getField(AbstractKinesisCodec.FIELD_KINESIS_STREAM)); Assert.assertEquals(KinesisRawLogCodec.SOURCE, message.getField("source")); Assert.assertEquals("This a raw message", message.getField("message")); Assert.assertEquals(timestamp, message.getTimestamp()); }
public void traverseExpression(Expression expr, Function<ExprSite, Boolean> func) { Preconditions.checkNotNull(expr); if (!func.apply(new ExprSite(expr))) { return; } traverseChildren(expr, func); }
@Test public void testTraverseExpression() throws InvocationTargetException, IllegalAccessException { Expression.Reference ref = new Expression.Reference("a", TypeRef.of(ExpressionVisitorTest.class)); Expression e1 = new Expression.Invoke(ref, "testTraverseExpression"); Literal start = Literal.ofInt(0); Literal end = Literal.ofInt(10); Literal step = Literal.ofInt(1); ExpressionVisitor.ExprHolder holder = ExpressionVisitor.ExprHolder.of("e1", e1, "e2", new Expression.ListExpression()); // FIXME ListExpression#add in lambda don't get executed, so ListExpression is the last expr. Expression.ForLoop forLoop = new Expression.ForLoop( start, end, step, expr -> ((Expression.ListExpression) (holder.get("e2"))).add(holder.get("e1"))); List<Expression> expressions = new ArrayList<>(); new ExpressionVisitor() .traverseExpression(forLoop, exprSite -> expressions.add(exprSite.current)); Preconditions.checkArgument(forLoop.action != null); Method writeReplace = ReflectionUtils.findMethods(forLoop.action.getClass(), "writeReplace").get(0); writeReplace.setAccessible(true); SerializedLambda serializedLambda = (SerializedLambda) writeReplace.invoke(forLoop.action); assertEquals(serializedLambda.getCapturedArgCount(), 1); ExpressionVisitor.ExprHolder exprHolder = (ExpressionVisitor.ExprHolder) (serializedLambda.getCapturedArg(0)); assertEquals( expressions, Arrays.asList(forLoop, start, end, step, e1, ref, exprHolder.get("e2"))); }
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids); criteria.forEach(criterion -> processCriterion(criterion, query)); return query; }
@Test public void fail_to_create_query_on_qualifier_when_value_is_incorrect() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(EQ).setValue("unknown").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unknown qualifier : 'unknown'"); }
@Transactional public Release rollbackTo(long releaseId, long toReleaseId, String operator) { if (releaseId == toReleaseId) { throw new BadRequestException("current release equal to target release"); } Release release = findOne(releaseId); Release toRelease = findOne(toReleaseId); if (release == null) { throw NotFoundException.releaseNotFound(releaseId); } if (toRelease == null) { throw NotFoundException.releaseNotFound(toReleaseId); } if (release.isAbandoned() || toRelease.isAbandoned()) { throw new BadRequestException("release is not active"); } String appId = release.getAppId(); String clusterName = release.getClusterName(); String namespaceName = release.getNamespaceName(); List<Release> releases = findActiveReleasesBetween(appId, clusterName, namespaceName, toReleaseId, releaseId); for (int i = 0; i < releases.size() - 1; i++) { releases.get(i).setAbandoned(true); releases.get(i).setDataChangeLastModifiedBy(operator); } releaseRepository.saveAll(releases); releaseHistoryService.createReleaseHistory(appId, clusterName, namespaceName, clusterName, toReleaseId, release.getId(), ReleaseOperation.ROLLBACK, null, operator); //publish child namespace if namespace has child rollbackChildNamespace(appId, clusterName, namespaceName, Lists.newArrayList(release, toRelease), operator); return release; }
@Test public void testRollbackTo() { List<Release> releaseList = new ArrayList<>(); for (int i = 0; i < 3; i++) { Release release = new Release(); release.setId(3 - i); release.setAppId(appId); release.setClusterName(clusterName); release.setNamespaceName(namespaceName); release.setAbandoned(false); releaseList.add(release); } long releaseId1 = 1; long releaseId3 = 3; when(releaseRepository.findById(releaseId1)).thenReturn(Optional.of(releaseList.get(2))); when(releaseRepository.findById(releaseId3)).thenReturn(Optional.of(releaseList.get(0))); when(releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseAndIdBetweenOrderByIdDesc(appId, clusterName, namespaceName, releaseId1, releaseId3)) .thenReturn(releaseList); releaseService.rollbackTo(releaseId3, releaseId1, user); verify(releaseRepository).saveAll(releaseList); Assert.assertTrue(releaseList.get(0).isAbandoned()); Assert.assertTrue(releaseList.get(1).isAbandoned()); Assert.assertFalse(releaseList.get(2).isAbandoned()); Assert.assertEquals(user, releaseList.get(0).getDataChangeLastModifiedBy()); Assert.assertEquals(user, releaseList.get(1).getDataChangeLastModifiedBy()); }
private Mono<ServerResponse> createUser(ServerRequest request) { return request.bodyToMono(CreateUserRequest.class) .doOnNext(createUserRequest -> { if (StringUtils.isBlank(createUserRequest.name())) { throw new ServerWebInputException("Name is required"); } if (StringUtils.isBlank(createUserRequest.email())) { throw new ServerWebInputException("Email is required"); } }) .flatMap(userRequest -> { User newUser = CreateUserRequest.from(userRequest); var encryptedPwd = userService.encryptPassword(userRequest.password()); newUser.getSpec().setPassword(encryptedPwd); return userService.createUser(newUser, userRequest.roles()); }) .flatMap(user -> ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .bodyValue(user) ); }
@Test void createWhenNameDuplicate() { when(userService.createUser(any(User.class), anySet())) .thenReturn(Mono.just(new User())); when(userService.updateWithRawPassword(anyString(), anyString())) .thenReturn(Mono.just(new User())); var userRequest = new UserEndpoint.CreateUserRequest("fake-user", "fake-email", "", "", "", "", "", Map.of(), Set.of()); webClient.post().uri("/users") .bodyValue(userRequest) .exchange() .expectStatus().isOk(); }
@Override public Path move(final Path source, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { Path target; if(source.attributes().getCustom().containsKey(KEY_DELETE_MARKER)) { // Delete marker, copy not supported but we have to retain the delete marker at the target target = new Path(renamed); target.attributes().setVersionId(null); delete.delete(Collections.singletonMap(target, status), connectionCallback, callback); try { // Find version id of moved delete marker final Path bucket = containerService.getContainer(renamed); final VersionOrDeleteMarkersChunk marker = session.getClient().listVersionedObjectsChunked( bucket.isRoot() ? StringUtils.EMPTY : bucket.getName(), containerService.getKey(renamed), String.valueOf(Path.DELIMITER), 1, null, null, false); if(marker.getItems().length == 1) { final BaseVersionOrDeleteMarker markerObject = marker.getItems()[0]; target.attributes().withVersionId(markerObject.getVersionId()).setCustom(Collections.singletonMap(KEY_DELETE_MARKER, Boolean.TRUE.toString())); delete.delete(Collections.singletonMap(source, status), connectionCallback, callback); } else { throw new NotfoundException(String.format("Unable to find delete marker %s", renamed.getName())); } } catch(ServiceException e) { throw new S3ExceptionMappingService().map("Failure to read attributes of {0}", e, renamed); } } else { try { target = proxy.copy(source, renamed, status.withLength(source.attributes().getSize()), connectionCallback, new DisabledStreamListener()); // Copy source path and nullify version id to add a delete marker delete.delete(Collections.singletonMap(new Path(source).withAttributes(new PathAttributes(source.attributes()).withVersionId(null)), status), connectionCallback, callback); } catch(NotfoundException e) { if(source.getType().contains(Path.Type.placeholder)) { // No placeholder object to copy, create a new one at the target target = session.getFeature(Directory.class).mkdir(renamed, new TransferStatus().withRegion(source.attributes().getRegion())); } else { throw e; } } } return target; }
@Test public void testMoveWithDelimiter() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path placeholder = new Path(container, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.directory)); final Path test = new Path(placeholder, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); new S3TouchFeature(session, acl).touch(test, new TransferStatus()); final Path renamed = new Path(placeholder, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file)); new S3MoveFeature(session, acl).move(test, renamed, new TransferStatus(), new Delete.DisabledCallback(), new DisabledConnectionCallback()); assertFalse(new S3FindFeature(session, acl).find(test)); assertTrue(new S3FindFeature(session, acl).find(renamed)); new S3DefaultDeleteFeature(session).delete(Collections.singletonList(renamed), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@SuppressWarnings("unchecked") @Override protected synchronized void heartbeat() throws Exception { AllocateRequest allocateRequest = AllocateRequest.newInstance(this.lastResponseID, super.getApplicationProgress(), new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>(), null); AllocateResponse allocateResponse = null; try { allocateResponse = scheduler.allocate(allocateRequest); // Reset retry count if no exception occurred. retrystartTime = System.currentTimeMillis(); } catch (ApplicationAttemptNotFoundException e) { LOG.info("Event from RM: shutting down Application Master"); // This can happen if the RM has been restarted. If it is in that state, // this application must clean itself up. eventHandler.handle(new JobEvent(this.getJob().getID(), JobEventType.JOB_AM_REBOOT)); throw new YarnRuntimeException( "Resource Manager doesn't recognize AttemptId: " + this.getContext().getApplicationID(), e); } catch (ApplicationMasterNotRegisteredException e) { LOG.info("ApplicationMaster is out of sync with ResourceManager," + " hence resync and send outstanding requests."); this.lastResponseID = 0; register(); } catch (Exception e) { // This can happen when the connection to the RM has gone down. Keep // re-trying until the retryInterval has expired. if (System.currentTimeMillis() - retrystartTime >= retryInterval) { LOG.error("Could not contact RM after " + retryInterval + " milliseconds."); eventHandler.handle(new JobEvent(this.getJob().getID(), JobEventType.INTERNAL_ERROR)); throw new YarnRuntimeException("Could not contact RM after " + retryInterval + " milliseconds."); } // Throw this up to the caller, which may decide to ignore it and // continue to attempt to contact the RM. throw e; } if (allocateResponse != null) { this.lastResponseID = allocateResponse.getResponseId(); Token token = allocateResponse.getAMRMToken(); if (token != null) { updateAMRMToken(token); } Priority priorityFromResponse = Priority.newInstance(allocateResponse .getApplicationPriority().getPriority()); // Update the job priority to Job directly. getJob().setJobPriority(priorityFromResponse); } }
@Test public void testRMConnectionRetry() throws Exception { // verify the connection exception is thrown // if we haven't exhausted the retry interval ApplicationMasterProtocol mockScheduler = mock(ApplicationMasterProtocol.class); when(mockScheduler.allocate(isA(AllocateRequest.class))) .thenThrow(RPCUtil.getRemoteException(new IOException("forcefail"))); Configuration conf = new Configuration(); LocalContainerAllocator lca = new StubbedLocalContainerAllocator(mockScheduler); lca.init(conf); lca.start(); try { lca.heartbeat(); Assert.fail("heartbeat was supposed to throw"); } catch (YarnException e) { // YarnException is expected } finally { lca.stop(); } // verify YarnRuntimeException is thrown when the retry interval has expired conf.setLong(MRJobConfig.MR_AM_TO_RM_WAIT_INTERVAL_MS, 0); lca = new StubbedLocalContainerAllocator(mockScheduler); lca.init(conf); lca.start(); try { lca.heartbeat(); Assert.fail("heartbeat was supposed to throw"); } catch (YarnRuntimeException e) { // YarnRuntimeException is expected } finally { lca.stop(); } }
@Override public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final SelectionParameters other = (SelectionParameters) obj; if ( !equals( this.qualifiers, other.qualifiers ) ) { return false; } if ( !Objects.equals( this.qualifyingNames, other.qualifyingNames ) ) { return false; } if ( !Objects.equals( this.conditionQualifiers, other.conditionQualifiers ) ) { return false; } if ( !Objects.equals( this.conditionQualifyingNames, other.conditionQualifyingNames ) ) { return false; } if ( !Objects.equals( this.sourceRHS, other.sourceRHS ) ) { return false; } return equals( this.resultType, other.resultType ); }
@Test public void testEqualsQualifiersInDifferentOrder() { List<String> qualifyingNames = Arrays.asList( "language", "german" ); TypeMirror resultType = new TestTypeMirror( "resultType" ); List<TypeMirror> qualifiers = new ArrayList<>(); qualifiers.add( new TestTypeMirror( "org.mapstruct.test.SomeType" ) ); qualifiers.add( new TestTypeMirror( "org.mapstruct.test.SomeOtherType" ) ); SelectionParameters params = new SelectionParameters( qualifiers, qualifyingNames, resultType, typeUtils ); List<TypeMirror> qualifiers2 = new ArrayList<>(); qualifiers2.add( new TestTypeMirror( "org.mapstruct.test.SomeOtherType" ) ); qualifiers2.add( new TestTypeMirror( "org.mapstruct.test.SomeType" ) ); SelectionParameters params2 = new SelectionParameters( qualifiers2, qualifyingNames, resultType, typeUtils ); assertThat( params.equals( params2 ) ).as( "Different order for qualifiers" ).isFalse(); assertThat( params2.equals( params ) ).as( "Different order for qualifiers" ).isFalse(); }
public void setMaxLengthBytes(long timeout) { kp.put("maxLengthBytes",timeout); }
@Test public void testMaxLengthBytes() throws Exception { CrawlURI curi = makeCrawlURI("http://localhost:7777/200k"); fetcher().setMaxLengthBytes(50000); fetcher().process(curi); assertEquals(50001, curi.getRecordedSize()); }
@Override public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback) { //This code path cannot accept content types or accept types that contain //multipart/related. This is because these types of requests will usually have very large payloads and therefore //would degrade server performance since RestRequest reads everything into memory. if (!isMultipart(request, requestContext, callback)) { _restRestLiServer.handleRequest(request, requestContext, callback); } }
@Test public void testRequestAttachmentsAndResponseAttachments() throws Exception { //This test verifies the server's ability to accept request attachments and send back response attachments. This is the //main test to verify the wire protocol for streaming. We send a payload that contains the rest.li payload and some attachments //and we send a response back with a rest.li payload and some attachments. //Define the server side resource attachments to be sent back. final RestLiResponseAttachments.Builder responseAttachmentsBuilder = new RestLiResponseAttachments.Builder(); responseAttachmentsBuilder.appendSingleAttachment(new RestLiTestAttachmentDataSource("1", ByteString.copyString("one", Charset.defaultCharset()))); Capture<ResourceContext> resourceContextCapture = EasyMock.newCapture(); final AsyncStatusCollectionResource statusResource = getMockResource(AsyncStatusCollectionResource.class, capture(resourceContextCapture)); statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(), EasyMock.<Callback<Long>> anyObject()); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { //Verify there are still attachments to be read. final RestLiAttachmentReader attachmentReader = (RestLiAttachmentReader)EasyMock.getCurrentArguments()[1]; Assert.assertFalse(attachmentReader.haveAllAttachmentsFinished()); //Verify the action param. Assert.assertEquals((String)EasyMock.getCurrentArguments()[0], "someMetadata"); //Set the response attachments resourceContextCapture.getValue().setResponseAttachments(responseAttachmentsBuilder.build()); //Now respond back to the request. @SuppressWarnings("unchecked") Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2]; callback.onSuccess(1234l); return null; } }); replay(statusResource); //Now we create a multipart/related payload. final String payload = "{\"metadata\": \"someMetadata\"}"; final ByteStringWriter byteStringWriter = new ByteStringWriter(ByteString.copyString(payload, Charset.defaultCharset())); final MultiPartMIMEWriter.Builder builder = new MultiPartMIMEWriter.Builder(); AttachmentUtils.appendSingleAttachmentToBuilder(builder, new RestLiTestAttachmentDataSource("2", ByteString.copyString("two", Charset.defaultCharset()))); final MultiPartMIMEWriter writer = AttachmentUtils.createMultiPartMIMEWriter(byteStringWriter, "application/json", builder); final StreamRequest streamRequest = MultiPartMIMEStreamRequestFactory.generateMultiPartMIMEStreamRequest(new URI("/asyncstatuses/?action=streamingAction"), "related", writer, Collections.<String, String>emptyMap(), "POST", ImmutableMap.of(RestConstants.HEADER_ACCEPT, RestConstants.HEADER_VALUE_MULTIPART_RELATED), Collections.emptyList()); final Callback<StreamResponse> callback = new Callback<StreamResponse>() { @Override public void onSuccess(StreamResponse streamResponse) { //Before reading the data make sure top level type is multipart/related Assert.assertEquals(streamResponse.getStatus(), 200); try { ContentType contentType = new ContentType(streamResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE)); Assert.assertEquals(contentType.getBaseType(), RestConstants.HEADER_VALUE_MULTIPART_RELATED); } catch (ParseException parseException) { Assert.fail(); } final CountDownLatch countDownLatch = new CountDownLatch(1); MultiPartMIMEFullReaderCallback fullReaderCallback = new MultiPartMIMEFullReaderCallback(countDownLatch); final MultiPartMIMEReader reader = MultiPartMIMEReader.createAndAcquireStream(streamResponse); reader.registerReaderCallback(fullReaderCallback); try { countDownLatch.await(3000, TimeUnit.MILLISECONDS); } catch (InterruptedException interruptedException) { Assert.fail(); } final List<SinglePartMIMEFullReaderCallback> singlePartMIMEReaderCallbacks = fullReaderCallback.getSinglePartMIMEReaderCallbacks(); Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 2); //Verify first part is Action response. Assert.assertEquals(singlePartMIMEReaderCallbacks.get(0).getHeaders().get(RestConstants.HEADER_CONTENT_TYPE), RestConstants.HEADER_VALUE_APPLICATION_JSON); Assert.assertEquals(singlePartMIMEReaderCallbacks.get(0).getFinishedData().asAvroString(), "{\"value\":1234}"); //Verify the second part matches what the server should have sent back Assert.assertEquals(singlePartMIMEReaderCallbacks.get(1).getHeaders().get(RestConstants.HEADER_CONTENT_ID), "1"); Assert.assertEquals(singlePartMIMEReaderCallbacks.get(1).getFinishedData().asString(Charset.defaultCharset()), "one"); EasyMock.verify(statusResource); EasyMock.reset(statusResource); } @Override public void onError(Throwable e) { fail(); } }; _server.handleRequest(streamRequest, new RequestContext(), callback); }
public static Combine.BinaryCombineDoubleFn ofDoubles() { return new Min.MinDoubleFn(); }
@Test public void testMinDoubleFnNan() { testCombineFn( Min.ofDoubles(), Lists.newArrayList(Double.NEGATIVE_INFINITY, 2.0, 3.0, Double.NaN), Double.NaN); }
@Override public Optional<ShardingConditionValue> generate(final InExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) { if (predicate.isNot()) { return Optional.empty(); } Collection<ExpressionSegment> expressionSegments = predicate.getExpressionList(); List<Integer> parameterMarkerIndexes = new ArrayList<>(expressionSegments.size()); List<Comparable<?>> shardingConditionValues = new LinkedList<>(); for (ExpressionSegment each : expressionSegments) { ConditionValue conditionValue = new ConditionValue(each, params); Optional<Comparable<?>> value = conditionValue.getValue(); if (conditionValue.isNull()) { shardingConditionValues.add(null); conditionValue.getParameterMarkerIndex().ifPresent(parameterMarkerIndexes::add); continue; } if (value.isPresent()) { shardingConditionValues.add(value.get()); conditionValue.getParameterMarkerIndex().ifPresent(parameterMarkerIndexes::add); continue; } if (ExpressionConditionUtils.isNowExpression(each)) { shardingConditionValues.add(timestampServiceRule.getTimestamp()); } } return shardingConditionValues.isEmpty() ? Optional.empty() : Optional.of(new ListShardingConditionValue<>(column.getName(), column.getTableName(), shardingConditionValues, parameterMarkerIndexes)); }
@Test void assertNowExpression() { ListExpression listExpression = new ListExpression(0, 0); listExpression.getItems().add(new CommonExpressionSegment(0, 0, "now()")); InExpression inExpression = new InExpression(0, 0, null, listExpression, false); Optional<ShardingConditionValue> shardingConditionValue = generator.generate(inExpression, column, new LinkedList<>(), timestampServiceRule); assertTrue(shardingConditionValue.isPresent()); assertThat(((ListShardingConditionValue<?>) shardingConditionValue.get()).getValues().iterator().next(), instanceOf(Date.class)); assertTrue(shardingConditionValue.get().getParameterMarkerIndexes().isEmpty()); }
@Override public AuthUser getAuthUser(Integer socialType, Integer userType, String code, String state) { // 构建请求 AuthRequest authRequest = buildAuthRequest(socialType, userType); AuthCallback authCallback = AuthCallback.builder().code(code).state(state).build(); // 执行请求 AuthResponse<?> authResponse = authRequest.login(authCallback); log.info("[getAuthUser][请求社交平台 type({}) request({}) response({})]", socialType, toJsonString(authCallback), toJsonString(authResponse)); if (!authResponse.ok()) { throw exception(SOCIAL_USER_AUTH_FAILURE, authResponse.getMsg()); } return (AuthUser) authResponse.getData(); }
@Test public void testAuthSocialUser_success() { // 准备参数 Integer socialType = SocialTypeEnum.WECHAT_MP.getType(); Integer userType = randomPojo(UserTypeEnum.class).getValue(); String code = randomString(); String state = randomString(); // mock 方法(AuthRequest) AuthRequest authRequest = mock(AuthRequest.class); when(authRequestFactory.get(eq("WECHAT_MP"))).thenReturn(authRequest); // mock 方法(AuthResponse) AuthUser authUser = randomPojo(AuthUser.class); AuthResponse<?> authResponse = new AuthResponse<>(2000, null, authUser); when(authRequest.login(argThat(authCallback -> { assertEquals(code, authCallback.getCode()); assertEquals(state, authCallback.getState()); return true; }))).thenReturn(authResponse); // 调用 AuthUser result = socialClientService.getAuthUser(socialType, userType, code, state); // 断言 assertSame(authUser, result); }
public static boolean safeContains(final Range<Comparable<?>> range, final Comparable<?> endpoint) { try { return range.contains(endpoint); } catch (final ClassCastException ex) { Comparable<?> rangeUpperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null; Comparable<?> rangeLowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : null; Optional<Class<?>> clazz = getTargetNumericType(Arrays.asList(rangeLowerEndpoint, rangeUpperEndpoint, endpoint)); if (!clazz.isPresent()) { throw ex; } Range<Comparable<?>> newRange = createTargetNumericTypeRange(range, clazz.get()); return newRange.contains(parseNumberByClazz(endpoint.toString(), clazz.get())); } }
@Test void assertSafeContainsForBigInteger() { Range<Comparable<?>> range = Range.closed(new BigInteger("123"), new BigInteger("1000")); assertTrue(SafeNumberOperationUtils.safeContains(range, 510)); }
public static String extractAttributeNameNameWithoutArguments(String attributeNameWithArguments) { int start = StringUtil.lastIndexOf(attributeNameWithArguments, '['); int end = StringUtil.lastIndexOf(attributeNameWithArguments, ']'); if (start > 0 && end > 0 && end > start) { return attributeNameWithArguments.substring(0, start); } if (start < 0 && end < 0) { return attributeNameWithArguments; } throw new IllegalArgumentException("Wrong argument input passed " + attributeNameWithArguments); }
@Test(expected = IllegalArgumentException.class) public void extractAttributeName_wrongArguments_noArgument_noOpening() { extractAttributeNameNameWithoutArguments("car.wheel]"); }
public static ImmutableList<SbeField> generateFields(Ir ir, IrOptions irOptions) { ImmutableList.Builder<SbeField> fields = ImmutableList.builder(); TokenIterator iterator = getIteratorForMessage(ir, irOptions); while (iterator.hasNext()) { Token token = iterator.next(); switch (token.signal()) { case BEGIN_FIELD: fields.add(processPrimitive(iterator)); break; default: // TODO(https://github.com/apache/beam/issues/21102): Support remaining field types break; } } return fields.build(); }
@Test public void testGenerateFieldsNoSpecifiedMessage() throws Exception { Ir ir = getIr(OnlyPrimitivesMultiMessage.RESOURCE_PATH); assertThrows( IllegalArgumentException.class, () -> IrFieldGenerator.generateFields(ir, IrOptions.DEFAULT)); }
@Override public ListenableFuture<BufferResult> get(OutputBufferId outputBufferId, long startingSequenceId, DataSize maxSize) { requireNonNull(outputBufferId, "outputBufferId is null"); checkArgument(maxSize.toBytes() > 0, "maxSize must be at least 1 byte"); return partitions.get(outputBufferId.getId()).getPages(startingSequenceId, maxSize); }
@Test public void testAcknowledgementFreesWriters() { int firstPartition = 0; int secondPartition = 1; PartitionedOutputBuffer buffer = createPartitionedBuffer( createInitialEmptyOutputBuffers(PARTITIONED) .withBuffer(FIRST, firstPartition) .withBuffer(SECOND, secondPartition) .withNoMoreBufferIds(), sizeOfPages(2)); // Add two pages, buffer is full addPage(buffer, createPage(1), firstPartition); addPage(buffer, createPage(2), firstPartition); assertQueueState(buffer, FIRST, 2, 0); // third page is blocked ListenableFuture<?> future = enqueuePage(buffer, createPage(3), secondPartition); // we should be blocked assertFalse(future.isDone()); assertQueueState(buffer, FIRST, 2, 0); assertQueueState(buffer, SECOND, 1, 0); // acknowledge pages for first partition, make space in the buffer buffer.get(FIRST, 2, sizeOfPages(10)).cancel(true); // writer should not be blocked assertFutureIsDone(future); assertQueueState(buffer, SECOND, 1, 0); }
public ExitStatus(Options options) { this.options = options; }
@Test void with_ambiguous_scenarios() { createRuntime(); bus.send(testCaseFinishedWithStatus(Status.AMBIGUOUS)); assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x1))); }
@Override public void process(Exchange exchange) throws Exception { final SchematronProcessor schematronProcessor = SchematronProcessorFactory.newSchematronEngine(endpoint.getRules()); final Object payload = exchange.getIn().getBody(); final String report; if (payload instanceof Source) { LOG.debug("Applying schematron validation on payload: {}", payload); report = schematronProcessor.validate((Source) payload); } else if (payload instanceof String) { LOG.debug("Applying schematron validation on payload: {}", payload); report = schematronProcessor.validate((String) payload); } else { String stringPayload = exchange.getIn().getBody(String.class); LOG.debug("Applying schematron validation on payload: {}", stringPayload); report = schematronProcessor.validate(stringPayload); } LOG.debug("Schematron validation report \n {}", report); String status = getValidationStatus(report); LOG.info("Schematron validation status : {}", status); setValidationReport(exchange, report, status); }
@Test public void testProcessValidXMLAsSource() throws Exception { Exchange exc = new DefaultExchange(context, ExchangePattern.InOut); exc.getIn().setBody( new SAXSource(getXMLReader(), new InputSource(ClassLoader.getSystemResourceAsStream("xml/article-1.xml")))); // process xml payload producer.process(exc); // assert assertEquals(Constants.SUCCESS, exc.getMessage().getHeader(Constants.VALIDATION_STATUS)); }
public void setContract(@Nullable Produce contract) { this.contract = contract; setStoredContract(contract); handleContractState(); }
@Test public void redberriesContractRedberriesDead() { // Get the bush patch final FarmingPatch patch = farmingGuildPatches.get(Varbits.FARMING_4772); assertNotNull(patch); when(farmingTracker.predictPatch(patch)) .thenReturn(new PatchPrediction(Produce.REDBERRIES, CropState.DEAD, 0, 2, 3)); farmingContractManager.setContract(Produce.REDBERRIES); assertEquals(SummaryState.IN_PROGRESS, farmingContractManager.getSummary()); assertEquals(CropState.DEAD, farmingContractManager.getContractCropState()); }
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor( DoFn<InputT, OutputT> fn) { return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn); }
@Test public void testTruncateFnWithHasDefaultMethodsWhenBounded() throws Exception { class BoundedMockFn extends DoFn<String, String> { @ProcessElement public void processElement( ProcessContext c, RestrictionTracker<RestrictionWithBoundedDefaultTracker, Void> tracker, WatermarkEstimator<WatermarkEstimatorStateWithDefaultWatermarkEstimator> watermarkEstimator) {} @GetInitialRestriction public RestrictionWithBoundedDefaultTracker getInitialRestriction(@Element String element) { return null; } @GetInitialWatermarkEstimatorState public WatermarkEstimatorStateWithDefaultWatermarkEstimator getInitialWatermarkEstimatorState() { return null; } } BoundedMockFn fn = mock(BoundedMockFn.class); DoFnInvoker<String, String> invoker = DoFnInvokers.invokerFor(fn); CoderRegistry coderRegistry = CoderRegistry.createDefault(); coderRegistry.registerCoderProvider( CoderProviders.fromStaticMethods( RestrictionWithBoundedDefaultTracker.class, CoderForDefaultTracker.class)); coderRegistry.registerCoderForClass( WatermarkEstimatorStateWithDefaultWatermarkEstimator.class, new CoderForWatermarkEstimatorStateWithDefaultWatermarkEstimator()); assertThat( invoker.<RestrictionWithBoundedDefaultTracker>invokeGetRestrictionCoder(coderRegistry), instanceOf(CoderForDefaultTracker.class)); assertThat( invoker.invokeGetWatermarkEstimatorStateCoder(coderRegistry), instanceOf(CoderForWatermarkEstimatorStateWithDefaultWatermarkEstimator.class)); RestrictionTracker tracker = invoker.invokeNewTracker( new FakeArgumentProvider<String, String>() { @Override public Object restriction() { return new RestrictionWithBoundedDefaultTracker(); } }); assertThat(tracker, instanceOf(BoundedDefaultTracker.class)); TruncateResult<?> result = invoker.invokeTruncateRestriction( new FakeArgumentProvider<String, String>() { @Override public RestrictionTracker restrictionTracker() { return tracker; } @Override public String element(DoFn<String, String> doFn) { return "blah"; } @Override public Object restriction() { return "foo"; } }); assertEquals("foo", result.getTruncatedRestriction()); assertEquals(stop(), invoker.invokeProcessElement(mockArgumentProvider)); assertThat( invoker.invokeNewWatermarkEstimator( new FakeArgumentProvider<String, String>() { @Override public Object watermarkEstimatorState() { return new WatermarkEstimatorStateWithDefaultWatermarkEstimator(); } }), instanceOf(DefaultWatermarkEstimator.class)); }
public KnownExploitedVulnerabilitiesSchema parse(InputStream in) throws UpdateException, CorruptedDatastreamException { final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); final Module module; if (Utils.getJavaVersion() <= 8) { module = new AfterburnerModule(); } else { module = new BlackbirdModule(); } objectMapper.registerModule(module); final ObjectReader objectReader = objectMapper.readerFor(KnownExploitedVulnerabilitiesSchema.class); //InputStream in = new GZIPInputStream(fin); try (InputStreamReader isr = new InputStreamReader(in, UTF_8); JsonParser parser = objectReader.getFactory().createParser(isr)) { final KnownExploitedVulnerabilitiesSchema data = objectReader.readValue(parser); return data; } catch (ZipException | EOFException ex) { throw new CorruptedDatastreamException("Error parsing CISA Known Exploited Vulnerabilities file", ex); } catch (IOException ex) { LOGGER.error("Error reading CISA Known Exploited Vulnerabilities JSON data"); LOGGER.debug("Error extracting the CISA Known Exploited Vulnerabilities JSON data", ex); throw new UpdateException("Unable to find the CISA Known Exploited Vulnerabilities file to parse", ex); } }
@Test public void testParse() throws Exception { File file = new File("./src/test/resources/update/cisa/known_exploited_vulnerabilities.json"); try (InputStream in = new FileInputStream(file)) { KnownExploitedVulnerabilityParser instance = new KnownExploitedVulnerabilityParser(); KnownExploitedVulnerabilitiesSchema result = instance.parse(in); assertEquals(834, result.getVulnerabilities().size()); } }
@Override public ByteBuf copy() { return copy(readerIndex, readableBytes()); }
@Test public void testCopy() { for (int i = 0; i < buffer.capacity(); i ++) { byte value = (byte) random.nextInt(); buffer.setByte(i, value); } final int readerIndex = CAPACITY / 3; final int writerIndex = CAPACITY * 2 / 3; buffer.setIndex(readerIndex, writerIndex); // Make sure all properties are copied. ByteBuf copy = buffer.copy(); assertEquals(0, copy.readerIndex()); assertEquals(buffer.readableBytes(), copy.writerIndex()); assertEquals(buffer.readableBytes(), copy.capacity()); assertSame(buffer.order(), copy.order()); for (int i = 0; i < copy.capacity(); i ++) { assertEquals(buffer.getByte(i + readerIndex), copy.getByte(i)); } // Make sure the buffer content is independent from each other. buffer.setByte(readerIndex, (byte) (buffer.getByte(readerIndex) + 1)); assertTrue(buffer.getByte(readerIndex) != copy.getByte(0)); copy.setByte(1, (byte) (copy.getByte(1) + 1)); assertTrue(buffer.getByte(readerIndex + 1) != copy.getByte(1)); copy.release(); }
@Override public ProducerBuilder<T> batchingMaxPublishDelay(long batchDelay, @NonNull TimeUnit timeUnit) { conf.setBatchingMaxPublishDelayMicros(batchDelay, timeUnit); return this; }
@Test(expectedExceptions = IllegalArgumentException.class) public void testProducerBuilderImplWhenBatchingMaxPublishDelayPropertyIsNegative() { producerBuilderImpl.batchingMaxPublishDelay(-1, TimeUnit.MILLISECONDS); }
@Override public void close() { }
@Test public void shouldSucceed_forward() throws ExecutionException, InterruptedException { // Given: final PushRouting routing = new PushRouting(); // When: final PushConnectionsHandle handle = handlePushRouting(routing); context.runOnContext(v -> { localPublisher.accept(LOCAL_ROW1); localPublisher.accept(LOCAL_ROW2); remotePublisher.accept(REMOTE_ROW1); remotePublisher.accept(REMOTE_ROW2); }); // Then: Set<List<?>> rows = waitOnRows(4); handle.close(); assertThat(rows.contains(LOCAL_ROW1.value().values()), is(true)); assertThat(rows.contains(LOCAL_ROW2.value().values()), is(true)); assertThat(rows.contains(REMOTE_ROW1.getRow().get().getColumns()), is(true)); assertThat(rows.contains(REMOTE_ROW2.getRow().get().getColumns()), is(true)); }
@Override public void registerTimer(long timestamp) { timerService.registerProcessingTimeTimer(VoidNamespace.INSTANCE, timestamp); }
@Test void testRegisterProcessingTimer() { TestInternalTimerService<Integer, VoidNamespace> timerService = getTimerService(); DefaultProcessingTimeManager manager = new DefaultProcessingTimeManager(timerService); assertThat(timerService.numProcessingTimeTimers()).isZero(); manager.registerTimer(100L); assertThat(timerService.numProcessingTimeTimers()).isOne(); }
Optional<CheckpointTriggerRequest> chooseRequestToExecute( CheckpointTriggerRequest newRequest, boolean isTriggering, long lastCompletionMs) { if (queuedRequests.size() >= maxQueuedRequests && !queuedRequests.last().isPeriodic) { // there are only non-periodic (ie user-submitted) requests enqueued - retain them and // drop the new one newRequest.completeExceptionally(new CheckpointException(TOO_MANY_CHECKPOINT_REQUESTS)); return Optional.empty(); } else { queuedRequests.add(newRequest); if (queuedRequests.size() > maxQueuedRequests) { queuedRequests .pollLast() .completeExceptionally( new CheckpointException(TOO_MANY_CHECKPOINT_REQUESTS)); } Optional<CheckpointTriggerRequest> request = chooseRequestToExecute(isTriggering, lastCompletionMs); request.ifPresent(CheckpointRequestDecider::logInQueueTime); return request; } }
@Test void testForce() { CheckpointRequestDecider decider = decider(1, 1, Integer.MAX_VALUE, new AtomicInteger(1), new AtomicInteger(0)); CheckpointTriggerRequest request = periodicSavepoint(); assertThat(decider.chooseRequestToExecute(request, false, 123)).hasValue(request); }
protected boolean isCore(Dependency left, Dependency right) { final String leftName = left.getFileName().toLowerCase(); final String rightName = right.getFileName().toLowerCase(); final boolean returnVal; //TODO - should we get rid of this merging? It removes a true BOM... if (left.isVirtual() && !right.isVirtual()) { returnVal = true; } else if (!left.isVirtual() && right.isVirtual()) { returnVal = false; } else if ((!rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war|rpm).+") && leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war|rpm).+")) || (rightName.contains("core") && !leftName.contains("core")) || (rightName.contains("kernel") && !leftName.contains("kernel")) || (rightName.contains("server") && !leftName.contains("server")) || (rightName.contains("project") && !leftName.contains("project")) || (rightName.contains("engine") && !leftName.contains("engine")) || (rightName.contains("akka-stream") && !leftName.contains("akka-stream")) || (rightName.contains("netty-transport") && !leftName.contains("netty-transport"))) { returnVal = false; } else if ((rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war|rpm).+") && !leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war|rpm).+")) || (!rightName.contains("core") && leftName.contains("core")) || (!rightName.contains("kernel") && leftName.contains("kernel")) || (!rightName.contains("server") && leftName.contains("server")) || (!rightName.contains("project") && leftName.contains("project")) || (!rightName.contains("engine") && leftName.contains("engine")) || (!rightName.contains("akka-stream") && leftName.contains("akka-stream")) || (!rightName.contains("netty-transport") && leftName.contains("netty-transport"))) { returnVal = true; } else { /* * considered splitting the names up and comparing the components, * but decided that the file name length should be sufficient as the * "core" component, if this follows a normal naming protocol should * be shorter: * axis2-saaj-1.4.1.jar * axis2-1.4.1.jar <----- * axis2-kernel-1.4.1.jar */ returnVal = leftName.length() <= rightName.length(); } LOGGER.debug("IsCore={} ({}, {})", returnVal, left.getFileName(), right.getFileName()); return returnVal; }
@Test public void testIsCore() { Dependency left = new Dependency(); Dependency right = new Dependency(); left.setFileName("axis2-kernel-1.4.1.jar"); right.setFileName("axis2-adb-1.4.1.jar"); DependencyBundlingAnalyzer instance = new DependencyBundlingAnalyzer(); boolean expResult = true; boolean result = instance.isCore(left, right); assertEquals(expResult, result); left.setFileName("struts-1.2.7.jar"); right.setFileName("file.tar.gz\\file.tar\\struts.jar"); expResult = true; result = instance.isCore(left, right); assertEquals(expResult, result); left.setFileName("struts-1.2.7.jar"); right.setFileName("struts-1.2.9-162.35.1.uyuni.noarch.rpm"); expResult = true; result = instance.isCore(left, right); assertEquals(expResult, result); }
public static final String[] guessStringsFromLine( VariableSpace space, LogChannelInterface log, String line, TextFileInputMeta inf, String delimiter, String enclosure, String escapeCharacter ) throws KettleException { List<String> strings = new ArrayList<>(); String pol; // piece of line try { if ( line == null ) { return null; } if ( inf.content.fileType.equalsIgnoreCase( "CSV" ) ) { // Split string in pieces, only for CSV! int pos = 0; int length = line.length(); boolean dencl = false; int len_encl = ( enclosure == null ? 0 : enclosure.length() ); int len_esc = ( escapeCharacter == null ? 0 : escapeCharacter.length() ); while ( pos < length ) { int from = pos; int next; boolean encl_found; boolean contains_escaped_enclosures = false; boolean contains_escaped_separators = false; boolean contains_escaped_escape = false; // Is the field beginning with an enclosure? // "aa;aa";123;"aaa-aaa";000;... if ( len_encl > 0 && line.substring( from, from + len_encl ).equalsIgnoreCase( enclosure ) ) { if ( log.isRowLevel() ) { log.logRowlevel( BaseMessages.getString( PKG, "TextFileInput.Log.ConvertLineToRowTitle" ), BaseMessages .getString( PKG, "TextFileInput.Log.ConvertLineToRow", line.substring( from, from + len_encl ) ) ); } encl_found = true; int p = from + len_encl; boolean is_enclosure = len_encl > 0 && p + len_encl < length && line.substring( p, p + len_encl ).equalsIgnoreCase( enclosure ); boolean is_escape = len_esc > 0 && p + len_esc < length && line.substring( p, p + len_esc ).equalsIgnoreCase( escapeCharacter ); boolean enclosure_after = false; // Is it really an enclosure? See if it's not repeated twice or escaped! if ( ( is_enclosure || is_escape ) && p < length - 1 ) { String strnext = line.substring( p + len_encl, p + 2 * len_encl ); if ( strnext.equalsIgnoreCase( enclosure ) ) { p++; enclosure_after = true; dencl = true; // Remember to replace them later on! if ( is_escape ) { contains_escaped_enclosures = true; } } else if ( strnext.equals( escapeCharacter ) ) { p++; // Remember to replace them later on! if ( is_escape ) { contains_escaped_escape = true; // remember } } } // Look for a closing enclosure! while ( ( !is_enclosure || enclosure_after ) && p < line.length() ) { p++; enclosure_after = false; is_enclosure = len_encl > 0 && p + len_encl < length && line.substring( p, p + len_encl ).equals( enclosure ); is_escape = len_esc > 0 && p + len_esc < length && line.substring( p, p + len_esc ).equals( escapeCharacter ); // Is it really an enclosure? See if it's not repeated twice or escaped! if ( ( is_enclosure || is_escape ) && p < length - 1 ) { String strnext = line.substring( p + len_encl, p + 2 * len_encl ); if ( strnext.equals( enclosure ) ) { p++; enclosure_after = true; dencl = true; // Remember to replace them later on! if ( is_escape ) { contains_escaped_enclosures = true; // remember } } else if ( strnext.equals( escapeCharacter ) ) { p++; // Remember to replace them later on! if ( is_escape ) { contains_escaped_escape = true; // remember } } } } if ( p >= length ) { next = p; } else { next = p + len_encl; } if ( log.isRowLevel() ) { log.logRowlevel( BaseMessages.getString( PKG, "TextFileInput.Log.ConvertLineToRowTitle" ), BaseMessages .getString( PKG, "TextFileInput.Log.EndOfEnclosure", "" + p ) ); } } else { encl_found = false; boolean found = false; int startpoint = from; // int tries = 1; do { next = line.indexOf( delimiter, startpoint ); // See if this position is preceded by an escape character. if ( len_esc > 0 && next - len_esc > 0 ) { String before = line.substring( next - len_esc, next ); if ( escapeCharacter.equals( before ) ) { // take the next separator, this one is escaped... startpoint = next + 1; // tries++; contains_escaped_separators = true; } else { found = true; } } else { found = true; } } while ( !found && next >= 0 ); } if ( next == -1 ) { next = length; } if ( encl_found ) { pol = line.substring( from + len_encl, next - len_encl ); if ( log.isRowLevel() ) { log.logRowlevel( BaseMessages.getString( PKG, "TextFileInput.Log.ConvertLineToRowTitle" ), BaseMessages .getString( PKG, "TextFileInput.Log.EnclosureFieldFound", "" + pol ) ); } } else { pol = line.substring( from, next ); if ( log.isRowLevel() ) { log.logRowlevel( BaseMessages.getString( PKG, "TextFileInput.Log.ConvertLineToRowTitle" ), BaseMessages .getString( PKG, "TextFileInput.Log.NormalFieldFound", "" + pol ) ); } } if ( dencl ) { StringBuilder sbpol = new StringBuilder( pol ); int idx = sbpol.indexOf( enclosure + enclosure ); while ( idx >= 0 ) { sbpol.delete( idx, idx + enclosure.length() ); idx = sbpol.indexOf( enclosure + enclosure ); } pol = sbpol.toString(); } // replace the escaped enclosures with enclosures... if ( contains_escaped_enclosures ) { String replace = escapeCharacter + enclosure; String replaceWith = enclosure; pol = Const.replace( pol, replace, replaceWith ); } // replace the escaped separators with separators... if ( contains_escaped_separators ) { String replace = escapeCharacter + delimiter; String replaceWith = delimiter; pol = Const.replace( pol, replace, replaceWith ); } // replace the escaped escape with escape... if ( contains_escaped_escape ) { String replace = escapeCharacter + escapeCharacter; String replaceWith = escapeCharacter; pol = Const.replace( pol, replace, replaceWith ); } // Now add pol to the strings found! strings.add( pol ); pos = next + delimiter.length(); } if ( pos == length ) { if ( log.isRowLevel() ) { log.logRowlevel( BaseMessages.getString( PKG, "TextFileInput.Log.ConvertLineToRowTitle" ), BaseMessages .getString( PKG, "TextFileInput.Log.EndOfEmptyLineFound" ) ); } strings.add( "" ); } } else { // Fixed file format: Simply get the strings at the required positions... for ( int i = 0; i < inf.inputFields.length; i++ ) { BaseFileField field = inf.inputFields[i]; int length = line.length(); if ( field.getPosition() + field.getLength() <= length ) { strings.add( line.substring( field.getPosition(), field.getPosition() + field.getLength() ) ); } else { if ( field.getPosition() < length ) { strings.add( line.substring( field.getPosition() ) ); } else { strings.add( "" ); } } } } } catch ( Exception e ) { throw new KettleException( BaseMessages.getString( PKG, "TextFileInput.Log.Error.ErrorConvertingLine", e .toString() ), e ); } return strings.toArray( new String[strings.size()] ); }
@Test public void guessStringsFromLine() throws Exception { TextFileInputMeta inputMeta = Mockito.mock( TextFileInputMeta.class ); inputMeta.content = new TextFileInputMeta.Content(); inputMeta.content.fileType = "CSV"; String line = "\"\\\\valueA\"|\"valueB\\\\\"|\"val\\\\ueC\""; // "\\valueA"|"valueB\\"|"val\\ueC" String[] strings = TextFileInputUtils .guessStringsFromLine( Mockito.mock( VariableSpace.class ), Mockito.mock( LogChannelInterface.class ), line, inputMeta, "|", "\"", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "\\valueA", strings[ 0 ] ); Assert.assertEquals( "valueB\\", strings[ 1 ] ); Assert.assertEquals( "val\\ueC", strings[ 2 ] ); }
public String getJson() { Collection<SlowPeerJsonReport> validReports = getJsonReports( maxNodesToReport); try { return WRITER.writeValueAsString(validReports); } catch (JsonProcessingException e) { // Failed to serialize. Don't log the exception call stack. LOG.debug("Failed to serialize statistics" + e); return null; } }
@Test public void testGetJson() throws IOException { OutlierMetrics outlierMetrics1 = new OutlierMetrics(0.0, 0.0, 0.0, 1.1); tracker.addReport("node1", "node2", outlierMetrics1); OutlierMetrics outlierMetrics2 = new OutlierMetrics(0.0, 0.0, 0.0, 1.23); tracker.addReport("node2", "node3", outlierMetrics2); OutlierMetrics outlierMetrics3 = new OutlierMetrics(0.0, 0.0, 0.0, 2.13); tracker.addReport("node2", "node1", outlierMetrics3); OutlierMetrics outlierMetrics4 = new OutlierMetrics(0.0, 0.0, 0.0, 1.244); tracker.addReport("node4", "node1", outlierMetrics4); final Set<SlowPeerJsonReport> reports = getAndDeserializeJson(); // And ensure its contents are what we expect. assertThat(reports.size(), is(3)); assertTrue(isNodeInReports(reports, "node1")); assertTrue(isNodeInReports(reports, "node2")); assertTrue(isNodeInReports(reports, "node4")); assertFalse(isNodeInReports(reports, "node3")); }
@Override public synchronized void editSchedule() { updateConfigIfNeeded(); long startTs = clock.getTime(); CSQueue root = scheduler.getRootQueue(); Resource clusterResources = Resources.clone(scheduler.getClusterResource()); containerBasedPreemptOrKill(root, clusterResources); if (LOG.isDebugEnabled()) { LOG.debug("Total time used=" + (clock.getTime() - startTs) + " ms."); } }
@Test public void testPreemptionWithVCoreResource() { int[][] qData = new int[][]{ // / A B {100, 100, 100}, // maxcap {5, 1, 1}, // apps {2, 0, 0}, // subqueues }; // Resources can be set like memory:vcores String[][] resData = new String[][]{ // / A B {"100:100", "50:50", "50:50"}, // abs {"10:100", "10:100", "0"}, // used {"70:20", "70:20", "10:100"}, // pending {"0", "0", "0"}, // reserved {"-1", "1:10", "1:10"}, // req granularity }; // Passing last param as TRUE to use DominantResourceCalculator ProportionalCapacityPreemptionPolicy policy = buildPolicy(qData, resData, true); policy.editSchedule(); // 4 containers will be preempted here verify(mDisp, times(4)).handle(argThat(new IsPreemptionRequestFor(appA))); }
public static OptionRule.Builder builder() { return new OptionRule.Builder(); }
@Test public void testVerify() { Executable executable = () -> { OptionRule.builder() .optional(TEST_NUM, TEST_MODE) .required(TEST_PORTS, TEST_REQUIRED_HAVE_DEFAULT_VALUE) .exclusive(TEST_TOPIC_PATTERN, TEST_TOPIC) .conditional(TEST_MODE, OptionTest.TestMode.TIMESTAMP, TEST_TIMESTAMP) .build(); }; executable = () -> { OptionRule.builder() .optional(TEST_NUM, TEST_MODE, TEST_REQUIRED_HAVE_DEFAULT_VALUE) .required(TEST_PORTS, TEST_REQUIRED_HAVE_DEFAULT_VALUE) .exclusive(TEST_TOPIC_PATTERN, TEST_TOPIC) .conditional(TEST_MODE, OptionTest.TestMode.TIMESTAMP, TEST_TIMESTAMP) .build(); }; // test duplicate assertEquals( "ErrorCode:[API-02], ErrorDescription:[Option item validate failed] - AbsolutelyRequiredOptions 'option.required-have-default' duplicate in option options.", assertThrows(OptionValidationException.class, executable).getMessage()); executable = () -> { OptionRule.builder() .optional(TEST_NUM, TEST_MODE) .exclusive(TEST_TOPIC_PATTERN, TEST_TOPIC, TEST_DUPLICATE) .required(TEST_PORTS, TEST_DUPLICATE) .conditional(TEST_MODE, OptionTest.TestMode.TIMESTAMP, TEST_TIMESTAMP) .build(); }; // test duplicate in RequiredOption$ExclusiveRequiredOptions assertEquals( "ErrorCode:[API-02], ErrorDescription:[Option item validate failed] - AbsolutelyRequiredOptions 'option.test-duplicate' duplicate in ExclusiveRequiredOptions options.", assertThrows(OptionValidationException.class, executable).getMessage()); executable = () -> { OptionRule.builder() .optional(TEST_NUM) .exclusive(TEST_TOPIC_PATTERN, TEST_TOPIC) .required(TEST_PORTS) .conditional(TEST_MODE, OptionTest.TestMode.TIMESTAMP, TEST_TIMESTAMP) .build(); }; // test conditional not found in other options assertEquals( "ErrorCode:[API-02], ErrorDescription:[Option item validate failed] - Conditional 'option.mode' not found in options.", assertThrows(OptionValidationException.class, executable).getMessage()); executable = () -> { OptionRule.builder() .optional(TEST_NUM, TEST_MODE) .exclusive(TEST_TOPIC_PATTERN, TEST_TOPIC) .required(TEST_PORTS) .conditional(TEST_MODE, OptionTest.TestMode.TIMESTAMP, TEST_TIMESTAMP) .conditional(TEST_NUM, 100, TEST_TIMESTAMP) .build(); }; // test parameter can only be controlled by one other parameter assertEquals( "ErrorCode:[API-02], ErrorDescription:[Option item validate failed] - ConditionalRequiredOptions 'option.timestamp' duplicate in ConditionalRequiredOptions options.", assertThrows(OptionValidationException.class, executable).getMessage()); }
@Override public void save(@NonNull Session session) { if (session.id() == null) { throw new IllegalArgumentException("session has no ID"); } store.put(session.id(), session); }
@Test void save_noId() { var sut = new CaffeineSessionRepo(null, Duration.ofMinutes(5)); var session = new Session(null, null, null, null, null, null, null, null, null); assertThrows(IllegalArgumentException.class, () -> sut.save(session)); }
public Response daemonLogPage(String fileName, Integer start, Integer length, String grep, String user) throws IOException, InvalidRequestException { Path file = daemonLogRoot.resolve(fileName).toAbsolutePath().normalize(); if (!file.startsWith(daemonLogRoot) || Paths.get(fileName).getNameCount() != 1) { //Prevent fileName from pathing into worker logs, or outside daemon log root return LogviewerResponseBuilder.buildResponsePageNotFound(); } if (file.toFile().exists()) { // all types of files included List<File> logFiles = Arrays.stream(daemonLogRoot.toFile().listFiles()) .filter(File::isFile) .collect(toList()); List<String> reorderedFilesStr = logFiles.stream() .map(File::getName) .filter(fName -> !StringUtils.equals(fileName, fName)) .collect(toList()); reorderedFilesStr.add(fileName); length = length != null ? Math.min(10485760, length) : LogviewerConstant.DEFAULT_BYTES_PER_PAGE; final boolean isZipFile = file.getFileName().toString().endsWith(".gz"); long fileLength = getFileLength(file.toFile(), isZipFile); if (start == null) { start = Long.valueOf(fileLength - length).intValue(); } String logString = isTxtFile(fileName) ? escapeHtml(pageFile(file.toString(), isZipFile, fileLength, start, length)) : escapeHtml("This is a binary file and cannot display! You may download the full file."); List<DomContent> bodyContents = new ArrayList<>(); if (StringUtils.isNotEmpty(grep)) { String matchedString = String.join("\n", Arrays.stream(logString.split("\n")) .filter(str -> str.contains(grep)).collect(toList())); bodyContents.add(pre(matchedString).withId("logContent")); } else { DomContent pagerData = null; if (isTxtFile(fileName)) { pagerData = pagerLinks(fileName, start, length, Long.valueOf(fileLength).intValue(), "daemonlog"); } bodyContents.add(searchFileForm(fileName, "yes")); // list all daemon logs bodyContents.add(logFileSelectionForm(reorderedFilesStr, fileName, "daemonlog")); if (pagerData != null) { bodyContents.add(pagerData); } bodyContents.add(daemonDownloadLink(fileName)); bodyContents.add(pre(logString).withClass("logContent")); if (pagerData != null) { bodyContents.add(pagerData); } } String content = logTemplate(bodyContents, fileName, user).render(); return LogviewerResponseBuilder.buildSuccessHtmlResponse(content); } else { return LogviewerResponseBuilder.buildResponsePageNotFound(); } }
@Test public void testDaemonLogPageOutsideLogRoot() throws Exception { try (TmpPath rootPath = new TmpPath()) { LogviewerLogPageHandler handler = createHandlerForTraversalTests(rootPath.getFile().toPath()); final Response returned = handler.daemonLogPage("../evil.sh", 0, 100, null, "user"); Utils.forceDelete(rootPath.toString()); //Should not show files outside daemon log root. assertThat(returned.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } }
public List<String> parse(final CharSequence line) { return this.lineParser.parse( line.toString() ); }
@Test public void testSimpleLineParse() { final CsvLineParser parser = new CsvLineParser(); final String s = "a,b,c"; final List<String> list = parser.parse(s); assertThat(list).hasSize(3).containsExactly("a", "b", "c"); }
public static LoadViewResponse fromJson(String json) { return JsonUtil.parse(json, LoadViewResponseParser::fromJson); }
@Test public void missingFields() { assertThatThrownBy(() -> LoadViewResponseParser.fromJson("{\"x\": \"val\"}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing string: metadata-location"); assertThatThrownBy( () -> LoadViewResponseParser.fromJson("{\"metadata-location\": \"custom-location\"}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing field: metadata"); }
@Override public InputFile newInputFile(String path) { return HadoopInputFile.fromLocation(path, hadoopConf.get()); }
@Test public void testFileExists() throws IOException { Path parent = new Path(tempDir.toURI()); Path randomFilePath = new Path(parent, "random-file-" + UUID.randomUUID()); fs.createNewFile(randomFilePath); // check existence of the created file assertThat(hadoopFileIO.newInputFile(randomFilePath.toUri().toString()).exists()).isTrue(); fs.delete(randomFilePath, false); assertThat(hadoopFileIO.newInputFile(randomFilePath.toUri().toString()).exists()).isFalse(); }
static void checkCompositeBatchVersion(final String configuredVersion, final Version batchVersion) throws SalesforceException { if (Version.create(configuredVersion).compareTo(batchVersion) < 0) { throw new SalesforceException( "Component is configured with Salesforce API version " + configuredVersion + ", but the payload of the Composite API batch operation requires at least " + batchVersion, 0); } }
@Test public void shouldNotAllowNewerPayloadsWhenConfiguredWithOlderVersion() throws SalesforceException { final SObjectBatch batch = new SObjectBatch(V35_0); assertThrows(SalesforceException.class, () -> DefaultCompositeApiClient.checkCompositeBatchVersion(V34_0, batch.getVersion())); }
RandomTextDataGenerator(int size, int wordSize) { this(size, DEFAULT_SEED , wordSize); }
@Test public void testRandomTextDataGenerator() { RandomTextDataGenerator rtdg = new RandomTextDataGenerator(10, 0L, 5); List<String> words = rtdg.getRandomWords(); // check the size assertEquals("List size mismatch", 10, words.size()); // check the words Set<String> wordsSet = new HashSet<String>(words); assertEquals("List size mismatch due to duplicates", 10, wordsSet.size()); // check the word lengths for (String word : wordsSet) { assertEquals("Word size mismatch", 5, word.length()); } }
@Override public boolean locatorsUpdateCopy() { return false; }
@Test void assertLocatorsUpdateCopy() { assertFalse(metaData.locatorsUpdateCopy()); }
public int controlledPoll(final ControlledFragmentHandler handler, final int fragmentLimit) { if (isClosed) { return 0; } int fragmentsRead = 0; long initialPosition = subscriberPosition.get(); int initialOffset = (int)initialPosition & termLengthMask; int offset = initialOffset; final UnsafeBuffer termBuffer = activeTermBuffer(initialPosition); final int capacity = termBuffer.capacity(); final Header header = this.header; header.buffer(termBuffer); try { while (fragmentsRead < fragmentLimit && offset < capacity) { final int length = frameLengthVolatile(termBuffer, offset); if (length <= 0) { break; } final int frameOffset = offset; final int alignedLength = BitUtil.align(length, FRAME_ALIGNMENT); offset += alignedLength; if (isPaddingFrame(termBuffer, frameOffset)) { continue; } ++fragmentsRead; header.offset(frameOffset); final Action action = handler.onFragment( termBuffer, frameOffset + HEADER_LENGTH, length - HEADER_LENGTH, header); if (ABORT == action) { --fragmentsRead; offset -= alignedLength; break; } if (BREAK == action) { break; } if (COMMIT == action) { initialPosition += (offset - initialOffset); initialOffset = offset; subscriberPosition.setOrdered(initialPosition); } } } catch (final Exception ex) { errorHandler.onError(ex); } finally { final long resultingPosition = initialPosition + (offset - initialOffset); if (resultingPosition > initialPosition) { subscriberPosition.setOrdered(resultingPosition); } } return fragmentsRead; }
@Test void shouldPollOneFragmentToControlledFragmentHandlerOnContinue() { final long initialPosition = computePosition(INITIAL_TERM_ID, 0, POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID); position.setOrdered(initialPosition); final Image image = createImage(); insertDataFrame(INITIAL_TERM_ID, offsetForFrame(0)); when(mockControlledFragmentHandler.onFragment(any(DirectBuffer.class), anyInt(), anyInt(), any(Header.class))) .thenReturn(Action.CONTINUE); final int fragmentsRead = image.controlledPoll(mockControlledFragmentHandler, Integer.MAX_VALUE); assertThat(fragmentsRead, is(1)); final InOrder inOrder = Mockito.inOrder(position, mockControlledFragmentHandler); inOrder.verify(mockControlledFragmentHandler).onFragment( any(UnsafeBuffer.class), eq(HEADER_LENGTH), eq(DATA.length), any(Header.class)); inOrder.verify(position).setOrdered(initialPosition + ALIGNED_FRAME_LENGTH); }
@Override public String getStorageAccountKey(String accountName, Configuration rawConfig) throws KeyProviderException { String envelope = super.getStorageAccountKey(accountName, rawConfig); AbfsConfiguration abfsConfig; try { abfsConfig = new AbfsConfiguration(rawConfig, accountName); } catch(IllegalAccessException | IOException e) { throw new KeyProviderException("Unable to get key from credential providers.", e); } final String command = abfsConfig.get(ConfigurationKeys.AZURE_KEY_ACCOUNT_SHELLKEYPROVIDER_SCRIPT); if (command == null) { throw new KeyProviderException( "Script path is not specified via fs.azure.shellkeyprovider.script"); } String[] cmd = command.split(" "); String[] cmdWithEnvelope = Arrays.copyOf(cmd, cmd.length + 1); cmdWithEnvelope[cmdWithEnvelope.length - 1] = envelope; String decryptedKey = null; try { decryptedKey = Shell.execCommand(cmdWithEnvelope); } catch (IOException ex) { throw new KeyProviderException(ex); } // trim any whitespace return decryptedKey.trim(); }
@Test public void testValidScript() throws Exception { if (!Shell.WINDOWS) { return; } String expectedResult = "decretedKey"; // Create a simple script which echoes the given key plus the given // expected result (so that we validate both script input and output) File scriptFile = new File(TEST_ROOT_DIR, "testScript.cmd"); FileUtils.writeStringToFile(scriptFile, "@echo %1 " + expectedResult, StandardCharsets.UTF_8); ShellDecryptionKeyProvider provider = new ShellDecryptionKeyProvider(); Configuration conf = new Configuration(); String account = "testacct"; String key = "key1"; conf.set(ConfigurationKeys.FS_AZURE_ACCOUNT_KEY_PROPERTY_NAME + account, key); conf.set(ConfigurationKeys.AZURE_KEY_ACCOUNT_SHELLKEYPROVIDER_SCRIPT, "cmd /c " + scriptFile.getAbsolutePath()); String result = provider.getStorageAccountKey(account, conf); assertEquals(key + " " + expectedResult, result); }
public static TriggerStateMachine stateMachineForTrigger(RunnerApi.Trigger trigger) { switch (trigger.getTriggerCase()) { case AFTER_ALL: return AfterAllStateMachine.of( stateMachinesForTriggers(trigger.getAfterAll().getSubtriggersList())); case AFTER_ANY: return AfterFirstStateMachine.of( stateMachinesForTriggers(trigger.getAfterAny().getSubtriggersList())); case AFTER_END_OF_WINDOW: return stateMachineForAfterEndOfWindow(trigger.getAfterEndOfWindow()); case ELEMENT_COUNT: return AfterPaneStateMachine.elementCountAtLeast( trigger.getElementCount().getElementCount()); case AFTER_SYNCHRONIZED_PROCESSING_TIME: return AfterSynchronizedProcessingTimeStateMachine.ofFirstElement(); case DEFAULT: return DefaultTriggerStateMachine.of(); case NEVER: return NeverStateMachine.ever(); case ALWAYS: return ReshuffleTriggerStateMachine.create(); case OR_FINALLY: return stateMachineForTrigger(trigger.getOrFinally().getMain()) .orFinally(stateMachineForTrigger(trigger.getOrFinally().getFinally())); case REPEAT: return RepeatedlyStateMachine.forever( stateMachineForTrigger(trigger.getRepeat().getSubtrigger())); case AFTER_EACH: return AfterEachStateMachine.inOrder( stateMachinesForTriggers(trigger.getAfterEach().getSubtriggersList())); case AFTER_PROCESSING_TIME: return stateMachineForAfterProcessingTime(trigger.getAfterProcessingTime()); case TRIGGER_NOT_SET: throw new IllegalArgumentException( String.format("Required field 'trigger' not set on %s", trigger)); default: throw new IllegalArgumentException(String.format("Unknown trigger type %s", trigger)); } }
@Test public void testAfterWatermarkEarlyTranslation() { RunnerApi.Trigger trigger = RunnerApi.Trigger.newBuilder() .setAfterEndOfWindow( RunnerApi.Trigger.AfterEndOfWindow.newBuilder().setEarlyFirings(subtrigger1)) .build(); AfterWatermarkStateMachine.AfterWatermarkEarlyAndLate machine = (AfterWatermarkStateMachine.AfterWatermarkEarlyAndLate) TriggerStateMachines.stateMachineForTrigger(trigger); assertThat( machine, equalTo(AfterWatermarkStateMachine.pastEndOfWindow().withEarlyFirings(submachine1))); }
@Operation(summary = "queryUiPluginDetailById", description = "QUERY_UI_PLUGIN_DETAIL_BY_ID") @Parameters({ @Parameter(name = "id", description = "PLUGIN_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), }) @GetMapping(value = "/{id}") @ResponseStatus(HttpStatus.CREATED) @ApiException(QUERY_PLUGINS_ERROR) public Result queryUiPluginDetailById(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @PathVariable("id") Integer pluginId) { Map<String, Object> result = uiPluginService.queryUiPluginDetailById(pluginId); return returnDataList(result); }
@Test public void testQueryUiPluginDetailById() throws Exception { when(uiPluginService.queryUiPluginDetailById(anyInt())) .thenReturn(uiPluginServiceResult); final MvcResult mvcResult = mockMvc.perform(get("/ui-plugins/{id}", pluginId) .header(SESSION_ID, sessionId)) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); }
public static HealthCheckRegistry getDefault() { final HealthCheckRegistry healthCheckRegistry = tryGetDefault(); if (healthCheckRegistry != null) { return healthCheckRegistry; } throw new IllegalStateException("Default registry name has not been set."); }
@Test public void defaultRegistryIsNotSetByDefault() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Default registry name has not been set."); SharedHealthCheckRegistries.getDefault(); }
public ConfigCenterBuilder cluster(String cluster) { this.cluster = cluster; return getThis(); }
@Test void cluster() { ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder(); builder.cluster("cluster"); Assertions.assertEquals("cluster", builder.build().getCluster()); }
@VisibleForTesting void configureCallbackInterval(Task task) { boolean isRunningForeachStep = false; boolean isMaestroTaskCreated = false; boolean isFirstPollingCycle = task != null && task.getPollCount() <= Constants.FIRST_POLLING_COUNT_LIMIT; if (task != null && task.getOutputData().containsKey(Constants.STEP_RUNTIME_SUMMARY_FIELD)) { StepRuntimeSummary runtimeSummary = StepHelper.retrieveRuntimeSummary(objectMapper, task.getOutputData()); Long callbackInSecs = stepRuntimeCallbackDelayPolicy.getCallBackDelayInSecs(runtimeSummary); if (callbackInSecs != null) { LOG.trace( "Set customized callback [{}] in seconds for step [{}]", callbackInSecs, runtimeSummary.getIdentity()); task.setCallbackAfterSeconds(callbackInSecs); } StepRuntimeState state = runtimeSummary.getRuntimeState(); isRunningForeachStep = (runtimeSummary.getType() == StepType.FOREACH && state.getStatus() == StepInstance.Status.RUNNING); isMaestroTaskCreated = state.getStatus() == StepInstance.Status.CREATED; isFirstPollingCycle = isFirstPollingCycle && state.getCreateTime() != null && System.currentTimeMillis() - state.getCreateTime() < Constants.FIRST_POLL_TIME_BUFFER_IN_MILLIS; } boolean isStartTaskStarted = task != null && Constants.DEFAULT_START_STEP_NAME.equals(task.getReferenceTaskName()); // a workaround to reduce start boostrap delay for the first few polling calls if ((isRunningForeachStep || isMaestroTaskCreated || isStartTaskStarted) && isFirstPollingCycle) { LOG.debug( "Update callback to 0 for task uuid [{}] for the first few polling calls", task.getTaskId()); task.setCallbackAfterSeconds(0); } }
@Test public void testConfigureCallBack() { Task task = new Task(); // stepRuntimeSummary object task.getOutputData() .put(Constants.STEP_RUNTIME_SUMMARY_FIELD, StepRuntimeSummary.builder().build()); when(callbackPolicy.getCallBackDelayInSecs(any())).thenReturn(30L); maestroWorkflowExecutor.configureCallbackInterval(task); verify(callbackPolicy, times(1)).getCallBackDelayInSecs(any()); assertEquals(30L, task.getCallbackAfterSeconds()); // run time summary not present task.getOutputData().clear(); task = new Task(); when(callbackPolicy.getCallBackDelayInSecs(any())).thenReturn(30L); maestroWorkflowExecutor.configureCallbackInterval(task); assertEquals(0, task.getCallbackAfterSeconds()); verify(callbackPolicy, times(1)).getCallBackDelayInSecs(any()); // null taskResult maestroWorkflowExecutor.configureCallbackInterval(null); verify(callbackPolicy, times(1)).getCallBackDelayInSecs(any()); // map object as runtime summary task.getOutputData().clear(); task.getOutputData().put(Constants.STEP_RUNTIME_SUMMARY_FIELD, new HashMap<>()); when(callbackPolicy.getCallBackDelayInSecs(any())).thenReturn(30L); maestroWorkflowExecutor.configureCallbackInterval(task); verify(callbackPolicy, times(2)).getCallBackDelayInSecs(any()); assertEquals(30L, task.getCallbackAfterSeconds()); }
List<String> liveKeysAsOrderedList() { return new ArrayList<String>(liveMap.keySet()); }
@Test public void destroy() { long now = 3000; CyclicBuffer<Object> cb = tracker.getOrCreate(key, now); cb.add(new Object()); assertEquals(1, cb.length()); tracker.endOfLife(key); now += CyclicBufferTracker.LINGERING_TIMEOUT + 10; tracker.removeStaleComponents(now); assertEquals(0, tracker.liveKeysAsOrderedList().size()); assertEquals(0, tracker.getComponentCount()); assertEquals(0, cb.length()); }
@Override public int length() { return 2; }
@Test public void testLength() { System.out.println("npara"); LogisticDistribution instance = new LogisticDistribution(2.0, 1.0); instance.rand(); assertEquals(2, instance.length()); }
@Override public boolean wasNull() throws SQLException { checkClosed(); return false; }
@Test void assertWasNull() throws SQLException { assertFalse(databaseMetaDataResultSet.wasNull()); }
public synchronized ResultSet fetchResults(FetchOrientation orientation, int maxFetchSize) { long token; switch (orientation) { case FETCH_NEXT: token = currentToken; break; case FETCH_PRIOR: token = currentToken - 1; break; default: throw new UnsupportedOperationException( String.format("Unknown fetch orientation: %s.", orientation)); } if (orientation == FetchOrientation.FETCH_NEXT && bufferedResults.isEmpty()) { // make sure data is available in the buffer resultStore.waitUntilHasData(); } return fetchResults(token, maxFetchSize); }
@Test void testFetchResultsMultipleTimesWithLimitedBufferSize() { int bufferSize = data.size() / 2; ResultFetcher fetcher = buildResultFetcher(Collections.singletonList(data.iterator()), bufferSize); int fetchSize = data.size(); runFetchMultipleTimes( bufferSize, fetchSize, token -> fetcher.fetchResults(token, fetchSize)); }
public int readInt3() { return byteBuf.readUnsignedMediumLE(); }
@Test void assertReadInt3() { when(byteBuf.readUnsignedMediumLE()).thenReturn(1); assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readInt3(), is(1)); }
Set<SourceName> analyzeExpression( final Expression expression, final String clauseType ) { final Validator extractor = new Validator(clauseType); extractor.process(expression, null); return extractor.referencedSources; }
@Test public void shouldNotThrowOnPossibleSyntheticKeyColumn() { // Given: when(sourceSchemas.isJoin()).thenReturn(true); // When: analyzer.analyzeExpression(POSSIBLE_SYNTHETIC_KEY, "SELECT"); // Then: did not throw. }
public <T extends AbstractMessageListenerContainer> T decorateMessageListenerContainer(T container) { Advice[] advice = prependTracingMessageContainerAdvice(container); if (advice != null) { container.setAdviceChain(advice); } return container; }
@Test void decorateDirectMessageListenerContainer__adds_by_default() { DirectMessageListenerContainer listenerContainer = new DirectMessageListenerContainer(); assertThat(rabbitTracing.decorateMessageListenerContainer(listenerContainer)) .extracting("adviceChain") .asInstanceOf(array(Advice[].class)) .hasSize(1); }
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String returnCommand = null; String subCommand = safeReadLine(reader, false); if (subCommand.equals(HELP_OBJECT_SUB_COMMAND_NAME)) { returnCommand = getHelpObject(reader); } else if (subCommand.equals(HELP_CLASS_SUB_COMMAND_NAME)) { returnCommand = getHelpClass(reader); } else { returnCommand = Protocol.getOutputErrorCommand("Unknown Help SubCommand Name: " + subCommand); } logger.finest("Returning command: " + returnCommand); writer.write(returnCommand); writer.flush(); }
@Test public void testHelpClassPattern() { String inputCommand = "c\n" + ExampleClass.class.getName() + "\nsm*\ntrue\ne\n"; try { assertTrue(gateway.getBindings().containsKey(target)); command.execute("h", new BufferedReader(new StringReader(inputCommand)), writer); String page = sWriter.toString(); System.out.println(page); assertTrue(page.length() > 1); assertTrue(page.contains("method1")); assertTrue(!page.contains("getField1")); } catch (Exception e) { e.printStackTrace(); fail(); } }
@Override public synchronized String toString() { if (parameters.isEmpty()) { return ""; } StringBuilder b = new StringBuilder(); char sep = '?'; for (String key : parameters.keySet()) { for (String value : parameters.get(key)) { b.append(sep); sep = '&'; try { b.append(URLEncoder.encode(key, encoding)); b.append('='); b.append(URLEncoder.encode(value, encoding)); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Cannot URL-encode query string (key=" + key + "; value=" + value + ").", e); } } } return b.toString(); }
@Test public void testKeepProtocolUpperCase() { QueryString qs = new QueryString( "http://site.com/page?NoEquals&WithEquals=EqualsValue"); Assert.assertTrue("Argument without equal sign was not found.", qs.toString().contains("NoEquals")); }
@Udf public <T> List<T> slice( @UdfParameter(description = "the input array") final List<T> in, @UdfParameter(description = "start index") final Integer from, @UdfParameter(description = "end index") final Integer to) { if (in == null) { return null; } try { // SQL systems are usually 1-indexed and are inclusive of end index final int start = from == null ? 0 : from - 1; final int end = to == null ? in.size() : to; return in.subList(start, end); } catch (final IndexOutOfBoundsException e) { return null; } }
@Test public void shouldFullListOnNullEndpoints() { // Given: final List<String> list = Lists.newArrayList("a", "b", "c"); // When: final List<String> slice = new Slice().slice(list, null, null); // Then: assertThat(slice, is(Lists.newArrayList("a", "b", "c"))); }
@Override public void changeLogLevel(LoggerLevel level) { requireNonNull(level, "level can't be null"); call(new ChangeLogLevelActionClient(level)); }
@Test public void changeLogLevel_throws_ISE_if_http_error() { String message = "blah"; server.enqueue(new MockResponse().setResponseCode(500).setBody(message)); // initialize registration of process setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE); assertThatThrownBy(() -> underTest.changeLogLevel(LoggerLevel.DEBUG)) .isInstanceOf(IllegalStateException.class) .hasMessage("Failed to call HTTP server of process " + ProcessId.COMPUTE_ENGINE) .hasRootCauseInstanceOf(IOException.class) .hasRootCauseMessage(format("Failed to change log level in Compute Engine. Code was '500' and response was 'blah' for url " + "'http://%s:%s/changeLogLevel'", server.getHostName(), server.getPort())); }
static Object math(Object left, Object right, EvaluationContext ctx, BinaryOperator<BigDecimal> op) { BigDecimal l = left instanceof String ? null : NumberEvalHelper.getBigDecimalOrNull(left); BigDecimal r = right instanceof String ? null : NumberEvalHelper.getBigDecimalOrNull(right); if (l == null || r == null) { return null; } try { return op.apply(l, r); } catch (ArithmeticException e) { // happens in cases like division by 0 ctx.notifyEvt(() -> new InvalidParametersEvent(FEELEvent.Severity.ERROR, Msg.createMessage(Msg.GENERAL_ARITHMETIC_EXCEPTION, e.getMessage()))); return null; } }
@Test void math_BothNumbers() { final Random rnd = new Random(); MATH_OPERATORS.forEach(operator -> { BigDecimal left = BigDecimal.valueOf(rnd.nextDouble()); BigDecimal right = BigDecimal.valueOf(rnd.nextDouble()); BigDecimal expected = operator.apply(left, right); Object retrieved = math(left, right, null, operator); assertThat(retrieved).isNotNull() .isInstanceOf(BigDecimal.class) .isEqualTo(expected); }); }
@Override public final MetadataResolver resolve(final boolean force) { if (force) { this.metadataResolver = prepareServiceProviderMetadata(); } return this.metadataResolver; }
@Test public void resolveServiceProviderMetadataViaFile() { val configuration = initializeConfiguration(new FileSystemResource("target/out.xml"), "target/keystore.jks"); final SAML2MetadataResolver metadataResolver = new SAML2ServiceProviderMetadataResolver(configuration); assertNotNull(metadataResolver.resolve()); }
public BlockLease flatten(Block block) { requireNonNull(block, "block is null"); if (block instanceof DictionaryBlock) { return flattenDictionaryBlock((DictionaryBlock) block); } if (block instanceof RunLengthEncodedBlock) { return flattenRunLengthEncodedBlock((RunLengthEncodedBlock) block); } return newLease(block); }
@Test public void testLongArrayIdentityDecode() { Block block = createLongArrayBlock(1, 2, 3, 4); try (BlockLease blockLease = flattener.flatten(block)) { Block flattenedBlock = blockLease.get(); assertSame(flattenedBlock, block); } }
public IntValue increment(int increment) { this.value += increment; this.set = true; return this; }
@Test public void multiples_calls_to_increment_int_increment_the_value() { IntValue value = new IntValue() .increment(10) .increment(95); verifySetValue(value, 105); }
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testGoMod() throws AnalysisException, InitializationException { analyzer.prepare(engine); final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "golang/go.mod")); analyzer.analyze(result, engine); assertEquals(7, engine.getDependencies().length); boolean found = false; for (Dependency d : engine.getDependencies()) { if ("gitea".equals(d.getName())) { found = true; assertEquals("1.5.0", d.getVersion()); assertEquals("github.com/go-gitea/gitea:1.5.0", d.getDisplayFileName()); assertEquals(GolangModAnalyzer.DEPENDENCY_ECOSYSTEM, d.getEcosystem()); assertTrue(d.getEvidence(EvidenceType.VENDOR).toString().toLowerCase().contains("go-gitea")); assertTrue(d.getEvidence(EvidenceType.PRODUCT).toString().toLowerCase().contains("gitea")); assertTrue(d.getEvidence(EvidenceType.VERSION).toString().toLowerCase().contains("1.5.0")); } } assertTrue("Expected to find gitea/gitea", found); }
public Optional<UpdateCenter> getUpdateCenter() { return getUpdateCenter(false); }
@Test public void update_center_is_null_when_property_is_false() { settings.setProperty(ProcessProperties.Property.SONAR_UPDATECENTER_ACTIVATE.getKey(), false); assertThat(underTest.getUpdateCenter()).isEmpty(); }
public static void deleteIfExists(final File file) { try { Files.deleteIfExists(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
@Test void deleteIfExistsFile() throws IOException { final Path file = tempDir.resolve("delete-me.txt"); Files.createFile(file); IoUtil.deleteIfExists(file.toFile()); assertFalse(Files.exists(file)); }
@Override public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) { log.debug( "sort catalogue tree based on creation time. catalogueTree: {}, sortTypeEnum: {}", catalogueTree, sortTypeEnum); return recursionSortCatalogues(catalogueTree, sortTypeEnum); }
@Test public void sortDescTest() { SortTypeEnum sortTypeEnum = SortTypeEnum.DESC; List<Catalogue> catalogueTree = Lists.newArrayList(); Catalogue catalogue = new Catalogue(); catalogue.setId(1); catalogue.setCreateTime(LocalDateTime.of(2024, 4, 28, 19, 22, 0)); Catalogue catalogue11 = new Catalogue(); catalogue11.setId(2); catalogue11.setCreateTime(LocalDateTime.of(2024, 4, 28, 20, 22, 0)); Catalogue catalogue12 = new Catalogue(); catalogue12.setId(3); catalogue12.setCreateTime(LocalDateTime.of(2024, 4, 28, 21, 22, 0)); catalogue.setChildren(Lists.newArrayList(catalogue12, catalogue11)); Catalogue catalogue2 = new Catalogue(); catalogue2.setId(4); catalogue2.setCreateTime(LocalDateTime.of(2024, 4, 29, 19, 22, 0)); Catalogue catalogue21 = new Catalogue(); catalogue21.setId(7); catalogue21.setCreateTime(LocalDateTime.of(2024, 4, 29, 21, 22, 0)); Catalogue catalogue22 = new Catalogue(); catalogue22.setId(6); catalogue22.setCreateTime(LocalDateTime.of(2024, 4, 29, 20, 22, 0)); catalogue2.setChildren(Lists.newArrayList(catalogue21, catalogue22)); catalogueTree.add(catalogue2); catalogueTree.add(catalogue); /* input: -- 4 (2024-04-29 19:22:00) -- 7 (2024-04-29 21:22:00) -- 6 (2024-04-29 20:22:00) -- 1 (2024-04-28 19:22:00) -- 3 (2024-04-28 21:22:00) -- 2 (2024-04-28 20:22:00) output: -- 4 (2024-04-29 19:22:00) -- 7 (2024-04-29 21:22:00) -- 6 (2024-04-29 20:22:00) -- 1 (2024-04-28 19:22:00) -- 3 (2024-04-28 21:22:00) -- 2 (2024-04-28 20:22:00) */ List<Catalogue> resultList = catalogueTreeSortCreateTimeStrategyTest.sort(catalogueTree, sortTypeEnum); List<Integer> resultIdList = CategoryTreeSortStrategyTestUtils.breadthTraverse(resultList); assertEquals(Lists.newArrayList(4, 1, 7, 6, 3, 2), resultIdList); }
public HealthCheckResponse checkHealth() { final Map<String, HealthCheckResponseDetail> results = DEFAULT_CHECKS.stream() .collect(Collectors.toMap( Check::getName, check -> check.check(this) )); final boolean allHealthy = results.values().stream() .allMatch(HealthCheckResponseDetail::getIsHealthy); final State serverState = commandRunner.checkServerState(); return new HealthCheckResponse(allHealthy, results, Optional.of(serverState.toString())); }
@Test public void shouldReturnUnhealthyIfMetastoreCheckFails() { // Given: when(ksqlClient.makeKsqlRequest(SERVER_URI, "list streams; list tables; list queries;", REQUEST_PROPERTIES)) .thenReturn(unSuccessfulResponse); // When: final HealthCheckResponse response = healthCheckAgent.checkHealth(); // Then: assertThat(response.getDetails().get(METASTORE_CHECK_NAME).getIsHealthy(), is(false)); assertThat(response.getIsHealthy(), is(false)); }
public static Builder newBuilder() { return new Builder(); }
@Test void spanHandlers_clearAndAdd() { SpanHandler one = mock(SpanHandler.class); SpanHandler two = mock(SpanHandler.class); SpanHandler three = mock(SpanHandler.class); Tracing.Builder builder = Tracing.newBuilder() .addSpanHandler(one) .addSpanHandler(two) .addSpanHandler(three); Set<SpanHandler> spanHandlers = builder.spanHandlers(); builder.clearSpanHandlers(); spanHandlers.forEach(builder::addSpanHandler); assertThat(builder) .usingRecursiveComparison() .isEqualTo(Tracing.newBuilder() .addSpanHandler(one) .addSpanHandler(two) .addSpanHandler(three)); }