method2testcases stringlengths 118 6.63k |
|---|
### Question:
Yaml { public static Object load(String content) throws IOException { return load(new StringReader(content)); } static Object load(String content); static Object load(File f); static Object load(Reader reader); static T loadAs(String content, Class<T> clazz); static T loadAs(File f, Class<T> clazz); static T loadAs(Reader reader, Class<T> clazz); static List<Object> loadAll(String content); static List<Object> loadAll(File f); static List<Object> loadAll(Reader reader); static String dump(Object object); static void dump(Object object, Writer writer); static String dumpAll(Iterator<? extends KubernetesType> data); static void dumpAll(Iterator<? extends KubernetesType> data, Writer output); static org.yaml.snakeyaml.Yaml getSnakeYaml(); @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); }### Answer:
@Test public void testLoad() { for (int i = 0; i < kinds.length; i++) { String className = classNames[i]; try { Object obj = Yaml.load( new StringReader(input.replace("XXXX", kinds[i]).replace("YYYY", apiVersions[i]))); Method m = obj.getClass().getMethod("getMetadata"); V1ObjectMeta metadata = (V1ObjectMeta) m.invoke(obj); assertEquals("foo", metadata.getName()); assertEquals(className, obj.getClass().getSimpleName()); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } } } |
### Question:
LeaderElectingController implements Controller { public LeaderElectingController(LeaderElector leaderElector, Controller delegateController) { this.delegateController = delegateController; this.leaderElector = leaderElector; } LeaderElectingController(LeaderElector leaderElector, Controller delegateController); @Override void shutdown(); @Override void run(); }### Answer:
@Test public void testLeaderElectingController() throws ApiException { AtomicReference<LeaderElectionRecord> record = new AtomicReference<>(); record.set(new LeaderElectionRecord()); when(mockLock.identity()).thenReturn("foo"); doAnswer(invocationOnMock -> record.get()).when(mockLock).get(); doAnswer( invocationOnMock -> { record.set(invocationOnMock.getArgument(0)); return true; }) .when(mockLock) .create(any()); doReturn(false).when(mockLock).update(any()); LeaderElectingController leaderElectingController = new LeaderElectingController( new LeaderElector( new LeaderElectionConfig( mockLock, Duration.ofMillis(300), Duration.ofMillis(200), Duration.ofMillis(100))), mockController); Thread controllerThread = new Thread(leaderElectingController::run); controllerThread.start(); cooldown(); controllerThread.interrupt(); verify(mockLock, times(1)).create(any()); verify(mockLock, atLeastOnce()).update(any()); verify(mockController, times(1)).run(); verify(mockController, times(1)).shutdown(); } |
### Question:
DefaultControllerBuilder { public Controller build() throws IllegalStateException { if (this.reconciler == null) { throw new IllegalStateException("Missing reconciler when building controller."); } DefaultController controller = new DefaultController( this.reconciler, this.workQueue, this.readyFuncs.stream().toArray(Supplier[]::new)); controller.setName(this.controllerName); controller.setWorkerCount(this.workerCount); controller.setWorkerThreadPool( Executors.newScheduledThreadPool( this.workerCount, Controllers.namedControllerThreadFactory(this.controllerName))); controller.setReconciler(this.reconciler); return controller; } DefaultControllerBuilder(); DefaultControllerBuilder(SharedInformerFactory informerFactory); DefaultControllerBuilder watch(
Function<WorkQueue<Request>, ControllerWatch<ApiType>> controllerWatchGetter); DefaultControllerBuilder withName(String controllerName); DefaultControllerBuilder withWorkQueue(RateLimitingQueue<Request> workQueue); DefaultControllerBuilder withReadyFunc(Supplier<Boolean> readyFunc); DefaultControllerBuilder withWorkerCount(int workerCount); DefaultControllerBuilder withReconciler(Reconciler reconciler); Controller build(); }### Answer:
@Test(expected = IllegalStateException.class) public void testDummyBuildShouldFail() { ControllerBuilder.defaultBuilder(informerFactory).build(); } |
### Question:
KubectlDrain extends KubectlCordon { @Override public V1Node execute() throws KubectlException { try { return doDrain(); } catch (ApiException | IOException ex) { throw new KubectlException(ex); } } KubectlDrain(); KubectlDrain gracePeriod(int gracePeriodSeconds); KubectlDrain force(); KubectlDrain ignoreDaemonSets(); @Override V1Node execute(); }### Answer:
@Test public void testDrainNodeNoPods() throws KubectlException, IOException { wireMockRule.stubFor( patch(urlPathEqualTo("/api/v1/nodes/node1")) .willReturn( aResponse().withStatus(200).withBody("{\"metadata\": { \"name\": \"node1\" } }"))); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/pods")) .withQueryParam("fieldSelector", equalTo("spec.nodeName=node1")) .willReturn(aResponse().withStatus(200).withBody("{}"))); V1Node node = new KubectlDrain().apiClient(apiClient).name("node1").execute(); wireMockRule.verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/nodes/node1"))); wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/api/v1/pods"))); assertEquals("node1", node.getMetadata().getName()); }
@Test public void testDrainNodePods() throws KubectlException, IOException { wireMockRule.stubFor( patch(urlPathEqualTo("/api/v1/nodes/node1")) .willReturn( aResponse().withStatus(200).withBody("{\"metadata\": { \"name\": \"node1\" } }"))); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/pods")) .withQueryParam("fieldSelector", equalTo("spec.nodeName=node1")) .willReturn( aResponse() .withStatus(200) .withBody(new String(Files.readAllBytes(Paths.get(POD_LIST_API)))))); wireMockRule.stubFor( delete(urlPathEqualTo("/api/v1/namespaces/mssql/pods/mssql-75b8b44f6b-znftp")) .willReturn(aResponse().withStatus(200).withBody("{}"))); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/mssql/pods/mssql-75b8b44f6b-znftp")) .willReturn(aResponse().withStatus(404).withBody("{}"))); V1Node node = new KubectlDrain().apiClient(apiClient).name("node1").execute(); wireMockRule.verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/nodes/node1"))); wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/api/v1/pods"))); wireMockRule.verify( 1, deleteRequestedFor(urlPathEqualTo("/api/v1/namespaces/mssql/pods/mssql-75b8b44f6b-znftp"))); wireMockRule.verify( 1, getRequestedFor(urlPathEqualTo("/api/v1/namespaces/mssql/pods/mssql-75b8b44f6b-znftp"))); assertEquals("node1", node.getMetadata().getName()); assertEquals(0, findUnmatchedRequests().size()); } |
### Question:
Yaml { public static List<Object> loadAll(String content) throws IOException { return loadAll(new StringReader(content)); } static Object load(String content); static Object load(File f); static Object load(Reader reader); static T loadAs(String content, Class<T> clazz); static T loadAs(File f, Class<T> clazz); static T loadAs(Reader reader, Class<T> clazz); static List<Object> loadAll(String content); static List<Object> loadAll(File f); static List<Object> loadAll(Reader reader); static String dump(Object object); static void dump(Object object, Writer writer); static String dumpAll(Iterator<? extends KubernetesType> data); static void dumpAll(Iterator<? extends KubernetesType> data, Writer output); static org.yaml.snakeyaml.Yaml getSnakeYaml(); @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); }### Answer:
@Test public void testLoadAll() throws IOException { StringBuilder sb = new StringBuilder(); for (int i = 0; i < kinds.length; i++) { sb.append(input.replace("XXXX", kinds[i]).replace("YYYY", apiVersions[i])); sb.append("\n---\n"); } List<Object> list = null; list = (List<Object>) Yaml.loadAll(sb.toString()); for (int i = 0; i < kinds.length; i++) { String className = classNames[i]; try { Object obj = list.get(i); Method m = obj.getClass().getMethod("getMetadata"); V1ObjectMeta metadata = (V1ObjectMeta) m.invoke(obj); assertEquals("foo", metadata.getName()); assertEquals(className, obj.getClass().getSimpleName()); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } } } |
### Question:
Yaml { public static <T> T loadAs(String content, Class<T> clazz) { return getSnakeYaml().loadAs(new StringReader(content), clazz); } static Object load(String content); static Object load(File f); static Object load(Reader reader); static T loadAs(String content, Class<T> clazz); static T loadAs(File f, Class<T> clazz); static T loadAs(Reader reader, Class<T> clazz); static List<Object> loadAll(String content); static List<Object> loadAll(File f); static List<Object> loadAll(Reader reader); static String dump(Object object); static void dump(Object object, Writer writer); static String dumpAll(Iterator<? extends KubernetesType> data); static void dumpAll(Iterator<? extends KubernetesType> data, Writer output); static org.yaml.snakeyaml.Yaml getSnakeYaml(); @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); }### Answer:
@Test public void testLoadIntOrString() { try { String strInput = "targetPort: test"; String intInput = "targetPort: 1"; V1ServicePort stringPort = Yaml.loadAs(strInput, V1ServicePort.class); V1ServicePort intPort = Yaml.loadAs(intInput, V1ServicePort.class); assertFalse( "Target port for 'stringPort' was parsed to an integer, string expected.", stringPort.getTargetPort().isInteger()); assertEquals("test", stringPort.getTargetPort().getStrValue()); assertTrue( "Target port for 'intPort' was parsed to a string, integer expected.", intPort.getTargetPort().isInteger()); assertEquals(1L, (long) intPort.getTargetPort().getIntValue()); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } }
@Test public void testLoadBytes() { try { String strInput = "data:\n hello: aGVsbG8="; V1Secret secret = Yaml.loadAs(strInput, V1Secret.class); assertEquals( "Incorrect value loaded for Base64 encoded secret", "hello", new String(secret.getData().get("hello"), UTF_8)); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } }
@Test public void testDateTime() { try { String strInput = "apiVersion: v1\n" + "kind: Pod\n" + "metadata:\n" + " creationTimestamp: 2018-09-06T15:12:24Z"; V1Pod pod = Yaml.loadAs(strInput, V1Pod.class); assertEquals( "Incorrect value loaded for creationTimestamp", "2018-09-06T15:12:24.000Z", new String(pod.getMetadata().getCreationTimestamp().toString().getBytes(), UTF_8)); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } } |
### Question:
AccessTokenAuthentication implements Authentication { @Override public void provide(ApiClient client) { client.setApiKeyPrefix("Bearer"); client.setApiKey(token); } AccessTokenAuthentication(final String token); @Override void provide(ApiClient client); }### Answer:
@Test public void testTokenProvided() { final ApiClient client = new ApiClient(); new AccessTokenAuthentication("token").provide(client); assertThat(getApiKeyAuthFromClient(client).getApiKeyPrefix(), is("Bearer")); assertThat(getApiKeyAuthFromClient(client).getApiKey(), is("token")); } |
### Question:
ClientCertificateAuthentication implements Authentication { @Override public void provide(ApiClient client) { String dataString = new String(key); String algo = ""; if (dataString.indexOf("BEGIN EC PRIVATE KEY") != -1) { algo = "EC"; } if (dataString.indexOf("BEGIN RSA PRIVATE KEY") != -1) { algo = "RSA"; } try { final KeyManager[] keyManagers = SSLUtils.keyManagers(certificate, key, algo, "", null, null); client.setKeyManagers(keyManagers); } catch (NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | KeyStoreException | InvalidKeySpecException | IOException e) { log.warn("Could not create key manager for Client Certificate authentication.", e); throw new RuntimeException(e); } } ClientCertificateAuthentication(final byte[] certificate, final byte[] key); @Override void provide(ApiClient client); }### Answer:
@Test public void testValidCertificates() throws Exception { final ApiClient client = new ApiClient(); final byte[] certificate = Files.readAllBytes(Paths.get(CLIENT_CERT_PATH)); final byte[] key = Files.readAllBytes(Paths.get(CLIENT_KEY_PATH)); new ClientCertificateAuthentication(certificate, key).provide(client); }
@Test(expected = RuntimeException.class) public void testInvalidCertificates() { final ApiClient client = new ApiClient(); new ClientCertificateAuthentication(new byte[] {}, new byte[] {}).provide(client); }
@Test public void testValidECCertificates() throws Exception { try { final ApiClient client = new ApiClient(); final byte[] certificate = Files.readAllBytes(Paths.get(CLIENT_EC_CERT_PATH)); final byte[] key = Files.readAllBytes(Paths.get(CLIENT_EC_KEY_PATH)); new ClientCertificateAuthentication(certificate, key).provide(client); } catch (Exception ex) { ex.printStackTrace(); } }
@Test public void testValidCertificatesChain() throws Exception { try { final ApiClient client = new ApiClient(); final byte[] certificate = Files.readAllBytes(Paths.get(CLIENT_CERT_CHAIN_PATH)); final byte[] key = Files.readAllBytes(Paths.get(CLIENT_CERT_CHAIN_KEY_PATH)); new ClientCertificateAuthentication(certificate, key).provide(client); } catch (Exception ex) { ex.printStackTrace(); } }
@Test public void testValidOldECCertificates() throws Exception { try { final ApiClient client = new ApiClient(); final byte[] certificate = Files.readAllBytes(Paths.get(CLIENT_EC_CERT_PATH)); final byte[] key = Files.readAllBytes(Paths.get(CLIENT_EC_KEY_OLD_PATH)); new ClientCertificateAuthentication(certificate, key).provide(client); } catch (Exception ex) { ex.printStackTrace(); } } |
### Question:
UsernamePasswordAuthentication implements Authentication { @Override public void provide(ApiClient client) { final String usernameAndPassword = username + ":" + password; client.setApiKeyPrefix("Basic"); client.setApiKey( ByteString.of(usernameAndPassword.getBytes(StandardCharsets.ISO_8859_1)).base64()); } UsernamePasswordAuthentication(final String username, final String password); @Override void provide(ApiClient client); }### Answer:
@Test public void testUsernamePasswordProvided() { final ApiClient client = new ApiClient(); new UsernamePasswordAuthentication(USERNAME, PASSWORD).provide(client); assertThat(getApiKeyAuthFromClient(client).getApiKeyPrefix(), is("Basic")); assertThat( getApiKeyAuthFromClient(client).getApiKey(), is(ByteString.of(USERNAME_PASSWORD_BYTES).base64())); } |
### Question:
Labels { public static void addLabels(KubernetesObject kubernetesObject, String label, String value) { Map<String, String> mergingLabels = new HashMap<>(); mergingLabels.put(label, value); addLabels(kubernetesObject, mergingLabels); } static void addLabels(KubernetesObject kubernetesObject, String label, String value); static void addLabels(
KubernetesObject kubernetesObject, Map<String, String> mergingLabels); }### Answer:
@Test public void testAddLabels() { V1Pod pod = new V1Pod().metadata(new V1ObjectMeta()); Labels.addLabels(pod, "foo", "bar"); assertEquals(pod.getMetadata().getLabels().get("foo"), "bar"); }
@Test public void testAddMultipleLabels() { V1Pod pod = new V1Pod().metadata(new V1ObjectMeta()); Map<String, String> newLabels = new HashMap<>(); newLabels.put("foo1", "bar1"); newLabels.put("foo2", "bar2"); Labels.addLabels(pod, newLabels); assertEquals(pod.getMetadata().getLabels().get("foo1"), "bar1"); assertEquals(pod.getMetadata().getLabels().get("foo2"), "bar2"); } |
### Question:
Config { public static ApiClient defaultClient() throws IOException { return ClientBuilder.standard().build(); } static ApiClient fromCluster(); static ApiClient fromUrl(String url); static ApiClient fromUrl(String url, boolean validateSSL); static ApiClient fromUserPassword(String url, String user, String password); static ApiClient fromUserPassword(
String url, String user, String password, boolean validateSSL); static ApiClient fromToken(String url, String token); static ApiClient fromToken(String url, String token, boolean validateSSL); static ApiClient fromConfig(String fileName); static ApiClient fromConfig(InputStream stream); static ApiClient fromConfig(Reader input); static ApiClient fromConfig(KubeConfig config); static ApiClient defaultClient(); static final String SERVICEACCOUNT_ROOT; static final String SERVICEACCOUNT_CA_PATH; static final String SERVICEACCOUNT_TOKEN_PATH; static final String ENV_KUBECONFIG; static final String ENV_SERVICE_HOST; static final String ENV_SERVICE_PORT; static final String DEFAULT_FALLBACK_HOST; }### Answer:
@Test public void testDefaultClientNothingPresent() { environmentVariables.set("HOME", "/non-existent"); try { ApiClient client = Config.defaultClient(); assertEquals("http: } catch (IOException ex) { fail("Unexpected exception: " + ex); } }
@Test public void testDefaultClientHomeDir() { try { environmentVariables.set("HOME", dir.getCanonicalPath()); ApiClient client = Config.defaultClient(); assertEquals("http: } catch (Exception ex) { ex.printStackTrace(); fail("Unexpected exception: " + ex); } }
@Test public void testDefaultClientKubeConfig() { try { environmentVariables.set("KUBECONFIG", configFile.getCanonicalPath()); ApiClient client = Config.defaultClient(); assertEquals("http: } catch (Exception ex) { ex.printStackTrace(); fail("Unexpected exception: " + ex); } }
@Test public void testDefaultClientPrecedence() { try { environmentVariables.set("HOME", dir.getCanonicalPath()); environmentVariables.set("KUBECONFIG", configFile.getCanonicalPath()); ApiClient client = Config.defaultClient(); assertEquals("http: } catch (Exception ex) { ex.printStackTrace(); fail("Unexpected exception: " + ex); } } |
### Question:
Watch implements Watchable<T>, Closeable { protected Response<T> parseLine(String line) throws IOException { if (!isStatus(line)) { return json.deserialize(line, watchType); } Type statusType = new TypeToken<Response<V1Status>>() {}.getType(); Response<V1Status> status = json.deserialize(line, statusType); return new Response<T>(status.type, status.object); } protected Watch(JSON json, ResponseBody body, Type watchType, Call call); static Watch<T> createWatch(ApiClient client, Call call, Type watchType); Response<T> next(); boolean hasNext(); Iterator<Response<T>> iterator(); void remove(); void close(); }### Answer:
@Test public void testWatchEnd() throws IOException { JSON json = new JSON(); Watch<V1ConfigMap> watch = new Watch<V1ConfigMap>( json, null, new TypeToken<Watch.Response<V1ConfigMap>>() {}.getType(), null); JsonObject metadata = new JsonObject(); metadata.addProperty("name", "foo"); metadata.addProperty("namespace", "bar"); JsonObject status = new JsonObject(); status.add("metadata", metadata); status.addProperty("kind", "Status"); status.addProperty("apiVersion", "v1"); status.addProperty("status", "failure"); status.addProperty("message", "too old resource version"); status.addProperty("reason", "Gone"); status.addProperty("code", 410); JsonObject obj = new JsonObject(); obj.addProperty("type", "ERROR"); obj.add("object", status); String data = json.getGson().toJson(obj); Watch.Response<V1ConfigMap> response = watch.parseLine(data); assertEquals(null, response.object); } |
### Question:
GenericKubernetesApi { public KubernetesApiResponse<ApiType> create(ApiType object) { return create(object, new CreateOptions()); } GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
ApiClient apiClient); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
CustomObjectsApi customObjectsApi); KubernetesApiResponse<ApiType> get(String name); KubernetesApiResponse<ApiType> get(String namespace, String name); KubernetesApiResponse<ApiListType> list(); KubernetesApiResponse<ApiListType> list(String namespace); KubernetesApiResponse<ApiType> create(ApiType object); KubernetesApiResponse<ApiType> update(ApiType object); KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> patch(
String namespace, String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> delete(String name); KubernetesApiResponse<ApiType> delete(String namespace, String name); Watchable<ApiType> watch(); Watchable<ApiType> watch(String namespace); KubernetesApiResponse<ApiType> get(String name, final GetOptions getOptions); KubernetesApiResponse<ApiType> get(
String namespace, String name, final GetOptions getOptions); KubernetesApiResponse<ApiListType> list(final ListOptions listOptions); KubernetesApiResponse<ApiListType> list(String namespace, final ListOptions listOptions); KubernetesApiResponse<ApiType> create(ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> create(
String namespace, ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> update(ApiType object, final UpdateOptions updateOptions); KubernetesApiResponse<ApiType> patch(
String name, String patchType, V1Patch patch, final PatchOptions patchOptions); KubernetesApiResponse<ApiType> patch(
String namespace,
String name,
String patchType,
V1Patch patch,
final PatchOptions patchOptions); KubernetesApiResponse<ApiType> delete(String name, final DeleteOptions deleteOptions); KubernetesApiResponse<ApiType> delete(
String namespace, String name, final DeleteOptions deleteOptions); Watchable<ApiType> watch(final ListOptions listOptions); Watchable<ApiType> watch(String namespace, final ListOptions listOptions); }### Answer:
@Test public void createNamespacedJobReturningObject() { V1Job foo1 = new V1Job().kind("Job").metadata(new V1ObjectMeta().namespace("default").name("foo1")); stubFor( post(urlEqualTo("/apis/batch/v1/namespaces/default/jobs")) .willReturn(aResponse().withStatus(200).withBody(new Gson().toJson(foo1)))); KubernetesApiResponse<V1Job> jobListResp = jobClient.create(foo1); assertTrue(jobListResp.isSuccess()); assertEquals(foo1, jobListResp.getObject()); assertNull(jobListResp.getStatus()); verify(1, postRequestedFor(urlPathEqualTo("/apis/batch/v1/namespaces/default/jobs"))); } |
### Question:
GenericKubernetesApi { public KubernetesApiResponse<ApiType> update(ApiType object) { return update(object, new UpdateOptions()); } GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
ApiClient apiClient); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
CustomObjectsApi customObjectsApi); KubernetesApiResponse<ApiType> get(String name); KubernetesApiResponse<ApiType> get(String namespace, String name); KubernetesApiResponse<ApiListType> list(); KubernetesApiResponse<ApiListType> list(String namespace); KubernetesApiResponse<ApiType> create(ApiType object); KubernetesApiResponse<ApiType> update(ApiType object); KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> patch(
String namespace, String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> delete(String name); KubernetesApiResponse<ApiType> delete(String namespace, String name); Watchable<ApiType> watch(); Watchable<ApiType> watch(String namespace); KubernetesApiResponse<ApiType> get(String name, final GetOptions getOptions); KubernetesApiResponse<ApiType> get(
String namespace, String name, final GetOptions getOptions); KubernetesApiResponse<ApiListType> list(final ListOptions listOptions); KubernetesApiResponse<ApiListType> list(String namespace, final ListOptions listOptions); KubernetesApiResponse<ApiType> create(ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> create(
String namespace, ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> update(ApiType object, final UpdateOptions updateOptions); KubernetesApiResponse<ApiType> patch(
String name, String patchType, V1Patch patch, final PatchOptions patchOptions); KubernetesApiResponse<ApiType> patch(
String namespace,
String name,
String patchType,
V1Patch patch,
final PatchOptions patchOptions); KubernetesApiResponse<ApiType> delete(String name, final DeleteOptions deleteOptions); KubernetesApiResponse<ApiType> delete(
String namespace, String name, final DeleteOptions deleteOptions); Watchable<ApiType> watch(final ListOptions listOptions); Watchable<ApiType> watch(String namespace, final ListOptions listOptions); }### Answer:
@Test public void updateNamespacedJobReturningObject() { V1Job foo1 = new V1Job().kind("Job").metadata(new V1ObjectMeta().namespace("default").name("foo1")); stubFor( put(urlEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1")) .willReturn(aResponse().withStatus(200).withBody(new Gson().toJson(foo1)))); KubernetesApiResponse<V1Job> jobListResp = jobClient.update(foo1); assertTrue(jobListResp.isSuccess()); assertEquals(foo1, jobListResp.getObject()); assertNull(jobListResp.getStatus()); verify(1, putRequestedFor(urlPathEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1"))); } |
### Question:
GenericKubernetesApi { public KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch) { return patch(name, patchType, patch, new PatchOptions()); } GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
ApiClient apiClient); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
CustomObjectsApi customObjectsApi); KubernetesApiResponse<ApiType> get(String name); KubernetesApiResponse<ApiType> get(String namespace, String name); KubernetesApiResponse<ApiListType> list(); KubernetesApiResponse<ApiListType> list(String namespace); KubernetesApiResponse<ApiType> create(ApiType object); KubernetesApiResponse<ApiType> update(ApiType object); KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> patch(
String namespace, String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> delete(String name); KubernetesApiResponse<ApiType> delete(String namespace, String name); Watchable<ApiType> watch(); Watchable<ApiType> watch(String namespace); KubernetesApiResponse<ApiType> get(String name, final GetOptions getOptions); KubernetesApiResponse<ApiType> get(
String namespace, String name, final GetOptions getOptions); KubernetesApiResponse<ApiListType> list(final ListOptions listOptions); KubernetesApiResponse<ApiListType> list(String namespace, final ListOptions listOptions); KubernetesApiResponse<ApiType> create(ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> create(
String namespace, ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> update(ApiType object, final UpdateOptions updateOptions); KubernetesApiResponse<ApiType> patch(
String name, String patchType, V1Patch patch, final PatchOptions patchOptions); KubernetesApiResponse<ApiType> patch(
String namespace,
String name,
String patchType,
V1Patch patch,
final PatchOptions patchOptions); KubernetesApiResponse<ApiType> delete(String name, final DeleteOptions deleteOptions); KubernetesApiResponse<ApiType> delete(
String namespace, String name, final DeleteOptions deleteOptions); Watchable<ApiType> watch(final ListOptions listOptions); Watchable<ApiType> watch(String namespace, final ListOptions listOptions); }### Answer:
@Test public void patchNamespacedJobReturningObject() { V1Patch v1Patch = new V1Patch("{}"); V1Job foo1 = new V1Job().kind("Job").metadata(new V1ObjectMeta().namespace("default").name("foo1")); stubFor( patch(urlEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1")) .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH)) .willReturn(aResponse().withStatus(200).withBody(new Gson().toJson(foo1)))); KubernetesApiResponse<V1Job> jobPatchResp = jobClient.patch("default", "foo1", V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, v1Patch); assertTrue(jobPatchResp.isSuccess()); assertEquals(foo1, jobPatchResp.getObject()); assertNull(jobPatchResp.getStatus()); verify(1, patchRequestedFor(urlPathEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1"))); } |
### Question:
GenericKubernetesApi { public KubernetesApiResponse<ApiType> get(String name) { return get(name, new GetOptions()); } GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
ApiClient apiClient); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
CustomObjectsApi customObjectsApi); KubernetesApiResponse<ApiType> get(String name); KubernetesApiResponse<ApiType> get(String namespace, String name); KubernetesApiResponse<ApiListType> list(); KubernetesApiResponse<ApiListType> list(String namespace); KubernetesApiResponse<ApiType> create(ApiType object); KubernetesApiResponse<ApiType> update(ApiType object); KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> patch(
String namespace, String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> delete(String name); KubernetesApiResponse<ApiType> delete(String namespace, String name); Watchable<ApiType> watch(); Watchable<ApiType> watch(String namespace); KubernetesApiResponse<ApiType> get(String name, final GetOptions getOptions); KubernetesApiResponse<ApiType> get(
String namespace, String name, final GetOptions getOptions); KubernetesApiResponse<ApiListType> list(final ListOptions listOptions); KubernetesApiResponse<ApiListType> list(String namespace, final ListOptions listOptions); KubernetesApiResponse<ApiType> create(ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> create(
String namespace, ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> update(ApiType object, final UpdateOptions updateOptions); KubernetesApiResponse<ApiType> patch(
String name, String patchType, V1Patch patch, final PatchOptions patchOptions); KubernetesApiResponse<ApiType> patch(
String namespace,
String name,
String patchType,
V1Patch patch,
final PatchOptions patchOptions); KubernetesApiResponse<ApiType> delete(String name, final DeleteOptions deleteOptions); KubernetesApiResponse<ApiType> delete(
String namespace, String name, final DeleteOptions deleteOptions); Watchable<ApiType> watch(final ListOptions listOptions); Watchable<ApiType> watch(String namespace, final ListOptions listOptions); }### Answer:
@Test public void testReadTimeoutShouldThrowException() { ApiClient apiClient = new ClientBuilder().setBasePath("http: apiClient.setHttpClient( apiClient .getHttpClient() .newBuilder() .readTimeout(1, TimeUnit.MILLISECONDS) .build()); stubFor( get(urlEqualTo("/apis/batch/v1/namespaces/foo/jobs/test")) .willReturn(aResponse().withFixedDelay(99999).withStatus(200).withBody(""))); jobClient = new GenericKubernetesApi<>(V1Job.class, V1JobList.class, "batch", "v1", "jobs", apiClient); try { KubernetesApiResponse<V1Job> response = jobClient.get("foo", "test"); } catch (Throwable t) { assertTrue(t.getCause() instanceof SocketTimeoutException); return; } fail("no exception happened"); } |
### Question:
FilePersister implements ConfigPersister { public void save( ArrayList<Object> contexts, ArrayList<Object> clusters, ArrayList<Object> users, Object preferences, String currentContext) throws IOException { HashMap<String, Object> config = new HashMap<>(); config.put("apiVersion", "v1"); config.put("kind", "Config"); config.put("current-context", currentContext); config.put("preferences", preferences); config.put("clusters", clusters); config.put("contexts", contexts); config.put("users", users); synchronized (configFile) { try (FileWriter fw = new FileWriter(configFile)) { Yaml yaml = new Yaml(); yaml.dump(config, fw); fw.flush(); } } } FilePersister(String filename); FilePersister(File file); void save(
ArrayList<Object> contexts,
ArrayList<Object> clusters,
ArrayList<Object> users,
Object preferences,
String currentContext); }### Answer:
@Test public void testPersistence() throws IOException { File file = folder.newFile("testconfig"); FilePersister fp = new FilePersister(file.getPath()); KubeConfig config = KubeConfig.loadKubeConfig(new FileReader(KUBECONFIG_FILE_PATH)); fp.save( config.getContexts(), config.getClusters(), config.getUsers(), config.getPreferences(), config.getCurrentContext()); KubeConfig configOut = KubeConfig.loadKubeConfig(new FileReader(file)); assertEquals(config.getCurrentContext(), configOut.getCurrentContext()); assertEquals(config.getClusters(), configOut.getClusters()); assertEquals(config.getContexts(), configOut.getContexts()); assertEquals(config.getUsers(), configOut.getUsers()); } |
### Question:
Version { public VersionInfo getVersion() throws ApiException, IOException { Call call = versionApi.getCodeCall(null); Response response = null; try { response = call.execute(); } catch (IOException e) { throw new ApiException(e); } if (!response.isSuccessful()) { throw new ApiException(response.code(), "Version request failed: " + response.code()); } return this.versionApi .getApiClient() .getJSON() .deserialize(response.body().string(), VersionInfo.class); } Version(); Version(ApiClient apiClient); VersionInfo getVersion(); }### Answer:
@Test public void testUrl() throws InterruptedException, IOException, ApiException { wireMockRule.stubFor( get(urlPathEqualTo("/version/")) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{}"))); Version versionUtil = new Version(client); try { VersionInfo versionInfo = versionUtil.getVersion(); } catch (ApiException ex) { } verify( getRequestedFor(urlPathEqualTo("/version/")) .withHeader("Content-Type", equalTo("application/json")) .withHeader("Accept", equalTo("application/json"))); }
@Test public void testFailure() throws InterruptedException, IOException, ApiException { wireMockRule.stubFor( get(urlPathEqualTo("/version/")) .willReturn( aResponse() .withStatus(401) .withHeader("Content-Type", "application/json") .withBody("{}"))); Version versionUtil = new Version(client); boolean thrown = false; try { VersionInfo versionInfo = versionUtil.getVersion(); } catch (ApiException ex) { assertEquals(401, ex.getCode()); thrown = true; } assertEquals(thrown, true); verify( getRequestedFor(urlPathEqualTo("/version/")) .withHeader("Content-Type", equalTo("application/json")) .withHeader("Accept", equalTo("application/json"))); } |
### Question:
PortForward { public PortForwardResult forward(V1Pod pod, List<Integer> ports) throws ApiException, IOException { return forward(pod.getMetadata().getNamespace(), pod.getMetadata().getName(), ports); } PortForward(); PortForward(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); PortForwardResult forward(V1Pod pod, List<Integer> ports); PortForwardResult forward(String namespace, String name, List<Integer> ports); }### Answer:
@Test public void testUrl() throws IOException, ApiException, InterruptedException { PortForward forward = new PortForward(client); V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name(podName).namespace(namespace)); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/portforward")) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody("{}"))); int portNumber = 8080; List<Integer> ports = new ArrayList<>(); ports.add(portNumber); assertThrows( ApiException.class, () -> { forward.forward(pod, ports); }); Thread.sleep(2000); wireMockRule.verify( getRequestedFor( urlPathEqualTo( "/api/v1/namespaces/" + namespace + "/pods/" + podName + "/portforward")) .withQueryParam("ports", equalTo(Integer.toString(portNumber)))); } |
### Question:
Discovery { public Set<APIResource> groupResourcesByName( String group, List<String> versions, String preferredVersion, V1APIResourceList resourceList) { Set<APIResource> resources = resourceList.getResources().stream() .filter(r -> !getSubResourceNameIfPossible(r.getName()).isPresent()) .map( r -> new APIResource( group, versions, preferredVersion, r.getKind(), r.getNamespaced(), r.getName(), r.getSingularName())) .collect(Collectors.toSet()); Map<String, Set<String>> subResources = manageRelationFromResourceToSubResources(resourceList); resources.stream() .forEach( r -> { if (subResources.containsKey(r.getResourcePlural())) { r.subResources.addAll(subResources.get(r.getResourcePlural())); } }); return resources; } Discovery(); Discovery(ApiClient apiClient); Set<APIResource> findAll(); Set<APIResource> findAll(String group, List<String> versions, String preferredVersion); Set<APIResource> findAll(
String group, List<String> versions, String preferredVersion, String path); Set<APIResource> groupResourcesByName(
String group,
List<String> versions,
String preferredVersion,
V1APIResourceList resourceList); V1APIVersions legacyCoreApi(); V1APIGroupList groupDiscovery(String path); V1APIVersions versionDiscovery(String path); V1APIResourceList resourceDiscovery(String path); }### Answer:
@Test public void testGroupResourcesByName() { Discovery discovery = new Discovery(apiClient); Set<Discovery.APIResource> discoveredResources = discovery.groupResourcesByName( "foo", Arrays.asList("v1", "v2"), "v1", new V1APIResourceList() .resources( Arrays.asList( new V1APIResource() .name("meows") .kind("Meow") .namespaced(true) .singularName("meow"), new V1APIResource() .name("meows/mouse") .kind("MeowMouse") .namespaced(true) .singularName(""), new V1APIResource() .name("zigs") .kind("Zig") .namespaced(false) .singularName("zig")))); assertEquals(2, discoveredResources.size()); Discovery.APIResource meow = discoveredResources.stream() .filter(r -> r.getResourcePlural().equals("meows")) .findFirst() .get(); assertEquals(1, meow.getSubResources().size()); assertEquals("meows", meow.getResourcePlural()); assertEquals("meow", meow.getResourceSingular()); assertEquals(true, meow.getNamespaced()); assertEquals("mouse", meow.getSubResources().get(0)); } |
### Question:
Controller { public void stop() { synchronized (this) { if (reflectorFuture != null) { reflector.stop(); reflectorFuture.cancel(true); } } reflectExecutor.shutdown(); } Controller(
Class<ApiType> apiTypeClass,
DeltaFIFO queue,
ListerWatcher<ApiType, ApiListType> listerWatcher,
Consumer<Deque<MutablePair<DeltaFIFO.DeltaType, KubernetesObject>>> processFunc,
Supplier<Boolean> resyncFunc,
long fullResyncPeriod); Controller(
Class<ApiType> apiTypeClass,
DeltaFIFO queue,
ListerWatcher<ApiType, ApiListType> listerWatcher,
Consumer<Deque<MutablePair<DeltaFIFO.DeltaType, KubernetesObject>>> popProcessFunc); void run(); void stop(); boolean hasSynced(); String lastSyncResourceVersion(); }### Answer:
@Test public void testControllerProcessDeltas() throws InterruptedException { AtomicInteger receivingDeltasCount = new AtomicInteger(0); V1Pod foo1 = new V1Pod().metadata(new V1ObjectMeta().name("foo1").namespace("default")); V1Pod foo2 = new V1Pod().metadata(new V1ObjectMeta().name("foo2").namespace("default")); V1Pod foo3 = new V1Pod().metadata(new V1ObjectMeta().name("foo3").namespace("default")); V1PodList podList = new V1PodList().metadata(new V1ListMeta()).items(Arrays.asList(foo1, foo2, foo3)); DeltaFIFO deltaFIFO = new DeltaFIFO(Caches::deletionHandlingMetaNamespaceKeyFunc, new Cache()); AtomicBoolean runOnce = new AtomicBoolean(false); ListerWatcher<V1Pod, V1PodList> listerWatcher = new MockRunOnceListerWatcher<V1Pod, V1PodList>( podList, new Watch.Response<V1Pod>(EventType.MODIFIED.name(), foo3)); Controller<V1Pod, V1PodList> controller = new Controller<>( V1Pod.class, deltaFIFO, listerWatcher, (deltas) -> { receivingDeltasCount.incrementAndGet(); }); Thread controllerThread = new Thread(controller::run); controllerThread.setDaemon(true); controllerThread.start(); Thread.sleep(1000); try { assertEquals(4, receivingDeltasCount.get()); } catch (Throwable t) { throw new RuntimeException(t); } finally { controller.stop(); } } |
### Question:
Caches { public static String metaNamespaceKeyFunc(KubernetesObject obj) { V1ObjectMeta metadata = obj.getMetadata(); if (!Strings.isNullOrEmpty(metadata.getNamespace())) { return metadata.getNamespace() + "/" + metadata.getName(); } return metadata.getName(); } static String deletionHandlingMetaNamespaceKeyFunc(
ApiType object); static String metaNamespaceKeyFunc(KubernetesObject obj); static List<String> metaNamespaceIndexFunc(KubernetesObject obj); static final String NAMESPACE_INDEX; }### Answer:
@Test public void testDefaultNamespaceNameKey() { String testName = "test-name"; String testNamespace = "test-namespace"; V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name(testName).namespace(testNamespace)); assertEquals(testNamespace + "/" + testName, Caches.metaNamespaceKeyFunc(pod)); } |
### Question:
Caches { public static List<String> metaNamespaceIndexFunc(KubernetesObject obj) { V1ObjectMeta metadata = obj.getMetadata(); if (metadata == null) { return Collections.emptyList(); } return Collections.singletonList(metadata.getNamespace()); } static String deletionHandlingMetaNamespaceKeyFunc(
ApiType object); static String metaNamespaceKeyFunc(KubernetesObject obj); static List<String> metaNamespaceIndexFunc(KubernetesObject obj); static final String NAMESPACE_INDEX; }### Answer:
@Test public void testDefaultNamespaceIndex() { String testName = "test-name"; String testNamespace = "test-namespace"; V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name(testName).namespace(testNamespace)); List<String> indices = Caches.metaNamespaceIndexFunc(pod); assertEquals(pod.getMetadata().getNamespace(), indices.get(0)); } |
### Question:
Cache implements Indexer<ApiType> { @Override public void addIndexers(Map<String, Function<ApiType, List<String>>> newIndexers) { if (!items.isEmpty()) { throw new IllegalStateException("cannot add indexers to a non-empty cache"); } Set<String> oldKeys = indexers.keySet(); Set<String> newKeys = newIndexers.keySet(); Set<String> intersection = new HashSet<>(oldKeys); intersection.retainAll(newKeys); if (!intersection.isEmpty()) { throw new IllegalArgumentException("indexer conflict: " + intersection); } for (Map.Entry<String, Function<ApiType, List<String>>> indexEntry : newIndexers.entrySet()) { addIndexFunc(indexEntry.getKey(), indexEntry.getValue()); } } Cache(); Cache(
String indexName,
Function<ApiType, List<String>> indexFunc,
Function<ApiType, String> keyFunc); @Override void add(ApiType obj); @Override void update(ApiType obj); @Override void delete(ApiType obj); @Override synchronized void replace(List<ApiType> list, String resourceVersion); @Override void resync(); @Override synchronized List<String> listKeys(); @Override ApiType get(ApiType obj); @Override synchronized List<ApiType> list(); @Override synchronized ApiType getByKey(String key); @Override synchronized List<ApiType> index(String indexName, ApiType obj); @Override synchronized List<String> indexKeys(String indexName, String indexKey); @Override synchronized List<ApiType> byIndex(String indexName, String indexKey); @Override Map<String, Function<ApiType, List<String>>> getIndexers(); @Override void addIndexers(Map<String, Function<ApiType, List<String>>> newIndexers); void updateIndices(ApiType oldObj, ApiType newObj, String key); void addIndexFunc(String indexName, Function<ApiType, List<String>> indexFunc); Function<ApiType, String> getKeyFunc(); void setKeyFunc(Function<ApiType, String> keyFunc); }### Answer:
@Test public void testAddIndexers() { Cache<V1Pod> podCache = new Cache<>(); String nodeIndex = "node-index"; String clusterIndex = "cluster-index"; Map<String, Function<V1Pod, List<String>>> indexers = new HashMap<>(); indexers.put( nodeIndex, (V1Pod pod) -> { return Arrays.asList(pod.getSpec().getNodeName()); }); indexers.put( clusterIndex, (V1Pod pod) -> { return Arrays.asList(pod.getMetadata().getClusterName()); }); podCache.addIndexers(indexers); V1Pod testPod = new V1Pod() .metadata(new V1ObjectMeta().namespace("ns").name("n").clusterName("cluster1")) .spec(new V1PodSpec().nodeName("node1")); podCache.add(testPod); List<V1Pod> namespaceIndexedPods = podCache.byIndex(Caches.NAMESPACE_INDEX, "ns"); assertEquals(1, namespaceIndexedPods.size()); List<V1Pod> nodeNameIndexedPods = podCache.byIndex(nodeIndex, "node1"); assertEquals(1, nodeNameIndexedPods.size()); List<V1Pod> clusterNameIndexedPods = podCache.byIndex(clusterIndex, "cluster1"); assertEquals(1, clusterNameIndexedPods.size()); } |
### Question:
ProcessorListener implements Runnable { public void add(Notification<ApiType> obj) { if (obj == null) { return; } this.queue.add(obj); } ProcessorListener(ResourceEventHandler<ApiType> handler, long resyncPeriod); @Override void run(); void add(Notification<ApiType> obj); void determineNextResync(DateTime now); boolean shouldResync(DateTime now); }### Answer:
@Test public void testNotificationHandling() throws InterruptedException { V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name("foo").namespace("default")); ProcessorListener<V1Pod> listener = new ProcessorListener<>( new ResourceEventHandler<V1Pod>() { @Override public void onAdd(V1Pod obj) { assertEquals(pod, obj); addNotificationReceived = true; } @Override public void onUpdate(V1Pod oldObj, V1Pod newObj) { assertEquals(pod, newObj); updateNotificationReceived = true; } @Override public void onDelete(V1Pod obj, boolean deletedFinalStateUnknown) { assertEquals(pod, obj); deleteNotificationReceived = true; } }, 0); listener.add(new ProcessorListener.AddNotification<>(pod)); listener.add(new ProcessorListener.UpdateNotification<>(null, pod)); listener.add(new ProcessorListener.DeleteNotification<>(pod)); Thread listenerThread = new Thread(listener::run); listenerThread.setDaemon(true); listenerThread.start(); Thread.sleep(1000); assertTrue(addNotificationReceived); assertTrue(updateNotificationReceived); assertTrue(deleteNotificationReceived); }
@Test public void testMultipleNotificationsHandling() throws InterruptedException { V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name("foo").namespace("default")); final int[] count = {0}; ProcessorListener<V1Pod> listener = new ProcessorListener<>( new ResourceEventHandler<V1Pod>() { @Override public void onAdd(V1Pod obj) { assertEquals(pod, obj); count[0]++; } @Override public void onUpdate(V1Pod oldObj, V1Pod newObj) {} @Override public void onDelete(V1Pod obj, boolean deletedFinalStateUnknown) {} }, 0); for (int i = 0; i < 2000; i++) { listener.add(new ProcessorListener.AddNotification<>(pod)); } Thread listenerThread = new Thread(listener); listenerThread.setDaemon(true); listenerThread.start(); Thread.sleep(2000); assertEquals(count[0], 2000); } |
### Question:
Copy extends Exec { public InputStream copyFileFromPod(String namespace, String pod, String srcPath) throws ApiException, IOException { return copyFileFromPod(namespace, pod, null, srcPath); } Copy(); Copy(ApiClient apiClient); InputStream copyFileFromPod(String namespace, String pod, String srcPath); InputStream copyFileFromPod(V1Pod pod, String srcPath); InputStream copyFileFromPod(V1Pod pod, String container, String srcPath); InputStream copyFileFromPod(String namespace, String pod, String container, String srcPath); void copyFileFromPod(
String namespace, String name, String container, String srcPath, Path destination); void copyDirectoryFromPod(V1Pod pod, String srcPath, Path destination); void copyDirectoryFromPod(V1Pod pod, String container, String srcPath, Path destination); void copyDirectoryFromPod(String namespace, String pod, String srcPath, Path destination); void copyDirectoryFromPod(
String namespace, String pod, String container, String srcPath, Path destination); void copyDirectoryFromPod(
String namespace,
String pod,
String container,
String srcPath,
Path destination,
boolean enableTarCompressing); static void copyFileFromPod(String namespace, String pod, String srcPath, Path dest); void copyFileToPod(
String namespace, String pod, String container, Path srcPath, Path destPath); void copyFileToPod(
String namespace, String pod, String container, byte[] src, Path destPath); }### Answer:
@Test public void testUrl() throws IOException, ApiException, InterruptedException { Copy copy = new Copy(client); V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name(podName).namespace(namespace)); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody("{}"))); try { copy.copyFileFromPod(pod, "container", "/some/path/to/file"); } catch (IOException | ApiException e) { e.printStackTrace(); } Thread.sleep(2000); wireMockRule.verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .withQueryParam("stdin", equalTo("false")) .withQueryParam("stdout", equalTo("true")) .withQueryParam("stderr", equalTo("true")) .withQueryParam("tty", equalTo("false")) .withQueryParam("command", new AnythingPattern())); } |
### Question:
GroupVersion { public static GroupVersion parse(String apiVersion) { if (Strings.isNullOrEmpty(apiVersion)) { throw new IllegalArgumentException("No apiVersion found on object"); } if ("v1".equals(apiVersion)) { return new GroupVersion("", "v1"); } String[] parts = apiVersion.split("/"); if (parts.length != 2) { throw new IllegalArgumentException("Invalid apiVersion found on object: " + apiVersion); } return new GroupVersion(parts[0], parts[1]); } GroupVersion(String group, String version); static GroupVersion parse(String apiVersion); static GroupVersion parse(KubernetesObject obj); String getGroup(); String getVersion(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void parse() { assertEquals(new GroupVersion("", "v1"), GroupVersion.parse(new V1Pod().apiVersion("v1"))); assertEquals( new GroupVersion("apps", "v1"), GroupVersion.parse(new V1Deployment().apiVersion("apps/v1"))); assertThrows( IllegalArgumentException.class, () -> { GroupVersion.parse(new V1Pod()); GroupVersion.parse(new V1Pod().apiVersion(null)); GroupVersion.parse(new V1Pod().apiVersion("foo/bar/f")); }); } |
### Question:
PodLogs { public InputStream streamNamespacedPodLog(V1Pod pod) throws ApiException, IOException { if (pod.getSpec() == null) { throw new ApiException("pod.spec is null and container isn't specified."); } if (pod.getSpec().getContainers() == null || pod.getSpec().getContainers().size() < 1) { throw new ApiException("pod.spec.containers has no containers"); } return streamNamespacedPodLog( pod.getMetadata().getNamespace(), pod.getMetadata().getName(), pod.getSpec().getContainers().get(0).getName()); } PodLogs(); PodLogs(ApiClient apiClient); ApiClient getApiClient(); InputStream streamNamespacedPodLog(V1Pod pod); InputStream streamNamespacedPodLog(String namespace, String name, String container); InputStream streamNamespacedPodLog(
String namespace,
String name,
String container,
Integer sinceSeconds,
Integer tailLines,
boolean timestamps); }### Answer:
@Test public void testNotFound() throws ApiException, IOException { V1Pod pod = new V1Pod() .metadata(new V1ObjectMeta().name(podName).namespace(namespace)) .spec( new V1PodSpec() .containers(Arrays.asList(new V1Container().name(container).image("nginx")))); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log")) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "text/plain") .withBody("Not Found"))); PodLogs logs = new PodLogs(client); boolean thrown = false; try { logs.streamNamespacedPodLog(pod); } catch (ApiException ex) { assertEquals(404, ex.getCode()); thrown = true; } assertEquals(thrown, true); wireMockRule.verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log")) .withQueryParam("container", equalTo(container)) .withQueryParam("follow", equalTo("true")) .withQueryParam("pretty", equalTo("false")) .withQueryParam("previous", equalTo("false")) .withQueryParam("timestamps", equalTo("false"))); }
@Test public void testStream() throws ApiException, IOException { V1Pod pod = new V1Pod() .metadata(new V1ObjectMeta().name(podName).namespace(namespace)) .spec( new V1PodSpec() .containers(Arrays.asList(new V1Container().name(container).image("nginx")))); String content = "this is some\n content for \n various logs \n done"; wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log")) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "text/plain") .withBody(content))); PodLogs logs = new PodLogs(client); InputStream is = logs.streamNamespacedPodLog(pod); wireMockRule.verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log")) .withQueryParam("container", equalTo(container)) .withQueryParam("follow", equalTo("true")) .withQueryParam("pretty", equalTo("false")) .withQueryParam("previous", equalTo("false")) .withQueryParam("timestamps", equalTo("false"))); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteStreams.copy(is, bos); assertEquals(content, bos.toString()); } |
### Question:
JSON { public String serialize(Object obj) { return gson.toJson(obj); } JSON(); static GsonBuilder createGson(); Gson getGson(); JSON setGson(Gson gson); JSON setLenientOnJson(boolean lenientOnJson); String serialize(Object obj); @SuppressWarnings("unchecked") T deserialize(String body, Type returnType); JSON setDateTimeFormat(DateTimeFormatter dateFormat); JSON setLocalDateFormat(DateTimeFormatter dateFormat); JSON setDateFormat(DateFormat dateFormat); JSON setSqlDateFormat(DateFormat dateFormat); }### Answer:
@Test public void testSerializeByteArray() { final JSON json = new JSON(); final String plainText = "string that contains '=' when encoded"; final String base64String = json.serialize(plainText.getBytes()); final String pureString = base64String.replaceAll("^\"|\"$", ""); final ByteString byteStr = ByteString.decodeBase64(pureString); assertNotNull(byteStr); final String decodedText = new String(byteStr.toByteArray()); assertThat(decodedText, is(plainText)); } |
### Question:
IntOrString { public boolean isInteger() { return isInt; } IntOrString(final String value); IntOrString(final int value); boolean isInteger(); String getStrValue(); Integer getIntValue(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void whenCreatedWithInt_isInteger() { IntOrString intOrString = new IntOrString(17); assertThat(intOrString.isInteger(), is(true)); }
@Test public void whenCreatedWithString_isNotInteger() { IntOrString intOrString = new IntOrString("17"); assertThat(intOrString.isInteger(), is(false)); } |
### Question:
IntOrString { public Integer getIntValue() { if (!isInt) { throw new IllegalStateException("Not an integer"); } return intValue; } IntOrString(final String value); IntOrString(final int value); boolean isInteger(); String getStrValue(); Integer getIntValue(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void whenCreatedWithInt_canRetrieveIntValue() { IntOrString intOrString = new IntOrString(17); assertThat(intOrString.getIntValue(), equalTo(17)); }
@Test(expected = IllegalStateException.class) public void whenCreatedWithInt_cannotRetrieveIntValue() { IntOrString intOrString = new IntOrString("17"); intOrString.getIntValue(); } |
### Question:
PatchUtils { public static <ApiType> ApiType patch( Class<ApiType> apiTypeClass, PatchCallFunc callFunc, String patchFormat) throws ApiException { return patch(apiTypeClass, callFunc, patchFormat, Configuration.getDefaultApiClient()); } static ApiType patch(
Class<ApiType> apiTypeClass, PatchCallFunc callFunc, String patchFormat); static ApiType patch(
Class<ApiType> apiTypeClass, PatchCallFunc callFunc, String patchFormat, ApiClient apiClient); }### Answer:
@Test public void testJsonPatchPod() throws ApiException { CoreV1Api coreV1Api = new CoreV1Api(client); stubFor( patch(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")) .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_JSON_PATCH)) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{}"))); PatchUtils.patch( V1Pod.class, () -> coreV1Api.patchNamespacedPodCall( "foo", "default", new V1Patch("[]"), null, null, null, null, null), V1Patch.PATCH_FORMAT_JSON_PATCH, client); verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo"))); }
@Test public void testMergePatchPod() throws ApiException { CoreV1Api coreV1Api = new CoreV1Api(client); stubFor( patch(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")) .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_JSON_MERGE_PATCH)) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{}"))); PatchUtils.patch( V1Pod.class, () -> coreV1Api.patchNamespacedPodCall( "foo", "default", new V1Patch("[]"), null, null, null, null, null), V1Patch.PATCH_FORMAT_JSON_MERGE_PATCH, client); verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo"))); }
@Test public void testStrategicMergePatchPod() throws ApiException { CoreV1Api coreV1Api = new CoreV1Api(client); stubFor( patch(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")) .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH)) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{}"))); PatchUtils.patch( V1Pod.class, () -> coreV1Api.patchNamespacedPodCall( "foo", "default", new V1Patch("[]"), null, null, null, null, null), V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, client); verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo"))); } |
### Question:
IntOrString { public String getStrValue() { if (isInt) { throw new IllegalStateException("Not a string"); } return strValue; } IntOrString(final String value); IntOrString(final int value); boolean isInteger(); String getStrValue(); Integer getIntValue(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = IllegalStateException.class) public void whenCreatedWithInt_cannotRetrieveStringValue() { IntOrString intOrString = new IntOrString(17); intOrString.getStrValue(); }
@Test public void whenCreatedWithString_canRetrieveStringValue() { IntOrString intOrString = new IntOrString("17"); assertThat(intOrString.getStrValue(), equalTo("17")); } |
### Question:
QuantityFormatter { public Quantity parse(final String value) { if (value == null || value.isEmpty()) { throw new QuantityFormatException(""); } final String[] parts = value.split(PARTS_RE); final BigDecimal numericValue = parseNumericValue(parts[0]); final String suffix = value.substring(parts[0].length()); final BaseExponent baseExponent = new SuffixFormatter().parse(suffix); final BigDecimal unitMultiplier = BigDecimal.valueOf(baseExponent.getBase()) .pow(baseExponent.getExponent(), MathContext.DECIMAL64); final BigDecimal unitlessValue = numericValue.multiply(unitMultiplier); return new Quantity(unitlessValue, baseExponent.getFormat()); } Quantity parse(final String value); String format(final Quantity quantity); }### Answer:
@Test public void testParsePlain() { final Quantity quantity = new QuantityFormatter().parse("1"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_SI)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(1))); }
@Test public void testParseFractional() { final Quantity quantity = new QuantityFormatter().parse("0.001"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_SI)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(0.001))); }
@Test public void testParseFractionalUnit() { final Quantity quantity = new QuantityFormatter().parse("0.001m"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_SI)); assertThat(quantity.getNumber(), is(new BigDecimal("0.000001"))); }
@Test public void testParseBinarySi() { final Quantity quantity = new QuantityFormatter().parse("1Ki"); assertThat(quantity.getFormat(), is(Quantity.Format.BINARY_SI)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(1024))); }
@Test public void testParseLargeNumeratorBinarySi() { final Quantity quantity = new QuantityFormatter().parse("32Mi"); assertThat(quantity.getFormat(), is(Quantity.Format.BINARY_SI)); assertThat( quantity.getNumber(), is(BigDecimal.valueOf(2).pow(20).multiply(BigDecimal.valueOf(32)))); }
@Test public void testParseExponent() { final Quantity quantity = new QuantityFormatter().parse("1e3"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(1000))); }
@Test public void testParseNegativeExponent() { final Quantity quantity = new QuantityFormatter().parse("1e-3"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(0.001))); }
@Test(expected = QuantityFormatException.class) public void testParseBad() { new QuantityFormatter().parse("4e9e"); } |
### Question:
QuantityFormatter { public String format(final Quantity quantity) { switch (quantity.getFormat()) { case DECIMAL_SI: case DECIMAL_EXPONENT: return toBase10String(quantity); case BINARY_SI: if (isFractional(quantity)) { return toBase10String(new Quantity(quantity.getNumber(), Quantity.Format.DECIMAL_SI)); } return toBase1024String(quantity); default: throw new IllegalArgumentException("Can't format a " + quantity.getFormat() + " quantity"); } } Quantity parse(final String value); String format(final Quantity quantity); }### Answer:
@Test public void testFormatPlain() { final String formattedString = new QuantityFormatter() .format(new Quantity(new BigDecimal("100"), Quantity.Format.DECIMAL_SI)); assertThat(formattedString, is("100")); }
@Test public void testFormatDecimalSi() { final String formattedString = new QuantityFormatter() .format(new Quantity(new BigDecimal("100000"), Quantity.Format.DECIMAL_SI)); assertThat(formattedString, is("100k")); }
@Test public void testFormatFractionalDecimalSi() { final String formattedString = new QuantityFormatter() .format(new Quantity(new BigDecimal("100.001"), Quantity.Format.DECIMAL_SI)); assertThat(formattedString, is("100001m")); }
@Test public void testFormatBinarySi() { final String formattedString = new QuantityFormatter() .format(new Quantity(new BigDecimal(2).pow(20), Quantity.Format.BINARY_SI)); assertThat(formattedString, is("1Mi")); }
@Test public void testFormatLessThan1024BinarySi() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(128), Quantity.Format.BINARY_SI)); assertThat(formattedString, is("128")); }
@Test public void testFormatNon1024BinarySi() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(2056), Quantity.Format.BINARY_SI)); assertThat(formattedString, is("2056")); }
@Test public void testFormatFractionalBinarySi() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(123.123), Quantity.Format.BINARY_SI)); assertThat(formattedString, is("123123m")); }
@Test public void testFormatDecimalExponent() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(1000000), Quantity.Format.DECIMAL_EXPONENT)); assertThat(formattedString, is("1e6")); }
@Test public void testFormatEnforceExpOf3DecimalExponent() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(100000), Quantity.Format.DECIMAL_EXPONENT)); assertThat(formattedString, is("100e3")); }
@Test public void testFormatNoExpDecimalExponent() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(12345), Quantity.Format.DECIMAL_EXPONENT)); assertThat(formattedString, is("12345")); } |
### Question:
SuffixFormatter { public BaseExponent parse(final String suffix) { final BaseExponent decimalSuffix = suffixToDecimal.get(suffix); if (decimalSuffix != null) { return decimalSuffix; } final BaseExponent binarySuffix = suffixToBinary.get(suffix); if (binarySuffix != null) { return binarySuffix; } if (suffix.length() > 0 && (suffix.charAt(0) == 'E' || suffix.charAt(0) == 'e')) { return extractDecimalExponent(suffix); } throw new QuantityFormatException("Could not parse suffix"); } BaseExponent parse(final String suffix); String format(final Quantity.Format format, final int exponent); }### Answer:
@Test public void testParseBinaryKi() { final BaseExponent baseExponent = new SuffixFormatter().parse("Ki"); assertThat(baseExponent.getBase(), is(2)); assertThat(baseExponent.getExponent(), is(10)); assertThat(baseExponent.getFormat(), is(Quantity.Format.BINARY_SI)); }
@Test public void testParseDecimalZero() { final BaseExponent baseExponent = new SuffixFormatter().parse(""); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(0)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_SI)); }
@Test public void testParseDecimalK() { final BaseExponent baseExponent = new SuffixFormatter().parse("k"); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(3)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_SI)); }
@Test public void testParseDecimalExponent() { final BaseExponent baseExponent = new SuffixFormatter().parse("E2"); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(2)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); }
@Test public void testParseDecimalExponentPositive() { final BaseExponent baseExponent = new SuffixFormatter().parse("e+3"); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(3)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); }
@Test public void testParseDecimalExponentNegative() { final BaseExponent baseExponent = new SuffixFormatter().parse("e-3"); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(-3)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); }
@Test(expected = QuantityFormatException.class) public void testParseBad() { new SuffixFormatter().parse("eKi"); } |
### Question:
SuffixFormatter { public String format(final Quantity.Format format, final int exponent) { switch (format) { case DECIMAL_SI: return getDecimalSiSuffix(exponent); case BINARY_SI: return getBinarySiSuffix(exponent); case DECIMAL_EXPONENT: return exponent == 0 ? "" : "e" + exponent; default: throw new IllegalStateException("Can't format " + format + " with exponent " + exponent); } } BaseExponent parse(final String suffix); String format(final Quantity.Format format, final int exponent); }### Answer:
@Test public void testFormatZeroDecimalExponent() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL_EXPONENT, 0); assertThat(formattedString, is("")); }
@Test public void testFormatDecimalExponent() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL_EXPONENT, 3); assertThat(formattedString, is("e3")); }
@Test public void testFormatZeroDecimalSi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL_SI, 0); assertThat(formattedString, is("")); }
@Test(expected = IllegalArgumentException.class) public void testFormatBadDecimalSi() { new SuffixFormatter().format(Quantity.Format.DECIMAL_SI, 2); }
@Test public void testFormatDecimalSi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL_SI, 3); assertThat(formattedString, is("k")); }
@Test public void testFormatNegativeDecimalSi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL_SI, -6); assertThat(formattedString, is("u")); }
@Test public void testFormatBinarySi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.BINARY_SI, 10); assertThat(formattedString, is("Ki")); }
@Test public void testFormatNoExponentBinarySi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.BINARY_SI, 0); assertThat(formattedString, is("")); }
@Test(expected = IllegalArgumentException.class) public void testFormatBadBinarySi() { new SuffixFormatter().format(Quantity.Format.BINARY_SI, 4); } |
### Question:
ModelMapper { public static Class<?> getApiTypeClass(String apiGroupVersion, String kind) { String[] parts = apiGroupVersion.split("/"); String apiGroup; String apiVersion; if (parts.length == 1) { apiGroup = ""; apiVersion = apiGroupVersion; } else { apiGroup = parts[0]; apiVersion = parts[1]; } return getApiTypeClass(apiGroup, apiVersion, kind); } @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); @Deprecated static void addModelMap(String group, String version, String kind, Class<?> clazz); static void addModelMap(
String group, String version, String kind, String resourceNamePlural, Class<?> clazz); static void addModelMap(
String group,
String version,
String kind,
String resourceNamePlural,
Boolean isNamespacedResource,
Class<?> clazz); static Class<?> getApiTypeClass(String apiGroupVersion, String kind); static Class<?> getApiTypeClass(String group, String version, String kind); static GroupVersionKind getGroupVersionKindByClass(Class<?> clazz); static GroupVersionResource getGroupVersionResourceByClass(Class<?> clazz); static Set<Discovery.APIResource> refresh(Discovery discovery); static Set<Discovery.APIResource> refresh(Discovery discovery, Duration refreshInterval); static boolean isApiDiscoveryRefreshed(); static Class<?> preBuiltGetApiTypeClass(String group, String version, String kind); static GroupVersionKind preBuiltGetGroupVersionKindByClass(Class<?> clazz); static Boolean isNamespaced(Class<?> clazz); static final Duration DEFAULT_DISCOVERY_REFRESH_INTERVAL; }### Answer:
@Test public void testPrebuiltModelMapping() { assertEquals(V1Pod.class, ModelMapper.getApiTypeClass("", "v1", "Pod")); assertEquals(V1Deployment.class, ModelMapper.getApiTypeClass("", "v1", "Deployment")); assertEquals( V1beta1CustomResourceDefinition.class, ModelMapper.getApiTypeClass("", "v1beta1", "CustomResourceDefinition")); } |
### Question:
ModelMapper { public static GroupVersionKind preBuiltGetGroupVersionKindByClass(Class<?> clazz) { return preBuiltClassesByGVK.entrySet().stream() .filter(e -> clazz.equals(e.getValue())) .map(e -> e.getKey()) .findFirst() .get(); } @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); @Deprecated static void addModelMap(String group, String version, String kind, Class<?> clazz); static void addModelMap(
String group, String version, String kind, String resourceNamePlural, Class<?> clazz); static void addModelMap(
String group,
String version,
String kind,
String resourceNamePlural,
Boolean isNamespacedResource,
Class<?> clazz); static Class<?> getApiTypeClass(String apiGroupVersion, String kind); static Class<?> getApiTypeClass(String group, String version, String kind); static GroupVersionKind getGroupVersionKindByClass(Class<?> clazz); static GroupVersionResource getGroupVersionResourceByClass(Class<?> clazz); static Set<Discovery.APIResource> refresh(Discovery discovery); static Set<Discovery.APIResource> refresh(Discovery discovery, Duration refreshInterval); static boolean isApiDiscoveryRefreshed(); static Class<?> preBuiltGetApiTypeClass(String group, String version, String kind); static GroupVersionKind preBuiltGetGroupVersionKindByClass(Class<?> clazz); static Boolean isNamespaced(Class<?> clazz); static final Duration DEFAULT_DISCOVERY_REFRESH_INTERVAL; }### Answer:
@Test public void testPreBuiltGetClassByKind() { assertEquals( new GroupVersionKind("", "v1", "Pod"), ModelMapper.preBuiltGetGroupVersionKindByClass(V1Pod.class)); assertEquals( new GroupVersionKind("", "v1", "Pod"), ModelMapper.preBuiltGetGroupVersionKindByClass(V1Pod.class)); assertEquals( new GroupVersionKind("", "v1", "Deployment"), ModelMapper.preBuiltGetGroupVersionKindByClass(V1Deployment.class)); assertEquals( new GroupVersionKind("", "v1beta1", "CustomResourceDefinition"), ModelMapper.preBuiltGetGroupVersionKindByClass(V1beta1CustomResourceDefinition.class)); } |
### Question:
StringWrapper { public static String[] wrapString(@Nonnull String str, int maxWidth, @Nullable String[] output) { if (output == null) { output = new String[(int)((str.length() / maxWidth) * 1.5d + 1)]; } int lineStart = 0; int arrayIndex = 0; int i; for (i=0; i<str.length(); i++) { char c = str.charAt(i); if (c == '\n') { output = addString(output, str.substring(lineStart, i), arrayIndex++); lineStart = i+1; } else if (i - lineStart == maxWidth) { output = addString(output, str.substring(lineStart, i), arrayIndex++); lineStart = i; } } if (lineStart != i || i == 0) { output = addString(output, str.substring(lineStart), arrayIndex++, output.length+1); } if (arrayIndex < output.length) { output[arrayIndex] = null; } return output; } static String[] wrapString(@Nonnull String str, int maxWidth, @Nullable String[] output); }### Answer:
@Test public void testWrapString() { validateResult( new String[]{"abc", "abcdef", "abcdef"}, StringWrapper.wrapString("abc\nabcdefabcdef", 6, null)); validateResult( new String[]{"abc"}, StringWrapper.wrapString("abc", 6, new String[3])); validateResult( new String[]{"abc"}, StringWrapper.wrapString("abc", 6, new String[0])); validateResult( new String[]{"abc"}, StringWrapper.wrapString("abc", 6, new String[1])); validateResult( new String[]{""}, StringWrapper.wrapString("", 6, new String[3])); validateResult( new String[]{"abcdef"}, StringWrapper.wrapString("abcdef", 6, new String[3])); validateResult( new String[]{"abcdef", "abcdef"}, StringWrapper.wrapString("abcdef\nabcdef", 6, new String[3])); validateResult( new String[]{"abc", "", "def"}, StringWrapper.wrapString("abc\n\ndef", 6, new String[3])); validateResult( new String[]{"", "abcdef"}, StringWrapper.wrapString("\nabcdef", 6, new String[3])); validateResult( new String[]{"", "", "abcdef"}, StringWrapper.wrapString("\n\nabcdef", 6, new String[3])); validateResult( new String[]{"", "", "abcdef"}, StringWrapper.wrapString("\n\nabcdef", 6, new String[4])); validateResult( new String[]{"", "", "abcdef", ""}, StringWrapper.wrapString("\n\nabcdef\n\n", 6, new String[4])); validateResult( new String[]{"", "", "abcdef", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 6, new String[4])); validateResult( new String[]{"", "", "abcdef", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 6, new String[0])); validateResult( new String[]{"", "", "abcdef", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 6, new String[5])); validateResult( new String[]{"", "", "a", "b", "c", "d", "e", "f", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 1, new String[5])); } |
### Question:
ClassFileNameHandler { @Nonnull static String shortenPathComponent(@Nonnull String pathComponent, int maxLength) { int toRemove = pathComponent.length() - maxLength + 1; int firstIndex = (pathComponent.length()/2) - (toRemove/2); return pathComponent.substring(0, firstIndex) + "#" + pathComponent.substring(firstIndex+toRemove); } ClassFileNameHandler(File path, String fileExtension); File getUniqueFilenameForClass(String className); }### Answer:
@Test public void testShortedPathComponent() { StringBuilder sb = new StringBuilder(); for (int i=0; i<300; i++) { sb.append((char)i); } String result = ClassFileNameHandler.shortenPathComponent(sb.toString(), 255); Assert.assertEquals(255, result.length()); } |
### Question:
BaseDexBuffer { public int readSmallUint(int offset) { byte[] buf = this.buf; int result = (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8) | ((buf[offset+2] & 0xff) << 16) | ((buf[offset+3]) << 24); if (result < 0) { throw new ExceptionWithContext("Encountered small uint that is out of range at offset 0x%x", offset); } return result; } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadSmallUintSuccess() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22, 0x33, 0x44}); Assert.assertEquals(0x44332211, dexBuf.readSmallUint(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, 0x00}); Assert.assertEquals(0, dexBuf.readSmallUint(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, 0x7f}); Assert.assertEquals(0x7fffffff, dexBuf.readSmallUint(0)); }
@Test(expected=ExceptionWithContext.class) public void testReadSmallUintTooLarge1() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, (byte)0x80}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadSmallUintTooLarge2() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0x80}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadSmallUintTooLarge3() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadOptionalUintTooLarge1() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, (byte)0x80}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadOptionalUintTooLarge2() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0x80}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadOptionalUintTooLarge3() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {(byte)0xfe, (byte)0xff, (byte)0xff, (byte)0xff}); dexBuf.readSmallUint(0); } |
### Question:
BaseDexBuffer { public int readUshort(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8); } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadUshort() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22}); Assert.assertEquals(dexBuf.readUshort(0), 0x2211); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00}); Assert.assertEquals(dexBuf.readUshort(0), 0); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff}); Assert.assertEquals(dexBuf.readUshort(0), 0xffff); dexBuf = new BaseDexBuffer(new byte[] {(byte)0x00, (byte)0x80}); Assert.assertEquals(dexBuf.readUshort(0), 0x8000); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0x7f}); Assert.assertEquals(dexBuf.readUshort(0), 0x7fff); } |
### Question:
BaseDexBuffer { public int readUbyte(int offset) { return buf[offset] & 0xff; } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadUbyte() { byte[] buf = new byte[1]; BaseDexBuffer dexBuf = new BaseDexBuffer(buf); for (int i=0; i<=0xff; i++) { buf[0] = (byte)i; Assert.assertEquals(i, dexBuf.readUbyte(0)); } } |
### Question:
BaseDexBuffer { public long readLong(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8) | ((buf[offset+2] & 0xff) << 16) | ((buf[offset+3] & 0xffL) << 24) | ((buf[offset+4] & 0xffL) << 32) | ((buf[offset+5] & 0xffL) << 40) | ((buf[offset+6] & 0xffL) << 48) | (((long)buf[offset+7]) << 56); } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadLong() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}); Assert.assertEquals(0x7766554433221100L, dexBuf.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); Assert.assertEquals(0, dexBuf.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, 0x7f}); Assert.assertEquals(Long.MAX_VALUE, dexBuf.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x80}); Assert.assertEquals(Long.MIN_VALUE, dexBuf.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x80}); Assert.assertEquals(0x80ffffffffffffffL, dexBuf.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff}); Assert.assertEquals(-1, dexBuf.readLong(0)); }
@Test public void testReadLongRandom() { Random r = new Random(1234567890); ByteBuffer byteBuf = ByteBuffer.allocateDirect(8).order(ByteOrder.LITTLE_ENDIAN); byte[] buf = new byte[8]; BaseDexBuffer dexBuf = new BaseDexBuffer(buf); for (int i=0; i<10000; i++) { int val = r.nextInt(); byteBuf.putLong(0, val); byteBuf.position(0); byteBuf.get(buf); Assert.assertEquals(val, dexBuf.readLong(0)); } } |
### Question:
BaseDexBuffer { public int readInt(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8) | ((buf[offset+2] & 0xff) << 16) | (buf[offset+3] << 24); } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadInt() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22, 0x33, 0x44}); Assert.assertEquals(0x44332211, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, 0x00}); Assert.assertEquals(0, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, 0x7f}); Assert.assertEquals(Integer.MAX_VALUE, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, (byte)0x80}); Assert.assertEquals(Integer.MIN_VALUE, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0x80}); Assert.assertEquals(0x80ffffff, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff}); Assert.assertEquals(-1, dexBuf.readInt(0)); } |
### Question:
BaseDexBuffer { public int readShort(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | (buf[offset+1] << 8); } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadShort() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22}); Assert.assertEquals(dexBuf.readShort(0), 0x2211); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00}); Assert.assertEquals(dexBuf.readShort(0), 0); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff}); Assert.assertEquals(dexBuf.readShort(0), -1); dexBuf = new BaseDexBuffer(new byte[] {(byte)0x00, (byte)0x80}); Assert.assertEquals(dexBuf.readShort(0), Short.MIN_VALUE); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0x7f}); Assert.assertEquals(dexBuf.readShort(0), 0x7fff); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0x80}); Assert.assertEquals(dexBuf.readShort(0), 0xffff80ff); } |
### Question:
BaseDexBuffer { public int readByte(int offset) { return buf[offset]; } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); }### Answer:
@Test public void testReadByte() { byte[] buf = new byte[1]; BaseDexBuffer dexBuf = new BaseDexBuffer(buf); for (int i=0; i<=0xff; i++) { buf[0] = (byte)i; Assert.assertEquals((byte)i, dexBuf.readByte(0)); } } |
### Question:
GenerateConfigMojo extends AbstractMojo { public String getSettingsForArtifact( String fullSettings, String groupId, String artifactId ) { if( fullSettings != null ) { for( String token : fullSettings.split( "," ) ) { int end = ( token.indexOf( "@" ) >= 0 ) ? token.indexOf( "@" ) : token.length(); String ga_part[] = token.substring( 0, end ).split( ":" ); if( ga_part[ 0 ].equals( groupId ) && ga_part[ 1 ].equals( artifactId ) ) { return token.substring( end ); } } } return ""; } void execute(); String getSettingsForArtifact( String fullSettings, String groupId, String artifactId ); }### Answer:
@Test public void testSettingsMatching() { assertEquals( "@42@bee", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "foo", "bar" ) ); assertEquals( "", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "xx", "bb" ) ); assertEquals( "", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "cheese", "bb" ) ); assertEquals( "@42@bee", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "foo", "bar" ) ); assertEquals( "", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx,ping:back", "ping", "back" ) ); } |
### Question:
CompositeScannerProvisionOption extends AbstractUrlProvisionOption<CompositeScannerProvisionOption> implements Scanner { public String getURL() { return new StringBuilder() .append( SCHEMA ) .append( SEPARATOR_SCHEME ) .append( super.getURL() ) .append( getOptions( this ) ) .toString(); } CompositeScannerProvisionOption( final String url ); CompositeScannerProvisionOption( final UrlReference url ); String getURL(); }### Answer:
@Test public void urlAsReferenceViaFactoryMethod() { assertThat( "Scan composite url", scanComposite( url( "file:foo.composite" ) ).getURL(), is( equalTo( "scan-composite:file:foo.composite@update" ) ) ); }
@Test public void urlAsMavenUrl() { assertThat( "Scan composite url", new CompositeScannerProvisionOption( maven().groupId( "bar" ).artifactId( "foo" ).type( "composite" ) ).getURL(), is( equalTo( "scan-composite:mvn:bar/foo ); }
@Test public void urlAsMavenUrlViaFactoryMethod() { assertThat( "Scan composite url", scanComposite( maven().groupId( "bar" ).artifactId( "foo" ).type( "composite" ) ).getURL(), is( equalTo( "scan-composite:mvn:bar/foo ); }
@Test public void urlAsString() { assertThat( "Scan composite url", new CompositeScannerProvisionOption( "file:foo.composite" ).getURL(), is( equalTo( "scan-composite:file:foo.composite@update" ) ) ); }
@Test public void urlAsStringViaFactoryMethod() { assertThat( "Scan composite url", scanComposite( "file:foo.composite" ).getURL(), is( equalTo( "scan-composite:file:foo.composite@update" ) ) ); }
@Test public void urlAsReference() { assertThat( "Scan composite url", new CompositeScannerProvisionOption( url( "file:foo.composite" ) ).getURL(), is( equalTo( "scan-composite:file:foo.composite@update" ) ) ); } |
### Question:
FileScannerProvisionOption extends AbstractUrlProvisionOption<FileScannerProvisionOption> implements Scanner { public String getURL() { return new StringBuilder() .append( SCHEMA ) .append( SEPARATOR_SCHEME ) .append( super.getURL() ) .append( getOptions( this ) ) .toString(); } FileScannerProvisionOption( final String url ); FileScannerProvisionOption( final UrlReference url ); String getURL(); }### Answer:
@Test public void urlAsString() { assertThat( "Scan file url", new FileScannerProvisionOption( "file:foo.bundles" ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsStringViaFactoryMethod() { assertThat( "Scan file url", scanFile( "file:foo.bundles" ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsReference() { assertThat( "Scan file url", new FileScannerProvisionOption( url( "file:foo.bundles" ) ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsReferenceViaFactoryMethod() { assertThat( "Scan file url", scanFile( url( "file:foo.bundles" ) ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsMavenUrl() { assertThat( "Scan file url", new FileScannerProvisionOption( maven().groupId( "bar" ).artifactId( "foo" ).type( "bundles" ) ).getURL(), is( equalTo( "scan-file:mvn:bar/foo ); }
@Test public void urlAsMavenUrlViaFactoryMethod() { assertThat( "Scan file url", scanFile( maven().groupId( "bar" ).artifactId( "foo" ).type( "bundles" ) ).getURL(), is( equalTo( "scan-file:mvn:bar/foo ); } |
### Question:
FeaturesScannerProvisionOption extends AbstractUrlProvisionOption<FeaturesScannerProvisionOption> implements Scanner { public String getURL() { final StringBuilder url = new StringBuilder() .append( SCHEMA ) .append( SEPARATOR_SCHEME ) .append( super.getURL() ) .append( SEPARATOR_FILTER ); boolean first = true; for( String feature : m_features ) { if( !first ) { url.append( FEATURE_SEPARATOR ); } first = false; url.append( feature ); } url.append( getOptions( this ) ); return url.toString(); } FeaturesScannerProvisionOption( final String repositoryUrl,
final String... features ); FeaturesScannerProvisionOption( final UrlReference repositoryUrl,
final String... features ); String getURL(); }### Answer:
@Test public void urlAsString() { assertThat( "Scan features url", new FeaturesScannerProvisionOption( "file:foo-features.xml", "f1", "f2/1.0.0" ).getURL(), is( equalTo( "scan-features:file:foo-features.xml!/f1,f2/1.0.0" ) ) ); }
@Test public void urlAsStringViaFactoryMethod() { assertThat( "Scan features url", scanFeatures( "file:foo-features.xml", "f1", "f2/1.0.0" ).getURL(), is( equalTo( "scan-features:file:foo-features.xml!/f1,f2/1.0.0" ) ) ); }
@Test public void urlAsReference() { assertThat( "Scan features url", new FeaturesScannerProvisionOption( url( "file:foo-features.xml" ), "f1", "f2/1.0.0" ).getURL(), is( equalTo( "scan-features:file:foo-features.xml!/f1,f2/1.0.0" ) ) ); }
@Test public void urlAsReferenceViaFactoryMethod() { assertThat( "Scan features url", scanFeatures( url( "file:foo-features.xml" ), "f1", "f2/1.0.0" ).getURL(), is( equalTo( "scan-features:file:foo-features.xml!/f1,f2/1.0.0" ) ) ); }
@Test public void urlAsMavenUrl() { assertThat( "Scan features url", new FeaturesScannerProvisionOption( maven().groupId( "bar" ).artifactId( "foo" ).classifier( "features" ).type( "xml" ), "f1", "f2/1.0.0" ).getURL(), is( equalTo( "scan-features:mvn:bar/foo ); }
@Test public void urlAsMavenUrlViaFactoryMethod() { assertThat( "Scan features url", scanFeatures( maven().groupId( "bar" ).artifactId( "foo" ).classifier( "features" ).type( "xml" ), "f1", "f2/1.0.0" ).getURL(), is( equalTo( "scan-features:mvn:bar/foo ); } |
### Question:
ConfigurationManager { static void setEnableDefaultload(boolean enabled){ enableDefaultload =enabled; } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); }### Answer:
@Test public void testGetDefaultAppPro(){ ConfigurationManager.setEnableDefaultload(true); System.out.println(ConfigurationManager.class.getProtectionDomain().getCodeSource().getLocation().toString()); URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); try { InputStream in = ConfigurationManager.class.getClassLoader().getResourceAsStream("jar:"+url.toURI().toString()+"!/META-INF/MANIFEST.MF"); System.out.println(url.toURI().toString()); System.out.println(in); ZipInputStream zip = new ZipInputStream(url.openStream()); ZipEntry ze; while ((ze = zip.getNextEntry())!=null){ if(ze.getName().equals("META-INF/MANIFEST.MF")){ System.out.println(ze.getName()); break; } } System.out.println(IOUtils.readAll(zip)); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ConfigurationManager.setEnableDefaultload(false); } |
### Question:
ConfigurationManager { static void loadProperties(Properties properties) throws InitConfigurationException { if (instance == null) { instance = getConfigInstance(); } ConfigurationUtils.loadProperties(properties, instance); } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); }### Answer:
@Test public void testLoadProperties() throws Exception { ConfigurationManager.loadPropertiesFromResources("test.properties"); assertEquals("9", ConfigurationManager.getConfigInstance().getProperty("com.ctrip.config.samples.needCount")); assertEquals("9", ConfigurationManager.getConfigInstance().getString("com.ctrip.config.samples.needCount")); assertEquals("100", ConfigurationManager.getConfigInstance().getString("no.exist","100")); } |
### Question:
ConfigurationManager { public static Configuration getConfigInstance() throws InitConfigurationException { if (instance == null) { synchronized (ConfigurationManager.class) { if (instance == null) { instance = createDefaultConfigInstance(); try { customProperties = Tools.loadPropertiesFromFile(TEMPFILENAME); } catch (Throwable e) { logger.error("load temp custom properties failed!", e); } if(customProperties!=null) { Iterator<String> keys = customProperties.getKeys(); while (keys.hasNext()) { String key = keys.next(); if (instance.containsKey(key)) { instance.setProperty(key, customProperties.getString(key)); } } } } } } return instance; } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); }### Answer:
@Test public void testNumberProperties() throws Exception { Configuration config = ConfigurationManager.getConfigInstance(); double val = 12.3; config.setProperty("test-double",val); assertTrue(val == config.getDouble("test-double")); config.setProperty("test-int",10); assertTrue(10 == config.getDouble("test-int")); assertTrue(0 == config.getDouble("test-int-emp")); assertTrue(20 == config.getInt("test-int-emp",20)); assertTrue(new Integer(23) == config.getInt("test-int-emp",new Integer(23))); assertEquals(false,config.getBoolean("test-boolean")); } |
### Question:
ConfigurationManager { private static Properties loadCascadedProperties(String configName) throws IOException { String defaultConfigFileName = configName + ".properties"; ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(defaultConfigFileName); if (url == null) { throw new IOException("Cannot locate " + defaultConfigFileName + " as a classpath resource."); } Properties props = getPropertiesFromFile(url); String environment = EnFactory.getEnBase().getEnvType(); if(environment!=null) { environment = environment.toLowerCase(); } if (environment != null && environment.length() > 0) { String envConfigFileName = configName + "-" + environment + ".properties"; url = loader.getResource(envConfigFileName); if(url==null){ url = loader.getResource(configName.replace("config/",environment+"-config/") +".properties"); } if (url != null) { Properties envProps = getPropertiesFromFile(url); if (envProps != null) { props.putAll(envProps); } } } return props; } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); }### Answer:
@Test public void testLoadCascadedProperties() throws Exception { ConfigurationManager.loadCascadedPropertiesFromResources("config/test"); assertEquals("7", ConfigurationManager.getConfigInstance().getProperty("com.ctrip.config.samples.needCount")); assertEquals("1", ConfigurationManager.getConfigInstance().getProperty("cascaded.property")); } |
### Question:
VIServer { public VIServer(int listenPort,boolean useVIAuthentication) throws Exception { server = new Server(listenPort); handler = bind(server, String.valueOf(listenPort),useVIAuthentication); } VIServer(int listenPort,boolean useVIAuthentication); VIServer(int listenPort); static ServletHandler bind(Server server,String id); static ServletHandler bind(Server server,String id,boolean useVIAuthentication); Server getInnerServer(); ServletHandler getHandler(); synchronized void start(); synchronized void stop(); }### Answer:
@Test public void testVIServer() throws Exception { int port = 1998; VIServer server = new VIServer(port); server.start(); URL url = new URL("http: Gson gson = new Gson(); List<CInfo> infos= new ArrayList<>(); String content = IOUtils.readAll((InputStream)url.getContent()); System.out.println(IgniteManager.getStatus().getMessages()); infos =gson.fromJson(content, infos.getClass()); Assert.assertTrue(infos.size()>=3); server.stop(); try{ infos =gson.fromJson(IOUtils.readAll((InputStream)url.getContent()), infos.getClass()); Assert.fail("can't reach there"); }catch (Exception e){ Assert.assertTrue(e instanceof ConnectException); } } |
### Question:
EventBusDispatcher implements IEventDispatcher { @Override public void dispatch(String name, Object event) { logger.debug("DispatchEvent: {} ({})", name, event); final Object[] args = event!=null?new Object[]{event}:new Object[]{}; dispatch(name, args); } EventBusDispatcher(EventBusManager ebManager, EventBus eb); @Override void dispatch(String name, Object event); @Override void dispatch(String name, Object... args); }### Answer:
@Test public void testDispatch_withArgumentAndExistingMethod_willSuccess() { testEventBus.testEventWithArgument(THE_ARG); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithArgument", THE_ARG); verify(testEventBus); }
@Test public void testDispatch_withoutArgumentAndExistingMethod_willSuccess() { testEventBus.testEventWithoutArgument(); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithoutArgument"); verify(testEventBus); }
@Test(expected = Exception.class) public void testDispatch_withoutArgument_exceptionOccurred_willBeRaised() { testEventBus.testEventWithoutArgument(); expectLastCall().andThrow(new RuntimeException("Faking an exception")); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithoutArgument"); verify(testEventBus); }
@Test(expected = Exception.class) public void testDispatch_witArgument_exceptionOccurred_willBeRaised() { testEventBus.testEventWithArgument(THE_ARG); expectLastCall().andThrow(new RuntimeException("Faking an exception")); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithArgument",THE_ARG); verify(testEventBus); }
@Test public void testDispatch_notExistingMethod() { replay(testEventBus); eventBusDispatcher.dispatch("notExistingMethod",THE_ARG); verify(testEventBus); } |
### Question:
ResourceBundleUiMessageSource implements IUiMessageSource { @Override public String getMessage(String key, Locale locale) { ResourceBundle bundle = getBundle(locale); if (bundle.containsKey(key)) { return bundle.getString(key); } return "{{ message missing: " + key + "}}"; } ResourceBundleUiMessageSource(String baseName); @Override String getMessage(String key, Locale locale); @Override String getMessage(String key, Object[] args, Locale locale); }### Answer:
@Test public void testGetMessageStringLocale() { String message = instance.getMessage("message.key", new Locale("de")); assertNotNull(message); assertEquals("Hier ein kleiner Text um die Sache zu erläutern.", message); }
@Test public void testGetMessageStringLocaleDefault() { String message = instance.getMessage("message.default", new Locale("en")); assertNotNull(message); assertEquals("Dieser Text steht nur in deutsch", message); }
@Test public void testGetMessageStringObjectArrayLocale() { String message = instance.getMessage("message.args", new Object[] {"PARAM"}, new Locale("de")); assertNotNull(message); assertEquals("Hier eine Nachricht mit Parametern... PARAM wurde eingegeben.", message); } |
### Question:
MethodHandler implements TargetHandler { @Override public String getTargetNamespace() { return "urn:org.vaadin.mvp.uibinder.method"; } MethodHandler(ComponentHandler ch); @Override String getTargetNamespace(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); }### Answer:
@Test public void getTargetNamespace() { assertEquals("urn:org.vaadin.mvp.uibinder.method", instance.getTargetNamespace()); } |
### Question:
MethodHandler implements TargetHandler { @Override public void handleElementOpen(String uri, String name) { method = findMethod(ch.getCurrent().getClass(), name); if (method == null) { throw new IllegalArgumentException("The method " + name + " is missing in " + ch.getCurrent().getClass()); } ch.setCurrentMethod(method); } MethodHandler(ComponentHandler ch); @Override String getTargetNamespace(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); }### Answer:
@Test public void handleElementOpen() { instance.handleElementOpen("", "addComponent"); Method m = ch.getCurrentMethod(); assertNotNull(m); assertEquals("addComponent", m.getName()); assertEquals(1, m.getParameterTypes().length); }
@Test (expected = IllegalArgumentException.class) public void handleElementOpenFail() { instance.handleElementOpen("", "nirvanaMethod"); } |
### Question:
MethodHandler implements TargetHandler { protected Method findMethod(Class<?> clazz, String name) { Class<?> searchType = clazz; while (searchType != null) { Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods()); for (Method method : methods) { if (name.equals(method.getName()) && method.getParameterTypes().length == 1 && Component.class.isAssignableFrom(method.getParameterTypes()[0])) { return method; } } searchType = searchType.getSuperclass(); } return null; } MethodHandler(ComponentHandler ch); @Override String getTargetNamespace(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); }### Answer:
@Test public void findMethod() throws SecurityException, NoSuchMethodException { Method m = instance.findMethod(VerticalLayout.class, "addComponent"); assertNotNull(m); assertEquals("addComponent", m.getName()); assertEquals(1, m.getParameterTypes().length); }
@Test public void findMethodNotFound() throws SecurityException, NoSuchMethodException { Method m = instance.findMethod(VerticalLayout.class, "nirvanaMethod"); assertNull(m); } |
### Question:
ComponentHandler implements TargetHandler { protected Method findApplicableSetterMethod(Object target, String propertyName, Object value) { String methodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); Method[] methods = target.getClass().getMethods(); if (value.getClass().isArray()) { } else { Method method = MethodUtils.getAccessibleMethod(target.getClass(), methodName, value.getClass()); if (method != null) { return method; } for (Method m : methods) { if (!m.getName().equals(methodName)) { continue; } Class<?>[] parameterTypes = m.getParameterTypes(); if (parameterTypes.length != 1) { continue; } Class<?> mpt = parameterTypes[0]; if (mpt.isAssignableFrom(value.getClass())) { return m; } Converter converter = ConvertUtils.lookup(mpt); if (converter != null) { return m; } } } if (value == null || value.toString().length() == 0) { for (Method m : methods) { if (m.getName().equals(methodName) && m.getParameterTypes().length == 0) { return m; } } } return null; } ComponentHandler(UiBinder uiBinder, Component view, Locale locale); IEventBinder getEventBinder(); void setEventBinder(IEventBinder eventBinder); @Override String getTargetNamespace(); Component getRootComponent(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); Component getCurrent(); void setCurrentMethod(Method currentMethod); }### Answer:
@Test public void testFindApplicableSetterMethodStringArg() throws SecurityException, NoSuchMethodException { Method m = instance.findApplicableSetterMethod(bean, "height", "67%"); assertEquals("wrong setter selected", VerticalLayout.class.getMethod("setHeight", String.class), m); }
@Ignore("Currently not supported, introduce expressions, e.g. MVEL to support this.") @Test public void testFindApplicableSetterMethodFloatIntArg() throws SecurityException, NoSuchMethodException { Method m = instance.findApplicableSetterMethod(bean, "height", "67, #UNITS_PERCENTAGE"); assertEquals("wrong setter selected", VerticalLayout.class.getMethod("setHeight", float.class, int.class), m); }
@Test public void testFindApplicableSetterMethodNoArg() throws SecurityException, NoSuchMethodException { Method m = instance.findApplicableSetterMethod(bean, "sizeFull", ""); assertEquals("wrong setter selected", VerticalLayout.class.getMethod("setSizeFull"), m); } |
### Question:
ComponentHandler implements TargetHandler { protected String namespaceUriToPackageName(String uri) throws UiConstraintException { if (packages.containsKey(uri)) { return packages.get(uri); } try { URI nsUri = new URI(uri); String pkg = null; String scheme = nsUri.getScheme(); if ("urn".equals(scheme)) { pkg = nsUri.getSchemeSpecificPart(); } else if ("http".equals(scheme)) { String[] hostParts = nsUri.getHost().split("\\."); String[] pathParts = nsUri.getPath().substring(1).split("/"); StringBuilder sb = new StringBuilder(); List<String> list = new ArrayList<String>(Arrays.asList(hostParts)); Collections.reverse(list); list.addAll(Arrays.asList(pathParts)); if (list.size() > 0) { sb.append(list.get(0)); for (int i = 1; i < list.size(); i++) { sb.append(".").append(list.get(i)); } } pkg = sb.toString(); } else { throw new UiConstraintException("Unsupported namespace URI scheme: " + scheme + " (URI = " + uri + ")"); } if (pkg.startsWith("import:")) { pkg = pkg.substring("import:".length()); } packages.put(uri, pkg); return pkg; } catch (URISyntaxException e) { throw new UiConstraintException("Invalid namespace URI", e); } } ComponentHandler(UiBinder uiBinder, Component view, Locale locale); IEventBinder getEventBinder(); void setEventBinder(IEventBinder eventBinder); @Override String getTargetNamespace(); Component getRootComponent(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); Component getCurrent(); void setCurrentMethod(Method currentMethod); }### Answer:
@Test public void testNamespaceUriToPackageName() throws UiConstraintException { String pkg = instance.namespaceUriToPackageName("urn:import:org.vaadin.test"); assertEquals("invalid conversion of namespace to package", "org.vaadin.test", pkg); }
@Test public void testNamespaceUriToPackageNameHttp() throws UiConstraintException { String pkg = instance.namespaceUriToPackageName("http: assertEquals("invalid conversion of namespace to package", "org.vaadin.test.some.pkg", pkg); } |
### Question:
EventBusManager { public <T extends EventBus> T getEventBus(Class<T> busType) { if (isPrivateEventBus(busType)) { throw new IllegalArgumentException("The bus " + busType + " is marked as private and it can be retrieved only from his presenter"); } assertEventBus(busType); EventBus eventBus = eventBusses.get(busType); return busType.cast(eventBus); } EventBusManager(); T register(Class<T> busType, Object subscriber); T register(Class<T> busType, Object subscriber,EventBus parentEventBus); void addSubscriber(Object subscriber); T getEventBus(Class<T> busType); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetEventBus_privateEventBus_NotSupported() { eventBusManager.getEventBus(StubPrivateEventBus.class); }
@Test public void testGetEventBus_NonPrivateEventBus_Supported() { eventBusManager.getEventBus(StubEventBus.class); } |
### Question:
EventBusManager { public <T extends EventBus> T register(Class<T> busType, Object subscriber) { return this.register(busType,subscriber,null); } EventBusManager(); T register(Class<T> busType, Object subscriber); T register(Class<T> busType, Object subscriber,EventBus parentEventBus); void addSubscriber(Object subscriber); T getEventBus(Class<T> busType); }### Answer:
@Test public void testRegister_NonPrivateEventBus_mustReturnSameBus() { EventBus eventBus = eventBusManager.register(StubEventBus.class,new Object()); EventBus eventBus2 = eventBusManager.register(StubEventBus.class,new Object()); Assert.assertSame("Different event bus instances",eventBus,eventBus2); }
@Test public void testRegister_NonPrivateEventBus_mustReturnDifferentBus() { EventBus eventBus = eventBusManager.register(StubPrivateEventBus.class,new Object()); EventBus eventBus2 = eventBusManager.register(StubPrivateEventBus.class,new Object()); Assert.assertNotSame("Same event bus instances",eventBus,eventBus2); } |
### Question:
EventBusHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("toString".equals(method.getName())) { return "EventBus<" + busName + ">"; } logger.info("Event received: {}", method.getName()); Event eventDef = method.getAnnotation(Event.class); logger.info("Event annotation: {}", eventDef); boolean localHandlerMethodFound = false; final boolean fallbackOnParent = parent != null; String eventName = method.getName(); String eventHandlerName = buildExpectedEventHandlerMethodName(eventName); Class<?>[] handlerTypes = eventDef.handlers(); for (Class<?> handlerType : handlerTypes) { Object handler = handlerRegistry.lookupReceiver(handlerType); if (handler == null) { logger.info("Handler {} not registered", handlerType.getName()); continue; } Method handlerMethod = lookupHandlerMethod(method, eventName, eventHandlerName, handler); if (handlerMethod == null) { continue; } try { localHandlerMethodFound = true; handlerMethod.invoke(handler, args); } catch (Exception e) { logger.debug("Failed to propagate event {} to handler {}", eventName, handlerType.getName()); throw new RuntimeException("During the invocations of the handler method an exception has occurred",e); } } if (!localHandlerMethodFound && fallbackOnParent) { delegateToParent(method.getName(),method.getParameterTypes(), args); } return null; } EventBusHandler(IEventReceiverRegistry hr, String name); EventBusHandler(IEventReceiverRegistry hr, String name, EventBus parent); @Override Object invoke(Object proxy, Method method, Object[] args); }### Answer:
@Test public void testParentFallbackEventsDelivery_notExistingEventOnChildWillBeForwarded() throws Exception{ StubPrivateEventBus parentEventBus = createNiceMock(StubPrivateEventBus.class); parentEventBus.niceEvent(); replay(mainEventReceiverRegistry, parentEventBus); StubEventBus eventBus = EventBusHandlerProxyFactory.createEventBusHandler(StubEventBus.class, mainEventReceiverRegistry,parentEventBus); Class<? extends EventBus> eventBusType = eventBus.getClass(); Method method = eventBusType.getMethod("niceEvent"); method.invoke(eventBus); verify(mainEventReceiverRegistry,parentEventBus); }
@Test(expected = Exception.class) public void testParentFallbackEventsDelivery_notExistingEventOnChildWillBeForwarded_exceptionIsThrown() throws Exception{ StubPrivateEventBus parentEventBus = createNiceMock(StubPrivateEventBus.class); parentEventBus.niceEvent(); expectLastCall().andThrow(new RuntimeException()); replay(mainEventReceiverRegistry, parentEventBus); StubEventBus eventBus = EventBusHandlerProxyFactory.createEventBusHandler(StubEventBus.class, mainEventReceiverRegistry,parentEventBus); Class<? extends EventBus> eventBusType = eventBus.getClass(); Method method = eventBusType.getMethod("niceEvent"); method.invoke(eventBus); verify(mainEventReceiverRegistry,parentEventBus); } |
### Question:
SpringPresenterFactory extends AbstractPresenterFactory implements ApplicationContextAware { @SuppressWarnings("unchecked") public IPresenter<?, ? extends EventBus> create(Object name,EventBus parentEventBus) { if (!(name instanceof String)) { throw new IllegalArgumentException("Argument is expected to be a bean name (string)"); } String beanName = (String) name; if (applicationContext.containsBean(beanName)) { IPresenter p = applicationContext.getBean(beanName, IPresenter.class); p.setApplication(application); p.setMessageSource(messageSource); Presenter def = p.getClass().getAnnotation(Presenter.class); if (def == null) { throw new IllegalArgumentException("Missing @Presenter annotation on bean '" + beanName + "'"); } EventBus eventBus = createEventBus((Class<IPresenter>) p.getClass(), p,parentEventBus); p.setEventBus(eventBus); try { Object view = viewFactory.createView(eventBusManager, p, def.view(), locale); p.setView(view); } catch (ViewFactoryException e) { logger.error("Failed to create view for presenter", e); } p.bind(); return p; } throw new IllegalArgumentException("No presenter is defined for name: " + name); } @Override void setApplicationContext(ApplicationContext applicationContext); @SuppressWarnings("unchecked") IPresenter<?, ? extends EventBus> create(Object name,EventBus parentEventBus); @Override IViewFactory getViewFactory(); }### Answer:
@Test public void testCreate() { IPresenter<?, ? extends EventBus> presenter = instance.createPresenter("spring"); assertNotNull("created presenter is null", presenter); assertNotNull("presenters view is null", presenter.getView()); assertTrue("presenters bind() method has not been called", ((SpringPresenter)presenter).bound); assertNotNull("presenter eventbus is null", presenter.getEventBus()); } |
### Question:
EventDeserializer extends AbstractAttributeStoreDeserializer<BaseEvent, EventBuilder> { @Override public BaseEvent build(EventBuilder entityBuilder) { return (BaseEvent) entityBuilder.build(); } @Override EventBuilder deserialize(JsonNode root); @Override BaseEvent build(EventBuilder entityBuilder); }### Answer:
@Test public void testBasicDeserialization() throws Exception { Event event = create("type", "id", 0) .attr("key", "value") .attr("key1", "valu1") .build(); String json = objectMapper.writeValueAsString(event); Event actualEntity = objectMapper.readValue(json, Event.class); assertEquals(actualEntity.getId(), event.getId()); assertEquals(actualEntity.getTimestamp(), event.getTimestamp()); assertEquals(new HashSet<>(actualEntity.getAttributes()), new HashSet<>(event.getAttributes())); }
@Test public void testBasicDeserialization2() throws Exception { Event event = create("type", "id", currentTimeMillis()) .attr("key", "value") .attr("key1", "valu1") .build(); String json = objectMapper.writeValueAsString(event); Event actualEntity = objectMapper.readValue(json, Event.class); assertEquals(actualEntity.getId(), event.getId()); assertEquals(actualEntity.getTimestamp(), event.getTimestamp()); assertEquals(new HashSet<>(actualEntity.getAttributes()), new HashSet<>(event.getAttributes())); } |
### Question:
CloseableIterators { public static <T> CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize) { return wrap(Iterators.limit(iterator, limitSize), iterator); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }### Answer:
@Test public void testLimit() { CloseableIterator<Integer> firstThree = limit(testIterator(), 3); assertTrue(elementsEqual(asList(1, 2, 3).iterator(), firstThree)); assertFalse(firstThree.hasNext()); firstThree.close(); } |
### Question:
CloseableIterators { public static <T> CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter) { return wrap(Iterators.filter(iterator, filter::test), iterator); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }### Answer:
@Test public void testFilter() { CloseableIterator<Integer> odd = filter(testIterator(), input -> input % 2 == 0); assertTrue(elementsEqual(asList(2, 4).iterator(), odd)); assertFalse(odd.hasNext()); odd.close(); } |
### Question:
CloseableIterators { public static <T> CloseableIterator<T> distinct(final CloseableIterator<T> iterator) { return wrap(Iterators2.distinct(iterator), iterator); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }### Answer:
@Test public void testDistinct() { CloseableIterator<Integer> distinct = distinct(fromIterator(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7).iterator())); assertTrue(elementsEqual(asList(1, 2, 3, 4, 5, 6, 7).iterator(), distinct)); assertFalse(distinct.hasNext()); distinct.close(); } |
### Question:
CloseableIterators { @SafeVarargs public static <T> CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators) { return chain(Iterators.forArray(iterators)); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }### Answer:
@SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testChain() { CloseableIterator iterator = chain(emptyIterator(), emptyIterator(), emptyIterator()); assertFalse(iterator.hasNext()); try { iterator.next(); fail(); } catch (NoSuchElementException ignored) { } iterator.close(); iterator = chain(fromIterator(asList(1).iterator())); try { assertTrue(iterator.hasNext()); iterator.next(); } catch (NoSuchElementException ex) { fail("should not throw NoSuchElementException here"); } finally { iterator.closeQuietly(); } iterator.close(); iterator = chain( fromIterator(asList(1, 2).iterator()), fromIterator(asList(3, 4).iterator()), fromIterator(asList(5, 6).iterator())); assertTrue(iterator.hasNext()); assertTrue(Iterators.elementsEqual(asList(1, 2, 3, 4, 5, 6).iterator(), iterator)); assertFalse(iterator.hasNext()); iterator.close(); } |
### Question:
CloseableIterators { public static <T> CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator) { requireNonNull(iterator); return new CloseableIterator<T>() { private boolean closed = false; @Override public void close() { if (closed) return; closed = true; iterator.close(); } @Override public boolean hasNext() { try { if (closed) return false; if (!iterator.hasNext()) { closeQuietly(); return false; } return true; } catch (RuntimeException re) { closeQuietly(); throw re; } } @Override public T next() { if (!closed) { try { return iterator.next(); } catch (RuntimeException re) { closeQuietly(); throw re; } } throw new NoSuchElementException(); } @Override public void remove() { if (!closed) { try { iterator.remove(); } catch (RuntimeException re) { closeQuietly(); throw re; } } throw new IllegalStateException(); } }; } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }### Answer:
@Test public void testAutoClose() { MockIterator<Integer> iterator = testIterator(); CloseableIterator<Integer> closeableIterator = autoClose(iterator); closeableIterator.close(); assertTrue(iterator.isClosed()); iterator = testIterator(); closeableIterator = autoClose(iterator); Iterators.size(closeableIterator); assertTrue(iterator.isClosed()); iterator = testExceptionThrowingIterator(); closeableIterator = autoClose(iterator); try { closeableIterator.next(); fail(); } catch (RuntimeException ignored) { } assertTrue(iterator.isClosed()); iterator = testIterator(); closeableIterator = autoClose(iterator); closeableIterator.close(); try { closeableIterator.next(); } catch (NoSuchElementException ignored) { } assertTrue(iterator.isClosed()); iterator = testExceptionThrowingIterator(); closeableIterator = autoClose(iterator); try { closeableIterator.remove(); fail(); } catch (RuntimeException ignored) { } assertTrue(iterator.isClosed()); iterator = testIterator(); closeableIterator = autoClose(iterator); closeableIterator.close(); try { closeableIterator.remove(); } catch (IllegalStateException ignored) { } assertTrue(iterator.isClosed()); } |
### Question:
CloseableIterables { @SuppressWarnings("unchecked") public static <T> CloseableIterable<T> emptyIterable() { return EMPTY_ITERABLE; } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }### Answer:
@Test public void testCloseEmptyMultipleTimes() { CloseableIterable<Integer> iterable = CloseableIterables.emptyIterable(); iterable.iterator(); iterable.closeQuietly(); iterable = CloseableIterables.emptyIterable(); iterable.iterator(); iterable.closeQuietly(); } |
### Question:
CloseableIterables { @Deprecated public static <T> CloseableIterable<T> wrap(final Iterable<T> iterable) { return fromIterable(iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }### Answer:
@Test public void testWrap() { CloseableIterable<Integer> wrapped = CloseableIterables.fromIterable(asList(1, 2, 3, 4, 5)); assertTrue(elementsEqual(asList(1, 2, 3, 4, 5), wrapped)); wrapped.close(); try { wrapped.iterator(); fail(); } catch (IllegalStateException ignored) { } } |
### Question:
CloseableIterables { public static <F, T> CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function) { return wrap(Iterables.transform(iterable, function::apply), iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }### Answer:
@Test public void testTransform() { CloseableIterable<Integer> addOne = transform(testIterable(), input -> input + 1); CloseableIterable<Integer> multTen = transform(addOne, input -> input * 10); assertTrue(elementsEqual(asList(20, 30, 40, 50, 60), multTen)); multTen.close(); try { multTen.iterator(); fail(); } catch (IllegalStateException ignored) { } } |
### Question:
CloseableIterables { public static <T> CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize) { return wrap(Iterables.limit(iterable, limitSize), iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }### Answer:
@Test public void testLimit() { CloseableIterable<Integer> firstThree = limit(testIterable(), 3); assertEquals(3, Iterables.size(firstThree)); assertTrue(elementsEqual(asList(1, 2, 3), firstThree)); firstThree.close(); try { firstThree.iterator(); fail(); } catch (IllegalStateException ignored) { } } |
### Question:
CloseableIterables { public static <T> CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type) { return wrap(Iterables.filter(iterable, type), iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }### Answer:
@Test public void testFilter() { CloseableIterable<Integer> odd = filter(testIterable(), input -> input % 2 == 0); assertTrue(elementsEqual(asList(2, 4), odd)); odd.close(); try { odd.iterator(); fail(); } catch (IllegalStateException ignored) { } } |
### Question:
CloseableIterables { public static <T> CloseableIterable<T> distinct(final CloseableIterable<T> iterable) { return wrap(Iterables2.distinct(iterable), iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }### Answer:
@Test public void testDistinct() { CloseableIterable<Integer> distinct = distinct(fromIterable(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7))); assertEquals(7, Iterables.size(distinct)); assertTrue(elementsEqual(asList(1, 2, 3, 4, 5, 6, 7), distinct)); distinct.close(); try { distinct.iterator(); fail(); } catch (IllegalStateException ignored) { } } |
### Question:
CloseableIterables { public static <T> CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable) { requireNonNull(iterable); return new FluentCloseableIterable<T>() { @Override protected void doClose() { iterable.close(); } @Override protected Iterator<T> retrieveIterator() { return CloseableIterators.autoClose( CloseableIterators.wrap(iterable.iterator(), iterable) ); } }; } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }### Answer:
@Test public void testAutoClose() { MockIterable<Integer> iterable = testIterable(); CloseableIterable<Integer> closeableIterable = autoClose(iterable); closeableIterable.close(); assertTrue(iterable.isClosed()); iterable = testIterable(); closeableIterable = autoClose(iterable); Iterator<Integer> iterator = closeableIterable.iterator(); Iterators.size(iterator); assertTrue(iterable.isClosed()); iterable = testExceptionThrowingIterable(); closeableIterable = autoClose(iterable); iterator = closeableIterable.iterator(); try { iterator.next(); fail(); } catch (RuntimeException ignored) { } assertTrue(iterable.isClosed()); } |
### Question:
FluentCloseableIterable extends AbstractCloseableIterable<T> { public final FluentCloseableIterable<T> limit(int size) { return from(CloseableIterables.limit(this, size)); } protected FluentCloseableIterable(); static FluentCloseableIterable<E> from(final CloseableIterable<E> iterable); final FluentCloseableIterable<T> autoClose(); @Override String toString(); final int size(); final boolean contains(Object target); final FluentCloseableIterable<T> cycle(); final FluentCloseableIterable<T> append(Iterable<? extends T> other); @SafeVarargs final FluentCloseableIterable<T> append(T... elements); final FluentCloseableIterable<T> filter(Predicate<? super T> predicate); final FluentCloseableIterable<E> filter(Class<E> type); final boolean anyMatch(Predicate<? super T> predicate); final boolean allMatch(Predicate<? super T> predicate); final Optional<T> firstMatch(Predicate<? super T> predicate); final FluentCloseableIterable<E> transform(Function<? super T, ? extends E> function); final FluentCloseableIterable<E> transformAndConcat(Function<? super T, ? extends Iterable<E>> function); final Optional<T> first(); final Optional<T> last(); final FluentCloseableIterable<T> skip(int numberToSkip); final FluentCloseableIterable<T> limit(int size); final boolean isEmpty(); final ImmutableList<T> toList(); final ImmutableList<T> toSortedList(Comparator<? super T> comparator); final ImmutableSet<T> toSet(); final ImmutableSortedSet<T> toSortedSet(Comparator<? super T> comparator); final ImmutableMultiset<T> toMultiset(); final ImmutableMap<T, V> toMap(Function<? super T, V> valueFunction); final ImmutableListMultimap<K, T> index(Function<? super T, K> keyFunction); final ImmutableMap<K, T> uniqueIndex(Function<? super T, K> keyFunction); final T[] toArray(Class<T> type); final C copyInto(C collection); final String join(Joiner joiner); final T get(int position); final Iterable<T> toSimpleIterable(); }### Answer:
@Test public void testLimit() { CloseableIterable<Integer> closeableIterable = fromIterable(asList(1, 2, 3, 4, 5)); FluentCloseableIterable<Integer> limit = FluentCloseableIterable. from(closeableIterable).limit(3); assertEquals(3, Iterables.size(limit)); limit.close(); } |
### Question:
Iterators2 { public static <T> Iterator<T> distinct(final Iterator<T> iterator) { requireNonNull(iterator); return new AbstractIterator<T>() { private final PeekingIterator<T> peekingIterator = peekingIterator(iterator); private T curr = null; @Override protected T computeNext() { while (peekingIterator.hasNext() && Objects.equals(curr, peekingIterator.peek())) { peekingIterator.next(); } if (!peekingIterator.hasNext()) return endOfData(); curr = peekingIterator.next(); return curr; } }; } private Iterators2(); static Iterator<T> distinct(final Iterator<T> iterator); static Iterator<List<T>> groupBy(final Iterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); }### Answer:
@Test public void distinctTest() throws Exception { Iterator<Integer> distinct = distinct(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7).iterator()); assertTrue(elementsEqual(asList(1, 2, 3, 4, 5, 6, 7).iterator(), distinct)); assertFalse(distinct.hasNext()); }
@Test(expected = NullPointerException.class) public void distinctNullIteratorTest() { distinct(null); } |
### Question:
Iterators2 { public static <T> Iterator<List<T>> groupBy(final Iterator<? extends T> iterator, final Function<? super T, ?> groupingFunction) { requireNonNull(iterator); requireNonNull(groupingFunction); return new AbstractIterator<List<T>>() { private final PeekingIterator<T> peekingIterator = peekingIterator(iterator); @Override protected List<T> computeNext() { if (!peekingIterator.hasNext()) return endOfData(); Object key = groupingFunction.apply(peekingIterator.peek()); List<T> group = new ArrayList<>(); do { group.add(peekingIterator.next()); } while (peekingIterator.hasNext() && Objects.equals(key, groupingFunction.apply(peekingIterator.peek()))); return unmodifiableList(group); } }; } private Iterators2(); static Iterator<T> distinct(final Iterator<T> iterator); static Iterator<List<T>> groupBy(final Iterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); }### Answer:
@Test public void groupByTest() { List<Integer> testdata = asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); Iterator<List<Integer>> grouped = groupBy(testdata.iterator(), input -> input / 5); assertTrue(grouped.hasNext()); assertEquals(asList(0, 1, 2, 3, 4), grouped.next()); assertEquals(asList(5, 6, 7, 8, 9), grouped.next()); assertFalse(grouped.hasNext()); grouped = groupBy(testdata.iterator(), input -> null); assertTrue(grouped.hasNext()); assertEquals(testdata, grouped.next()); assertFalse(grouped.hasNext()); grouped = groupBy(testdata.iterator(), input -> input); assertTrue(grouped.hasNext()); for (int i = 0; i< testdata.size(); i++) { assertTrue(grouped.hasNext()); List<Integer> group = grouped.next(); assertEquals(1, group.size()); assertEquals(new Integer(i), group.get(0)); } assertFalse(grouped.hasNext()); }
@Test(expected = NullPointerException.class) public void groupByNullIteratorTest() { groupBy(null, input -> null); }
@Test(expected = NullPointerException.class) public void groupByNullEquivTest() { groupBy(emptyIterator(), null); } |
### Question:
MoreInetAddresses { public static InetAddress forString(String ipString) { requireNonNull(ipString); InetAddress address = InetAddresses.forString(ipString); if (address instanceof Inet4Address && ipString.contains(":")) return getIPv4MappedIPv6Address((Inet4Address) address); return address; } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void forStringTest() { InetAddress address; address = MoreInetAddresses.forString("1.2.3.4"); assertTrue(address instanceof Inet4Address); assertEquals("1.2.3.4", toAddrString(address)); address = MoreInetAddresses.forString("::1.2.3.4"); assertTrue(address instanceof Inet6Address); assertEquals("::102:304", toAddrString(address)); address = MoreInetAddresses.forString("::ffff:1.2.3.4"); assertTrue(address instanceof Inet6Address); assertEquals("::ffff:102:304", toAddrString(address)); }
@Test(expected = NullPointerException.class) public void forStringNullTest() { MoreInetAddresses.forString(null); } |
### Question:
EntityDeserializer extends AbstractAttributeStoreDeserializer<BaseEntity, EntityBuilder> { @Override public BaseEntity build(EntityBuilder entityBuilder) { return (BaseEntity)entityBuilder.build(); } @Override EntityBuilder deserialize(JsonNode root); @Override BaseEntity build(EntityBuilder entityBuilder); }### Answer:
@Test public void testBasicDeserialization() throws Exception { Entity entity = create("type", "id") .attr("key", "value") .build(); String json = objectMapper.writeValueAsString(entity); Entity actualEntity = objectMapper.readValue(json, Entity.class); assertEquals(actualEntity.getType(), entity.getType()); assertEquals(actualEntity.getId(), entity.getId()); assertEquals(new HashSet<>(actualEntity.getAttributes()), new HashSet<>(entity.getAttributes())); } |
### Question:
MoreInetAddresses { public static Inet4Address forIPv4String(String ipString) { requireNonNull(ipString); try{ InetAddress parsed = forString(ipString); if (parsed instanceof Inet4Address) return (Inet4Address) parsed; } catch(Exception ignored){} throw new IllegalArgumentException(format("Invalid IPv4 representation: %s", ipString)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void forIpv4StringTest() { Inet4Address address; address = forIPv4String("1.2.3.4"); assertEquals("1.2.3.4", toAddrString(address)); }
@Test(expected = NullPointerException.class) public void forIpv4StringNullTest() { forIPv4String(null); }
@Test(expected = IllegalArgumentException.class) public void forIpv4StringWithIpv6Test() { forIPv4String("::1.2.3.4"); }
@Test(expected = IllegalArgumentException.class) public void forIpv4StringWithMappedIpv4Test() { forIPv4String("::ffff:1.2.3.4"); } |
### Question:
MoreInetAddresses { public static Inet6Address forIPv6String(String ipString) { requireNonNull(ipString); try{ InetAddress parsed = forString(ipString); if (parsed instanceof Inet6Address) return (Inet6Address) parsed; } catch(Exception ignored){} throw new IllegalArgumentException(format("Invalid IPv6 representation: %s", ipString)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void forIpv6StringTest() { Inet6Address address; address = forIPv6String("::1.2.3.4"); assertEquals("::102:304", toAddrString(address)); address = forIPv6String("::ffff:1.2.3.4"); assertEquals("::ffff:102:304", toAddrString(address)); }
@Test(expected = NullPointerException.class) public void forIpv6StringNullTest() { forIPv6String(null); }
@Test(expected = IllegalArgumentException.class) public void forIpv6StringWithIpv4Test() { forIPv6String("1.2.3.4"); } |
### Question:
MoreInetAddresses { public static boolean isMappedIPv4Address(Inet6Address ip) { byte bytes[] = ip.getAddress(); return ((bytes[0] == 0x00) && (bytes[1] == 0x00) && (bytes[2] == 0x00) && (bytes[3] == 0x00) && (bytes[4] == 0x00) && (bytes[5] == 0x00) && (bytes[6] == 0x00) && (bytes[7] == 0x00) && (bytes[8] == 0x00) && (bytes[9] == 0x00) && (bytes[10] == (byte)0xff) && (bytes[11] == (byte)0xff)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void isMappedIPv4AddressTest() throws UnknownHostException { byte[] bytes = new byte[]{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, (byte) 0xff, (byte) 0xff, 0x1, 0x2, 0x3, 0x4 }; Inet6Address address = Inet6Address.getByAddress(null, bytes, -1); assertTrue(MoreInetAddresses.isMappedIPv4Address(address)); bytes = new byte[]{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x2, 0x3, 0x4 }; address = Inet6Address.getByAddress(null, bytes, -1); assertFalse(MoreInetAddresses.isMappedIPv4Address(address)); }
@Test(expected = NullPointerException.class) public void isMappedIPv4AddressNullTest() { MoreInetAddresses.isMappedIPv4Address(null); } |
### Question:
MoreInetAddresses { public static Inet4Address getMappedIPv4Address(Inet6Address ip) { if (!isMappedIPv4Address(ip)) throw new IllegalArgumentException(String.format("Address '%s' is not IPv4-mapped.", toAddrString(ip))); return getInet4Address(copyOfRange(ip.getAddress(), 12, 16)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void getMappedIPv4AddressTest() throws UnknownHostException { byte[] bytes = new byte[]{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, (byte) 0xff, (byte) 0xff, 0x1, 0x2, 0x3, 0x4 }; Inet6Address address = Inet6Address.getByAddress(null, bytes, -1); Inet4Address inet4Address = MoreInetAddresses.getMappedIPv4Address(address); assertEquals(InetAddress.getByAddress(bytes), inet4Address); }
@Test(expected = NullPointerException.class) public void getMappedIPv4AddressNullTest() { MoreInetAddresses.getMappedIPv4Address(null); }
@Test(expected = IllegalArgumentException.class) public void getMappedIPv4AddressInvalidTypeTest() throws UnknownHostException { byte[] bytes = new byte[]{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x2, 0x3, 0x4 }; Inet6Address address = Inet6Address.getByAddress(null, bytes, -1); MoreInetAddresses.getMappedIPv4Address(address); } |
### Question:
Iterables2 { public static <T> Iterable<T> distinct(final Iterable<T> iterable) { requireNonNull(iterable); return () -> Iterators2.distinct(iterable.iterator()); } private Iterables2(); static Iterable<T> simpleIterable(final Iterable<T> iterable); static Iterable<T> distinct(final Iterable<T> iterable); static Iterable<List<T>> groupBy(final Iterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); }### Answer:
@Test public void distinctTest() throws Exception { Iterable<Integer> distinct = distinct(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7)); assertEquals(asList(1, 2, 3, 4, 5, 6, 7), newArrayList(distinct)); }
@Test(expected = NullPointerException.class) public void distinctNullIteratorTest() { distinct(null); } |
### Question:
MoreInetAddresses { public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) { return isMappedIPv4Address(ip) || InetAddresses.hasEmbeddedIPv4ClientAddress(ip); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void hasEmbeddedIPv4ClientAddressTest() { assertTrue(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("::ffff:1.2.3.4"))); assertTrue(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("::1.2.3.4"))); assertTrue(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("2002:102:304::"))); assertFalse(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("1::1.2.3.4"))); }
@Test(expected = NullPointerException.class) public void hasEmbeddedIPv4ClientAddressNullTest() { MoreInetAddresses.hasEmbeddedIPv4ClientAddress(null); } |
### Question:
MoreInetAddresses { public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) { if (isMappedIPv4Address(ip)) return getMappedIPv4Address(ip); return InetAddresses.getEmbeddedIPv4ClientAddress(ip); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void getEmbeddedIPv4ClientAddressTest() { assertEquals(MoreInetAddresses.forString("1.2.3.4"), MoreInetAddresses.getEmbeddedIPv4ClientAddress(forIPv6String("::ffff:1.2.3.4"))); assertEquals(MoreInetAddresses.forString("1.2.3.4"), MoreInetAddresses.getEmbeddedIPv4ClientAddress(forIPv6String("::1.2.3.4"))); assertEquals(MoreInetAddresses.forString("1.2.3.4"), MoreInetAddresses.getEmbeddedIPv4ClientAddress(forIPv6String("2002:102:304::"))); }
@Test(expected = NullPointerException.class) public void getEmbeddedIPv4ClientAddressNullTest() { MoreInetAddresses.getEmbeddedIPv4ClientAddress(null); } |
### Question:
MoreInetAddresses { public static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip) { byte[] from = ip.getAddress(); byte[] bytes = new byte[] { 0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0, 0x0,0x0,(byte)0xff,(byte)0xff, from[0],from[1],from[2],from[3] }; return getInet6Address(bytes); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void getIPv4MappedIPv6AddressTest() { assertEquals("::ffff:102:304", toAddrString(MoreInetAddresses.getIPv4MappedIPv6Address(forIPv4String("1.2.3.4")))); }
@Test(expected = NullPointerException.class) public void getIPv4MappedIPv6AddressNullTest() { MoreInetAddresses.getIPv4MappedIPv6Address(null); } |
### Question:
MoreInetAddresses { public static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip) { byte[] from = ip.getAddress(); byte[] bytes = new byte[] { 0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0, from[0],from[1],from[2],from[3] }; return getInet6Address(bytes); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }### Answer:
@Test public void getIPv4CompatIPv6AddressTest() { assertEquals("::102:304", toAddrString(MoreInetAddresses.getIPV4CompatIPv6Address(forIPv4String("1.2.3.4")))); }
@Test(expected = NullPointerException.class) public void getIPv4CompatIPv6AddressNullTest() { MoreInetAddresses.getIPV4CompatIPv6Address(null); } |
### Question:
IP implements Serializable { @Override public String toString() { return toAddrString(address); } protected IP(T address); @SuppressWarnings("unchecked") T getAddress(); byte[] toByteArray(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void ipv4ToStringTest() { IPv4 ip = new IPv4(forIPv4String("1.2.3.4")); assertEquals("1.2.3.4", ip.toString()); }
@Test public void ipv6ToStringTest() { IPv6 ip = new IPv6(forIPv6String("::1.2.3.4")); assertEquals("::102:304", ip.toString()); ip = new IPv6(forIPv6String("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); assertEquals("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", ip.toString()); ip = new IPv6(forIPv6String("1234:0000:0000:0000:0000:0000:0000:1234")); assertEquals("1234::1234", ip.toString()); } |
### Question:
QueryBuilder { public QueryBuilder eq(String type, Object value) { checkFinished(); if (this.current == null) { this.current = new AndNode(); finished = true; } EqualsLeaf equalsLeaf = new EqualsLeaf<>(type, value, current); this.current.addChild(equalsLeaf); return this; } protected QueryBuilder(); protected QueryBuilder(ParentNode current, QueryBuilder parentBuilder); static QueryBuilder create(); QueryBuilder and(); QueryBuilder or(); Node build(); QueryBuilder eq(String type, Object value); QueryBuilder has(String key); QueryBuilder hasNot(String key); QueryBuilder in(String key, Collection<Object> values); QueryBuilder in(String key, Object... values); QueryBuilder notIn(String key, Collection<Object> values); QueryBuilder notIn(String key, Object... values); QueryBuilder notEq(String type, Object value); QueryBuilder lessThan(String type, Object value); QueryBuilder lessThanEq(String type, Object value); QueryBuilder greaterThan(String type, Object value); QueryBuilder greaterThanEq(String type, Object value); QueryBuilder range(String type, Object start, Object end); QueryBuilder end(); }### Answer:
@Test public void testEq() throws Exception { Node build = QueryBuilder.create().eq("feedName", "netflowv9").build(); StringWriter writer = new StringWriter(); build.accept(new PrintNodeVisitor(writer)); assertEquals("AndNode(Equals[feedName,netflowv9],),", writer.toString()); } |
### Question:
CollapseParentClauseVisitor implements NodeVisitor { @Override public void end(ParentNode node) { } @Override void begin(ParentNode node); @Override void end(ParentNode node); @Override void visit(Leaf node); }### Answer:
@Test public void testCollapseAndAndChildren() throws Exception { StringWriter writer = new StringWriter(); Node node = QueryBuilder.create().and().and().eq("k1", "v1").eq("k2", "v2").end().end().build(); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); node.accept(new CollapseParentClauseVisitor()); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); }
@Test public void testCollapseAndAndOrChildren() throws Exception { StringWriter writer = new StringWriter(); Node node = QueryBuilder.create().and().and().eq("k1", "v1").eq("k2", "v2").end().or().eq("k3", "v3").eq("k4", "v4").end().end().build(); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); node.accept(new CollapseParentClauseVisitor()); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); } |
### Question:
LessThanEqualsCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) <= 0) return true; } return false; } LessThanEqualsCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer:
@Test public void test() { LessThanEqualsCriteria criteria = new LessThanEqualsCriteria<>("key1", 5, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id"); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 10); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 5); assertTrue(criteria.test(entity.build())); entity = entity.attr("key1", 4); assertTrue(criteria.test(entity.build())); } |
### Question:
EqualsCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) == 0) return true; } return false; } EqualsCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer:
@Test public void testEquals() { Criteria eq = new EqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val1"); assertTrue(eq.test(entity.build())); }
@Test public void testNotEquals() { Criteria eq = new EqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val2"); assertFalse(eq.test(entity.build())); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.