or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdjaxb-lifecycle.mdjaxb-model.mdobject-locators.mdstrategic-patterns.mdutilities.md

utilities.mddocs/

0

# Utility Classes

1

2

Essential utility classes for string manipulation, class name handling, validation, JAXB context management, and XML Schema constants. These utilities provide common functionality used throughout the JAXB2 Basics runtime library.

3

4

## Capabilities

5

6

### String Manipulation

7

8

```java { .api }

9

final class StringUtils {

10

// String constants

11

static final String LINE_SEPARATOR;

12

static final String EMPTY;

13

static final String[] EMPTY_STRING_ARRAY;

14

15

// Core string operations

16

static boolean isEmpty(String str);

17

static String[] split(String str, char separatorChar);

18

static String join(Iterator iterator, String separator);

19

}

20

```

21

22

### Class Name Utilities

23

24

```java { .api }

25

final class ClassUtils {

26

// Separator constants

27

static final char PACKAGE_SEPARATOR_CHAR;

28

static final char INNER_CLASS_SEPARATOR_CHAR;

29

30

// Class name operations

31

static String getShortClassName(Class cls);

32

static String getShortClassName(String className);

33

}

34

```

35

36

### JAXB Context Management

37

38

```java { .api }

39

final class ContextUtils {

40

static String getContextPath(Class<?>... classes);

41

static String toString(JAXBContext context, Object object);

42

}

43

```

44

45

### Validation Utilities

46

47

```java { .api }

48

final class Validate {

49

static void notNull(Object object);

50

static void isTrue(boolean expression);

51

static void notEmpty(Collection collection);

52

static void noNullElements(Collection<?> collection);

53

}

54

```

55

56

### XML Schema Constants

57

58

```java { .api }

59

final class XmlSchemaConstants {

60

// XML Schema namespace

61

static final String NAMESPACE_URI;

62

63

// Built-in type constants

64

static final QName ANYTYPE;

65

static final QName ANYSIMPLETYPE;

66

static final QName STRING;

67

static final QName NORMALIZEDSTRING;

68

static final QName TOKEN;

69

static final QName LANGUAGE;

70

static final QName NAME;

71

static final QName NCNAME;

72

static final QName ID;

73

static final QName IDREF;

74

static final QName IDREFS;

75

static final QName ENTITY;

76

static final QName ENTITIES;

77

static final QName NMTOKEN;

78

static final QName NMTOKENS;

79

static final QName BOOLEAN;

80

static final QName BASE64BINARY;

81

static final QName HEXBINARY;

82

static final QName FLOAT;

83

static final QName DECIMAL;

84

static final QName INTEGER;

85

static final QName NONPOSITIVEINTEGER;

86

static final QName NEGATIVEINTEGER;

87

static final QName LONG;

88

static final QName INT;

89

static final QName SHORT;

90

static final QName BYTE;

91

static final QName NONNEGATIVEINTEGER;

92

static final QName UNSIGNEDLONG;

93

static final QName UNSIGNEDINT;

94

static final QName UNSIGNEDSHORT;

95

static final QName UNSIGNEDBYTE;

96

static final QName POSITIVEINTEGER;

97

static final QName DOUBLE;

98

static final QName ANYURI;

99

static final QName QNAME;

100

static final QName NOTATION;

101

static final QName DURATION;

102

static final QName DATETIME;

103

static final QName TIME;

104

static final QName DATE;

105

static final QName GYEARMONTH;

106

static final QName GYEAR;

107

static final QName GMONTHDAY;

108

static final QName GDAY;

109

static final QName GMONTH;

110

static final QName CALENDAR;

111

112

// Array of all type names

113

static final QName[] TYPE_NAMES;

114

115

// Utility method

116

static QName xsd(String localPart);

117

}

118

```

119

120

## Usage Examples

121

122

### String Utilities

123

124

```java

125

import org.jvnet.jaxb2_commons.lang.StringUtils;

126

127

// Check for empty/null strings

128

String value = getInputValue();

129

if (StringUtils.isEmpty(value)) {

130

System.out.println("Input is null or empty");

131

}

132

133

// Split strings by character

134

String csvData = "apple,banana,cherry,date";

135

String[] fruits = StringUtils.split(csvData, ',');

136

// Result: ["apple", "banana", "cherry", "date"]

137

138

// Join collections with separator

139

List<String> names = Arrays.asList("John", "Jane", "Bob");

140

String joined = StringUtils.join(names.iterator(), ", ");

141

// Result: "John, Jane, Bob"

142

143

// Using constants

144

String[] emptyArray = StringUtils.EMPTY_STRING_ARRAY; // More efficient than new String[0]

145

String emptyString = StringUtils.EMPTY; // More efficient than ""

146

String separator = StringUtils.LINE_SEPARATOR; // Platform-specific line separator

147

```

148

149

### Class Name Utilities

150

151

```java

152

import org.jvnet.jaxb2_commons.lang.ClassUtils;

153

154

// Get short class names (without package)

155

Class<?> clazz = java.util.ArrayList.class;

156

String shortName = ClassUtils.getShortClassName(clazz);

157

// Result: "ArrayList"

158

159

String fullClassName = "com.example.schema.Customer";

160

String shortClassName = ClassUtils.getShortClassName(fullClassName);

161

// Result: "Customer"

162

163

// Handle inner classes

164

Class<?> innerClass = Map.Entry.class;

165

String innerShortName = ClassUtils.getShortClassName(innerClass);

166

// Result: "Map.Entry"

167

168

// Using separator constants

169

char packageSep = ClassUtils.PACKAGE_SEPARATOR_CHAR; // '.'

170

char innerSep = ClassUtils.INNER_CLASS_SEPARATOR_CHAR; // '$'

171

172

// Custom class name processing

173

public String getDisplayName(Class<?> clazz) {

174

String shortName = ClassUtils.getShortClassName(clazz);

175

return shortName.replace(ClassUtils.INNER_CLASS_SEPARATOR_CHAR, '.');

176

}

177

```

178

179

### JAXB Context Utilities

180

181

```java

182

import org.jvnet.jaxb2_commons.lang.ContextUtils;

183

import javax.xml.bind.JAXBContext;

184

import javax.xml.bind.JAXBException;

185

186

// Generate context path from classes

187

Class<?>[] classes = {Customer.class, Order.class, Product.class};

188

String contextPath = ContextUtils.getContextPath(classes);

189

// Result: "com.example.schema"

190

191

// Create JAXB context using generated path

192

JAXBContext context = JAXBContext.newInstance(contextPath);

193

194

// Marshal object to formatted XML string

195

Customer customer = new Customer();

196

customer.setName("John Doe");

197

customer.setEmail("john@example.com");

198

199

String xml = ContextUtils.toString(context, customer);

200

System.out.println(xml);

201

/* Output:

202

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

203

<customer>

204

<name>John Doe</name>

205

<email>john@example.com</email>

206

</customer>

207

*/

208

209

// Utility method for creating contexts from multiple packages

210

public JAXBContext createMultiPackageContext(String... packageNames) throws JAXBException {

211

String contextPath = String.join(":", packageNames);

212

return JAXBContext.newInstance(contextPath);

213

}

214

```

215

216

### Validation Utilities

217

218

```java

219

import org.jvnet.jaxb2_commons.lang.Validate;

220

import java.util.*;

221

222

public class CustomerService {

223

224

public void createCustomer(String name, String email, List<String> tags) {

225

// Validate required parameters

226

Validate.notNull(name);

227

Validate.notNull(email);

228

229

// Validate conditions

230

Validate.isTrue(!name.trim().isEmpty());

231

Validate.isTrue(email.contains("@"));

232

233

// Validate collections

234

if (tags != null) {

235

Validate.notEmpty(tags);

236

Validate.noNullElements(tags);

237

}

238

239

// Process customer creation...

240

System.out.println("Creating customer: " + name);

241

}

242

243

public void updateCustomer(Customer customer) {

244

Validate.notNull(customer);

245

Validate.notNull(customer.getId());

246

Validate.isTrue(customer.getId() > 0);

247

248

// Update logic...

249

}

250

251

public List<Customer> findCustomers(Collection<Long> customerIds) {

252

Validate.notNull(customerIds);

253

Validate.notEmpty(customerIds);

254

Validate.noNullElements(customerIds);

255

256

// Find customers...

257

return new ArrayList<>();

258

}

259

}

260

261

// Usage examples that would throw exceptions:

262

try {

263

customerService.createCustomer(null, "test@example.com", null);

264

} catch (IllegalArgumentException e) {

265

// "The validated object is null"

266

}

267

268

try {

269

customerService.createCustomer("", "test@example.com", null);

270

} catch (IllegalArgumentException e) {

271

// "The validated expression is false"

272

}

273

274

try {

275

customerService.findCustomers(Arrays.asList(1L, null, 3L));

276

} catch (IllegalArgumentException e) {

277

// "The validated collection contains null element at index: 1"

278

}

279

```

280

281

### XML Schema Constants

282

283

```java

284

import org.jvnet.jaxb2_commons.xmlschema.XmlSchemaConstants;

285

import javax.xml.namespace.QName;

286

287

// Using built-in type constants

288

QName stringType = XmlSchemaConstants.STRING;

289

QName intType = XmlSchemaConstants.INT;

290

QName dateType = XmlSchemaConstants.DATE;

291

QName booleanType = XmlSchemaConstants.BOOLEAN;

292

293

// Create custom XSD QNames

294

QName customType = XmlSchemaConstants.xsd("myCustomType");

295

// Result: QName with namespace "http://www.w3.org/2001/XMLSchema" and local part "myCustomType"

296

297

// Check if a type is a built-in XML Schema type

298

public boolean isBuiltinType(QName typeName) {

299

if (!XmlSchemaConstants.NAMESPACE_URI.equals(typeName.getNamespaceURI())) {

300

return false;

301

}

302

303

for (QName builtin : XmlSchemaConstants.TYPE_NAMES) {

304

if (builtin.equals(typeName)) {

305

return true;

306

}

307

}

308

return false;

309

}

310

311

// Generate type mapping

312

public Map<String, QName> createTypeMapping() {

313

Map<String, QName> mapping = new HashMap<>();

314

mapping.put("string", XmlSchemaConstants.STRING);

315

mapping.put("int", XmlSchemaConstants.INT);

316

mapping.put("integer", XmlSchemaConstants.INTEGER);

317

mapping.put("long", XmlSchemaConstants.LONG);

318

mapping.put("double", XmlSchemaConstants.DOUBLE);

319

mapping.put("float", XmlSchemaConstants.FLOAT);

320

mapping.put("boolean", XmlSchemaConstants.BOOLEAN);

321

mapping.put("date", XmlSchemaConstants.DATE);

322

mapping.put("dateTime", XmlSchemaConstants.DATETIME);

323

mapping.put("time", XmlSchemaConstants.TIME);

324

mapping.put("decimal", XmlSchemaConstants.DECIMAL);

325

mapping.put("base64Binary", XmlSchemaConstants.BASE64BINARY);

326

mapping.put("hexBinary", XmlSchemaConstants.HEXBINARY);

327

mapping.put("anyURI", XmlSchemaConstants.ANYURI);

328

mapping.put("QName", XmlSchemaConstants.QNAME);

329

return mapping;

330

}

331

332

// Validate schema types

333

public void validateSchemaType(QName typeName) {

334

if (XmlSchemaConstants.NAMESPACE_URI.equals(typeName.getNamespaceURI())) {

335

if (!isBuiltinType(typeName)) {

336

throw new IllegalArgumentException("Unknown XML Schema built-in type: " + typeName.getLocalPart());

337

}

338

}

339

}

340

341

// Get all available type names

342

public void printAllTypes() {

343

System.out.println("XML Schema built-in types:");

344

for (QName type : XmlSchemaConstants.TYPE_NAMES) {

345

System.out.println(" " + type.getLocalPart());

346

}

347

}

348

```

349

350

### Combined Utility Usage

351

352

```java

353

import org.jvnet.jaxb2_commons.lang.*;

354

import org.jvnet.jaxb2_commons.xmlschema.XmlSchemaConstants;

355

356

public class SchemaAnalyzer {

357

358

public void analyzeClass(Class<?> clazz) {

359

// Use ClassUtils for name handling

360

String shortName = ClassUtils.getShortClassName(clazz);

361

String packageName = clazz.getPackage().getName();

362

363

System.out.println("Analyzing class: " + shortName);

364

System.out.println("Package: " + packageName);

365

366

// Use Validate for parameter checking

367

Validate.notNull(clazz);

368

Validate.isTrue(!clazz.isInterface());

369

370

// Use ContextUtils for JAXB operations

371

try {

372

String contextPath = ContextUtils.getContextPath(clazz);

373

System.out.println("JAXB Context Path: " + contextPath);

374

} catch (Exception e) {

375

System.out.println("Not a JAXB class: " + e.getMessage());

376

}

377

378

// Use StringUtils for text processing

379

List<String> annotations = getAnnotationNames(clazz);

380

if (!annotations.isEmpty()) {

381

String annotationList = StringUtils.join(annotations.iterator(), ", ");

382

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

383

}

384

}

385

386

private List<String> getAnnotationNames(Class<?> clazz) {

387

return Arrays.stream(clazz.getAnnotations())

388

.map(annotation -> ClassUtils.getShortClassName(annotation.annotationType()))

389

.collect(Collectors.toList());

390

}

391

392

public void validateXmlType(QName typeName, Object value) {

393

Validate.notNull(typeName);

394

395

if (XmlSchemaConstants.NAMESPACE_URI.equals(typeName.getNamespaceURI())) {

396

// It's a built-in XML Schema type

397

validateBuiltinType(typeName, value);

398

} else {

399

System.out.println("Custom type: " + typeName);

400

}

401

}

402

403

private void validateBuiltinType(QName typeName, Object value) {

404

if (XmlSchemaConstants.STRING.equals(typeName)) {

405

Validate.isTrue(value instanceof String);

406

} else if (XmlSchemaConstants.INT.equals(typeName)) {

407

Validate.isTrue(value instanceof Integer);

408

} else if (XmlSchemaConstants.BOOLEAN.equals(typeName)) {

409

Validate.isTrue(value instanceof Boolean);

410

}

411

// ... additional type validations

412

}

413

}

414

```

415

416

## Utility Integration Patterns

417

418

These utility classes are designed to work together and integrate seamlessly with the rest of the JAXB2 Basics runtime:

419

420

1. **String Processing**: StringUtils provides efficient string operations used throughout the library

421

2. **Class Introspection**: ClassUtils supports reflection-based operations and display formatting

422

3. **JAXB Integration**: ContextUtils bridges between Java classes and JAXB contexts

423

4. **Robust Validation**: Validate ensures consistent error handling and parameter validation

424

5. **Schema Compliance**: XmlSchemaConstants provides standard XML Schema type definitions

425

426

These utilities form the foundation for higher-level strategic patterns and JAXB integration features.