or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

api-groups.mdclient-configuration.mdcore-resources.mdcustom-resources.mdexception-handling.mdindex.mdpod-operations.mdutilities.mdwatch-informers.md

utilities.mddocs/

0

# Utilities

1

2

The Fabric8 Kubernetes Client provides various utility classes and methods for serialization, resource manipulation, and common operations. These utilities simplify working with Kubernetes resources and client functionality.

3

4

## Serialization Utilities

5

6

### KubernetesSerialization Class

7

8

Utilities for serializing and deserializing Kubernetes resources.

9

10

```java { .api }

11

public class KubernetesSerialization {

12

// ObjectMapper access

13

public ObjectMapper jsonMapper();

14

public ObjectMapper yamlMapper();

15

16

// Unmarshaling (deserialization)

17

public <T> T unmarshal(String str);

18

public <T> T unmarshal(String str, Class<T> type);

19

public <T> T unmarshal(String str, TypeReference<T> type);

20

public <T> T unmarshal(InputStream is);

21

public <T> T unmarshal(InputStream is, Class<T> type);

22

public <T> T unmarshal(InputStream is, TypeReference<T> type);

23

24

// Marshaling (serialization)

25

public String asJson(Object object);

26

public String asYaml(Object object);

27

public void marshal(Object object, OutputStream os);

28

29

// Clone operations

30

public <T> T clone(T object);

31

32

// Conversion

33

public <T> T convertValue(Object fromValue, Class<T> toValueType);

34

public <T> T convertValue(Object fromValue, TypeReference<T> toValueType);

35

}

36

37

// Access via client

38

public interface KubernetesClient {

39

KubernetesSerialization getKubernetesSerialization();

40

}

41

```

42

43

## Resource Utilities

44

45

### KubernetesResourceUtil Class

46

47

Utilities for working with Kubernetes resources.

48

49

```java { .api }

50

public class KubernetesResourceUtil {

51

// Resource identification

52

public static String getName(HasMetadata resource);

53

public static String getNamespace(HasMetadata resource);

54

public static String getResourceVersion(HasMetadata resource);

55

public static String getUid(HasMetadata resource);

56

public static String getKind(HasMetadata resource);

57

public static String getApiVersion(HasMetadata resource);

58

59

// Resource status

60

public static boolean isResourceReady(HasMetadata resource);

61

public static String getResourceStatus(HasMetadata resource);

62

63

// Owner references

64

public static String getControllerUid(HasMetadata resource);

65

public static List<OwnerReference> getOwnerReferences(HasMetadata resource);

66

public static boolean isOwnedBy(HasMetadata resource, HasMetadata owner);

67

68

// Labels and annotations

69

public static Map<String, String> getLabels(HasMetadata resource);

70

public static Map<String, String> getAnnotations(HasMetadata resource);

71

public static String getLabel(HasMetadata resource, String key);

72

public static String getAnnotation(HasMetadata resource, String key);

73

74

// Utility methods

75

public static boolean isNamespaced(HasMetadata resource);

76

public static String getFullResourceName(HasMetadata resource);

77

public static boolean hasOwnerReference(HasMetadata resource);

78

}

79

```

80

81

### Utils Class

82

83

General utility methods for the client.

84

85

```java { .api }

86

public class Utils {

87

// String utilities

88

public static boolean isNullOrEmpty(String str);

89

public static boolean isNotNullOrEmpty(String str);

90

public static String join(Collection<String> list, String separator);

91

public static String join(String[] array, String separator);

92

93

// Resource waiting

94

public static boolean waitUntilReady(HasMetadata resource, long amount, TimeUnit timeUnit);

95

public static boolean isResourceInFinalState(HasMetadata resource);

96

97

// System utilities

98

public static String getSystemPropertyOrEnvVar(String systemPropertyKey, String envVarKey);

99

public static String getSystemPropertyOrEnvVar(String key);

100

101

// Validation

102

public static void checkNotNull(Object reference, String errorMessage);

103

public static void checkArgument(boolean expression, String errorMessage);

104

105

// File utilities

106

public static String readFile(String path);

107

public static Properties loadProperties(String path);

108

}

109

```

110

111

## Usage Examples

112

113

### JSON and YAML Serialization

114

115

```java

116

KubernetesSerialization serialization = client.getKubernetesSerialization();

117

118

// Create a pod

119

Pod pod = new PodBuilder()

120

.withNewMetadata()

121

.withName("example-pod")

122

.withLabels(Map.of("app", "example"))

123

.endMetadata()

124

.withNewSpec()

125

.addNewContainer()

126

.withName("app")

127

.withImage("nginx:latest")

128

.endContainer()

129

.endSpec()

130

.build();

131

132

// Serialize to JSON

133

String jsonString = serialization.asJson(pod);

134

System.out.println("Pod as JSON:\n" + jsonString);

135

136

// Serialize to YAML

137

String yamlString = serialization.asYaml(pod);

138

System.out.println("Pod as YAML:\n" + yamlString);

139

140

// Write to file

141

try (FileOutputStream fos = new FileOutputStream("pod.yaml")) {

142

serialization.marshal(pod, fos);

143

}

144

```

145

146

### Deserializing Resources

147

148

```java

149

KubernetesSerialization serialization = client.getKubernetesSerialization();

150

151

// Deserialize from JSON string

152

String jsonPod = "{ \"apiVersion\": \"v1\", \"kind\": \"Pod\", ... }";

153

Pod podFromJson = serialization.unmarshal(jsonPod, Pod.class);

154

155

// Deserialize from YAML string

156

String yamlPod = """

157

apiVersion: v1

158

kind: Pod

159

metadata:

160

name: yaml-pod

161

spec:

162

containers:

163

- name: app

164

image: nginx:latest

165

""";

166

Pod podFromYaml = serialization.unmarshal(yamlPod, Pod.class);

167

168

// Deserialize from file

169

try (FileInputStream fis = new FileInputStream("pod.yaml")) {

170

Pod podFromFile = serialization.unmarshal(fis, Pod.class);

171

System.out.println("Loaded pod: " + podFromFile.getMetadata().getName());

172

}

173

174

// Generic deserialization (auto-detect type)

175

HasMetadata genericResource = serialization.unmarshal(yamlPod);

176

System.out.println("Resource type: " + genericResource.getKind());

177

178

// Deserialize list of resources

179

String yamlList = """

180

apiVersion: v1

181

kind: List

182

items:

183

- apiVersion: v1

184

kind: Pod

185

metadata:

186

name: pod1

187

- apiVersion: v1

188

kind: Service

189

metadata:

190

name: service1

191

""";

192

193

KubernetesList resourceList = serialization.unmarshal(yamlList, KubernetesList.class);

194

for (HasMetadata item : resourceList.getItems()) {

195

System.out.println("Item: " + item.getKind() + "/" + item.getMetadata().getName());

196

}

197

```

198

199

### Resource Manipulation Utilities

200

201

```java

202

// Get resource information

203

Pod pod = client.pods().withName("my-pod").get();

204

205

if (pod != null) {

206

// Basic information

207

String name = KubernetesResourceUtil.getName(pod);

208

String namespace = KubernetesResourceUtil.getNamespace(pod);

209

String uid = KubernetesResourceUtil.getUid(pod);

210

String resourceVersion = KubernetesResourceUtil.getResourceVersion(pod);

211

212

System.out.println("Pod: " + name + " in namespace: " + namespace);

213

System.out.println("UID: " + uid);

214

System.out.println("Resource Version: " + resourceVersion);

215

216

// Check if ready

217

boolean isReady = KubernetesResourceUtil.isResourceReady(pod);

218

System.out.println("Pod ready: " + isReady);

219

220

// Get full resource name

221

String fullName = KubernetesResourceUtil.getFullResourceName(pod);

222

System.out.println("Full name: " + fullName); // namespace/name

223

224

// Labels and annotations

225

Map<String, String> labels = KubernetesResourceUtil.getLabels(pod);

226

Map<String, String> annotations = KubernetesResourceUtil.getAnnotations(pod);

227

228

System.out.println("Labels: " + labels);

229

System.out.println("Annotations: " + annotations);

230

231

// Specific label/annotation

232

String appLabel = KubernetesResourceUtil.getLabel(pod, "app");

233

String createdByAnnotation = KubernetesResourceUtil.getAnnotation(pod, "created-by");

234

235

// Owner references

236

List<OwnerReference> owners = KubernetesResourceUtil.getOwnerReferences(pod);

237

if (!owners.isEmpty()) {

238

for (OwnerReference owner : owners) {

239

System.out.println("Owned by: " + owner.getKind() + "/" + owner.getName());

240

}

241

242

String controllerUid = KubernetesResourceUtil.getControllerUid(pod);

243

System.out.println("Controller UID: " + controllerUid);

244

}

245

}

246

```

247

248

### Resource Cloning and Conversion

249

250

```java

251

KubernetesSerialization serialization = client.getKubernetesSerialization();

252

253

// Clone a resource

254

Pod originalPod = client.pods().withName("original-pod").get();

255

Pod clonedPod = serialization.clone(originalPod);

256

257

// Modify the clone

258

clonedPod.getMetadata().setName("cloned-pod");

259

clonedPod.getMetadata().setResourceVersion(null); // Clear resource version

260

clonedPod.getMetadata().setUid(null); // Clear UID

261

262

// Create the cloned resource

263

Pod createdClone = client.pods().create(clonedPod);

264

265

// Convert between resource types (if compatible)

266

GenericKubernetesResource generic = serialization.convertValue(originalPod, GenericKubernetesResource.class);

267

System.out.println("Converted to generic: " + generic.getKind());

268

269

// Convert back

270

Pod convertedBack = serialization.convertValue(generic, Pod.class);

271

```

272

273

### String and Collection Utilities

274

275

```java

276

// String utilities

277

String value = Utils.getSystemPropertyOrEnvVar("MY_CONFIG", "DEFAULT_VALUE");

278

System.out.println("Config value: " + value);

279

280

// Check for null or empty

281

if (Utils.isNotNullOrEmpty(value)) {

282

System.out.println("Value is valid: " + value);

283

}

284

285

// Join collections

286

List<String> podNames = Arrays.asList("pod1", "pod2", "pod3");

287

String joinedNames = Utils.join(podNames, ", ");

288

System.out.println("Pod names: " + joinedNames);

289

290

// Join arrays

291

String[] containerNames = {"app", "sidecar", "init"};

292

String joinedContainers = Utils.join(containerNames, " | ");

293

System.out.println("Containers: " + joinedContainers);

294

295

// Validation utilities

296

Utils.checkNotNull(client, "Kubernetes client cannot be null");

297

Utils.checkArgument(podNames.size() > 0, "Pod list cannot be empty");

298

```

299

300

### Resource Waiting Utilities

301

302

```java

303

// Wait for resource to be ready

304

Pod pod = client.pods().withName("slow-starting-pod").get();

305

306

if (pod != null) {

307

boolean becameReady = Utils.waitUntilReady(pod, 2, TimeUnit.MINUTES);

308

309

if (becameReady) {

310

System.out.println("Pod became ready");

311

} else {

312

System.out.println("Pod did not become ready within timeout");

313

}

314

315

// Check if resource is in final state

316

boolean inFinalState = Utils.isResourceInFinalState(pod);

317

System.out.println("Pod in final state: " + inFinalState);

318

}

319

```

320

321

### File and Configuration Utilities

322

323

```java

324

// Read configuration file

325

String configContent = Utils.readFile("/path/to/config.yaml");

326

System.out.println("Config content:\n" + configContent);

327

328

// Load properties

329

Properties props = Utils.loadProperties("application.properties");

330

String dbUrl = props.getProperty("database.url");

331

332

// Environment variable handling

333

String kubeconfig = Utils.getSystemPropertyOrEnvVar("kubeconfig", "KUBECONFIG");

334

if (Utils.isNotNullOrEmpty(kubeconfig)) {

335

System.out.println("Using kubeconfig: " + kubeconfig);

336

}

337

338

// System property with fallback to environment variable

339

String logLevel = Utils.getSystemPropertyOrEnvVar("log.level", "LOG_LEVEL", "INFO");

340

System.out.println("Log level: " + logLevel);

341

```

342

343

### Owner Reference Utilities

344

345

```java

346

// Check ownership relationships

347

Deployment deployment = client.apps().deployments().withName("my-app").get();

348

ReplicaSet replicaSet = client.apps().replicaSets().withName("my-app-12345").get();

349

350

if (deployment != null && replicaSet != null) {

351

// Check if ReplicaSet is owned by Deployment

352

boolean isOwned = KubernetesResourceUtil.isOwnedBy(replicaSet, deployment);

353

System.out.println("ReplicaSet owned by Deployment: " + isOwned);

354

355

// Get all owner references

356

List<OwnerReference> owners = KubernetesResourceUtil.getOwnerReferences(replicaSet);

357

for (OwnerReference owner : owners) {

358

System.out.println("Owner: " + owner.getKind() + "/" + owner.getName() +

359

" (Controller: " + owner.getController() + ")");

360

}

361

}

362

363

// Find resources owned by a specific resource

364

String deploymentUid = deployment.getMetadata().getUid();

365

List<ReplicaSet> ownedReplicaSets = client.apps().replicaSets().list().getItems().stream()

366

.filter(rs -> KubernetesResourceUtil.getOwnerReferences(rs).stream()

367

.anyMatch(owner -> deploymentUid.equals(owner.getUid())))

368

.collect(Collectors.toList());

369

370

System.out.println("ReplicaSets owned by deployment: " + ownedReplicaSets.size());

371

```

372

373

### Custom Resource Utilities

374

375

```java

376

// Working with custom resources using utilities

377

HasMetadata customResource = client.genericKubernetesResources("example.com/v1", "Database")

378

.withName("my-database").get();

379

380

if (customResource != null) {

381

// All utilities work with custom resources too

382

String name = KubernetesResourceUtil.getName(customResource);

383

String namespace = KubernetesResourceUtil.getNamespace(customResource);

384

boolean isReady = KubernetesResourceUtil.isResourceReady(customResource);

385

386

System.out.println("Custom resource: " + name);

387

System.out.println("Namespace: " + namespace);

388

System.out.println("Ready: " + isReady);

389

390

// Serialize custom resource

391

KubernetesSerialization serialization = client.getKubernetesSerialization();

392

String yaml = serialization.asYaml(customResource);

393

System.out.println("Custom resource YAML:\n" + yaml);

394

}

395

```

396

397

### Resource Template Processing

398

399

```java

400

public class ResourceTemplateProcessor {

401

402

private final KubernetesSerialization serialization;

403

404

public ResourceTemplateProcessor(KubernetesClient client) {

405

this.serialization = client.getKubernetesSerialization();

406

}

407

408

public HasMetadata processTemplate(String template, Map<String, String> variables) {

409

// Replace variables in template

410

String processedTemplate = template;

411

for (Map.Entry<String, String> var : variables.entrySet()) {

412

processedTemplate = processedTemplate.replace("${" + var.getKey() + "}", var.getValue());

413

}

414

415

// Deserialize the processed template

416

return serialization.unmarshal(processedTemplate);

417

}

418

419

public List<HasMetadata> processMultiResourceTemplate(String template, Map<String, String> variables) {

420

String processedTemplate = template;

421

for (Map.Entry<String, String> var : variables.entrySet()) {

422

processedTemplate = processedTemplate.replace("${" + var.getKey() + "}", var.getValue());

423

}

424

425

// Handle both single resources and lists

426

try {

427

KubernetesList list = serialization.unmarshal(processedTemplate, KubernetesList.class);

428

return list.getItems();

429

} catch (Exception e) {

430

// Single resource

431

HasMetadata single = serialization.unmarshal(processedTemplate);

432

return Collections.singletonList(single);

433

}

434

}

435

}

436

437

// Usage

438

ResourceTemplateProcessor processor = new ResourceTemplateProcessor(client);

439

440

String podTemplate = """

441

apiVersion: v1

442

kind: Pod

443

metadata:

444

name: ${POD_NAME}

445

labels:

446

app: ${APP_NAME}

447

spec:

448

containers:

449

- name: ${CONTAINER_NAME}

450

image: ${IMAGE}

451

""";

452

453

Map<String, String> variables = Map.of(

454

"POD_NAME", "generated-pod",

455

"APP_NAME", "my-app",

456

"CONTAINER_NAME", "main",

457

"IMAGE", "nginx:latest"

458

);

459

460

HasMetadata processedPod = processor.processTemplate(podTemplate, variables);

461

Pod createdPod = client.resource(processedPod).create();

462

```