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); stat...
### Question: LeaderElectingController implements Controller { public LeaderElectingController(LeaderElector leaderElector, Controller delegateController) { this.delegateController = delegateController; this.leaderElector = leaderElector; } LeaderElectingController(LeaderElector leaderElector, Controller delegateContro...
### 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.strea...
### 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 ignore...
### 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> ...
### 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,...
### 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() ...
### 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";...
### 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()); ...
### 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,...
### 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, Stri...
### 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)...
### 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 resourcePlura...
### 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 resourcePlura...
### 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, St...
### 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); GenericKu...
### 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",...
### 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(), "...
### 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 ...
### 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 AP...
### 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, Cons...
### 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 deletionHandlingMetaNamespac...
### 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( Ap...
### 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 = newIndexer...
### 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...
### 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); In...
### 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 ...
### 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 Api...
### 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); ...
### 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...
### 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 boolea...
### 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, PatchCallFu...
### 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 eq...
### 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(...
### 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)); ...
### 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 (suffi...
### 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 Illeg...
### 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 g...
### 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, ...
### 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);...
### 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.substrin...
### 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 offse...
### 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 readLon...
### 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 ...
### 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) | (...
### 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 readUshor...
### 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 offs...
### 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);...
### 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 ...
### 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(); } CompositeScanner...
### 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...
### 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 =...
### 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 synchronize...
### 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,Str...
### Question: ConfigurationManager { public static Configuration getConfigInstance() throws InitConfigurationException { if (instance == null) { synchronized (ConfigurationManager.class) { if (instance == null) { instance = createDefaultConfigInstance(); try { customProperties = Tools.loadPropertiesFromFile(TEMPFILENAM...
### 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 == nu...
### 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(S...
### 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, Even...
### 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(...
### 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(); ...
### 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.setCurren...
### 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....
### 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.getCl...
### 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)) { p...
### 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.g...
### 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(O...
### 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.getAnno...
### 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...
### 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); }##...
### 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> ...
### 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 CloseableI...
### 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> ...
### 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(Ite...
### 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(); } @Overr...
### 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 CloseableIte...
### 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 Closea...
### 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(St...
### 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> ...
### 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> fro...
### 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> ...
### 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 Cl...
### 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 FluentClose...
### 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.h...
### 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 = peekingIte...
### 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 M...
### 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 entityBuilde...
### 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 re...
### 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 re...
### 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]...
### 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 MoreInetAdd...
### 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)...
### 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); sta...
### 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 Inet4Add...
### 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 MoreInetAddres...
### 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 ...
### 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 pu...
### 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(); prot...
### 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 wri...
### 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(Stri...
### 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...