proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
kekingcn_kkFileView
|
kkFileView/server/src/main/java/cn/keking/utils/UrlEncoderUtils.java
|
UrlEncoderUtils
|
hasUrlEncoded
|
class UrlEncoderUtils {
private static BitSet dontNeedEncoding;
static {
dontNeedEncoding = new BitSet(256);
int i;
for (i = 'a'; i <= 'z'; i++) {
dontNeedEncoding.set(i);
}
for (i = 'A'; i <= 'Z'; i++) {
dontNeedEncoding.set(i);
}
for (i = '0'; i <= '9'; i++) {
dontNeedEncoding.set(i);
}
dontNeedEncoding.set('+');
/**
* 这里会有误差,比如输入一个字符串 123+456,它到底是原文就是123+456还是123 456做了urlEncode后的内容呢?<br>
* 其实问题是一样的,比如遇到123%2B456,它到底是原文即使如此,还是123+456 urlEncode后的呢? <br>
* 在这里,我认为只要符合urlEncode规范的,就当作已经urlEncode过了<br>
* 毕竟这个方法的初衷就是判断string是否urlEncode过<br>
*/
dontNeedEncoding.set('-');
dontNeedEncoding.set('_');
dontNeedEncoding.set('.');
dontNeedEncoding.set('*');
}
/**
* 判断str是否urlEncoder.encode过<br>
* 经常遇到这样的情况,拿到一个URL,但是搞不清楚到底要不要encode.<Br>
* 不做encode吧,担心出错,做encode吧,又怕重复了<Br>
*
* @param str
* @return
*/
public static boolean hasUrlEncoded(String str) {<FILL_FUNCTION_BODY>}
/**
* 判断c是否是16进制的字符
*
* @param c
* @return
*/
private static boolean isDigit16Char(char c) {
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F');
}
}
|
/**
* 支持JAVA的URLEncoder.encode出来的string做判断。 即: 将' '转成'+' <br>
* 0-9a-zA-Z保留 <br>
* '-','_','.','*'保留 <br>
* 其他字符转成%XX的格式,X是16进制的大写字符,范围是[0-9A-F]
*/
boolean needEncode = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (dontNeedEncoding.get((int) c)) {
continue;
}
if (c == '%' && (i + 2) < str.length()) {
// 判断是否符合urlEncode规范
char c1 = str.charAt(++i);
char c2 = str.charAt(++i);
if (isDigit16Char(c1) && isDigit16Char(c2)) {
continue;
}
}
// 其他字符,肯定需要urlEncode
needEncode = true;
break;
}
return !needEncode;
| 541
| 312
| 853
|
<no_super_class>
|
kekingcn_kkFileView
|
kkFileView/server/src/main/java/cn/keking/web/controller/OnlinePreviewController.java
|
OnlinePreviewController
|
onlinePreview
|
class OnlinePreviewController {
public static final String BASE64_DECODE_ERROR_MSG = "Base64解码失败,请检查你的 %s 是否采用 Base64 + urlEncode 双重编码了!";
private final Logger logger = LoggerFactory.getLogger(OnlinePreviewController.class);
private final FilePreviewFactory previewFactory;
private final CacheService cacheService;
private final FileHandlerService fileHandlerService;
private final OtherFilePreviewImpl otherFilePreview;
private static final RestTemplate restTemplate = new RestTemplate();
private static final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
private static final ObjectMapper mapper = new ObjectMapper();
public OnlinePreviewController(FilePreviewFactory filePreviewFactory, FileHandlerService fileHandlerService, CacheService cacheService, OtherFilePreviewImpl otherFilePreview) {
this.previewFactory = filePreviewFactory;
this.fileHandlerService = fileHandlerService;
this.cacheService = cacheService;
this.otherFilePreview = otherFilePreview;
}
@GetMapping( "/onlinePreview")
public String onlinePreview(String url, Model model, HttpServletRequest req) {<FILL_FUNCTION_BODY>}
@GetMapping( "/picturesPreview")
public String picturesPreview(String urls, Model model, HttpServletRequest req) {
String fileUrls;
try {
fileUrls = WebUtils.decodeUrl(urls);
// 防止XSS攻击
fileUrls = KkFileUtils.htmlEscape(fileUrls);
} catch (Exception ex) {
String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "urls");
return otherFilePreview.notSupportedFile(model, errorMsg);
}
logger.info("预览文件url:{},urls:{}", fileUrls, urls);
// 抽取文件并返回文件列表
String[] images = fileUrls.split("\\|");
List<String> imgUrls = Arrays.asList(images);
model.addAttribute("imgUrls", imgUrls);
String currentUrl = req.getParameter("currentUrl");
if (StringUtils.hasText(currentUrl)) {
String decodedCurrentUrl = new String(Base64.decodeBase64(currentUrl));
decodedCurrentUrl = KkFileUtils.htmlEscape(decodedCurrentUrl); // 防止XSS攻击
model.addAttribute("currentUrl", decodedCurrentUrl);
} else {
model.addAttribute("currentUrl", imgUrls.get(0));
}
return PICTURE_FILE_PREVIEW_PAGE;
}
/**
* 根据url获取文件内容
* 当pdfjs读取存在跨域问题的文件时将通过此接口读取
*
* @param urlPath url
* @param response response
*/
@GetMapping("/getCorsFile")
public void getCorsFile(String urlPath, HttpServletResponse response,FileAttribute fileAttribute) throws IOException {
URL url;
try {
urlPath = WebUtils.decodeUrl(urlPath);
url = WebUtils.normalizedURL(urlPath);
} catch (Exception ex) {
logger.error(String.format(BASE64_DECODE_ERROR_MSG, urlPath),ex);
return;
}
assert urlPath != null;
if (!urlPath.toLowerCase().startsWith("http") && !urlPath.toLowerCase().startsWith("https") && !urlPath.toLowerCase().startsWith("ftp")) {
logger.info("读取跨域文件异常,可能存在非法访问,urlPath:{}", urlPath);
return;
}
InputStream inputStream = null;
logger.info("读取跨域pdf文件url:{}", urlPath);
if (!urlPath.toLowerCase().startsWith("ftp:")) {
factory.setConnectionRequestTimeout(2000);
factory.setConnectTimeout(10000);
factory.setReadTimeout(72000);
HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new DefaultRedirectStrategy()).build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
RequestCallback requestCallback = request -> {
request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
String proxyAuthorization = fileAttribute.getKkProxyAuthorization();
if(StringUtils.hasText(proxyAuthorization)){
Map<String,String> proxyAuthorizationMap = mapper.readValue(proxyAuthorization, Map.class);
proxyAuthorizationMap.forEach((key, value) -> request.getHeaders().set(key, value));
}
};
try {
restTemplate.execute(url.toURI(), HttpMethod.GET, requestCallback, fileResponse -> {
IOUtils.copy(fileResponse.getBody(), response.getOutputStream());
return null;
});
} catch (Exception e) {
System.out.println(e);
}
}else{
try {
if(urlPath.contains(".svg")) {
response.setContentType("image/svg+xml");
}
inputStream = (url).openStream();
IOUtils.copy(inputStream, response.getOutputStream());
} catch (IOException e) {
logger.error("读取跨域文件异常,url:{}", urlPath);
} finally {
IOUtils.closeQuietly(inputStream);
}
}
}
/**
* 通过api接口入队
*
* @param url 请编码后在入队
*/
@GetMapping("/addTask")
@ResponseBody
public String addQueueTask(String url) {
logger.info("添加转码队列url:{}", url);
cacheService.addQueueTask(url);
return "success";
}
}
|
String fileUrl;
try {
fileUrl = WebUtils.decodeUrl(url);
} catch (Exception ex) {
String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "url");
return otherFilePreview.notSupportedFile(model, errorMsg);
}
FileAttribute fileAttribute = fileHandlerService.getFileAttribute(fileUrl, req); //这里不在进行URL 处理了
model.addAttribute("file", fileAttribute);
FilePreview filePreview = previewFactory.get(fileAttribute);
logger.info("预览文件url:{},previewType:{}", fileUrl, fileAttribute.getType());
return filePreview.filePreviewHandle(WebUtils.urlEncoderencode(fileUrl), model, fileAttribute); //统一在这里处理 url
| 1,528
| 205
| 1,733
|
<no_super_class>
|
kekingcn_kkFileView
|
kkFileView/server/src/main/java/cn/keking/web/filter/AttributeSetFilter.java
|
AttributeSetFilter
|
setWatermarkAttribute
|
class AttributeSetFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
this.setWatermarkAttribute(request);
this.setFileAttribute(request);
filterChain.doFilter(request, response);
}
/**
* 设置办公文具预览逻辑需要的属性
* @param request request
*/
private void setFileAttribute(ServletRequest request){
HttpServletRequest httpRequest = (HttpServletRequest) request;
request.setAttribute("pdfPresentationModeDisable", ConfigConstants.getPdfPresentationModeDisable());
request.setAttribute("pdfOpenFileDisable", ConfigConstants.getPdfOpenFileDisable());
request.setAttribute("pdfPrintDisable", ConfigConstants.getPdfPrintDisable());
request.setAttribute("pdfDownloadDisable", ConfigConstants.getPdfDownloadDisable());
request.setAttribute("pdfBookmarkDisable", ConfigConstants.getPdfBookmarkDisable());
request.setAttribute("pdfDisableEditing", ConfigConstants.getPdfDisableEditing());
request.setAttribute("switchDisabled", ConfigConstants.getOfficePreviewSwitchDisabled());
request.setAttribute("fileUploadDisable", ConfigConstants.getFileUploadDisable());
request.setAttribute("beian", ConfigConstants.getBeian());
request.setAttribute("size", ConfigConstants.maxSize());
request.setAttribute("deleteCaptcha", ConfigConstants.getDeleteCaptcha());
request.setAttribute("homePageNumber", ConfigConstants.getHomePageNumber());
request.setAttribute("homePagination", ConfigConstants.getHomePagination());
request.setAttribute("homePageSize", ConfigConstants.getHomePageSize());
request.setAttribute("homeSearch", ConfigConstants.getHomeSearch());
}
/**
* 设置水印属性
* @param request request
*/
private void setWatermarkAttribute(ServletRequest request) {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
}
}
|
String watermarkTxt= KkFileUtils.htmlEscape(request.getParameter("watermarkTxt"));
request.setAttribute("watermarkTxt", watermarkTxt != null ? watermarkTxt : WatermarkConfigConstants.getWatermarkTxt());
String watermarkXSpace = KkFileUtils.htmlEscape(request.getParameter("watermarkXSpace"));
if (!KkFileUtils.isInteger(watermarkXSpace)){
watermarkXSpace =null;
}
request.setAttribute("watermarkXSpace", watermarkXSpace != null ? watermarkXSpace : WatermarkConfigConstants.getWatermarkXSpace());
String watermarkYSpace = KkFileUtils.htmlEscape(request.getParameter("watermarkYSpace"));
if (!KkFileUtils.isInteger(watermarkYSpace)){
watermarkYSpace =null;
}
request.setAttribute("watermarkYSpace", watermarkYSpace != null ? watermarkYSpace : WatermarkConfigConstants.getWatermarkYSpace());
String watermarkFont = KkFileUtils.htmlEscape(request.getParameter("watermarkFont"));
request.setAttribute("watermarkFont", watermarkFont != null ? watermarkFont : WatermarkConfigConstants.getWatermarkFont());
String watermarkFontsize = KkFileUtils.htmlEscape(request.getParameter("watermarkFontsize"));
request.setAttribute("watermarkFontsize", watermarkFontsize != null ? watermarkFontsize : WatermarkConfigConstants.getWatermarkFontsize());
String watermarkColor = KkFileUtils.htmlEscape(request.getParameter("watermarkColor"));
request.setAttribute("watermarkColor", watermarkColor != null ? watermarkColor : WatermarkConfigConstants.getWatermarkColor());
String watermarkAlpha = KkFileUtils.htmlEscape(request.getParameter("watermarkAlpha"));
if (!KkFileUtils.isInteger(watermarkAlpha)){
watermarkAlpha =null;
}
request.setAttribute("watermarkAlpha", watermarkAlpha != null ? watermarkAlpha : WatermarkConfigConstants.getWatermarkAlpha());
String watermarkWidth = KkFileUtils.htmlEscape(request.getParameter("watermarkWidth"));
if (!KkFileUtils.isInteger(watermarkWidth)){
watermarkWidth =null;
}
request.setAttribute("watermarkWidth", watermarkWidth != null ? watermarkWidth : WatermarkConfigConstants.getWatermarkWidth());
String watermarkHeight = KkFileUtils.htmlEscape(request.getParameter("watermarkHeight"));
if (!KkFileUtils.isInteger(watermarkHeight)){
watermarkHeight =null;
}
request.setAttribute("watermarkHeight", watermarkHeight != null ? watermarkHeight : WatermarkConfigConstants.getWatermarkHeight());
String watermarkAngle = KkFileUtils.htmlEscape(request.getParameter("watermarkAngle"));
if (!KkFileUtils.isInteger(watermarkAngle)){
watermarkAngle =null;
}
request.setAttribute("watermarkAngle", watermarkAngle != null ? watermarkAngle : WatermarkConfigConstants.getWatermarkAngle());
| 542
| 789
| 1,331
|
<no_super_class>
|
kekingcn_kkFileView
|
kkFileView/server/src/main/java/cn/keking/web/filter/BaseUrlFilter.java
|
BaseUrlFilter
|
getBaseUrl
|
class BaseUrlFilter implements Filter {
private static String BASE_URL;
public static String getBaseUrl() {<FILL_FUNCTION_BODY>}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String baseUrl;
String configBaseUrl = ConfigConstants.getBaseUrl();
final HttpServletRequest servletRequest = (HttpServletRequest) request;
//1、支持通过 http header 中 X-Base-Url 来动态设置 baseUrl 以支持多个域名/项目的共享使用
final String urlInHeader = servletRequest.getHeader("X-Base-Url");
if (StringUtils.isNotEmpty(urlInHeader)) {
baseUrl = urlInHeader;
} else if (configBaseUrl != null && !ConfigConstants.DEFAULT_VALUE.equalsIgnoreCase(configBaseUrl)) {
//2、如果配置文件中配置了 baseUrl 且不为 default 则以配置文件为准
baseUrl = configBaseUrl;
} else {
//3、默认动态拼接 baseUrl
baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ servletRequest.getContextPath() + "/";
}
if (!baseUrl.endsWith("/")) {
baseUrl = baseUrl.concat("/");
}
BASE_URL = baseUrl;
request.setAttribute("baseUrl", baseUrl);
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
|
String baseUrl;
try {
baseUrl = (String) RequestContextHolder.currentRequestAttributes().getAttribute("baseUrl", 0);
} catch (Exception e) {
baseUrl = BASE_URL;
}
return baseUrl;
| 429
| 66
| 495
|
<no_super_class>
|
kekingcn_kkFileView
|
kkFileView/server/src/main/java/cn/keking/web/filter/SecurityFilterProxy.java
|
SecurityFilterProxy
|
doFilterInternal
|
class SecurityFilterProxy extends OncePerRequestFilter {
private String NOT_ALLOW_METHODS = "TRACE";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
}
|
if((","+NOT_ALLOW_METHODS+",").indexOf(","+request.getMethod().toUpperCase()+",") > -1) {
response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
response.setHeader("Content-Type", "text/html; charset=iso-8859-1");
response.getWriter().println("Method Not Allowed");
return;
}
super.doFilter(request, response, filterChain);
| 80
| 124
| 204
|
<no_super_class>
|
kekingcn_kkFileView
|
kkFileView/server/src/main/java/cn/keking/web/filter/TrustDirFilter.java
|
TrustDirFilter
|
init
|
class TrustDirFilter implements Filter {
private String notTrustDirView;
private final Logger logger = LoggerFactory.getLogger(TrustDirFilter.class);
@Override
public void init(FilterConfig filterConfig) {<FILL_FUNCTION_BODY>}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String url = WebUtils.getSourceUrl(request);
if (!allowPreview(url)) {
response.getWriter().write(this.notTrustDirView);
response.getWriter().close();
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
private boolean allowPreview(String urlPath) {
//判断URL是否合法
if(!StringUtils.hasText(urlPath) || !WebUtils.isValidUrl(urlPath)) {
return false ;
}
try {
URL url = WebUtils.normalizedURL(urlPath);
if ("file".equals(url.getProtocol().toLowerCase(Locale.ROOT))) {
String filePath = URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8.name());
if (OSUtils.IS_OS_WINDOWS) {
filePath = filePath.replaceAll("/", "\\\\");
}
return filePath.startsWith(ConfigConstants.getFileDir()) || filePath.startsWith(ConfigConstants.getLocalPreviewDir());
}
return true;
} catch (IOException | GalimatiasParseException e) {
logger.error("解析URL异常,url:{}", urlPath, e);
return false;
}
}
}
|
ClassPathResource classPathResource = new ClassPathResource("web/notTrustDir.html");
try {
classPathResource.getInputStream();
byte[] bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
this.notTrustDirView = new String(bytes, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
| 445
| 104
| 549
|
<no_super_class>
|
kekingcn_kkFileView
|
kkFileView/server/src/main/java/cn/keking/web/filter/TrustHostFilter.java
|
TrustHostFilter
|
doFilter
|
class TrustHostFilter implements Filter {
private String notTrustHostHtmlView;
@Override
public void init(FilterConfig filterConfig) {
ClassPathResource classPathResource = new ClassPathResource("web/notTrustHost.html");
try {
classPathResource.getInputStream();
byte[] bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
this.notTrustHostHtmlView = new String(bytes, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
public boolean isNotTrustHost(String host) {
if (CollectionUtils.isNotEmpty(ConfigConstants.getNotTrustHostSet())) {
return ConfigConstants.getNotTrustHostSet().contains(host);
}
if (CollectionUtils.isNotEmpty(ConfigConstants.getTrustHostSet())) {
return !ConfigConstants.getTrustHostSet().contains(host);
}
return false;
}
@Override
public void destroy() {
}
}
|
String url = WebUtils.getSourceUrl(request);
String host = WebUtils.getHost(url);
assert host != null;
if (isNotTrustHost(host)) {
String html = this.notTrustHostHtmlView.replace("${current_host}", host);
response.getWriter().write(html);
response.getWriter().close();
} else {
chain.doFilter(request, response);
}
| 311
| 115
| 426
|
<no_super_class>
|
kekingcn_kkFileView
|
kkFileView/server/src/main/java/cn/keking/web/filter/UrlCheckFilter.java
|
UrlCheckFilter
|
doFilter
|
class UrlCheckFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
}
|
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String servletPath = httpServletRequest.getServletPath();
boolean redirect = false;
// servletPath 中不能包含 //
if (servletPath.contains("//")) {
servletPath = servletPath.replaceAll("//+", "/");
redirect = true;
}
// 不能以 / 结尾,同时考虑 **首页** 的特殊性
if (servletPath.endsWith("/") && servletPath.length() > 1) {
servletPath = servletPath.substring(0, servletPath.length() - 1);
redirect = true;
}
if (redirect) {
String redirectUrl;
if (StringUtils.isBlank(BaseUrlFilter.getBaseUrl())) {
// 正常 BaseUrlFilter 有限此 Filter 执行,不会执行到此
redirectUrl = httpServletRequest.getContextPath() + servletPath;
} else {
if (BaseUrlFilter.getBaseUrl().endsWith("/") && servletPath.startsWith("/")) {
// BaseUrlFilter.getBaseUrl() 以 / 结尾,servletPath 以 / 开头,需再去除一次 //
redirectUrl = BaseUrlFilter.getBaseUrl() + servletPath.substring(1);
} else {
redirectUrl = BaseUrlFilter.getBaseUrl() + servletPath;
}
}
((HttpServletResponse) response).sendRedirect(redirectUrl + "?" + httpServletRequest.getQueryString());
} else {
chain.doFilter(request, response);
}
| 55
| 411
| 466
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/AbstractCustomResourceHandler.java
|
AbstractCustomResourceHandler
|
visitTypeDefInParallel
|
class AbstractCustomResourceHandler {
protected final Resources resources;
private final boolean parallel;
protected AbstractCustomResourceHandler(Resources resources, boolean parallel) {
this.resources = resources;
this.parallel = parallel;
}
public void handle(CustomResourceInfo config) {
final String name = config.crdName();
final String version = config.version();
TypeDef def = config.definition();
SpecReplicasPathDetector specReplicasPathDetector = new SpecReplicasPathDetector();
StatusReplicasPathDetector statusReplicasPathDetector = new StatusReplicasPathDetector();
LabelSelectorPathDetector labelSelectorPathDetector = new LabelSelectorPathDetector();
AdditionalPrinterColumnDetector additionalPrinterColumnDetector = new AdditionalPrinterColumnDetector();
ClassDependenciesVisitor traversedClassesVisitor = new ClassDependenciesVisitor(config.crClassName(), name);
List<Visitor<TypeDefBuilder>> visitors = new ArrayList<>();
if (config.specClassName().isPresent()) {
visitors.add(specReplicasPathDetector);
}
if (config.statusClassName().isPresent()) {
visitors.add(statusReplicasPathDetector);
}
visitors.add(labelSelectorPathDetector);
visitors.add(additionalPrinterColumnDetector);
visitors.add(traversedClassesVisitor);
visitTypeDef(def, visitors);
addDecorators(config, def, specReplicasPathDetector.getPath(),
statusReplicasPathDetector.getPath(), labelSelectorPathDetector.getPath());
Map<String, Property> additionalPrinterColumns = new HashMap<>(additionalPrinterColumnDetector.getProperties());
additionalPrinterColumns.forEach((path, property) -> {
Map<String, Object> parameters = property.getAnnotations().stream()
.filter(a -> a.getClassRef().getName().equals("PrinterColumn")).map(AnnotationRef::getParameters)
.findFirst().orElse(Collections.emptyMap());
String type = AbstractJsonSchema.getSchemaTypeFor(property.getTypeRef());
String column = (String) parameters.get("name");
if (Utils.isNullOrEmpty(column)) {
column = property.getName().toUpperCase();
}
String description = property.getComments().stream().filter(l -> !l.trim().startsWith("@"))
.collect(Collectors.joining(" ")).trim();
String format = (String) parameters.get("format");
int priority = (int) parameters.getOrDefault("priority", 0);
resources.decorate(
getPrinterColumnDecorator(name, version, path, type, column, description, format, priority));
});
}
private TypeDef visitTypeDef(TypeDef def, List<Visitor<TypeDefBuilder>> visitors) {
if (visitors.isEmpty()) {
return def;
}
if (parallel) {
return visitTypeDefInParallel(def, visitors);
} else {
return visitTypeDefSequentially(def, visitors);
}
}
private TypeDef visitTypeDefSequentially(TypeDef def, List<Visitor<TypeDefBuilder>> visitors) {
TypeDefBuilder builder = new TypeDefBuilder(def);
for (Visitor<TypeDefBuilder> visitor : visitors) {
builder.accept(visitor);
}
return builder.build();
}
private TypeDef visitTypeDefInParallel(TypeDef def, List<Visitor<TypeDefBuilder>> visitors) {<FILL_FUNCTION_BODY>}
/**
* Provides the decorator implementation associated with the CRD generation version.
*
* @param name the resource name
* @param version the associated version
* @param path the path from which the printer column is extracted
* @param type the data type of the printer column
* @param column the name of the column
* @param description the description of the column
* @param format the format of the printer column
* @return the concrete decorator implementing the addition of a printer column to the currently built CRD
*/
protected abstract Decorator<?> getPrinterColumnDecorator(String name, String version, String path,
String type, String column, String description, String format, int priority);
/**
* Adds all the necessary decorators to build the specific CRD version. For optional paths, see
* https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.20/#customresourcesubresourcescale-v1-apiextensions-k8s-io
* These paths
*
* @param config the gathered {@link CustomResourceInfo} used as basis for the CRD generation
* @param def the {@link TypeDef} associated with the {@link io.fabric8.kubernetes.client.CustomResource} from which the CRD
* is generated
* @param specReplicasPath an optionally detected path of field defining spec replicas
* @param statusReplicasPath an optionally detected path of field defining status replicas
* @param labelSelectorPath an optionally detected path of field defining `status.selector`
*/
protected abstract void addDecorators(CustomResourceInfo config, TypeDef def,
Optional<String> specReplicasPath, Optional<String> statusReplicasPath,
Optional<String> labelSelectorPath);
}
|
final ExecutorService executorService = Executors.newFixedThreadPool(
Math.min(visitors.size(), Runtime.getRuntime().availableProcessors()));
try {
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (Visitor<TypeDefBuilder> visitor : visitors) {
futures.add(CompletableFuture.runAsync(() -> {
// in this case we're not building a new typedef,
// instead we just need to traverse the object graph.
TypeDefBuilder builder = new TypeDefBuilder(def);
builder.accept(visitor);
}, executorService));
}
try {
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();
} catch (InterruptedException interruptedException) {
Thread.currentThread().interrupt();
} catch (ExecutionException ex) {
if (ex.getCause() instanceof RuntimeException) {
throw (RuntimeException) ex.getCause();
}
throw new RuntimeException(ex.getCause());
}
} finally {
executorService.shutdown();
}
return def;
| 1,348
| 289
| 1,637
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/CRDGenerationInfo.java
|
CRDGenerationInfo
|
add
|
class CRDGenerationInfo {
static final CRDGenerationInfo EMPTY = new CRDGenerationInfo();
private final Map<String, Map<String, CRDInfo>> crdNameToVersionToCRDInfoMap = new HashMap<>();
public Map<String, CRDInfo> getCRDInfos(String crdName) {
return crdNameToVersionToCRDInfoMap.get(crdName);
}
public Map<String, Map<String, CRDInfo>> getCRDDetailsPerNameAndVersion() {
return crdNameToVersionToCRDInfoMap;
}
void add(String crdName, String version, URI fileURI) {<FILL_FUNCTION_BODY>}
public int numberOfGeneratedCRDs() {
return crdNameToVersionToCRDInfoMap.values().stream().map(Map::size).reduce(Integer::sum).orElse(0);
}
}
|
crdNameToVersionToCRDInfoMap.computeIfAbsent(crdName, k -> new HashMap<>())
.put(version, new CRDInfo(crdName, version, new File(fileURI).getAbsolutePath(),
ClassDependenciesVisitor.getDependentClassesFromCRDName(crdName)));
| 238
| 83
| 321
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/CustomResourceInfo.java
|
CustomResourceInfo
|
fromClass
|
class CustomResourceInfo {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomResourceInfo.class);
public static final boolean DESCRIBE_TYPE_DEFS = false;
private final String group;
private final String version;
private final String kind;
private final String singular;
private final String plural;
private final String[] shortNames;
private final boolean storage;
private final boolean served;
private final boolean deprecated;
private final String deprecationWarning;
private final Scope scope;
private final TypeDef definition;
private final String crClassName;
private final String specClassName;
private final String statusClassName;
private final String id;
private final int hash;
private final String[] annotations;
private final String[] labels;
public CustomResourceInfo(String group, String version, String kind, String singular,
String plural, String[] shortNames, boolean storage, boolean served, boolean deprecated, String deprecationWarning,
Scope scope, TypeDef definition, String crClassName,
String specClassName, String statusClassName, String[] annotations, String[] labels) {
this.group = group;
this.version = version;
this.kind = kind;
this.singular = singular;
this.plural = plural;
this.shortNames = shortNames;
this.storage = storage;
this.served = served;
this.deprecated = deprecated;
this.deprecationWarning = deprecationWarning;
this.scope = scope;
this.definition = definition;
this.crClassName = crClassName;
this.specClassName = specClassName;
this.statusClassName = statusClassName;
this.id = crdName() + "/" + version;
this.hash = id.hashCode();
this.annotations = annotations;
this.labels = labels;
}
public boolean storage() {
return storage;
}
public boolean served() {
return served;
}
public boolean deprecated() {
return deprecated;
}
public String deprecationWarning() {
return deprecationWarning;
}
public String key() {
return crdName();
}
public Scope scope() {
return scope;
}
public String crdName() {
return plural() + "." + group;
}
public String[] shortNames() {
return shortNames;
}
public String singular() {
return singular;
}
public String plural() {
return plural;
}
public String kind() {
return kind;
}
public String version() {
return version;
}
public String group() {
return group;
}
public String crClassName() {
return crClassName;
}
public Optional<String> specClassName() {
return Optional.ofNullable(specClassName);
}
public Optional<String> statusClassName() {
return Optional.ofNullable(statusClassName);
}
public TypeDef definition() {
return definition;
}
public String[] annotations() {
return annotations;
}
public String[] labels() {
return labels;
}
public static CustomResourceInfo fromClass(Class<? extends CustomResource<?, ?>> customResource) {<FILL_FUNCTION_BODY>}
public static String[] toStringArray(Map<String, String> map) {
String[] res = new String[map.size()];
Set<Map.Entry<String, String>> entrySet = map.entrySet();
int i = 0;
for (Map.Entry<String, String> e : entrySet) {
res[i] = e.getKey() + "=" + e.getValue();
i++;
}
return res;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CustomResourceInfo that = (CustomResourceInfo) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return hash;
}
}
|
try {
final CustomResource<?, ?> instance = customResource.getDeclaredConstructor().newInstance();
final String[] shortNames = CustomResource.getShortNames(customResource);
final TypeDef definition = Types.typeDefFrom(customResource);
if (DESCRIBE_TYPE_DEFS) {
Types.output(definition);
}
final Scope scope = Types.isNamespaced(definition) ? Scope.NAMESPACED : Scope.CLUSTER;
SpecAndStatus specAndStatus = Types.resolveSpecAndStatusTypes(definition);
if (specAndStatus.isUnreliable()) {
LOGGER.warn(
"Cannot reliably determine status types for {} because it isn't parameterized with only spec and status types. Status replicas detection will be deactivated.",
customResource.getCanonicalName());
}
return new CustomResourceInfo(instance.getGroup(), instance.getVersion(), instance.getKind(),
instance.getSingular(), instance.getPlural(), shortNames, instance.isStorage(), instance.isServed(),
instance.isDeprecated(), instance.getDeprecationWarning(),
scope, definition,
customResource.getCanonicalName(), specAndStatus.getSpecClassName(),
specAndStatus.getStatusClassName(), toStringArray(instance.getMetadata().getAnnotations()),
toStringArray(instance.getMetadata().getLabels()));
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw KubernetesClientException.launderThrowable(e);
}
| 1,099
| 396
| 1,495
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/InternalSchemaSwaps.java
|
SwapResult
|
lookupAndMark
|
class SwapResult {
final ClassRef classRef;
final boolean onGoing;
public SwapResult(ClassRef classRef, boolean onGoing) {
this.classRef = classRef;
this.onGoing = onGoing;
}
}
public SwapResult lookupAndMark(ClassRef originalType, String name) {<FILL_FUNCTION_BODY>
|
Key key = new Key(originalType, name);
Value value = swaps.getOrDefault(key, parentSwaps.get(key));
if (value != null) {
int currentDepth = swapDepths.getOrDefault(key, 0);
swapDepths.put(key, currentDepth + 1);
value.markUsed();
if (currentDepth == value.depth) {
return new SwapResult(value.getTargetType(), false);
}
if (currentDepth > value.depth) {
throw new IllegalStateException("Somthing has gone wrong with tracking swap depths, please raise an issue.");
}
return new SwapResult(null, true);
}
return new SwapResult(null, false);
| 100
| 186
| 286
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/Resources.java
|
Resources
|
applyConstraints
|
class Resources {
private static final Logger LOGGER = LoggerFactory.getLogger(Resources.class);
private static final int SORT_ROUND_LIMIT = 10;
private final KubernetesListBuilder global = new KubernetesListBuilder();
private final Set<Decorator<?>> globalDecorators = new TreeSet<>();
/**
* Get the global builder
*
* @return The groups map.
*/
public KubernetesListBuilder global() {
return this.global;
}
/**
* Get the Decorator Set.
* The method is visible for testing purposes.
*
* @return the Set of registed Decorators.
*/
protected Set<Decorator<?>> getDecorators() {
return globalDecorators;
}
/**
* Add a {@link Decorator}.
*
* @param decorator The decorator.
*/
public void decorate(Decorator<?> decorator) {
globalDecorators.add(decorator);
}
/**
* Add a resource to all groups.
*
* @param metadata the resource to add to this Resources
*/
public void add(HasMetadata metadata) {
global.addToItems(metadata);
}
/**
* Generate all resources.
*
* @return A map of {@link KubernetesList} by group name.
*/
public KubernetesList generate() {
for (Decorator<?> decorator : applyConstraints(globalDecorators)) {
this.global.accept(decorator);
}
return this.global.build();
}
public List<Decorator<?>> applyConstraints(Set<Decorator<?>> decorators) {<FILL_FUNCTION_BODY>}
/**
* Bubble sort for decorators.
*
* @param decorators the {@link Decorator} array to be sorted
*/
private boolean bubbleSort(Decorator<?>[] decorators) {
boolean swapped = false;
int n = decorators.length;
Decorator<?> temp;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (decorators[j].compareTo(decorators[j - 1]) < 0) {
swapped = true;
temp = decorators[j - 1];
decorators[j - 1] = decorators[j];
decorators[j] = temp;
}
}
}
return swapped;
}
}
|
Decorator<?>[] array = decorators.toArray(new Decorator<?>[0]);
// We can't guarantee that `when `decorator a < b and b < c then a < c``.
// Why?
// Because our comparators express constraints on particular pairs and can't express the global order.
// So, in order to be accurate we need to compare each decorator, with ALL OTHER decorators.
// In other words we need bubble sort.
// We also might need it more than once. So, we'll do it as many times as we have to, till there are not more transformations.
// But hey, let's have an upper limit just to prevent infinite loops.
for (int i = 0; i < SORT_ROUND_LIMIT && bubbleSort(array); i++) {
LOGGER.debug("Sorting again: {}", i + 1);
}
List<Decorator<?>> result = Collections.unmodifiableList(Arrays.asList(array));
if (LOGGER.isTraceEnabled()) {
result.forEach(decorator -> LOGGER.trace("{}", decorator));
}
return result;
| 666
| 291
| 957
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/decorator/Decorator.java
|
Decorator
|
compareTo
|
class Decorator<T> extends TypedVisitor<T> implements Comparable<Decorator> {
public Class<? extends Decorator>[] after() {
return new Class[0];
}
public Class<? extends Decorator>[] before() {
return new Class[0];
}
@Override
public int compareTo(Decorator o) {<FILL_FUNCTION_BODY>}
}
|
//We only want to return 0 if decorators are equal.
if (this.equals(o)) {
return 0;
}
Class c = o.getClass();
//1st pass: ours
for (Class b : before()) {
if (b.isAssignableFrom(c)) {
return -1;
}
}
for (Class a : after()) {
if (a.isAssignableFrom(c)) {
return 1;
}
}
//2nd pass: their
for (Class b : o.before()) {
if (b.isAssignableFrom(getClass())) {
return 1;
}
}
for (Class a : o.after()) {
if (a.isAssignableFrom(getClass())) {
return -1;
}
}
//Reproducible order every single time
int result = getClass().getName().compareTo(o.getClass().getName());
if (result == 0) {
result = hashCode() - o.hashCode();
}
return result;
| 109
| 280
| 389
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/decorator/NamedResourceDecorator.java
|
NamedResourceDecorator
|
visit
|
class NamedResourceDecorator<T> extends Decorator<VisitableBuilder> {
/**
* For resource name null acts as a wildcards.
* Let's use a constant instead, for clarity's shake
*/
public static final String ANY = null;
protected final String kind;
protected final String name;
private final ResourceVisitor visitor = new ResourceVisitor(null, null);
public NamedResourceDecorator() {
this(ANY, ANY);
}
public NamedResourceDecorator(String name) {
this(ANY, name);
}
public NamedResourceDecorator(String kind, String name) {
this.kind = kind;
this.name = name;
}
public String getKind() {
return kind;
}
public String getName() {
return name;
}
@Override
public void visit(VisitableBuilder builder) {<FILL_FUNCTION_BODY>}
/**
* Visit a part of a Resource.
*
* @param item the visited item
* @param resourceMeta the {@link ObjectMeta} of the current resource.
*/
public abstract void andThenVisit(T item, ObjectMeta resourceMeta);
/**
* Visit a part of a Resource.
*
* @param item the visited item
* @param kind the resource kind
* @param resourceMeta the {@link ObjectMeta} of the current resource.
*/
public void andThenVisit(T item, String kind, ObjectMeta resourceMeta) {
andThenVisit(item, resourceMeta);
}
private class ResourceVisitor extends TypedVisitor<T> {
private final String kind;
private final ObjectMeta metadata;
public ResourceVisitor(String kind, ObjectMeta metadata) {
this.kind = kind;
this.metadata = metadata;
}
@Override
public void visit(T item) {
andThenVisit(item, kind, metadata);
}
public ResourceVisitor withKind(String kind) {
return new ResourceVisitor(kind, this.metadata);
}
public ResourceVisitor withMetadata(ObjectMeta metadata) {
return new ResourceVisitor(this.kind, metadata);
}
public Class<T> getType() {
return (Class) Generics
.getTypeArguments(NamedResourceDecorator.class, NamedResourceDecorator.this.getClass())
.get(0);
}
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { ResourceProvidingDecorator.class };
}
}
|
Optional<String> resourceKind = Metadata.getKind(builder);
Optional<ObjectMeta> objectMeta = Metadata.getMetadata(builder);
if (!resourceKind.isPresent() || !objectMeta.isPresent()) {
return;
}
if (Utils.isNullOrEmpty(kind)) {
if (Utils.isNullOrEmpty(name)) {
builder.accept(visitor.withKind(resourceKind.get()).withMetadata(objectMeta.get()));
} else if (objectMeta.map(ObjectMeta::getName).filter(s -> s.equals(name)).isPresent()) {
builder.accept(visitor.withKind(resourceKind.get()).withMetadata(objectMeta.get()));
}
} else if (resourceKind.filter(k -> k.equals(kind)).isPresent()) {
if (Utils.isNullOrEmpty(name)) {
builder.accept(visitor.withKind(resourceKind.get()).withMetadata(objectMeta.get()));
} else if (objectMeta.map(ObjectMeta::getName).filter(s -> s.equals(name)).isPresent()) {
builder.accept(visitor.withKind(resourceKind.get()).withMetadata(objectMeta.get()));
}
}
| 667
| 301
| 968
|
<methods>public non-sealed void <init>() ,public Class<? extends Decorator#RAW>[] after() ,public Class<? extends Decorator#RAW>[] before() ,public int compareTo(Decorator#RAW) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/decorator/ResourceProvidingDecorator.java
|
ResourceProvidingDecorator
|
toMap
|
class ResourceProvidingDecorator<T> extends Decorator<T> {
protected Map<String, String> toMap(String[] arr) {<FILL_FUNCTION_BODY>}
}
|
Map<String, String> res = new HashMap<>();
if (arr != null) {
for (String e : arr) {
String[] splitted = e.split("\\=");
if (splitted.length >= 2) {
res.put(splitted[0], e.substring(splitted[0].length() + 1));
} else {
throw new IllegalArgumentException(
"Invalid value: " + e + " cannot be parsed as a key-value pair. Expected format is 'key=value'.");
}
}
}
return res;
| 51
| 147
| 198
|
<methods>public non-sealed void <init>() ,public Class<? extends Decorator#RAW>[] after() ,public Class<? extends Decorator#RAW>[] before() ,public int compareTo(Decorator#RAW) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/utils/Generics.java
|
Generics
|
getClass
|
class Generics {
/**
* Get the underlying class for a type, or null if the type is a variable type.
*
* @param type the type
* @return the underlying class
*/
private Generics() {
throw new IllegalStateException("Utility class");
}
public static Class<?> getClass(Type type) {<FILL_FUNCTION_BODY>}
/**
* Get the actual type arguments a child class has used to extend a generic base class.
*
* @param baseClass the base class
* @param childClass the child class
* @param <T> the type of the base class
* @return a list of the raw classes for the actual type arguments
*/
public static <T> List<Class> getTypeArguments(Class<T> baseClass,
Class<? extends T> childClass) {
Map<Type, Type> resolvedTypes = new LinkedHashMap<>();
Type type = childClass;
// start walking up the inheritance hierarchy until we hit baseClass
while (true) {
final Class<?> clazz = getClass(type);
if (clazz == null || clazz.equals(baseClass))
break;
if (type instanceof Class) {
// there is no useful information for us in raw types, so just keep going.
type = ((Class) type).getGenericSuperclass();
} else {
ParameterizedType parameterizedType = (ParameterizedType) type;
Class<?> rawType = (Class) parameterizedType.getRawType();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
for (int i = 0; i < actualTypeArguments.length; i++) {
resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
}
if (!rawType.equals(baseClass)) {
type = rawType.getGenericSuperclass();
}
}
}
// finally, for each actual type argument provided to baseClass, determine (if possible)
// the raw class for that type argument.
Type[] actualTypeArguments;
if (type instanceof Class) {
actualTypeArguments = ((Class) type).getTypeParameters();
} else {
actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
}
List<Class> typeArgumentsAsClasses = new ArrayList<>();
// resolve types by chasing down type variables.
for (Type baseType : actualTypeArguments) {
while (resolvedTypes.containsKey(baseType)) {
baseType = resolvedTypes.get(baseType);
}
typeArgumentsAsClasses.add(getClass(baseType));
}
return typeArgumentsAsClasses;
}
}
|
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
return Array.newInstance(componentClass, 0).getClass();
} else {
return null;
}
} else {
return null;
}
| 688
| 152
| 840
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/utils/Metadata.java
|
Metadata
|
addToLabels
|
class Metadata {
private Metadata() {
throw new IllegalStateException("Utility class");
}
public static Optional<String> getKind(Builder builder) {
try {
Method method = builder.getClass().getMethod("getKind");
Object o = method.invoke(builder);
if (o instanceof String) {
return Optional.of((String) o);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
//ignore
}
return Optional.empty();
}
public static Optional<ObjectMeta> getMetadata(Builder builder) {
try {
Method method = builder.getClass().getMethod("buildMetadata");
Object o = method.invoke(builder);
if (o instanceof ObjectMeta) {
return Optional.of((ObjectMeta) o);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
//ignore
}
return Optional.empty();
}
public static boolean addToLabels(Builder builder, String key, String value) {<FILL_FUNCTION_BODY>}
public static boolean removeFromLabels(Builder builder, String key) {
try {
Method editMethod = builder.getClass().getMethod("editOrNewMetadata");
Object o = editMethod.invoke(builder);
if (o instanceof ObjectMetaFluent) {
ObjectMetaFluent fluent = (ObjectMetaFluent) o;
fluent.removeFromLabels(key);
Method endMethod = fluent.getClass().getMethod("endMetadata");
endMethod.invoke(fluent);
return true;
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
//ignore
}
return false;
}
/**
* Create a {@link Predicate} that checks that a resource builder doesn't match the name and kind.
*
* @param candidate The specified resource.
* @return The predicate.
*/
public static Predicate<VisitableBuilder<? extends HasMetadata, ?>> matching(
HasMetadata candidate) {
return matching(candidate.getApiVersion(), candidate.getKind(),
candidate.getMetadata().getName());
}
/**
* Create a {@link Predicate} that checks that a resource builder doesn't match the name and kind.
*
* @param apiVersion the API version the resources must match
* @param kind The specified kind.
* @param name The specified name.
* @return The predicate.
*/
public static Predicate<VisitableBuilder<? extends HasMetadata, ?>> matching(String apiVersion,
String kind, String name) {
return builder -> {
HasMetadata item = builder.build();
ObjectMeta metadata = item.getMetadata();
return apiVersion.equals(item.getApiVersion()) &&
kind != null && kind.equals(item.getKind()) &&
name != null && name.equals(metadata.getName());
};
}
}
|
try {
Method editMethod = builder.getClass().getMethod("editOrNewMetadata");
Object o = editMethod.invoke(builder);
if (o instanceof ObjectMetaFluent) {
ObjectMetaFluent fluent = (ObjectMetaFluent) o;
fluent.addToLabels(key, value);
Method endMethod = fluent.getClass().getMethod("endMetadata");
endMethod.invoke(fluent);
return true;
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
//ignore
}
return false;
| 751
| 153
| 904
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/CustomResourceHandler.java
|
CustomResourceHandler
|
addDecorators
|
class CustomResourceHandler extends AbstractCustomResourceHandler {
public static final String VERSION = "v1";
public CustomResourceHandler(Resources resources, boolean parallel) {
super(resources, parallel);
}
@Override
protected Decorator<?> getPrinterColumnDecorator(String name,
String version, String path,
String type, String column, String description, String format, int priority) {
return new AddAdditionPrinterColumnDecorator(name, version, type, column, path, format,
description, priority);
}
@Override
protected void addDecorators(CustomResourceInfo config, TypeDef def, Optional<String> specReplicasPath,
Optional<String> statusReplicasPath, Optional<String> labelSelectorPath) {<FILL_FUNCTION_BODY>}
@Override
public void handle(CustomResourceInfo config) {
super.handle(config);
}
}
|
final String name = config.crdName();
final String version = config.version();
resources.decorate(
new AddCustomResourceDefinitionResourceDecorator(name, config.group(), config.kind(),
config.scope().value(), config.shortNames(), config.plural(), config.singular(), config.annotations(),
config.labels()));
resources.decorate(new AddCustomResourceDefinitionVersionDecorator(name, version));
resources.decorate(new AddSchemaToCustomResourceDefinitionVersionDecorator(name, version,
JsonSchema.from(def, "kind", "apiVersion", "metadata")));
specReplicasPath.ifPresent(path -> {
resources.decorate(new AddSubresourcesDecorator(name, version));
resources.decorate(new AddSpecReplicasPathDecorator(name, version, path));
});
statusReplicasPath.ifPresent(path -> {
resources.decorate(new AddSubresourcesDecorator(name, version));
resources.decorate(new AddStatusReplicasPathDecorator(name, version, path));
});
labelSelectorPath.ifPresent(path -> {
resources.decorate(new AddSubresourcesDecorator(name, version));
resources.decorate(new AddLabelSelectorPathDecorator(name, version, path));
});
if (config.statusClassName().isPresent()) {
resources.decorate(new AddSubresourcesDecorator(name, version));
resources.decorate(new AddStatusSubresourceDecorator(name, version));
}
resources.decorate(new SetServedVersionDecorator(name, version, config.served()));
resources.decorate(new SetStorageVersionDecorator(name, version, config.storage()));
resources.decorate(new SetDeprecatedVersionDecorator(name, version, config.deprecated(), config.deprecationWarning()));
resources.decorate(new EnsureSingleStorageVersionDecorator(name));
resources.decorate(new SortCustomResourceDefinitionVersionDecorator(name));
resources.decorate(new SortPrinterColumnsDecorator(name, version));
| 233
| 531
| 764
|
<methods>public void handle(io.fabric8.crd.generator.CustomResourceInfo) <variables>private final non-sealed boolean parallel,protected final non-sealed io.fabric8.crd.generator.Resources resources
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/JsonSchema.java
|
JsonSchema
|
mapValidationRule
|
class JsonSchema extends AbstractJsonSchema<JSONSchemaProps, JSONSchemaPropsBuilder> {
private static final JsonSchema instance = new JsonSchema();
private static final JSONSchemaProps JSON_SCHEMA_INT_OR_STRING = new JSONSchemaPropsBuilder()
.withXKubernetesIntOrString(true)
.withAnyOf(
new JSONSchemaPropsBuilder().withType("integer").build(),
new JSONSchemaPropsBuilder().withType("string").build())
.build();
/**
* Creates the JSON schema for the particular {@link TypeDef}.
*
* @param definition The definition.
* @param ignore an optional list of property names to ignore
* @return The schema.
*/
public static JSONSchemaProps from(TypeDef definition, String... ignore) {
return instance.internalFrom(definition, ignore);
}
@Override
public JSONSchemaPropsBuilder newBuilder() {
return newBuilder("object");
}
@Override
public JSONSchemaPropsBuilder newBuilder(String type) {
final JSONSchemaPropsBuilder builder = new JSONSchemaPropsBuilder();
builder.withType(type);
return builder;
}
@Override
public void addProperty(Property property, JSONSchemaPropsBuilder builder,
JSONSchemaProps schema, SchemaPropsOptions options) {
if (schema != null) {
options.getDefault().ifPresent(s -> {
try {
schema.setDefault(YAML_MAPPER.readTree(s));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Cannot parse default value: '" + s + "' as valid YAML.");
}
});
options.getMin().ifPresent(schema::setMinimum);
options.getMax().ifPresent(schema::setMaximum);
options.getPattern().ifPresent(schema::setPattern);
List<ValidationRule> validationRulesFromProperty = options.getValidationRules().stream()
.map(this::mapValidationRule)
.collect(Collectors.toList());
List<ValidationRule> resultingValidationRules = new ArrayList<>(schema.getXKubernetesValidations());
resultingValidationRules.addAll(validationRulesFromProperty);
if (!resultingValidationRules.isEmpty()) {
schema.setXKubernetesValidations(resultingValidationRules);
}
if (options.isNullable()) {
schema.setNullable(true);
}
if (options.isPreserveUnknownFields()) {
schema.setXKubernetesPreserveUnknownFields(true);
}
builder.addToProperties(property.getName(), schema);
}
}
@Override
public JSONSchemaProps build(JSONSchemaPropsBuilder builder, List<String> required,
List<KubernetesValidationRule> validationRules, boolean preserveUnknownFields) {
builder = builder.withRequired(required);
if (preserveUnknownFields) {
builder.withXKubernetesPreserveUnknownFields(preserveUnknownFields);
}
builder.addAllToXKubernetesValidations(mapValidationRules(validationRules));
return builder.build();
}
@Override
protected JSONSchemaProps arrayLikeProperty(JSONSchemaProps schema) {
return new JSONSchemaPropsBuilder()
.withType("array")
.withNewItems()
.withSchema(schema)
.and()
.build();
}
@Override
protected JSONSchemaProps mapLikeProperty(JSONSchemaProps schema) {
return new JSONSchemaPropsBuilder()
.withType("object")
.withNewAdditionalProperties()
.withSchema(schema)
.endAdditionalProperties()
.build();
}
@Override
protected JSONSchemaProps singleProperty(String typeName) {
return new JSONSchemaPropsBuilder().withType(typeName).build();
}
@Override
protected JSONSchemaProps mappedProperty(TypeRef ref) {
return JSON_SCHEMA_INT_OR_STRING;
}
@Override
protected JSONSchemaProps enumProperty(JsonNode... enumValues) {
return new JSONSchemaPropsBuilder().withType("string").withEnum(enumValues).build();
}
@Override
protected JSONSchemaProps addDescription(JSONSchemaProps schema, String description) {
return new JSONSchemaPropsBuilder(schema)
.withDescription(description)
.build();
}
private List<ValidationRule> mapValidationRules(List<KubernetesValidationRule> validationRules) {
return validationRules.stream()
.map(this::mapValidationRule)
.collect(Collectors.toList());
}
private ValidationRule mapValidationRule(KubernetesValidationRule validationRule) {<FILL_FUNCTION_BODY>}
}
|
return new ValidationRuleBuilder()
.withRule(validationRule.getRule())
.withMessage(validationRule.getMessage())
.withMessageExpression(validationRule.getMessageExpression())
.withReason(validationRule.getReason())
.withFieldPath(validationRule.getFieldPath())
.withOptionalOldSelf(validationRule.getOptionalOldSelf())
.build();
| 1,177
| 95
| 1,272
|
<methods>public non-sealed void <init>() ,public abstract void addProperty(Property, JSONSchemaPropsBuilder, JSONSchemaProps, io.fabric8.crd.generator.AbstractJsonSchema.SchemaPropsOptions) ,public abstract JSONSchemaProps build(JSONSchemaPropsBuilder, List<java.lang.String>, List<io.fabric8.crd.generator.AbstractJsonSchema.KubernetesValidationRule>, boolean) ,public static java.lang.String getSchemaTypeFor(TypeRef) ,public JSONSchemaProps internalFrom(java.lang.String, TypeRef) ,public abstract JSONSchemaPropsBuilder newBuilder() ,public abstract JSONSchemaPropsBuilder newBuilder(java.lang.String) <variables>public static final java.lang.String ANNOTATION_DEFAULT,public static final java.lang.String ANNOTATION_JSON_ANY_GETTER,public static final java.lang.String ANNOTATION_JSON_ANY_SETTER,public static final java.lang.String ANNOTATION_JSON_IGNORE,public static final java.lang.String ANNOTATION_JSON_PROPERTY,public static final java.lang.String ANNOTATION_JSON_PROPERTY_DESCRIPTION,public static final java.lang.String ANNOTATION_MAX,public static final java.lang.String ANNOTATION_MIN,public static final java.lang.String ANNOTATION_NULLABLE,public static final java.lang.String ANNOTATION_PATTERN,public static final java.lang.String ANNOTATION_PERSERVE_UNKNOWN_FIELDS,public static final java.lang.String ANNOTATION_REQUIRED,public static final java.lang.String ANNOTATION_SCHEMA_FROM,public static final java.lang.String ANNOTATION_SCHEMA_SWAP,public static final java.lang.String ANNOTATION_SCHEMA_SWAPS,public static final java.lang.String ANNOTATION_VALIDATION_RULE,public static final java.lang.String ANNOTATION_VALIDATION_RULES,public static final java.lang.String ANY_TYPE,private static final java.lang.String BOOLEAN_MARKER,private static final Map<TypeRef,java.lang.String> COMMON_MAPPINGS,protected static final TypeDef DATE,protected static final TypeRef DATE_REF,protected static final TypeDef DURATION,protected static final TypeRef DURATION_REF,private static final java.lang.String INTEGER_MARKER,protected static final TypeDef INT_OR_STRING,private static final java.lang.String INT_OR_STRING_MARKER,protected static final TypeRef INT_OR_STRING_REF,public static final java.lang.String JSON_NODE_TYPE,private static final Logger LOGGER,private static final java.lang.String NUMBER_MARKER,protected static final TypeDef OBJECT,protected static final TypeRef OBJECT_REF,protected static final TypeRef P_BOOLEAN_REF,protected static final TypeRef P_DOUBLE_REF,protected static final TypeRef P_FLOAT_REF,protected static final TypeRef P_INT_REF,protected static final TypeRef P_LONG_REF,protected static final TypeDef QUANTITY,protected static final TypeRef QUANTITY_REF,private static final java.lang.String STRING_MARKER,private static final java.lang.String VALUE
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/AddAdditionPrinterColumnDecorator.java
|
AddAdditionPrinterColumnDecorator
|
equals
|
class AddAdditionPrinterColumnDecorator extends
CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
private final String type;
private final String columnName;
private final String path;
private final String format;
private final String description;
private final int priority;
public AddAdditionPrinterColumnDecorator(String name, String version, String type, String columnName, String path,
String format, String description, int priority) {
super(name, version);
this.type = type;
this.columnName = columnName;
this.path = path;
this.format = format;
this.description = description;
this.priority = priority;
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> spec) {
Predicate<CustomResourceColumnDefinitionBuilder> matchingColumn = col -> col.getName() != null
&& col.getName().equals(columnName) && col.getJsonPath() != null && col.getJsonPath().equals(path);
spec.removeMatchingFromAdditionalPrinterColumns(matchingColumn);
spec.addNewAdditionalPrinterColumn()
.withType(type)
.withName(columnName)
.withJsonPath(path)
.withFormat(Utils.isNotNullOrEmpty(format) ? format : null)
.withDescription(Utils.isNotNullOrEmpty(description) ? description : null)
.withPriority(priority)
.endAdditionalPrinterColumn();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getVersion() == null) ? 0 : getVersion().hashCode());
result = prime * result + ((columnName == null) ? 0 : columnName.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((path == null) ? 0 : path.hashCode());
result = prime * result + ((format == null) ? 0 : format.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + priority;
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + "column:" + columnName + "priority:"
+ priority + "]";
}
}
|
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AddAdditionPrinterColumnDecorator other = (AddAdditionPrinterColumnDecorator) obj;
if (getName() == null) {
if (other.getName() != null)
return false;
} else if (!getName().equals(other.getName()))
return false;
if (getVersion() == null) {
if (other.getVersion() != null)
return false;
} else if (!getVersion().equals(other.getVersion()))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (format == null) {
if (other.format != null)
return false;
} else if (!format.equals(other.format))
return false;
if (columnName == null) {
if (other.columnName != null)
return false;
} else if (!columnName.equals(other.columnName))
return false;
if (path == null) {
if (other.path != null)
return false;
} else if (!path.equals(other.path))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return priority == other.priority;
| 681
| 406
| 1,087
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/AddCustomResourceDefinitionResourceDecorator.java
|
AddCustomResourceDefinitionResourceDecorator
|
toString
|
class AddCustomResourceDefinitionResourceDecorator extends ResourceProvidingDecorator<KubernetesListBuilder> {
private String name;
private String apiGroup;
private String kind;
private String scope;
private String[] shortNames;
private String plural;
private String singular;
private String[] annotations;
private String[] labels;
public AddCustomResourceDefinitionResourceDecorator(String name, String apiGroup, String kind,
String scope, String[] shortNames, String plural, String singular, String[] annotations, String[] labels) {
this.name = name;
this.apiGroup = apiGroup;
this.kind = kind;
this.scope = scope;
this.shortNames = shortNames;
this.plural = plural;
this.singular = singular;
this.annotations = annotations;
this.labels = labels;
}
@Override
public void visit(KubernetesListBuilder list) {
boolean exists = list.buildItems().stream().anyMatch(i -> i.getKind().equals("CustomResourceDefinition")
&& i.getMetadata().getName().equals(name)
&& ApiVersionUtil.trimVersion(i.getApiVersion()).equals("v1"));
if (!exists) {
list.addToItems(new CustomResourceDefinitionBuilder()
.withNewMetadata()
.withName(name)
.withAnnotations(toMap(annotations))
.withLabels(toMap(labels))
.endMetadata()
.withNewSpec()
.withScope(scope)
.withGroup(apiGroup)
.withNewNames()
.withKind(kind)
.withShortNames(shortNames)
.withPlural(plural)
.withSingular(singular)
.endNames()
.endSpec()
.build());
}
}
@Override
public Class<? extends Decorator>[] before() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class, CustomResourceDefinitionDecorator.class };
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [apiGroup=" + apiGroup + ", kind=" + kind + ", name=" + name + ", plural=" + plural
+ ", scope=" + scope + "]";
| 539
| 55
| 594
|
<methods>public non-sealed void <init>() <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/AddCustomResourceDefinitionVersionDecorator.java
|
AddCustomResourceDefinitionVersionDecorator
|
andThenVisit
|
class AddCustomResourceDefinitionVersionDecorator extends
CustomResourceDefinitionDecorator<CustomResourceDefinitionSpecFluent<?>> {
private final String version;
public AddCustomResourceDefinitionVersionDecorator(String name, String version) {
super(name);
this.version = version;
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
@Override
public void andThenVisit(CustomResourceDefinitionSpecFluent<?> spec, ObjectMeta resourceMeta) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionResourceDecorator.class };
}
@Override
public String toString() {
return getClass().getName() + " [name:" + getName() + ", version:" + version + "]";
}
}
|
Predicate<CustomResourceDefinitionVersionBuilder> predicate = candidate -> candidate.getName()
.equals(version);
spec.removeMatchingFromVersions(predicate);
spec.addNewVersion()
.withName(version)
.endVersion();
| 242
| 67
| 309
|
<methods>public void <init>(java.lang.String) ,public void andThenVisit(CustomResourceDefinitionSpecFluent<?>, ObjectMeta) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/AddLabelSelectorPathDecorator.java
|
AddLabelSelectorPathDecorator
|
andThenVisit
|
class AddLabelSelectorPathDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceSubresourcesFluent<?>> {
private final String path;
public AddLabelSelectorPathDecorator(String name, String version, String path) {
super(name, version);
this.path = path;
}
@Override
public void andThenVisit(CustomResourceSubresourcesFluent<?> subresources) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class,
AddSubresourcesDecorator.class };
}
}
|
if (subresources.hasScale()) {
subresources.editScale().withLabelSelectorPath(path).endScale();
} else {
subresources.withNewScale().withLabelSelectorPath(path).endScale();
}
| 172
| 59
| 231
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceSubresourcesFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/AddSchemaToCustomResourceDefinitionVersionDecorator.java
|
AddSchemaToCustomResourceDefinitionVersionDecorator
|
toString
|
class AddSchemaToCustomResourceDefinitionVersionDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
private JSONSchemaProps schema;
public AddSchemaToCustomResourceDefinitionVersionDecorator(String name, String version, JSONSchemaProps schema) {
super(name, version);
this.schema = schema;
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> version) {
version.withNewSchema().withOpenAPIV3Schema(schema).endSchema();
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class };
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + "]";
| 205
| 32
| 237
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/AddSpecReplicasPathDecorator.java
|
AddSpecReplicasPathDecorator
|
andThenVisit
|
class AddSpecReplicasPathDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceSubresourcesFluent<?>> {
private final String path;
public AddSpecReplicasPathDecorator(String name, String version, String path) {
super(name, version);
this.path = path;
}
@Override
public void andThenVisit(CustomResourceSubresourcesFluent<?> subresources) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class,
AddSubresourcesDecorator.class };
}
}
|
if (subresources.hasScale()) {
subresources.editScale().withSpecReplicasPath(path).endScale();
} else {
subresources.withNewScale().withSpecReplicasPath(path).endScale();
}
| 176
| 63
| 239
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceSubresourcesFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/AddStatusReplicasPathDecorator.java
|
AddStatusReplicasPathDecorator
|
andThenVisit
|
class AddStatusReplicasPathDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceSubresourcesFluent<?>> {
private final String path;
public AddStatusReplicasPathDecorator(String name, String version, String path) {
super(name, version);
this.path = path;
}
@Override
public void andThenVisit(CustomResourceSubresourcesFluent<?> subresources) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddSubresourcesDecorator.class };
}
}
|
if (subresources.hasScale()) {
subresources.editScale().withStatusReplicasPath(path).endScale();
} else {
subresources.withNewScale().withStatusReplicasPath(path).endScale();
}
| 163
| 63
| 226
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceSubresourcesFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/AddStatusSubresourceDecorator.java
|
AddStatusSubresourceDecorator
|
toString
|
class AddStatusSubresourceDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceSubresourcesFluent<?>> {
public AddStatusSubresourceDecorator(String name, String version) {
super(name, version);
}
@Override
public void andThenVisit(CustomResourceSubresourcesFluent<?> subresources) {
subresources.withNewStatus().endStatus();
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class,
AddSubresourcesDecorator.class };
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + "]";
| 181
| 32
| 213
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceSubresourcesFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/AddSubresourcesDecorator.java
|
AddSubresourcesDecorator
|
toString
|
class AddSubresourcesDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
public AddSubresourcesDecorator(String name, String version) {
super(name, version);
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> spec) {
if (!spec.hasSubresources()) {
spec.withNewSubresources().endSubresources();
}
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class };
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + "]";
| 182
| 32
| 214
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/CustomResourceDefinitionVersionDecorator.java
|
CustomResourceDefinitionVersionDecorator
|
visit
|
class CustomResourceDefinitionVersionDecorator<T> extends Decorator<VisitableBuilder> {
protected static final String ANY = null;
private final String name;
private final String version;
private final CustomResourceDefinitionVersionVisitor versionSelector = new CustomResourceDefinitionVersionVisitor();
private final VersionVisitor versionVisitor = new VersionVisitor();
public CustomResourceDefinitionVersionDecorator(String name, String version) {
this.name = name;
this.version = version;
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
@Override
public void visit(VisitableBuilder builder) {<FILL_FUNCTION_BODY>}
public abstract void andThenVisit(T version);
private class CustomResourceDefinitionVersionVisitor extends TypedVisitor<CustomResourceDefinitionVersionBuilder> {
@Override
public void visit(CustomResourceDefinitionVersionBuilder builder) {
if (Utils.isNullOrEmpty(version) || builder.getName().equals(version)) {
builder.accept(versionVisitor);
}
}
}
private class VersionVisitor extends TypedVisitor<T> {
@Override
public void visit(T version) {
andThenVisit(version);
}
public Class<T> getType() {
return (Class) Generics
.getTypeArguments(CustomResourceDefinitionVersionDecorator.class,
CustomResourceDefinitionVersionDecorator.this.getClass())
.get(0);
}
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] {
AddCustomResourceDefinitionResourceDecorator.class,
AddCustomResourceDefinitionVersionDecorator.class };
}
@Override
public Class<? extends Decorator>[] before() {
return new Class[] {};
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomResourceDefinitionVersionDecorator other = (CustomResourceDefinitionVersionDecorator) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
}
|
Optional<ObjectMeta> objectMeta = getMetadata(builder);
if (!objectMeta.isPresent()) {
return;
}
if (Utils.isNullOrEmpty(name) || objectMeta.map(ObjectMeta::getName).filter(s -> s.equals(name)).isPresent()) {
builder.accept(versionSelector);
}
| 741
| 87
| 828
|
<methods>public non-sealed void <init>() ,public Class<? extends Decorator#RAW>[] after() ,public Class<? extends Decorator#RAW>[] before() ,public int compareTo(Decorator#RAW) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/EnsureSingleStorageVersionDecorator.java
|
EnsureSingleStorageVersionDecorator
|
andThenVisit
|
class EnsureSingleStorageVersionDecorator
extends CustomResourceDefinitionDecorator<CustomResourceDefinitionSpecFluent<?>> {
public EnsureSingleStorageVersionDecorator(String name) {
super(name);
}
@Override
public void andThenVisit(CustomResourceDefinitionSpecFluent<?> spec, ObjectMeta resourceMeta) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] {
CustomResourceDefinitionVersionDecorator.class
};
}
@Override
public String toString() {
return getClass().getName() + " [name:" + getName() + "]";
}
}
|
List<CustomResourceDefinitionVersion> versions = spec.buildVersions();
List<String> storageVersions = versions.stream()
.filter(v -> Optional.ofNullable(v.getStorage()).orElse(true))
.map(CustomResourceDefinitionVersion::getName)
.collect(Collectors.toList());
if (storageVersions.size() > 1) {
throw new IllegalStateException(String.format(
"'%s' custom resource has versions %s marked as storage. Only one version can be marked as storage per custom resource.",
resourceMeta.getName(), storageVersions));
}
| 182
| 151
| 333
|
<methods>public void <init>(java.lang.String) ,public void andThenVisit(CustomResourceDefinitionSpecFluent<?>, ObjectMeta) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/SetDeprecatedVersionDecorator.java
|
SetDeprecatedVersionDecorator
|
toString
|
class SetDeprecatedVersionDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
private final boolean deprecated;
private final String deprecationWarning;
public SetDeprecatedVersionDecorator(String name, String version, boolean deprecated, String deprecationWarning) {
super(name, version);
this.deprecated = deprecated;
this.deprecationWarning = deprecationWarning;
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> version) {
if (deprecated) {
version.withDeprecated(true);
version.withDeprecationWarning(deprecationWarning);
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion()
+ ", deprecated:" + deprecated + ", deprecationWarning:" + deprecationWarning + "]";
| 204
| 54
| 258
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/SetServedVersionDecorator.java
|
SetServedVersionDecorator
|
toString
|
class SetServedVersionDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
private final boolean served;
public SetServedVersionDecorator(String name, String version, boolean served) {
super(name, version);
this.served = served;
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> version) {
version.withServed(served);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + ", served:" + served + "]";
| 148
| 38
| 186
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/SetStorageVersionDecorator.java
|
SetStorageVersionDecorator
|
toString
|
class SetStorageVersionDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
private final boolean storage;
public SetStorageVersionDecorator(String name, String version, boolean storage) {
super(name, version);
this.storage = storage;
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> version) {
version.withStorage(storage);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + ", storage:" + storage + "]";
| 143
| 38
| 181
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/SortCustomResourceDefinitionVersionDecorator.java
|
SortCustomResourceDefinitionVersionDecorator
|
toString
|
class SortCustomResourceDefinitionVersionDecorator
extends CustomResourceDefinitionDecorator<CustomResourceDefinitionSpecFluent<?>> {
public SortCustomResourceDefinitionVersionDecorator(String name) {
super(name);
}
@Override
public void andThenVisit(CustomResourceDefinitionSpecFluent<?> spec, ObjectMeta resourceMeta) {
spec.withVersions(KubernetesVersionPriority.sortByPriority(spec.buildVersions(), CustomResourceDefinitionVersion::getName));
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { EnsureSingleStorageVersionDecorator.class };
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + "]";
| 189
| 24
| 213
|
<methods>public void <init>(java.lang.String) ,public void andThenVisit(CustomResourceDefinitionSpecFluent<?>, ObjectMeta) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1/decorator/SortPrinterColumnsDecorator.java
|
SortPrinterColumnsDecorator
|
hashCode
|
class SortPrinterColumnsDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
public SortPrinterColumnsDecorator(String name, String version) {
super(name, version);
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> version) {
List<CustomResourceColumnDefinition> columns = version.buildAdditionalPrinterColumns();
if (columns != null && !columns.isEmpty()) {
columns.sort((o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getJsonPath(), o2.getJsonPath()));
}
version.withAdditionalPrinterColumns(columns);
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { CustomResourceDefinitionVersionDecorator.class, AddAdditionPrinterColumnDecorator.class };
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomResourceDefinitionVersionDecorator other = (CustomResourceDefinitionVersionDecorator) obj;
if (getName() == null) {
if (other.getName() != null)
return false;
} else if (!getName().equals(other.getName()))
return false;
if (getVersion() == null) {
if (other.getVersion() != null)
return false;
} else if (!getVersion().equals(other.getVersion()))
return false;
return true;
}
@Override
public String toString() {
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + "]";
}
}
|
final int prime = 31;
int result = 1;
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getVersion() == null) ? 0 : getVersion().hashCode());
return result;
| 491
| 73
| 564
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public boolean equals(java.lang.Object) ,public java.lang.String getName() ,public java.lang.String getVersion() ,public int hashCode() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/CustomResourceHandler.java
|
CustomResourceHandler
|
addDecorators
|
class CustomResourceHandler extends AbstractCustomResourceHandler {
public static final String VERSION = "v1beta1";
public CustomResourceHandler(Resources resources, boolean parallel) {
super(resources, parallel);
}
@Override
protected Decorator<?> getPrinterColumnDecorator(
String name, String version, String path, String type, String column,
String description, String format, int priority) {
return new AddAdditionPrinterColumnDecorator(name, version, type, column, path, format,
description, priority);
}
@Override
protected void addDecorators(CustomResourceInfo config, TypeDef def,
Optional<String> specReplicasPath, Optional<String> statusReplicasPath,
Optional<String> labelSelectorPath) {<FILL_FUNCTION_BODY>}
@Override
public void handle(CustomResourceInfo config) {
super.handle(config);
}
}
|
final String name = config.crdName();
final String version = config.version();
resources.decorate(
new AddCustomResourceDefinitionResourceDecorator(name, config.group(), config.kind(),
config.scope().value(), config.shortNames(), config.plural(), config.singular(), config.annotations(),
config.labels()));
resources.decorate(new AddCustomResourceDefinitionVersionDecorator(name, version));
resources.decorate(new AddSchemaToCustomResourceDefinitionVersionDecorator(name, version,
JsonSchema.from(def, "kind", "apiVersion", "metadata")));
specReplicasPath.ifPresent(path -> {
resources.decorate(new AddSubresourcesDecorator(name, version));
resources.decorate(new AddSpecReplicasPathDecorator(name, version, path));
});
statusReplicasPath.ifPresent(path -> {
resources.decorate(new AddSubresourcesDecorator(name, version));
resources.decorate(new AddStatusReplicasPathDecorator(name, version, path));
});
labelSelectorPath.ifPresent(path -> {
resources.decorate(new AddSubresourcesDecorator(name, version));
resources.decorate(new AddLabelSelectorPathDecorator(name, version, path));
});
if (config.statusClassName().isPresent()) {
resources.decorate(new AddSubresourcesDecorator(name, version));
resources.decorate(new AddStatusSubresourceDecorator(name, version));
}
resources.decorate(new SetServedVersionDecorator(name, version, config.served()));
resources.decorate(new SetStorageVersionDecorator(name, version, config.storage()));
resources.decorate(new SetDeprecatedVersionDecorator(name, version, config.deprecated(), config.deprecationWarning()));
resources.decorate(new EnsureSingleStorageVersionDecorator(name));
resources.decorate(new SortCustomResourceDefinitionVersionDecorator(name));
resources.decorate(new PromoteSingleVersionAttributesDecorator(name));
resources.decorate(new SortPrinterColumnsDecorator(name, version));
| 236
| 550
| 786
|
<methods>public void handle(io.fabric8.crd.generator.CustomResourceInfo) <variables>private final non-sealed boolean parallel,protected final non-sealed io.fabric8.crd.generator.Resources resources
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/JsonSchema.java
|
JsonSchema
|
build
|
class JsonSchema extends AbstractJsonSchema<JSONSchemaProps, JSONSchemaPropsBuilder> {
private static final JsonSchema instance = new JsonSchema();
public static final JSONSchemaProps JSON_SCHEMA_INT_OR_STRING = new JSONSchemaPropsBuilder()
.withXKubernetesIntOrString(true)
.withAnyOf(
new JSONSchemaPropsBuilder().withType("integer").build(),
new JSONSchemaPropsBuilder().withType("string").build())
.build();
/**
* Creates the JSON schema for the particular {@link TypeDef}.
*
* @param definition The definition.
* @param ignore an optional list of property names to ignore
* @return The schema.
*/
public static JSONSchemaProps from(
TypeDef definition, String... ignore) {
return instance.internalFrom(definition, ignore);
}
@Override
public JSONSchemaPropsBuilder newBuilder() {
return newBuilder("object");
}
@Override
public JSONSchemaPropsBuilder newBuilder(String type) {
final JSONSchemaPropsBuilder builder = new JSONSchemaPropsBuilder();
builder.withType(type);
return builder;
}
@Override
public void addProperty(Property property, JSONSchemaPropsBuilder builder,
JSONSchemaProps schema, SchemaPropsOptions options) {
if (schema != null) {
options.getDefault().ifPresent(s -> {
try {
schema.setDefault(YAML_MAPPER.readTree(s));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Cannot parse default value: '" + s + "' as valid YAML.");
}
});
options.getMin().ifPresent(schema::setMinimum);
options.getMax().ifPresent(schema::setMaximum);
options.getPattern().ifPresent(schema::setPattern);
List<ValidationRule> validationRulesFromProperty = options.getValidationRules().stream()
.map(this::mapValidationRule)
.collect(Collectors.toList());
List<ValidationRule> resultingValidationRules = new ArrayList<>(schema.getXKubernetesValidations());
resultingValidationRules.addAll(validationRulesFromProperty);
if (!resultingValidationRules.isEmpty()) {
schema.setXKubernetesValidations(resultingValidationRules);
}
if (options.isNullable()) {
schema.setNullable(true);
}
if (options.isPreserveUnknownFields()) {
schema.setXKubernetesPreserveUnknownFields(true);
}
builder.addToProperties(property.getName(), schema);
}
}
@Override
public JSONSchemaProps build(JSONSchemaPropsBuilder builder, List<String> required,
List<KubernetesValidationRule> validationRules, boolean preserveUnknownFields) {<FILL_FUNCTION_BODY>}
@Override
protected JSONSchemaProps arrayLikeProperty(JSONSchemaProps schema) {
return new JSONSchemaPropsBuilder()
.withType("array")
.withNewItems()
.withSchema(schema)
.and()
.build();
}
@Override
protected JSONSchemaProps mapLikeProperty(JSONSchemaProps schema) {
return new JSONSchemaPropsBuilder()
.withType("object")
.withNewAdditionalProperties()
.withSchema(schema)
.endAdditionalProperties()
.build();
}
@Override
protected JSONSchemaProps singleProperty(String typeName) {
return new JSONSchemaPropsBuilder()
.withType(typeName)
.build();
}
@Override
protected JSONSchemaProps mappedProperty(TypeRef ref) {
return JSON_SCHEMA_INT_OR_STRING;
}
@Override
protected JSONSchemaProps enumProperty(JsonNode... enumValues) {
return new JSONSchemaPropsBuilder().withType("string").withEnum(enumValues).build();
}
@Override
protected JSONSchemaProps addDescription(JSONSchemaProps schema, String description) {
return new JSONSchemaPropsBuilder(schema)
.withDescription(description)
.build();
}
private List<ValidationRule> mapValidationRules(List<KubernetesValidationRule> validationRules) {
return validationRules.stream()
.map(this::mapValidationRule)
.collect(Collectors.toList());
}
private ValidationRule mapValidationRule(KubernetesValidationRule validationRule) {
return new ValidationRuleBuilder()
.withRule(validationRule.getRule())
.withMessage(validationRule.getMessage())
.withMessageExpression(validationRule.getMessageExpression())
.withReason(validationRule.getReason())
.withFieldPath(validationRule.getFieldPath())
.withOptionalOldSelf(validationRule.getOptionalOldSelf())
.build();
}
}
|
builder = builder.withRequired(required);
if (preserveUnknownFields) {
builder.withXKubernetesPreserveUnknownFields(preserveUnknownFields);
}
builder.addAllToXKubernetesValidations(mapValidationRules(validationRules));
return builder.build();
| 1,204
| 76
| 1,280
|
<methods>public non-sealed void <init>() ,public abstract void addProperty(Property, JSONSchemaPropsBuilder, JSONSchemaProps, io.fabric8.crd.generator.AbstractJsonSchema.SchemaPropsOptions) ,public abstract JSONSchemaProps build(JSONSchemaPropsBuilder, List<java.lang.String>, List<io.fabric8.crd.generator.AbstractJsonSchema.KubernetesValidationRule>, boolean) ,public static java.lang.String getSchemaTypeFor(TypeRef) ,public JSONSchemaProps internalFrom(java.lang.String, TypeRef) ,public abstract JSONSchemaPropsBuilder newBuilder() ,public abstract JSONSchemaPropsBuilder newBuilder(java.lang.String) <variables>public static final java.lang.String ANNOTATION_DEFAULT,public static final java.lang.String ANNOTATION_JSON_ANY_GETTER,public static final java.lang.String ANNOTATION_JSON_ANY_SETTER,public static final java.lang.String ANNOTATION_JSON_IGNORE,public static final java.lang.String ANNOTATION_JSON_PROPERTY,public static final java.lang.String ANNOTATION_JSON_PROPERTY_DESCRIPTION,public static final java.lang.String ANNOTATION_MAX,public static final java.lang.String ANNOTATION_MIN,public static final java.lang.String ANNOTATION_NULLABLE,public static final java.lang.String ANNOTATION_PATTERN,public static final java.lang.String ANNOTATION_PERSERVE_UNKNOWN_FIELDS,public static final java.lang.String ANNOTATION_REQUIRED,public static final java.lang.String ANNOTATION_SCHEMA_FROM,public static final java.lang.String ANNOTATION_SCHEMA_SWAP,public static final java.lang.String ANNOTATION_SCHEMA_SWAPS,public static final java.lang.String ANNOTATION_VALIDATION_RULE,public static final java.lang.String ANNOTATION_VALIDATION_RULES,public static final java.lang.String ANY_TYPE,private static final java.lang.String BOOLEAN_MARKER,private static final Map<TypeRef,java.lang.String> COMMON_MAPPINGS,protected static final TypeDef DATE,protected static final TypeRef DATE_REF,protected static final TypeDef DURATION,protected static final TypeRef DURATION_REF,private static final java.lang.String INTEGER_MARKER,protected static final TypeDef INT_OR_STRING,private static final java.lang.String INT_OR_STRING_MARKER,protected static final TypeRef INT_OR_STRING_REF,public static final java.lang.String JSON_NODE_TYPE,private static final Logger LOGGER,private static final java.lang.String NUMBER_MARKER,protected static final TypeDef OBJECT,protected static final TypeRef OBJECT_REF,protected static final TypeRef P_BOOLEAN_REF,protected static final TypeRef P_DOUBLE_REF,protected static final TypeRef P_FLOAT_REF,protected static final TypeRef P_INT_REF,protected static final TypeRef P_LONG_REF,protected static final TypeDef QUANTITY,protected static final TypeRef QUANTITY_REF,private static final java.lang.String STRING_MARKER,private static final java.lang.String VALUE
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/AddAdditionPrinterColumnDecorator.java
|
AddAdditionPrinterColumnDecorator
|
andThenVisit
|
class AddAdditionPrinterColumnDecorator extends
CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
private final String type;
private final String columnName;
private final String path;
private final String format;
private final String description;
private int priority;
public AddAdditionPrinterColumnDecorator(String resourceName, String resourceVersion, String type,
String columnName, String path, String format, String description, int priority) {
super(resourceName, resourceVersion);
this.type = type;
this.columnName = columnName;
this.path = path;
this.format = format;
this.description = description;
this.priority = priority;
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> spec) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getVersion() == null) ? 0 : getVersion().hashCode());
result = prime * result + ((columnName == null) ? 0 : columnName.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((path == null) ? 0 : path.hashCode());
result = prime * result + ((format == null) ? 0 : format.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + priority;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AddAdditionPrinterColumnDecorator other = (AddAdditionPrinterColumnDecorator) obj;
if (getName() == null) {
if (other.getName() != null)
return false;
} else if (!getName().equals(other.getName()))
return false;
if (getVersion() == null) {
if (other.getVersion() != null)
return false;
} else if (!getVersion().equals(other.getVersion()))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (format == null) {
if (other.format != null)
return false;
} else if (!format.equals(other.format))
return false;
if (columnName == null) {
if (other.columnName != null)
return false;
} else if (!columnName.equals(other.columnName))
return false;
if (path == null) {
if (other.path != null)
return false;
} else if (!path.equals(other.path))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return priority == other.priority;
}
@Override
public String toString() {
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + "column:" + columnName + "priority:"
+ priority + "]";
}
}
|
Predicate<CustomResourceColumnDefinitionBuilder> matchingColumn = col -> col.getName() != null
&& col.getName().equals(columnName) && col.getJSONPath() != null && col.getJSONPath().equals(path);
spec.removeMatchingFromAdditionalPrinterColumns(matchingColumn);
spec.addNewAdditionalPrinterColumn()
.withType(type)
.withName(columnName)
.withJSONPath(path)
.withFormat(Utils.isNotNullOrEmpty(format) ? format : null)
.withDescription(Utils.isNotNullOrEmpty(description) ? description : null)
.withPriority(priority)
.endAdditionalPrinterColumn();
| 917
| 173
| 1,090
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public java.lang.String getName() ,public java.lang.String getVersion() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/AddCustomResourceDefinitionResourceDecorator.java
|
AddCustomResourceDefinitionResourceDecorator
|
visit
|
class AddCustomResourceDefinitionResourceDecorator extends ResourceProvidingDecorator<KubernetesListBuilder> {
private String name;
private String apiGroup;
private String kind;
private String scope;
private String[] shortNames;
private String plural;
private String singular;
private String[] annotations;
private String[] labels;
public AddCustomResourceDefinitionResourceDecorator(String name, String apiGroup, String kind,
String scope, String[] shortNames, String plural, String singular, String[] annotations, String[] labels) {
this.name = name;
this.apiGroup = apiGroup;
this.kind = kind;
this.scope = scope;
this.shortNames = shortNames;
this.plural = plural;
this.singular = singular;
this.annotations = annotations;
this.labels = labels;
}
@Override
public void visit(KubernetesListBuilder list) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] before() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class,
CustomResourceDefinitionDecorator.class };
}
@Override
public String toString() {
return getClass().getName() + " [apiGroup=" + apiGroup + ", kind=" + kind + ", name=" + name + ", plural=" + plural
+ ", scope=" + scope + "]";
}
}
|
boolean exists = list.buildItems().stream().anyMatch(i -> i.getKind().equals("CustomResourceDefinition")
&& i.getMetadata().getName().equals(name)
&& ApiVersionUtil.trimVersion(i.getApiVersion()).equals("v1beta1"));
if (!exists) {
list.addToItems(new CustomResourceDefinitionBuilder()
.withNewMetadata()
.withName(name)
.withAnnotations(toMap(annotations))
.withLabels(toMap(labels))
.endMetadata()
.withNewSpec()
.withScope(scope)
.withGroup(apiGroup)
.withNewNames()
.withKind(kind)
.withShortNames(shortNames)
.withPlural(plural)
.withSingular(singular)
.endNames()
.endSpec()
.build());
}
| 371
| 227
| 598
|
<methods>public non-sealed void <init>() <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/AddCustomResourceDefinitionVersionDecorator.java
|
AddCustomResourceDefinitionVersionDecorator
|
andThenVisit
|
class AddCustomResourceDefinitionVersionDecorator extends
CustomResourceDefinitionDecorator<CustomResourceDefinitionSpecFluent<?>> {
private String version;
public AddCustomResourceDefinitionVersionDecorator(String name, String version) {
super(name);
this.version = version;
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
@Override
public void andThenVisit(CustomResourceDefinitionSpecFluent<?> spec, ObjectMeta resourceMeta) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionResourceDecorator.class };
}
@Override
public String toString() {
return getClass().getName() + " [name:" + getName() + ", version:" + version + "]";
}
}
|
Predicate<CustomResourceDefinitionVersionBuilder> predicate = candidate -> candidate.getName()
.equals(version);
spec.removeMatchingFromVersions(predicate);
spec.addNewVersion()
.withName(version)
.endVersion();
| 241
| 67
| 308
|
<methods>public void <init>(java.lang.String) ,public void andThenVisit(CustomResourceDefinitionSpecFluent<?>, ObjectMeta) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/AddLabelSelectorPathDecorator.java
|
AddLabelSelectorPathDecorator
|
andThenVisit
|
class AddLabelSelectorPathDecorator extends
CustomResourceDefinitionVersionDecorator<CustomResourceSubresourcesFluent<?>> {
private final String path;
public AddLabelSelectorPathDecorator(String name, String version, String path) {
super(name, version);
this.path = path;
}
@Override
public void andThenVisit(CustomResourceSubresourcesFluent<?> subresources) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class,
AddSubresourcesDecorator.class };
}
}
|
if (subresources.hasScale()) {
subresources.editScale().withLabelSelectorPath(path).endScale();
} else {
subresources.withNewScale().withLabelSelectorPath(path).endScale();
}
| 172
| 59
| 231
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceSubresourcesFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public java.lang.String getName() ,public java.lang.String getVersion() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/AddSchemaToCustomResourceDefinitionVersionDecorator.java
|
AddSchemaToCustomResourceDefinitionVersionDecorator
|
toString
|
class AddSchemaToCustomResourceDefinitionVersionDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
private JSONSchemaProps schema;
public AddSchemaToCustomResourceDefinitionVersionDecorator(String name, String version,
JSONSchemaProps schema) {
super(name, version);
this.schema = schema;
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> version) {
version.withNewSchema().withOpenAPIV3Schema(schema).endSchema();
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class };
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + "]";
| 207
| 32
| 239
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public java.lang.String getName() ,public java.lang.String getVersion() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/AddSpecReplicasPathDecorator.java
|
AddSpecReplicasPathDecorator
|
andThenVisit
|
class AddSpecReplicasPathDecorator extends
CustomResourceDefinitionVersionDecorator<CustomResourceSubresourcesFluent<?>> {
private final String path;
public AddSpecReplicasPathDecorator(String name, String version, String path) {
super(name, version);
this.path = path;
}
@Override
public void andThenVisit(CustomResourceSubresourcesFluent<?> subresources) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class,
AddSubresourcesDecorator.class };
}
}
|
if (subresources.hasScale()) {
subresources.editScale().withSpecReplicasPath(path).endScale();
} else {
subresources.withNewScale().withSpecReplicasPath(path).endScale();
}
| 176
| 63
| 239
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceSubresourcesFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public java.lang.String getName() ,public java.lang.String getVersion() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/AddStatusReplicasPathDecorator.java
|
AddStatusReplicasPathDecorator
|
andThenVisit
|
class AddStatusReplicasPathDecorator extends
CustomResourceDefinitionVersionDecorator<CustomResourceSubresourcesFluent<?>> {
private final String path;
public AddStatusReplicasPathDecorator(String name, String version, String path) {
super(name, version);
this.path = path;
}
@Override
public void andThenVisit(CustomResourceSubresourcesFluent<?> subresources) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddSubresourcesDecorator.class };
}
}
|
if (subresources.hasScale()) {
subresources.editScale().withStatusReplicasPath(path).endScale();
} else {
subresources.withNewScale().withStatusReplicasPath(path).endScale();
}
| 163
| 63
| 226
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceSubresourcesFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public java.lang.String getName() ,public java.lang.String getVersion() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/AddStatusSubresourceDecorator.java
|
AddStatusSubresourceDecorator
|
toString
|
class AddStatusSubresourceDecorator extends
CustomResourceDefinitionVersionDecorator<CustomResourceSubresourcesFluent<?>> {
public AddStatusSubresourceDecorator(String name, String version) {
super(name, version);
}
@Override
public void andThenVisit(CustomResourceSubresourcesFluent<?> subresources) {
subresources.withNewStatus().endStatus();
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class,
AddSubresourcesDecorator.class };
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + "]";
| 181
| 32
| 213
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceSubresourcesFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public java.lang.String getName() ,public java.lang.String getVersion() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/AddSubresourcesDecorator.java
|
AddSubresourcesDecorator
|
toString
|
class AddSubresourcesDecorator extends
CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
public AddSubresourcesDecorator(String name, String version) {
super(name, version);
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> spec) {
if (!spec.hasSubresources()) {
spec.withNewSubresources().endSubresources();
}
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class };
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion() + "]";
| 182
| 32
| 214
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public java.lang.String getName() ,public java.lang.String getVersion() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/CustomResourceDefinitionVersionDecorator.java
|
CustomResourceDefinitionVersionDecorator
|
visit
|
class CustomResourceDefinitionVersionDecorator<T> extends
Decorator<VisitableBuilder> {
protected static final String ANY = null;
private final String name;
private final String version;
private final CustomResourceDefinitionVersionVisitor versionSelector = new CustomResourceDefinitionVersionVisitor();
private final VersionVisitor versionVisitor = new VersionVisitor();
public CustomResourceDefinitionVersionDecorator(String name, String version) {
this.name = name;
this.version = version;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
@Override
public void visit(VisitableBuilder builder) {<FILL_FUNCTION_BODY>}
public abstract void andThenVisit(T version);
private class CustomResourceDefinitionVersionVisitor extends
TypedVisitor<CustomResourceDefinitionVersionBuilder> {
@Override
public void visit(CustomResourceDefinitionVersionBuilder builder) {
if (builder.getName().equals(version)) {
builder.accept(versionVisitor);
}
}
}
private class VersionVisitor extends TypedVisitor<T> {
@Override
public void visit(T version) {
andThenVisit(version);
}
public Class<T> getType() {
return (Class) Generics
.getTypeArguments(CustomResourceDefinitionVersionDecorator.class,
CustomResourceDefinitionVersionDecorator.this.getClass())
.get(0);
}
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] {
AddCustomResourceDefinitionResourceDecorator.class,
AddCustomResourceDefinitionVersionDecorator.class };
}
@Override
public Class<? extends Decorator>[] before() {
return new Class[] {};
}
}
|
Optional<ObjectMeta> objectMeta = getMetadata(builder);
if (!objectMeta.isPresent()) {
return;
}
if (Utils.isNullOrEmpty(name) || objectMeta.map(ObjectMeta::getName).filter(s -> s.equals(name))
.isPresent()) {
builder.accept(versionSelector);
}
| 473
| 90
| 563
|
<methods>public non-sealed void <init>() ,public Class<? extends Decorator#RAW>[] after() ,public Class<? extends Decorator#RAW>[] before() ,public int compareTo(Decorator#RAW) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/EnsureSingleStorageVersionDecorator.java
|
EnsureSingleStorageVersionDecorator
|
andThenVisit
|
class EnsureSingleStorageVersionDecorator extends
CustomResourceDefinitionDecorator<CustomResourceDefinitionSpecFluent<?>> {
public EnsureSingleStorageVersionDecorator(String name) {
super(name);
}
@Override
public void andThenVisit(CustomResourceDefinitionSpecFluent<?> spec, ObjectMeta resourceMeta) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] {
CustomResourceDefinitionVersionDecorator.class
};
}
@Override
public String toString() {
return getClass().getName() + " [name:" + getName() + "]";
}
}
|
List<CustomResourceDefinitionVersion> versions = spec.buildVersions();
List<String> storageVersions = versions.stream()
.filter(v -> Optional.ofNullable(v.getStorage()).orElse(true))
.map(CustomResourceDefinitionVersion::getName)
.collect(Collectors.toList());
if (storageVersions.size() > 1) {
throw new IllegalStateException(String.format(
"'%s' custom resource has versions %s marked as storage. Only one version can be marked as storage per custom resource.",
resourceMeta.getName(), storageVersions));
}
| 181
| 151
| 332
|
<methods>public void <init>(java.lang.String) ,public void andThenVisit(CustomResourceDefinitionSpecFluent<?>, ObjectMeta) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/PromoteSingleVersionAttributesDecorator.java
|
PromoteSingleVersionAttributesDecorator
|
mergeSubresources
|
class PromoteSingleVersionAttributesDecorator
extends CustomResourceDefinitionDecorator<CustomResourceDefinitionSpecFluent<?>> {
public PromoteSingleVersionAttributesDecorator(String name) {
super(name);
}
private CustomResourceSubresources mergeSubresources(CustomResourceSubresources versionSub,
CustomResourceSubresources topLevelSub) {<FILL_FUNCTION_BODY>}
@Override
public void andThenVisit(CustomResourceDefinitionSpecFluent<?> spec, ObjectMeta resourceMeta) {
List<CustomResourceDefinitionVersion> versions = spec.buildVersions();
if (versions.size() == 1) {
CustomResourceDefinitionVersion version = versions.get(0);
spec.withSubresources(mergeSubresources(version.getSubresources(), spec.buildSubresources()))
.withValidation(version.getSchema())
.withAdditionalPrinterColumns(version.getAdditionalPrinterColumns());
CustomResourceDefinitionVersion newVersion = new CustomResourceDefinitionVersionBuilder(version).build();
newVersion.setSubresources(null);
newVersion.setSchema(null);
newVersion.setAdditionalPrinterColumns(null);
spec.removeAllFromVersions(versions);
spec.withVersions(newVersion);
} else {
Set<CustomResourceSubresources> subresources = versions.stream().map(CustomResourceDefinitionVersion::getSubresources)
.filter(o -> o != null).collect(Collectors.toSet());
Set<List<CustomResourceColumnDefinition>> additionalPrinterColumns = versions.stream()
.map(CustomResourceDefinitionVersion::getAdditionalPrinterColumns).filter(o -> o != null).collect(Collectors.toSet());
Set<CustomResourceValidation> schemas = versions.stream().map(CustomResourceDefinitionVersion::getSchema)
.filter(o -> o != null).collect(Collectors.toSet());
boolean hasIdenticalSubresources = subresources.size() == 1;
boolean hasIdenticalAdditionalPrinterColumns = additionalPrinterColumns.size() == 1;
boolean hasIdenticalSchemas = schemas.size() == 1;
if (hasIdenticalSchemas) {
spec.withValidation(schemas.iterator().next());
}
if (hasIdenticalSubresources) {
spec.withSubresources(mergeSubresources(subresources.iterator().next(), spec.buildSubresources()));
}
if (hasIdenticalAdditionalPrinterColumns) {
spec.withAdditionalPrinterColumns(additionalPrinterColumns.iterator().next());
}
spec.removeAllFromVersions(versions);
List<CustomResourceDefinitionVersion> newVersions = new ArrayList<>();
for (CustomResourceDefinitionVersion version : versions) {
CustomResourceDefinitionVersion newVersion = new CustomResourceDefinitionVersionBuilder(version).build();
if (hasIdenticalSchemas) {
newVersion.setSchema(null);
}
if (hasIdenticalSubresources) {
newVersion.setSubresources(null);
}
if (hasIdenticalAdditionalPrinterColumns) {
newVersion.setAdditionalPrinterColumns(null);
}
newVersions.add(newVersion);
}
spec.withVersions(newVersions);
}
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] {
AddCustomResourceDefinitionResourceDecorator.class,
AddCustomResourceDefinitionVersionDecorator.class,
CustomResourceDefinitionVersionDecorator.class,
AddSchemaToCustomResourceDefinitionVersionDecorator.class,
AddSubresourcesDecorator.class, AddStatusSubresourceDecorator.class,
AddStatusReplicasPathDecorator.class, AddSpecReplicasPathDecorator.class,
AddLabelSelectorPathDecorator.class };
}
}
|
if (versionSub == null) {
return topLevelSub;
} else if (topLevelSub == null) {
return versionSub;
} else {
// merge additional properties
Map<String, Object> additionalProperties = new HashMap<>();
if (versionSub.getAdditionalProperties() != null) {
additionalProperties.putAll(versionSub.getAdditionalProperties());
}
if (topLevelSub.getAdditionalProperties() != null) {
additionalProperties.putAll(topLevelSub.getAdditionalProperties());
}
// merge scale
CustomResourceSubresourceScale scale = null;
if (topLevelSub.getScale() != null) {
scale = topLevelSub.getScale();
} else if (versionSub.getScale() != null) {
scale = versionSub.getScale();
}
// merge status
CustomResourceSubresourceStatus status = null;
if (topLevelSub.getStatus() != null) {
status = topLevelSub.getStatus();
} else if (versionSub.getStatus() != null) {
status = versionSub.getStatus();
}
return new CustomResourceSubresourcesBuilder()
.withAdditionalProperties(additionalProperties)
.withScale(scale)
.withStatus(status)
.build();
}
| 936
| 330
| 1,266
|
<methods>public void <init>(java.lang.String) ,public void andThenVisit(CustomResourceDefinitionSpecFluent<?>, ObjectMeta) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/SetDeprecatedVersionDecorator.java
|
SetDeprecatedVersionDecorator
|
toString
|
class SetDeprecatedVersionDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
private final boolean deprecated;
private final String deprecationWarning;
public SetDeprecatedVersionDecorator(String name, String version, boolean deprecated, String deprecationWarning) {
super(name, version);
this.deprecated = deprecated;
this.deprecationWarning = deprecationWarning;
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> version) {
if (deprecated) {
version.withDeprecated(true);
version.withDeprecationWarning(deprecationWarning);
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + ", version:" + getVersion()
+ ", deprecated:" + deprecated + ", deprecationWarning:" + deprecationWarning + "]";
| 204
| 54
| 258
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public java.lang.String getName() ,public java.lang.String getVersion() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/SortCustomResourceDefinitionVersionDecorator.java
|
SortCustomResourceDefinitionVersionDecorator
|
toString
|
class SortCustomResourceDefinitionVersionDecorator
extends CustomResourceDefinitionDecorator<CustomResourceDefinitionSpecFluent<?>> {
public SortCustomResourceDefinitionVersionDecorator(String name) {
super(name);
}
@Override
public void andThenVisit(CustomResourceDefinitionSpecFluent<?> spec, ObjectMeta resourceMeta) {
spec.withVersions(KubernetesVersionPriority.sortByPriority(spec.buildVersions(), CustomResourceDefinitionVersion::getName));
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { EnsureSingleStorageVersionDecorator.class };
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " [name:" + getName() + "]";
| 189
| 24
| 213
|
<methods>public void <init>(java.lang.String) ,public void andThenVisit(CustomResourceDefinitionSpecFluent<?>, ObjectMeta) <variables>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/SortPrinterColumnsDecorator.java
|
SortPrinterColumnsDecorator
|
andThenVisit
|
class SortPrinterColumnsDecorator
extends CustomResourceDefinitionVersionDecorator<CustomResourceDefinitionVersionFluent<?>> {
public SortPrinterColumnsDecorator(String name, String version) {
super(name, version);
}
@Override
public void andThenVisit(CustomResourceDefinitionVersionFluent<?> version) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { AddCustomResourceDefinitionVersionDecorator.class, AddAdditionPrinterColumnDecorator.class };
}
}
|
List<CustomResourceColumnDefinition> columns = version.buildAdditionalPrinterColumns();
if (columns != null && !columns.isEmpty()) {
columns.sort((o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getJSONPath(), o2.getJSONPath()));
}
version.withAdditionalPrinterColumns(columns);
| 153
| 94
| 247
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public Class<? extends Decorator#RAW>[] after() ,public abstract void andThenVisit(CustomResourceDefinitionVersionFluent<?>) ,public Class<? extends Decorator#RAW>[] before() ,public java.lang.String getName() ,public java.lang.String getVersion() ,public void visit(VisitableBuilder) <variables>protected static final java.lang.String ANY,private final non-sealed java.lang.String name,private final non-sealed java.lang.String version,private final CustomResourceDefinitionVersionVisitor versionSelector,private final VersionVisitor versionVisitor
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/visitor/AnnotatedMultiPropertyPathDetector.java
|
AnnotatedMultiPropertyPathDetector
|
visit
|
class AnnotatedMultiPropertyPathDetector extends TypedVisitor<TypeDefBuilder> {
protected static final String DOT = ".";
protected static final String STATUS = ".status.";
private final String prefix;
private final String annotationName;
private final List<Property> parents;
private final Map<String, Property> properties;
private final Deque<Runnable> toRun;
public AnnotatedMultiPropertyPathDetector(String prefix, String annotationName) {
this(prefix, annotationName, new ArrayList<>(), new HashMap<>(), new ArrayDeque<>());
}
public AnnotatedMultiPropertyPathDetector(String prefix, String annotationName, List<Property> parents,
Map<String, Property> properties, Deque<Runnable> toRun) {
this.prefix = prefix;
this.annotationName = annotationName;
this.parents = parents;
this.properties = properties;
this.toRun = toRun;
}
private boolean excludePropertyProcessing(Property p) {
return p.getAnnotations().stream()
.anyMatch(ann -> ann.getClassRef().getFullyQualifiedName().equals(ANNOTATION_JSON_IGNORE));
}
@Override
public void visit(TypeDefBuilder builder) {<FILL_FUNCTION_BODY>}
public Set<String> getPaths() {
return properties.keySet();
}
public Map<String, Property> getProperties() {
return properties;
}
}
|
TypeDef type = builder.build();
final List<Property> props = type.getProperties();
for (Property p : props) {
if (parents.contains(p)) {
continue;
}
List<Property> newParents = new ArrayList<>(parents);
boolean match = p.getAnnotations().stream().anyMatch(a -> a.getClassRef().getName().equals(annotationName));
if (match) {
newParents.add(p);
this.properties
.put(newParents.stream().map(Property::getName).collect(Collectors.joining(DOT, prefix, "")), p);
}
}
props.stream().filter(p -> p.getTypeRef() instanceof ClassRef).forEach(p -> {
if (!parents.contains(p) && !excludePropertyProcessing(p)) {
ClassRef classRef = (ClassRef) p.getTypeRef();
TypeDef propertyType = Types.typeDefFrom(classRef);
if (!propertyType.isEnum() && !classRef.getPackageName().startsWith("java.")) {
List<Property> newParents = new ArrayList<>(parents);
newParents.add(p);
toRun.add(() -> new TypeDefBuilder(propertyType)
.accept(new AnnotatedMultiPropertyPathDetector(prefix, annotationName, newParents, properties, toRun)));
}
}
});
if (parents.isEmpty()) {
while (!toRun.isEmpty()) {
toRun.pop().run();
}
}
| 384
| 393
| 777
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/visitor/AnnotatedPropertyPathDetector.java
|
AnnotatedPropertyPathDetector
|
visit
|
class AnnotatedPropertyPathDetector extends TypedVisitor<TypeDefBuilder> {
protected static final String DOT = ".";
protected static final String STATUS = ".status.";
private final String prefix;
private final String annotationName;
private final List<Property> parents;
private final AtomicReference<String> reference;
private final Deque<Runnable> toRun;
public AnnotatedPropertyPathDetector(String prefix, String annotationName) {
this(prefix, annotationName, new ArrayList<>(), new AtomicReference<>(), new ArrayDeque<>());
}
public AnnotatedPropertyPathDetector(String prefix, String annotationName, List<Property> parents,
AtomicReference<String> reference, Deque<Runnable> toRun) {
this.prefix = prefix;
this.annotationName = annotationName;
this.parents = parents;
this.reference = reference;
this.toRun = toRun;
}
private static boolean excludePropertyProcessing(Property p) {
for (AnnotationRef annotation : p.getAnnotations()) {
if (annotation.getClassRef().getFullyQualifiedName().equals(ANNOTATION_JSON_IGNORE)) {
return true;
}
}
return false;
}
@Override
public void visit(TypeDefBuilder builder) {<FILL_FUNCTION_BODY>}
private void visitProperties(List<Property> properties) {
for (Property p : properties) {
if (parents.contains(p)) {
continue;
}
List<Property> newParents = new ArrayList<>(parents);
boolean match = false;
for (AnnotationRef annotation : p.getAnnotations()) {
match = annotation.getClassRef().getName().equals(annotationName);
if (match) {
newParents.add(p);
reference.set(newParents.stream().map(Property::getName).collect(Collectors.joining(DOT, prefix, "")));
return;
}
}
if (p.getTypeRef() instanceof ClassRef && !excludePropertyProcessing(p)) {
ClassRef classRef = (ClassRef) p.getTypeRef();
TypeDef propertyType = Types.typeDefFrom(classRef);
if (!propertyType.isEnum() && !classRef.getPackageName().startsWith("java.")) {
newParents.add(p);
new TypeDefBuilder(propertyType)
.accept(new AnnotatedPropertyPathDetector(prefix, annotationName, newParents, reference, toRun));
}
}
}
if (parents.isEmpty()) {
while (!toRun.isEmpty() && reference.get() == null) {
toRun.pop().run();
}
}
}
public Optional<String> getPath() {
return Optional.ofNullable(reference.get());
}
}
|
TypeDef type = builder.build();
final List<Property> properties = type.getProperties();
visitProperties(properties);
| 729
| 34
| 763
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/visitor/ClassDependenciesVisitor.java
|
ClassDependenciesVisitor
|
visit
|
class ClassDependenciesVisitor extends TypedVisitor<TypeDefBuilder> {
private static final Map<String, Set<String>> traversedClasses = new HashMap<>();
private static final Map<String, Set<String>> crdNameToCrClass = new HashMap<>();
private final Set<String> classesForCR;
private final Set<ClassRef> processed = new HashSet<>();
public ClassDependenciesVisitor(String crClassName, String crdName) {
// need to record all classes associated with the different versions of the CR (not the CRD spec)
crdNameToCrClass.computeIfAbsent(crdName, k -> new HashSet<>()).add(crClassName);
classesForCR = traversedClasses.computeIfAbsent(crClassName, k -> new HashSet<>());
}
@Override
public void visit(TypeDefBuilder builder) {<FILL_FUNCTION_BODY>}
private boolean ignore(String className) {
return (className.startsWith("java.") && !className.startsWith("java.util."))
|| className.startsWith("com.fasterxml.jackson") || className.startsWith("jdk.");
}
private void processTypeRef(TypeRef t) {
if (t instanceof ClassRef) {
ClassRef classRef = (ClassRef) t;
// only process the class reference if we haven't already
// note that the references are stored in the set including type arguments, so List<A> and List<B> are not the same
if (processed.add(classRef)) {
visit(new TypeDefBuilder(Types.typeDefFrom(classRef)));
}
}
}
public static Map<String, Set<String>> getTraversedClasses() {
return traversedClasses;
}
public static Set<String> getDependentClasses(String crClassName) {
return traversedClasses.get(crClassName);
}
public static Set<String> getDependentClassesFromCRDName(String crdName) {
// retrieve all dependent classes that might affect any of the CR versions
return crdNameToCrClass.get(crdName).stream()
.flatMap(crClassName -> traversedClasses.get(crClassName).stream())
.collect(Collectors.toSet());
}
}
|
TypeDef type = builder.build();
// finish quickly if we're ignoring the class or we already have processed it
// note that we cannot simply check the traversed class set to know if a class has been processed because classes
// are usually added to the traversed set before they're looked at in depth
final String className = type.getFullyQualifiedName();
if (ignore(className)) {
return;
}
// process all references to see if they need to be added or not
type.getReferences().forEach(c -> {
final String fqn = c.getFullyQualifiedName();
if (ignore(fqn)) {
return;
}
// check if we're dealing with a collection type to extract parameter types if existing
if (fqn.startsWith("java.util") && (Collections.isCollection(c) || Collections.IS_MAP.apply(c))) {
c.getArguments().forEach(this::processTypeRef);
} else {
// otherwise, process all non-JDK classes that we haven't already processed
if (!ignore(fqn) && classesForCR.add(fqn)) {
// deal with generic arguments if present
c.getArguments().forEach(this::processTypeRef);
}
}
});
// add classes from extends list
type.getExtendsList().forEach(this::processTypeRef);
| 582
| 355
| 937
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/apt/src/main/java/io/fabric8/crd/generator/apt/CustomResourceAnnotationProcessor.java
|
CustomResourceAnnotationProcessor
|
enableParallelGeneration
|
class CustomResourceAnnotationProcessor extends AbstractProcessor {
public static final String PROCESSOR_OPTION_PARALLEL = "io.fabric8.crd.generator.parallel";
private final CRDGenerator generator = new CRDGenerator();
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@SuppressWarnings("unchecked")
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
final Messager messager = processingEnv.getMessager();
final CRDGenerator crdGenerator = generator
.withOutput(new FileObjectCRDOutput(processingEnv));
final Map<String, String> options = processingEnv.getOptions();
enableParallelGeneration(messager, crdGenerator, options);
final CRDGenerationInfo allCRDs = crdGenerator
.detailedGenerate();
allCRDs.getCRDDetailsPerNameAndVersion().forEach((crdName, versionToInfo) -> {
messager.printMessage(Diagnostic.Kind.NOTE, "Generating CRD " + crdName + ":\n");
versionToInfo.forEach(
(version, info) -> messager.printMessage(Diagnostic.Kind.NOTE, " - " + version + " -> " + info.getFilePath()));
});
return true;
}
// make sure we create the context before using it
AptContext.create(processingEnv.getElementUtils(), processingEnv.getTypeUtils(), DefinitionRepository.getRepository());
//Collect all annotated types.
for (TypeElement annotation : annotations) {
for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
if (element instanceof TypeElement) {
try {
// The annotation is loaded with reflection for compatibility with Java 8
Class<Annotation> generatedAnnotation = (Class<Annotation>) Class.forName("javax.annotation.processing.Generated");
if (element.getAnnotationsByType(generatedAnnotation).length > 0) {
continue;
}
} catch (ClassNotFoundException e) {
// ignore
}
generator.customResources(toCustomResourceInfo((TypeElement) element));
}
}
}
return false;
}
private void enableParallelGeneration(Messager messager, CRDGenerator crdGenerator, Map<String, String> options) {<FILL_FUNCTION_BODY>}
private CustomResourceInfo toCustomResourceInfo(TypeElement customResource) {
TypeDef definition = Adapters.adaptType(customResource, AptContext.getContext());
definition = Types.unshallow(definition);
if (CustomResourceInfo.DESCRIBE_TYPE_DEFS) {
Types.output(definition);
}
final Name crClassName = customResource.getQualifiedName();
SpecAndStatus specAndStatus = Types.resolveSpecAndStatusTypes(definition);
if (specAndStatus.isUnreliable()) {
System.out.println("Cannot reliably determine status types for " + crClassName
+ " because it isn't parameterized with only spec and status types. Status replicas detection will be deactivated.");
}
final String group = customResource.getAnnotation(Group.class).value();
final String version = customResource.getAnnotation(Version.class).value();
final String kind = Optional.ofNullable(customResource.getAnnotation(Kind.class))
.map(Kind::value)
.orElse(customResource.getSimpleName().toString());
final String singular = Optional.ofNullable(customResource.getAnnotation(Singular.class))
.map(Singular::value)
.orElse(kind.toLowerCase(Locale.ROOT));
final String plural = Optional.ofNullable(customResource.getAnnotation(Plural.class))
.map(Plural::value)
.map(s -> s.toLowerCase(Locale.ROOT))
.orElse(Pluralize.toPlural(singular));
final String[] shortNames = Optional
.ofNullable(customResource.getAnnotation(ShortNames.class))
.map(ShortNames::value)
.orElse(new String[] {});
final String[] annotations = Optional
.ofNullable(customResource.getAnnotation(Annotations.class))
.map(Annotations::value)
.orElse(new String[] {});
final String[] labels = Optional
.ofNullable(customResource.getAnnotation(Labels.class))
.map(Labels::value)
.orElse(new String[] {});
final boolean storage = customResource.getAnnotation(Version.class).storage();
final boolean served = customResource.getAnnotation(Version.class).served();
final boolean deprecated = customResource.getAnnotation(Version.class).deprecated();
final String deprecationWarning = Optional.ofNullable(customResource.getAnnotation(Version.class).deprecationWarning())
.filter(s -> deprecated)
.filter(Utils::isNotNullOrEmpty)
.orElse(null);
final Scope scope = Types.isNamespaced(definition) ? Scope.NAMESPACED : Scope.CLUSTER;
return new CustomResourceInfo(group, version, kind, singular, plural, shortNames, storage, served,
deprecated, deprecationWarning,
scope, definition, crClassName.toString(),
specAndStatus.getSpecClassName(), specAndStatus.getStatusClassName(), annotations, labels);
}
private static class FileObjectOutputStream extends OutputStream {
private final FileObject yml;
private final OutputStream out;
public FileObjectOutputStream(FileObject yml) throws IOException {
this.yml = yml;
this.out = yml.openOutputStream();
}
@Override
public void write(byte[] b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
out.close();
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
public URI toUri() {
return yml.toUri();
}
}
private static class FileObjectCRDOutput extends AbstractCRDOutput<FileObjectOutputStream> {
private final ProcessingEnvironment processingEnv;
public FileObjectCRDOutput(ProcessingEnvironment processingEnv) {
this.processingEnv = processingEnv;
}
@Override
protected FileObjectOutputStream createStreamFor(String crdName) throws IOException {
return new FileObjectOutputStream(
processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "",
"META-INF/fabric8/" + crdName + ".yml"));
}
@Override
public URI crdURI(String crdName) {
return getStreamFor(crdName).toUri();
}
}
}
|
if (options.containsKey(PROCESSOR_OPTION_PARALLEL)) {
final String rawValue = options.get(PROCESSOR_OPTION_PARALLEL);
final boolean parallel = Boolean.parseBoolean(rawValue);
messager.printMessage(Diagnostic.Kind.NOTE,
String.format("Found option %s set to %s, parallel set to %b ", PROCESSOR_OPTION_PARALLEL, rawValue, parallel));
crdGenerator.withParallelGenerationEnabled(parallel);
}
| 1,811
| 133
| 1,944
|
<methods>public Iterable<? extends javax.annotation.processing.Completion> getCompletions(javax.lang.model.element.Element, javax.lang.model.element.AnnotationMirror, javax.lang.model.element.ExecutableElement, java.lang.String) ,public Set<java.lang.String> getSupportedAnnotationTypes() ,public Set<java.lang.String> getSupportedOptions() ,public javax.lang.model.SourceVersion getSupportedSourceVersion() ,public synchronized void init(javax.annotation.processing.ProcessingEnvironment) ,public abstract boolean process(Set<? extends javax.lang.model.element.TypeElement>, javax.annotation.processing.RoundEnvironment) <variables>static final boolean $assertionsDisabled,private boolean initialized,protected javax.annotation.processing.ProcessingEnvironment processingEnv
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/CertManagerExtensionAdapter.java
|
CertManagerExtensionAdapter
|
registerClients
|
class CertManagerExtensionAdapter implements ExtensionAdapter<CertManagerClient> {
@Override
public Class<CertManagerClient> getExtensionType() {
return CertManagerClient.class;
}
@Override
public CertManagerClient adapt(Client client) {
return new DefaultCertManagerClient(client);
}
@Override
public void registerClients(ClientFactory factory) {<FILL_FUNCTION_BODY>}
}
|
factory.register(V1alpha2APIGroupDSL.class, new V1alpha2APIGroupClient());
factory.register(V1alpha3APIGroupDSL.class, new V1alpha3APIGroupClient());
factory.register(V1beta1APIGroupDSL.class, new V1beta1APIGroupClient());
factory.register(V1APIGroupDSL.class, new V1APIGroupClient());
| 111
| 111
| 222
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/certmanager/examples/src/main/java/io/fabric8/certmanager/examples/ClientFactory.java
|
ClientFactory
|
newClient
|
class ClientFactory {
private ClientFactory() {
throw new IllegalStateException("Utility class");
}
public static CertManagerClient newClient(String[] args) {<FILL_FUNCTION_BODY>}
public static String getOptions(String[] args, String name, String defaultValue) {
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals(name)) {
return value;
}
}
return defaultValue;
}
}
|
ConfigBuilder config = new ConfigBuilder();
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals("--api-server")) {
config = config.withMasterUrl(value);
}
if (key.equals("--token")) {
config = config.withOauthToken(value);
}
if (key.equals("--username")) {
config = config.withUsername(value);
}
if (key.equals("--password")) {
config = config.withPassword(value);
}
if (key.equals("--namespace")) {
config = config.withNamespace(value);
}
}
return new KubernetesClientBuilder().withConfig(config.build()).build().adapt(CertManagerClient.class);
| 152
| 226
| 378
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/certmanager/examples/src/main/java/io/fabric8/certmanager/examples/v1/CertificateCreate.java
|
CertificateCreate
|
main
|
class CertificateCreate {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try (NamespacedCertManagerClient certManagerClient = new DefaultCertManagerClient()) {
String namespace = "default";
Certificate certificate = new CertificateBuilder()
.build();
// Create Certificate
certManagerClient.v1().certificates().inNamespace(namespace).create(certificate);
System.out.println("Created: " + certificate.getMetadata().getName());
// List Certificate
CertificateList certificateList = certManagerClient.v1().certificates().inNamespace(namespace).list();
System.out.println("There are " + certificateList.getItems().size() + " TaskRun objects in " + namespace);
}
| 32
| 162
| 194
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/certmanager/examples/src/main/java/io/fabric8/certmanager/examples/v1alpha2/CertificateCreate.java
|
CertificateCreate
|
main
|
class CertificateCreate {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try (NamespacedCertManagerClient certManagerClient = new DefaultCertManagerClient()) {
String namespace = "default";
Certificate certificate = new CertificateBuilder()
.build();
// Create Certificate
certManagerClient.v1alpha2().certificates().inNamespace(namespace).create(certificate);
System.out.println("Created: " + certificate.getMetadata().getName());
// List Certificate
CertificateList certificateList = certManagerClient.v1alpha2().certificates().inNamespace(namespace).list();
System.out.println("There are " + certificateList.getItems().size() + " TaskRun objects in " + namespace);
}
| 32
| 166
| 198
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/certmanager/examples/src/main/java/io/fabric8/certmanager/examples/v1alpha3/CertificateCreate.java
|
CertificateCreate
|
main
|
class CertificateCreate {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try (NamespacedCertManagerClient certManagerClient = new DefaultCertManagerClient()) {
String namespace = "default";
Certificate certificate = new CertificateBuilder()
.build();
// Create Certificate
certManagerClient.v1alpha3().certificates().inNamespace(namespace).create(certificate);
System.out.println("Created: " + certificate.getMetadata().getName());
// List Certificate
CertificateList certificateList = certManagerClient.v1alpha3().certificates().inNamespace(namespace).list();
System.out.println("There are " + certificateList.getItems().size() + " TaskRun objects in " + namespace);
}
| 32
| 166
| 198
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/certmanager/examples/src/main/java/io/fabric8/certmanager/examples/v1beta1/CertificateCreate.java
|
CertificateCreate
|
main
|
class CertificateCreate {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try (NamespacedCertManagerClient certManagerClient = new DefaultCertManagerClient()) {
String namespace = "default";
Certificate certificate = new CertificateBuilder()
.build();
// Create Certificate
certManagerClient.v1beta1().certificates().inNamespace(namespace).create(certificate);
System.out.println("Created: " + certificate.getMetadata().getName());
// List Certificate
CertificateList certificateList = certManagerClient.v1beta1().certificates().inNamespace(namespace).list();
System.out.println("There are " + certificateList.getItems().size() + " TaskRun objects in " + namespace);
}
| 32
| 166
| 198
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/chaosmesh/examples/src/main/java/io/fabric8/chaosmesh/examples/ClientFactory.java
|
ClientFactory
|
newClient
|
class ClientFactory {
private ClientFactory() {
}
public static ChaosMeshClient newClient(String[] args) {<FILL_FUNCTION_BODY>}
public static String getOptions(String[] args, String name, String defaultValue) {
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals(name)) {
return value;
}
}
return defaultValue;
}
}
|
ConfigBuilder config = new ConfigBuilder();
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals("--api-server")) {
config = config.withMasterUrl(value);
}
if (key.equals("--token")) {
config = config.withOauthToken(value);
}
if (key.equals("--username")) {
config = config.withUsername(value);
}
if (key.equals("--password")) {
config = config.withPassword(value);
}
if (key.equals("--namespace")) {
config = config.withNamespace(value);
}
}
return new DefaultChaosMeshClient(config.build());
| 141
| 215
| 356
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/chaosmesh/examples/src/main/java/io/fabric8/chaosmesh/examples/CreateIoChaos.java
|
CreateIoChaos
|
main
|
class CreateIoChaos {
//apiVersion: chaos-mesh.org/v1alpha1
//kind: IOChaos
//metadata:
// name: io-delay-example
//spec:
// action: latency
// mode: one
// selector:
// labelSelectors:
// app: etcd
// volumePath: /var/run/etcd
// path: "/var/run/etcd/**/*"
// delay: "100ms"
// percent: 50
// duration: "400s"
// scheduler:
// cron: "@every 10m"
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try (ChaosMeshClient client = ClientFactory.newClient(args)) {
System.out.println("Creating a ioChaos");
client.ioChaos().inNamespace("default").create(new IOChaosBuilder()
.withNewMetadata()
.withName("io-delay-example")
.endMetadata()
.withNewSpec()
.withAction("latency")
.withMode("one")
.withNewSelector().withLabelSelectors(Collections.singletonMap("app", "etcd")).endSelector()
.withVolumePath("/var/run/etcd")
.withPath("/var/run/etc/**/*")
.withPercent(50)
.withDuration("400s")
.endSpec()
.build());
}
| 204
| 203
| 407
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/AuthorizationPolicyExample.java
|
AuthorizationPolicyExample
|
createResource
|
class AuthorizationPolicyExample {
private static final String NAMESPACE = "test";
public static void main(String[] args) {
try {
IstioClient client = ClientFactory.newClient(args);
createResource(client);
System.exit(0);
} catch (KubernetesClientException ex) {
System.err.println("Failed with " + ex.getMessage());
System.exit(1);
}
}
public static void createResource(IstioClient client) {<FILL_FUNCTION_BODY>}
}
|
System.out.println("Creating a AuthorizationPolicy entry");
client.v1beta1().authorizationPolicies().inNamespace(NAMESPACE).create(new AuthorizationPolicyBuilder()
.withNewMetadata()
.withName("httpbin")
.endMetadata()
.withNewSpec()
.withSelector(new WorkloadSelectorBuilder().withMatchLabels(Collections.singletonMap("app", "httpbin")).build())
.withAction(AuthorizationPolicyAction.DENY)
.withRules(new RuleBuilder()
.withFrom(
new RuleFromBuilder()
.withSource(new SourceBuilder().withPrincipals("cluster.local/ns/default/sa/sleep").build())
.build(),
new RuleFromBuilder().withSource(new SourceBuilder().withNamespaces("dev").build()).build())
.withTo(new RuleToBuilder().withOperation(new OperationBuilder().withMethods("GET").build()).build())
.withWhen(
new ConditionBuilder().withKey("request.auth.claims[iss]").withValues("https://accounts.google.com").build())
.build())
.endSpec()
.build());
System.out.println("Listing AuthorizationPolicy instances:");
AuthorizationPolicyList list = client.v1beta1().authorizationPolicies().inNamespace(NAMESPACE).list();
list.getItems().forEach(b -> System.out.println(b.getMetadata().getName()));
System.out.println("Done");
| 142
| 373
| 515
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/ClientFactory.java
|
ClientFactory
|
newClient
|
class ClientFactory {
private ClientFactory() {
throw new IllegalStateException("Utility class");
}
public static IstioClient newClient(String[] args) {<FILL_FUNCTION_BODY>}
public static String getOptions(String[] args, String name, String defaultValue) {
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals(name)) {
return value;
}
}
return defaultValue;
}
}
|
ConfigBuilder config = new ConfigBuilder();
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals("--api-server")) {
config = config.withMasterUrl(value);
}
if (key.equals("--token")) {
config = config.withOauthToken(value);
}
if (key.equals("--username")) {
config = config.withUsername(value);
}
if (key.equals("--password")) {
config = config.withPassword(value);
}
if (key.equals("--namespace")) {
config = config.withNamespace(value);
}
}
return new DefaultIstioClient(config.build());
| 153
| 213
| 366
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/DestinationRuleExample.java
|
DestinationRuleExample
|
createResource
|
class DestinationRuleExample {
private static final String NAMESPACE = "test";
public static void main(String[] args) {
try {
IstioClient client = ClientFactory.newClient(args);
createResource(client);
System.exit(0);
} catch (KubernetesClientException ex) {
System.err.println("Failed with " + ex.getMessage());
System.exit(1);
}
}
public static void createResource(IstioClient client) {<FILL_FUNCTION_BODY>}
}
|
System.out.println("Creating a destination rule");
// Example from: https://istio.io/latest/docs/reference/config/networking/destination-rule/
client.v1beta1().destinationRules().inNamespace(NAMESPACE).create(new DestinationRuleBuilder()
.withNewMetadata()
.withName("reviews-route")
.endMetadata()
.withNewSpec()
.withHost("ratings.prod.svc.cluster.local")
.withNewTrafficPolicy()
.withLoadBalancer(
new LoadBalancerSettingsBuilder().withLbPolicy(new LoadBalancerSettingsSimple(LoadBalancerSettingsSimpleLB.RANDOM))
.build())
.endTrafficPolicy()
.endSpec()
.build());
System.out.println("Listing destination rules instances:");
DestinationRuleList list = client.v1beta1().destinationRules().inNamespace(NAMESPACE).list();
list.getItems().forEach(b -> System.out.println(b.getMetadata().getName()));
System.out.println("Done");
| 142
| 280
| 422
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/GatewayExample.java
|
GatewayExample
|
createResource
|
class GatewayExample {
private static final String NAMESPACE = "test";
public static void main(String[] args) {
try {
IstioClient client = ClientFactory.newClient(args);
createResource(client);
System.exit(0);
} catch (KubernetesClientException ex) {
System.err.println("Failed with " + ex.getMessage());
System.exit(1);
}
}
public static void createResource(IstioClient client) {<FILL_FUNCTION_BODY>}
}
|
System.out.println("Creating a gateway");
// Example from: https://istio.io/latest/docs/reference/config/networking/gateway/
client.v1beta1().gateways().inNamespace(NAMESPACE).create(new GatewayBuilder()
.withNewMetadata()
.withName("my-gateway")
.endMetadata()
.withNewSpec()
.withSelector(Collections.singletonMap("app", "my-gateway-controller"))
.withServers(new ServerBuilder()
.withPort(new PortBuilder().withNumber(80).withProtocol("HTTP").withName("http").build())
.withHosts("uk.bookinfo.com", "eu.bookinfo.com")
.withTls(new ServerTLSSettingsBuilder().withHttpsRedirect(true).build())
.build())
.endSpec()
.build());
System.out.println("Listing gateway instances:");
GatewayList list = client.v1beta1().gateways().inNamespace(NAMESPACE).list();
list.getItems().forEach(b -> System.out.println(b.getMetadata().getName()));
System.out.println("Done");
| 141
| 303
| 444
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/PeerAuthenticationExample.java
|
PeerAuthenticationExample
|
main
|
class PeerAuthenticationExample {
private static final String NAMESPACE = "test";
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
public static void createResource(IstioClient client) {
System.out.println("Creating a PeerAuthentication entry");
client.v1beta1().peerAuthentications().inNamespace(NAMESPACE).create(new PeerAuthenticationBuilder()
.withNewMetadata()
.withName("details-svc")
.endMetadata()
.withNewSpec()
.withSelector(new WorkloadSelectorBuilder().addToMatchLabels("app", "reviews").build())
.withMtls(new PeerAuthenticationMutualTLSBuilder().withMode(PeerAuthenticationMutualTLSMode.DISABLE).build())
.endSpec()
.build());
System.out.println("Listing workload entry instances:");
PeerAuthenticationList list = client.v1beta1().peerAuthentications().inNamespace(NAMESPACE).list();
list.getItems().forEach(b -> System.out.println(b.getMetadata().getName()));
System.out.println("Done");
}
}
|
try {
IstioClient client = ClientFactory.newClient(args);
createResource(client);
System.exit(0);
} catch (KubernetesClientException ex) {
System.err.println("Failed with " + ex.getMessage());
System.exit(1);
}
| 300
| 78
| 378
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/ServiceEntryExample.java
|
ServiceEntryExample
|
createResource
|
class ServiceEntryExample {
private static final String NAMESPACE = "test";
public static void main(String[] args) {
try {
IstioClient client = ClientFactory.newClient(args);
createResource(client);
System.exit(0);
} catch (KubernetesClientException ex) {
System.err.println("Failed with " + ex.getMessage());
System.exit(1);
}
}
public static void createResource(IstioClient client) {<FILL_FUNCTION_BODY>}
}
|
System.out.println("Creating a service entry");
// Example from: https://istio.io/latest/docs/reference/config/networking/service-entry/
client.v1beta1().serviceEntries().inNamespace(NAMESPACE).create(new ServiceEntryBuilder()
.withNewMetadata()
.withName("external-svc-https")
.endMetadata()
.withNewSpec()
.withHosts("api.dropboxapi.com", "www.googleapis.com")
.withLocation(ServiceEntryLocation.MESH_INTERNAL)
.withPorts(new ServicePortBuilder().withName("https").withProtocol("TLS").withNumber(443).build())
.endSpec()
.build());
System.out.println("Listing Virtual Service Instances:");
ServiceEntryList list = client.v1beta1().serviceEntries().inNamespace(NAMESPACE).list();
list.getItems().forEach(b -> System.out.println(b.getMetadata().getName()));
System.out.println("Done");
| 141
| 269
| 410
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/SidecarExample.java
|
SidecarExample
|
createResource
|
class SidecarExample {
private static final String NAMESPACE = "test";
public static void main(String[] args) {
try {
IstioClient client = ClientFactory.newClient(args);
createResource(client);
System.exit(0);
} catch (KubernetesClientException ex) {
System.err.println("Failed with " + ex.getMessage());
System.exit(1);
}
}
public static void createResource(IstioClient client) {<FILL_FUNCTION_BODY>}
}
|
System.out.println("Creating a sidecar");
// Example from: https://istio.io/latest/docs/reference/config/networking/sidecar/
client.v1beta1().sidecars().inNamespace(NAMESPACE).create(new SidecarBuilder()
.withNewMetadata()
.withName("default")
.endMetadata()
.withNewSpec()
.withEgress(new IstioEgressListenerBuilder()
.withHosts("./*", "istio-system/*").build())
.endSpec()
.build());
System.out.println("Listing sidecar instances:");
SidecarList list = client.v1beta1().sidecars().inNamespace(NAMESPACE).list();
list.getItems().forEach(b -> System.out.println(b.getMetadata().getName()));
System.out.println("Done");
| 141
| 224
| 365
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/VirtualServiceExample.java
|
VirtualServiceExample
|
main
|
class VirtualServiceExample {
private static final String NAMESPACE = "test";
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
public static void createResource(IstioClient client) {
System.out.println("Creating a virtual service");
// Example from: https://istio.io/latest/docs/reference/config/networking/virtual-service/
final String reviewsHost = "reviews.prod.svc.cluster.local";
client.v1beta1().virtualServices().inNamespace(NAMESPACE).create(new VirtualServiceBuilder()
.withNewMetadata()
.withName("reviews-route")
.endMetadata()
.withNewSpec()
.addToHosts(reviewsHost)
.addNewHttp()
.withName("reviews-v2-routes")
.addNewMatch().withNewUri().withNewStringMatchPrefixType("/wpcatalog").endUri().endMatch()
.addNewMatch().withNewUri().withNewStringMatchPrefixType("/consumercatalog").endUri().endMatch()
.withNewRewrite().withUri("/newcatalog").endRewrite()
.addNewRoute()
.withNewDestination().withHost(reviewsHost).withSubset("v2").endDestination()
.endRoute()
.endHttp()
.addNewHttp()
.withName("reviews-v2-routes")
.addNewRoute()
.withNewDestination().withHost(reviewsHost).withSubset("v1").endDestination()
.endRoute()
.endHttp()
.endSpec()
.build());
System.out.println("Listing Virtual Service Instances:");
VirtualServiceList list = client.v1beta1().virtualServices().inNamespace(NAMESPACE).list();
list.getItems().forEach(b -> System.out.println(b.getMetadata().getName()));
System.out.println("Done");
}
}
|
try {
IstioClient client = ClientFactory.newClient(args);
createResource(client);
System.exit(0);
} catch (KubernetesClientException ex) {
System.err.println("Failed with " + ex.getMessage());
System.exit(1);
}
| 500
| 78
| 578
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/WorkloadEntryExample.java
|
WorkloadEntryExample
|
createResource
|
class WorkloadEntryExample {
private static final String NAMESPACE = "test";
public static void main(String[] args) {
try {
IstioClient client = ClientFactory.newClient(args);
createResource(client);
System.exit(0);
} catch (KubernetesClientException ex) {
System.err.println("Failed with " + ex.getMessage());
System.exit(1);
}
}
public static void createResource(IstioClient client) {<FILL_FUNCTION_BODY>}
}
|
System.out.println("Creating a workload entry");
// Example from: https://istio.io/latest/docs/reference/config/networking/workload-entry/
client.v1beta1().workloadEntries().inNamespace(NAMESPACE).create(new WorkloadEntryBuilder()
.withNewMetadata()
.withName("details-svc")
.endMetadata()
.withNewSpec()
.withServiceAccount("details-legacy")
.withLabels(Collections.singletonMap("app", "details-legacy"))
.endSpec()
.build());
System.out.println("Listing workload entry instances:");
WorkloadEntryList list = client.v1beta1().workloadEntries().inNamespace(NAMESPACE).list();
list.getItems().forEach(b -> System.out.println(b.getMetadata().getName()));
System.out.println("Done");
| 142
| 234
| 376
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/knative/client/src/main/java/io/fabric8/knative/client/util/ApiVersionUtil.java
|
ApiVersionUtil
|
trimGroupOrNull
|
class ApiVersionUtil {
private ApiVersionUtil() {
throw new IllegalStateException("Utility class");
}
/**
* Extracts apiGroupName from apiGroupVersion when in resource for apiGroupName/apiGroupVersion combination
*
* @param item resource which is being used
* @param apiGroup apiGroupName present if any
* @return Just the apiGroupName part without apiGroupVersion
*/
public static <T> String apiGroup(T item, String apiGroup) {
if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) {
return trimGroupOrNull(((HasMetadata) item).getApiVersion());
} else if (apiGroup != null && !apiGroup.isEmpty()) {
return trimGroup(apiGroup);
}
return null;
}
/**
* Returns the api version falling back to the items apiGroupVersion if not null.
*
* @param <T>
* @param item
* @param apiVersion
* @return
*/
public static <T> String apiVersion(T item, String apiVersion) {
if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) {
return trimVersion(((HasMetadata) item).getApiVersion());
} else if (apiVersion != null && !apiVersion.isEmpty()) {
return trimVersion(apiVersion);
}
return null;
}
/**
* Separates apiGroupVersion for apiGroupName/apiGroupVersion combination.
*
* @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo.
* @return Just the apiGroupVersion part without the apiGroupName.
*/
private static String trimVersion(String apiVersion) {
if (apiVersion != null && apiVersion.contains("/")) {
String[] versionParts = apiVersion.split("/");
return versionParts[versionParts.length - 1];
}
return apiVersion;
}
/**
* Separates apiGroupName for apiGroupName/apiGroupVersion combination.
*
* @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo.
* @return Just the apiGroupName part without the apiGroupName, or apiVersion if no separator is found.
*/
private static String trimGroup(String apiVersion) {
if (apiVersion != null && apiVersion.contains("/")) {
String[] versionParts = apiVersion.split("/");
return versionParts[0];
}
return apiVersion;
}
/**
* Separates apiGroupName for apiGroupName/apiGroupVersion combination.
*
* @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo.
* @return Just the apiGroupName part without the apiGroupName, or null if no separator is found.
*/
private static String trimGroupOrNull(String apiVersion) {<FILL_FUNCTION_BODY>}
}
|
if (apiVersion != null && apiVersion.contains("/")) {
String[] versionParts = apiVersion.split("/");
return versionParts[0];
}
return null;
| 743
| 51
| 794
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/knative/examples/src/main/java/io/fabric8/knative/api/examples/ClientFactory.java
|
ClientFactory
|
getOptions
|
class ClientFactory {
private ClientFactory() {
throw new IllegalStateException("Utility class");
}
public static KnativeClient newClient(String[] args) {
ConfigBuilder config = new ConfigBuilder();
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals("--api-server")) {
config = config.withMasterUrl(value);
}
if (key.equals("--token")) {
config = config.withOauthToken(value);
}
if (key.equals("--username")) {
config = config.withUsername(value);
}
if (key.equals("--password")) {
config = config.withPassword(value);
}
if (key.equals("--namespace")) {
config = config.withNamespace(value);
}
}
return new KubernetesClientBuilder().withConfig(config.build()).build().adapt(KnativeClient.class);
}
public static String getOptions(String[] args, String name, String defaultValue) {<FILL_FUNCTION_BODY>}
}
|
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals(name)) {
return value;
}
}
return defaultValue;
| 305
| 73
| 378
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/open-cluster-management/client/src/main/java/io/fabric8/openclustermanagement/client/OpenClusterManagementExtensionAdapter.java
|
OpenClusterManagementExtensionAdapter
|
registerClients
|
class OpenClusterManagementExtensionAdapter implements ExtensionAdapter<OpenClusterManagementClient> {
@Override
public Class<OpenClusterManagementClient> getExtensionType() {
return OpenClusterManagementClient.class;
}
@Override
public OpenClusterManagementClient adapt(Client client) {
return new DefaultOpenClusterManagementClient(client);
}
@Override
public void registerClients(ClientFactory factory) {<FILL_FUNCTION_BODY>}
}
|
factory.register(OpenClusterManagementAppsAPIGroupDSL.class, new OpenClusterManagementAppsAPIGroupClient());
factory.register(OpenClusterManagementAgentAPIGroupDSL.class, new OpenClusterManagementAgentAPIGroupClient());
factory.register(OpenClusterManagementClustersAPIGroupDSL.class, new OpenClusterManagementClustersAPIGroupClient());
factory.register(OpenClusterManagementDiscoveryAPIGroupDSL.class, new OpenClusterManagementDiscoveryAPIGroupClient());
factory.register(OpenClusterManagementObservabilityAPIGroupDSL.class,
new OpenClusterManagementObservabilityAPIGroupClient());
factory.register(OpenClusterManagementOperatorAPIGroupDSL.class, new OpenClusterManagementOperatorAPIGroupClient());
factory.register(OpenClusterManagementPolicyAPIGroupDSL.class, new OpenClusterManagementPolicyAPIGroupClient());
factory.register(OpenClusterManagementSearchAPIGroupDSL.class, new OpenClusterManagementSearchAPIGroupClient());
| 116
| 239
| 355
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/open-cluster-management/examples/src/main/java/io/fabric8/openclustermanagement/examples/apps/PlacementRuleCreate.java
|
PlacementRuleCreate
|
main
|
class PlacementRuleCreate {
private static final Logger logger = LoggerFactory.getLogger(PlacementRuleCreate.class.getSimpleName());
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try (OpenClusterManagementClient ocmClient = new DefaultOpenClusterManagementClient()) {
PlacementRule placementRule = new PlacementRuleBuilder()
.withNewMetadata().withName("towhichcluster").endMetadata()
.withNewSpec()
.addNewClusterCondition()
.withType("ManagedClusterConditionAvailable")
.withStatus("True")
.endClusterCondition()
.endSpec()
.build();
logger.info("Creating PlacementRule {}", placementRule.getMetadata().getName());
ocmClient.apps().placementRules().inNamespace("default").create(placementRule);
logger.info("Success.");
}
| 61
| 163
| 224
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/open-cluster-management/examples/src/main/java/io/fabric8/openclustermanagement/examples/cluster/ManagedClusterList.java
|
ManagedClusterList
|
main
|
class ManagedClusterList {
private static final Logger logger = LoggerFactory.getLogger(ManagedClusterList.class.getSimpleName());
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try (OpenClusterManagementClient ocmClient = new DefaultOpenClusterManagementClient()) {
logger.info("Listing all ManagedClusters: ");
ocmClient.clusters().managedClusters()
.list().getItems().stream()
.map(ManagedCluster::getMetadata)
.map(ObjectMeta::getName)
.forEach(logger::info);
}
| 61
| 99
| 160
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/open-cluster-management/examples/src/main/java/io/fabric8/openclustermanagement/examples/cluster/ManagedClusterSetCreate.java
|
ManagedClusterSetCreate
|
main
|
class ManagedClusterSetCreate {
private static final Logger logger = LoggerFactory.getLogger(ManagedClusterSetCreate.class.getSimpleName());
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try (OpenClusterManagementClient ocmClient = new DefaultOpenClusterManagementClient()) {
ManagedClusterSet managedClusterSet = new ManagedClusterSetBuilder()
.withNewMetadata().withName("managedclusterset1").endMetadata()
.withNewSpec()
.endSpec()
.build();
logger.info("Creating ManagedClusterSet {}", managedClusterSet.getMetadata().getName());
ocmClient.clusters().managedClusterSets().create(managedClusterSet);
}
| 63
| 129
| 192
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/open-virtual-networking/client/src/main/java/io/fabric8/ovn/client/OpenVirtualNetworkingExtensionAdapter.java
|
OpenVirtualNetworkingExtensionAdapter
|
adapt
|
class OpenVirtualNetworkingExtensionAdapter implements ExtensionAdapter<OpenVirtualNetworkingClient> {
@Override
public Class<OpenVirtualNetworkingClient> getExtensionType() {
return OpenVirtualNetworkingClient.class;
}
@Override
public OpenVirtualNetworkingClient adapt(Client client) {<FILL_FUNCTION_BODY>}
@Override
public void registerClients(ClientFactory factory) {
factory.register(V1OpenVirtualNetworkingAPIGroupDSL.class, new V1OpenVirtualNetworkingAPIGroupClient());
}
}
|
if (client.hasApiGroup("k8s.ovn.org", false)) {
return new DefaultOpenVirtualNetworkingClient(client);
}
return null;
| 141
| 46
| 187
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/ServiceCatalogExtensionAdapter.java
|
ServiceCatalogExtensionAdapter
|
registerResources
|
class ServiceCatalogExtensionAdapter implements ExtensionAdapter<ServiceCatalogClient> {
@Override
public Class<ServiceCatalogClient> getExtensionType() {
return ServiceCatalogClient.class;
}
@Override
public ServiceCatalogClient adapt(Client client) {
return new DefaultServiceCatalogClient(client);
}
@Override
public void registerResources(ResourceFactory factory) {<FILL_FUNCTION_BODY>}
}
|
factory.register(ClusterServiceBroker.class, new ClusterServiceBrokerOperationsImpl());
factory.register(ClusterServiceClass.class, new ClusterServiceClassOperationsImpl());
factory.register(ClusterServicePlan.class, new ClusterServicePlanOperationsImpl());
factory.register(ServiceBinding.class, new ServiceBindingOperationsImpl());
factory.register(ServiceInstance.class, new ServiceInstanceOperationsImpl());
| 114
| 104
| 218
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceBrokerOperationsImpl.java
|
ClusterServiceBrokerOperationsImpl
|
useServiceClass
|
class ClusterServiceBrokerOperationsImpl extends ExtensibleResourceAdapter<ClusterServiceBroker>
implements ClusterServiceBrokerResource {
@Override
public ExtensibleResourceAdapter<ClusterServiceBroker> newInstance() {
return new ClusterServiceBrokerOperationsImpl();
}
@Override
public ClusterServicePlanList listPlans() {
ClusterServiceBroker item = get();
return client.adapt(ServiceCatalogClient.class).clusterServicePlans()
.withField("spec.clusterServiceBrokerName", item.getMetadata().getName())
.list();
}
@Override
public ClusterServiceClassList listClasses() {
ClusterServiceBroker item = get();
return client.adapt(ServiceCatalogClient.class).clusterServiceClasses()
.withField("spec.clusterServiceBrokerName", item.getMetadata().getName())
.list();
}
@Override
public ClusterServiceClassResource useServiceClass(String externalName) {<FILL_FUNCTION_BODY>}
}
|
ClusterServiceBroker item = get();
Map<String, String> fields = new HashMap<>();
fields.put("spec.clusterServiceBrokerName", item.getMetadata().getName());
if (externalName != null) {
fields.put("spec.externalName", externalName);
}
List<ClusterServiceClass> list = client.adapt(ServiceCatalogClient.class).clusterServiceClasses().withFields(fields).list()
.getItems();
if (list.size() != 1) {
throw new IllegalArgumentException("No unique ClusterServiceClass with external name:" + externalName
+ "found for ClusterServiceBroker: " + item.getMetadata().getName());
}
ClusterServiceClass c = list.get(0);
return client.adapt(ServiceCatalogClient.class).clusterServiceClasses().resource(c);
| 260
| 211
| 471
|
<methods>public void <init>() ,public ExtensibleResource<ClusterServiceBroker> dryRun(boolean) ,public ExtensibleResource<ClusterServiceBroker> fieldManager(java.lang.String) ,public ExtensibleResource<ClusterServiceBroker> fieldValidation(io.fabric8.kubernetes.client.dsl.FieldValidateable.Validation) ,public ExtensibleResource<ClusterServiceBroker> forceConflicts() ,public ExtensibleResource<ClusterServiceBroker> fromServer() ,public ClusterServiceBroker getItem() ,public C inWriteContext(Class<C>) ,public ExtensibleResourceAdapter<ClusterServiceBroker> init(ExtensibleResource<ClusterServiceBroker>, io.fabric8.kubernetes.client.Client) ,public ExtensibleResource<ClusterServiceBroker> lockResourceVersion(java.lang.String) ,public ExtensibleResource<ClusterServiceBroker> lockResourceVersion() ,public abstract ExtensibleResourceAdapter<ClusterServiceBroker> newInstance() ,public ExtensibleResource<ClusterServiceBroker> subresource(java.lang.String) ,public ExtensibleResource<ClusterServiceBroker> unlock() ,public ExtensibleResource<ClusterServiceBroker> withGracePeriod(long) ,public ExtensibleResource<ClusterServiceBroker> withIndexers(Map<java.lang.String,Function<ClusterServiceBroker,List<java.lang.String>>>) ,public ExtensibleResource<ClusterServiceBroker> withLimit(java.lang.Long) ,public ExtensibleResource<ClusterServiceBroker> withPropagationPolicy(io.fabric8.kubernetes.api.model.DeletionPropagation) ,public ExtensibleResource<ClusterServiceBroker> withResourceVersion(java.lang.String) ,public ExtensibleResource<ClusterServiceBroker> withTimeout(long, java.util.concurrent.TimeUnit) ,public ExtensibleResource<ClusterServiceBroker> withTimeoutInMillis(long) <variables>protected io.fabric8.kubernetes.client.Client client,protected ExtensibleResource<ClusterServiceBroker> resource
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceClassOperationsImpl.java
|
ClusterServiceClassOperationsImpl
|
usePlan
|
class ClusterServiceClassOperationsImpl extends ExtensibleResourceAdapter<ClusterServiceClass>
implements ClusterServiceClassResource {
@Override
public ExtensibleResourceAdapter<ClusterServiceClass> newInstance() {
return new ClusterServiceClassOperationsImpl();
}
@Override
public ClusterServicePlanList listPlans() {
ClusterServiceClass item = get();
return client.adapt(ServiceCatalogClient.class)
.clusterServicePlans()
.withField("spec.clusterServiceClassRef.name", item != null ? item.getMetadata().getName() : null)
.list();
}
@Override
public ClusterServicePlanResource usePlan(String externalName) {<FILL_FUNCTION_BODY>}
@Override
public ServiceInstance instantiate(String instanceName, String plan) {
ClusterServiceClass item = get();
return client.adapt(ServiceCatalogClient.class)
.serviceInstances()
.create(new ServiceInstanceBuilder()
.withNewMetadata()
.withName(instanceName)
.endMetadata()
.withNewSpec()
.withClusterServiceClassExternalName(item.getMetadata().getName())
.withClusterServicePlanExternalName(plan)
.endSpec()
.build());
}
}
|
ClusterServiceClass item = get();
Map<String, String> fields = new HashMap<>();
fields.put("spec.clusterServiceClassRef.name", item.getMetadata().getName());
fields.put("spec.externalName", externalName);
List<ClusterServicePlan> list = client.adapt(ServiceCatalogClient.class)
.clusterServicePlans()
.withFields(fields)
.list()
.getItems();
if (list.size() != 1) {
throw new IllegalArgumentException("No unique ClusterServicePlan with external name: " + externalName
+ " found for ClusterServiceBroker: " + item.getSpec().getClusterServiceBrokerName()
+ " and ClusterServiceClass: " + item.getSpec().getExternalName() + ".");
}
ClusterServicePlan plan = list.get(0);
return client.adapt(ServiceCatalogClient.class).clusterServicePlans().resource(plan);
| 324
| 238
| 562
|
<methods>public void <init>() ,public ExtensibleResource<ClusterServiceClass> dryRun(boolean) ,public ExtensibleResource<ClusterServiceClass> fieldManager(java.lang.String) ,public ExtensibleResource<ClusterServiceClass> fieldValidation(io.fabric8.kubernetes.client.dsl.FieldValidateable.Validation) ,public ExtensibleResource<ClusterServiceClass> forceConflicts() ,public ExtensibleResource<ClusterServiceClass> fromServer() ,public ClusterServiceClass getItem() ,public C inWriteContext(Class<C>) ,public ExtensibleResourceAdapter<ClusterServiceClass> init(ExtensibleResource<ClusterServiceClass>, io.fabric8.kubernetes.client.Client) ,public ExtensibleResource<ClusterServiceClass> lockResourceVersion(java.lang.String) ,public ExtensibleResource<ClusterServiceClass> lockResourceVersion() ,public abstract ExtensibleResourceAdapter<ClusterServiceClass> newInstance() ,public ExtensibleResource<ClusterServiceClass> subresource(java.lang.String) ,public ExtensibleResource<ClusterServiceClass> unlock() ,public ExtensibleResource<ClusterServiceClass> withGracePeriod(long) ,public ExtensibleResource<ClusterServiceClass> withIndexers(Map<java.lang.String,Function<ClusterServiceClass,List<java.lang.String>>>) ,public ExtensibleResource<ClusterServiceClass> withLimit(java.lang.Long) ,public ExtensibleResource<ClusterServiceClass> withPropagationPolicy(io.fabric8.kubernetes.api.model.DeletionPropagation) ,public ExtensibleResource<ClusterServiceClass> withResourceVersion(java.lang.String) ,public ExtensibleResource<ClusterServiceClass> withTimeout(long, java.util.concurrent.TimeUnit) ,public ExtensibleResource<ClusterServiceClass> withTimeoutInMillis(long) <variables>protected io.fabric8.kubernetes.client.Client client,protected ExtensibleResource<ClusterServiceClass> resource
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServicePlanOperationsImpl.java
|
ClusterServicePlanOperationsImpl
|
instantiate
|
class ClusterServicePlanOperationsImpl extends ExtensibleResourceAdapter<ClusterServicePlan>
implements ClusterServicePlanResource {
@Override
public ExtensibleResourceAdapter<ClusterServicePlan> newInstance() {
return new ClusterServicePlanOperationsImpl();
}
@Override
public ServiceInstance instantiate(String... args) {<FILL_FUNCTION_BODY>}
@Override
public ServiceInstanceResource instantiateAnd(String... args) {
ServiceInstance item = instantiate(args);
return client.adapt(ServiceCatalogClient.class).serviceInstances().resource(item);
}
}
|
String instanceName;
String instanceNamespace;
if (args.length == 1) {
instanceName = args[0];
instanceNamespace = client.getConfiguration().getNamespace();
} else if (args.length == 2) {
instanceNamespace = args[0];
instanceName = args[1];
} else {
throw new IllegalArgumentException(
"Instantiate needs to be called with either <namespace> <instance name> or <instance name> arguments, but instead found: "
+ args.length + " arguments.");
}
ClusterServicePlan item = get();
return client.adapt(ServiceCatalogClient.class).serviceInstances()
.inNamespace(instanceNamespace).create(new ServiceInstanceBuilder()
.withNewMetadata()
.withName(instanceName)
.withNamespace(instanceNamespace)
.endMetadata()
.withNewSpec()
.withClusterServiceClassName(item.getSpec().getClusterServiceClassRef().getName())
.withClusterServicePlanName(item.getMetadata().getName())
.endSpec()
.build());
| 155
| 267
| 422
|
<methods>public void <init>() ,public ExtensibleResource<ClusterServicePlan> dryRun(boolean) ,public ExtensibleResource<ClusterServicePlan> fieldManager(java.lang.String) ,public ExtensibleResource<ClusterServicePlan> fieldValidation(io.fabric8.kubernetes.client.dsl.FieldValidateable.Validation) ,public ExtensibleResource<ClusterServicePlan> forceConflicts() ,public ExtensibleResource<ClusterServicePlan> fromServer() ,public ClusterServicePlan getItem() ,public C inWriteContext(Class<C>) ,public ExtensibleResourceAdapter<ClusterServicePlan> init(ExtensibleResource<ClusterServicePlan>, io.fabric8.kubernetes.client.Client) ,public ExtensibleResource<ClusterServicePlan> lockResourceVersion(java.lang.String) ,public ExtensibleResource<ClusterServicePlan> lockResourceVersion() ,public abstract ExtensibleResourceAdapter<ClusterServicePlan> newInstance() ,public ExtensibleResource<ClusterServicePlan> subresource(java.lang.String) ,public ExtensibleResource<ClusterServicePlan> unlock() ,public ExtensibleResource<ClusterServicePlan> withGracePeriod(long) ,public ExtensibleResource<ClusterServicePlan> withIndexers(Map<java.lang.String,Function<ClusterServicePlan,List<java.lang.String>>>) ,public ExtensibleResource<ClusterServicePlan> withLimit(java.lang.Long) ,public ExtensibleResource<ClusterServicePlan> withPropagationPolicy(io.fabric8.kubernetes.api.model.DeletionPropagation) ,public ExtensibleResource<ClusterServicePlan> withResourceVersion(java.lang.String) ,public ExtensibleResource<ClusterServicePlan> withTimeout(long, java.util.concurrent.TimeUnit) ,public ExtensibleResource<ClusterServicePlan> withTimeoutInMillis(long) <variables>protected io.fabric8.kubernetes.client.Client client,protected ExtensibleResource<ClusterServicePlan> resource
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ServiceInstanceOperationsImpl.java
|
ServiceInstanceOperationsImpl
|
bind
|
class ServiceInstanceOperationsImpl extends ExtensibleResourceAdapter<ServiceInstance>
implements ServiceInstanceResource {
@Override
public ExtensibleResourceAdapter<ServiceInstance> newInstance() {
return new ServiceInstanceOperationsImpl();
}
@Override
public ServiceBinding bind(String secretName) {<FILL_FUNCTION_BODY>}
}
|
ServiceInstance item = get();
return client.adapt(ServiceCatalogClient.class)
.serviceBindings().create(new ServiceBindingBuilder()
.withNewMetadata()
.withName(item.getMetadata().getName())
.withNamespace(item.getMetadata().getNamespace())
.endMetadata()
.withNewSpec()
.withSecretName(secretName)
.withNewInstanceRef(item.getMetadata().getName())
.endSpec()
.build());
| 90
| 122
| 212
|
<methods>public void <init>() ,public ExtensibleResource<ServiceInstance> dryRun(boolean) ,public ExtensibleResource<ServiceInstance> fieldManager(java.lang.String) ,public ExtensibleResource<ServiceInstance> fieldValidation(io.fabric8.kubernetes.client.dsl.FieldValidateable.Validation) ,public ExtensibleResource<ServiceInstance> forceConflicts() ,public ExtensibleResource<ServiceInstance> fromServer() ,public ServiceInstance getItem() ,public C inWriteContext(Class<C>) ,public ExtensibleResourceAdapter<ServiceInstance> init(ExtensibleResource<ServiceInstance>, io.fabric8.kubernetes.client.Client) ,public ExtensibleResource<ServiceInstance> lockResourceVersion(java.lang.String) ,public ExtensibleResource<ServiceInstance> lockResourceVersion() ,public abstract ExtensibleResourceAdapter<ServiceInstance> newInstance() ,public ExtensibleResource<ServiceInstance> subresource(java.lang.String) ,public ExtensibleResource<ServiceInstance> unlock() ,public ExtensibleResource<ServiceInstance> withGracePeriod(long) ,public ExtensibleResource<ServiceInstance> withIndexers(Map<java.lang.String,Function<ServiceInstance,List<java.lang.String>>>) ,public ExtensibleResource<ServiceInstance> withLimit(java.lang.Long) ,public ExtensibleResource<ServiceInstance> withPropagationPolicy(io.fabric8.kubernetes.api.model.DeletionPropagation) ,public ExtensibleResource<ServiceInstance> withResourceVersion(java.lang.String) ,public ExtensibleResource<ServiceInstance> withTimeout(long, java.util.concurrent.TimeUnit) ,public ExtensibleResource<ServiceInstance> withTimeoutInMillis(long) <variables>protected io.fabric8.kubernetes.client.Client client,protected ExtensibleResource<ServiceInstance> resource
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/util/ApiVersionUtil.java
|
ApiVersionUtil
|
trimGroup
|
class ApiVersionUtil {
private ApiVersionUtil() {
throw new IllegalStateException("Utility class");
}
/**
* Extracts apiGroupName from apiGroupVersion when in resource for apiGroupName/apiGroupVersion combination
*
* @param item resource which is being used
* @param apiGroup apiGroupName present if any
* @return Just the apiGroupName part without apiGroupVersion
*/
public static <T> String apiGroup(T item, String apiGroup) {
if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) {
return trimGroupOrNull(((HasMetadata) item).getApiVersion());
} else if (apiGroup != null && !apiGroup.isEmpty()) {
return trimGroup(apiGroup);
}
return null;
}
/**
* Returns the api version falling back to the items apiGroupVersion if not null.
*
* @param <T>
* @param item
* @param apiVersion
* @return
*/
public static <T> String apiVersion(T item, String apiVersion) {
if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) {
return trimVersion(((HasMetadata) item).getApiVersion());
} else if (apiVersion != null && !apiVersion.isEmpty()) {
return trimVersion(apiVersion);
}
return null;
}
/**
* Separates apiGroupVersion for apiGroupName/apiGroupVersion combination.
*
* @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo.
* @return Just the apiGroupVersion part without the apiGroupName.
*/
private static String trimVersion(String apiVersion) {
if (apiVersion != null && apiVersion.contains("/")) {
String[] versionParts = apiVersion.split("/");
return versionParts[versionParts.length - 1];
}
return apiVersion;
}
/**
* Separates apiGroupName for apiGroupName/apiGroupVersion combination.
*
* @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo.
* @return Just the apiGroupName part without the apiGroupName, or apiVersion if no separator is found.
*/
private static String trimGroup(String apiVersion) {<FILL_FUNCTION_BODY>}
/**
* Separates apiGroupName for apiGroupName/apiGroupVersion combination.
*
* @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo.
* @return Just the apiGroupName part without the apiGroupName, or null if no separator is found.
*/
private static String trimGroupOrNull(String apiVersion) {
if (apiVersion != null && apiVersion.contains("/")) {
String[] versionParts = apiVersion.split("/");
return versionParts[0];
}
return null;
}
}
|
if (apiVersion != null && apiVersion.contains("/")) {
String[] versionParts = apiVersion.split("/");
return versionParts[0];
}
return apiVersion;
| 742
| 52
| 794
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/ClientFactory.java
|
ClientFactory
|
newClient
|
class ClientFactory {
private ClientFactory() {
throw new IllegalStateException("Utility class");
}
public static ServiceCatalogClient newClient(String[] args) {<FILL_FUNCTION_BODY>}
public static String getOptions(String[] args, String name, String defaultValue) {
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals(name)) {
return value;
}
}
return defaultValue;
}
}
|
ConfigBuilder config = new ConfigBuilder();
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals("--api-server")) {
config = config.withMasterUrl(value);
}
if (key.equals("--token")) {
config = config.withOauthToken(value);
}
if (key.equals("--username")) {
config = config.withUsername(value);
}
if (key.equals("--password")) {
config = config.withPassword(value);
}
if (key.equals("--namespace")) {
config = config.withNamespace(value);
}
}
return new KubernetesClientBuilder().withConfig(config.build()).build().adapt(ServiceCatalogClient.class);
| 153
| 227
| 380
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/CreateBinding.java
|
CreateBinding
|
main
|
class CreateBinding {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ServiceCatalogClient client = ClientFactory.newClient(args);
System.out.println("Creating a service binding");
client.serviceBindings().inNamespace("iocanel").create(new ServiceBindingBuilder()
.withNewMetadata()
.withName("mybinding")
.endMetadata()
.withNewSpec()
.withNewInstanceRef("myservice")
.withSecretName("mysercret")
.endSpec().build());
| 32
| 116
| 148
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/CreateBroker.java
|
CreateBroker
|
main
|
class CreateBroker {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ServiceCatalogClient client = ClientFactory.newClient(args);
ClusterServiceBroker broker = client.clusterServiceBrokers().create(new ClusterServiceBrokerBuilder()
.withNewMetadata()
.withName("mybroker")
.endMetadata()
.withNewSpec()
.withUrl("http://url.to.service.broker")
.endSpec()
.build());
| 33
| 103
| 136
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/ListBrokers.java
|
ListBrokers
|
main
|
class ListBrokers {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ServiceCatalogClient client = ClientFactory.newClient(args);
ClusterServiceBrokerList list = client.clusterServiceBrokers().list();
System.out.println("Listing Cluster Service Brokers:");
list.getItems().stream()
.map(b -> b.getMetadata().getName())
.forEach(System.out::println);
System.out.println("Done");
| 33
| 100
| 133
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/ListServiceClasses.java
|
ListServiceClasses
|
main
|
class ListServiceClasses {
private static final Logger logger = LoggerFactory.getLogger(ListServiceClasses.class.getSimpleName());
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ServiceCatalogClient client = ClientFactory.newClient(args);
logger.info("Listing Cluster Service Classes:");
ClusterServiceClassList list = client.clusterServiceClasses().list();
list.getItems()
.forEach(b -> logger.info(b.getSpec().getClusterServiceBrokerName() + "\t\t" + b.getSpec().getExternalName()
+ "\t\t\t\t" + b.getMetadata().getName()));
logger.info("Done");
| 59
| 125
| 184
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/ListServiceClassesByBroker.java
|
ListServiceClassesByBroker
|
main
|
class ListServiceClassesByBroker {
private static final Logger logger = LoggerFactory.getLogger(ListServiceClassesByBroker.class.getSimpleName());
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ServiceCatalogClient client = ClientFactory.newClient(args);
String broker = ClientFactory.getOptions(args, "--broker", null);
if (broker == null || broker.isEmpty()) {
logger.info("Missing --broker option!");
System.exit(1);
}
logger.info("Listing Cluster Service Classes {} :", broker);
ClusterServiceClassList list = client.clusterServiceBrokers().withName(broker).listClasses();
list.getItems()
.forEach(b -> logger.info(b.getSpec().getExternalName() + "\t\t\t\t" + b.getMetadata().getName()));
logger.info("Done");
| 65
| 173
| 238
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/ListServiceInstances.java
|
ListServiceInstances
|
main
|
class ListServiceInstances {
private static final Logger logger = LoggerFactory.getLogger(ListServiceInstances.class.getSimpleName());
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ServiceCatalogClient client = ClientFactory.newClient(args);
ServiceInstanceList list = client.serviceInstances().inNamespace("iocanel").list();
logger.info("Listing Service Instances:");
list.getItems()
.forEach(b -> logger.info(b.getMetadata().getName()));
logger.info("Done");
| 61
| 91
| 152
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/ListServicePlans.java
|
ListServicePlans
|
main
|
class ListServicePlans {
private static final Logger logger = LoggerFactory.getLogger(ListServicePlans.class.getSimpleName());
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ServiceCatalogClient client = ClientFactory.newClient(args);
ClusterServicePlanList list = client.clusterServicePlans().list();
ClusterServicePlan c;
logger.info("Listing Cluster Service Plans:");
list.getItems()
.forEach(b -> logger.info(b.getSpec().getClusterServiceBrokerName() + "\t\t\t" + b.getSpec().getClusterServiceClassRef()
+ "\t\t\t" + b.getSpec().getExternalName()));
logger.info("Done");
| 61
| 139
| 200
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/ListServicePlansByBroker.java
|
ListServicePlansByBroker
|
main
|
class ListServicePlansByBroker {
private static final Logger logger = LoggerFactory.getLogger(ListServicePlansByBroker.class.getSimpleName());
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ServiceCatalogClient client = ClientFactory.newClient(args);
String broker = ClientFactory.getOptions(args, "--broker", null);
if (broker == null || broker.isEmpty()) {
logger.info("Missing --broker option!");
System.exit(1);
}
logger.info("Listing Cluster Service Plans {} :", broker);
ClusterServicePlanList list = client.clusterServiceBrokers().withName(broker).listPlans();
list.getItems()
.forEach(b -> logger.info(b.getSpec().getClusterServiceClassRef() + "\t\t\t" + b.getSpec().getExternalName()
+ "\t\t\t\t" + b.getMetadata().getName()));
logger.info("Done");
| 67
| 197
| 264
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/service-catalog/examples/src/main/java/io/fabric8/servicecatalog/examples/ProvisionService.java
|
ProvisionService
|
main
|
class ProvisionService {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ServiceCatalogClient client = ClientFactory.newClient(args);
System.out.println("Provisioning a service");
ServiceInstance instance = client.serviceInstances().inNamespace("iocanel").create(new ServiceInstanceBuilder()
.withNewMetadata()
.withName("myserivce")
.endMetadata()
.withNewSpec()
.withClusterServiceClassExternalName("jenkins-ephemeral")
.withClusterServicePlanExternalName("default")
.endSpec()
.build());
System.out.println("Done");
| 33
| 143
| 176
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/TektonExtensionAdapter.java
|
TektonExtensionAdapter
|
registerClients
|
class TektonExtensionAdapter implements ExtensionAdapter<TektonClient> {
@Override
public Class<TektonClient> getExtensionType() {
return TektonClient.class;
}
@Override
public TektonClient adapt(Client client) {
return new DefaultTektonClient(client);
}
@Override
public void registerClients(ClientFactory factory) {<FILL_FUNCTION_BODY>}
}
|
factory.register(V1APIGroupDSL.class, new V1APIGroupClient());
factory.register(V1beta1APIGroupDSL.class, new V1beta1APIGroupClient());
factory.register(V1alpha1APIGroupDSL.class, new V1alpha1APIGroupClient());
| 117
| 83
| 200
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/util/ApiVersionUtil.java
|
ApiVersionUtil
|
trimGroupOrNull
|
class ApiVersionUtil {
private ApiVersionUtil() {
throw new IllegalStateException("Utility class");
}
/**
* Extracts apiGroupName from apiGroupVersion when in resource for apiGroupName/apiGroupVersion combination
*
* @param item resource which is being used
* @param apiGroup apiGroupName present if any
* @return Just the apiGroupName part without apiGroupVersion
*/
public static <T> String apiGroup(T item, String apiGroup) {
if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) {
return trimGroupOrNull(((HasMetadata) item).getApiVersion());
} else if (apiGroup != null && !apiGroup.isEmpty()) {
return trimGroup(apiGroup);
}
return null;
}
/**
* Returns the api version falling back to the items apiGroupVersion if not null.
*
* @param <T>
* @param item
* @param apiVersion
* @return
*/
public static <T> String apiVersion(T item, String apiVersion) {
if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) {
return trimVersion(((HasMetadata) item).getApiVersion());
} else if (apiVersion != null && !apiVersion.isEmpty()) {
return trimVersion(apiVersion);
}
return null;
}
/**
* Separates apiGroupVersion for apiGroupName/apiGroupVersion combination.
*
* @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo.
* @return Just the apiGroupVersion part without the apiGroupName.
*/
private static String trimVersion(String apiVersion) {
if (apiVersion != null && apiVersion.contains("/")) {
String[] versionParts = apiVersion.split("/");
return versionParts[versionParts.length - 1];
}
return apiVersion;
}
/**
* Separates apiGroupName for apiGroupName/apiGroupVersion combination.
*
* @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo.
* @return Just the apiGroupName part without the apiGroupName, or apiVersion if no separator is found.
*/
private static String trimGroup(String apiVersion) {
if (apiVersion != null && apiVersion.contains("/")) {
String[] versionParts = apiVersion.split("/");
return versionParts[0];
}
return apiVersion;
}
/**
* Separates apiGroupName for apiGroupName/apiGroupVersion combination.
*
* @param apiVersion The apiGroupVersion or apiGroupName/apiGroupVersion combo.
* @return Just the apiGroupName part without the apiGroupName, or null if no separator is found.
*/
private static String trimGroupOrNull(String apiVersion) {<FILL_FUNCTION_BODY>}
}
|
if (apiVersion != null && apiVersion.contains("/")) {
String[] versionParts = apiVersion.split("/");
return versionParts[0];
}
return null;
| 743
| 51
| 794
|
<no_super_class>
|
fabric8io_kubernetes-client
|
kubernetes-client/extensions/tekton/examples/src/main/java/io/fabric8/tekton/api/examples/ClientFactory.java
|
ClientFactory
|
newClient
|
class ClientFactory {
private ClientFactory() {
throw new IllegalStateException("Utility class");
}
public static TektonClient newClient(String[] args) {<FILL_FUNCTION_BODY>}
public static String getOptions(String[] args, String name, String defaultValue) {
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals(name)) {
return value;
}
}
return defaultValue;
}
}
|
ConfigBuilder config = new ConfigBuilder();
for (int i = 0; i < args.length - 1; i++) {
String key = args[i];
String value = args[i + 1];
if (key.equals("--api-server")) {
config = config.withMasterUrl(value);
}
if (key.equals("--token")) {
config = config.withOauthToken(value);
}
if (key.equals("--username")) {
config = config.withUsername(value);
}
if (key.equals("--password")) {
config = config.withPassword(value);
}
if (key.equals("--namespace")) {
config = config.withNamespace(value);
}
}
return new DefaultTektonClient(config.build());
| 153
| 213
| 366
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.