diff --git a/.erupt/erupt-job.loaded b/.erupt/erupt-job.loaded deleted file mode 100644 index 99cd5f9..0000000 --- a/.erupt/erupt-job.loaded +++ /dev/null @@ -1 +0,0 @@ -1.12.9 \ No newline at end of file diff --git a/.erupt/erupt-magic-api.loaded b/.erupt/erupt-magic-api.loaded deleted file mode 100644 index 99cd5f9..0000000 --- a/.erupt/erupt-magic-api.loaded +++ /dev/null @@ -1 +0,0 @@ -1.12.9 \ No newline at end of file diff --git a/.erupt/erupt-upms-user.loaded b/.erupt/erupt-upms-user.loaded deleted file mode 100644 index 99cd5f9..0000000 --- a/.erupt/erupt-upms-user.loaded +++ /dev/null @@ -1 +0,0 @@ -1.12.9 \ No newline at end of file diff --git a/.erupt/erupt-upms.loaded b/.erupt/erupt-upms.loaded deleted file mode 100644 index 99cd5f9..0000000 --- a/.erupt/erupt-upms.loaded +++ /dev/null @@ -1 +0,0 @@ -1.12.9 \ No newline at end of file diff --git a/.erupt/fluent-github.loaded b/.erupt/fluent-github.loaded deleted file mode 100644 index 99cd5f9..0000000 --- a/.erupt/fluent-github.loaded +++ /dev/null @@ -1 +0,0 @@ -1.12.9 \ No newline at end of file diff --git a/.gitignore b/.gitignore index a0869ed..24dfb87 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ .idea/ +.erupt/ +.env target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/**/target/ @@ -11,6 +13,7 @@ target/ *.iws *.iml *.ipr +srcipts/jaxb-ri/* ### Eclipse ### .apt_generated diff --git a/docs/ai-help/README.md b/docs/ai-help/README.md new file mode 100644 index 0000000..d99d445 --- /dev/null +++ b/docs/ai-help/README.md @@ -0,0 +1,3 @@ +# ADD API Support + +- Generators \ No newline at end of file diff --git a/docs/bpm/README.md b/docs/bpm/README.md index e69de29..a7b13a2 100644 --- a/docs/bpm/README.md +++ b/docs/bpm/README.md @@ -0,0 +1,4 @@ +# README + + +- [camunda-bpm-platform](https://github.com/camunda/camunda-bpm-platform.git) \ No newline at end of file diff --git a/docs/cicd/README.md b/docs/cicd/README.md index e69de29..e1798e3 100644 --- a/docs/cicd/README.md +++ b/docs/cicd/README.md @@ -0,0 +1,3 @@ +# README + +- [cds](https://github.com/ovh/cds.git) \ No newline at end of file diff --git a/docs/data/database-client.md b/docs/data/database-client.md index e69de29..614dde3 100644 --- a/docs/data/database-client.md +++ b/docs/data/database-client.md @@ -0,0 +1,3 @@ +# README + +- [Simple SQL Client for lightweight data analysis.](https://github.com/bdash-app/bdash) \ No newline at end of file diff --git a/docs/data/tis.md b/docs/data/tis.md index e69de29..cbcbdc8 100644 --- a/docs/data/tis.md +++ b/docs/data/tis.md @@ -0,0 +1,9 @@ +# TIS + +一个完整的TIS应用,由以下三个子工程构成: + +TIS主干逻辑 https://github.com/datavane/tis +TIS插件 https://github.com/qlangtech/plugins +前端逻辑 https://github.com/qlangtech/ng-tis + + diff --git a/docs/features/authing-integrations.md b/docs/features/authing-integrations.md index e69de29..17441f9 100644 --- a/docs/features/authing-integrations.md +++ b/docs/features/authing-integrations.md @@ -0,0 +1,2 @@ +# Authing Integration + diff --git a/docs/features/ngrox.md b/docs/features/ngrox.md index e69de29..3f939c7 100644 --- a/docs/features/ngrox.md +++ b/docs/features/ngrox.md @@ -0,0 +1,6 @@ +# ngrox + +```shell +brew install ngrok/ngrok/ngrok +``` + diff --git a/docs/framework/README.md b/docs/framework/README.md index e69de29..73408f4 100644 --- a/docs/framework/README.md +++ b/docs/framework/README.md @@ -0,0 +1,3 @@ +# README + +- [caf-framework](https://gitee.com/ubml/caf-framework) \ No newline at end of file diff --git a/docs/low-code/README.md b/docs/low-code/README.md index e69de29..ed5c043 100644 --- a/docs/low-code/README.md +++ b/docs/low-code/README.md @@ -0,0 +1,37 @@ +# README + +- [baserow](https://gitlab.com/baserow/baserow) + + +## Backend + +- [https://github.com/ConduitPlatform/Conduit.git] + +## Integration + +- [connections](https://github.com/buildable/connections.git) + +## Webhook + +- [convoy](https://github.com/frain-dev/convoy.git) + +## Generator + +- [youyaboot](https://gitee.com/magicalcoder/youyaboot) + +## Admin + +- [admin-ui-vue](https://gitee.com/yudaocode/yudao-ui-admin-vben) +- [wukong-nocode](https://gitee.com/wukongcrm/wukong-nocode) + +## Data integration + +- [wrangler](https://github.com/data-integrations/wrangler) +- []( https://github.com/WeBankFinTech/DataSphereStudio.git) +- [](https://github.com/dataease/dataease.git) +- [](https://github.com/multiprocessio/datastation) + +## Tools + +- [](https://github.com/formbricks/formbricks) +- [](https://github.com/httpie/cli) \ No newline at end of file diff --git a/docs/tools/1-akita.md b/docs/tools/1-akita.md index e69de29..cb97f8b 100644 --- a/docs/tools/1-akita.md +++ b/docs/tools/1-akita.md @@ -0,0 +1,42 @@ +# Akita + +[akita](https://docs.akita.software/docs/how-akita-works) +> Akita watches your API traffic for automatic discovery and dashboards + +根据提供的文档《How Akita Works》,以下是Akita软件的要点总结: + +1. **API流量监控**:Akita通过使用eBPF技术自动发现API流量,并为监控和仪表板生成数据。 + +2. **低摩擦部署**:Akita代理(Agent)可以无摩擦地部署,不需要通过SDK提供访问权限,也不需要更改代码或代理。 + +3. **低风险部署**:Akita代理在服务器上运行,仅将请求/响应的元数据发送回云端,确保敏感数据不会暴露给Akita服务器。 + +4. **自动API行为建模**:Akita自动对API流量进行建模,推断API路径,为每个端点提供监控和警报功能。 + +5. **流量分析技术**:Akita代理使用salted hash对有效载荷数据进行加密,并且永远不会解密(unhash),确保敏感数据不会被Akita云服务看到。 + +6. **高级流量分析算法**:Akita云使用先进的流量分析算法自动推断端点结构(包括路径参数)、数据类型、认证等,减少了编写API规范或制作仪表板的工作。 + +7. **数据访问和处理政策**:Akita有明确的数据访问和处理政策,确保用户数据的安全性和隐私性。 + +8. **支持的技术栈**:Akita支持多种技术栈,以适应不同的部署环境和需求。 + +## How to Run + +```shell +docker pull public.ecr.aws/akitasoftware/akita-cli:latest +``` + +start agent +```shell +docker run --rm --network host + -e AKITA_API_KEY_ID= API KEY ID \ + -e AKITA_API_KEY_SECRET= API KEY SECRET \ + akitasoftware/cli:latest apidump \ + --project PROJECT NAME +``` + +## codes + +- [akita-cli](https://github.com/akitasoftware/akita-cli) +- [akita-libs](https://github.com/akitasoftware/akita-libs.git) diff --git a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/FeishuWrapper.java b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/FeishuWrapper.java deleted file mode 100644 index 97341d5..0000000 --- a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/FeishuWrapper.java +++ /dev/null @@ -1,4 +0,0 @@ -package io.fluent.wrappers.feishu; - -public class FeishuWrapper { -} diff --git a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/auth/service/AuthApiService.java b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/auth/service/AuthApiService.java index 74a39b0..5effccb 100644 --- a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/auth/service/AuthApiService.java +++ b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/auth/service/AuthApiService.java @@ -1,78 +1,78 @@ -package io.fluent.wrappers.feishu.auth.service; - -import cn.hutool.core.util.StrUtil; -import cn.hutool.http.HttpUtil; -import io.fluent.wrappers.feishu.auth.dto.req.TenantAccessTokenGetReqDTO; -import io.fluent.wrappers.feishu.auth.dto.resp.TenantAccessTokenGetRespDTO; -import lombok.Data; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -/** - * 飞书认证api接口 - * - * @author Tao.Liu - * @date 2022/6/29 13:55 - */ -@Data -public class AuthApiService { - - public final static String BASE_URL = "https://open.feishu.cn/open-apis/auth"; - - - - - /** - * 过期时间 - */ - private AtomicLong EXPIRE_TIMES = new AtomicLong(); - - /** - * 企业自建应用token - */ - private String tenantAccessToken = ""; - - /** - * 应用ID - */ - private String appId; - - /** - * 应用名称 - */ - private String appSecret; - - - public AuthApiService(final String appId, final String appSecret) { - this.appId = appId; - this.appSecret = appSecret; - } - - /** - * 企业自建应用token - * - * @return - */ - public String getTenantAccessToken() { - if (StrUtil.isNotBlank(tenantAccessToken) && System.currentTimeMillis() < EXPIRE_TIMES.get()) { - return this.tenantAccessToken; - } - - synchronized (this) { - final TenantAccessTokenGetReqDTO tokenGetReqDTO = new TenantAccessTokenGetReqDTO(appId, appSecret); - final TenantAccessTokenGetRespDTO tokenRespDTO = HttpUtil.post(BASE_URL + "/v3/tenant_access_token/internal", - tokenGetReqDTO, TenantAccessTokenGetRespDTO.class); - if (tokenGetReqDTO == null && Strings.isBlank(tokenRespDTO.getTenantAccessToken())) { - throw new FeishuException(FeishuErrorCodeEnum.TABLE_ERROR, "获取飞书token出错"); - } - - // 设置过期时间,提前半小时失效 - final long expireMills = TimeUnit.SECONDS.toMillis(tokenRespDTO.getExpire() - 1800); - EXPIRE_TIMES.set(System.currentTimeMillis() + expireMills); - this.tenantAccessToken = tokenRespDTO.getTenantAccessToken(); - return this.tenantAccessToken; - } - } - -} +//package io.fluent.wrappers.feishu.auth.service; +// +//import cn.hutool.core.util.StrUtil; +//import cn.hutool.http.HttpUtil; +//import io.fluent.wrappers.feishu.auth.dto.req.TenantAccessTokenGetReqDTO; +//import io.fluent.wrappers.feishu.auth.dto.resp.TenantAccessTokenGetRespDTO; +//import lombok.Data; +// +//import java.util.concurrent.TimeUnit; +//import java.util.concurrent.atomic.AtomicLong; +// +///** +// * 飞书认证api接口 +// * +// * @author Tao.Liu +// * @date 2022/6/29 13:55 +// */ +//@Data +//public class AuthApiService { +// +// public final static String BASE_URL = "https://open.feishu.cn/open-apis/auth"; +// +// +// +// +// /** +// * 过期时间 +// */ +// private AtomicLong EXPIRE_TIMES = new AtomicLong(); +// +// /** +// * 企业自建应用token +// */ +// private String tenantAccessToken = ""; +// +// /** +// * 应用ID +// */ +// private String appId; +// +// /** +// * 应用名称 +// */ +// private String appSecret; +// +// +// public AuthApiService(final String appId, final String appSecret) { +// this.appId = appId; +// this.appSecret = appSecret; +// } +// +// /** +// * 企业自建应用token +// * +// * @return +// */ +// public String getTenantAccessToken() { +// if (StrUtil.isNotBlank(tenantAccessToken) && System.currentTimeMillis() < EXPIRE_TIMES.get()) { +// return this.tenantAccessToken; +// } +// +// synchronized (this) { +// final TenantAccessTokenGetReqDTO tokenGetReqDTO = new TenantAccessTokenGetReqDTO(appId, appSecret); +// final TenantAccessTokenGetRespDTO tokenRespDTO = HttpUtil.post(BASE_URL + "/v3/tenant_access_token/internal", +// tokenGetReqDTO, TenantAccessTokenGetRespDTO.class); +// if (tokenGetReqDTO == null && Strings.isBlank(tokenRespDTO.getTenantAccessToken())) { +// throw new FeishuException(FeishuErrorCodeEnum.TABLE_ERROR, "获取飞书token出错"); +// } +// +// // 设置过期时间,提前半小时失效 +// final long expireMills = TimeUnit.SECONDS.toMillis(tokenRespDTO.getExpire() - 1800); +// EXPIRE_TIMES.set(System.currentTimeMillis() + expireMills); +// this.tenantAccessToken = tokenRespDTO.getTenantAccessToken(); +// return this.tenantAccessToken; +// } +// } +// +//} diff --git a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/dto/req/BiFieldQueryReqDTO.java b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/dto/req/BiFieldQueryReqDTO.java index e167af1..ac7aa7c 100644 --- a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/dto/req/BiFieldQueryReqDTO.java +++ b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/dto/req/BiFieldQueryReqDTO.java @@ -1,8 +1,8 @@ package io.fluent.wrappers.feishu.bitable.dto.req; -import com.cloudminds.data.smith.external.feishu.common.dto.PageReqDTO; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.annotation.JsonNaming; +import io.fluent.wrappers.feishu.common.dto.PageReqDTO; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/dto/req/BiTableRecordQueryReqDTO.java b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/dto/req/BiTableRecordQueryReqDTO.java index 0f8f0fe..e5be85a 100644 --- a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/dto/req/BiTableRecordQueryReqDTO.java +++ b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/dto/req/BiTableRecordQueryReqDTO.java @@ -1,8 +1,8 @@ package io.fluent.wrappers.feishu.bitable.dto.req; -import com.cloudminds.data.smith.external.feishu.common.dto.PageReqDTO; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.annotation.JsonNaming; +import io.fluent.wrappers.feishu.common.dto.PageReqDTO; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/service/BiTableApiService.java b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/service/BiTableApiService.java index df2ef82..3dbeb4b 100644 --- a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/service/BiTableApiService.java +++ b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/bitable/service/BiTableApiService.java @@ -1,395 +1,383 @@ -package io.fluent.wrappers.feishu.bitable.service; - -import cn.hutool.core.io.IoUtil; -import cn.hutool.core.map.MapUtil; -import cn.hutool.core.thread.ThreadUtil; -import cn.hutool.json.JSONUtil; -import com.cloudminds.data.smith.external.feishu.auth.service.AuthApiService; -import com.cloudminds.data.smith.external.feishu.bitable.dto.req.*; -import com.cloudminds.data.smith.external.feishu.bitable.dto.resp.BiFieldItemRespDTO; -import com.cloudminds.data.smith.external.feishu.bitable.dto.resp.BiRecordItemRespDTO; -import com.cloudminds.data.smith.external.feishu.bitable.dto.resp.BiTableItemRespDTO; -import com.cloudminds.data.smith.external.feishu.common.constant.FeishuErrorCodeEnum; -import com.cloudminds.data.smith.external.feishu.common.dto.Page; -import com.cloudminds.data.smith.external.feishu.common.dto.PageReqDTO; -import com.cloudminds.data.smith.external.feishu.common.dto.Resp; -import com.cloudminds.data.smith.external.feishu.common.exception.FeishuException; -import com.cloudminds.data.smith.util.Lists; -import com.cloudminds.data.smith.util.Strings; -import lombok.extern.slf4j.Slf4j; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.*; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.web.client.ResponseErrorHandler; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * 飞书多维表格API操作接口 - * - * @author Tao.Liu - * @date 2022/6/22 13:44 - */ -@Slf4j -public class BiTableApiService { - - /** - * 请求地址 - */ - public static final String BASE_URL = "https://open.feishu.cn/open-apis/bitable"; - - /** - * 超过1KB,则不输出响应 - */ - private final int MAX_IGNORE_RESP_BYTES = 1 * 1024; - - private List RETRY_ERROR_CODES = Lists.asList(1255040, 1254607); - - /** - * 请求模板 - */ - private RestTemplate restTemplate; - - /** - * 认证请求模板 - */ - private AuthApiService authApiService; - - - public BiTableApiService(final String appId, final String appSecret) { - this.authApiService = new AuthApiService(appId, appSecret); - this.buildRestTemplate(); - } - - /** - * 分页获取多维表格列表 - * - * @param appToken - * @param pageReqDTO - * @return - */ - public Page pageTableList(final String appToken, final PageReqDTO pageReqDTO) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables", appToken); - final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(url); - uriBuilder.queryParam("page_token", pageReqDTO.getPageToken()) - .queryParam("page_size", pageReqDTO.getPageSize()); - final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { - }; - final ResponseEntity>> response = restTemplate.exchange(uriBuilder.toUriString(), HttpMethod.GET, HttpEntity.EMPTY, reference); - return this.getSuccessData(response.getBody()); - } - - /** - * 创建数据表格 - * - * @param appToken - * @param name - * @return - */ - public BiTableItemRespDTO createTable(final String appToken, final String name) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables", appToken); - final Map requestBody = MapUtil.of("table", MapUtil.of("name", name)); - - final ParameterizedTypeReference> reference = new ParameterizedTypeReference>() { - }; - final HttpEntity> httpEntity = new HttpEntity<>(requestBody); - final ResponseEntity> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, reference); - return this.getSuccessData(response.getBody()); - } - - /** - * 删除单个数据表 - * - * @param appToken - * @param tableId - */ - public void deleteTable(final String appToken, String tableId) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s", appToken, tableId); - final ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, HttpEntity.EMPTY, Resp.class); - this.getSuccessData(response.getBody()); - } - - /** - * 查询字段分页列表 - * - * @param appToken - * @param queryReqDTO - * @return - */ - public Page pageFieldList(final String appToken, final String tableId, final BiFieldQueryReqDTO queryReqDTO) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/fields", appToken, tableId); - final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(url); - uriBuilder.queryParam("view_id", queryReqDTO.getViewId()) - .queryParam("page_token", queryReqDTO.getPageToken()) - .queryParam("page_size", queryReqDTO.getPageSize()); - final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { - }; - final ResponseEntity>> response = restTemplate.exchange(uriBuilder.toUriString(), HttpMethod.GET, HttpEntity.EMPTY, reference); - return this.getSuccessData(response.getBody()); - } - - /** - * 获取表格所有字段列表 - * - * @param appToken - * @param tableId - * @return - */ - public List getFieldList(final String appToken, final String tableId) { - final List fieldList = new ArrayList<>(); - // 查询当前表格所有字段数据,最多100个字段 - final BiFieldQueryReqDTO queryReqDTO = new BiFieldQueryReqDTO(100); - boolean hasMore; - do { - final Page existPage = this.pageFieldList(appToken, tableId, queryReqDTO); - if (existPage == null || Lists.isEmpty(existPage.getItems())) { - break; - } - fieldList.addAll(existPage.getItems()); - queryReqDTO.setPageToken(existPage.getPageToken()); - hasMore = Boolean.TRUE.equals(existPage.getHasMore()) && Strings.isNotBlank(existPage.getPageToken()); - } while (hasMore); - return fieldList; - } - - /** - * 创建字段 - * 新增记录、修改记录、修改字段、新增字段、删除这种写入操作都不支持并发 - * @param appToken - * @param saveReqDTO - * @return - */ - public BiFieldItemRespDTO createField(final String appToken, final BiFieldSaveReqDTO saveReqDTO) { - synchronized (saveReqDTO.getTableId().intern()) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/fields", appToken, saveReqDTO.getTableId()); - final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { - }; - final HttpEntity httpEntity = new HttpEntity<>(saveReqDTO.getSaveBody()); - final ResponseEntity>> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, reference); - final Map resultMap = this.getSuccessData(response.getBody()); - return resultMap.get("field"); - } - } - - /** - * 更新字段 - * - * @param appToken - * @param saveReqDTO - * @return - */ - public BiFieldItemRespDTO updateField(final String appToken, final BiFieldSaveReqDTO saveReqDTO) { - synchronized (saveReqDTO.getTableId().intern()) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/fields/%s", appToken, saveReqDTO.getTableId(), saveReqDTO.getFieldId()); - final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { - }; - final HttpEntity httpEntity = new HttpEntity<>(saveReqDTO.getSaveBody()); - final ResponseEntity>> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, reference); - try { - final Map resultMap = this.getSuccessData(response.getBody()); - return resultMap.get("field"); - } catch (FeishuException e) { - log.warn("同步飞书字段出错, message={}", e.getMessage()); - } - } - final BiFieldItemRespDTO itemRespDTO = new BiFieldItemRespDTO(); - itemRespDTO.setFieldId(saveReqDTO.getFieldId()); - itemRespDTO.setFieldName(saveReqDTO.getSaveBody().getFieldName()); - itemRespDTO.setType(saveReqDTO.getSaveBody().getType()); - itemRespDTO.setProperty(saveReqDTO.getSaveBody().getProperty()); - return itemRespDTO; - } - - /** - * 删除字段 - * - * @param appToken - * @param tableId - * @param fieldId - * @return - */ - public Boolean deleteField(final String appToken, final String tableId, final String fieldId) { - synchronized (tableId.intern()) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/fields/%s", appToken, tableId, fieldId); - final ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, HttpEntity.EMPTY, Resp.class); - try { - final Map resultMap = (Map) this.getSuccessData(response.getBody()); - return (Boolean) resultMap.get("deleted"); - } catch (FeishuException e) { - log.warn("删除飞书字段出错, message={}", e.getMessage()); - } - } - return false; - } - - /** - * 分页获取多维表格记录 - * - * @param appToken - * @param queryReqDTO - * @return - */ - public Page pageRecordList(final String appToken, final String tableId, final BiTableRecordQueryReqDTO queryReqDTO) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/records", appToken, tableId); - final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { - }; - final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(url); - uriBuilder.queryParam("view_id", queryReqDTO.getViewId()) - .queryParam("filter", queryReqDTO.getFilter()) - .queryParam("sort", queryReqDTO.getSort()) - .queryParam("field_names", queryReqDTO.getFieldNames()) - .queryParam("text_field_as_array", queryReqDTO.getTextFieldAsArray()) - .queryParam("page_token", queryReqDTO.getPageToken()) - .queryParam("page_size", queryReqDTO.getPageSize()); - final String requestUrl = uriBuilder.build().toString(); - final ResponseEntity>> response = restTemplate.exchange(requestUrl, HttpMethod.GET, HttpEntity.EMPTY, reference); - return this.getSuccessData(response.getBody()); - } - - /** - * 批量新增记录 - * - * @param appToken - * @param tableId - * @param saveReqDTO - * @return - */ - public List insertBatchRecords(final String appToken, final String tableId, final TableRecordSaveReqDTO saveReqDTO) { - synchronized (tableId.intern()) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/records/batch_create", appToken, tableId); - return this.syncBatchRecords(url, saveReqDTO); - } - } - - /** - * 批量更新 - * - * @param appToken - * @param tableId - * @param saveReqDTO - * @return - */ - public List updateBatchRecords(final String appToken, final String tableId, final TableRecordSaveReqDTO saveReqDTO) { - synchronized (tableId.intern()) { - final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/records/batch_update", appToken, tableId); - return this.syncBatchRecords(url, saveReqDTO); - } - } - - /** - * 批量同步记录 - * - * @param url - * @param saveReqDTO - * @return - */ - private List syncBatchRecords(final String url, final TableRecordSaveReqDTO saveReqDTO) { - /** - *飞书更新数据内部逻辑是异步操作,下次更新时会触发同步处理,可能会产生上次数据未处理完的问题,产生try again later - * 加上重试处理 - */ - // 最大重试次数 - final int maxRetry = 3; - // 间隔时间3秒 - int interval = 3000; - for (int i = 0; i <= maxRetry; i++) { - try { - return this.saveBatchRecords(saveReqDTO, url); - } catch (FeishuException e) { - if (i == maxRetry || Strings.isNotEquals(FeishuErrorCodeEnum.TRY_AGAIN_LATER.getCode(), e.getCode())) { - throw e; - } - log.info("飞书更新记录异常,进行重试处理, url={}", url); - ThreadUtil.sleep(interval * (i + 1)); - } - } - return new ArrayList<>(); - } - - /** - * 批量保存记录 - * - * @param saveReqDTO - * @param url - * @return - */ - private List saveBatchRecords(final TableRecordSaveReqDTO saveReqDTO, final String url) { - final ParameterizedTypeReference>>> reference = new ParameterizedTypeReference>>>() { - }; - final HttpEntity httpEntity = new HttpEntity<>(saveReqDTO); - final ResponseEntity>>> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, reference); - final Map> responseBody = this.getSuccessData(response.getBody()); - return responseBody.get("records"); - } - - - /** - * 获取成功数据 - * - * @param resp - * @param - * @return - */ - private T getSuccessData(final Resp resp) { - if (!Resp.isSuccess(resp)) { - log.warn("飞书接口响应 --> {}", JSONUtil.toJsonStr(resp)); - throw new FeishuException(FeishuErrorCodeEnum.TABLE_ERROR, "飞书接口响应异常:" + resp.getMsg()); - } - return resp.getData(); - } - - /** - * 构建restTemplate - */ - private void buildRestTemplate() { - this.restTemplate = new RestTemplate(AuthApiService.REQUEST_FACTORY); - this.restTemplate.setErrorHandler(new ResponseErrorHandler() { - @Override - public boolean hasError(final ClientHttpResponse response) throws IOException { - return response.getStatusCode() != HttpStatus.OK; - } - - @Override - public void handleError(final ClientHttpResponse response) throws IOException { - final String body = IoUtil.read(response.getBody(), StandardCharsets.UTF_8); - final String logId = response.getHeaders().getFirst("x-tt-logid"); - final int statusCode = response.getRawStatusCode(); - log.warn("飞书接口响应异常 --> status:{}, body: {}, x-tt-logid:{}", statusCode, body, logId); - if (HttpStatus.FORBIDDEN == response.getStatusCode()) { - throw new FeishuException(FeishuErrorCodeEnum.TABLE_ERROR, "无权限操作,请设置多维表格应用权限"); - } - // 504响应码转换 - if (Strings.isNotBlank(body)) { - final Resp resp = JSONUtil.toBean(body, Resp.class); - if (RETRY_ERROR_CODES.contains(resp.getCode())) { - // 飞书接口响应please try again later - throw new FeishuException(FeishuErrorCodeEnum.TRY_AGAIN_LATER, "飞书接口响应出错:" + resp.getMsg()); - } - } - if (HttpStatus.OK != response.getStatusCode()) { - throw new FeishuException(FeishuErrorCodeEnum.TABLE_ERROR, "飞书接口响应出错:" + body); - } - } - }); - // 拦截器 - final ClientHttpRequestInterceptor interceptor = (request, body, execution) -> { - final String tenantAccessToken = "Bearer " + this.authApiService.getTenantAccessToken(); - final String requestBody = body.length > MAX_IGNORE_RESP_BYTES ? "ignore..." : new String(body, StandardCharsets.UTF_8); - log.info("请求飞书接口,{} url={}, token={}, body={}", request.getMethod().name(), request.getURI().getRawPath(), tenantAccessToken, requestBody); - // 添加请求头 - request.getHeaders().add(HttpHeaders.AUTHORIZATION, tenantAccessToken); - final ClientHttpResponse response = execution.execute(request, body); - return response; - }; - this.restTemplate.setInterceptors(Lists.asList(interceptor)); - } - - -} +//package io.fluent.wrappers.feishu.bitable.service; +// +//import cn.hutool.core.io.IoUtil; +//import cn.hutool.core.map.MapUtil; +//import cn.hutool.core.thread.ThreadUtil; +//import cn.hutool.json.JSONUtil; +//import io.fluent.wrappers.feishu.auth.service.AuthApiService; +//import io.fluent.wrappers.feishu.bitable.dto.req.BiFieldSaveBodyReqDTO; +//import io.fluent.wrappers.feishu.bitable.dto.resp.BiFieldItemRespDTO; +//import io.fluent.wrappers.feishu.bitable.dto.resp.BiTableItemRespDTO; +//import io.fluent.wrappers.feishu.common.dto.PageReqDTO; +//import io.fluent.wrappers.feishu.common.dto.Resp; +//import io.fluent.wrappers.feishu.common.exception.FeishuException; +//import lombok.extern.slf4j.Slf4j; +// +//import java.io.IOException; +//import java.nio.charset.StandardCharsets; +//import java.util.ArrayList; +//import java.util.List; +//import java.util.Map; +// +///** +// * 飞书多维表格API操作接口 +// * +// * @author Tao.Liu +// * @date 2022/6/22 13:44 +// */ +//@Slf4j +//public class BiTableApiService { +// +// /** +// * 请求地址 +// */ +// public static final String BASE_URL = "https://open.feishu.cn/open-apis/bitable"; +// +// /** +// * 超过1KB,则不输出响应 +// */ +// private final int MAX_IGNORE_RESP_BYTES = 1 * 1024; +// +// private List RETRY_ERROR_CODES = Lists.asList(1255040, 1254607); +// +// /** +// * 请求模板 +// */ +// private RestTemplate restTemplate; +// +// /** +// * 认证请求模板 +// */ +// private AuthApiService authApiService; +// +// +// public BiTableApiService(final String appId, final String appSecret) { +// this.authApiService = new AuthApiService(appId, appSecret); +// this.buildRestTemplate(); +// } +// +// /** +// * 分页获取多维表格列表 +// * +// * @param appToken +// * @param pageReqDTO +// * @return +// */ +// public Page pageTableList(final String appToken, final PageReqDTO pageReqDTO) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables", appToken); +// final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(url); +// uriBuilder.queryParam("page_token", pageReqDTO.getPageToken()) +// .queryParam("page_size", pageReqDTO.getPageSize()); +// final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { +// }; +// final ResponseEntity>> response = restTemplate.exchange(uriBuilder.toUriString(), HttpMethod.GET, HttpEntity.EMPTY, reference); +// return this.getSuccessData(response.getBody()); +// } +// +// /** +// * 创建数据表格 +// * +// * @param appToken +// * @param name +// * @return +// */ +// public BiTableItemRespDTO createTable(final String appToken, final String name) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables", appToken); +// final Map requestBody = MapUtil.of("table", MapUtil.of("name", name)); +// +// final ParameterizedTypeReference> reference = new ParameterizedTypeReference>() { +// }; +// final HttpEntity> httpEntity = new HttpEntity<>(requestBody); +// final ResponseEntity> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, reference); +// return this.getSuccessData(response.getBody()); +// } +// +// /** +// * 删除单个数据表 +// * +// * @param appToken +// * @param tableId +// */ +// public void deleteTable(final String appToken, String tableId) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s", appToken, tableId); +// final ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, HttpEntity.EMPTY, Resp.class); +// this.getSuccessData(response.getBody()); +// } +// +// /** +// * 查询字段分页列表 +// * +// * @param appToken +// * @param queryReqDTO +// * @return +// */ +// public Page pageFieldList(final String appToken, final String tableId, final BiFieldQueryReqDTO queryReqDTO) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/fields", appToken, tableId); +// final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(url); +// uriBuilder.queryParam("view_id", queryReqDTO.getViewId()) +// .queryParam("page_token", queryReqDTO.getPageToken()) +// .queryParam("page_size", queryReqDTO.getPageSize()); +// final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { +// }; +// final ResponseEntity>> response = restTemplate.exchange(uriBuilder.toUriString(), HttpMethod.GET, HttpEntity.EMPTY, reference); +// return this.getSuccessData(response.getBody()); +// } +// +// /** +// * 获取表格所有字段列表 +// * +// * @param appToken +// * @param tableId +// * @return +// */ +// public List getFieldList(final String appToken, final String tableId) { +// final List fieldList = new ArrayList<>(); +// // 查询当前表格所有字段数据,最多100个字段 +// final BiFieldQueryReqDTO queryReqDTO = new BiFieldQueryReqDTO(100); +// boolean hasMore; +// do { +// final Page existPage = this.pageFieldList(appToken, tableId, queryReqDTO); +// if (existPage == null || Lists.isEmpty(existPage.getItems())) { +// break; +// } +// fieldList.addAll(existPage.getItems()); +// queryReqDTO.setPageToken(existPage.getPageToken()); +// hasMore = Boolean.TRUE.equals(existPage.getHasMore()) && Strings.isNotBlank(existPage.getPageToken()); +// } while (hasMore); +// return fieldList; +// } +// +// /** +// * 创建字段 +// * 新增记录、修改记录、修改字段、新增字段、删除这种写入操作都不支持并发 +// * @param appToken +// * @param saveReqDTO +// * @return +// */ +// public BiFieldItemRespDTO createField(final String appToken, final BiFieldSaveReqDTO saveReqDTO) { +// synchronized (saveReqDTO.getTableId().intern()) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/fields", appToken, saveReqDTO.getTableId()); +// final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { +// }; +// final HttpEntity httpEntity = new HttpEntity<>(saveReqDTO.getSaveBody()); +// final ResponseEntity>> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, reference); +// final Map resultMap = this.getSuccessData(response.getBody()); +// return resultMap.get("field"); +// } +// } +// +// /** +// * 更新字段 +// * +// * @param appToken +// * @param saveReqDTO +// * @return +// */ +// public BiFieldItemRespDTO updateField(final String appToken, final BiFieldSaveReqDTO saveReqDTO) { +// synchronized (saveReqDTO.getTableId().intern()) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/fields/%s", appToken, saveReqDTO.getTableId(), saveReqDTO.getFieldId()); +// final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { +// }; +// final HttpEntity httpEntity = new HttpEntity<>(saveReqDTO.getSaveBody()); +// final ResponseEntity>> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, reference); +// try { +// final Map resultMap = this.getSuccessData(response.getBody()); +// return resultMap.get("field"); +// } catch (FeishuException e) { +// log.warn("同步飞书字段出错, message={}", e.getMessage()); +// } +// } +// final BiFieldItemRespDTO itemRespDTO = new BiFieldItemRespDTO(); +// itemRespDTO.setFieldId(saveReqDTO.getFieldId()); +// itemRespDTO.setFieldName(saveReqDTO.getSaveBody().getFieldName()); +// itemRespDTO.setType(saveReqDTO.getSaveBody().getType()); +// itemRespDTO.setProperty(saveReqDTO.getSaveBody().getProperty()); +// return itemRespDTO; +// } +// +// /** +// * 删除字段 +// * +// * @param appToken +// * @param tableId +// * @param fieldId +// * @return +// */ +// public Boolean deleteField(final String appToken, final String tableId, final String fieldId) { +// synchronized (tableId.intern()) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/fields/%s", appToken, tableId, fieldId); +// final ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, HttpEntity.EMPTY, Resp.class); +// try { +// final Map resultMap = (Map) this.getSuccessData(response.getBody()); +// return (Boolean) resultMap.get("deleted"); +// } catch (FeishuException e) { +// log.warn("删除飞书字段出错, message={}", e.getMessage()); +// } +// } +// return false; +// } +// +// /** +// * 分页获取多维表格记录 +// * +// * @param appToken +// * @param queryReqDTO +// * @return +// */ +// public Page pageRecordList(final String appToken, final String tableId, final BiTableRecordQueryReqDTO queryReqDTO) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/records", appToken, tableId); +// final ParameterizedTypeReference>> reference = new ParameterizedTypeReference>>() { +// }; +// final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(url); +// uriBuilder.queryParam("view_id", queryReqDTO.getViewId()) +// .queryParam("filter", queryReqDTO.getFilter()) +// .queryParam("sort", queryReqDTO.getSort()) +// .queryParam("field_names", queryReqDTO.getFieldNames()) +// .queryParam("text_field_as_array", queryReqDTO.getTextFieldAsArray()) +// .queryParam("page_token", queryReqDTO.getPageToken()) +// .queryParam("page_size", queryReqDTO.getPageSize()); +// final String requestUrl = uriBuilder.build().toString(); +// final ResponseEntity>> response = restTemplate.exchange(requestUrl, HttpMethod.GET, HttpEntity.EMPTY, reference); +// return this.getSuccessData(response.getBody()); +// } +// +// /** +// * 批量新增记录 +// * +// * @param appToken +// * @param tableId +// * @param saveReqDTO +// * @return +// */ +// public List insertBatchRecords(final String appToken, final String tableId, final TableRecordSaveReqDTO saveReqDTO) { +// synchronized (tableId.intern()) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/records/batch_create", appToken, tableId); +// return this.syncBatchRecords(url, saveReqDTO); +// } +// } +// +// /** +// * 批量更新 +// * +// * @param appToken +// * @param tableId +// * @param saveReqDTO +// * @return +// */ +// public List updateBatchRecords(final String appToken, final String tableId, final TableRecordSaveReqDTO saveReqDTO) { +// synchronized (tableId.intern()) { +// final String url = String.format(BASE_URL + "/v1/apps/%s/tables/%s/records/batch_update", appToken, tableId); +// return this.syncBatchRecords(url, saveReqDTO); +// } +// } +// +// /** +// * 批量同步记录 +// * +// * @param url +// * @param saveReqDTO +// * @return +// */ +// private List syncBatchRecords(final String url, final TableRecordSaveReqDTO saveReqDTO) { +// /** +// *飞书更新数据内部逻辑是异步操作,下次更新时会触发同步处理,可能会产生上次数据未处理完的问题,产生try again later +// * 加上重试处理 +// */ +// // 最大重试次数 +// final int maxRetry = 3; +// // 间隔时间3秒 +// int interval = 3000; +// for (int i = 0; i <= maxRetry; i++) { +// try { +// return this.saveBatchRecords(saveReqDTO, url); +// } catch (FeishuException e) { +// if (i == maxRetry || Strings.isNotEquals(FeishuErrorCodeEnum.TRY_AGAIN_LATER.getCode(), e.getCode())) { +// throw e; +// } +// log.info("飞书更新记录异常,进行重试处理, url={}", url); +// ThreadUtil.sleep(interval * (i + 1)); +// } +// } +// return new ArrayList<>(); +// } +// +// /** +// * 批量保存记录 +// * +// * @param saveReqDTO +// * @param url +// * @return +// */ +// private List saveBatchRecords(final TableRecordSaveReqDTO saveReqDTO, final String url) { +// final ParameterizedTypeReference>>> reference = new ParameterizedTypeReference>>>() { +// }; +// final HttpEntity httpEntity = new HttpEntity<>(saveReqDTO); +// final ResponseEntity>>> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, reference); +// final Map> responseBody = this.getSuccessData(response.getBody()); +// return responseBody.get("records"); +// } +// +// +// /** +// * 获取成功数据 +// * +// * @param resp +// * @param +// * @return +// */ +// private T getSuccessData(final Resp resp) { +// if (!Resp.isSuccess(resp)) { +// log.warn("飞书接口响应 --> {}", JSONUtil.toJsonStr(resp)); +// throw new FeishuException(FeishuErrorCodeEnum.TABLE_ERROR, "飞书接口响应异常:" + resp.getMsg()); +// } +// return resp.getData(); +// } +// +// /** +// * 构建restTemplate +// */ +// private void buildRestTemplate() { +// this.restTemplate = new RestTemplate(AuthApiService.REQUEST_FACTORY); +// this.restTemplate.setErrorHandler(new ResponseErrorHandler() { +// @Override +// public boolean hasError(final ClientHttpResponse response) throws IOException { +// return response.getStatusCode() != HttpStatus.OK; +// } +// +// @Override +// public void handleError(final ClientHttpResponse response) throws IOException { +// final String body = IoUtil.read(response.getBody(), StandardCharsets.UTF_8); +// final String logId = response.getHeaders().getFirst("x-tt-logid"); +// final int statusCode = response.getRawStatusCode(); +// log.warn("飞书接口响应异常 --> status:{}, body: {}, x-tt-logid:{}", statusCode, body, logId); +// if (HttpStatus.FORBIDDEN == response.getStatusCode()) { +// throw new FeishuException(FeishuErrorCodeEnum.TABLE_ERROR, "无权限操作,请设置多维表格应用权限"); +// } +// // 504响应码转换 +// if (Strings.isNotBlank(body)) { +// final Resp resp = JSONUtil.toBean(body, Resp.class); +// if (RETRY_ERROR_CODES.contains(resp.getCode())) { +// // 飞书接口响应please try again later +// throw new FeishuException(FeishuErrorCodeEnum.TRY_AGAIN_LATER, "飞书接口响应出错:" + resp.getMsg()); +// } +// } +// if (HttpStatus.OK != response.getStatusCode()) { +// throw new FeishuException(FeishuErrorCodeEnum.TABLE_ERROR, "飞书接口响应出错:" + body); +// } +// } +// }); +// // 拦截器 +// final ClientHttpRequestInterceptor interceptor = (request, body, execution) -> { +// final String tenantAccessToken = "Bearer " + this.authApiService.getTenantAccessToken(); +// final String requestBody = body.length > MAX_IGNORE_RESP_BYTES ? "ignore..." : new String(body, StandardCharsets.UTF_8); +// log.info("请求飞书接口,{} url={}, token={}, body={}", request.getMethod().name(), request.getURI().getRawPath(), tenantAccessToken, requestBody); +// // 添加请求头 +// request.getHeaders().add(HttpHeaders.AUTHORIZATION, tenantAccessToken); +// final ClientHttpResponse response = execution.execute(request, body); +// return response; +// }; +// this.restTemplate.setInterceptors(Lists.asList(interceptor)); +// } +// +// +//} diff --git a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/common/constant/FeishuErrorCodeEnum.java b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/common/constant/FeishuErrorCodeEnum.java index 58e5ee8..ddceb1a 100644 --- a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/common/constant/FeishuErrorCodeEnum.java +++ b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/common/constant/FeishuErrorCodeEnum.java @@ -1,6 +1,5 @@ package io.fluent.wrappers.feishu.common.constant; -import com.cloudminds.data.smith.exception.ICode; /** * 飞书错误码 @@ -8,7 +7,7 @@ * @author Tao.Liu * @date 2021/12/9 14:50 */ -public enum FeishuErrorCodeEnum implements ICode { +public enum FeishuErrorCodeEnum { TABLE_ERROR("smith.feishu_table_error", "飞书接口响应异常"), TRY_AGAIN_LATER("cade.feishu_try_again_later", "请求超时,请稍后重试"), @@ -29,12 +28,10 @@ public enum FeishuErrorCodeEnum implements ICode { } - @Override public String getCode() { return this.code; } - @Override public String getMessage() { return this.message; } diff --git a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/common/exception/FeishuException.java b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/common/exception/FeishuException.java index cb9d156..c0f746d 100644 --- a/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/common/exception/FeishuException.java +++ b/fluent-wrappers/fluent-feishu/src/main/java/io/fluent/wrappers/feishu/common/exception/FeishuException.java @@ -1,8 +1,7 @@ package io.fluent.wrappers.feishu.common.exception; -import com.cloudminds.data.smith.exception.BaseServiceException; -import com.cloudminds.data.smith.exception.ServiceCodeEnum; -import com.cloudminds.data.smith.external.feishu.common.constant.FeishuErrorCodeEnum; + +import io.fluent.wrappers.feishu.common.constant.FeishuErrorCodeEnum; /** * 飞书异常 @@ -10,12 +9,9 @@ * @author Tao.Liu * @date 2022/6/30 10:28 */ -public class FeishuException extends BaseServiceException { +public class FeishuException extends RuntimeException { private static final long serialVersionUID = -1191541920182893393L; - public FeishuException(final FeishuErrorCodeEnum codeEnum, final String message) { - super(ServiceCodeEnum.EXTERNAL_SYSTEM_ERROR, codeEnum, message); - } } diff --git a/pom.xml b/pom.xml index 1f3e68d..4777be7 100644 --- a/pom.xml +++ b/pom.xml @@ -24,7 +24,7 @@ - 1.12.10 + 1.12.11 1.0-SNAPSHOT 42.5.1 UTF-8 diff --git a/references.yaml b/references.yaml index 598ca64..570e35c 100644 --- a/references.yaml +++ b/references.yaml @@ -164,6 +164,9 @@ products: self-hosts: - https://github.com/dronahq/self-hosted.git +agile/NPM: + + solutions: - name: cal repos: diff --git a/scripts/jaxb-ri/LICENSE.txt b/scripts/jaxb-ri/LICENSE.txt new file mode 100644 index 0000000..da1c1ce --- /dev/null +++ b/scripts/jaxb-ri/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Eclipse Foundation, Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/scripts/jaxb-ri/bin/schemagen.bat b/scripts/jaxb-ri/bin/schemagen.bat new file mode 100644 index 0000000..5a27fe2 --- /dev/null +++ b/scripts/jaxb-ri/bin/schemagen.bat @@ -0,0 +1,65 @@ +@echo off + +REM +REM Copyright (c) 1997, 2022 Oracle and/or its affiliates. All rights reserved. +REM +REM This program and the accompanying materials are made available under the +REM terms of the Eclipse Distribution License v. 1.0, which is available at +REM http://www.eclipse.org/org/documents/edl-v10.php. +REM +REM SPDX-License-Identifier: BSD-3-Clause +REM + +rem +rem Make sure that JAXB_HOME and JAVA_HOME are set +rem +if not "%JAXB_HOME%" == "" goto SETMODULEPATH + +rem Try to locate JAXB_HOME +set JAXB_HOME=%~dp0 +set JAXB_HOME=%JAXB_HOME%\.. +if exist %JAXB_HOME%\mod\jaxb-xjc.jar goto SETMODULEPATH + +rem Unable to find it +echo JAXB_HOME must be set before running this script +goto END + +:SETMODULEPATH +rem JXC module path +set JAXB_PATH=^ +%JAXB_HOME%/mod/jakarta.xml.bind-api.jar;^ +%JAXB_HOME%/mod/jaxb-jxc.jar;^ +%JAXB_HOME%/mod/jaxb-xjc.jar;^ +%JAXB_HOME%/mod/jaxb-impl.jar;^ +%JAXB_HOME%/mod/jaxb-core.jar;^ +%JAXB_HOME%/mod/jakarta.activation-api.jar + +if "%CLASSPATH%" == "" goto NOUSERCLASSPATH +set LOCALMODULEPATH=%JAXB_PATH%;%CLASSPATH% +goto CHECKJAVAHOME + +:NOUSERCLASSPATH +set LOCALMODULEPATH=%JAXB_PATH% +goto CHECKJAVAHOME + +:CHECKJAVAHOME +if not "%JAVA_HOME%" == "" goto USE_JAVA_HOME + +set JAVA=java +goto LAUNCHSCHEMAGEN + +:USE_JAVA_HOME +set JAVA="%JAVA_HOME%\bin\java" +goto LAUNCHSCHEMAGEN + +:LAUNCHSCHEMAGEN +if not "%SCHEMAGEN_OPTS%" == "" goto LAUNCHSCHEMAGENWITHOPTS +%JAVA% --module-path %LOCALMODULEPATH% --add-modules com.sun.xml.bind -m com.sun.tools.jxc %* +goto END + +:LAUNCHSCHEMAGENWITHOPTS +%JAVA% %SCHEMAGEN_OPTS% --module-path %LOCALMODULEPATH% --add-modules com.sun.xml.bind -m com.sun.tools.jxc %* +goto END + +:END +%COMSPEC% /C exit %ERRORLEVEL% diff --git a/scripts/jaxb-ri/bin/schemagen.sh b/scripts/jaxb-ri/bin/schemagen.sh new file mode 100755 index 0000000..c3182a1 --- /dev/null +++ b/scripts/jaxb-ri/bin/schemagen.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# +# Copyright (c) 1997, 2022 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# +# Make sure that JAXB_HOME and JAVA_HOME are set +# +if [ -z "$JAXB_HOME" ] +then + # search the installation directory + + PRG=$0 + progname=`basename $0` + saveddir=`pwd` + + cd `dirname $PRG` + + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '.*/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname $PRG`/$link" + fi + done + + JAXB_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + cd "$saveddir" + JAXB_HOME=`cd "$JAXB_HOME" && pwd` + + cd $saveddir +fi + +#JXC module path +JAXB_PATH=${JAXB_HOME}/mod/jakarta.xml.bind-api.jar:\ +${JAXB_HOME}/mod/jaxb-jxc.jar:\ +${JAXB_HOME}/mod/jaxb-xjc.jar:\ +${JAXB_HOME}/mod/jaxb-impl.jar:\ +${JAXB_HOME}/mod/jaxb-core.jar:\ +${JAXB_HOME}/mod/jakarta.activation-api.jar + +# add the api jar file +if [ -n ${CLASSPATH} ] ; then + LOCALPATH=${JAXB_PATH}:"${CLASSPATH}" +else + LOCALPATH=${JAXB_PATH} +fi + +if [ -n "$JAVA_HOME" ] +then + JAVA="$JAVA_HOME"/bin/java +else + JAVA=java +fi +[ `expr \`uname\` : 'CYGWIN'` -eq 6 ] && +{ + LOCALPATH=`cygpath -w -p ${LOCALPATH}` +} + +if [ `expr \`uname\` : 'CYGWIN'` -eq 6 ] +then + JAXB_HOME="`cygpath -w "$JAXB_HOME"`" +fi + +exec "${JAVA}" ${SCHEMAGEN_OPTS} --module-path "${LOCALPATH}" --add-modules com.sun.xml.bind -m com.sun.tools.jxc "$@" diff --git a/scripts/jaxb-ri/bin/schemagend.sh b/scripts/jaxb-ri/bin/schemagend.sh new file mode 100755 index 0000000..884920d --- /dev/null +++ b/scripts/jaxb-ri/bin/schemagend.sh @@ -0,0 +1,73 @@ +#!/bin/sh +x +# +# Copyright (c) 1997, 2022 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# +# Make sure that JAXB_HOME and JAVA_HOME are set +# +if [ -z "$JAXB_HOME" ] +then + # search the installation directory + + PRG=$0 + progname=`basename $0` + saveddir=`pwd` + + cd `dirname $PRG` + + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '.*/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname $PRG`/$link" + fi + done + + JAXB_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + cd "$saveddir" + JAXB_HOME=`cd "$JAXB_HOME" && pwd` + + cd $saveddir +fi + +#JXC module path +JAXB_PATH=${JAXB_HOME}/mod/jakarta.xml.bind-api.jar:\ +${JAXB_HOME}/mod/jaxb-jxc.jar:\ +${JAXB_HOME}/mod/jaxb-xjc.jar:\ +${JAXB_HOME}/mod/jaxb-impl.jar:\ +${JAXB_HOME}/mod/jaxb-core.jar:\ +${JAXB_HOME}/mod/jakarta.activation-api.jar + +# add the api jar file +if [ -n ${CLASSPATH} ] ; then + LOCALPATH=${JAXB_PATH}:"${CLASSPATH}" +else + LOCALPATH=${JAXB_PATH} +fi + +if [ -n "$JAVA_HOME" ] +then + JAVA="$JAVA_HOME"/bin/java +else + JAVA=java +fi + +DEBUG_OPTS="-Djava.compiler=NONE -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8000" + +if [ `expr \`uname\` : 'CYGWIN'` -eq 6 ] +then + JAXB_HOME="`cygpath -w "$JAXB_HOME"`" +fi + +exec "${JAVA}" $DEBUG_OPTS ${SCHEMAGEN_OPTS} --module-path "${LOCALPATH}" --add-modules com.sun.xml.bind -m com.sun.tools.jxc "$@" diff --git a/scripts/jaxb-ri/bin/xjc.bat b/scripts/jaxb-ri/bin/xjc.bat new file mode 100644 index 0000000..b72df4a --- /dev/null +++ b/scripts/jaxb-ri/bin/xjc.bat @@ -0,0 +1,53 @@ +@echo off + +REM +REM Copyright (c) 1997, 2022 Oracle and/or its affiliates. All rights reserved. +REM +REM This program and the accompanying materials are made available under the +REM terms of the Eclipse Distribution License v. 1.0, which is available at +REM http://www.eclipse.org/org/documents/edl-v10.php. +REM +REM SPDX-License-Identifier: BSD-3-Clause +REM + +rem +rem Make sure that JAXB_HOME and JAVA_HOME are set +rem +if not "%JAXB_HOME%" == "" goto SETMODULEPATH + +rem Try to locate JAXB_HOME +set JAXB_HOME=%~dp0 +set JAXB_HOME=%JAXB_HOME%\.. +if exist "%JAXB_HOME%\mod\jaxb-xjc.jar" goto SETMODULEPATH + +rem Unable to find it +echo JAXB_HOME must be set before running this script +goto END + +:SETMODULEPATH +rem XJC module path +set JAXB_PATH=^ +%JAXB_HOME%/mod/jakarta.xml.bind-api.jar;^ +%JAXB_HOME%/mod/jaxb-xjc.jar;^ +%JAXB_HOME%/mod/jaxb-core.jar;^ +%JAXB_HOME%/mod/jaxb-impl.jar;^ +%JAXB_HOME%/mod/jakarta.activation-api.jar +goto CHECKJAVAHOME + +:CHECKJAVAHOME +if not "%JAVA_HOME%" == "" goto USE_JAVA_HOME + +set JAVA=java +goto LAUNCHXJC + +:USE_JAVA_HOME +set JAVA="%JAVA_HOME%\bin\java" +goto LAUNCHXJC + +:LAUNCHXJC +rem module path +%JAVA% --module-path %JAXB_PATH% --add-modules com.sun.xml.bind %XJC_OPTS% -m com.sun.tools.xjc %* +GOTO END + +:END +%COMSPEC% /C exit %ERRORLEVEL% diff --git a/scripts/jaxb-ri/bin/xjc.sh b/scripts/jaxb-ri/bin/xjc.sh new file mode 100755 index 0000000..f0ea58d --- /dev/null +++ b/scripts/jaxb-ri/bin/xjc.sh @@ -0,0 +1,63 @@ +#!/bin/bash +# +# Copyright (c) 1997, 2022 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# +# Make sure that JAXB_HOME and JAVA_HOME are set +# +if [ -z "$JAXB_HOME" ] +then + # search the installation directory + + PRG=$0 + progname=`basename $0` + saveddir=`pwd` + + cd "`dirname $PRG`" + + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '.*/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname $PRG`/$link" + fi + done + + JAXB_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + cd "$saveddir" + JAXB_HOME=`cd "$JAXB_HOME" && pwd` + + cd "$saveddir" +fi + +[ `expr \`uname\` : 'CYGWIN'` -eq 6 ] && +{ + JAXB_HOME=`cygpath -w "$JAXB_HOME"` +} + +if [ -n "$JAVA_HOME" ] +then + JAVA="$JAVA_HOME/bin/java" +else + JAVA=java +fi + +#XJC module path +JAXB_PATH=${JAXB_HOME}/mod/jaxb-xjc.jar:\ +${JAXB_HOME}/mod/jakarta.xml.bind-api.jar:\ +${JAXB_HOME}/mod/jaxb-core.jar:\ +${JAXB_HOME}/mod/jaxb-impl.jar:\ +${JAXB_HOME}/mod/jakarta.activation-api.jar:\ + +exec "${JAVA}" --module-path "${JAXB_PATH}" --add-modules com.sun.xml.bind ${XJC_OPTS} -m com.sun.tools.xjc "$@" diff --git a/scripts/jaxb-ri/docs/LICENSE.md b/scripts/jaxb-ri/docs/LICENSE.md new file mode 100644 index 0000000..14bdf73 --- /dev/null +++ b/scripts/jaxb-ri/docs/LICENSE.md @@ -0,0 +1,28 @@ +Copyright (c) 2017 Oracle and/or its affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Eclipse Foundation, Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/scripts/jaxb-ri/docs/ch01.html b/scripts/jaxb-ri/docs/ch01.html new file mode 100644 index 0000000..079f740 --- /dev/null +++ b/scripts/jaxb-ri/docs/ch01.html @@ -0,0 +1,174 @@ + + + OverviewLinks: Table of Contents | Single HTML | Single PDF

Overview

Jakarta XML Binding + provides an API and tools that automate the mapping between XML documents + and Java objects.

The Jakarta XML Binding framework enables developers to perform the following + operations:

  • Unmarshal XML content into + a Java representation

  • Access and update the Java representation

  • Marshal the Java + representation of the XML content into XML content

Jakarta XML Binding gives Java developers an efficient and standard way of mapping + between XML and Java code. Java developers using Jakarta XML Binding are more productive + because they can write less code themselves and do not have to be experts + in XML. Jakarta XML Binding makes it easier for developers to extend their applications + with XML and Web Services technologies.

1. Documentation

Documentation for this release consists of the following:

2. Software Licenses

3. Sample Apps

This page summarizes basic use-cases for Java-2-Schema, + Schema-2-Java, and lists all of the sample applications that ship with + JAXB.

3.1. Using the Runtime Binding Framework

3.1.1. Schema-2-Java

Schema-2-Java is the process of compiling one or more schema + files into generated Java classes. Here are some of the basic + steps for developing an app:

  1. Develop/locate your schema

  2. Annotate the schema with binding customizations if + necessary (or place them in an external bindings + file)

  3. Compile the schema with the XJC binding + compiler

  4. Develop your JAXB client application using the Java + content classes generated by the XJC binding compiler + along with the jakarta.xml.bind runtime + framework

  5. Set your CLASSPATH to include all + of the Identifying the JAR Files

  6. Compile all of your Java sources with + javac

  7. Run it!

3.1.2. Java-2-Schema

Java-2-Schema is the process of augmenting existing Java + classes with the annotations defined in the + jakarta.xml.bind.annotation package so that the JAXB + runtime binding framework is capable of performing the (un)marshal + operations. Here are the basic steps for developing an app:

  1. Develop your data model in Java

  2. Apply the jakarta.xml.bind.annotation + annotations to control the binding process

  3. Set your CLASSPATH to include all + of the Identifying the JAR Files

  4. Compile your data model with + javac

    Important

    Make sure that you CLASSPATH + includes jaxb-xjc.jar before + running javac.

  5. The resulting class files will contain your + annotations as well other default annotations needed by + the JAXB runtime binding framework

  6. Develop your client application that uses the data + model and develop the code that uses the JAXB runtime + binding framework to persist your data model using the + (un)marshal operations.

  7. Compile and run your client application!

For more information about this process, see the the Java + WSDP Tutorial and the extensive Sample Apps + documentation.

3.1.3. Building and Running the Sample Apps with Ant

To run the sample applications, add jaxb dependencies + to classpath at jaxb.home property, and run ant + without any option into each sample directory.

A few sample applications do not use + Ant. For those samples, refer to the included + readme.txt files for instructions.

3.1.4. List of Sample Apps

samples/catalog-resolver

This example demonstrates how to use the + -catalog compiler switch to handle + references to schemas in external web sites.

samples/character-escape

This example shows how you can use the new JAXB + RI Marshaller property + org.glassfish.jaxb.characterEscapeHandler + to change the default character escaping + behavior.

samples/class-resolver

This little DI-container-by-JAXB example + demonstrates how one can avoid passing in a list of + classes upfront, and instead load classes + lazily.

samples/create-marshal

This sample application demonstrates how to use + the ObjectFactory class to create a + Java content tree from scratch and marshal it to XML + data. It also demonstrates how to add content to a + JAXB List property.

samples/cycle-recovery

Eclipse Implementation of JAXB's vendor extension + CycleRecoverable provides + application a hook to handle cycles in the object + graph. Advanced.

samples/datatypeconverter

This sample application is very similar to the + inline-customize sample application (formerly + SampleApp6), but + illustrates an easier, but not as robust, + <jaxb:javaType> + customization.

samples/dtd

This sample application illustrate some of the + DTD support available in the Eclipse Implementation of JAXB's extension mode. + Please refer to the Eclipse Implementation of JAXB Extensions page for more + detail.

samples/element-substitution

This sample application illustrates how W3C XML + Schema substitution groups are supported in Eclipse Implementation of JAXB's + extension mode. Please refer to the Eclipse Implementation of JAXB Extensions page for more + detail.

samples/external-customize

This sample application is identical to the + datatypeconverter sample + application (formerly + SampleApp7) except that the + binding customizations are contained in an external + binding file.

samples/fix-collides

Another binding customization example that + illustrates how to resolve name conflicts. Running + this sample without the binding file will result in + name collisions (see readme.txt) + . Running ant will use the + binding customizations to resolve the name conflicts + while compiling the schema.

samples/inline-customize

This sample application demonstrates how to + customize the default binding produced by the XJC + binding compiler.

samples/j2s-crete-marshal

This sample application demonstrates + marshalling, unmarshalling and unmarshal validation + with existing Java classes annotated with JAXB + annotations.

samples/j2s-xmlAccessorOrder

This sample application demonstrates the use of + mapping annotations + @XmlAccessorOrder and + @XmlType.propOrder in Java classes + for ordering properties and fields in Java to schema + bindings.

samples/j2s-xmlAdapter

This sample application demonstrates the use of + interface XmlAdapter and annotation + XmlJavaTypeAdapter for custom + marshaling/unmarshaling XML content into/out of a Java + type.

samples/j2s-xmlAttribute

This sample application demonstrates the use of + annotation @XmlAttribute for + defining Java properties and fields as XML + attributes.

samples/j2s-xmlRootElement

This sample application demonstrates the use of + annotation @XmlRootElement to + define a class to be an XML element.

samples/j2s-xmlSchematType

This sample application demonstrates the use of + annotation @XmlSchemaType to + customize the mapping of a property or field to an XML + built-in type.

samples/j2s-xmlType

This sample application demonstrates the use of + mapping annotations + @XmlAccessorOrder and + @XmlType.propOrder in Java classes + for ordering properties and fields in Java to schema + bindings.

samples/locator-support

This sample shows how to use the new + non-standard locator support. By following the + instructions in the readme.txt file, you can cause all + of the generated impl classes to implement a new + interface that provides more information about error + locations. When a ValidationEvent + happens on your content tree, simply retrieve the + object and cast it down to + com.sun.xml.bind.extra.Locatable.

samples/modify-marshal

This sample application demonstrates how to + modify a java content tree and marshal it back to XML + data.

samples/namespace-prefix

This sample application demonstrates how to use + the new Eclipse Implementation of JAXB Marshaller property + org.glassfish.jaxb.namespacePrefixMapper + to customize the namespace prefixes generated during + marshalling.

samples/partial-unmarshalling

In this example, the input document will be + unmarshalled a small chunk at a time, instead of + unmarshalling the whole document at once.

samples/pull-parser

This sample app demonstrates how a pull-parser + can be used with JAXB to increase the flexibility of + processing.

samples/streaming-unmarshalling

This example illustrates a different approach to + the streaming unmarshalling, which is suitable for + processing a large document.

samples/synchronized-methods

This sample shows how to use the new + non-standard synchronized method support. By following + the instructions in the + readme.txt, you can cause all of + the generated impl class methods signatures to contain + the synchronized keyword.

samples/type-substitution

This sample app demonstrates type substitution + using the W3C XML Schema Part 0: Primer international + purchase order schema.

samples/ubl

This project processes a UBL (Universal Business + Language) order instance and prints a report to the + screen.

samples/unmarshal-read

This sample application demonstrates how to + unmarshal an instance document into a Java content + tree and access data contained within it.

samples/unmarshal-validate

This sample application demonstrates how to + enable validation during the unmarshal + operations.

samples/updateablePartialBind

This sample application demonstrates how to + partially map a DOM tree to JAXB (using JAXP 1.3 + XPath), modify JAXB mapped instance and then update + modifications back to the DOM tree.

samples/vendor-extensions

This example demonstrates how to use + <xjc:superClass> vendor + extensions provided by Eclipse Implementation of JAXB's, as well as + <jaxb:serializable> + customization.

samples/xml-channel

This example demonstrates how one can use one + communication channel (such as a socket) to send + multiple XML messages, and how it can be combined with + JAXB.

samples/xml-stylesheet

A common customization need for the marshalling + output is about introducing extra processing + instruction and/or DOCTYPE + declaration. This example demonstrates how such + modification can be done easily.

\ No newline at end of file diff --git a/scripts/jaxb-ri/docs/ch02.html b/scripts/jaxb-ri/docs/ch02.html new file mode 100644 index 0000000..399fdda --- /dev/null +++ b/scripts/jaxb-ri/docs/ch02.html @@ -0,0 +1,70 @@ + + + Release NotesLinks: Table of Contents | Single HTML | Single PDF

Release Notes

This document contains information that should help you use this + software library more effectively. See the + Frequently Asked Questions + for additional information. +

The most up-to-date version of this document can be found on-line. +

1.  + Java™ SE Requirements +

This release of the Eclipse Implementation of JAXB requires Java SE 11 or higher.

2. Identifying the JAR Files

Use

Description

Jar

Runtime

Jars required to deploy a Jakarta XML Binding client

jakarta.activation-api.jar

angus-activation.jar

jakarta.xml.bind-api.jar

jaxb-core.jar

jaxb-impl.jar

Compiler

Jars required at your development environment (but not runtime)

jaxb-jxc.jar

jaxb-xjc.jar

3. Identifying the JPMS module names

Jar

Module name

Maven GAV

jakarta.activation-api.jar

jakarta.activation

jakarta.activation:jakarta.activation-api

angus-activation.jar

com.sun.activation.registries

org.eclipse.angus:angus-activation

jakarta.xml.bind-api.jar

jakarta.xml.bind

jakarta.xml.bind:jakarta.xml.bind-api

jaxb-core.jar

com.sun.xml.bind.core

com.sun.xml.bind:jaxb-core

jaxb-impl.jar

com.sun.xml.bind

com.sun.xml.bind:jaxb-impl

jaxb-jxc.jar

com.sun.tools.jxc

com.sun.xml.bind:jaxb-jxc

jaxb-xjc.jar

com.sun.tools.xjc

com.sun.xml.bind:jaxb-xjc

4. Locating the Normative Binding Schema

You may find information about the normative binding schema + defined in the Jakarta XML Binding Specification at https://jakarta.ee/xml/ns/jaxb. +

5. Changelog

The Eclipse Implementation of JAXB 4.x meets the requirements of the Jakarta XML Binding 4.x specifications.

5.1. Changes in 4.0.0 - initial release for Jakarta EE 10

  • Requires Java SE 11 or newer

  • Supports usage of JAXB 2.x schema bindings customizations

  • Bug fixes: +

    • Fix equality on BISerializable

    • + #936: problem with XMLMixed in a tag annotated XmlAnyElement +

    • + #971: annotation @XmlJavaTypeAdapters on package is ignored since JAXB v2.2.4-1 +

    • + #1053: Use Java 7 diamond operator +

    • + #1117: xjc-generated classes may have methods with missing @param or @return +

    • + #1489: DOMScanner ignores default namespace at scan method +

    • + #1499: xjc - NGCCRuntimeEx.resolveRelativeURL(String namespaceURI, String relativeUri ) doesn't work as it should +

    • + #1505: JCodeModel.parseType(String) silently ignores type params in specific scenarios +

    • + #1590: Marshalling an object that overrides the parent's method, + the XML that gets created contains both child's and parent's tag +

    • + #1599: XNOR implementation in NameUtil is called "xor" +

    • + #1624: Order of Exceptions in generated classes is non-deterministic +

    • + #1631: Support setting (un)marshaller listener on binder +

    +

5.2. Changes between 3.0.1 and 3.0.2

  • Bug fixes: +

    • Fixed classloading in OSGI

    • + #1547: Running with -XX:-StackTraceInThrowable causes a index out of bounds exception +

    • + #1556: xjc generates class reference with generics +

    +

5.3. Changes between 3.0.0 and 3.0.1

  • Bug fixes: +

    • + #1105: xjc mark-generated sometimes produces a wrong date value +

    • + #1466: ContextFinder always load the JAXBContext from jaxb-runtime 2.3.3 +

    • + #1475: xjc: Option to generate old package names +

    • + #1502: XJC: fails to process XSD files without systemId. +

    +

5.4. Changes in 3.0.0 - initial release for Jakarta EE 9

  • Requires Java SE 8 or newer

  • Adopts new API package namespace - jakarta.xml.bind.*

  • Main implementation jar split into two parts - jaxb-core and (smaller) jaxb-impl

  • Content of the new jaxb-impl moved from com.sun.xml.bind package to org.glassfish.jaxb.runtime package +

  • Content of the new jaxb-core moved from com.sun.xml.bind package to org.glassfish.jaxb.core package

  • Changed prefix of all properties from com.sun.xml.bind to org.glassfish.jaxb

  • Supports new namespace for schema customizations +

    <bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0">...</bindings>

    +

5.5. Changes in 2.3.2 - initial release for Jakarta EE 8

  • First release under Eclipse Jakarta EE Platform: +

    • Uptake of moved Jakarta APIs.

    +

\ No newline at end of file diff --git a/scripts/jaxb-ri/docs/ch03.html b/scripts/jaxb-ri/docs/ch03.html new file mode 100644 index 0000000..7a8b056 --- /dev/null +++ b/scripts/jaxb-ri/docs/ch03.html @@ -0,0 +1,1681 @@ + + + Eclipse Implementation of JAXB Users GuideLinks: Table of Contents | Single HTML | Single PDF

Eclipse Implementation of JAXB Users Guide

Abstract

This document explains various interesting/complex/tricky + aspects of Eclipse Implementation of JAXB, based on questions posted on the old JAXB + users forum and answers provided there. This is an ongoing + work-in-progress. Any feedback + appreciated.

1. Compiling XML Schema

1.1. Dealing with errors

1.1.1. Schema errors

Because XML Schema is so complicated, and because there are a + lot of tools out there do not implement the spec correctly, it is + often the case that a schema you are trying to compile has some real + errors in it. When this is the case, you'll see XJC reporting somewhat + cryptic errors such as rcase-RecurseLax.2: There is not a + complete functional mapping between the particles.

The Eclipse Implementation of JAXB uses the schema correctness checker from the + underlying JAXP implementation, which is the JAXP RI in a typical + setup. The JAXP RI is one of the most conformant schema validators, + and therefore most likely correct. So the first course of action + usually is to fix problems in the schema.

However, in some situations, you might not have an authority to + make changes to the schema. If that is the case and you really need to + compile the schema, you can bypass the correctness check by using the + -nv option in XJC. When you do this, keep in mind + that you are possibly feeding "garbage" in, so you may see XJC choke + with some random exception.

1.1.2. Property 'fooBarZot' is already defined

One of the typical errors you'll see when compiling a complex + schema is:

Example 1. Multiple property definitions error

parsing a schema...
+[ERROR] Property "MiOrMoOrMn" is already defined.
+  line 132 of
+file:/C:/kohsuke/Sun/JAXB/jaxb-unit/schemas/individual/MathML2/presentation/scripts.xsd
+
+[ERROR] The following location is relevant to the above error
+  line 138 of
+file:/C:/kohsuke/Sun/JAXB/jaxb-unit/schemas/individual/MathML2/presentation/scripts.xsd

This is an actual example of the offending part of a schema, + taken from MathML. If you go to line 132 of + scripts.xsd, you'll see that it has a somewhat + complicated content model definition:

Example 2. Multiple property definitions in MathML

<xs:group name="mmultiscripts.content">
+    <xs:sequence>
+        <xs:group ref="Presentation-expr.class"/>
+        <xs:sequence minOccurs="0" maxOccurs="unbounded">      <!-- line 132 -->
+            <xs:group ref="Presentation-expr-or-none.class"/>
+            <xs:group ref="Presentation-expr-or-none.class"/>
+        </xs:sequence>
+        <xs:sequence minOccurs="0">
+            <xs:element ref="mprescripts"/>
+            <xs:sequence maxOccurs="unbounded">                 <!-- line 138 -->
+                <xs:group ref="Presentation-expr-or-none.class"/>
+                <xs:group ref="Presentation-expr-or-none.class"/>
+            </xs:sequence>
+        </xs:sequence>
+    </xs:sequence>
+</xs:group>

This is a standard technique in designing a schema. When you + want to say "in this element, B can occur arbitrary + times, but C can occur only up to once", you write + this as B*,(C,B*)?. This, however, confuses Eclipse Implementation of JAXB, + because it tries to bind the first B to its own + property, then C to its own property, then the + second B to its own property, and so we end up + having a collision again.

In this particular case, B isn't a single + element but it's a choice of large number of elements abstracted away + in <xs:group>s, so they are hard to see. But + if you see the same content model referring to the same element/group + twice in a different place, you can suspect this.

In this case, you'd probably want the whole thing to map to a + single list so that you can retain the order those elements show up in + the document. You can do this by putting the same + <jaxb:property> customization on the whole + "mmultiscripts.content" model group, like this (or + you can do it externally with XPath):

Example 3. How to fix the problem?

<xs:groupname="mmultiscripts.content">
+<xs:annotation>
+    <xs:appinfo>
+        <jaxb:propertyname="content"/>
+    </xs:appinfo>
+</xs:annotation>
+<xs:sequence>
+<xs:groupref="Presentation-expr.class"/>

Another way to fix this problem is to use the + simpler and better binding mode in XJC, which is a Eclipse Implementation of JAXB + vendor extension.

1.1.3. Two declarations cause a collision in the ObjectFactory + class

When schemas contain similar looking element/type names, they + can result in "Two declarations cause a collision in the ObjectFactory + class" errors. To be more precise, for each of all types and many + elements (exactly what elements get a factory and what doesn't is bit + tricky to explain), XJC produces one method on the + ObjectFactory class in the same package. The + ObjectFactory class is created for each package that XJC + generates some files into. The name of the method is derived from XML + element/type names, and the error is reported if two elements/types + try to generate the same method name.

There are two approaches to fix this problem. If the collision + is coming from two different schemas with different target namespaces, + then you can easily avoid the collision by compiling them into + different Java packages. To do this, use <schemabindings> + customization on two schemas and specify the package name.

Another way to fix this problem is to use <factoryMethod> + customization on two conflicting elements/types to specify different + factory method names. This can be used in all cases, but if you have a + large number of conflicts, you'll have to specify this customization + one by one.

Notice that <class> + customization doesn't affect the ObjectFactory method + name by itself.

1.1.4. Customization errors

1.1.4.1. XPath evaluation of ... results in empty target + node

External Jakarta XML Binding customizations are specified by using XPath + (or using SCD.) + This works by writing an XPath expression that matches a + particular element in the schema document. For example, given the + following schema and binding file:

Example 4. Schema and external binding file

test.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+    <xs:complexTypename="foo"/>
+</xs:schema>

test.xjb

<bindings version="3.0" xmlns="https://jakarta.ee/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+    <bindings schemaLocation="test.xsd">
+        <bindings node="//xs:complexType[@name='foo']">
+            <classname="Bar"/>
+        </bindings>
+    </bindings>
+</bindings>

will be interpreted as if the class customization is + attached to the complex type 'foo'.

For this to work, the XPath expression needs to match one + and only one element in the schema document. When the XPath + expression is incorrect and it didn't match anything, you get this + "XPath evaluation of ... results in empty target node" + problem.

Common causes of this problem include typos, incorrect + namespace URI declarations, and misunderstanding of XPath.

1.2. Fixing broken references in schema

Sometimes a schema may refer to another schema document without + indicating where the schema file can be found, like this:

Example 5. Schema reference without location

<xs:import namespace="http://www.w3.org/1999/xlink" />

In other cases, a schema may refer to another schema on the network, + which often slows down your compilation process and makes it unreliable. + Yet in some other cases, a schema may reference another schema in relative + path, and that may not match your directory structure.

XJC bundles a catalog + resolver so that you can work around these situations without + changing the schema documents. The main idea behind the catalog is + "redirection" --- when XJC is about to fetch resources, it will consult + the catalog resolver to see if it can find the resource elsewhere (which + is usually your local resources.)

1.2.1. Catalog format

The catalog resolver supports many different formats, but the + easiest one is a line based *.cat format. Other than + comments and empty lines, the file mainly consists of two kinds of + declarations, SYSTEM, and + PUBLIC.

Example 6. sample-catalog.cat

--
+  sample catalog file.
+
+  double hyphens are used to begin and end a comment section.
+--
+
+SYSTEM "http://www.w3.org/2001/xml.xsd" "xml.xsd"
+
+PUBLIC "-//W3C//DTD XMLSCHEMA 200102//EN" "s4s/XMLSchema.dtd"

1.2.2. Resolve by system ID

The SYSTEM entry has the format of "SYSTEM + REFERENCE ACTUAL-LOCATION", + which defines a simple redirection. Every time XJC loads any resource + (be it schemas, DTDs, any entities referenced within), it will first + resolve relative paths to absolute paths, then looks for a matching + REFERENCE line. If it is found, the specified + actual location is read instead. Otherwise XJC will attempt to resolve + the absolutepath.

ACTUAL-LOCATION above accepts relative + paths, and those are resolved against the catalog file itself (so in + the above example, xml.xsd is assumed to be in the same + directory with sample-catalog.cat.

What you need to be careful is the fact that the + REFERENCE portion must be absolute, and when XJC + finds a reference in schema, it will first convert that to the + absolute path before checking the catalog. So what this means is that + if your schema is written like this:

Example 7. Schema reference by relative path

<xs:import namespace="http://www.w3.org/1999/xlink" schemaLocation="xlink.xsd" />

Then your catalog entry would have to look like this:

Example 8. xlink.cat

-- this doesn't work because xlink.xsd will be turned into absolute path --
+SYSTEM "xlink.xsd" "http://www.w3.org/2001/xlink.xsd"
+
+-- this will work, assuming that the above schema is in /path/to/my/test.xsd --
+SYSTEM "/path/to/my/xlink.xsd" "http://www.w3.org/2001/xlink.xsd"

1.2.3. Resolve by public ID / namespace URI

Another kind of entry has the format of "PUBLIC + PUBLICID ACTUAL-LOCATION" or + "PUBLIC NAMESPACEURI + ACTUAL-LOCATION".

The "PUBLICID" version is used to resolve DTDs and entities in + DTDs. But this type of entry is also used to resolve <xs:import> + statements. XJC will match the value of the namespace attribute and + see if there's any matching entry. So given a schema like this:

Example 9. Schema import

<xs:import namespace="http://www.w3.org/1999/xlink" schemaLocation="xlink.xsd" />
+<xs:import namespace="http://www.w3.org/1998/Math/MathML" />

The following catalog entries will match them.

Example 10. by-publicid.cat

PUBLIC "http://www.w3.org/1999/xlink" "http://www.w3.org/2001/xlink.xsd"
+PUBLIC "http://www.w3.org/1998/Math/MathML" "/path/to/my/mathml.xsd"

As you can see, XJC will check the PUBLIC entries regardless of + whether <xs:import> has the schemaLocation attribute or not. As + with the case with the SYSTEM entry, the ACTUAL-LOCATION part can be + relative to the location of the catalog file.

1.2.4. Specifying the catalog file

Once you write a catalog file, you'd need to specify that when + you invoke XJC.

CLI

To do this from the CLI, use the -catalog option. See xjc + -help for more details.

Ant

Use the catalog attribute on the <xjc> task. + See XJC + ant task documentation for more details.

Maven

For the Maven + plugin, use the <catalog> element in the + configuration:

<plugin>
+    <groupId>org.jvnet.jaxb2.maven2</groupId>
+    <artifactId>maven-jaxb2-plugin</artifactId>
+    <configuration>
+        <!-- relative to the POM file -->
+        <catalog>mycatalog.cat</catalog>
+    </copnfiguration>
+</plugin>

1.2.5. Debugging catalog file

If you are trying to write a catalog file and banging your head + against a wall because it's not working, you should enable the verbose + option of the catalog resolver. How you do this depends on what + interface you use:

CLI

Specify export + XJC_OPTS="-Dxml.catalog.verbosity=999" then run + XJC.

Ant/Maven

Add -Dxml.catalog.verbosity=999 as a + command line option to Ant/Maven.

If you are otherwise invoking XJC programmatically, you can set + the above system property before invoking XJC.

1.3. Mapping of <xs:any />

XJC binds <xs:any /> in the following ways:

1.3.1. processContents="skip"

<xs:any /> with processContents=skip means + any well-formed XML elements can be placed. Therefore, XJC binds this + to DOM Element interface.

Example 11. Any/Skip schema

<xs:element name="person">
+  <xs:complexType>
+    <xs:sequence>
+      <xs:element name="name" type="xs:string" />
+      <xs:any processContents="skip" maxOccurs="unbounded" minOccurs="0" />
+    </xs:sequence>
+  </xs:complexType>
+</xs:element>

Example 12. Any/Skip binding

import org.w3c.dom.Element;
+
+@XmlRootElement
+class Person {
+  public String getName();
+  public void setName(String);
+
+  @XmlAnyElement
+  public List<Element> getAny();
+}

1.3.2. processContents="strict"

<xs:any /> with processContents=strict (or + <xs:any /> without any processContents attribute, since it + defaults to "strict") means any XML elements placed here must have + corresponding schema definitions. This mode is not what people + typically expect as "wildcard", but this is the default. The following + shows this binding. (lax=true is unintuitive, but it's + not an error in this document):

Example 13. Any/Strict schema

<xs:element name="person">
+  <xs:complexType>
+    <xs:sequence>
+      <xs:element name="name" type="xs:string" />
+      <xs:any maxOccurs="unbounded" minOccurs="0" />
+    </xs:sequence>
+  </xs:complexType>
+</xs:element>

Example 14. Any/Strict binding

@XmlRootElement
+class Person {
+  public String getName();
+  public void setName(String);
+
+  @XmlAnyElement(lax=true)
+  public List<Object> getAny();
+}

Jakarta XML Binding binds any such element to an Object, and + during unmarshalling, all elements encountered are unmarshalled into + corresponding Jakarta XML Binding objects (including JAXBElements if + necessary) and placed in this field. If it encounters elements that + cannot be unmarshalled, DOM elements are produced instead.

At runtime, you can place either DOM elements or some Jakarta XML Binding + objects that map to elements. A typical mistake is to put a + String that contains XML fragment, but this won't work; + you'd have to first read that into a DOM.

1.3.3. processContents="lax"

<xs:any /> with processContents=lax means any + XML elements can be placed here, but if their element names match + those defined in the schema, they have to be valid. XJC actually + handles this exactly like processContents='strict', since the strict + binding allows unknown elements anyway.

1.4. Mapping of <xs:element /> to JAXBElement

Sometimes XJC binds an element declaration to + JAXBElement. Sometimes XJC binds an element declaration to a + Java class. What makes this difference?

1.5. How modularization of schema interacts with XJC

Over time schema authors have developed several techniques to + modularize large schemas. Some of those techniques have some noteworthy + interactions with XJC.

1.5.1. Chameleon schema

Chameleon + schema" (read + more, in particular this) + is a technique used to define multiple almost-identical sets of + definitions into multiple namespaces from a single schema + document.

For example, with this technique, you can write just one "foo" + complex type and define it into namespace X and Y. In this case, one + tends to hope that XJC will only give you one Foo class + for this, but unfortunately because it's actually defined in two + namespaces, Jakarta XML Binding needs two Java classes to distinguish X:foo and + Y:foo, so you'll get multiple copies.

If you find this to be problematic, there are a few ways to work + around the problem.

  1. If you are in control of the schema, see if you can + rewrite the schema to avoid using this technique. In some + cases, the schema doesn't actually exploit the additional + power of this technique, so this translation can be done + without affecting XML instance documents. In some other cases, + the chameleon schema can be argued as a bad schema design, as + it duplicates definitions in many places.

  2. If you are not in control of the schema, see if you can + rewrite the schema nevertheless. This will only work if your + transformation doesn't affect XML instance documents.

  3. Perhaps there can be a plugin that eases the pain of + this, such as by defining common interfaces among + copies.

1.6. Adding behaviors

Adding behaviors to the generated code is one area that + still needs improvement. Your feedback is appreciated.

Suppose if Eclipse Implementation of JAXB generated the following classes.

Example 15. Simple Eclipse Implementation of JAXB Generated Code

package org.acme.foo;
+
+@XmlRootElement
+class Person {
+  private String name;
+
+  public String getName() { return name; }
+  public void setName(String) { this.name=name; }
+}
+
+@XmlRegistry
+class ObjectFactory {
+  Person createPerson() { ... }
+}

To add a behavior, first write a class that extends from + Person. You also need to extend ObjectFactory to return this + new class. Notice that neither classes have any Jakarta XML Binding annotation, and I put + them in a separate package. This is because we'd like + PersonEx class to be used in place of Person, + and we don't want PersonEx to be bound to its own XML + type.

Example 16. Extended Person class

package org.acme.foo.impl;
+
+class PersonEx extends Person {
+  @Override
+  public void setName(String name) {
+    if(name.length()<3) throw new IllegalArgumentException();
+    super.setName(name);
+  }
+}
+
+@XmlRegistry
+class ObjectFactoryEx extends ObjectFactory {
+  @Override
+  Person createPerson() {
+    return new PersonEx();
+  }
+}

At runtime, you can create JAXBContext normally, like + this.

Example 17. Creating JAXBContext

JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
+// or JAXBContext.newInstance("org.acme.foo");

PersonEx can be marshalled out just like + Person:

Example 18. Marshalling

Person p = new PersonEx();
+context.createMarshaller().marshal(p,System.out);
+// this will produce <person />

To unmarshal XML documents into PersonEx, you'll need + to configure the unmarshaller to use your ObjectFactoryEx as + the factory, like this:

Example 19. Unmarshalling

Unmarshaller u = context.createUnmarshaller();
+u.setProperty("org.glassfish.jaxb.core.ObjectFactory",new ObjectFactoryEx());
+PersonEx p = (PersonEx)u.unmarshal(new StringReader("<person />"));

If you have multiple packages and thus multiple + ObjectFactorys, you can pass in an array of them (new + Object[]{new OFEx1(),new OFEx2(),...}.)

1.6.1. Inserting your class in the middle

If you have a type hierarchy and would like to insert your class + in the middle, you can use the combination of XmlTransient + and @implClass of <class> + customization. See the following example:

Example 20. Hierarchy of types and <jaxb:class implClass>

<xs:schema ...>
+  <xs:complexType name="vehicle">
+    <xs:annotation><xs:appinfo>
+      <jaxb:class implClass="MyVehicle" />
+    </xs:appinfo></xs:annotation>
+  </xs:complexType>
+
+  <xs:complexType name="car">
+    <xs:complexContent>
+      <xs:extension base="vehicle" />
+    </xs:complexContent>
+  </xs:complexType>
+
+  <xs:complexType name="bicycle">
+    <xs:complexContent>
+      <xs:extension base="vehicle" />
+    </xs:complexContent>
+  </xs:complexType>
+</xs:schema>

Example 21. This creates a class hierarchy like the following (among + the generated Java code):

            Vehicle
+               ^
+               |
+            MyVehicle
+               ^
+          _____|______
+         |            |
+        Car          Bicycle

You'll then manually write MyVehicle class that + extends from Vehicle. Annotate this class with XmlTransient + to achieve the desired effect.

1.7. Avoid strong databinding

Under some limited circumstances, a weaker databinding is preferable + for various reasons. Jakarta XML Binding does offer a few ways for you to achieve + this.

1.7.1. Avoid mapping to enum

The following customization will stop binding a simple type to a + type-safe enum. This can be convenient when number of constants is too + large to be an useful enum (by default, the Jakarta XML Binding spec won't generate + enum with more than 256 constants, but even 100 might be too large for + you.)

Example 22. Avoid mapping one simple type

<xs:simpleType name="foo">
+  <xs:annotation><xs:appinfo>
+    <jaxb:typesafeEnumClass map="false" />
+  </xs:appinfo></xs:annotation>
+  <xs:restriction base="xs:string">
+    <xs:enumeration value="x" />
+    <xs:enumeration value="y" />
+    <xs:enumeration value="z" />
+  </xs:restriction>
+</xs:simpleType>

To disable such type-safe enum binding altogether for the entire + schema, use a global binding setting like this (this is actually + telling XJC not to generate enums if a simple type has more than 0 + constants --- the net effect is no enum generation):

Example 23. Avoid generating enums at all

<xs:schema ...>
+  <xs:annotation><xs:appinfo>
+    <jaxb:globalBindings typesafeEnumMaxMembers="0" />
+  </xs:appinfo></xs:annotation>
+  ...
+</xs:schema>

1.7.2. Mapping to DOM

The <jaxb:dom>customization allows you to map + a certain part of the schema into a DOM tree. This customization can + be attached to the following schema components:

  • Wildcards (<xs:any>)

  • Type definitions (<xs:complexType> and + <xs:simpleType>)

  • Model groups + (<xs:choice>,<xs:all>,<xs:sequence>)

  • Model group declarations (<xs:group>)

  • Particles

  • Element declarations (<xs:element>)

In the following example, a wildcard is mapped to a DOM node. + Each element that matches to the wildcard will be turned into a DOM + tree.

Example 24. Dom Customization example

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+               xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+               jaxb:version="3.0">
+
+        <xs:element>
+           <xs:complexType>
+              <xs:sequence>
+                 <xs:any maxOccurs="unbounded" processContents="skip">
+                    <xs:annotation><xs:appinfo>
+                      <jaxb:dom/>
+                    </xs:appinfo></xs:annotation>
+                 </xs:any>
+              </xs:sequence>
+           </xs:complexType>
+        </xs:element>
+    .
+    .
+    .
+    </xs:schema>

This extension can be used to access wildcard content or can be + used to process a part of a document by using other technologies that + require "raw" XML. By default, Jakarta XML Binding generates a getContent() method + for accessing wildcard content, but it only supports "lax" handling + which means that unknown content is discarded. You may find more + information in 7.12 chapter of Jakarta XML Binding 2 + specification.

1.8. Working with generated code in memory

1.8.1. Cloning

The generated beans (and in particular the + JAXBElement class) do not support the clone operation. + There was a suggestion by another user that beanlib has been + used successfully to clone Jakarta XML Binding objects.

2. Customization of Schema Compilation

2.1. Customizing Java packages

The Jakarta XML Binding specification provides a <jaxb:schemaBindings> + customization so that you can control which namespace goes to which + package. See the example below:

Example 25. package customization

    <jaxb:schemaBindings>
+      <jaxb:package name="org.acme.foo"/>
+    </jaxb:schemaBindings>

You can do this as an internal customization (in which case you put + this in <xs:annotation><xs:appinfo> under place it right under + the <xs:schema> element), or do this as an external customization, + like this:

Example 26. External package customization

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0">
+  <bindings schemaLocation="../path/to/my.xsd">
+    <schemaBindings>
+      <package name="org.acme.foo"/>
+    </schemaBindings>
+  </bindings>
+</bindings>

Note that this customization is per namespace. That is, even if your + schema is split into multiple schema documents, you cannot put them into + different packages if they are all in the same namespace.

2.1.1. Tip: get rid of the org.w3._2001.xmlschema package

Under some rare circumstances, XJC will generate some Java + classes into a package called org.w3._2001.xmlschema. + This happens when XJC decides that it needs some Java artifacts for + the XML Schema built-in namespace of + http://www.w3.org/2001/XMLSchema.

Since this package name is most often problematic, you can + rename this by simply saving the following text in an .xsd file and + submitting it to XJC along with the other schemas you have:

Example 27. Schemalet to get rid of org.w3._2001.xmlschema

<schema xmlns="http://www.w3.org/2001/XMLSchema"
+  targetNamespace="http://www.w3.org/2001/XMLSchema"
+  xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+  jaxb:version="3.0">
+  <annotation><appinfo>
+    <jaxb:schemaBindings>
+      <jaxb:package name="org.acme.foo"/>
+    </jaxb:schemaBindings>
+  </appinfo></annotation>
+</schema>

This is bit tricky, but the idea is that since you can define a + schema for one namespace in multiple schema documents, this makes XJC + think that this schema is a part of the built-in "XML Schema for XML + Schema".

2.2. Using SCD for customizations

When using an external customization file, the Jakarta XML Binding spec requires + that you use XPath as a means to specify what your customization is + attached to. For example, if you want to change the class name generated + from a complex type, you'd write something like:

Example 28. External customization example

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <bindings schemaLocation="../path/to/my.xsd" node="/xs:schema/xs:complexType[@name='foo']">
+    <class name="FooType"/>
+  </bindings>
+</bindings>

While the above process works, the problem with this is that the + XPath+ schemaLocation combo tends to be verbose and error + prone. It's verbose, because often a trivial target schema component like + this "global complex type foo" takes up a lot of characters. The xs + namespace declaration also takes up some space, although in this case we + managed to avoid declaring the "tns" namespace (that represents the + namespace that the schema defines.)

It's also error prone, because it relies on the way schema documents + are laid out, because the schemaLocation attribute needs to point to the + right schema document file. When a schema is split into multiple files for + modularity (happens especially often with large schemas), then you'd have + to find which schema file it is. Even though you can use relative paths, + this hard-coding of path information makes it hard to pass around the + binding file to other people.

JAXB RI 2.1 and onward offers a better way to do this as a vendor + extension.

The key technology to solve this problem is a "schema component + designator" (SCD.) This is a path language just like XPath, but + whereas XPath is designed to refer to XML infoset items like elements and + attributes, SCD is designed to refer to schema components like element + declarations or complex types.

With SCD, the above binding can be written more concisely as + follows:

Example 29. External customization by SCD

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0" xmlns:tns="http://my.namespace/">
+  <bindings scd="/type::tns:foo">
+    <class name="FooType"/>
+  </bindings>
+</bindings>

/type::tns:foo can be written more concisely as + /~tns:foo, too. If you are interested in more about the + syntax of SCDs, read the + example part of the spec, and maybe EBNF. + If you know XPath, I think you'll find this fairly easy to learn.

Another benefit of an SCD is that tools will have easier time + generating SCDs than XPath, as XPaths are often vulnerable to small + changes in the schema document, while SCDs are much more robust. The + downside of using SCD is as of JAXB 2.1, this feature is a vendor + extension and not defined in the spec.

2.3. Using different datatypes

Eclipse Implementation of JAXB has a built-in table that determines what Java classes are used + to represent what XML Schema built-in types, but this can be + customized.

One of the common use cases for customization is to replace the + XMLGregorianCalendar with the friendlier + Calendar or Date. + XMLGregorianCalendar is designed to be 100% compatible with + XML Schema's date/time system, such as providing infinite precision in + sub-seconds and years, but often the ease of use of those familiar Java + classes win over the precise compatibility.

One very easy way to do this is to simply use your IDE (or even + "sed") to replace all the references to XMLGregorianCalendar + by Calendar. This is of course not a very attractive option + if your build process runs XJC as a part of it.

Alternatively, the following customization file can be used to do + this. When using external customization file, the Jakarta XML Binding spec requires you + to use XPath as a means to specify what your customization is attached to. + For example, if you want to change the class name generated from a complex + type, you'd use the following customization:

Example 30. Customization to use Calendar for xs:date

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <globalBindings>
+    <javaType name="java.util.Calendar" xmlType="xs:date"
+      parseMethod="jakarta.xml.bind.DatatypeConverter.parseDate"
+      printMethod="jakarta.xml.bind.DatatypeConverter.printDate"
+    />
+  </globalBindings>
+</bindings>

Save this in a file and specify this to Eclipse Implementation of JAXB with the "-b" + option.

To use the Date class, you'll need to do a bit more + work. First, put the following class into your source tree:

Example 31. Adapter for Date

package org.acme.foo;
+public class DateAdapter {
+  public static Date parseDate(String s) {
+    return DatatypeConverter.parseDate(s).getTime();
+  }
+  public static String printDate(Date dt) {
+    Calendar cal = new GregorianCalendar();
+    cal.setTime(dt);
+    return DatatypeConverter.printDate(cal);
+  }
+}

... then your binding file will be the following:

Example 32. Customization to use Date for xs:date

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <globalBindings>
+    <javaType name="java.util.Date" xmlType="xs:date"
+      parseMethod="org.acme.foo.DateAadpter.parseDate"
+      printMethod="org.acme.foo.DateAdapter.printDate"
+    />
+  </globalBindings>
+</bindings>

3. Annotating Your Classes

3.1. Mapping your favorite class

3.1.1. ResultSet

Jakarta XML Binding (or any other databinding engine, for that matter) is for + binding strongly-typed POJO-like objects to XML, such as + AddressBook class, PurchaseOrder class, and + so on, where you have fields and methods that shape a class.

There are other kinds of classes that are more close to + reflection. Those classes don't have methods like + getAddress, and instead you'd do + get("Address"). JDBC ResultSet is one of those classes. + It's one class that represents million different data structures, be + it a customer table or a product table. Generally speaking, these + classes does not allow Jakarta XML Binding to statically determine what the XML + representation should look like. Instead, you almost always need to + look at an instance to determine the shape of XML.

These classes are not really suitable for binding in Jakarta XML Binding. If + this is the only object that you'd want to write out, then you'd be + better off using XMLStreamWriter or some such XML infoset writing API. + There are a few online + articles that cover this topic. Also, many modern database + offers a native ability to export a query into XML, which is supposed + to work a lot faster than you'd do in Java (and saves your time of + writing code.)

If you are using ResultSet as a part of your object tree that + you want to marshal to Jakarta XML Binding, then you can use + XmlJavaTypeAdapter.

3.1.2. HashMap

Jakarta XML Binding spec defines a special handling for Map when + it's used as a propety of a bean. For example, the following bean + would produce XMLs like the following:

Example 33. Bean with Map

@XmlRootElement
+class Foo {
+  public HashMap<String,Integer> map;
+}

Example 34. XML representation

<foo>
+  <map>
+    <entry>
+      <key>a</key>
+      <value>1</value>
+    </entry>
+    <entry>
+      <key>b</key>
+      <value>2</value>
+    </entry>
+  </map>
+</foo>

Unfortunately, as of 2.1, this processing is only defined for + bean properties and not when you marshal HashMap as a + top-level object (such as a value in JAXBElement.) In + such case, HashMap will be treated as a Java bean, and + when you look at HashMap as a bean it defines no + getter/setter property pair, so the following code would produce the + following XML:

Example 35. Bean with Map

m = new HashMap();
+m.put("abc",1);
+marshaller.marshal(new JAXBElement(new QName("root"),HashMap.class,m),System.out);

Example 36. XML representation

<root />

This issue has been recorded as #223 + and the fix needs to happen in later versions of the Jakarta XML Binding spec.

In the mean time, such top-level objects have to be first + adapted to a bean that Jakarta XML Binding can process. This has added benefit of + being able to control XML representation better. The following code + illustrates how to do this:

Example 37. Adapting HashMap

public class MyHashMapType {
+    public List<MyHashMapEntryType> entry = new ArrayList<MyHashMapEntryType>();
+    public MyHashMapType(Map<String,Integer> map) {
+        for( Map.Entry<String,Integer> e : map.entrySet() )
+            entry.add(new MyHashMapEntryType(e));
+    }
+    public MyHashMapType() {}
+}
+
+public class MyHashMapEntryType {
+    @XmlAttribute // @XmlElement and @XmlValue are also fine
+    public String key;
+
+    @XmlAttribute // @XmlElement and @XmlValue are also fine
+    public int value;
+
+    public MyHashMapEntryType() {}
+    public MyHashMapEntryType(Map.Entry<String,Integer> e) {
+       key = e.getKey();
+       value = e.getValue();
+    }
+}
+
+marshaller.marshal(new JAXBElement(new QName("root"),MyHashMapType.class,new MyHashMapType(m)),System.out);

If you have a lot of difference kinds of Map, you + can instead use Object as the key and the value type. In + that way, you'll be able to use maps with different type parameters, + at the expense of seeing xsi:type attribute on the + instance document.

3.2. Mapping interfaces

Because of the difference between the XML type system induced by W3C + XML Schema and the Java type system, Jakarta XML Binding cannot bind interfaces out of + the box, but there are a few things you can do.

3.2.1. Use @XmlRootElement

When your interface is implemented by a large number of + sub-classes, consider using XmlRootElement annotation like this:

Example 38. XmlRootElement for open-ended interfaces

@XmlRootElement
+class Zoo {
+  @XmlAnyElement
+  public List<Animal> animals;
+}
+
+interface Animal {
+  void sleep();
+  void eat();
+  ...
+}
+
+@XmlRootElement
+class Dog implements Animal { ... }
+
+@XmlRootElement
+class Lion implements Animal { ... }

This will produce XML documents like this:

Example 39. XML for XmlRootElement

<zoo>
+    <lion> ... </lion>
+    <dog> ... </dog>
+</zoo>

The key characteristics of this approach is:

  1. Implementations are open-ended; anyone can implement + those interfaces, even by different people from different + modules, provided they are all given to the + JAXBContext.newInstance method. There's no need + to list all the implementation classes in anywhere.

  2. Each implementation of the interface needs to have an + unique element name.

  3. Every reference to interface needs to have the XmlElementRef annotation. The + type=Object.class portion tells Jakarta XML Binding that the + greatest common base type of all implementations would be + java.lang.Object.

@XmlElementWrapper is often useful with this, + as it allows you need to group them. Such as:

Example 40. XmlRootElement for open-ended interfaces

@XmlRootElement
+class Zoo {
+  @XmlElementWrapper
+  @XmlAnyElement
+  public List<Animal> onExhibit;
+  @XmlElementWrapper
+  @XmlAnyElement
+  public List<Animal> resting;
+}

Example 41. Effect of XmlElementWrapper

<zoo>
+    <onExhibit>
+        <lion> ... </lion>
+        <dog> ... </dog>
+    </onExhibit>
+    <resting>
+        <lion> ... </lion>
+        <dog> ... </dog>
+    </resting>
+</zoo>

3.2.2. Use @XmlJavaTypeAdapter

When you use interfaces just to hide your implementation classes + from exposure, and when there's 1-to-1 (or close to 1-on-1) + relationship between a class and an interface, XmlJavaTypeAdapter can be used like below.

Example 42. XmlJavaTypeAdapter for interfaces

@XmlJavaTypeAdapter(FooImpl.Adapter.class)
+interface IFoo {
+  ...
+}
+class FooImpl implements IFoo {
+  @XmlAttribute
+  private String name;
+  @XmlElement
+  private int x;
+
+  ...
+
+  static class Adapter extends XmlAdapter<FooImpl,IFoo> {
+    IFoo unmarshal(FooImpl v) { return v; }
+    FooImpl marshal(IFoo v) { return (FooImpl)v; }
+  }
+}
+
+class Somewhere {
+  public IFoo lhs;
+  public IFoo rhs;
+}

Example 43. XML of XmlJavaTypeAdapter

<somewhere>
+  <lhs name="...">
+    <x>5</x>
+  </lhs>
+  <rhs name="...">
+    <x>5</x>
+  </rhs>
+</somewhere>

The key characteristics of this approach is:

  1. Interface and implementation will be tightly coupled + through an adapter, although changing an adapter code will + allow you to support multiple implementations.

  2. There's no need of any annotation in where interfaces + are used.

A variation of this technique is when you have a few + implementations for interface, not just one.

Example 44. XmlJavaTypeAdapter for interfaces with multiple + implementations

@XmlJavaTypeAdapter(AbstractFooImpl.Adapter.class)
+interface IFoo {
+  ...
+}
+abstract class AbstractFooImpl implements IFoo {
+  ...
+
+  static class Adapter extends XmlAdapter<AbstractFooImpl,IFoo> {
+    IFoo unmarshal(AbstractFooImpl v) { return v; }
+    AbstractFooImpl marshal(IFoo v) { return (AbstractFooImpl)v; }
+  }
+}
+
+class SomeFooImpl extends AbstractFooImpl {
+  @XmlAttribute String name;
+  ...
+}
+
+class AnotherFooImpl extends AbstractFooImpl {
+  @XmlAttribute int id;
+  ...
+}
+
+class Somewhere {
+  public IFoo lhs;
+  public IFoo rhs;
+}

Example 45. XML of XmlJavaTypeAdapter with multiple + implementations

<somewhere>
+  <lhs xsi:type="someFooImpl" name="...">
+  </lhs>
+  <rhs xsi:type="anotherFooImpl" id="3" />
+</somewhere>

Note that SomeFooImpl and + AnotherFooImpl must be submitted to + JAXBContext.newInstance one way or the other.

To take this example a bit further, you can use + Object instead of AbstractFooImpl. The + following example illustarates this:

Example 46. XmlJavaTypeAdapter for interfaces with multiple + implementations

@XmlJavaTypeAdapter(AnyTypeAdapter.class)
+interface IFoo {
+  ...
+}
+public class AnyTypeAdapter extends XmlAdapter<Object,Object> {
+  Object unmarshal(Object v) { return v; }
+  Object marshal(Object v) { return v; }
+}
+
+class SomeFooImpl implements IFoo {
+  @XmlAttribute String name;
+  ...
+}
+
+class Somewhere {
+  public IFoo lhs;
+  public IFoo rhs;
+}

Example 47. Corresponding schema

<xs:complexType name="somewhere">
+  <xs:sequence>
+    <xs:element name="lhs" type="xs:anyType" minOccurs="0"/>
+    <xs:element name="rhs" type="xs:anyType" minOccurs="0"/>
+  </xs:sequence>
+</xs:complexType>

As you can see, the schema will generated to accept + xs:anyType which is more relaxed than what the Java code + actually demands. The instance will be the same as the above example. + Starting from JAXB RI 2.1, we bundle the + AnyTypeAdapter class in the runtime that + defines this adapter. So you won't have to write this adapter in your + code.

3.2.3. Use @XmlElement

If the use of interface is very little and there's 1-to-1 (or + close to) relationship between interfaces and implementations, then + you might find XmlElement to be the least amount of work.

Example 48. XmlElement for interfaces

interface IFoo {
+  ...
+}
+class FooImpl implements IFoo {
+  ...
+}
+
+class Somewhere {
+  @XmlElement(type=FooImpl.class)
+  public IFoo lhs;
+}

Example 49. XML of XmlElement

<somewhere>
+  <lhs> ... </lhs>
+</somewhere>

This effectively tells Jakarta XML Binding runtime that "even though the field + is IFoo, it's really just FooImpl.

In this approach, a reference to an interface has to have + knowledge of the actual implementation class. So while this requires + the least amount of typing, it probably wouldn't work very well if + this crosses module boundaries.

Like the XmlJavaTypeAdapter approach, this can be used + even when there are multiple implementations, provided that they share + the common ancestor.

The extreme of this case is to specify + @XmlElement(type=Object.class).

3.2.4. Hand-write schema

Occasionally the above approaches cause the generated schema to + become somewhat ugly, even though it does make the Jakarta XML Binding runtime work + correctly. In such case you can choose not to use the generated schema + and instead manually modify/author schemas tht better match your + needs.

3.2.5. Do schema-to-java

With sufficient knowlege, one can also use <jaxb:class + ref="..."/> annotation so that you can cause XJC to use the classes + you already wrote. See this + thread for an example. TODO: more details and perhaps an + example.

3.2.6. DOESN'T WORK: Have Jakarta XML Binding generate interaces and swap different + implementations

Some + users attempted to use the "generateValueClass" customization + and see if they can completely replace the generated implementations + with other implementations. Unfortunately, this does not work.

Even with the interface/implementation mode, Jakarta XML Binding runtime still + requires that the implementation classes have all the Jakarta XML Binding + annotations. So just implementing interfaces is not sufficient. (This + mode is mainly added to simplify the migration from JAXB 1.0 to Jakarta XML Binding, + and that's a part of the reason why things are done this + way.)

3.3. Evolving annotated classes

Here is the basic problem of evolution. You got your CoolApp v1, + which contains class Foo that has some Jakarta XML Binding annotations. Now you are + working towawrd CoolApp v2, and you want to make some changes to Foo. But + you want to do so in such a way that v1 and v2 can still talk to each + other.

The evolution compatibility has two different aspects. One is the + schema compatibility, which is about the relationship + between the v1 schema and the v2 schema. The other is about + runtime compatibility, which is about reading/writing + documents between two versions.

3.3.1. Runtime compatibility

There are two directions in the runtime compatibility. One is + whether v1 can still read what v2 write (forward + compatible), and the other is whether v2 can read what v1 + wrote (backward compatible).

3.3.2. "Semi-compatible"

Jakarta XML Binding can read XML documents that don't exactly match what's + expected. This is the default behavior of the Jakarta XML Binding unmarshaller, yet + you can change it to a more draconian behavior (TODO: pointer to the + unmarshalling section.)

When we are talking about evolving classes, it's often + convenient to leave it in the default behavior, as that would allow + Jakarta XML Binding to nicely ignore elements/attributes newly added in v2. So we + call it backward semi-compatible if v2 can read + what v1 wrote in this default unmarshalling mode, and similarly + forward semi-compatible if v1 can read what v2 + wrote in this default unmarshalling mode.

Technically, these are weaker than true backward/forward + compatibility (since you can't do a draconian error detection), yet in + practice it works just fine.

3.3.3. Adding/removing/changing non-annotated things

You can add, remove, or change any non-annotated fields, + methods, inner/nested types, constructors, interfaces. Those changes + are both backward and forward compatible, as they don't cause any + change to the XML representation.

Adding super class is backward compatible and forward + semi-compatible. Similarly, removing super class is forward compatible + and backward semi-compatible.

3.3.4. Adding/removing/changing properties

Adding new annotated fields or methods is backward compatible + and forward semi-compatible. Similarly, removing them is forward + compatible and backward semi-compatible.

Changing a property is bit more tricky.

  1. If you change the property name from X to Y, that would + be the equivalent of deleting X and adding Y, so it would be + backward and forward semi-compatible. What Jakarta XML Binding really cares + is properties' XML names and not Java names, so by using the + name parameter of XmlElement, XmlAttribute et al, you can change Java + property names without affecting XML, or change XML without + affecting Java properties. These are backward and forward + semi-compatible. See below:

  2. Example 50. Changing Java without affecting XML

    // BEFORE
    +public class Foo {
    +    public String abc;
    +}
    +// AFTER: Java name changed, but XML remains the same
    +public class Foo {
    +    @XmlElement(name="abc")
    +    public String def;
    +}

    Example 51. Changing XML without affecting Java

    // BEFORE
    +public class Foo {
    +    public String abc;
    +}
    +// AFTER: no Java change, but XML will look different
    +public class Foo {
    +    @XmlElement(name="def")
    +    public String abc;
    +}

  3. If you change a property type, generally speaking it + will be not compatible at all. For example, you can't change + from java.util.Calendar to int and + expect it to work. To make it a somewhat compatible change, + the old type and the new type has to be related. For example, + String can represent all int values, + so changing int to String would be a + backward compatible and forward semi-compatible change. XmlJavaTypeAdapter allows you to make + changes to Java without affecting XML (or vice versa.)

3.3.5. Changing class names

XmlType and XmlRootElement allows you to change a class name + without affecting XML.

Example 52. Changing class name without affecting XML (1)

// BEFORE
+@XmlRootElement
+public class Foo { ... }
+
+// AFTER: no XML change
+@XmlRootElement(name="foo")
+@XmlType(name="foo")
+public class Bar { ... }

Example 53. Changing class name without affecting XML (2)

// BEFORE
+public class Foo { ... }
+
+// AFTER: no XML change
+@XmlType(name="foo")
+public class Bar { ... }

3.3.6. Schema Compatibility

TODO.

3.4. XML layout and in-memory data layout

Your program sometimes needs to have a different in-memory data + structure from its XML representation. Jakarta XML Binding has a few different ways to + achieve this.

3.4.1. XmlJavaTypeAdapter

XmlJavaTypeAdapter allows you to de-couple the + in-memory representation and the XML representation by introducing an + intermediate representation. The basic model is as follows:

In-memory objects  <===>  Intermediate objects   <===>
+XML
+                  adapter                         XMLBinding

Your adapter code will be responsible for converting in-memory + objects to/from intermediate objects. Intermediate objects are then + bound to XML by following the standard Jakarta XML Binding rules. See XmlAdapter for a general description of how + adapters works.

Adapters extend from the XmlAdapter class and provide two methods + "unmarshal" and "marshal" that converts values in both directions, and + then the XmlJavaTypeAdapter annotation is used to tell + Jakarta XML Binding where and what adapters kick in.

(TODO: more info about XmlJavaTypeAdapter needed)

  1. adapting a class

  2. adapting a property

  3. adapting an external class

  4. adapting a collection and its effect

  5. adapting and using interfaces

3.4.2. Using XmlJavaTypeAdapter for element/attribute values

One of the common use cases of XmlJavaTypeAdapter is to map a "value object" to + a string in XML. The following example illustrates how to do this, by + using java.awt.Color as an example.

Example 54. Mapping Color to #RRGGBB

@XmlRootElement
+class Box {
+  @XmlJavaTypeAdapter(ColorAdapter.class)
+  @XmlElement
+  Color fill;
+}
+
+class ColorAdapter extends XmlAdapter<String,Color> {
+  public Color unmarshal(String s) {
+    return Color.decode(s);
+  }
+  public String marshal(Color c) {
+    return "#"+Integer.toHexString(c.getRGB());
+  }
+}

This maps to the following XML representation:

Example 55. Box instance

<box>
+  <fill>#112233</fill>
+</box>

Since XmlJavaTypeAdapter is on a field, this adapter + only kicks in for this particular field. If you have many + Color fields and would like them all to use the same + adapter, you can move the annotation to a package:

Example 56. package-info.java

@XmlJavaTypeAdapter(type=Color.class,value=ColorAdapter.class)
+package foo;

Example 57. Box.java

@XmlRootElement
+class Box {
+  @XmlElement Color fill;
+  @XmlElement Color border;
+}

This causes all the fields in the classes in the + foo package to use the same specified adapter.

Also see the DatatypeConverter class that defines a + series of basic conversion routines that you may find useful.

3.4.3. Pair property

Another useful technique is to define two properties, one for + Jakarta XML Binding and the other for your application. See the following + example:

Example 58. Pair property sample

@XmlRootElement
+class Person {
+  private int age;
+
+  // This public property is for users
+  @XmlTransient
+  public int getAge() {
+    return age;
+  }
+  public void setAge(int age) {
+    this.age = age;
+  }
+
+  // This property is for Jakarta XML Binding
+  @XmlAttribute(name="age")
+  private String getAge_() {
+    if(age==-1)  return "dead";
+    else         return String.valueOf(age);
+  }
+  private void setAge_(String v) throws NumberFormatException {
+    if(v.equals("dead"))   this.age=-1;
+    else                   this.age=Integer.parseInt(age);
+}

The main "age" property is public, but marked as XmlTransient, so it's exposed in your program, + but Jakarta XML Binding will not map this to XML. There's another private "age_" + property. Since this is marked with XmlAttribute, this is what Jakarta XML Binding is going to use + to map to the attribute. The getter and setter methods on this + property will handle the conversion between the in-memory + representation and the XML representation.

3.5. Mapping cyclic references to XML

Object models designed in Java often have cycles, which prevent + straight-forward conversion to XML by Jakarta XML Binding. In fact, when you try to + marshal an object tree that contains a cycle, the Jakarta XML Binding marshaller reports + an error, pointing out the objects that formed the cycle. This is because + Jakarta XML Binding by itself cannot figure out how to cut cycles into a tree.

Thus it is your responsibility to annotate classes and use other + means to "tell" Jakarta XML Binding how to handle a cycle. This chapter talks about + various techniques to do this.

3.5.1. Parent pointers

One of the very common forms of cycle is a parent pointer. The + following example illustrates a typical parent pointer, and how this + can be turned into "natural" XML:

Example 59. Classes with parent pointer

@XmlRootElement
+class Department {
+  @XmlAttribute
+  String name;
+  @XmlElement(name="employee")
+  List<Employee> employees;
+}
+
+class Employee {
+  @XmlTransient
+  Department department;  // parent pointer
+  @XmlAttribute
+  String name;
+
+  public void afterUnmarshal(Unmarshaller u, Object parent) {
+    this.department = (Department)parent;
+  }
+}

This will produce the following XML:

Example 60. XML view of department

<department name="accounting">
+  <employee name="Joe Chin" />
+  <employee name="Adam Smith" />
+  ...
+</department>

And reading this document back into Java objects will produce + the expected tree with all the proper parent pointers set up + correctly.

The first technique here is the use of XmlTransient on the parent pointer. This tells + Jakarta XML Binding that you don't need this parent pointer to be represented + explicitly in XML, because the fact that employee is + always contained inside department implies the + parent/child relationship. This causes the marshaller to produce the + expected XML. However, when you unmarshal it, since this field is not + bound, the Employee.department field will be left + null.

That's where the second technique comes in, which is the use of + the afterUnmarshal callback. This method is invoked by + the Jakarta XML Binding implementation on each instance when the unmarshalling of a + Employee object completes. Furthermore, the second + parameter to the method is the parent object, which in this case is a + Department object. So in this example, this sets up the + parent pointer correctly.

This callback can be also used to perform other + post-unmarshalling set up work.

3.5.2. Many-to-many relationship

TBD

3.5.3. @XmlID and + @XmlIDREF

When a reference to another object is annotated with XmlIDREF, its corresponding XML it will be + referenced by xs:IDREF, instead of containment. See below + for an example:

Example of @XmlID and + @XmlIDREF

@XmlRootElement
+class Root {
+  List<Foo> foos;
+  List<Bar> bars;
+}
+class Foo {
+  // you don't have to make it an attribute, but that's more common
+  @XmlAttribute @XmlIDREF Bar bar;
+}
+class Bar {
+  // you don't have to make it an attribute, but that's more common
+  @XmlAttribute @XmlID String id;
+}

Example 61. Schema for above

<xs:complexType name="foo">
+  <xs:sequence/>
+  <xs:attribute name="bar" type="xs:IDREF"/>
+  </xs:sequence>
+</xs:complexType>
+<xs:complexType name="bar">
+  <xs:sequence/>
+  <xs:attribute name="id" type="xs:ID"/>
+</xs:complexType>

Example 62. A sample instance

<root>
+  <foo bar="x"/>
+  <foo bar="y"/>
+  <bar id="x"/>
+  <bar id="y"/>
+</root>

There are a few things to consider when you do this. First, the + object to be referenced must have an ID that is unique within the + whole document. You'd also need to ensure that the referenced objects + are contained somewhere else (like in the + Root class in this case), or else Bar + objects will never be marshalled. This technique can be used to remove + the cyclic references, but it's only possible when your object model + has an easy cut point.

3.5.4. Use the CycleRecoverable interface

Starting 2.1 EA2, the Eclipse Implementation of JAXB exposes CycleRecoverable interface. Applications can + choose to implement this interface in some of its objects. When a + cyclic reference is detected during marshalling, and if the object + that formed a cycle implements this interface, then the method on this + interface is called to allow an application to nominate its + replacement to be written to XML. In this way, the application can + recover from a cycle gracefully.

This technique allows you to cope with a situation where you + cannot easily determine upfront as to where a cycle might happen. On + the other hand, this feature is a Eclipse Implementation of JAXB feature. Another downside of + this is that unless you nominate your replacement carefully, you can + make the marshalling output invalid with respect to the schema, and + thus you might hit another problem when you try to read it back + later.

4. Unmarshalling

4.1. @XmlRootElement and unmarshalling

Classes with XmlRootElement can be unmarshalled from XML elements + simply by invoking the unmarshal method that takes one parameter. This is + the simplest mode of unmarshalling.

Unmarshalling with @XmlRootElement

@XmlRootElement
+class Foo {
+  @XmlAttribute
+  String name;
+  @XmlElement
+  String content;
+}
+
+Unmarshaller u = ...;
+Foo foo = (Foo)u.unmarshal(new File("foo.xml"));

Example 63. foo.xml

<foo name="something">
+  <content>abc</content>
+</foo>

However, sometimes you may need to unmarshal an instance of a type + that does not have an XmlRootElement. For example, you might dynamically + find out at the runtime that a certain element has a certain type. For + example, the following document illustrates an XML instance where the + content of <someOtherTagName> element is represented by the + Foo class.

Example 64. foo2.xml

<someOtherTagName name="something">
+  <content>abc</content>
+</someOtherTagName>

To unmarshal this into a Foo class, use the version of + the unmarshal method that takes the 'expectedType' argument, + as follows:

Example 65. Unmarshalling into a known type

Unmarshaller u = ...;
+JAXBElement<Foo> root = u.unmarshal(new StreamSource(new File("foo.xml")),Foo.class);
+Foo foo = root.getValue();

To reduce the number of the unmarshal methods, this + two-argument version is not defined for every single-argument version. So + as in this example, you might need to perform additional wrapping of the + input parameter.

This instructs Jakarta XML Binding that the caller is expecting to unmarshal + Foo instance. Jakarta XML Binding returns a JAXBElement of + Foo, and this JAXBElement captures the tag name + of the root element.

4.2. Unmarshalling is not working! Help!

There are a few common causes for this problem. These causes often + exhibit similar symptoms:

  1. Instance documents are invalid

  2. JAXBContext is not created correctly.

4.2.1. Make sure your instance document is valid

First, use an independent schema validator to check if your + document is really valid with respect to the schema you compiled. When + the root element of a document is invalid, then the unmarshaller will + issue "unexpected element" errors. When a portion of a document is + invalid, Eclipse Implementation of JAXB skips that portion, so the end result is that the + unmarshalling returns normally, yet you notice that a part of the + content tree is missing. This is often the desirable behavior, but it + sometimes ends up masking a problem.

Also, try to install ValidationEventHandler on the + unmarshaller. When a portion of a document is skipped, the + unmarshaller notifies a ValidationEventHandler, so it + allows you to see what's going on.

Example 66. Installing ValidationEventHandler

Unmarshaller u = ...;
+// this implementation is a part of the API and convenient for trouble-shooting,
+// as it prints out errors to System.out
+u.setEventHandler(new jakarta.xml.bind.helpers.DefaultValidationEventHandler());
+
+u.unmarshal(new File("foo.xml"));

Also consider installing a Schema object to the + unmarshaller, so that the unmarshaller performs a schema validation + while unmarshalling. Earlier I suggested that you try an independent + schema validator, but for various reasons (not all tools are reliable, + you might have made an error and used a different schema/instance), + using validating unmarshalling is a better way to guarantee the + validity of your instance document being unmarshalled. Please follow + the JAXP + tutorial for more about how to construct a Schema + object from your schema.

If you are unmarshalling from XML parser APIs (such as DOM, SAX, + StAX), then also make sure that the parser/DOM is configured with the + namespace enabled.

4.2.2. Check if your JAXBContext is correct

(TODO: This also applies to the marshaller. Think about moving + it.)

The other possibility is that JAXBContext is not + set up correctly. JAXBContext "knows" a set of classes, + and if it doesn't know a class that it's supposed to know, then the + unmarshaller may fail to perform as you expected.

To verify that you created JAXBContext correctly, + call JAXBContext.toString(). It will output the list of + classes it knows. If a class is not in this list, the unmarshaller + will never return an instance of that class. Make you see all the + classes you expect to be returned from the unmarshaller in the list. + When dealing with a large schema that spans across a large number of + classes and packages, this is one possible cause of a problem.

If you noticed that a class is missing, explicitly specify that + to JAXBContext.newInstance. If you are binding classes + that are generated from XJC, then the easiest way to include all the + classes is to specify the generated ObjectFactory + class(es).

4.3. Element default values and unmarshalling

Because of the "strange" way that element default values in XML + Schema work, people often get confused about their behavior. This section + describes how this works.

When a class has an element property with the default value, and if + the document you are reading is missing the element, then the unmarshaller + does not fill the field with the default value. + Instead, the unmarshaller fills in the field when the element is present + but the content is missing. See below:

Example 67. XML instance 1

<foo />

Example 68. XML instance 2

<foo>
+  <a/>  <!-- or <a></a> -->
+</foo>

Example 69. XML instance 3

<foo>
+  <a>abc</a>
+</foo>

Example 70. Element defaults and XML

@XmlRootElement
+class Foo {
+  @XmlElement(defaultValue="value") public String a=null;
+}
+
+Foo foo = unmarshaller.unmarshal("instance1.xml");
+System.out.println(foo.a);   // null
+
+Foo foo = unmarshaller.unmarshal("instance2.xml");
+System.out.println(foo.a);   // "value". The default kicked in.
+
+Foo foo = unmarshaller.unmarshal("instance3.xml");
+System.out.println(foo.a);   // "abc". Read from the instance.

This is consistent with the XML Schema spec, where it essentially + states that the element defaults do not kick in when the element is + absent, so unfortunately we can't change this behavior.

Depending on your expectation, using a field initializer may achieve + what you are looking for. See below:

Example 71. Possible changes by using field initializer

@XmlRootElement
+class Foo {
+  @XmlElement public String a="value";
+}
+
+Foo foo = unmarshaller.unmarshal("instance1.xml");
+System.out.println(foo.a);   // "value", because Jakarta XML Binding didn't overwrite the value
+
+Foo foo = unmarshaller.unmarshal("instance2.xml");
+System.out.println(foo.a);   // "", because <a> element had 0-length string in it
+
+Foo foo = unmarshaller.unmarshal("instance3.xml");
+System.out.println(foo.a);   // "abc". Read from the instance.

Alternatively, attribute default values work in a way that agrees + with the typical expectation, so consider using that. Also, see Element default values and marshalling.

4.4. Dealing with large documents

Jakarta XML Binding API is designed to make it easy to read the whole XML document + into a single tree of Jakarta XML Binding objects. This is the typical use case, but in + some situations this is not desirable. Perhaps:

  1. A document is huge and therefore the whole may not fit the + memory.

  2. A document is a live stream of XML (such as XMPP) and therefore you + can't wait for the EOF.

  3. You only need to databind the portion of a document and + would like to process the rest in other XML APIs.

This section discusses several advanced techniques to deal with + these situations.

4.4.1. Processing a document by chunk

When a document is large, it's usually because there's + repetitive parts in it. Perhaps it's a purchase order with a large + list of line items, or perhaps it's an XML log file with large number + of log entries.

This kind of XML is suitable for chunk-processing; the main idea + is to use the StAX API, run a loop, and unmarshal individual chunks + separately. Your program acts on a single chunk, and then throws it + away. In this way, you'll be only keeping at most one chunk in memory, + which allows you to process large documents.

See the streaming-unmarshalling example and the + partial-unmarshalling example in the Eclipse Implementation of JAXB distribution for more + about how to do this. The streaming-unmarshalling example has an + advantage that it can handle chunks at arbitrary nest level, yet it + requires you to deal with the push model --- Jakarta XML Binding unmarshaller will + "push" new chunk to you and you'll need to process them right + there.

In contrast, the partial-unmarshalling example works in a pull + model (which usually makes the processing easier), but this approach + has some limitations in databinding portions other than the repeated + part.

4.4.2. Processing a live stream of XML

The techniques discussed above can be used to handle this case + as well, since they let you unmarshal chunks one by one. See the + xml-channel example in the Eclipse Implementation of JAXB distribution for more about how to + do this.

4.4.3. Creating virtual infosets

For further advanced cases, one could always run a streaming + infoset conversion outside Jakarta XML Binding API and basically curve just the + portion of the infoset you want to data-bind, and feed it as a + complete infoset into Jakarta XML Binding API. Jakarta XML Binding API accepts XML infoset in many + different forms (DOM, SAX, StAX), so there's a fair amount of + flexibility in choosing the right trade off between the development + effort in doing this and the runtime performance.

For more about this, refer to the respective XML infoset + API.

5. Marshalling

5.1. Changing prefixes

By default, a Jakarta XML Binding marshaller uses random namespace prefixes (such + as ns1, ns2, ...) when it needs to declare new + namespace URIs. While this is perfectly valid XML wrt the schema, for + human readability, you might want to change them to something that makes + more sense.

The Eclipse Implementation of JAXB defines NamespacePrefixMapper to allow you to do this. See + the namespace-prefix sample in the distribution for more + details.

5.2. Element default values and marshalling

Because of a "strange" way element default values in XML Schema + work, people often get confused about its behavior. This section describes + how this works.

When a class has an element property with the default value, and if + a value is null, then the marshaller will not produce the corresponding + element in XML:

Example 72. Element defaults and XML

@XmlRootElement
+class Foo {
+  @XmlElement(defaultValue="value") public String a=null;
+}
+
+marshaller.marshal(new Foo(),System.out);

Example 73. Marshalling output from above

<foo />

This is consistent with the XML Schema spec, where it essentially + states that the element defaults do not kick in when the element is + absent. Attribute default values do not have this problem, so if you can + change the schema, changing it to an attribute is usually a better idea. + Alternatively, depending on your expectation, setting the field to a + default value in Java may achieve what you are looking for.

Example 74. Possible changes

@XmlRootElement
+class Foo {
+  @XmlElement public String a="value";
+}
+@XmlRootElement
+class Bar {
+  @XmlAttribute public String a;
+}
+
+marshaller.marshal(new Foo(),System.out);
+marshaller.marshal(new Bar(),System.out);

Example 75. Marshalling output from above

<foo>
+    <a>value</a>
+</foo>
+
+<bar/>

Also, see Element default values and unmarshalling.

5.3. Different ways of marshalling

5.3.1. Different output media

The most basic notion of the marshalling is to take a Jakarta XML Binding-bound + object that has @XmlRootElement, and write it out as a + whole XML document. So perhaps you have a class like this:

Example 76. Jakarta XML Binding POJO

class Point {
+  @XmlElement
+  public int x;
+  @XmlElement
+  public int y;
+  Point(...) { ... }
+}

Then you can do:

Example 77. Plain marshalling

marshaller.marshal( new Point(1,3), System.out );
+marshaller.marshal( new Point(1,3), new File("out.xml") );

.. and so on. There're seven Marshaller.marshal + methods that takes different output media as the second parameter. If + you are writing to a file, a socket, or memory, then you should use + the version that takes OutputStream. Unless you change + the target encoding to something else (default is UTF-8), there's a + special marshaller codepath for OutputStream, which makes + it run really fast. You also don't have to use + BufferedOutputStream, since the Eclipse Implementation of JAXB does the adequate + buffering.

You can also write to Writer, but in this case + you'll be responsible for encoding characters, so in general you need + to be careful. If you want to marshal XML into an encoding other than + UTF-8, it's best to use the JAXB_ENCODING property and + then write to OutputStream, as it escapes characters to + things like &#x1824; correctly.

The next medium we support is W3C DOM. This is bit unintuitive, + but you'll do it like this:

Example 78. Marshal to DOM

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+dbf.setNamespaceAware(true);
+Document doc = dbf.newDocumentBuilder().newDocument();
+
+marshaller.marshal( new Point(1,3), doc );

And after the method invocation you get a complete DOM tree that + represents the marshalled document.

The other versions of the marshal methods are there to write XML + documents in terms of other XML APIs, such as SAX and StAX. The + version that takes ContentHandler is useful when you need + a custom formatting needs (like you want each attribute to be in new + line, etc), but otherwise they are not very interesting if you are + writing a whole document.

5.3.2. Marshalling into a subtree

Another common use of Jakarta XML Binding is where you are writing a bigger + document, and you use Jakarta XML Binding to generate part(s) of it. The Eclipse Implementation of XML Web Services is + the prime example. It produces a SOAP message, and Jakarta XML Binding is only used + to produce the body. When you are doing this, you first set + JAXB_FRAGMENT property on the marshaller. This changes + the behaviors of the marshaller so that it works better in this + situation.

If you are writing to an OutputStream or + Writer and generally sending it to someone else, you can + do something like this:

Example 79. Marshalling into a subtree

System.out.println("<envelope>");
+marshaller.marshal( object, System.out );
+System.out.println("</envelope>");

Like I mentioned, this is probably the fastest, even though + println isn't very pretty. JAXB_FRAGMENT + prevents the marshaller from producing an XML declaration, so the + above works just fine. The downside of this approach is that if the + ancestor elements declare the namespaces, Jakarta XML Binding won't be able to take + advantage of them.

You can also marshal an object as a subtree of an existing DOM + tree. To do this, you pass the Element object as the + second parameter, and the marshaller will marshal an object as a child + of this node.

StAX is also very convenient for doing this sort of things. You + can create XMLStreamWriter, write some stuff, and then + pass that to the marshaller. JAXB_FRAGMENT prevents the + marshaller from producing startDocument and + endDocument token. When doing this sub-tree marshaling to + DOM and StAX, Jakarta XML Binding can take advantage of available in-scope namespace + bindings.

Finally, you can marshal an object as a subtree into + ContentHandler, but it requires a fair amount of SAX + programming experience, and it goes beyond the scope of this + entry.

5.3.3. Marshalling a non-element

Another common use case is where you have an object that doesn't + have @XmlRootElement on it. Jakarta XML Binding allows you to marshal it + like this:

Example 80. Marshalling a non-element

marshaller.marshal( new JAXBElement(
+  new QName("","rootTag"),Point.class,new Point(...)));

This puts the <rootTag> element as the root element, + followed by the contents of the object, then </rootTag>. You can + actually use it with a class that has @XmlRootElement, + and that simply renames the root element name.

At the first glance the second Point.class + parameter may look redundant, but it's actually necessary to determine + if the marshaller will produce (infamous) + @xsi:type. In this example, both the class and the + instance are Point, so you won't see + @xsi:type. But if they are different, you'll see + it.

This can be also used to marshal a simple object, like + String or an integer.

Marshalling a non-element with + @xsi:type

marshaller.marshal( new JAXBElement(
+  new QName("","rootTag"),String.class,"foo bar"));

But unfortunately it cannot be + used to marshal objects like List or Map, as + they aren't handled as the first-class citizen in the Jakarta XML Binding + world.

5.3.4. Connecting to other XML APIs

Because of the Source and Result + support, Jakarta XML Binding objects can be easily marshalled into other XML APIs + that are not mentioned here. For example, dom4j has + DocumentResult that extends Result, so you + can do:

Example 81. Marshalling to dom4j

DocumentResult dr = new DocumentResult();
+marshaller.marshal( object, dr );
+o = dr.getDocument();

Similar mechanism is available for JDOM and XOM. This conversion + is much more efficient than first marshalling to + ByteArrayOutputStream and then read it back into these + DOMs. The same mechanism can be used to marshal to FastInfoset or send the + marshaled document to an XSLT engine (TransformerHandler.)

The other interesting connector is JAXBSource, + which wraps a marshaller and allows a Jakarta XML Binding object to be used as a + "source" of XML. Many XML APIs take Source as an input, + and now Jakarta XML Binding object can be passed to them directly.

For example, you can marshal a Jakarta XML Binding object and unmarshal it into + another JAXBContext like this:

Example 82. Loading into a different JAXBContext

JAXBContext context1 = ... ;
+JAXBContext context2 = ... ;
+
+context1.createUnmarshaller().unmarshal( new JAXBSource(context2,object) );

This amounts to looking at the same XML by using different + schema, and again this is much more efficient than going through + ByteArrayOutputStream.

5.4. Interaction between marshalling and DOM

Sometimes you may notice that Jakarta XML Binding is producing XML with seemingly + unnecessary namespace declarations. In this section, we'll discuss the + possible causes and how to resolve this.

5.4.1. Caused by DOM mapping

The #1 cause of extra namespace declarations is due to the DOM + mapping. This mainly happens because of a schema construct that forces + XJC to generate a property with DOM. This includes the use of wildcard + <xs:any/> (see more about this Mapping of <xs:any />), as well as xs:anyType + (which can also happen by omission, such as <xs:element + name="foo"/>, which is interpreted as <xs:element + name="foo" type="xs:anyType" />.

During unmarshalling, when a subtree of the input XML is + converted into XML, Jakarta XML Binding copies all the in-scope namespace bindings + active at that time to the root of the DOM element. So for example, + given the following Java class and XML, the DOM tree that the + child field will get will look like the following:

Example 83. Bean with wildcard

@XmlRootElement
+class Foo {
+  @XmlAnyElement
+  public Element child;
+}

Example 84. Instance with subtree matching wildcard

<foo xmlns:a="a" xmlns:b="b" xmlns:c="c">
+  <subtree xmlns:c="cc">
+    <data>a:xyz</data>
+  </subtree>
+</foo>

Example 85. DOM tree to be stored in Foo.child

<subtree xmlns:a="a" xmlns:b="b" xmlns:c="cc">
+    <data>a:xyz</data>
+  </subtree>

Note that the two namespace declarations are copied over, but + c is not because it's overridden. Also not that Jakarta XML Binding is + not touching the whitespace in document. This copying of namespace + declarations is necessary to preserve the infoset in the input + document. For example, if the <data> is a QName, its meaning + would change if Jakarta XML Binding unmarshaller doesn't copy it.

Now, imagine what happens when you marshal this back to XML. + Despite the fact that in this example neither b nor + c prefixes are in use, Jakarta XML Binding cannot delete them, because + it doesn't know if those attributes are significant to the application + or not. Therefore, this could end up producing XML with "extra + namespace declarations" like:

Example 86. DOM tree to be stored in Foo.child

<foo>
+  <subtree xmlns:a="a" xmlns:b="b" xmlns:c="cc">
+    <data>a:xyz</data>
+  </subtree>
+</foo>

Resolving this problem is not possible in the general case, but + sometimes one of the following strategy works:

  1. Sometimes schema author incorrectly assumes that + <xs:element name="foo"/> means + <xs:element name="foo" type="xs:string"/>, + because attribute declarations work somewhat like this. In + such a case, adding explicit type attribute + avoids the use of DOM, so things will work as expected.

  2. The wildcard processing mode " strict" + would force a typed binding, and thereby eliminate any DOM + mapping.

  3. You might be able to manulally go into the DOM tree and + remove unnecessary namespace declarations, if your application + knows what are necessary and what are not.

6. Schema Generation

6.1. Invoking schemagen programatically

Schemagen tools by default come in as CLI, ant task, and Maven + plugin. These interfaces allow you to invoke schemagen functionality from + your program.

6.1.1. At runtime

If the classes you'd like to generate schema from are already + available as java.lang.Class objects (meaning they are + already loaded and resolved in the current JVM), then the easiest way + to generate a schema is to use the Jakarta XML Binding API:

Example 87. Generate schema at runtime

File baseDir = new File(".");
+
+class MySchemaOutputResolver extends SchemaOutputResolver {
+    public Result createOutput( String namespaceUri, String suggestedFileName ) throws IOException {
+        return new StreamResult(new File(baseDir,suggestedFileName));
+    }
+}
+
+JAXBContext context = JAXBContext.newInstance(Foo.class, Bar.class, ...);
+context.generateSchema(new MySchemaOutputResolver());

6.1.2. CLI interface

The CLI + interface (public static int + com.sun.tools.jxc.SchemaGenerator.run(String[])) is the + easiest API to access. You can pass in all the schemagen command-line + arguments as a string array, and get the exit code as an int value. + Messages are sent to System.err and + System.out.

6.1.3. Ant interface

Ant task can be invoked very easily from a non-Ant program. The + schemagen ant task is defined in the + SchemaGenTask class,

6.1.4. Native Java API

The above two interfaces are built on top of externally + committed contracts, so they'll evolve only in a compatibile way. The + downside is that the amount of control you can exercise over them + would be limited.

So yet another approach to invoke schemagen is to use Eclipse Implementation of JAXB's + internal interfaces. But be warned that those interfaces are subject + to change in the future versions, despite our best effort to preserve + them. This is the API that the Eclipse Implementation of XML Web Services uses to generate schema + inside WSDL when they generate WSDL, so does some other web services + toolkits that work with the Eclipse Implementation of JAXB.

Most of those interfaces are defined and well-documented in + the com.sun.tools.xjc.api package. You can see how the schemagen + tools are eventually calling into this API at the + implementaion of SchemaGenerator class.

6.2. Generating Schema that you want

This section discusses how you can change the generated XML schema. + For changes that also affect the infoset (such as changing elements to + attributes, namespaces, etc.), refer to a different section "XML + layout and in-memory data layout".

6.2.1. Adding facets to datatypes

As of Eclipse Implementation of JAXB 4.0.0, currently no support for this, although there + has been several discussions in the users alias.

The Eclipse Implementation of JAXB project is currently lacking resources to attack this + problem, and therefore looking for volunteers to work on this project. + The basic idea would be to define enough annotations to cover the + basic constraint facets (such as length, enumerations, pattern, etc.) + The schema generator would have to be then extended to honor those + annotations and generate schemas accordingly.

Some users pointed out relevance of this to Jakarta Bean Validation. + If you are interested in picking up this task, let us know!

7. Deployment

7.1. Using Eclipse Implementation of JAXB with Maven

7.1.1. Maven coordinates for Eclipse Implementation of JAXB artifacts

  • jakarta.xml.bind:jakarta.xml.bind-api: API classes for Jakarta XML Binding. + Required to compile against Jakarta XML Binding.

  • org.glassfish.jaxb:jaxb-core: Contains sources required by XJC, + JXC and Runtime modules.

  • org.glassfish.jaxb:jaxb-runtime: Contains the main runtime used + for serialization and deserialization java objects to/from xml.

  • org.glassfish.jaxb:jaxb-xjc: Tool to generate Jakarta XML Binding java sources + from XML representation.

  • org.glassfish.jaxb:jaxb-jxc: Tool to generate XML schema from + Jakarta XML Binding java sources.

7.1.2. JAXB RI bundles

  • com.sun.xml.bind:jaxb-core: Contains sources required by XJC, + JXC and Runtime modules with dependencies.

  • com.sun.xml.bind:jaxb-impl: Eclipse Implementation of JAXB runtime jar.

  • com.sun.xml.bind:jaxb-xjc: Class generation tool jar.

  • com.sun.xml.bind:jaxb-jxc: Schema generation tool jar.

In contrast to org.glassfish.jaxb artifacts, these jars have all dependency classes included inside. +

7.1.3. Binary distribution

  • com.sun.xml.bind:jaxb-ri: Zip distribution containing tooling + scripts and all dependency jars in one archive.

7.1.4. Jakarta XML Binding API and Runtime

+ Minimum requirement to compile is jakarta.xml.bind-api.jar. If a client application is running on an environment + where Jakarta XML Binding + runtime is provided, jakarta.xml.bind-api.jar is all that is needed. +

Example 88. API only

+                <!-- API -->
+                <dependency>
+                    <groupId>jakarta.xml.bind</groupId>
+                    <artifactId>jakarta.xml.bind-api</artifactId>
+                    <version>4.0.0</version>
+                </dependency>


+ If client application needs to include the runtime, e.g. running standalone on Java SE + jaxb-impl should be also included. +

Example 89. API + Runtime

+                <!-- API -->
+                <dependency>
+                    <groupId>jakarta.xml.bind</groupId>
+                    <artifactId>jakarta.xml.bind-api</artifactId>
+                    <version>4.0.0</version>
+                </dependency>
+
+                <!-- Runtime -->
+                <dependency>
+                    <groupId>com.sun.xml.bind</groupId>
+                    <artifactId>jaxb-impl</artifactId>
+                    <version>4.0.0</version>
+                </dependency>


7.1.5. Using Eclipse Implementation of JAXB tools for java sources and XML schema generation

+ To generate Jakarta XML Binding classes from schema in Maven project, there are multiple community plugins + available: +

  • The most advanced and feature-full Maven plugin for XML Schema compilation: + highsource maven-jaxb2-plugin +

    Example 90. Using highsource maven-jaxb2-plugin

    +                <build>
    +                    <plugins>
    +                        <plugin>
    +                            <groupId>org.jvnet.jaxb2.maven2</groupId>
    +                            <artifactId>maven-jaxb2-plugin</artifactId>
    +                            <executions>
    +                                <execution>
    +                                    <goals>
    +                                        <goal>generate</goal>
    +                                    </goals>
    +                                </execution>
    +                            </executions>
    +                        </plugin>
    +                    </plugins>
    +                </build>


    + See the maven-jaxb2-plugin user guide for configuration details. +

  • A Maven plugin originating from MojoHaus which has been updated for Jakarta XML Binding 3+ by Evolved Binary: + MojoHaus jaxb-maven-plugin +

    Example 91. Using MojoHaus jaxb-maven-plugin

    +                <build>
    +                    <plugins>
    +                        <plugin>
    +                            <groupId>com.evolvedbinary.maven.mojohaus</groupId>
    +                            <artifactId>jaxb-maven-plugin</artifactId>
    +                            <executions>
    +                                <execution>
    +                                    <id>schemagen</id>
    +                                    <goals>
    +                                        <goal>schemagen</goal>
    +                                    </goals>
    +                                </execution>
    +                            </executions>
    +                        </plugin>
    +                    </plugins>
    +                </build>


    + See the MojoHaus jaxb-maven-plugin documentation for configuration details. +

  • A Maven plugin originating from java.net which has been updated for Jakarta XML Binding 3+ by Evolved Binary: + jvnet jaxb-maven-plugin +

    Example 92. Using jvnet jaxb-maven-plugin

    +                <build>
    +                    <plugins>
    +                        <plugin>
    +                            <groupId>com.evolvedbinary.maven.jvnet</groupId>
    +                            <artifactId>jaxb-maven-plugin</artifactId>
    +                            <executions>
    +                                <execution>
    +                                    <id>generate</id>
    +                                    <goals>
    +                                        <goal>generate</goal>
    +                                    </goals>
    +                                </execution>
    +                            </executions>
    +                        </plugin>
    +                    </plugins>
    +                </build>


    + See the jvnet jaxb-maven-plugin documentation for configuration details. +

+

+ Alternatively to community plugins, there are tooling artifacts jaxb-xjc and jaxb-jxc, + which can be used for + java from XML schema generation and vice versa. +

Example 93. Using Eclipse Implementation of JAXB tooling artifacts

+            <!-- Tooling dependencies -->
+            <dependency>
+                <groupId>com.sun.xml.bind</groupId>
+                <artifactId>jaxb-xjc</artifactId>
+                <version>4.0.0</version>
+            </dependency>
+            <dependency>
+                <groupId>com.sun.xml.bind</groupId>
+                <artifactId>jaxb-jxc</artifactId>
+                <version>4.0.0</version>
+            </dependency>
+
+            <!-- Invoke tooling API (Java 11) -->
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>exec-maven-plugin</artifactId>
+                    <!-- Generate java sources from schema -->
+                    <execution>
+                        <id>xjc</id>
+                        <goals>
+                            <goal>exec</goal>
+                        </goals>
+                        <configuration>
+                            <executable>java</executable>
+                            <arguments>
+                                <argument>--module-path</argument>
+                                <modulepath/>
+                                <argument>-m</argument>
+                                <argument>com.sun.tools.xjc</argument>
+                                <argument>-p</argument>
+                                <argument>com.example</argument>
+                                <argument>-d</argument>
+                                <argument>${project.build.directory}/generated-sources</argument>
+                                <argument>${project.build.directory}/classes/schema.xsd</argument>
+                            </arguments>
+                        </configuration>
+                    </execution>
+
+                    <!-- Generate XML Schema from sources -->
+                    <execution>
+                        <id>jxc</id>
+                        <goals>
+                            <goal>exec</goal>
+                        </goals>
+                        <configuration>
+                            <executable>java</executable>
+                            <arguments>
+                                <argument>--module-path</argument>
+                                <modulepath/>
+                                <argument>-m</argument>
+                                <argument>com.sun.tools.jxc</argument>
+                                <argument>-d</argument>
+                                <argument>${project.build.directory}/generated-sources</argument>
+                                <argument>${project.build.directory}/classes/com/example/Author.java</argument>
+                                <argument>${project.build.directory}/classes/com/example/Book.java</argument>
+                            </arguments>
+                            <longModulepath>false</longModulepath>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>


+ See also xml schema compiler usage.

schemagen and xjc command line scripts are available + only in the zip distribution.

7.2. Using Eclipse Implementation of JAXB on JPMS

Java SE 11 features JSR 376 Java Platform Module System. + Starting from version 2.3.2 Eclipse Implementation of JAXB supports JPMS and can be loaded and used from module path. + There are only a few things to be aware of. +

7.2.1. Eclipse Implementation of JAXB classes openness

+ Eclipse Implementation of JAXB does reflectively access private members of the class, so client application if loaded from module path + needs to "open" packages containing jaxb classes to Jakarta XML Binding. There are alternative Jakarta XML Binding implementations, + having different module names, Jakarta XML Binding requires pojo classes to be open only to API module. +

Example 94. JPMS module descriptor opening Jakarta XML Binding pojo classes to Jakarta XML Binding API

+//JPMS module descriptor
+module com.example.jaxbclasses {
+
+    //Jakarta XML Binding module name
+    requires jakarta.xml.bind;
+
+    //open pojo package to make accessing private members possible for Jakarta XML Binding.
+    opens com.example.jaxbclasses.pojos to jakarta.xml.bind;
+}


+ Jakarta XML Binding API will delegate openness to implementation module after resolving it with service discovery mechanism. +

+

Example 95. Eclipse Implementation of JAXB on JPMS Command line examples

+#Both client and Eclipse Implementation of JAXB on module path:
+$ java -m com.example.jaxbclasses/com.example.jaxb.Main --module-path jaxbclient.jar:jakarta.xml.bind-api.jar:jakarta.activation-api.jar:jaxb-core.jar:jaxb-impl.jar
+
+#Both client and Eclipse Implementation of JAXB on classpath:
+$ java com.example.jaxb.Main -cp jaxbclient.jar:jakarta.xml.bind-api.jar:jakarta.activation-api.jar:jaxb-core.jar:jaxb-impl.jar
+
+#Client on classpath, Eclipse Implementation of JAXB on module path:
+$ java com.example.jaxb.Main -cp jaxbclient.jar --module-path jakarta.xml.bind-api.jar:jakarta.activation-api.jar:jaxb-core.jar:jaxb-impl.jar --add-modules jakarta.xml.bind


+ Jakarta XML Binding API will delegate openness to implementation module after resolving it with service discovery mechanism. +

8. Other Miscellaneous Topics

8.1. Performance and thread-safety

The JAXBContext class is thread safe, but the Marshaller, + Unmarshaller, and Validator classes are not thread safe.

For example, suppose you have a multi-thread server application that + processes incoming XML documents by Jakarta XML Binding. In this case, for the best + performance you should have just one instance of JAXBContext in your whole + application like this:

Example 96. Singleton JAXBContext

class MyServlet extends HttpServlet {
+    static final JAXBContext context = initContext();
+
+    private static JAXBContext initContext() {
+        return JAXBContext.newInstance(Foo.class,Bar.class);
+    }
+}

And each time you need to unmarshal/marshal/validate a document. + Just create a new Unmarshaller/Marshaller/Validator from this context, + like this:

Example 97. Thread local Unmarshaller

    public void doGet( HttpServletRequest req, HttpServletResponse ) {
+        Unmarshaller u = context.createUnmarshaller();
+        u.unmarshal(...);
+    }

This is the simplest safe way to use the Eclipse Implementation of JAXB from multi-threaded + applications.

If you really care about the performance, and/or your application is + going to read a lot of small documents, then creating Unmarshaller could + be relatively an expensive operation. In that case, consider pooling + Unmarshaller objects. Different threads may reuse one Unmarshaller + instance, as long as you don't use one instance from two threads at the + same time.

8.2. Compiling DTD

The Eclipse Implementation of JAXB is shipped with an "experimental" DTD support, which + let's you compile XML DTDs. It is marked "experimental" not because the + feature is unstable nor unreliable, but rather because it's not a part of + the JAXB specification and therefore the level of commitment to + compatibility is lower.

Example 98. To compile a DTD, run the XJC binding compiler as + follows:

$ xjc.sh -dtd test.dtd

All the other command-line options of the XJC binding compiler can + be applied. Similarly, the XJC ant task supports DTD. The generated code + will be no different from what is generated from W3C XML Schema. You'll + use the same JAXB API to access the generated code, and it is portable in + the sense that it will run on any JAXB 2.0 implementation.

DTD long predates XML namespace, although people since then + developed various techniques to use XML namespaces in conjunction with + DTD. Because of this, XJC is currently unable to reverse-engineer the use + of XML namespace from DTD. If you compile DTDs that use those techniques, + you'd either manuallly modify the generated code, or you can try a tool + like Trang + that can convert DTD into XML Schema in ways that better preserves XML + namespaces.

8.2.1. Customizations

The customization syntax for DTD is roughly based on the + ver.0.21 working draft of the JAXB specification, which is available + at xml.coverpages.org. + The deviations from this document are:

  • The whitespace attribute of the + conversion element takes " + preserve", " replace", and " + collapse" instead of " preserve", " + normalize", and " collapse" as + specified in the document.

  • The interface customization just generates + marker interfaces with no method.

8.2.2. Compiling DTD from Maven

Example 99. The following POM snippest describes how to invoke XJC to + compile DTD from a Maven project:

<plugin>
+  <groupId>org.jvnet.jaxb2.maven2</groupId>
+  <artifactId>maven-jaxb2-plugin</artifactId>
+  <executions>
+    <execution>
+      <goals>
+        <goal>generate</goal>
+      </goals>
+      <configuration>
+        <!--  if you want to put DTD somewhere else
+        <schemaDirectory>src/main/jaxb</schemaDirectory>
+        -->
+        <extension>true</extension>
+        <schemaLanguage>DTD</schemaLanguage>
+        <schemaIncludes>
+          <schemaInclude>*.dtd</schemaInclude>
+        </schemaIncludes>
+        <bindingIncludes>
+          <bindingInclude>*.jaxb</bindingInclude>
+        </bindingIncludes>
+        <args>
+          <arg>-Xinject-listener-code</arg>
+        </args>
+      </configuration>
+    </execution>
+  </executions>
+  <dependencies>
+    <dependency>
+      <groupId>org.jvnet.jaxb2-commons</groupId>
+      <artifactId>property-listener-injector</artifactId>
+      <version>1.0</version>
+    </dependency>
+  </dependencies>
+</plugin>

Example 100. The dependencies section inside the plugin element can be + used to specify additional XJC plugins. If you'd like to use more + recent version of the Eclipse Implementation of JAXB, you can specify a dependency to XJC + here to do so, like this:

<dependency>
+  <groupId>com.sun.xml.bind</groupId>
+  <artifactId>jaxb-xjc</artifactId>
+  <version>4.0.0</version>
+</dependency>

8.3. Designing a client/server protocol in XML

Occasionally, people try to define a custom protocol that allows + multiple XML requests/responses to be sent over a single transport channel. + This section discusses the non-trivial interaction between XML and + sockets, and how you can design a protocol correctly.

XML1.0 requires a conforming parser to read the entire data till end + of the stream (because a parser needs to handle documents like + <root/><!-- post root comment -->). As a result, + a naive attempt to keep one OutputStream open and marshal + objects multiple times fails.

Example 101. One easy way to work around this limitation is to design your + protocol so that the data on the wire will look like the + following:

<conversation>
+  <!-- message 1 -->
+  <message>
+    ...
+  </message>
+
+  <!-- message 2 -->
+  <message>
+    ...
+  </message>
+
+  ...
+</conversation>

The <conversation> start tag is sent immediately after the + socket is opened. This works as a container to send multiple "messages", + and this is also an excellent opportunity to do the hand-shaking (e.g., + protocol-version='1.0' attribute.) Once the + <conversation> tag is written, multiple messages can be marshalled + as a tree into the channel, possibly with a large time lag in between. You + can use the Jakarta XML Binding marshaller to produce such message. When the sender wants + to disconnect the channel, it can do so by sending the + </conversation> end tag, followed by the socket + disconnection.

Of course, you can choose any tag names freely, and each message can + have different tag names.

The receiver would use the StAX API and use + XMLStreamReader to read this stream. You'd have to use this + to process the first <conversation> start tag. After that, every + time you call a Jakarta XML Binding unmarshaller, you'll get the next message.

For the concrete code, see the xml-channel example in + the Eclipse Implementation of JAXB distribution.

\ No newline at end of file diff --git a/scripts/jaxb-ri/docs/ch04.html b/scripts/jaxb-ri/docs/ch04.html new file mode 100644 index 0000000..9be9234 --- /dev/null +++ b/scripts/jaxb-ri/docs/ch04.html @@ -0,0 +1,466 @@ + + + ToolsLinks: Table of Contents | Single HTML | Single PDF

Tools

1. XJC

1.1. xjc Overview

Eclipse Implementation of JAXB also provides an Ant task to run the binding complier - + see the instructions for XJC Ant Task.

1.2. Launching xjc

The binding compiler can be launched using the appropriate + xjc shell script in the bin + directory for your platform.

  • Solaris/Linux

    % /path/to/jaxb/bin/xjc.sh -help
  • Windows

    > c:\path\to\jaxb\bin\xjc.bat -help

1.2.1. Execute the jaxb-xjc.jar JAR + File

If all else fails, you should be able to execute the + jaxb-xjc.jar file:

  • Solaris/Linux

    % java -jar $JAXB_HOME/lib/jaxb-xjc.jar -help
  • Windows

    > java -jar %JAXB_HOME%\lib\jaxb-xjc.jar -help

This is equivalent of running xjc.sh or + xjc.bat, and it allows you to set the JVM + parameters.

1.3. xjc Syntax

xjc [OPTION]... <schema file/URL/dir/jar> [-b <binding>...]

Usage: xjc [-options ...] <schema file/URL/dir/jar> ... [-b <bindinfo>] ...
+If dir is specified, all schema files in it will be compiled.
+If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.
+Options:
+  -nv                :  do not perform strict validation of the input schema(s)
+  -extension         :  allow vendor extensions - do not strictly follow the
+                        Compatibility Rules and App E.2 from the JAXB Spec
+  -b <file/dir>      :  specify external bindings files (each <file> must have its own -b)
+                        If a directory is given, **/*.xjb is searched
+  -d <dir>           :  generated files will go into this directory
+  -p <pkg>           :  specifies the target package
+  -httpproxy <proxy> :  set HTTP/HTTPS proxy. Format is [user[:password]@]proxyHost:proxyPort
+  -httpproxyfile <f> :  Works like -httpproxy but takes the argument in a file to protect password 
+  -classpath <arg>   :  specify where to find user class files
+  -catalog <file>    :  specify catalog files to resolve external entity references
+                        support TR9401, XCatalog, and OASIS XML Catalog format.
+  -readOnly          :  generated files will be in read-only mode
+  -npa               :  suppress generation of package level annotations (**/package-info.java)
+  -no-header         :  suppress generation of a file header with timestamp
+  -target (2.0|2.1)  :  behave like XJC 2.0 or 2.1 and generate code that doesn't use any 2.2 features.
+  -encoding <encoding> :  specify character encoding for generated source files
+  -enableIntrospection :  enable correct generation of Boolean getters/setters to enable Bean Introspection apis 
+  -disableXmlSecurity  :  disables XML security features when parsing XML documents 
+  -contentForWildcard  :  generates content property for types with multiple xs:any derived elements 
+  -xmlschema         :  treat input as W3C XML Schema (default)
+  -relaxng           :  treat input as RELAX NG (experimental,unsupported)
+  -relaxng-compact   :  treat input as RELAX NG compact syntax (experimental,unsupported)
+  -dtd               :  treat input as XML DTD (experimental,unsupported)
+  -wsdl              :  treat input as WSDL and compile schemas inside it (experimental,unsupported)
+  -verbose           :  be extra verbose
+  -quiet             :  suppress compiler output
+  -help              :  display this help message
+  -version           :  display version information
+  -fullversion       :  display full version information
+
+Extensions:
+  -Xinject-code      :  inject specified Java code fragments into the generated code
+  -Xlocator          :  enable source location support for generated code
+  -Xsync-methods     :  generate accessor methods with the 'synchronized' keyword
+  -mark-generated    :  mark the generated code as @javax.annotation.Generated
+  -episode           :  generate the episode file for separate compilation
+  -Xpropertyaccessors :  Use XmlAccessType PROPERTY instead of FIELD for generated classes

1.3.1. Summary of Command Line Options

-nv

By default, the XJC binding compiler performs + strict validation of the source schema before + processing it. Use this option to disable strict + schema validation. This does not mean that the binding + compiler will not perform any validation, it simply + means that it will perform less-strict + validation.

-extension

By default, the XJC binding compiler strictly + enforces the rules outlined in the Compatibility + chapter of the Jakarta XML Binding Specification. Appendix E.2 + defines a set of W3C XML Schema features that are not + completely supported by JAXB v1.0. In some cases, you + may be allowed to use them in the "-extension" mode + enabled by this switch. In the default (strict) mode, + you are also limited to using only the binding + customizations defined in the specification. By using + the "-extension" switch, you will be allowed to use + the Overview.

-b + <file>

Specify one or more external binding files to + process. (Each binding file must have it's own -b switch.) The syntax of the external + binding files is extremely flexible. You may have a + single binding file that contains customizations for + multiple schemas or you can break the customizations + into multiple bindings files:

xjc schema1.xsd schema2.xsd schema3.xsd -b bindings123.xjb
+xjc schema1.xsd schema2.xsd schema3.xsd -b bindings1.xjb -b bindings2.xjb -b bindings3.xjb

In addition, + the ordering of the schema files and binding files on + the command line does not matter.

-d + <dir>

By default, the XJC binding compiler will + generate the Java content classes in the current + directory. Use this option to specify an alternate + output directory. The output directory must already + exist, the XJC binding compiler will not create it for + you.

-encoding + <encoding>

Set the encoding name for generated sources, + such as EUC-JP or UTF-8. If -encoding is + not specified, the platform default encoding is + used.

-p + <pkg>

Specifying a target package via this + command-line option overrides any binding + customization for package name and the default package + name algorithm defined in the specification.

-httpproxy + <proxy>

Specify the HTTP/HTTPS proxy. The format is + [user[:password]@]proxyHost[:proxyPort]. The old -host and -port are still + supported by the RI for backwards compatibility, but + they have been deprecated.

-httpproxyfile + <f>

Same as the -httpproxy + <proxy> option, but it takes the + <proxy> parameter in a file, so that you can + protect the password (passing a password in the + argument list is not safe.)

-classpath + <arg>

Specify where to find client application class + files used by the <jxb:javaType> + and <xjc:superClass> + customizations.

-catalog + <file>

Specify catalog files to resolve external entity + references. Supports TR9401, XCatalog, and OASIS XML + Catalog format. Please read the XML Entity and URI + Resolvers document or the + catalog-resolver sample + application.

-readOnly

By default, the XJC binding compiler does not + write-protect the Java source files it generates. Use + this option to force the XJC binding compiler to mark + the generated Java sources read-only.

-npa

Supress the generation of package level + annotations into **/package-info.java. Using this + switch causes the generated code to internalize those + annotations into the other generated classes.

-no-header

Supress the generation of a file header comment + that includes some note and timestamp. Using this + makes the generated code more + diff-friendly.

-target (2.0|2.1)

Avoid generating code that relies on any JAXB + 2.1|2.2 features. This will allow the generated code to + run with JAXB 2.0 runtime (such as JavaSE 6.)

-xmlschema

treat input schemas as W3C XML Schema (default). + If you do not specify this switch, your input schemas + will be treated as W3C XML Schema.

-relaxng

Treat input schemas as RELAX NG (experimental, + unsupported). Support for RELAX NG schemas is provided + as a Overview.

-relaxng-compact

Treat input schemas as RELAX NG compact + syntax(experimental, unsupported). Support for RELAX + NG schemas is provided as a Overview.

-dtd

Treat input schemas as XML DTD (experimental, + unsupported). Support for RELAX NG schemas is provided + as a Overview.

-wsdl

Treat input as WSDL and compile schemas inside + it (experimental,unsupported).

-quiet

Suppress compiler output, such as progress + information and warnings..

-verbose

Be extra verbose, such as printing informational + messages or displaying stack traces upon some + errors..

-help

Display a brief summary of the compiler + switches.

-version

Display the compiler version information.

-fullversion

Display the compiler full version information.

<schema + file/URL/dir>

Specify one or more schema files to compile. If + you specify a directory, then xjc will scan it for all + schema files and compile them.

-Xlocator

This feature causes the generated code to expose + SAX Locator information about the source XML in the + Java bean instances after unmarshalling.

-Xsync-methods

This feature causes all of the generated method + signatures to include the synchronized keyword.

-mark-generated

This feature causes all of the generated code to + have + @Generated annotation.

-episode + <FILE>

Generate an episode file from this compilation, + so that other schemas that rely on this schema can be + compiled later and rely on classes that are generated + from this compilation. The generated episode file is + really just a Jakarta XML Binding customization file (but with vendor + extensions.)

-Xinject-code
-Xpropertyaccessors>

Annotate the @XmlAccessorType + of generated classes with XmlAccessType PROPERTY + instead of FIELD

1.3.2. Summary of Deprecated and Removed Command Line + Options

-host & + -port

These options have been deprecated and replaced + with the -httpproxy + option. For backwards compatibility, we will continue + to support these options, but they will no longer be + documented and may be removed from future + releases.

-use-runtime

Since the Jakarta XML Binding specification has defined a + portable runtime, it is no longer necessary for the + Eclipse Implementation of JAXB to generate **/impl/runtime packages. + Therefore, this switch is obsolete and has been + removed.

1.4. Compiler Restrictions

In general, it is safest to compile all related schemas as a + single unit with the same binding compiler switches.

Please keep the following list of restrictions in mind when + running xjc. Most of these issues only apply when compiling multiple + schemas with multiple invocations of xjc.

  • To compile multiple schemas at the same time, keep the + following precedence rules for the target Java package name in + mind:

    1. The -p command line option + takes the highest precedence.

    2. <jaxb:package> + customization

    3. If targetNamespace is declared, + apply targetNamespace -> Java + package name algorithm defined in the + specification.

    4. If no targetNamespace is + declared, use a hardcoded package named + "generated".

  • It is not legal to have more than one < + jaxb:schemaBindings> per namespace, so it is + impossible to have two schemas in the same target namespace + compiled into different Java packages.

  • All schemas being compiled into the same Java package + must be submitted to the XJC binding compiler at the same time + - they cannot be compiled independently and work as + expected.

  • Element substitution groups spread across multiple + schema files must be compiled at the same time.

1.5. Generated Resource Files

XJC produces a set of packages containing Java source files and + also jaxb.properties files, depending on the binding + options you used for compilation. When generated, + jaxb.properties files must be kept with the compiled + source code and made available on the runtime classpath of your client + applications:

2. XJC Ant Task

2.1. xjc Task Overview

The jaxb-xjc.jar file contains the + XJCTask.class file, which allows the XJC binding + compiler to be invoked from the Ant build tool. To + use XJCTask, include the following statement in + your build.xml file:

<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath>
+        <fileset dir="path/to/jaxb/lib" includes="*.jar"/>
+    </classpath>
+</taskdef>

This maps XJCTask to an Ant task named + xjc. For detailed examples of using this task, + refer to any of the build.xml files used by the Sample Apps.

2.2. xjc Task Attributes

2.2.1. Environment Variables

  • ANT_OPTS + - command-line arguments that should be passed to the JVM. + For example, you can define system properties or set the + maximum Java heap size here.

2.2.2. Parameter Attributes

xjc supports the following parameter + attributes.

AttributeDescriptionRequired

schema

A schema file to be compiled. A file + name (can be relative to the build script base + directory), or an URL.

This or nested < + schema> elements are + required.

binding

An external binding file that will be + applied to the schema file.

No

package

If specified, generated code will be + placed under this Java package. This option is + equivalent to the "-p" command-line + switch.

No

destdir

Generated code will be written under + this directory. If you specify + destdir="abc/def" and + package="org.acme", then files + are generated to + abc/def/org/acme.

Yes

disableXmlSecurity

Disable XML security features when parsing XML documents. + false by default.

No

encoding

Set the encoding name for generated + sources, such as EUC-JP or UTF-8. If it is not + specified, the platform default encoding is + used.

No

readonly

Generate Java source files in the + read-only mode if true is + specified. false by + default.

No

header

Generate a header in each generated + file indicating that this file is generated by such + and such version of Eclipse Implementation of JAXB when. + true by default.

No

extension

If set to true, the XJC + binding compiler will run in the extension mode. + Otherwise, it will run in the strict conformance + mode. Equivalent of the " + -extension" command line switch. + The default is + false.

No

catalog

Specify the catalog file to resolve + external entity references. Support TR9401, + XCatalog, and OASIS XML Catalog format. See the + catalog-resolver sample for details.

No

removeOldOutput

Used in pair with nested + <produces> elements. When + this attribute is specified as " yes", + the files pointed to by the + <produces> elements will be + all deleted before the XJC binding compiler + recompiles the source files. See the up-to-date + check section for details.

No

target

Specifies the runtime environment in + which the generated code is supposed to run. Expects 2.0 or 2.1 values. + This allows more up-to-date versions of XJC to be used for + developing applications that run on earlier JAXB + versions.

No, defaults to "2.2"

language

Specifies the schema language to + compile. Supported values are "WSDL", "XMLSCHEMA", + and "WSDL." Case insensitive.

No, defaults to + "XMLSCHEMA"

2.2.3. Nested Elements

xjc supports the following nested element + parameters.

2.2.3.1. schema

To compile more than one schema at the same time, use a + nested <schema> element, which has + the same syntax as + <fileset> .

2.2.3.2. binding

To specify more than one external binding file at the + same time, use a nested <binding> + element, which has the same syntax as + <fileset> .

2.2.3.3. classpath

To specify locations of the user-defined classes + necessary during the compilation (such as an user-defined type + that is used through a <javaType> + customization), use nested + <classpath> elements. For the syntax, + see "path-like + structure" .

2.2.3.4. arg

Additional command line arguments passed to the XJC. For + details about the syntax, see the + relevant section in the Ant manual. This nested element + can be used to specify various options not natively supported + in the xjc Ant task. For example, currently there + is no native support for the following xjc + command-line options:

  • -nv

  • -use-runtime

  • -schema

  • -dtd

  • -relaxng

  • -Xlocator

  • -Xsync-methods

To use any of these features from the + <xjc> Ant task, you must specify the + appropriate nested < arg> elements.

2.2.3.5. depends

Files specified with this nested element will be taken + into account when the XJC task does the up-to-date check. See + the up-to-date check section for details. For the syntax, see + + <fileset> .

2.2.3.6. produces

Files specified with this nested element will be taken + into account when the XJC task does the up-to-date check. See + the up-to-date check section for details. For the syntax, see + + <fileset> .

2.2.3.7. xmlcatalog

The xmlcatalog + element is used to resolve entities when parsing schema + documents.

2.3. Generated Resource Files

Please see the Generated Resource Files for more detail.

2.4. Up-to-date Check

By default, the XJC binding compiler always compiles the inputs. + However, with a little additional setting, it can compare timestamps + of the input files and output files and skip compilation if the files + are up-to-date.

Ideally, the program should be able to find out all the inputs + and outputs and compare their timestamps, but this is difficult and + time-consuming. So you have to tell the task input files and output + files manually by using nested <depends> and + <produces> elements. Basically, the XJC + binding compiler compares the timestamps specified by the + <depends> elements against those of the + <produces> set. If any one of the "depends" + file has a more recent timestamp than some of the files in the + "produces" set, it will compile the inputs. Otherwise it will skip the + compilation.

This will allow you to say, for example "if any of the + .xsd files in this directory are newer than the + .java files in that directory, recompile the + schema".

Files specified as the schema files and binding files are + automatically added to the "depends" set as well, but if those schemas + are including/importing other schemas, you have to use a nested + <depends> elements. No files are added to the + <produces> set, so you have to add all of + them manually.

A change in a schema or an external binding file often results + in a Java file that stops being generated. To avoid such an "orphan" + file, it is often desirable to isolate all the generated code into a + particular package and delete it before compiling a schema. This can + be done by using the removeOldOutput attribute. + This option allows you to remove all the files that match the + "produces" filesets before a compilation. Be careful when + you use this option so that you don't delete important + files.

2.5. Schema Language Support

This release of the Eclipse Implementation of JAXB includes experimental support for + RELAX NG, DTD, and WSDL. To compile anything other than W3C XML Schema + from the xjc Ant task, you must use the nested < + arg> element to specify the appropriate command line + switch, such as -dtd, -relaxng, or -wsdl. Otherwise, your input schemas will be treated as + W3C XML Schema and the binding compiler will fail.

2.6. xjc Examples

Compile myschema.xsd and place the generated + files under src/org/acme/foo:

<xjc schema="src/myschema.xsd" destdir="src" package="org.acme.foo"/>

Compile all XML Schema files in the src + directory and place the generated files under the appropriate packages + in the src directory:

<xjc destdir="src">
+    <schema dir="src" includes="*.xsd"/>
+</xjc>

Compile all XML Schema files in the src + directory together with binding files in the same directory and places + the generated files under the appropriate packages in the + src directory. This example assumes that binding + files contain package customizations. This example doesn't search + subdirectories of the src directory to look for + schema files.

<xjc destdir="src">
+    <schema dir="src" includes="*.xsd"/>
+    <binding dir="src" includes="*.xjb"/>
+</xjc>

Compile abc.xsd with an up-to-date check. + Compilation only happens when abc.xsd is newer than + any of the files in the src/org/acme/foo directory + (and its impl subdirectory). Files in these two + directories will be wiped away before a compilation, so + don't add your own code in those directories. + Note that the additional mkdir task is necessary + because Ant's fileset requires the directory specified by the + dir attribute to exist.

<mkdir dir="src/org/acme/foo"/>
+<xjc destdir="src" schema="abc.xsd" removeOldOutput="yes"
+     package="org.acme.foo">
+    <produces dir="src/org/acme/foo" includes="* impl/*"/>
+</xjc>

More complicated example of up-to-date check. In this example, + we assume that you have a large set of schema documents that reference + each other, with DTDs that describe the schema documents. An explicit + <depends> is necessary so that when you update one of the DTDs, + XJC will recompile your schema. But <depends> don't have to + re-specify all the schema files, because you've already done that via + <schema>.

<mkdir dir="src/org/acme/foo"/>
+<xjc destdir="src" removeOldOutput="yes"
+     package="org.acme.foo">
+    <schema dir="schema" includes="*.xsd"/>
+    <depends dir="schema" includes="*.dtd"/>
+    <produces dir="build/generated-src/org/acme/foo"
+              includes="**/*"/>
+</xjc>

Compile all XML Schema files in the src + directory and subdirectories, excluding files named + debug.xsd, and place the generated files under the + appropriate packages in the src directory. This + example also specifies the -nv option, which disables + the strict schema correctness checking:

<xjc destdir="src">
+    <schema dir="src" includes="**/*.xsd"
+            excludes="**/debug.xsd"/>
+    <arg value="-nv"/>
+</xjc>

If you depend on a proxy server to resolve the location of + imported or included schemas (as you might if you're behind a + firewall), you need to make the hostname and port number accessible to + the JVM hosting ant. Do this by setting the + environment variable ANT_OPTS to a string + containing the appropriate java options. For + example, from DOS:

> set ANT_OPTS=-Dhttp.proxyHost=webcache.east
+> set ANT_OPTS=%ANT_OPTS% -Dhttp.proxyPort=8080
+> ant

3. SchemaGen

3.1. schemagen Overview

The current schema generator can process either Java source + files or class files.

We also provide an Ant task to run the schema generator - see + the instructions for SchemaGen Ant Task.

3.2. Launching schemagen

The schema generator can be launched using the appropriate + schemagen shell script in the + bin directory for your platform.

If your java sources/classes reference other classes, they must + be accessable on your system CLASSPATH environment variable, or they + need to be given to the tool by using the -classpath/ + -cp options. Otherwise you will see errors when + generating your schema.

  • Solaris/Linux

    % path/to/jaxb/bin/schemagen.sh Foo.java Bar.java ...
    +Note: Writing schema1.xsd
  • Windows

    > path\to\jaxb\bin\schemagen.bat Foo.java Bar.java ...
    +Note: Writing schema1.xsd

3.3. schemagen Syntax

schemagen [OPTION]... <java files>

Usage: schemagen [-options ...] <java files> 
+
+Options: 
+    -d <path>             : specify where to place processor and javac generated class files
+    -cp <path>            : specify where to find user specified files
+    -classpath <path>     : specify where to find user specified files
+    -encoding <encoding>  : specify encoding to be used for annotation processing/javac invocation
+    -episode <file>       : generate episode file for separate compilation
+    -disableXmlSecurity   : disables XML security features when parsing XML documents
+    -version              : display version information
+    -fullversion          : display full version information
+    -help                 : display this usage message

3.3.1. Summary of Command Line Options

-d + <dir>

By default, the schema generator will + generate the content in the current + directory. Use this option to specify an alternate + output directory. The output directory must already + exist, the schema generator will not create it for + you.

-encoding + <encoding>

Set the encoding name for generated sources, + such as EUC-JP or UTF-8. If -encoding is + not specified, the platform default encoding is + used.

-classpath + <arg>

Specify where to find client application class + files.

-episode

Generates the "episode file", which is really + just a Jakarta XML Binding customization file (but with vendor + extensions). When people develop additional schemas that + depend on what this schemagen invocation produces, they can use this + episode file to have their generated code refer to + your classes.

-help

Display a brief summary of the generator + switches.

-version

Display the compiler version information.

-fullversion

Display the compiler full version information.

3.4. Generated Resource Files

The current schema generator simply creates a schema file for + each namespace referenced in your Java classes. There is no way to + control the name of the generated schema files at this time. Use SchemaGen Ant Task for + that purpose.

4. SchemaGen Ant Task

4.1. schemagen Task Overview

The jaxb-jxc.jar file contains the + SchemaGenTask.class file, which allows the schema + generator to be invoked from the Ant build tool. To + use SchemaGenTask, include the following statement + in your build.xml file:

<taskdef name="schemagen"
+         classname="com.sun.tools.jxc.SchemaGenTask">
+    <classpath>
+        <fileset dir="path/to/jaxb/lib" includes="*.jar"/>
+    </classpath>
+</taskdef>

This maps SchemaGenTask to an Ant task named + schemagen. For detailed examples of using this + task, refer to the build.xml files used by the java to + schema Sample Apps.

4.2. schemagen Task Attributes

4.2.1. Environment Variables

  • ANT_OPTS + - command-line arguments that should be passed to the JVM. + For example, you can define system properties or set the + maximum Java heap size here.

4.2.2. Parameter Attributes

schemagen supports most of the attributes + defined by the + javac task, plus the following parameter attributes.

AttributeDescriptionRequired

destdir

Base directory to place the generated + schema files

No

classpath

Works just like the nested + <classpath> element

No

episode

If specified, generate an episode file + in the specified name. For more about the episode + file, see -episode.

No

4.2.3. Nested Elements

xjc supports all the nested elements + defined by the + javac task, the following nested element parameters.

4.2.3.1. schema

Control the file name of the generated schema. This + element takes a mandatory namespace attribute and + a mandaotry file attribute. When this element is + present, the schema document generated for the specified + namespace will be placed in the specified file name.

The file name is interpreted as relative to the destdir + attribute. In the absence of the destdir attribute, file names + are relative to the project base directory. This element can + be specified multiple times.

4.2.3.2. classpath

A path-like + structure that represents the classpath. If your Java + sources/classes depend on other libraries, they need to be + available in the classpath.

4.3. schemagen Examples

Generate schema files from source files in the src + dir and place them in the build/schemas directory.

<schemagen srcdir="src" destdir="build/schemas">

Compile a portion of the source tree.

<schemagen destdir="build/schemas">
+    <src path="src"/>
+    <exclude name="Main.java"/>
+</schemagen>

Set schema file names.

<schemagen srcdir="src" destdir="build/schemas">
+    <schema namespace="http://myschema.acme.org/common"
+            file="myschema-common.xsd"/>
+    <schema namespace="http://myschema.acme.org/onion"
+            file="myschema-onion.xsd"/>
+</schemagen>

5. 3rd Party Tools

5.1. Maven JAXB Plugin

If you are using Maven, JAXB + jars are available in + the maven central repository.

5.2. XJC Plugins

Various people in the community have developed plugins for + XJC that you can use today. These plugins allow you to + enhance/alter the code generation of XJC in many different + ways.

5.3. RDBMS Persistence

Lexi has developed the + HyperJAXB3 + project for RDBMS persistence support for the Eclipse Implementation of JAXB.

\ No newline at end of file diff --git a/scripts/jaxb-ri/docs/ch05.html b/scripts/jaxb-ri/docs/ch05.html new file mode 100644 index 0000000..41d227b --- /dev/null +++ b/scripts/jaxb-ri/docs/ch05.html @@ -0,0 +1,612 @@ + + + Eclipse Implementation of JAXB ExtensionsLinks: Table of Contents | Single HTML | Single PDF

Eclipse Implementation of JAXB Extensions

1. Overview

This page contains information about vendor-specific features + provided by the Eclipse Implementation of JAXB.

Runtime Properties

This document describes Eclipse Implementation of JAXB specific properties that + affect the way that the Jakarta XML Binding runtime library behaves.

XJC Customizations

This document describes additional binding + customizations that can be used to control the generated + source code.

DTD

This document describes the Eclipse Implementation of JAXB's experimental + support for W3C XML Schema features not currently described in + the Jakarta XML Binding Specification as well as support for other schema + languages (RELAX NG and DTD).

2. Runtime Properties

2.1. Marshaller Properties

The Eclipse Implementation of JAXB provides additional Marshaller properties that are + not defined by the Jakarta XML Binding specification. These properties allow you to + better control the marshalling process, but they only work with the + Eclipse Implementation of JAXB; they may not work with other Jakarta XML Binding providers.

2.1.2. Namespace Prefix Mapping

Property + name:org.glassfish.jaxb.namespacePrefixMapper
Type:org.glassfish.jaxb.runtime.marshaller.NamespacePrefixMapper
Default + value:

null

The Eclipse Implementation of JAXB provides a mechanism for users to control + declarations of namespace URIs and what prefixes they will be + bound to. This is the general procedure:

  1. The application developer provides an implementation + of + org.glassfish.jaxb.runtime.marshaller.NamespacePrefixMapper.

  2. This class is then set on the marshaller via the RI + specific property + org.glassfish.jaxb.namespacePrefixMapper.

  3. Each time the marshaller sees a URI, it performs a + callback on the mapper: "What prefix do you want for this + namespace URI?"

  4. If the mapper returns something, the marshaller will + try to use it.

The + org.glassfish.jaxb.runtime.marshaller.NamespacePrefixMapper + class has the following method that you need to implement:

/**
+ * Implemented by the user application to determine URI -> prefix
+ * mapping.
+ * 
+ * This is considered as an interface, though it's implemented
+ * as an abstract class to make it easy to add new methods in
+ * a future. 
+ * 
+ * @author
+ *     Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
+ */
+public abstract class NamespacePrefixMapper {
+
+    private static final String[] EMPTY_STRING = new String[0];
+
+    /**
+     * Returns a preferred prefix for the given namespace URI.
+     * 
+     * This method is intended to be overrided by a derived class.
+     *
+     * <p>
+     * As noted in the return value portion of the javadoc, there
+     * are several cases where the preference cannot be honored.
+     * Specifically, as of JAXB RI 2.0 and onward:
+     *
+     * <ol>
+     * <li>
+     * If the prefix returned is already in use as one of the in-scope
+     * namespace bindings. This is partly necessary for correctness
+     * (so that we don't unexpectedly change the meaning of QNames
+     * bound to {@link String}), partly to simplify the marshaller.
+     * <li>
+     * If the prefix returned is "" yet the current {@link JAXBContext}
+     * includes classes that use the empty namespace URI. This allows
+     * the JAXB RI to reserve the "" prefix for the empty namespace URI,
+     * which is the only possible prefix for the URI.
+     * This restriction is also to simplify the marshaller.
+     * </ol>
+     *
+     * @param namespaceUri
+     *      The namespace URI for which the prefix needs to be found.
+     *      Never be null. "" is used to denote the default namespace.
+     * @param suggestion
+     *      When the content tree has a suggestion for the prefix
+     *      to the given namespaceUri, that suggestion is passed as a
+     *      parameter. Typicall this value comes from the QName.getPrefix
+     *      to show the preference of the content tree. This parameter
+     *      may be null, and this parameter may represent an already
+     *      occupied prefix. 
+     * @param requirePrefix
+     *      If this method is expected to return non-empty prefix.
+     *      When this flag is true, it means that the given namespace URI
+     *      cannot be set as the default namespace.
+     * 
+     * @return
+     *      null if there's no prefered prefix for the namespace URI.
+     *      In this case, the system will generate a prefix for you.
+     * 
+     *      Otherwise the system will try to use the returned prefix,
+     *      but generally there's no guarantee if the prefix will be
+     *      actually used or not.
+     * 
+     *      return "" to map this namespace URI to the default namespace.
+     *      Again, there's no guarantee that this preference will be
+     *      honored.
+     * 
+     *      If this method returns "" when requirePrefix=true, the return
+     *      value will be ignored and the system will generate one.
+     * 
+     * @since JAXB 1.0.1
+     */
+    public abstract String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix);
+
+    /**
+     * Returns a list of namespace URIs that should be declared
+     * at the root element.
+     *
+     * <p>
+     * By default, the JAXB RI 1.0.x produces namespace declarations only when
+     * they are necessary, only at where they are used. Because of this
+     * lack of look-ahead, sometimes the marshaller produces a lot of
+     * namespace declarations that look redundant to human eyes. For example,
+     * <pre><xmp>
+     * <?xml version="1.0"?>
+     * <root>
+     *   <ns1:child xmlns:ns1="urn:foo"> ... </ns1:child>
+     *   <ns2:child xmlns:ns2="urn:foo"> ... </ns2:child>
+     *   <ns3:child xmlns:ns3="urn:foo"> ... </ns3:child>
+     *   ...
+     * </root>
+     * </xmp></pre>
+     *
+     * <p>
+     * The JAXB RI 2.x mostly doesn't exhibit this behavior any more,
+     * as it declares all statically known namespace URIs (those URIs
+     * that are used as element/attribute names in JAXB annotations),
+     * but it may still declare additional namespaces in the middle of
+     * a document, for example when (i) a QName as an attribute/element value
+     * requires a new namespace URI, or (ii) DOM nodes as a portion of an object
+     * tree requires a new namespace URI.
+     *
+     * <p>
+     * If you know in advance that you are going to use a certain set of
+     * namespace URIs, you can override this method and have the marshaller
+     * declare those namespace URIs at the root element.
+     *
+     * <p>
+     * For example, by returning <code>new String[]{"urn:foo"}</code>,
+     * the marshaller will produce:
+     * <pre><xmp>
+     * <?xml version="1.0"?>
+     * <root xmlns:ns1="urn:foo">
+     *   <ns1:child> ... </ns1:child>
+     *   <ns1:child> ... </ns1:child>
+     *   <ns1:child> ... </ns1:child>
+     *   ...
+     * </root>
+     * </xmp></pre>
+     * <p>
+     * To control prefixes assigned to those namespace URIs, use the
+     * {@link #getPreferredPrefix(String, String, boolean)} method. 
+     * 
+     * @return
+     *      A list of namespace URIs as an array of {@link String}s.
+     *      This method can return a length-zero array but not null.
+     *      None of the array component can be null. To represent
+     *      the empty namespace, use the empty string <code>""</code>.
+     * 
+     * @since
+     *      JAXB RI 1.0.2 
+     */
+    public String[] getPreDeclaredNamespaceUris() {
+        return EMPTY_STRING;
+    }
+
+    /**
+     * Similar to {@link #getPreDeclaredNamespaceUris()} but allows the
+     * (prefix,nsUri) pairs to be returned.
+     *
+     * <p>
+     * With {@link #getPreDeclaredNamespaceUris()}, applications who wish to control
+     * the prefixes as well as the namespaces needed to implement both
+     * {@link #getPreDeclaredNamespaceUris()} and {@link #getPreferredPrefix(String, String, boolean)}.
+     *
+     * <p>
+     * This version eliminates the needs by returning an array of pairs.
+     *
+     * @return
+     *      always return a non-null (but possibly empty) array. The array stores
+     *      data like (prefix1,nsUri1,prefix2,nsUri2,...) Use an empty string to represent
+     *      the empty namespace URI and the default prefix. Null is not allowed as a value
+     *      in the array.
+     *
+     * @since
+     *      JAXB RI 2.0 beta
+     */
+    public String[] getPreDeclaredNamespaceUris2() {
+        return EMPTY_STRING;
+    }
+
+    /**
+     * Returns a list of (prefix,namespace URI) pairs that represents
+     * namespace bindings available on ancestor elements (that need not be repeated
+     * by the JAXB RI.)
+     *
+     * <p>
+     * Sometimes JAXB is used to marshal an XML document, which will be
+     * used as a subtree of a bigger document. When this happens, it's nice
+     * for a JAXB marshaller to be able to use in-scope namespace bindings
+     * of the larger document and avoid declaring redundant namespace URIs.
+     *
+     * <p>
+     * This is automatically done when you are marshalling to {@link XMLStreamWriter},
+     * {@link XMLEventWriter}, {@link DOMResult}, or {@link Node}, because
+     * those output format allows us to inspect what's currently available
+     * as in-scope namespace binding. However, with other output format,
+     * such as {@link OutputStream}, the JAXB RI cannot do this automatically.
+     * That's when this method comes into play.
+     *
+     * <p>
+     * Namespace bindings returned by this method will be used by the JAXB RI,
+     * but will not be re-declared. They are assumed to be available when you insert
+     * this subtree into a bigger document.
+     *
+     * <p>
+     * It is <b>NOT</b> OK to return  the same binding, or give
+     * the receiver a conflicting binding information.
+     * It's a responsibility of the caller to make sure that this doesn't happen
+     * even if the ancestor elements look like:
+     * <pre><xmp>
+     *   <foo:abc xmlns:foo="abc">
+     *     <foo:abc xmlns:foo="def">
+     *       <foo:abc xmlns:foo="abc">
+     *         ... JAXB marshalling into here.
+     *       </foo:abc>
+     *     </foo:abc>
+     *   </foo:abc>
+     * </xmp></pre>
+     *
+     * @return
+     *      always return a non-null (but possibly empty) array. The array stores
+     *      data like (prefix1,nsUri1,prefix2,nsUri2,...) Use an empty string to represent
+     *      the empty namespace URI and the default prefix. Null is not allowed as a value
+     *      in the array.
+     *
+     * @since JAXB RI 2.0 beta
+     */
+    public String[] getContextualNamespaceDecls() {
+        return EMPTY_STRING;
+    }
+}

See the Sample Apps sample application for a detailed + example.

2.1.3. Indentation

Property + name:org.glassfish.jaxb.indentString
Type:java.lang.String
Default + value:

" " (four whitespaces)

This property controls the string used for the indentation + of XML. An element of depth k will be + indented by printing this string k times. + Note that the "jaxb.formatted.output" property + needs to be set to "true" for the formatting/indentation of the + output to occur. See the API documentation for + jakarta.xml.bind.Marshaller interface for + details of this property.

2.1.4. Character Escaping Control

Property + name:org.glassfish.jaxb.characterEscapeHandler
Type:org.glassfish.jaxb.core.marshaller.CharacterEscapeHandler
Default + value:

null

By default, the marshaller implementation of the Eclipse Implementation of JAXB + tries to escape characters so they can be safely represented in + the output encoding (by using Unicode numeric character references + of the form &#dddd;)

Unfortunately, due to various technical reasons, the default + behavior may not meet your expectations. If you need to handle + escaping more adroitly than the default manner, you can do so by + doing the following:

  1. Write a class that implements the + org.glassfish.jaxb.core.marshaller.CharacterEscapeHandler + interface.

  2. Create a new instance of it.

  3. Set that instance to the Marshaller by using this + property.

See the Sample Apps sample application for more + details.

2.1.5. XML Declaration Control

Property + name:org.glassfish.jaxb.xmlDeclaration
Type:boolean
Default + value:

true

This experimental JAXB RI 1.0.x property has been adopted as + a standard in Eclipse Implementation of JAXB. The Eclipse Implementation of JAXB will continue to support this + property, but client code should be using the Marshaller.JAXB_FRAGMENT + property instead. Please refer to the Marshaller + javadoc for a complete description of the behavior.

In Eclipse Implementation of JAXB, calling:

marshaller.setProperty("org.glassfish.jaxb.xmlDeclaration", true);

is equivalent to calling:

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

JAXB 1.0 generated code and clients will continue to work + exactly the same on the Jakarta XML Binding runtime as they did on the JAXB + 1.0 runtime.

Enabling fragment marshalling could be useful if you are + inserting the output of the XML into another XML.

2.1.6. XML Preamble Control

Property + name:org.glassfish.jaxb.xmlHeaders
Type:java.lang.String
Default + value:

null

This property allows you to specify an XML preamble + (<?xml ...> declaration) and any additional PIs, comments, + DOCTYPE declaration that follows it. This property takes effect + only when you are marshalling to OutputStream, + Writer, or StreamResult. Note that this + property interacts with the Marshaller.JAXB_FRAGMENT + property. If that property is untouched or set to false, then Eclipse Implementation of JAXB + would always write its XML preamble, so this property can be only + used to write PIs, comments, DOCTYPE, etc. On the other hand, if + it is set to true, then Jakarta XML Binding will not write its own XML preamble, + so this property may contain custom XML preamble.

2.1.7. Jaxb Annotation Control

Property + name:XmlAccessorFactory
Type:boolean
Default + value:

false

This property provides support for a custom + org.glassfish.jaxb.runtime.v2.runtime.reflect.Accessor implementation.  It + allows the user to control the access to class fields and + properties.

In Eclipse Implementation of JAXB, set the property to enable:

marshaller.setProperty("XmlAccessorFactory", true);

3. XJC Customizations

3.1. Customizations

The Eclipse Implementation of JAXB provides additional customizations that are not + defined by the Jakarta XML Binding specification. Note the following:

  • These features may only be used when the Eclipse Implementation of JAXB XJC + binding compiler is run in the -extension + mode.

  • All of the Eclipse Implementation of JAXB vendor extensions are defined in the + "http://java.sun.com/xml/ns/jaxb/xjc" + namespace.

  • The namespaces containing extension binding declarations + are specified to a Eclipse Implementation of JAXB processor by the occurrence of the + global attribute @jaxb:extensionBindingPrefixes + within an instance of <xs:schema> element. + The value of this attribute is a whitespace-separated list of + namespace prefixes. For more information, please refer to + section 6.1.1 of the Jakarta XML Binding Specification.

3.1.1. Index of Customizations

3.1.2. SCD Support

The Eclipse Implementation of JAXB supports the use of schema + component designator as a means of specifying the + customization target (of all standard Jakarta XML Binding customizations as well + as vendor extensions explained below.) To use this feature, use + the scd attribute on <bindings> element instead + of the schemaLocation and node + attributes.

<bindings xmlns:tns="http://example.com/myns"
+          xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0">
+    <bindings
+            ...
+            scd="tns:foo">
+        <!-- this customization applies to the global element declaration -->
+        <!-- 'foo' in the http://example.com/myns namespace -->
+        <class name="FooElement"/>
+    </bindings>
+    <bindings
+            ...
+            scd="~tns:bar">
+        <!-- this customization applies to the global type declaration -->
+        <!-- 'bar' in the http://example.com/myns namespace -->
+        <class name="BarType"/>
+    </bindings>
+</bindings>

Compared to the standard XPath based approach, SCD allows + more robust and concise way of identifying a target of a + customization. For more about SCD, refer to the scd example. Note + that SCD is a W3C working draft, and may change in the + future.

3.1.3. Extending a Common Super Class

The <xjc:superClass> customization allows + you to specify the fully qualified name of the Java class that is + to be used as the super class of all the generated implementation + classes. The <xjc:superClass> customization can + only occur within your <jaxb:globalBindings> + customization on the <xs:schema> + element:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    <xs:annotation>
+        <xs:appinfo>
+            <jaxb:globalBindings>
+                <xjc:superClass
+                        name="org.acme.RocketBooster"/>
+            </jaxb:globalBindings>
+        </xs:appinfo>
+    </xs:annotation>
+
+    ...
+
+</xs:schema>

In the sample above, the <xjc:superClass> + customization will cause all of the generated implementation + classes to extend the named class, + org.acme.RocketBooster.

3.1.4. Extending a Common Super Interface

The <xjc:superInterface> customization + allows you to specify the fully qualified name of the Java + interface that is to be used as the root interface of all the + generated interfaces. The <xjc:superInterface> + customization can only occur within your + <jaxb:globalBindings> customization on the + <xs:schema> element:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    <xs:annotation>
+        <xs:appinfo>
+            <jaxb:globalBindings>
+                <xjc:superInterface
+                        name="org.acme.RocketBooster"/>
+            </jaxb:globalBindings>
+        </xs:appinfo>
+    </xs:annotation>
+
+    ...
+
+</xs:schema>

In the sample above, the + <xjc:superInterface> customization will cause + all of the generated interfaces to extend the named interface, + org.acme.RocketBooster.

3.1.5. Enhanced <jaxb:javaType>

The <xjc:javaType> customization can be used just like + the standard <jaxb:javaType> customization, except that it + allows you to specify an XmlAdapter-derived + class, instead of parse&print method pair.

This customization can be used in all the places + <jaxb:javaType> is used, but nowhere else:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    ...
+
+    <xsd:simpleType name="LayerRate_T">
+        <xsd:annotation>
+            <xsd:appinfo>
+                <xjc:javaType name="org.acme.foo.LayerRate"
+                              adapter="org.acme.foo.LayerRateAdapter"/>
+            </xsd:appinfo>
+        </xsd:annotation>
+
+        ... gory simple type definition here ...
+
+    </xsd:simpleType>
+</xsd:schema>

In the above example, LayerRate_T simple type + is adapted by org.acme.foo.LayerRateAdapter, which + extends from XmlAdapter.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    <xsd:annotation>
+        <xsd:appinfo>
+            <jaxb:globalBindings>
+                <xjc:javaType name="org.acme.foo.MyDateType"
+                              xmlType="xsd:dateTime"
+                              adapter="org.acme.foo.MyAdapterImpl"/>
+            </jaxb:globalBindings>
+        </xsd:appinfo>
+    </xsd:annotation>
+
+    ...
+
+</xsd:schema>

In the above example, all the use of + xsd:dateTime type is adapter by + org.acme.foo.MyAdapterImpl to + org.acme.foo.MyDateType

3.1.6. Experimental simpler & better binding mode

This experimental binding mode can be enabled as a part of + the global binding. See below:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    <xs:annotation>
+        <xs:appinfo>
+            <jaxb:globalBindings generateValueClass="false">
+                <xjc:simple/>
+            </jaxb:globalBindings>
+        </xs:appinfo>
+    </xs:annotation>
+
+    ...
+
+</xs:schema>

When enabled, XJC produces Java source code that are more + concise and easier to use. Improvements include:

  1. Some content model definitions, such as + A,B,A, which used to cause an XJC compilation + error and required manual intervention, now compile out of + the box without any customization.

  2. Some content model definitions that used to bind to + a non-intuitive Java class now binds to a much better Java + class:

    <!-- schema -->
    +<xs:complexType name="foo">
    +    <xs:choice>
    +        <xs:sequence>
    +            <xs:element name="a" type="xs:int"/>
    +            <xs:element name="b" type="xs:int"/>
    +        </xs:sequence>
    +        <xs:sequence>
    +            <xs:element name="b" type="xs:int"/>
    +            <xs:element name="c" type="xs:int"/>
    +        </xs:sequence>
    +    </xs:choice>
    +</xs:complexType>
    // before
    +class Foo {
    +    List<JAXBElement<Integer>> content;
    +}
    +
    +// in <xjc:simple> binding
    +class Foo {
    +    Integer a;
    +    int b; // notice that b is effectively mandatory, hence primitive
    +    Integer c;
    +}
  3. When repetable elements are bound, the method name + will become plural.

    <!-- schema -->
    +<xs:complexType name="person">
    +    <xs:sequence>
    +        <xs:element name="child" type="xs:string"
    +                    maxOccurs="unbounded"/>
    +        <xs:element name="parent" type="xs:string"
    +                    maxOccurs="unbounded"/>
    +    </xs:sequence>
    +</xs:complexType>
    // before
    +public class Person {
    +    protected List<String> child;
    +    protected List<String> parent;
    +}
    +
    +// in <xjc:simple> binding
    +public class Person {
    +    protected List<String> children;
    +    protected List<String> parents;
    +}     

Once again, readers are warned that this is an experimental binding mode, and therefore + the binding is subject to change in future versions of the Eclipse Implementation of JAXB + without notice. Please send feedbacks on this binding to + jaxb-impl-dev@eclipse.org

3.1.7. Alternative Derivation-by-restriction Binding Mode

Normally, the Jakarta XML Binding specification requires that a + derivation-by-restriction be mapped to an inheritance betwee n two + Java classes. This is necessary to preserve the type hierarchy, + but one of the downsides is that the derived class does not really + provide easy-to-use properties that reflect the restricted content + model.

This experimental <xjc:treatRestrictionLikeNewType> + changes this behavior by not preserving the type inheritance to + Java. Instead, it generates two unrelated Java classes, both with + proper properties. For example, given the following schema:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           jaxb:version="3.0"
+           elementFormDefault="qualified">
+
+    <xs:annotation>
+        <xs:appinfo>
+            <jaxb:globalBindings>
+                <xjc:treatRestrictionLikeNewType/>
+            </jaxb:globalBindings>
+        </xs:appinfo>
+    </xs:annotation>
+
+    <xs:complexType name="DerivedType">
+        <xs:complexContent>
+            <xs:restriction base="ResponseOptionType">
+                <xs:sequence>
+                    <xs:element name="foo" type="xs:string"/>
+                </xs:sequence>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+
+    <xs:complexType name="ResponseOptionType">
+        <xs:sequence>
+            <xs:element name="foo" type="xs:string"
+                        maxOccurs="unbounded"/>
+        </xs:sequence>
+    </xs:complexType>
+
+</xs:schema>

The generated Derived class will look like this + (comment and annotations removed for brevity):

public class DerivedType {
+    protected String foo;
+
+    public String getFoo() { return foo; }
+    public void setFoo(String value) { this.foo = value; }
+} 

In contrast, without this customization the + Derived class would look like the following:

public class DerivedType extends ResponseOptionType {
+
+    // it simply inherits List<String> ResponseOptionType.getFoo()
+
+}

3.1.8. Allow separate compilations to perform element + substitutions

In an attempt to make the generated code easier to use, the + Jakarta XML Binding specification sometimes choose bindings based on how certain + feature is used. One of them is element substitution feature. If + no actual element substitution happens in the schema, Jakarta XML Binding assumes + that the element is not used for substitution, and generates code + that assumes it.

Most of the time this is fine, but when you expect other + "extension" schemas to be compiled later on top of your base + schema, and if those extension schemas do element substitutions, + this binding causes a problem ( see + example.)

<xjc:substitutable> customization is a work around for + this issue. It explicitly tells XJC that a certain element is used + for element substitution head, even though no actual substitution + might be present in the current compilation. This customization + should be attached in the element declaration itself, like + this:

<xs:element name="Model" type="Model">
+    <xs:annotation>
+        <xs:appinfo>
+            <xjc:substitutable/>
+        </xs:appinfo>
+    </xs:annotation>
+</xs:element>

4. DTD

4.1. DTD

The Eclipse Implementation of JAXB is shipped with experimental DTD support, which lets + you compile XML DTDs.

To compile a DTD test.dtd, run the XJC + binding compiler as follows:

$ xjc.sh -dtd test.dtd

All the other command-line options of the XJC binding compiler + can be applied. Similarly, the xjc ant task supports + DTD. The generated code will be no different from what is generated + from W3C XML Schema. You'll use the same Jakarta XML Binding API to access the + generated code, and it is portable in the sense that it will run on + any Jakarta XML Binding implementation.

4.1.1. Customization

The customization syntax for DTD is roughly based on the + ver.0.21 working draft of the Jakarta XML Binding specification, which is + available at xml.coverpages.org. + The deviations from this document are:

  • The whitespace attribute of the + conversion element takes " + preserve", " replace", and " + collapse" instead of " + preserve"," normalize", and " + collapse" as specified in the + document.

  • The interface customization just + generates marker interfaces with no method.

5. Develop Plugins

This document describes how to write an XJC plugin to extend the + code generation of XJC.

5.1. What Can A Plugin Do?

An XJC plugin participates in the code generation from a schema. + It can define its own customizations that users can use to control it, + it can access the code that the Eclipse Implementation of JAXB generates, it can generate + additional classes/methods/fields/annotations/comments, and it can + also replace some of the pluggability points in the compilation + process, such as XML name -> Java name conversion.

As a show case of what a plugin can do, take a look at plugins hosted at + JAXB2-commons.

5.1.1. Quick Start

To write a plugin, do the following simple steps.

  1. Write a class, say, org.acme.MyPlugin + by extending com.sun.tools.xjc.Plugin. See + javadoc for how to implement methods.

  2. Write the name of your plugin class in a text file + and put it as + /META-INF/services/com.sun.tools.xjc.Plugin + in your jar file.

Users can then use your plugins by declaring an XJC ant task + with your jar files.

<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath>
+        <fileset dir="jaxb-ri/lib" includes="*.jar"/>
+        <fileset dir="your-plugin" includes="*.jar"/>
+    </classpath>
+</taskdef>

5.1.2. Resources

Although we will do our best to maintain the compatibility + of the interfaces, it is still subject to change at this + point.

\ No newline at end of file diff --git a/scripts/jaxb-ri/docs/ch06.html b/scripts/jaxb-ri/docs/ch06.html new file mode 100644 index 0000000..86a174b --- /dev/null +++ b/scripts/jaxb-ri/docs/ch06.html @@ -0,0 +1,115 @@ + + + Frequently Asked QuestionsLinks: Table of Contents | Single HTML | Single PDF

Frequently Asked Questions

1. JAXB 2.0
Q: Which version of Java SE does Eclipse Implementation of JAXB 4.0.0 require?
Q: Can I run my existing JAXB 1.x/2.x applications on the + Eclipse Implementation of JAXB runtime?
Q: What if I want to port my JAXB 1.x/2.x application to Jakarta XML Binding runtime?
Q: Where are schemagen and xjc command line scripts available?
Q: Are the Jakarta XML Binding runtime API's thread safe?
Q: Why can't I cast the unmarshalled object into the + generated type.
Q: Which jar files do I need to distribute with my + application that uses the Eclipse Implementation of JAXB?
Q: How can I cause the Marshaller to + generate CDATA blocks?
Q: Can I access <xs:any/> as a DOM node?
Q: How do I find out which version of the Eclipse Implementation of JAXB I'm + using?

1. JAXB 2.0

Q:

Which version of Java SE does Eclipse Implementation of JAXB 4.0.0 require?

A:

Java SE 11 or higher.

Q:

Can I run my existing JAXB 1.x/2.x applications on the + Eclipse Implementation of JAXB runtime?

A:

This is not supported.

Q:

What if I want to port my JAXB 1.x/2.x application to Jakarta XML Binding runtime?

A:

You need to replace references to javax.xml.bind + package by jakarta.xml.bind package, recompile your schema + with the newer xjc and modify your application code to work with + the new bindings.

Q:

Where are schemagen and xjc command line scripts available?

A:

They are included only in the zip distribution.

Q:

Are the Jakarta XML Binding runtime API's thread safe?

A:

The Jakarta XML Binding Specification currently does not address + the thread safety of any of the runtime classes. In the + case of the Eclipse Implementation of JAXB, the + JAXBContext class is thread safe, but the + Marshaller, + Unmarshaller, and + Validator classes are not thread safe.

For example, suppose you have a multi-thread server + application that processes incoming XML documents by Jakarta XML Binding. + In this case, for the best performance you should have + just one instance of JAXBContext in + your whole application like this:

class MyServlet extends HttpServlet {
+    static final JAXBContext context = initContext();
+
+    private static JAXBContext initContext() {
+        return JAXBContext.newInstance("....", MyServlet.class.getClassLoader());
+    }
+}

And each time you need to unmarshal/marshal/validate + a document. Just create a new + Unmarshaller/Marshaller/Validator + from this context, like this:

public void doGet(HttpServletRequest req, HttpServletResponse resp) {
+    Unmarshaller u = context.createUnmarshaller();
+    u.unmarshal(...);
+}

This is the simplest safe way to use the Eclipse Implementation of JAXB + from multi-threaded applications.

If you really care about the performance, and/or + your application is going to read a lot of small + documents, then creating Unmarshaller + could be relatively an expensive operation. In that case, + consider pooling Unmarshaller objects. + Different threads may reuse one + Unmarshaller instance, as long as you + don't use one instance from two threads at the same + time.

Q:

Why can't I cast the unmarshalled object into the + generated type.

A:

When you invoke + JAXBContext.newInstance("aaa.bbb.ccc"), + it tries to load classes and resources using the same + classloader used to load the + JAXBContext class itself. This + classloader may be different from the classloader which + was used to load your application (see the picture Parent/Child classloader). In + this case, you'll see the above error. This problem is + often seen with application servers, Jakarta EE containers, Ant, + JUnit, and other applications that use sophisticated class + loading mechanisms.

Figure 1. Parent/Child classloader

Parent/Child classloader

With some applications, things get even more + complicated when the Jakarta XML Binding-generated code can be loaded by + either classloader. In this case, + JAXBContext.newInstance("aaa.bbb.ccc") + will work but the JVM ends up loading two copies of the + generated classes for each class loader. As a result, + unmarshalling works but an attempt to cast the returned + object into the expected type will fail, even though its + getClass().getName() returns the + expected name.

The solution for both situations is to pass your + curent class loader like this:

JAXBContext.newInstance("aaa.bbb.ccc", this.getClass().getClassLoader());

In general, if you are writing code that uses Jakarta XML Binding, + it is always better to explicitly pass in a class loader, + so that your code will work no matter where it is + deployed.

Q:

Which jar files do I need to distribute with my + application that uses the Eclipse Implementation of JAXB?

A:

+

+$JAXB_HOME/mod/jakarta.xml.bind-api.jar
+$JAXB_HOME/mod/jakarta.activation-api.jar
+$JAXB_HOME/mod/angus-activation.jar
+$JAXB_HOME/mod/jaxb-core.jar
+$JAXB_HOME/mod/jaxb-impl.jar

+

Q:

How can I cause the Marshaller to + generate CDATA blocks?

A:

This functionality is not available from Eclipse Implementation of JAXB + directly, but you can configure an Apache Xerces-J + XMLSerializer to produce + CDATA blocks. Please review the JaxbCDATASample.java + sample app for more detail.

Q:

Can I access <xs:any/> as a DOM node?

A:

In Eclipse Implementation of JAXB, <xs:any/> is handled correctly + without any customization.

  1. If it's strict, it will map + to Object or + List<Object> and when you + unmarshal documents, you'll get objects that map to + elements (such as JAXBElements or + classes that are annotated with + XmlRootElement).

  2. If it's skip, it will map + to org.w3c.dom.Element or + List<Element> and when you + unmarshal documents, you'll get DOM elements.

  3. If it's lax, it will map to + the same as with strict, and when + you unmarshal documents, you'll get either:

    1. JAXBElements

    2. classes that are annotated with + XmlRootElement

    3. DOM elements

Q:

How do I find out which version of the Eclipse Implementation of JAXB I'm + using?

A:

Run the following command

$ java -jar jaxb-xjc.jar -version

Alternatively, each Eclipse Implementation of JAXB jar has version information + in its META-INF/MANIFEST.MF, such as + this:

Manifest-Version: 1.0
+Specification-Title: Jakarta XML Binding
+Specification-Version: 4.0
+Specification-Vendor: Eclipse Foundation
+Implementation-Title: Eclipse Implementation of JAXB
+Implementation-Version: 4.0.0
+Implementation-Vendor: Eclipse Foundation
+Implementation-Vendor-Id: org.eclipse
+Build-Id: 2022-05-18 22:33
+Class-Path: jaxb-core.jar jaxb-impl.jar
\ No newline at end of file diff --git a/scripts/jaxb-ri/docs/ch07.html b/scripts/jaxb-ri/docs/ch07.html new file mode 100644 index 0000000..20189e9 --- /dev/null +++ b/scripts/jaxb-ri/docs/ch07.html @@ -0,0 +1,19 @@ + + + Related ArticlesLinks: Table of Contents | Single HTML | Single PDF \ No newline at end of file diff --git a/scripts/jaxb-ri/docs/download/JaxbCDATASample.java b/scripts/jaxb-ri/docs/download/JaxbCDATASample.java new file mode 100644 index 0000000..b50db39 --- /dev/null +++ b/scripts/jaxb-ri/docs/download/JaxbCDATASample.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.File; +import java.io.StringWriter; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.xml.serialize.OutputFormat; +import org.apache.xml.serialize.XMLSerializer; +import org.w3c.dom.Document; + +public class JaxbCDATASample { + + public static void main(String[] args) throws Exception { + // unmarshal a doc + JAXBContext jc = JAXBContext.newInstance("..."); + Unmarshaller u = jc.createUnmarshaller(); + Object o = u.unmarshal(...); + + // create a JAXB marshaller + Marshaller m = jc.createMarshaller(); + + // get an Apache XMLSerializer configured to generate CDATA + XMLSerializer serializer = getXMLSerializer(); + + // marshal using the Apache XMLSerializer + m.marshal(o, serializer.asContentHandler()); + } + + private static XMLSerializer getXMLSerializer() { + // configure an OutputFormat to handle CDATA + OutputFormat of = new OutputFormat(); + + // specify which of your elements you want to be handled as CDATA. + // The use of the '^' between the namespaceURI and the localname + // seems to be an implementation detail of the xerces code. + // When processing xml that doesn't use namespaces, simply omit the + // namespace prefix as shown in the third CDataElement below. + of.setCDataElements( + new String[] { "ns1^foo", // + "ns2^bar", // + "^baz" }); // + + // set any other options you'd like + of.setPreserveSpace(true); + of.setIndenting(true); + + // create the serializer + XMLSerializer serializer = new XMLSerializer(of); + serializer.setOutputByteStream(System.out); + + return serializer; + } + +} diff --git a/scripts/jaxb-ri/docs/figures/classLoaderFAQ.gif b/scripts/jaxb-ri/docs/figures/classLoaderFAQ.gif new file mode 100644 index 0000000..963d764 Binary files /dev/null and b/scripts/jaxb-ri/docs/figures/classLoaderFAQ.gif differ diff --git a/scripts/jaxb-ri/docs/icons/annot-close.png b/scripts/jaxb-ri/docs/icons/annot-close.png new file mode 100644 index 0000000..b9e1a0d Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/annot-close.png differ diff --git a/scripts/jaxb-ri/docs/icons/annot-open.png b/scripts/jaxb-ri/docs/icons/annot-open.png new file mode 100644 index 0000000..71040ec Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/annot-open.png differ diff --git a/scripts/jaxb-ri/docs/icons/blank.png b/scripts/jaxb-ri/docs/icons/blank.png new file mode 100644 index 0000000..764bf4f Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/blank.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/1.gif b/scripts/jaxb-ri/docs/icons/callouts/1.gif new file mode 100644 index 0000000..9e7a87f Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/1.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/1.png b/scripts/jaxb-ri/docs/icons/callouts/1.png new file mode 100644 index 0000000..7d47343 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/1.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/1.svg b/scripts/jaxb-ri/docs/icons/callouts/1.svg new file mode 100644 index 0000000..9ebab18 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/1.svg @@ -0,0 +1,27 @@ + + + + + + +]> + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/10.gif b/scripts/jaxb-ri/docs/icons/callouts/10.gif new file mode 100644 index 0000000..e80f7f8 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/10.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/10.png b/scripts/jaxb-ri/docs/icons/callouts/10.png new file mode 100644 index 0000000..997bbc8 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/10.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/10.svg b/scripts/jaxb-ri/docs/icons/callouts/10.svg new file mode 100644 index 0000000..0db1ad6 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/10.svg @@ -0,0 +1,30 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/11.gif b/scripts/jaxb-ri/docs/icons/callouts/11.gif new file mode 100644 index 0000000..67f91a2 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/11.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/11.png b/scripts/jaxb-ri/docs/icons/callouts/11.png new file mode 100644 index 0000000..ce47dac Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/11.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/11.svg b/scripts/jaxb-ri/docs/icons/callouts/11.svg new file mode 100644 index 0000000..97e344b --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/11.svg @@ -0,0 +1,28 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/12.gif b/scripts/jaxb-ri/docs/icons/callouts/12.gif new file mode 100644 index 0000000..54c4b42 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/12.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/12.png b/scripts/jaxb-ri/docs/icons/callouts/12.png new file mode 100644 index 0000000..31daf4e Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/12.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/12.svg b/scripts/jaxb-ri/docs/icons/callouts/12.svg new file mode 100644 index 0000000..05e84e7 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/12.svg @@ -0,0 +1,30 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/13.gif b/scripts/jaxb-ri/docs/icons/callouts/13.gif new file mode 100644 index 0000000..dd5d7d9 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/13.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/13.png b/scripts/jaxb-ri/docs/icons/callouts/13.png new file mode 100644 index 0000000..14021a8 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/13.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/13.svg b/scripts/jaxb-ri/docs/icons/callouts/13.svg new file mode 100644 index 0000000..8fd93b3 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/13.svg @@ -0,0 +1,32 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/14.gif b/scripts/jaxb-ri/docs/icons/callouts/14.gif new file mode 100644 index 0000000..3d7a952 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/14.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/14.png b/scripts/jaxb-ri/docs/icons/callouts/14.png new file mode 100644 index 0000000..64014b7 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/14.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/14.svg b/scripts/jaxb-ri/docs/icons/callouts/14.svg new file mode 100644 index 0000000..55bda73 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/14.svg @@ -0,0 +1,29 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/15.gif b/scripts/jaxb-ri/docs/icons/callouts/15.gif new file mode 100644 index 0000000..1c9183d Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/15.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/15.png b/scripts/jaxb-ri/docs/icons/callouts/15.png new file mode 100644 index 0000000..0d65765 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/15.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/15.svg b/scripts/jaxb-ri/docs/icons/callouts/15.svg new file mode 100644 index 0000000..a5e6462 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/15.svg @@ -0,0 +1,31 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/16.svg b/scripts/jaxb-ri/docs/icons/callouts/16.svg new file mode 100644 index 0000000..e42d45b --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/16.svg @@ -0,0 +1,32 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/17.svg b/scripts/jaxb-ri/docs/icons/callouts/17.svg new file mode 100644 index 0000000..cd7b193 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/17.svg @@ -0,0 +1,29 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/18.svg b/scripts/jaxb-ri/docs/icons/callouts/18.svg new file mode 100644 index 0000000..3b41099 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/18.svg @@ -0,0 +1,33 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/19.svg b/scripts/jaxb-ri/docs/icons/callouts/19.svg new file mode 100644 index 0000000..b82d793 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/19.svg @@ -0,0 +1,32 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/2.gif b/scripts/jaxb-ri/docs/icons/callouts/2.gif new file mode 100644 index 0000000..94d42a3 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/2.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/2.png b/scripts/jaxb-ri/docs/icons/callouts/2.png new file mode 100644 index 0000000..5d09341 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/2.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/2.svg b/scripts/jaxb-ri/docs/icons/callouts/2.svg new file mode 100644 index 0000000..bfc6e17 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/2.svg @@ -0,0 +1,29 @@ + + + + + + +]> + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/20.svg b/scripts/jaxb-ri/docs/icons/callouts/20.svg new file mode 100644 index 0000000..cc2d041 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/20.svg @@ -0,0 +1,32 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/21.svg b/scripts/jaxb-ri/docs/icons/callouts/21.svg new file mode 100644 index 0000000..dd03e68 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/21.svg @@ -0,0 +1,30 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/22.svg b/scripts/jaxb-ri/docs/icons/callouts/22.svg new file mode 100644 index 0000000..30653aa --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/22.svg @@ -0,0 +1,32 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/23.svg b/scripts/jaxb-ri/docs/icons/callouts/23.svg new file mode 100644 index 0000000..165f13a --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/23.svg @@ -0,0 +1,34 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/24.svg b/scripts/jaxb-ri/docs/icons/callouts/24.svg new file mode 100644 index 0000000..a7427d8 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/24.svg @@ -0,0 +1,31 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/25.svg b/scripts/jaxb-ri/docs/icons/callouts/25.svg new file mode 100644 index 0000000..b8f787d --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/25.svg @@ -0,0 +1,33 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/26.svg b/scripts/jaxb-ri/docs/icons/callouts/26.svg new file mode 100644 index 0000000..2bb3022 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/26.svg @@ -0,0 +1,34 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/27.svg b/scripts/jaxb-ri/docs/icons/callouts/27.svg new file mode 100644 index 0000000..9301fea --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/27.svg @@ -0,0 +1,31 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/28.svg b/scripts/jaxb-ri/docs/icons/callouts/28.svg new file mode 100644 index 0000000..646db4d --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/28.svg @@ -0,0 +1,35 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/29.svg b/scripts/jaxb-ri/docs/icons/callouts/29.svg new file mode 100644 index 0000000..24c1d47 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/29.svg @@ -0,0 +1,34 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/3.gif b/scripts/jaxb-ri/docs/icons/callouts/3.gif new file mode 100644 index 0000000..dd3541a Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/3.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/3.png b/scripts/jaxb-ri/docs/icons/callouts/3.png new file mode 100644 index 0000000..ef7b700 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/3.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/3.svg b/scripts/jaxb-ri/docs/icons/callouts/3.svg new file mode 100644 index 0000000..35f9f76 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/3.svg @@ -0,0 +1,31 @@ + + + + + + +]> + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/30.svg b/scripts/jaxb-ri/docs/icons/callouts/30.svg new file mode 100644 index 0000000..726ca47 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/30.svg @@ -0,0 +1,34 @@ + + + + + + +]> + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/4.gif b/scripts/jaxb-ri/docs/icons/callouts/4.gif new file mode 100644 index 0000000..4bcbf7e Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/4.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/4.png b/scripts/jaxb-ri/docs/icons/callouts/4.png new file mode 100644 index 0000000..adb8364 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/4.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/4.svg b/scripts/jaxb-ri/docs/icons/callouts/4.svg new file mode 100644 index 0000000..85f63b0 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/4.svg @@ -0,0 +1,28 @@ + + + + + + +]> + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/5.gif b/scripts/jaxb-ri/docs/icons/callouts/5.gif new file mode 100644 index 0000000..1c62b4f Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/5.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/5.png b/scripts/jaxb-ri/docs/icons/callouts/5.png new file mode 100644 index 0000000..4d7eb46 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/5.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/5.svg b/scripts/jaxb-ri/docs/icons/callouts/5.svg new file mode 100644 index 0000000..44e42e3 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/5.svg @@ -0,0 +1,30 @@ + + + + + + +]> + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/6.gif b/scripts/jaxb-ri/docs/icons/callouts/6.gif new file mode 100644 index 0000000..23bc555 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/6.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/6.png b/scripts/jaxb-ri/docs/icons/callouts/6.png new file mode 100644 index 0000000..0ba694a Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/6.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/6.svg b/scripts/jaxb-ri/docs/icons/callouts/6.svg new file mode 100644 index 0000000..ac0700b --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/6.svg @@ -0,0 +1,31 @@ + + + + + + +]> + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/7.gif b/scripts/jaxb-ri/docs/icons/callouts/7.gif new file mode 100644 index 0000000..e55ce89 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/7.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/7.png b/scripts/jaxb-ri/docs/icons/callouts/7.png new file mode 100644 index 0000000..472e96f Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/7.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/7.svg b/scripts/jaxb-ri/docs/icons/callouts/7.svg new file mode 100644 index 0000000..17b9a14 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/7.svg @@ -0,0 +1,28 @@ + + + + + + +]> + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/8.gif b/scripts/jaxb-ri/docs/icons/callouts/8.gif new file mode 100644 index 0000000..49375e0 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/8.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/8.png b/scripts/jaxb-ri/docs/icons/callouts/8.png new file mode 100644 index 0000000..5e60973 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/8.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/8.svg b/scripts/jaxb-ri/docs/icons/callouts/8.svg new file mode 100644 index 0000000..291acb2 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/8.svg @@ -0,0 +1,32 @@ + + + + + + +]> + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/callouts/9.gif b/scripts/jaxb-ri/docs/icons/callouts/9.gif new file mode 100644 index 0000000..da12a4f Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/9.gif differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/9.png b/scripts/jaxb-ri/docs/icons/callouts/9.png new file mode 100644 index 0000000..a0676d2 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/callouts/9.png differ diff --git a/scripts/jaxb-ri/docs/icons/callouts/9.svg b/scripts/jaxb-ri/docs/icons/callouts/9.svg new file mode 100644 index 0000000..639f4af --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/callouts/9.svg @@ -0,0 +1,31 @@ + + + + + + +]> + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/caution.gif b/scripts/jaxb-ri/docs/icons/caution.gif new file mode 100644 index 0000000..d9f5e5b Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/caution.gif differ diff --git a/scripts/jaxb-ri/docs/icons/caution.png b/scripts/jaxb-ri/docs/icons/caution.png new file mode 100644 index 0000000..5b7809c Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/caution.png differ diff --git a/scripts/jaxb-ri/docs/icons/caution.svg b/scripts/jaxb-ri/docs/icons/caution.svg new file mode 100644 index 0000000..9e7f597 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/caution.svg @@ -0,0 +1,37 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/caution.tif b/scripts/jaxb-ri/docs/icons/caution.tif new file mode 100644 index 0000000..4a28294 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/caution.tif differ diff --git a/scripts/jaxb-ri/docs/icons/colorsvg/caution.svg b/scripts/jaxb-ri/docs/icons/colorsvg/caution.svg new file mode 100644 index 0000000..7296e76 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/colorsvg/caution.svg @@ -0,0 +1,153 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/colorsvg/home.svg b/scripts/jaxb-ri/docs/icons/colorsvg/home.svg new file mode 100644 index 0000000..b15288c --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/colorsvg/home.svg @@ -0,0 +1,510 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/colorsvg/important.svg b/scripts/jaxb-ri/docs/icons/colorsvg/important.svg new file mode 100644 index 0000000..43dce3f --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/colorsvg/important.svg @@ -0,0 +1,251 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/colorsvg/next.svg b/scripts/jaxb-ri/docs/icons/colorsvg/next.svg new file mode 100644 index 0000000..d5613e1 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/colorsvg/next.svg @@ -0,0 +1,350 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/colorsvg/note.svg b/scripts/jaxb-ri/docs/icons/colorsvg/note.svg new file mode 100644 index 0000000..f668ccc --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/colorsvg/note.svg @@ -0,0 +1,212 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/colorsvg/prev.svg b/scripts/jaxb-ri/docs/icons/colorsvg/prev.svg new file mode 100644 index 0000000..656e12c --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/colorsvg/prev.svg @@ -0,0 +1,350 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/colorsvg/tip.svg b/scripts/jaxb-ri/docs/icons/colorsvg/tip.svg new file mode 100644 index 0000000..54cfcd6 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/colorsvg/tip.svg @@ -0,0 +1,379 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/colorsvg/up.svg b/scripts/jaxb-ri/docs/icons/colorsvg/up.svg new file mode 100644 index 0000000..f4086e9 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/colorsvg/up.svg @@ -0,0 +1,350 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/colorsvg/warning.svg b/scripts/jaxb-ri/docs/icons/colorsvg/warning.svg new file mode 100644 index 0000000..cbbff14 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/colorsvg/warning.svg @@ -0,0 +1,244 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/draft.png b/scripts/jaxb-ri/docs/icons/draft.png new file mode 100644 index 0000000..59673fe Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/draft.png differ diff --git a/scripts/jaxb-ri/docs/icons/home.gif b/scripts/jaxb-ri/docs/icons/home.gif new file mode 100644 index 0000000..6784f5b Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/home.gif differ diff --git a/scripts/jaxb-ri/docs/icons/home.png b/scripts/jaxb-ri/docs/icons/home.png new file mode 100644 index 0000000..cbb711d Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/home.png differ diff --git a/scripts/jaxb-ri/docs/icons/home.svg b/scripts/jaxb-ri/docs/icons/home.svg new file mode 100644 index 0000000..d4a5efe --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/home.svg @@ -0,0 +1,38 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/important.gif b/scripts/jaxb-ri/docs/icons/important.gif new file mode 100644 index 0000000..6795d9a Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/important.gif differ diff --git a/scripts/jaxb-ri/docs/icons/important.png b/scripts/jaxb-ri/docs/icons/important.png new file mode 100644 index 0000000..12c90f6 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/important.png differ diff --git a/scripts/jaxb-ri/docs/icons/important.svg b/scripts/jaxb-ri/docs/icons/important.svg new file mode 100644 index 0000000..9e7f597 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/important.svg @@ -0,0 +1,37 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/important.tif b/scripts/jaxb-ri/docs/icons/important.tif new file mode 100644 index 0000000..184de63 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/important.tif differ diff --git a/scripts/jaxb-ri/docs/icons/next.gif b/scripts/jaxb-ri/docs/icons/next.gif new file mode 100644 index 0000000..aa1516e Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/next.gif differ diff --git a/scripts/jaxb-ri/docs/icons/next.png b/scripts/jaxb-ri/docs/icons/next.png new file mode 100644 index 0000000..45835bf Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/next.png differ diff --git a/scripts/jaxb-ri/docs/icons/next.svg b/scripts/jaxb-ri/docs/icons/next.svg new file mode 100644 index 0000000..dcce539 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/next.svg @@ -0,0 +1,31 @@ + + + + + + + + +]> + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/note.gif b/scripts/jaxb-ri/docs/icons/note.gif new file mode 100644 index 0000000..f329d35 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/note.gif differ diff --git a/scripts/jaxb-ri/docs/icons/note.png b/scripts/jaxb-ri/docs/icons/note.png new file mode 100644 index 0000000..d0c3c64 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/note.png differ diff --git a/scripts/jaxb-ri/docs/icons/note.svg b/scripts/jaxb-ri/docs/icons/note.svg new file mode 100644 index 0000000..a316a10 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/note.svg @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + +]> + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/note.tif b/scripts/jaxb-ri/docs/icons/note.tif new file mode 100644 index 0000000..08644d6 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/note.tif differ diff --git a/scripts/jaxb-ri/docs/icons/prev.gif b/scripts/jaxb-ri/docs/icons/prev.gif new file mode 100644 index 0000000..64ca8f3 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/prev.gif differ diff --git a/scripts/jaxb-ri/docs/icons/prev.png b/scripts/jaxb-ri/docs/icons/prev.png new file mode 100644 index 0000000..cf24654 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/prev.png differ diff --git a/scripts/jaxb-ri/docs/icons/prev.svg b/scripts/jaxb-ri/docs/icons/prev.svg new file mode 100644 index 0000000..d464a32 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/prev.svg @@ -0,0 +1,31 @@ + + + + + + + + +]> + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/tip.gif b/scripts/jaxb-ri/docs/icons/tip.gif new file mode 100644 index 0000000..823f2b4 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/tip.gif differ diff --git a/scripts/jaxb-ri/docs/icons/tip.png b/scripts/jaxb-ri/docs/icons/tip.png new file mode 100644 index 0000000..5c4aab3 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/tip.png differ diff --git a/scripts/jaxb-ri/docs/icons/tip.svg b/scripts/jaxb-ri/docs/icons/tip.svg new file mode 100644 index 0000000..c1923e9 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/tip.svg @@ -0,0 +1,43 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/tip.tif b/scripts/jaxb-ri/docs/icons/tip.tif new file mode 100644 index 0000000..4a3d8c7 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/tip.tif differ diff --git a/scripts/jaxb-ri/docs/icons/toc-blank.png b/scripts/jaxb-ri/docs/icons/toc-blank.png new file mode 100644 index 0000000..6ffad17 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/toc-blank.png differ diff --git a/scripts/jaxb-ri/docs/icons/toc-minus.png b/scripts/jaxb-ri/docs/icons/toc-minus.png new file mode 100644 index 0000000..abbb020 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/toc-minus.png differ diff --git a/scripts/jaxb-ri/docs/icons/toc-plus.png b/scripts/jaxb-ri/docs/icons/toc-plus.png new file mode 100644 index 0000000..941312c Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/toc-plus.png differ diff --git a/scripts/jaxb-ri/docs/icons/up.gif b/scripts/jaxb-ri/docs/icons/up.gif new file mode 100644 index 0000000..aabc2d0 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/up.gif differ diff --git a/scripts/jaxb-ri/docs/icons/up.png b/scripts/jaxb-ri/docs/icons/up.png new file mode 100644 index 0000000..07634de Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/up.png differ diff --git a/scripts/jaxb-ri/docs/icons/up.svg b/scripts/jaxb-ri/docs/icons/up.svg new file mode 100644 index 0000000..6c59d1f --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/up.svg @@ -0,0 +1,31 @@ + + + + + + + + +]> + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/warning.gif b/scripts/jaxb-ri/docs/icons/warning.gif new file mode 100644 index 0000000..3adf191 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/warning.gif differ diff --git a/scripts/jaxb-ri/docs/icons/warning.png b/scripts/jaxb-ri/docs/icons/warning.png new file mode 100644 index 0000000..1c33db8 Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/warning.png differ diff --git a/scripts/jaxb-ri/docs/icons/warning.svg b/scripts/jaxb-ri/docs/icons/warning.svg new file mode 100644 index 0000000..8088748 --- /dev/null +++ b/scripts/jaxb-ri/docs/icons/warning.svg @@ -0,0 +1,35 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/docs/icons/warning.tif b/scripts/jaxb-ri/docs/icons/warning.tif new file mode 100644 index 0000000..7b6611e Binary files /dev/null and b/scripts/jaxb-ri/docs/icons/warning.tif differ diff --git a/scripts/jaxb-ri/docs/index.html b/scripts/jaxb-ri/docs/index.html new file mode 100644 index 0000000..cc6423e --- /dev/null +++ b/scripts/jaxb-ri/docs/index.html @@ -0,0 +1,15 @@ + + + Eclipse Implementation of JAXB Release DocumentationLinks: Table of Contents | Single HTML | Single PDF

Eclipse Implementation of JAXB Release Documentation


Table of Contents

Overview
1. Documentation
2. Software Licenses
3. Sample Apps
3.1. Using the Runtime Binding Framework
Release Notes
1. + Java™ SE Requirements +
2. Identifying the JAR Files
3. Identifying the JPMS module names
4. Locating the Normative Binding Schema
5. Changelog
5.1. Changes in 4.0.0 - initial release for Jakarta EE 10
5.2. Changes between 3.0.1 and 3.0.2
5.3. Changes between 3.0.0 and 3.0.1
5.4. Changes in 3.0.0 - initial release for Jakarta EE 9
5.5. Changes in 2.3.2 - initial release for Jakarta EE 8
Eclipse Implementation of JAXB Users Guide
1. Compiling XML Schema
1.1. Dealing with errors
1.2. Fixing broken references in schema
1.3. Mapping of <xs:any />
1.4. Mapping of <xs:element /> to JAXBElement
1.5. How modularization of schema interacts with XJC
1.6. Adding behaviors
1.7. Avoid strong databinding
1.8. Working with generated code in memory
2. Customization of Schema Compilation
2.1. Customizing Java packages
2.2. Using SCD for customizations
2.3. Using different datatypes
3. Annotating Your Classes
3.1. Mapping your favorite class
3.2. Mapping interfaces
3.3. Evolving annotated classes
3.4. XML layout and in-memory data layout
3.5. Mapping cyclic references to XML
4. Unmarshalling
4.1. @XmlRootElement and unmarshalling
4.2. Unmarshalling is not working! Help!
4.3. Element default values and unmarshalling
4.4. Dealing with large documents
5. Marshalling
5.1. Changing prefixes
5.2. Element default values and marshalling
5.3. Different ways of marshalling
5.4. Interaction between marshalling and DOM
6. Schema Generation
6.1. Invoking schemagen programatically
6.2. Generating Schema that you want
7. Deployment
7.1. Using Eclipse Implementation of JAXB with Maven
7.2. Using Eclipse Implementation of JAXB on JPMS
8. Other Miscellaneous Topics
8.1. Performance and thread-safety
8.2. Compiling DTD
8.3. Designing a client/server protocol in XML
Tools
1. XJC
1.1. xjc Overview
1.2. Launching xjc
1.3. xjc Syntax
1.4. Compiler Restrictions
1.5. Generated Resource Files
2. XJC Ant Task
2.1. xjc Task Overview
2.2. xjc Task Attributes
2.3. Generated Resource Files
2.4. Up-to-date Check
2.5. Schema Language Support
2.6. xjc Examples
3. SchemaGen
3.1. schemagen Overview
3.2. Launching schemagen
3.3. schemagen Syntax
3.4. Generated Resource Files
4. SchemaGen Ant Task
4.1. schemagen Task Overview
4.2. schemagen Task Attributes
4.3. schemagen Examples
5. 3rd Party Tools
5.1. Maven JAXB Plugin
5.2. XJC Plugins
5.3. RDBMS Persistence
Eclipse Implementation of JAXB Extensions
1. Overview
2. Runtime Properties
2.1. Marshaller Properties
3. XJC Customizations
3.1. Customizations
4. DTD
4.1. DTD
5. Develop Plugins
5.1. What Can A Plugin Do?
Frequently Asked Questions
Related Articles
1. Introductory
2. Blogs
3. Interesting articles
\ No newline at end of file diff --git a/scripts/jaxb-ri/docs/release-documentation.html b/scripts/jaxb-ri/docs/release-documentation.html new file mode 100644 index 0000000..bce683e --- /dev/null +++ b/scripts/jaxb-ri/docs/release-documentation.html @@ -0,0 +1,3061 @@ + + + Eclipse Implementation of JAXB Release DocumentationLinks: Table of Contents | Single HTML | Single PDF

Eclipse Implementation of JAXB Release Documentation


Table of Contents

Overview
1. Documentation
2. Software Licenses
3. Sample Apps
3.1. Using the Runtime Binding Framework
Release Notes
1. + Java™ SE Requirements +
2. Identifying the JAR Files
3. Identifying the JPMS module names
4. Locating the Normative Binding Schema
5. Changelog
5.1. Changes in 4.0.0 - initial release for Jakarta EE 10
5.2. Changes between 3.0.1 and 3.0.2
5.3. Changes between 3.0.0 and 3.0.1
5.4. Changes in 3.0.0 - initial release for Jakarta EE 9
5.5. Changes in 2.3.2 - initial release for Jakarta EE 8
Eclipse Implementation of JAXB Users Guide
1. Compiling XML Schema
1.1. Dealing with errors
1.2. Fixing broken references in schema
1.3. Mapping of <xs:any />
1.4. Mapping of <xs:element /> to JAXBElement
1.5. How modularization of schema interacts with XJC
1.6. Adding behaviors
1.7. Avoid strong databinding
1.8. Working with generated code in memory
2. Customization of Schema Compilation
2.1. Customizing Java packages
2.2. Using SCD for customizations
2.3. Using different datatypes
3. Annotating Your Classes
3.1. Mapping your favorite class
3.2. Mapping interfaces
3.3. Evolving annotated classes
3.4. XML layout and in-memory data layout
3.5. Mapping cyclic references to XML
4. Unmarshalling
4.1. @XmlRootElement and unmarshalling
4.2. Unmarshalling is not working! Help!
4.3. Element default values and unmarshalling
4.4. Dealing with large documents
5. Marshalling
5.1. Changing prefixes
5.2. Element default values and marshalling
5.3. Different ways of marshalling
5.4. Interaction between marshalling and DOM
6. Schema Generation
6.1. Invoking schemagen programatically
6.2. Generating Schema that you want
7. Deployment
7.1. Using Eclipse Implementation of JAXB with Maven
7.2. Using Eclipse Implementation of JAXB on JPMS
8. Other Miscellaneous Topics
8.1. Performance and thread-safety
8.2. Compiling DTD
8.3. Designing a client/server protocol in XML
Tools
1. XJC
1.1. xjc Overview
1.2. Launching xjc
1.3. xjc Syntax
1.4. Compiler Restrictions
1.5. Generated Resource Files
2. XJC Ant Task
2.1. xjc Task Overview
2.2. xjc Task Attributes
2.3. Generated Resource Files
2.4. Up-to-date Check
2.5. Schema Language Support
2.6. xjc Examples
3. SchemaGen
3.1. schemagen Overview
3.2. Launching schemagen
3.3. schemagen Syntax
3.4. Generated Resource Files
4. SchemaGen Ant Task
4.1. schemagen Task Overview
4.2. schemagen Task Attributes
4.3. schemagen Examples
5. 3rd Party Tools
5.1. Maven JAXB Plugin
5.2. XJC Plugins
5.3. RDBMS Persistence
Eclipse Implementation of JAXB Extensions
1. Overview
2. Runtime Properties
2.1. Marshaller Properties
3. XJC Customizations
3.1. Customizations
4. DTD
4.1. DTD
5. Develop Plugins
5.1. What Can A Plugin Do?
Frequently Asked Questions
Related Articles
1. Introductory
2. Blogs
3. Interesting articles

Overview

Jakarta XML Binding + provides an API and tools that automate the mapping between XML documents + and Java objects.

The Jakarta XML Binding framework enables developers to perform the following + operations:

  • Unmarshal XML content into + a Java representation

  • Access and update the Java representation

  • Marshal the Java + representation of the XML content into XML content

Jakarta XML Binding gives Java developers an efficient and standard way of mapping + between XML and Java code. Java developers using Jakarta XML Binding are more productive + because they can write less code themselves and do not have to be experts + in XML. Jakarta XML Binding makes it easier for developers to extend their applications + with XML and Web Services technologies.

1. Documentation

Documentation for this release consists of the following:

2. Software Licenses

3. Sample Apps

This page summarizes basic use-cases for Java-2-Schema, + Schema-2-Java, and lists all of the sample applications that ship with + JAXB.

3.1. Using the Runtime Binding Framework

3.1.1. Schema-2-Java

Schema-2-Java is the process of compiling one or more schema + files into generated Java classes. Here are some of the basic + steps for developing an app:

  1. Develop/locate your schema

  2. Annotate the schema with binding customizations if + necessary (or place them in an external bindings + file)

  3. Compile the schema with the XJC binding + compiler

  4. Develop your JAXB client application using the Java + content classes generated by the XJC binding compiler + along with the jakarta.xml.bind runtime + framework

  5. Set your CLASSPATH to include all + of the Identifying the JAR Files

  6. Compile all of your Java sources with + javac

  7. Run it!

3.1.2. Java-2-Schema

Java-2-Schema is the process of augmenting existing Java + classes with the annotations defined in the + jakarta.xml.bind.annotation package so that the JAXB + runtime binding framework is capable of performing the (un)marshal + operations. Here are the basic steps for developing an app:

  1. Develop your data model in Java

  2. Apply the jakarta.xml.bind.annotation + annotations to control the binding process

  3. Set your CLASSPATH to include all + of the Identifying the JAR Files

  4. Compile your data model with + javac

    Important

    Make sure that you CLASSPATH + includes jaxb-xjc.jar before + running javac.

  5. The resulting class files will contain your + annotations as well other default annotations needed by + the JAXB runtime binding framework

  6. Develop your client application that uses the data + model and develop the code that uses the JAXB runtime + binding framework to persist your data model using the + (un)marshal operations.

  7. Compile and run your client application!

For more information about this process, see the the Java + WSDP Tutorial and the extensive Sample Apps + documentation.

3.1.3. Building and Running the Sample Apps with Ant

To run the sample applications, add jaxb dependencies + to classpath at jaxb.home property, and run ant + without any option into each sample directory.

A few sample applications do not use + Ant. For those samples, refer to the included + readme.txt files for instructions.

3.1.4. List of Sample Apps

samples/catalog-resolver

This example demonstrates how to use the + -catalog compiler switch to handle + references to schemas in external web sites.

samples/character-escape

This example shows how you can use the new JAXB + RI Marshaller property + org.glassfish.jaxb.characterEscapeHandler + to change the default character escaping + behavior.

samples/class-resolver

This little DI-container-by-JAXB example + demonstrates how one can avoid passing in a list of + classes upfront, and instead load classes + lazily.

samples/create-marshal

This sample application demonstrates how to use + the ObjectFactory class to create a + Java content tree from scratch and marshal it to XML + data. It also demonstrates how to add content to a + JAXB List property.

samples/cycle-recovery

Eclipse Implementation of JAXB's vendor extension + CycleRecoverable provides + application a hook to handle cycles in the object + graph. Advanced.

samples/datatypeconverter

This sample application is very similar to the + inline-customize sample application (formerly + SampleApp6), but + illustrates an easier, but not as robust, + <jaxb:javaType> + customization.

samples/dtd

This sample application illustrate some of the + DTD support available in the Eclipse Implementation of JAXB's extension mode. + Please refer to the Eclipse Implementation of JAXB Extensions page for more + detail.

samples/element-substitution

This sample application illustrates how W3C XML + Schema substitution groups are supported in Eclipse Implementation of JAXB's + extension mode. Please refer to the Eclipse Implementation of JAXB Extensions page for more + detail.

samples/external-customize

This sample application is identical to the + datatypeconverter sample + application (formerly + SampleApp7) except that the + binding customizations are contained in an external + binding file.

samples/fix-collides

Another binding customization example that + illustrates how to resolve name conflicts. Running + this sample without the binding file will result in + name collisions (see readme.txt) + . Running ant will use the + binding customizations to resolve the name conflicts + while compiling the schema.

samples/inline-customize

This sample application demonstrates how to + customize the default binding produced by the XJC + binding compiler.

samples/j2s-crete-marshal

This sample application demonstrates + marshalling, unmarshalling and unmarshal validation + with existing Java classes annotated with JAXB + annotations.

samples/j2s-xmlAccessorOrder

This sample application demonstrates the use of + mapping annotations + @XmlAccessorOrder and + @XmlType.propOrder in Java classes + for ordering properties and fields in Java to schema + bindings.

samples/j2s-xmlAdapter

This sample application demonstrates the use of + interface XmlAdapter and annotation + XmlJavaTypeAdapter for custom + marshaling/unmarshaling XML content into/out of a Java + type.

samples/j2s-xmlAttribute

This sample application demonstrates the use of + annotation @XmlAttribute for + defining Java properties and fields as XML + attributes.

samples/j2s-xmlRootElement

This sample application demonstrates the use of + annotation @XmlRootElement to + define a class to be an XML element.

samples/j2s-xmlSchematType

This sample application demonstrates the use of + annotation @XmlSchemaType to + customize the mapping of a property or field to an XML + built-in type.

samples/j2s-xmlType

This sample application demonstrates the use of + mapping annotations + @XmlAccessorOrder and + @XmlType.propOrder in Java classes + for ordering properties and fields in Java to schema + bindings.

samples/locator-support

This sample shows how to use the new + non-standard locator support. By following the + instructions in the readme.txt file, you can cause all + of the generated impl classes to implement a new + interface that provides more information about error + locations. When a ValidationEvent + happens on your content tree, simply retrieve the + object and cast it down to + com.sun.xml.bind.extra.Locatable.

samples/modify-marshal

This sample application demonstrates how to + modify a java content tree and marshal it back to XML + data.

samples/namespace-prefix

This sample application demonstrates how to use + the new Eclipse Implementation of JAXB Marshaller property + org.glassfish.jaxb.namespacePrefixMapper + to customize the namespace prefixes generated during + marshalling.

samples/partial-unmarshalling

In this example, the input document will be + unmarshalled a small chunk at a time, instead of + unmarshalling the whole document at once.

samples/pull-parser

This sample app demonstrates how a pull-parser + can be used with JAXB to increase the flexibility of + processing.

samples/streaming-unmarshalling

This example illustrates a different approach to + the streaming unmarshalling, which is suitable for + processing a large document.

samples/synchronized-methods

This sample shows how to use the new + non-standard synchronized method support. By following + the instructions in the + readme.txt, you can cause all of + the generated impl class methods signatures to contain + the synchronized keyword.

samples/type-substitution

This sample app demonstrates type substitution + using the W3C XML Schema Part 0: Primer international + purchase order schema.

samples/ubl

This project processes a UBL (Universal Business + Language) order instance and prints a report to the + screen.

samples/unmarshal-read

This sample application demonstrates how to + unmarshal an instance document into a Java content + tree and access data contained within it.

samples/unmarshal-validate

This sample application demonstrates how to + enable validation during the unmarshal + operations.

samples/updateablePartialBind

This sample application demonstrates how to + partially map a DOM tree to JAXB (using JAXP 1.3 + XPath), modify JAXB mapped instance and then update + modifications back to the DOM tree.

samples/vendor-extensions

This example demonstrates how to use + <xjc:superClass> vendor + extensions provided by Eclipse Implementation of JAXB's, as well as + <jaxb:serializable> + customization.

samples/xml-channel

This example demonstrates how one can use one + communication channel (such as a socket) to send + multiple XML messages, and how it can be combined with + JAXB.

samples/xml-stylesheet

A common customization need for the marshalling + output is about introducing extra processing + instruction and/or DOCTYPE + declaration. This example demonstrates how such + modification can be done easily.

Release Notes

This document contains information that should help you use this + software library more effectively. See the + Frequently Asked Questions + for additional information. +

The most up-to-date version of this document can be found on-line. +

1.  + Java™ SE Requirements +

This release of the Eclipse Implementation of JAXB requires Java SE 11 or higher.

2. Identifying the JAR Files

Use

Description

Jar

Runtime

Jars required to deploy a Jakarta XML Binding client

jakarta.activation-api.jar

angus-activation.jar

jakarta.xml.bind-api.jar

jaxb-core.jar

jaxb-impl.jar

Compiler

Jars required at your development environment (but not runtime)

jaxb-jxc.jar

jaxb-xjc.jar

3. Identifying the JPMS module names

Jar

Module name

Maven GAV

jakarta.activation-api.jar

jakarta.activation

jakarta.activation:jakarta.activation-api

angus-activation.jar

com.sun.activation.registries

org.eclipse.angus:angus-activation

jakarta.xml.bind-api.jar

jakarta.xml.bind

jakarta.xml.bind:jakarta.xml.bind-api

jaxb-core.jar

com.sun.xml.bind.core

com.sun.xml.bind:jaxb-core

jaxb-impl.jar

com.sun.xml.bind

com.sun.xml.bind:jaxb-impl

jaxb-jxc.jar

com.sun.tools.jxc

com.sun.xml.bind:jaxb-jxc

jaxb-xjc.jar

com.sun.tools.xjc

com.sun.xml.bind:jaxb-xjc

4. Locating the Normative Binding Schema

You may find information about the normative binding schema + defined in the Jakarta XML Binding Specification at https://jakarta.ee/xml/ns/jaxb. +

5. Changelog

The Eclipse Implementation of JAXB 4.x meets the requirements of the Jakarta XML Binding 4.x specifications.

5.1. Changes in 4.0.0 - initial release for Jakarta EE 10

  • Requires Java SE 11 or newer

  • Supports usage of JAXB 2.x schema bindings customizations

  • Bug fixes: +

    • Fix equality on BISerializable

    • + #936: problem with XMLMixed in a tag annotated XmlAnyElement +

    • + #971: annotation @XmlJavaTypeAdapters on package is ignored since JAXB v2.2.4-1 +

    • + #1053: Use Java 7 diamond operator +

    • + #1117: xjc-generated classes may have methods with missing @param or @return +

    • + #1489: DOMScanner ignores default namespace at scan method +

    • + #1499: xjc - NGCCRuntimeEx.resolveRelativeURL(String namespaceURI, String relativeUri ) doesn't work as it should +

    • + #1505: JCodeModel.parseType(String) silently ignores type params in specific scenarios +

    • + #1590: Marshalling an object that overrides the parent's method, + the XML that gets created contains both child's and parent's tag +

    • + #1599: XNOR implementation in NameUtil is called "xor" +

    • + #1624: Order of Exceptions in generated classes is non-deterministic +

    • + #1631: Support setting (un)marshaller listener on binder +

    +

5.2. Changes between 3.0.1 and 3.0.2

  • Bug fixes: +

    • Fixed classloading in OSGI

    • + #1547: Running with -XX:-StackTraceInThrowable causes a index out of bounds exception +

    • + #1556: xjc generates class reference with generics +

    +

5.3. Changes between 3.0.0 and 3.0.1

  • Bug fixes: +

    • + #1105: xjc mark-generated sometimes produces a wrong date value +

    • + #1466: ContextFinder always load the JAXBContext from jaxb-runtime 2.3.3 +

    • + #1475: xjc: Option to generate old package names +

    • + #1502: XJC: fails to process XSD files without systemId. +

    +

5.4. Changes in 3.0.0 - initial release for Jakarta EE 9

  • Requires Java SE 8 or newer

  • Adopts new API package namespace - jakarta.xml.bind.*

  • Main implementation jar split into two parts - jaxb-core and (smaller) jaxb-impl

  • Content of the new jaxb-impl moved from com.sun.xml.bind package to org.glassfish.jaxb.runtime package +

  • Content of the new jaxb-core moved from com.sun.xml.bind package to org.glassfish.jaxb.core package

  • Changed prefix of all properties from com.sun.xml.bind to org.glassfish.jaxb

  • Supports new namespace for schema customizations +

    <bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0">...</bindings>

    +

5.5. Changes in 2.3.2 - initial release for Jakarta EE 8

  • First release under Eclipse Jakarta EE Platform: +

    • Uptake of moved Jakarta APIs.

    +

Eclipse Implementation of JAXB Users Guide

Abstract

This document explains various interesting/complex/tricky + aspects of Eclipse Implementation of JAXB, based on questions posted on the old JAXB + users forum and answers provided there. This is an ongoing + work-in-progress. Any feedback + appreciated.

1. Compiling XML Schema

1.1. Dealing with errors

1.1.1. Schema errors

Because XML Schema is so complicated, and because there are a + lot of tools out there do not implement the spec correctly, it is + often the case that a schema you are trying to compile has some real + errors in it. When this is the case, you'll see XJC reporting somewhat + cryptic errors such as rcase-RecurseLax.2: There is not a + complete functional mapping between the particles.

The Eclipse Implementation of JAXB uses the schema correctness checker from the + underlying JAXP implementation, which is the JAXP RI in a typical + setup. The JAXP RI is one of the most conformant schema validators, + and therefore most likely correct. So the first course of action + usually is to fix problems in the schema.

However, in some situations, you might not have an authority to + make changes to the schema. If that is the case and you really need to + compile the schema, you can bypass the correctness check by using the + -nv option in XJC. When you do this, keep in mind + that you are possibly feeding "garbage" in, so you may see XJC choke + with some random exception.

1.1.2. Property 'fooBarZot' is already defined

One of the typical errors you'll see when compiling a complex + schema is:

Example 1. Multiple property definitions error

parsing a schema...
+[ERROR] Property "MiOrMoOrMn" is already defined.
+  line 132 of
+file:/C:/kohsuke/Sun/JAXB/jaxb-unit/schemas/individual/MathML2/presentation/scripts.xsd
+
+[ERROR] The following location is relevant to the above error
+  line 138 of
+file:/C:/kohsuke/Sun/JAXB/jaxb-unit/schemas/individual/MathML2/presentation/scripts.xsd

This is an actual example of the offending part of a schema, + taken from MathML. If you go to line 132 of + scripts.xsd, you'll see that it has a somewhat + complicated content model definition:

Example 2. Multiple property definitions in MathML

<xs:group name="mmultiscripts.content">
+    <xs:sequence>
+        <xs:group ref="Presentation-expr.class"/>
+        <xs:sequence minOccurs="0" maxOccurs="unbounded">      <!-- line 132 -->
+            <xs:group ref="Presentation-expr-or-none.class"/>
+            <xs:group ref="Presentation-expr-or-none.class"/>
+        </xs:sequence>
+        <xs:sequence minOccurs="0">
+            <xs:element ref="mprescripts"/>
+            <xs:sequence maxOccurs="unbounded">                 <!-- line 138 -->
+                <xs:group ref="Presentation-expr-or-none.class"/>
+                <xs:group ref="Presentation-expr-or-none.class"/>
+            </xs:sequence>
+        </xs:sequence>
+    </xs:sequence>
+</xs:group>

This is a standard technique in designing a schema. When you + want to say "in this element, B can occur arbitrary + times, but C can occur only up to once", you write + this as B*,(C,B*)?. This, however, confuses Eclipse Implementation of JAXB, + because it tries to bind the first B to its own + property, then C to its own property, then the + second B to its own property, and so we end up + having a collision again.

In this particular case, B isn't a single + element but it's a choice of large number of elements abstracted away + in <xs:group>s, so they are hard to see. But + if you see the same content model referring to the same element/group + twice in a different place, you can suspect this.

In this case, you'd probably want the whole thing to map to a + single list so that you can retain the order those elements show up in + the document. You can do this by putting the same + <jaxb:property> customization on the whole + "mmultiscripts.content" model group, like this (or + you can do it externally with XPath):

Example 3. How to fix the problem?

<xs:groupname="mmultiscripts.content">
+<xs:annotation>
+    <xs:appinfo>
+        <jaxb:propertyname="content"/>
+    </xs:appinfo>
+</xs:annotation>
+<xs:sequence>
+<xs:groupref="Presentation-expr.class"/>

Another way to fix this problem is to use the + simpler and better binding mode in XJC, which is a Eclipse Implementation of JAXB + vendor extension.

1.1.3. Two declarations cause a collision in the ObjectFactory + class

When schemas contain similar looking element/type names, they + can result in "Two declarations cause a collision in the ObjectFactory + class" errors. To be more precise, for each of all types and many + elements (exactly what elements get a factory and what doesn't is bit + tricky to explain), XJC produces one method on the + ObjectFactory class in the same package. The + ObjectFactory class is created for each package that XJC + generates some files into. The name of the method is derived from XML + element/type names, and the error is reported if two elements/types + try to generate the same method name.

There are two approaches to fix this problem. If the collision + is coming from two different schemas with different target namespaces, + then you can easily avoid the collision by compiling them into + different Java packages. To do this, use <schemabindings> + customization on two schemas and specify the package name.

Another way to fix this problem is to use <factoryMethod> + customization on two conflicting elements/types to specify different + factory method names. This can be used in all cases, but if you have a + large number of conflicts, you'll have to specify this customization + one by one.

Notice that <class> + customization doesn't affect the ObjectFactory method + name by itself.

1.1.4. Customization errors

1.1.4.1. XPath evaluation of ... results in empty target + node

External Jakarta XML Binding customizations are specified by using XPath + (or using SCD.) + This works by writing an XPath expression that matches a + particular element in the schema document. For example, given the + following schema and binding file:

Example 4. Schema and external binding file

test.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+    <xs:complexTypename="foo"/>
+</xs:schema>

test.xjb

<bindings version="3.0" xmlns="https://jakarta.ee/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+    <bindings schemaLocation="test.xsd">
+        <bindings node="//xs:complexType[@name='foo']">
+            <classname="Bar"/>
+        </bindings>
+    </bindings>
+</bindings>

will be interpreted as if the class customization is + attached to the complex type 'foo'.

For this to work, the XPath expression needs to match one + and only one element in the schema document. When the XPath + expression is incorrect and it didn't match anything, you get this + "XPath evaluation of ... results in empty target node" + problem.

Common causes of this problem include typos, incorrect + namespace URI declarations, and misunderstanding of XPath.

1.2. Fixing broken references in schema

Sometimes a schema may refer to another schema document without + indicating where the schema file can be found, like this:

Example 5. Schema reference without location

<xs:import namespace="http://www.w3.org/1999/xlink" />

In other cases, a schema may refer to another schema on the network, + which often slows down your compilation process and makes it unreliable. + Yet in some other cases, a schema may reference another schema in relative + path, and that may not match your directory structure.

XJC bundles a catalog + resolver so that you can work around these situations without + changing the schema documents. The main idea behind the catalog is + "redirection" --- when XJC is about to fetch resources, it will consult + the catalog resolver to see if it can find the resource elsewhere (which + is usually your local resources.)

1.2.1. Catalog format

The catalog resolver supports many different formats, but the + easiest one is a line based *.cat format. Other than + comments and empty lines, the file mainly consists of two kinds of + declarations, SYSTEM, and + PUBLIC.

Example 6. sample-catalog.cat

--
+  sample catalog file.
+
+  double hyphens are used to begin and end a comment section.
+--
+
+SYSTEM "http://www.w3.org/2001/xml.xsd" "xml.xsd"
+
+PUBLIC "-//W3C//DTD XMLSCHEMA 200102//EN" "s4s/XMLSchema.dtd"

1.2.2. Resolve by system ID

The SYSTEM entry has the format of "SYSTEM + REFERENCE ACTUAL-LOCATION", + which defines a simple redirection. Every time XJC loads any resource + (be it schemas, DTDs, any entities referenced within), it will first + resolve relative paths to absolute paths, then looks for a matching + REFERENCE line. If it is found, the specified + actual location is read instead. Otherwise XJC will attempt to resolve + the absolutepath.

ACTUAL-LOCATION above accepts relative + paths, and those are resolved against the catalog file itself (so in + the above example, xml.xsd is assumed to be in the same + directory with sample-catalog.cat.

What you need to be careful is the fact that the + REFERENCE portion must be absolute, and when XJC + finds a reference in schema, it will first convert that to the + absolute path before checking the catalog. So what this means is that + if your schema is written like this:

Example 7. Schema reference by relative path

<xs:import namespace="http://www.w3.org/1999/xlink" schemaLocation="xlink.xsd" />

Then your catalog entry would have to look like this:

Example 8. xlink.cat

-- this doesn't work because xlink.xsd will be turned into absolute path --
+SYSTEM "xlink.xsd" "http://www.w3.org/2001/xlink.xsd"
+
+-- this will work, assuming that the above schema is in /path/to/my/test.xsd --
+SYSTEM "/path/to/my/xlink.xsd" "http://www.w3.org/2001/xlink.xsd"

1.2.3. Resolve by public ID / namespace URI

Another kind of entry has the format of "PUBLIC + PUBLICID ACTUAL-LOCATION" or + "PUBLIC NAMESPACEURI + ACTUAL-LOCATION".

The "PUBLICID" version is used to resolve DTDs and entities in + DTDs. But this type of entry is also used to resolve <xs:import> + statements. XJC will match the value of the namespace attribute and + see if there's any matching entry. So given a schema like this:

Example 9. Schema import

<xs:import namespace="http://www.w3.org/1999/xlink" schemaLocation="xlink.xsd" />
+<xs:import namespace="http://www.w3.org/1998/Math/MathML" />

The following catalog entries will match them.

Example 10. by-publicid.cat

PUBLIC "http://www.w3.org/1999/xlink" "http://www.w3.org/2001/xlink.xsd"
+PUBLIC "http://www.w3.org/1998/Math/MathML" "/path/to/my/mathml.xsd"

As you can see, XJC will check the PUBLIC entries regardless of + whether <xs:import> has the schemaLocation attribute or not. As + with the case with the SYSTEM entry, the ACTUAL-LOCATION part can be + relative to the location of the catalog file.

1.2.4. Specifying the catalog file

Once you write a catalog file, you'd need to specify that when + you invoke XJC.

CLI

To do this from the CLI, use the -catalog option. See xjc + -help for more details.

Ant

Use the catalog attribute on the <xjc> task. + See XJC + ant task documentation for more details.

Maven

For the Maven + plugin, use the <catalog> element in the + configuration:

<plugin>
+    <groupId>org.jvnet.jaxb2.maven2</groupId>
+    <artifactId>maven-jaxb2-plugin</artifactId>
+    <configuration>
+        <!-- relative to the POM file -->
+        <catalog>mycatalog.cat</catalog>
+    </copnfiguration>
+</plugin>

1.2.5. Debugging catalog file

If you are trying to write a catalog file and banging your head + against a wall because it's not working, you should enable the verbose + option of the catalog resolver. How you do this depends on what + interface you use:

CLI

Specify export + XJC_OPTS="-Dxml.catalog.verbosity=999" then run + XJC.

Ant/Maven

Add -Dxml.catalog.verbosity=999 as a + command line option to Ant/Maven.

If you are otherwise invoking XJC programmatically, you can set + the above system property before invoking XJC.

1.3. Mapping of <xs:any />

XJC binds <xs:any /> in the following ways:

1.3.1. processContents="skip"

<xs:any /> with processContents=skip means + any well-formed XML elements can be placed. Therefore, XJC binds this + to DOM Element interface.

Example 11. Any/Skip schema

<xs:element name="person">
+  <xs:complexType>
+    <xs:sequence>
+      <xs:element name="name" type="xs:string" />
+      <xs:any processContents="skip" maxOccurs="unbounded" minOccurs="0" />
+    </xs:sequence>
+  </xs:complexType>
+</xs:element>

Example 12. Any/Skip binding

import org.w3c.dom.Element;
+
+@XmlRootElement
+class Person {
+  public String getName();
+  public void setName(String);
+
+  @XmlAnyElement
+  public List<Element> getAny();
+}

1.3.2. processContents="strict"

<xs:any /> with processContents=strict (or + <xs:any /> without any processContents attribute, since it + defaults to "strict") means any XML elements placed here must have + corresponding schema definitions. This mode is not what people + typically expect as "wildcard", but this is the default. The following + shows this binding. (lax=true is unintuitive, but it's + not an error in this document):

Example 13. Any/Strict schema

<xs:element name="person">
+  <xs:complexType>
+    <xs:sequence>
+      <xs:element name="name" type="xs:string" />
+      <xs:any maxOccurs="unbounded" minOccurs="0" />
+    </xs:sequence>
+  </xs:complexType>
+</xs:element>

Example 14. Any/Strict binding

@XmlRootElement
+class Person {
+  public String getName();
+  public void setName(String);
+
+  @XmlAnyElement(lax=true)
+  public List<Object> getAny();
+}

Jakarta XML Binding binds any such element to an Object, and + during unmarshalling, all elements encountered are unmarshalled into + corresponding Jakarta XML Binding objects (including JAXBElements if + necessary) and placed in this field. If it encounters elements that + cannot be unmarshalled, DOM elements are produced instead.

At runtime, you can place either DOM elements or some Jakarta XML Binding + objects that map to elements. A typical mistake is to put a + String that contains XML fragment, but this won't work; + you'd have to first read that into a DOM.

1.3.3. processContents="lax"

<xs:any /> with processContents=lax means any + XML elements can be placed here, but if their element names match + those defined in the schema, they have to be valid. XJC actually + handles this exactly like processContents='strict', since the strict + binding allows unknown elements anyway.

1.4. Mapping of <xs:element /> to JAXBElement

Sometimes XJC binds an element declaration to + JAXBElement. Sometimes XJC binds an element declaration to a + Java class. What makes this difference?

1.5. How modularization of schema interacts with XJC

Over time schema authors have developed several techniques to + modularize large schemas. Some of those techniques have some noteworthy + interactions with XJC.

1.5.1. Chameleon schema

Chameleon + schema" (read + more, in particular this) + is a technique used to define multiple almost-identical sets of + definitions into multiple namespaces from a single schema + document.

For example, with this technique, you can write just one "foo" + complex type and define it into namespace X and Y. In this case, one + tends to hope that XJC will only give you one Foo class + for this, but unfortunately because it's actually defined in two + namespaces, Jakarta XML Binding needs two Java classes to distinguish X:foo and + Y:foo, so you'll get multiple copies.

If you find this to be problematic, there are a few ways to work + around the problem.

  1. If you are in control of the schema, see if you can + rewrite the schema to avoid using this technique. In some + cases, the schema doesn't actually exploit the additional + power of this technique, so this translation can be done + without affecting XML instance documents. In some other cases, + the chameleon schema can be argued as a bad schema design, as + it duplicates definitions in many places.

  2. If you are not in control of the schema, see if you can + rewrite the schema nevertheless. This will only work if your + transformation doesn't affect XML instance documents.

  3. Perhaps there can be a plugin that eases the pain of + this, such as by defining common interfaces among + copies.

1.6. Adding behaviors

Adding behaviors to the generated code is one area that + still needs improvement. Your feedback is appreciated.

Suppose if Eclipse Implementation of JAXB generated the following classes.

Example 15. Simple Eclipse Implementation of JAXB Generated Code

package org.acme.foo;
+
+@XmlRootElement
+class Person {
+  private String name;
+
+  public String getName() { return name; }
+  public void setName(String) { this.name=name; }
+}
+
+@XmlRegistry
+class ObjectFactory {
+  Person createPerson() { ... }
+}

To add a behavior, first write a class that extends from + Person. You also need to extend ObjectFactory to return this + new class. Notice that neither classes have any Jakarta XML Binding annotation, and I put + them in a separate package. This is because we'd like + PersonEx class to be used in place of Person, + and we don't want PersonEx to be bound to its own XML + type.

Example 16. Extended Person class

package org.acme.foo.impl;
+
+class PersonEx extends Person {
+  @Override
+  public void setName(String name) {
+    if(name.length()<3) throw new IllegalArgumentException();
+    super.setName(name);
+  }
+}
+
+@XmlRegistry
+class ObjectFactoryEx extends ObjectFactory {
+  @Override
+  Person createPerson() {
+    return new PersonEx();
+  }
+}

At runtime, you can create JAXBContext normally, like + this.

Example 17. Creating JAXBContext

JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
+// or JAXBContext.newInstance("org.acme.foo");

PersonEx can be marshalled out just like + Person:

Example 18. Marshalling

Person p = new PersonEx();
+context.createMarshaller().marshal(p,System.out);
+// this will produce <person />

To unmarshal XML documents into PersonEx, you'll need + to configure the unmarshaller to use your ObjectFactoryEx as + the factory, like this:

Example 19. Unmarshalling

Unmarshaller u = context.createUnmarshaller();
+u.setProperty("org.glassfish.jaxb.core.ObjectFactory",new ObjectFactoryEx());
+PersonEx p = (PersonEx)u.unmarshal(new StringReader("<person />"));

If you have multiple packages and thus multiple + ObjectFactorys, you can pass in an array of them (new + Object[]{new OFEx1(),new OFEx2(),...}.)

1.6.1. Inserting your class in the middle

If you have a type hierarchy and would like to insert your class + in the middle, you can use the combination of XmlTransient + and @implClass of <class> + customization. See the following example:

Example 20. Hierarchy of types and <jaxb:class implClass>

<xs:schema ...>
+  <xs:complexType name="vehicle">
+    <xs:annotation><xs:appinfo>
+      <jaxb:class implClass="MyVehicle" />
+    </xs:appinfo></xs:annotation>
+  </xs:complexType>
+
+  <xs:complexType name="car">
+    <xs:complexContent>
+      <xs:extension base="vehicle" />
+    </xs:complexContent>
+  </xs:complexType>
+
+  <xs:complexType name="bicycle">
+    <xs:complexContent>
+      <xs:extension base="vehicle" />
+    </xs:complexContent>
+  </xs:complexType>
+</xs:schema>

Example 21. This creates a class hierarchy like the following (among + the generated Java code):

            Vehicle
+               ^
+               |
+            MyVehicle
+               ^
+          _____|______
+         |            |
+        Car          Bicycle

You'll then manually write MyVehicle class that + extends from Vehicle. Annotate this class with XmlTransient + to achieve the desired effect.

1.7. Avoid strong databinding

Under some limited circumstances, a weaker databinding is preferable + for various reasons. Jakarta XML Binding does offer a few ways for you to achieve + this.

1.7.1. Avoid mapping to enum

The following customization will stop binding a simple type to a + type-safe enum. This can be convenient when number of constants is too + large to be an useful enum (by default, the Jakarta XML Binding spec won't generate + enum with more than 256 constants, but even 100 might be too large for + you.)

Example 22. Avoid mapping one simple type

<xs:simpleType name="foo">
+  <xs:annotation><xs:appinfo>
+    <jaxb:typesafeEnumClass map="false" />
+  </xs:appinfo></xs:annotation>
+  <xs:restriction base="xs:string">
+    <xs:enumeration value="x" />
+    <xs:enumeration value="y" />
+    <xs:enumeration value="z" />
+  </xs:restriction>
+</xs:simpleType>

To disable such type-safe enum binding altogether for the entire + schema, use a global binding setting like this (this is actually + telling XJC not to generate enums if a simple type has more than 0 + constants --- the net effect is no enum generation):

Example 23. Avoid generating enums at all

<xs:schema ...>
+  <xs:annotation><xs:appinfo>
+    <jaxb:globalBindings typesafeEnumMaxMembers="0" />
+  </xs:appinfo></xs:annotation>
+  ...
+</xs:schema>

1.7.2. Mapping to DOM

The <jaxb:dom>customization allows you to map + a certain part of the schema into a DOM tree. This customization can + be attached to the following schema components:

  • Wildcards (<xs:any>)

  • Type definitions (<xs:complexType> and + <xs:simpleType>)

  • Model groups + (<xs:choice>,<xs:all>,<xs:sequence>)

  • Model group declarations (<xs:group>)

  • Particles

  • Element declarations (<xs:element>)

In the following example, a wildcard is mapped to a DOM node. + Each element that matches to the wildcard will be turned into a DOM + tree.

Example 24. Dom Customization example

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+               xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+               jaxb:version="3.0">
+
+        <xs:element>
+           <xs:complexType>
+              <xs:sequence>
+                 <xs:any maxOccurs="unbounded" processContents="skip">
+                    <xs:annotation><xs:appinfo>
+                      <jaxb:dom/>
+                    </xs:appinfo></xs:annotation>
+                 </xs:any>
+              </xs:sequence>
+           </xs:complexType>
+        </xs:element>
+    .
+    .
+    .
+    </xs:schema>

This extension can be used to access wildcard content or can be + used to process a part of a document by using other technologies that + require "raw" XML. By default, Jakarta XML Binding generates a getContent() method + for accessing wildcard content, but it only supports "lax" handling + which means that unknown content is discarded. You may find more + information in 7.12 chapter of Jakarta XML Binding 2 + specification.

1.8. Working with generated code in memory

1.8.1. Cloning

The generated beans (and in particular the + JAXBElement class) do not support the clone operation. + There was a suggestion by another user that beanlib has been + used successfully to clone Jakarta XML Binding objects.

2. Customization of Schema Compilation

2.1. Customizing Java packages

The Jakarta XML Binding specification provides a <jaxb:schemaBindings> + customization so that you can control which namespace goes to which + package. See the example below:

Example 25. package customization

    <jaxb:schemaBindings>
+      <jaxb:package name="org.acme.foo"/>
+    </jaxb:schemaBindings>

You can do this as an internal customization (in which case you put + this in <xs:annotation><xs:appinfo> under place it right under + the <xs:schema> element), or do this as an external customization, + like this:

Example 26. External package customization

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0">
+  <bindings schemaLocation="../path/to/my.xsd">
+    <schemaBindings>
+      <package name="org.acme.foo"/>
+    </schemaBindings>
+  </bindings>
+</bindings>

Note that this customization is per namespace. That is, even if your + schema is split into multiple schema documents, you cannot put them into + different packages if they are all in the same namespace.

2.1.1. Tip: get rid of the org.w3._2001.xmlschema package

Under some rare circumstances, XJC will generate some Java + classes into a package called org.w3._2001.xmlschema. + This happens when XJC decides that it needs some Java artifacts for + the XML Schema built-in namespace of + http://www.w3.org/2001/XMLSchema.

Since this package name is most often problematic, you can + rename this by simply saving the following text in an .xsd file and + submitting it to XJC along with the other schemas you have:

Example 27. Schemalet to get rid of org.w3._2001.xmlschema

<schema xmlns="http://www.w3.org/2001/XMLSchema"
+  targetNamespace="http://www.w3.org/2001/XMLSchema"
+  xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+  jaxb:version="3.0">
+  <annotation><appinfo>
+    <jaxb:schemaBindings>
+      <jaxb:package name="org.acme.foo"/>
+    </jaxb:schemaBindings>
+  </appinfo></annotation>
+</schema>

This is bit tricky, but the idea is that since you can define a + schema for one namespace in multiple schema documents, this makes XJC + think that this schema is a part of the built-in "XML Schema for XML + Schema".

2.2. Using SCD for customizations

When using an external customization file, the Jakarta XML Binding spec requires + that you use XPath as a means to specify what your customization is + attached to. For example, if you want to change the class name generated + from a complex type, you'd write something like:

Example 28. External customization example

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <bindings schemaLocation="../path/to/my.xsd" node="/xs:schema/xs:complexType[@name='foo']">
+    <class name="FooType"/>
+  </bindings>
+</bindings>

While the above process works, the problem with this is that the + XPath+ schemaLocation combo tends to be verbose and error + prone. It's verbose, because often a trivial target schema component like + this "global complex type foo" takes up a lot of characters. The xs + namespace declaration also takes up some space, although in this case we + managed to avoid declaring the "tns" namespace (that represents the + namespace that the schema defines.)

It's also error prone, because it relies on the way schema documents + are laid out, because the schemaLocation attribute needs to point to the + right schema document file. When a schema is split into multiple files for + modularity (happens especially often with large schemas), then you'd have + to find which schema file it is. Even though you can use relative paths, + this hard-coding of path information makes it hard to pass around the + binding file to other people.

JAXB RI 2.1 and onward offers a better way to do this as a vendor + extension.

The key technology to solve this problem is a "schema component + designator" (SCD.) This is a path language just like XPath, but + whereas XPath is designed to refer to XML infoset items like elements and + attributes, SCD is designed to refer to schema components like element + declarations or complex types.

With SCD, the above binding can be written more concisely as + follows:

Example 29. External customization by SCD

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0" xmlns:tns="http://my.namespace/">
+  <bindings scd="/type::tns:foo">
+    <class name="FooType"/>
+  </bindings>
+</bindings>

/type::tns:foo can be written more concisely as + /~tns:foo, too. If you are interested in more about the + syntax of SCDs, read the + example part of the spec, and maybe EBNF. + If you know XPath, I think you'll find this fairly easy to learn.

Another benefit of an SCD is that tools will have easier time + generating SCDs than XPath, as XPaths are often vulnerable to small + changes in the schema document, while SCDs are much more robust. The + downside of using SCD is as of JAXB 2.1, this feature is a vendor + extension and not defined in the spec.

2.3. Using different datatypes

Eclipse Implementation of JAXB has a built-in table that determines what Java classes are used + to represent what XML Schema built-in types, but this can be + customized.

One of the common use cases for customization is to replace the + XMLGregorianCalendar with the friendlier + Calendar or Date. + XMLGregorianCalendar is designed to be 100% compatible with + XML Schema's date/time system, such as providing infinite precision in + sub-seconds and years, but often the ease of use of those familiar Java + classes win over the precise compatibility.

One very easy way to do this is to simply use your IDE (or even + "sed") to replace all the references to XMLGregorianCalendar + by Calendar. This is of course not a very attractive option + if your build process runs XJC as a part of it.

Alternatively, the following customization file can be used to do + this. When using external customization file, the Jakarta XML Binding spec requires you + to use XPath as a means to specify what your customization is attached to. + For example, if you want to change the class name generated from a complex + type, you'd use the following customization:

Example 30. Customization to use Calendar for xs:date

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <globalBindings>
+    <javaType name="java.util.Calendar" xmlType="xs:date"
+      parseMethod="jakarta.xml.bind.DatatypeConverter.parseDate"
+      printMethod="jakarta.xml.bind.DatatypeConverter.printDate"
+    />
+  </globalBindings>
+</bindings>

Save this in a file and specify this to Eclipse Implementation of JAXB with the "-b" + option.

To use the Date class, you'll need to do a bit more + work. First, put the following class into your source tree:

Example 31. Adapter for Date

package org.acme.foo;
+public class DateAdapter {
+  public static Date parseDate(String s) {
+    return DatatypeConverter.parseDate(s).getTime();
+  }
+  public static String printDate(Date dt) {
+    Calendar cal = new GregorianCalendar();
+    cal.setTime(dt);
+    return DatatypeConverter.printDate(cal);
+  }
+}

... then your binding file will be the following:

Example 32. Customization to use Date for xs:date

<bindings xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <globalBindings>
+    <javaType name="java.util.Date" xmlType="xs:date"
+      parseMethod="org.acme.foo.DateAadpter.parseDate"
+      printMethod="org.acme.foo.DateAdapter.printDate"
+    />
+  </globalBindings>
+</bindings>

3. Annotating Your Classes

3.1. Mapping your favorite class

3.1.1. ResultSet

Jakarta XML Binding (or any other databinding engine, for that matter) is for + binding strongly-typed POJO-like objects to XML, such as + AddressBook class, PurchaseOrder class, and + so on, where you have fields and methods that shape a class.

There are other kinds of classes that are more close to + reflection. Those classes don't have methods like + getAddress, and instead you'd do + get("Address"). JDBC ResultSet is one of those classes. + It's one class that represents million different data structures, be + it a customer table or a product table. Generally speaking, these + classes does not allow Jakarta XML Binding to statically determine what the XML + representation should look like. Instead, you almost always need to + look at an instance to determine the shape of XML.

These classes are not really suitable for binding in Jakarta XML Binding. If + this is the only object that you'd want to write out, then you'd be + better off using XMLStreamWriter or some such XML infoset writing API. + There are a few online + articles that cover this topic. Also, many modern database + offers a native ability to export a query into XML, which is supposed + to work a lot faster than you'd do in Java (and saves your time of + writing code.)

If you are using ResultSet as a part of your object tree that + you want to marshal to Jakarta XML Binding, then you can use + XmlJavaTypeAdapter.

3.1.2. HashMap

Jakarta XML Binding spec defines a special handling for Map when + it's used as a propety of a bean. For example, the following bean + would produce XMLs like the following:

Example 33. Bean with Map

@XmlRootElement
+class Foo {
+  public HashMap<String,Integer> map;
+}

Example 34. XML representation

<foo>
+  <map>
+    <entry>
+      <key>a</key>
+      <value>1</value>
+    </entry>
+    <entry>
+      <key>b</key>
+      <value>2</value>
+    </entry>
+  </map>
+</foo>

Unfortunately, as of 2.1, this processing is only defined for + bean properties and not when you marshal HashMap as a + top-level object (such as a value in JAXBElement.) In + such case, HashMap will be treated as a Java bean, and + when you look at HashMap as a bean it defines no + getter/setter property pair, so the following code would produce the + following XML:

Example 35. Bean with Map

m = new HashMap();
+m.put("abc",1);
+marshaller.marshal(new JAXBElement(new QName("root"),HashMap.class,m),System.out);

Example 36. XML representation

<root />

This issue has been recorded as #223 + and the fix needs to happen in later versions of the Jakarta XML Binding spec.

In the mean time, such top-level objects have to be first + adapted to a bean that Jakarta XML Binding can process. This has added benefit of + being able to control XML representation better. The following code + illustrates how to do this:

Example 37. Adapting HashMap

public class MyHashMapType {
+    public List<MyHashMapEntryType> entry = new ArrayList<MyHashMapEntryType>();
+    public MyHashMapType(Map<String,Integer> map) {
+        for( Map.Entry<String,Integer> e : map.entrySet() )
+            entry.add(new MyHashMapEntryType(e));
+    }
+    public MyHashMapType() {}
+}
+
+public class MyHashMapEntryType {
+    @XmlAttribute // @XmlElement and @XmlValue are also fine
+    public String key;
+
+    @XmlAttribute // @XmlElement and @XmlValue are also fine
+    public int value;
+
+    public MyHashMapEntryType() {}
+    public MyHashMapEntryType(Map.Entry<String,Integer> e) {
+       key = e.getKey();
+       value = e.getValue();
+    }
+}
+
+marshaller.marshal(new JAXBElement(new QName("root"),MyHashMapType.class,new MyHashMapType(m)),System.out);

If you have a lot of difference kinds of Map, you + can instead use Object as the key and the value type. In + that way, you'll be able to use maps with different type parameters, + at the expense of seeing xsi:type attribute on the + instance document.

3.2. Mapping interfaces

Because of the difference between the XML type system induced by W3C + XML Schema and the Java type system, Jakarta XML Binding cannot bind interfaces out of + the box, but there are a few things you can do.

3.2.1. Use @XmlRootElement

When your interface is implemented by a large number of + sub-classes, consider using XmlRootElement annotation like this:

Example 38. XmlRootElement for open-ended interfaces

@XmlRootElement
+class Zoo {
+  @XmlAnyElement
+  public List<Animal> animals;
+}
+
+interface Animal {
+  void sleep();
+  void eat();
+  ...
+}
+
+@XmlRootElement
+class Dog implements Animal { ... }
+
+@XmlRootElement
+class Lion implements Animal { ... }

This will produce XML documents like this:

Example 39. XML for XmlRootElement

<zoo>
+    <lion> ... </lion>
+    <dog> ... </dog>
+</zoo>

The key characteristics of this approach is:

  1. Implementations are open-ended; anyone can implement + those interfaces, even by different people from different + modules, provided they are all given to the + JAXBContext.newInstance method. There's no need + to list all the implementation classes in anywhere.

  2. Each implementation of the interface needs to have an + unique element name.

  3. Every reference to interface needs to have the XmlElementRef annotation. The + type=Object.class portion tells Jakarta XML Binding that the + greatest common base type of all implementations would be + java.lang.Object.

@XmlElementWrapper is often useful with this, + as it allows you need to group them. Such as:

Example 40. XmlRootElement for open-ended interfaces

@XmlRootElement
+class Zoo {
+  @XmlElementWrapper
+  @XmlAnyElement
+  public List<Animal> onExhibit;
+  @XmlElementWrapper
+  @XmlAnyElement
+  public List<Animal> resting;
+}

Example 41. Effect of XmlElementWrapper

<zoo>
+    <onExhibit>
+        <lion> ... </lion>
+        <dog> ... </dog>
+    </onExhibit>
+    <resting>
+        <lion> ... </lion>
+        <dog> ... </dog>
+    </resting>
+</zoo>

3.2.2. Use @XmlJavaTypeAdapter

When you use interfaces just to hide your implementation classes + from exposure, and when there's 1-to-1 (or close to 1-on-1) + relationship between a class and an interface, XmlJavaTypeAdapter can be used like below.

Example 42. XmlJavaTypeAdapter for interfaces

@XmlJavaTypeAdapter(FooImpl.Adapter.class)
+interface IFoo {
+  ...
+}
+class FooImpl implements IFoo {
+  @XmlAttribute
+  private String name;
+  @XmlElement
+  private int x;
+
+  ...
+
+  static class Adapter extends XmlAdapter<FooImpl,IFoo> {
+    IFoo unmarshal(FooImpl v) { return v; }
+    FooImpl marshal(IFoo v) { return (FooImpl)v; }
+  }
+}
+
+class Somewhere {
+  public IFoo lhs;
+  public IFoo rhs;
+}

Example 43. XML of XmlJavaTypeAdapter

<somewhere>
+  <lhs name="...">
+    <x>5</x>
+  </lhs>
+  <rhs name="...">
+    <x>5</x>
+  </rhs>
+</somewhere>

The key characteristics of this approach is:

  1. Interface and implementation will be tightly coupled + through an adapter, although changing an adapter code will + allow you to support multiple implementations.

  2. There's no need of any annotation in where interfaces + are used.

A variation of this technique is when you have a few + implementations for interface, not just one.

Example 44. XmlJavaTypeAdapter for interfaces with multiple + implementations

@XmlJavaTypeAdapter(AbstractFooImpl.Adapter.class)
+interface IFoo {
+  ...
+}
+abstract class AbstractFooImpl implements IFoo {
+  ...
+
+  static class Adapter extends XmlAdapter<AbstractFooImpl,IFoo> {
+    IFoo unmarshal(AbstractFooImpl v) { return v; }
+    AbstractFooImpl marshal(IFoo v) { return (AbstractFooImpl)v; }
+  }
+}
+
+class SomeFooImpl extends AbstractFooImpl {
+  @XmlAttribute String name;
+  ...
+}
+
+class AnotherFooImpl extends AbstractFooImpl {
+  @XmlAttribute int id;
+  ...
+}
+
+class Somewhere {
+  public IFoo lhs;
+  public IFoo rhs;
+}

Example 45. XML of XmlJavaTypeAdapter with multiple + implementations

<somewhere>
+  <lhs xsi:type="someFooImpl" name="...">
+  </lhs>
+  <rhs xsi:type="anotherFooImpl" id="3" />
+</somewhere>

Note that SomeFooImpl and + AnotherFooImpl must be submitted to + JAXBContext.newInstance one way or the other.

To take this example a bit further, you can use + Object instead of AbstractFooImpl. The + following example illustarates this:

Example 46. XmlJavaTypeAdapter for interfaces with multiple + implementations

@XmlJavaTypeAdapter(AnyTypeAdapter.class)
+interface IFoo {
+  ...
+}
+public class AnyTypeAdapter extends XmlAdapter<Object,Object> {
+  Object unmarshal(Object v) { return v; }
+  Object marshal(Object v) { return v; }
+}
+
+class SomeFooImpl implements IFoo {
+  @XmlAttribute String name;
+  ...
+}
+
+class Somewhere {
+  public IFoo lhs;
+  public IFoo rhs;
+}

Example 47. Corresponding schema

<xs:complexType name="somewhere">
+  <xs:sequence>
+    <xs:element name="lhs" type="xs:anyType" minOccurs="0"/>
+    <xs:element name="rhs" type="xs:anyType" minOccurs="0"/>
+  </xs:sequence>
+</xs:complexType>

As you can see, the schema will generated to accept + xs:anyType which is more relaxed than what the Java code + actually demands. The instance will be the same as the above example. + Starting from JAXB RI 2.1, we bundle the + AnyTypeAdapter class in the runtime that + defines this adapter. So you won't have to write this adapter in your + code.

3.2.3. Use @XmlElement

If the use of interface is very little and there's 1-to-1 (or + close to) relationship between interfaces and implementations, then + you might find XmlElement to be the least amount of work.

Example 48. XmlElement for interfaces

interface IFoo {
+  ...
+}
+class FooImpl implements IFoo {
+  ...
+}
+
+class Somewhere {
+  @XmlElement(type=FooImpl.class)
+  public IFoo lhs;
+}

Example 49. XML of XmlElement

<somewhere>
+  <lhs> ... </lhs>
+</somewhere>

This effectively tells Jakarta XML Binding runtime that "even though the field + is IFoo, it's really just FooImpl.

In this approach, a reference to an interface has to have + knowledge of the actual implementation class. So while this requires + the least amount of typing, it probably wouldn't work very well if + this crosses module boundaries.

Like the XmlJavaTypeAdapter approach, this can be used + even when there are multiple implementations, provided that they share + the common ancestor.

The extreme of this case is to specify + @XmlElement(type=Object.class).

3.2.4. Hand-write schema

Occasionally the above approaches cause the generated schema to + become somewhat ugly, even though it does make the Jakarta XML Binding runtime work + correctly. In such case you can choose not to use the generated schema + and instead manually modify/author schemas tht better match your + needs.

3.2.5. Do schema-to-java

With sufficient knowlege, one can also use <jaxb:class + ref="..."/> annotation so that you can cause XJC to use the classes + you already wrote. See this + thread for an example. TODO: more details and perhaps an + example.

3.2.6. DOESN'T WORK: Have Jakarta XML Binding generate interaces and swap different + implementations

Some + users attempted to use the "generateValueClass" customization + and see if they can completely replace the generated implementations + with other implementations. Unfortunately, this does not work.

Even with the interface/implementation mode, Jakarta XML Binding runtime still + requires that the implementation classes have all the Jakarta XML Binding + annotations. So just implementing interfaces is not sufficient. (This + mode is mainly added to simplify the migration from JAXB 1.0 to Jakarta XML Binding, + and that's a part of the reason why things are done this + way.)

3.3. Evolving annotated classes

Here is the basic problem of evolution. You got your CoolApp v1, + which contains class Foo that has some Jakarta XML Binding annotations. Now you are + working towawrd CoolApp v2, and you want to make some changes to Foo. But + you want to do so in such a way that v1 and v2 can still talk to each + other.

The evolution compatibility has two different aspects. One is the + schema compatibility, which is about the relationship + between the v1 schema and the v2 schema. The other is about + runtime compatibility, which is about reading/writing + documents between two versions.

3.3.1. Runtime compatibility

There are two directions in the runtime compatibility. One is + whether v1 can still read what v2 write (forward + compatible), and the other is whether v2 can read what v1 + wrote (backward compatible).

3.3.2. "Semi-compatible"

Jakarta XML Binding can read XML documents that don't exactly match what's + expected. This is the default behavior of the Jakarta XML Binding unmarshaller, yet + you can change it to a more draconian behavior (TODO: pointer to the + unmarshalling section.)

When we are talking about evolving classes, it's often + convenient to leave it in the default behavior, as that would allow + Jakarta XML Binding to nicely ignore elements/attributes newly added in v2. So we + call it backward semi-compatible if v2 can read + what v1 wrote in this default unmarshalling mode, and similarly + forward semi-compatible if v1 can read what v2 + wrote in this default unmarshalling mode.

Technically, these are weaker than true backward/forward + compatibility (since you can't do a draconian error detection), yet in + practice it works just fine.

3.3.3. Adding/removing/changing non-annotated things

You can add, remove, or change any non-annotated fields, + methods, inner/nested types, constructors, interfaces. Those changes + are both backward and forward compatible, as they don't cause any + change to the XML representation.

Adding super class is backward compatible and forward + semi-compatible. Similarly, removing super class is forward compatible + and backward semi-compatible.

3.3.4. Adding/removing/changing properties

Adding new annotated fields or methods is backward compatible + and forward semi-compatible. Similarly, removing them is forward + compatible and backward semi-compatible.

Changing a property is bit more tricky.

  1. If you change the property name from X to Y, that would + be the equivalent of deleting X and adding Y, so it would be + backward and forward semi-compatible. What Jakarta XML Binding really cares + is properties' XML names and not Java names, so by using the + name parameter of XmlElement, XmlAttribute et al, you can change Java + property names without affecting XML, or change XML without + affecting Java properties. These are backward and forward + semi-compatible. See below:

  2. Example 50. Changing Java without affecting XML

    // BEFORE
    +public class Foo {
    +    public String abc;
    +}
    +// AFTER: Java name changed, but XML remains the same
    +public class Foo {
    +    @XmlElement(name="abc")
    +    public String def;
    +}

    Example 51. Changing XML without affecting Java

    // BEFORE
    +public class Foo {
    +    public String abc;
    +}
    +// AFTER: no Java change, but XML will look different
    +public class Foo {
    +    @XmlElement(name="def")
    +    public String abc;
    +}

  3. If you change a property type, generally speaking it + will be not compatible at all. For example, you can't change + from java.util.Calendar to int and + expect it to work. To make it a somewhat compatible change, + the old type and the new type has to be related. For example, + String can represent all int values, + so changing int to String would be a + backward compatible and forward semi-compatible change. XmlJavaTypeAdapter allows you to make + changes to Java without affecting XML (or vice versa.)

3.3.5. Changing class names

XmlType and XmlRootElement allows you to change a class name + without affecting XML.

Example 52. Changing class name without affecting XML (1)

// BEFORE
+@XmlRootElement
+public class Foo { ... }
+
+// AFTER: no XML change
+@XmlRootElement(name="foo")
+@XmlType(name="foo")
+public class Bar { ... }

Example 53. Changing class name without affecting XML (2)

// BEFORE
+public class Foo { ... }
+
+// AFTER: no XML change
+@XmlType(name="foo")
+public class Bar { ... }

3.3.6. Schema Compatibility

TODO.

3.4. XML layout and in-memory data layout

Your program sometimes needs to have a different in-memory data + structure from its XML representation. Jakarta XML Binding has a few different ways to + achieve this.

3.4.1. XmlJavaTypeAdapter

XmlJavaTypeAdapter allows you to de-couple the + in-memory representation and the XML representation by introducing an + intermediate representation. The basic model is as follows:

In-memory objects  <===>  Intermediate objects   <===>
+XML
+                  adapter                         XMLBinding

Your adapter code will be responsible for converting in-memory + objects to/from intermediate objects. Intermediate objects are then + bound to XML by following the standard Jakarta XML Binding rules. See XmlAdapter for a general description of how + adapters works.

Adapters extend from the XmlAdapter class and provide two methods + "unmarshal" and "marshal" that converts values in both directions, and + then the XmlJavaTypeAdapter annotation is used to tell + Jakarta XML Binding where and what adapters kick in.

(TODO: more info about XmlJavaTypeAdapter needed)

  1. adapting a class

  2. adapting a property

  3. adapting an external class

  4. adapting a collection and its effect

  5. adapting and using interfaces

3.4.2. Using XmlJavaTypeAdapter for element/attribute values

One of the common use cases of XmlJavaTypeAdapter is to map a "value object" to + a string in XML. The following example illustrates how to do this, by + using java.awt.Color as an example.

Example 54. Mapping Color to #RRGGBB

@XmlRootElement
+class Box {
+  @XmlJavaTypeAdapter(ColorAdapter.class)
+  @XmlElement
+  Color fill;
+}
+
+class ColorAdapter extends XmlAdapter<String,Color> {
+  public Color unmarshal(String s) {
+    return Color.decode(s);
+  }
+  public String marshal(Color c) {
+    return "#"+Integer.toHexString(c.getRGB());
+  }
+}

This maps to the following XML representation:

Example 55. Box instance

<box>
+  <fill>#112233</fill>
+</box>

Since XmlJavaTypeAdapter is on a field, this adapter + only kicks in for this particular field. If you have many + Color fields and would like them all to use the same + adapter, you can move the annotation to a package:

Example 56. package-info.java

@XmlJavaTypeAdapter(type=Color.class,value=ColorAdapter.class)
+package foo;

Example 57. Box.java

@XmlRootElement
+class Box {
+  @XmlElement Color fill;
+  @XmlElement Color border;
+}

This causes all the fields in the classes in the + foo package to use the same specified adapter.

Also see the DatatypeConverter class that defines a + series of basic conversion routines that you may find useful.

3.4.3. Pair property

Another useful technique is to define two properties, one for + Jakarta XML Binding and the other for your application. See the following + example:

Example 58. Pair property sample

@XmlRootElement
+class Person {
+  private int age;
+
+  // This public property is for users
+  @XmlTransient
+  public int getAge() {
+    return age;
+  }
+  public void setAge(int age) {
+    this.age = age;
+  }
+
+  // This property is for Jakarta XML Binding
+  @XmlAttribute(name="age")
+  private String getAge_() {
+    if(age==-1)  return "dead";
+    else         return String.valueOf(age);
+  }
+  private void setAge_(String v) throws NumberFormatException {
+    if(v.equals("dead"))   this.age=-1;
+    else                   this.age=Integer.parseInt(age);
+}

The main "age" property is public, but marked as XmlTransient, so it's exposed in your program, + but Jakarta XML Binding will not map this to XML. There's another private "age_" + property. Since this is marked with XmlAttribute, this is what Jakarta XML Binding is going to use + to map to the attribute. The getter and setter methods on this + property will handle the conversion between the in-memory + representation and the XML representation.

3.5. Mapping cyclic references to XML

Object models designed in Java often have cycles, which prevent + straight-forward conversion to XML by Jakarta XML Binding. In fact, when you try to + marshal an object tree that contains a cycle, the Jakarta XML Binding marshaller reports + an error, pointing out the objects that formed the cycle. This is because + Jakarta XML Binding by itself cannot figure out how to cut cycles into a tree.

Thus it is your responsibility to annotate classes and use other + means to "tell" Jakarta XML Binding how to handle a cycle. This chapter talks about + various techniques to do this.

3.5.1. Parent pointers

One of the very common forms of cycle is a parent pointer. The + following example illustrates a typical parent pointer, and how this + can be turned into "natural" XML:

Example 59. Classes with parent pointer

@XmlRootElement
+class Department {
+  @XmlAttribute
+  String name;
+  @XmlElement(name="employee")
+  List<Employee> employees;
+}
+
+class Employee {
+  @XmlTransient
+  Department department;  // parent pointer
+  @XmlAttribute
+  String name;
+
+  public void afterUnmarshal(Unmarshaller u, Object parent) {
+    this.department = (Department)parent;
+  }
+}

This will produce the following XML:

Example 60. XML view of department

<department name="accounting">
+  <employee name="Joe Chin" />
+  <employee name="Adam Smith" />
+  ...
+</department>

And reading this document back into Java objects will produce + the expected tree with all the proper parent pointers set up + correctly.

The first technique here is the use of XmlTransient on the parent pointer. This tells + Jakarta XML Binding that you don't need this parent pointer to be represented + explicitly in XML, because the fact that employee is + always contained inside department implies the + parent/child relationship. This causes the marshaller to produce the + expected XML. However, when you unmarshal it, since this field is not + bound, the Employee.department field will be left + null.

That's where the second technique comes in, which is the use of + the afterUnmarshal callback. This method is invoked by + the Jakarta XML Binding implementation on each instance when the unmarshalling of a + Employee object completes. Furthermore, the second + parameter to the method is the parent object, which in this case is a + Department object. So in this example, this sets up the + parent pointer correctly.

This callback can be also used to perform other + post-unmarshalling set up work.

3.5.2. Many-to-many relationship

TBD

3.5.3. @XmlID and + @XmlIDREF

When a reference to another object is annotated with XmlIDREF, its corresponding XML it will be + referenced by xs:IDREF, instead of containment. See below + for an example:

Example of @XmlID and + @XmlIDREF

@XmlRootElement
+class Root {
+  List<Foo> foos;
+  List<Bar> bars;
+}
+class Foo {
+  // you don't have to make it an attribute, but that's more common
+  @XmlAttribute @XmlIDREF Bar bar;
+}
+class Bar {
+  // you don't have to make it an attribute, but that's more common
+  @XmlAttribute @XmlID String id;
+}

Example 61. Schema for above

<xs:complexType name="foo">
+  <xs:sequence/>
+  <xs:attribute name="bar" type="xs:IDREF"/>
+  </xs:sequence>
+</xs:complexType>
+<xs:complexType name="bar">
+  <xs:sequence/>
+  <xs:attribute name="id" type="xs:ID"/>
+</xs:complexType>

Example 62. A sample instance

<root>
+  <foo bar="x"/>
+  <foo bar="y"/>
+  <bar id="x"/>
+  <bar id="y"/>
+</root>

There are a few things to consider when you do this. First, the + object to be referenced must have an ID that is unique within the + whole document. You'd also need to ensure that the referenced objects + are contained somewhere else (like in the + Root class in this case), or else Bar + objects will never be marshalled. This technique can be used to remove + the cyclic references, but it's only possible when your object model + has an easy cut point.

3.5.4. Use the CycleRecoverable interface

Starting 2.1 EA2, the Eclipse Implementation of JAXB exposes CycleRecoverable interface. Applications can + choose to implement this interface in some of its objects. When a + cyclic reference is detected during marshalling, and if the object + that formed a cycle implements this interface, then the method on this + interface is called to allow an application to nominate its + replacement to be written to XML. In this way, the application can + recover from a cycle gracefully.

This technique allows you to cope with a situation where you + cannot easily determine upfront as to where a cycle might happen. On + the other hand, this feature is a Eclipse Implementation of JAXB feature. Another downside of + this is that unless you nominate your replacement carefully, you can + make the marshalling output invalid with respect to the schema, and + thus you might hit another problem when you try to read it back + later.

4. Unmarshalling

4.1. @XmlRootElement and unmarshalling

Classes with XmlRootElement can be unmarshalled from XML elements + simply by invoking the unmarshal method that takes one parameter. This is + the simplest mode of unmarshalling.

Unmarshalling with @XmlRootElement

@XmlRootElement
+class Foo {
+  @XmlAttribute
+  String name;
+  @XmlElement
+  String content;
+}
+
+Unmarshaller u = ...;
+Foo foo = (Foo)u.unmarshal(new File("foo.xml"));

Example 63. foo.xml

<foo name="something">
+  <content>abc</content>
+</foo>

However, sometimes you may need to unmarshal an instance of a type + that does not have an XmlRootElement. For example, you might dynamically + find out at the runtime that a certain element has a certain type. For + example, the following document illustrates an XML instance where the + content of <someOtherTagName> element is represented by the + Foo class.

Example 64. foo2.xml

<someOtherTagName name="something">
+  <content>abc</content>
+</someOtherTagName>

To unmarshal this into a Foo class, use the version of + the unmarshal method that takes the 'expectedType' argument, + as follows:

Example 65. Unmarshalling into a known type

Unmarshaller u = ...;
+JAXBElement<Foo> root = u.unmarshal(new StreamSource(new File("foo.xml")),Foo.class);
+Foo foo = root.getValue();

To reduce the number of the unmarshal methods, this + two-argument version is not defined for every single-argument version. So + as in this example, you might need to perform additional wrapping of the + input parameter.

This instructs Jakarta XML Binding that the caller is expecting to unmarshal + Foo instance. Jakarta XML Binding returns a JAXBElement of + Foo, and this JAXBElement captures the tag name + of the root element.

4.2. Unmarshalling is not working! Help!

There are a few common causes for this problem. These causes often + exhibit similar symptoms:

  1. Instance documents are invalid

  2. JAXBContext is not created correctly.

4.2.1. Make sure your instance document is valid

First, use an independent schema validator to check if your + document is really valid with respect to the schema you compiled. When + the root element of a document is invalid, then the unmarshaller will + issue "unexpected element" errors. When a portion of a document is + invalid, Eclipse Implementation of JAXB skips that portion, so the end result is that the + unmarshalling returns normally, yet you notice that a part of the + content tree is missing. This is often the desirable behavior, but it + sometimes ends up masking a problem.

Also, try to install ValidationEventHandler on the + unmarshaller. When a portion of a document is skipped, the + unmarshaller notifies a ValidationEventHandler, so it + allows you to see what's going on.

Example 66. Installing ValidationEventHandler

Unmarshaller u = ...;
+// this implementation is a part of the API and convenient for trouble-shooting,
+// as it prints out errors to System.out
+u.setEventHandler(new jakarta.xml.bind.helpers.DefaultValidationEventHandler());
+
+u.unmarshal(new File("foo.xml"));

Also consider installing a Schema object to the + unmarshaller, so that the unmarshaller performs a schema validation + while unmarshalling. Earlier I suggested that you try an independent + schema validator, but for various reasons (not all tools are reliable, + you might have made an error and used a different schema/instance), + using validating unmarshalling is a better way to guarantee the + validity of your instance document being unmarshalled. Please follow + the JAXP + tutorial for more about how to construct a Schema + object from your schema.

If you are unmarshalling from XML parser APIs (such as DOM, SAX, + StAX), then also make sure that the parser/DOM is configured with the + namespace enabled.

4.2.2. Check if your JAXBContext is correct

(TODO: This also applies to the marshaller. Think about moving + it.)

The other possibility is that JAXBContext is not + set up correctly. JAXBContext "knows" a set of classes, + and if it doesn't know a class that it's supposed to know, then the + unmarshaller may fail to perform as you expected.

To verify that you created JAXBContext correctly, + call JAXBContext.toString(). It will output the list of + classes it knows. If a class is not in this list, the unmarshaller + will never return an instance of that class. Make you see all the + classes you expect to be returned from the unmarshaller in the list. + When dealing with a large schema that spans across a large number of + classes and packages, this is one possible cause of a problem.

If you noticed that a class is missing, explicitly specify that + to JAXBContext.newInstance. If you are binding classes + that are generated from XJC, then the easiest way to include all the + classes is to specify the generated ObjectFactory + class(es).

4.3. Element default values and unmarshalling

Because of the "strange" way that element default values in XML + Schema work, people often get confused about their behavior. This section + describes how this works.

When a class has an element property with the default value, and if + the document you are reading is missing the element, then the unmarshaller + does not fill the field with the default value. + Instead, the unmarshaller fills in the field when the element is present + but the content is missing. See below:

Example 67. XML instance 1

<foo />

Example 68. XML instance 2

<foo>
+  <a/>  <!-- or <a></a> -->
+</foo>

Example 69. XML instance 3

<foo>
+  <a>abc</a>
+</foo>

Example 70. Element defaults and XML

@XmlRootElement
+class Foo {
+  @XmlElement(defaultValue="value") public String a=null;
+}
+
+Foo foo = unmarshaller.unmarshal("instance1.xml");
+System.out.println(foo.a);   // null
+
+Foo foo = unmarshaller.unmarshal("instance2.xml");
+System.out.println(foo.a);   // "value". The default kicked in.
+
+Foo foo = unmarshaller.unmarshal("instance3.xml");
+System.out.println(foo.a);   // "abc". Read from the instance.

This is consistent with the XML Schema spec, where it essentially + states that the element defaults do not kick in when the element is + absent, so unfortunately we can't change this behavior.

Depending on your expectation, using a field initializer may achieve + what you are looking for. See below:

Example 71. Possible changes by using field initializer

@XmlRootElement
+class Foo {
+  @XmlElement public String a="value";
+}
+
+Foo foo = unmarshaller.unmarshal("instance1.xml");
+System.out.println(foo.a);   // "value", because Jakarta XML Binding didn't overwrite the value
+
+Foo foo = unmarshaller.unmarshal("instance2.xml");
+System.out.println(foo.a);   // "", because <a> element had 0-length string in it
+
+Foo foo = unmarshaller.unmarshal("instance3.xml");
+System.out.println(foo.a);   // "abc". Read from the instance.

Alternatively, attribute default values work in a way that agrees + with the typical expectation, so consider using that. Also, see Element default values and marshalling.

4.4. Dealing with large documents

Jakarta XML Binding API is designed to make it easy to read the whole XML document + into a single tree of Jakarta XML Binding objects. This is the typical use case, but in + some situations this is not desirable. Perhaps:

  1. A document is huge and therefore the whole may not fit the + memory.

  2. A document is a live stream of XML (such as XMPP) and therefore you + can't wait for the EOF.

  3. You only need to databind the portion of a document and + would like to process the rest in other XML APIs.

This section discusses several advanced techniques to deal with + these situations.

4.4.1. Processing a document by chunk

When a document is large, it's usually because there's + repetitive parts in it. Perhaps it's a purchase order with a large + list of line items, or perhaps it's an XML log file with large number + of log entries.

This kind of XML is suitable for chunk-processing; the main idea + is to use the StAX API, run a loop, and unmarshal individual chunks + separately. Your program acts on a single chunk, and then throws it + away. In this way, you'll be only keeping at most one chunk in memory, + which allows you to process large documents.

See the streaming-unmarshalling example and the + partial-unmarshalling example in the Eclipse Implementation of JAXB distribution for more + about how to do this. The streaming-unmarshalling example has an + advantage that it can handle chunks at arbitrary nest level, yet it + requires you to deal with the push model --- Jakarta XML Binding unmarshaller will + "push" new chunk to you and you'll need to process them right + there.

In contrast, the partial-unmarshalling example works in a pull + model (which usually makes the processing easier), but this approach + has some limitations in databinding portions other than the repeated + part.

4.4.2. Processing a live stream of XML

The techniques discussed above can be used to handle this case + as well, since they let you unmarshal chunks one by one. See the + xml-channel example in the Eclipse Implementation of JAXB distribution for more about how to + do this.

4.4.3. Creating virtual infosets

For further advanced cases, one could always run a streaming + infoset conversion outside Jakarta XML Binding API and basically curve just the + portion of the infoset you want to data-bind, and feed it as a + complete infoset into Jakarta XML Binding API. Jakarta XML Binding API accepts XML infoset in many + different forms (DOM, SAX, StAX), so there's a fair amount of + flexibility in choosing the right trade off between the development + effort in doing this and the runtime performance.

For more about this, refer to the respective XML infoset + API.

5. Marshalling

5.1. Changing prefixes

By default, a Jakarta XML Binding marshaller uses random namespace prefixes (such + as ns1, ns2, ...) when it needs to declare new + namespace URIs. While this is perfectly valid XML wrt the schema, for + human readability, you might want to change them to something that makes + more sense.

The Eclipse Implementation of JAXB defines NamespacePrefixMapper to allow you to do this. See + the namespace-prefix sample in the distribution for more + details.

5.2. Element default values and marshalling

Because of a "strange" way element default values in XML Schema + work, people often get confused about its behavior. This section describes + how this works.

When a class has an element property with the default value, and if + a value is null, then the marshaller will not produce the corresponding + element in XML:

Example 72. Element defaults and XML

@XmlRootElement
+class Foo {
+  @XmlElement(defaultValue="value") public String a=null;
+}
+
+marshaller.marshal(new Foo(),System.out);

Example 73. Marshalling output from above

<foo />

This is consistent with the XML Schema spec, where it essentially + states that the element defaults do not kick in when the element is + absent. Attribute default values do not have this problem, so if you can + change the schema, changing it to an attribute is usually a better idea. + Alternatively, depending on your expectation, setting the field to a + default value in Java may achieve what you are looking for.

Example 74. Possible changes

@XmlRootElement
+class Foo {
+  @XmlElement public String a="value";
+}
+@XmlRootElement
+class Bar {
+  @XmlAttribute public String a;
+}
+
+marshaller.marshal(new Foo(),System.out);
+marshaller.marshal(new Bar(),System.out);

Example 75. Marshalling output from above

<foo>
+    <a>value</a>
+</foo>
+
+<bar/>

Also, see Element default values and unmarshalling.

5.3. Different ways of marshalling

5.3.1. Different output media

The most basic notion of the marshalling is to take a Jakarta XML Binding-bound + object that has @XmlRootElement, and write it out as a + whole XML document. So perhaps you have a class like this:

Example 76. Jakarta XML Binding POJO

class Point {
+  @XmlElement
+  public int x;
+  @XmlElement
+  public int y;
+  Point(...) { ... }
+}

Then you can do:

Example 77. Plain marshalling

marshaller.marshal( new Point(1,3), System.out );
+marshaller.marshal( new Point(1,3), new File("out.xml") );

.. and so on. There're seven Marshaller.marshal + methods that takes different output media as the second parameter. If + you are writing to a file, a socket, or memory, then you should use + the version that takes OutputStream. Unless you change + the target encoding to something else (default is UTF-8), there's a + special marshaller codepath for OutputStream, which makes + it run really fast. You also don't have to use + BufferedOutputStream, since the Eclipse Implementation of JAXB does the adequate + buffering.

You can also write to Writer, but in this case + you'll be responsible for encoding characters, so in general you need + to be careful. If you want to marshal XML into an encoding other than + UTF-8, it's best to use the JAXB_ENCODING property and + then write to OutputStream, as it escapes characters to + things like &#x1824; correctly.

The next medium we support is W3C DOM. This is bit unintuitive, + but you'll do it like this:

Example 78. Marshal to DOM

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+dbf.setNamespaceAware(true);
+Document doc = dbf.newDocumentBuilder().newDocument();
+
+marshaller.marshal( new Point(1,3), doc );

And after the method invocation you get a complete DOM tree that + represents the marshalled document.

The other versions of the marshal methods are there to write XML + documents in terms of other XML APIs, such as SAX and StAX. The + version that takes ContentHandler is useful when you need + a custom formatting needs (like you want each attribute to be in new + line, etc), but otherwise they are not very interesting if you are + writing a whole document.

5.3.2. Marshalling into a subtree

Another common use of Jakarta XML Binding is where you are writing a bigger + document, and you use Jakarta XML Binding to generate part(s) of it. The Eclipse Implementation of XML Web Services is + the prime example. It produces a SOAP message, and Jakarta XML Binding is only used + to produce the body. When you are doing this, you first set + JAXB_FRAGMENT property on the marshaller. This changes + the behaviors of the marshaller so that it works better in this + situation.

If you are writing to an OutputStream or + Writer and generally sending it to someone else, you can + do something like this:

Example 79. Marshalling into a subtree

System.out.println("<envelope>");
+marshaller.marshal( object, System.out );
+System.out.println("</envelope>");

Like I mentioned, this is probably the fastest, even though + println isn't very pretty. JAXB_FRAGMENT + prevents the marshaller from producing an XML declaration, so the + above works just fine. The downside of this approach is that if the + ancestor elements declare the namespaces, Jakarta XML Binding won't be able to take + advantage of them.

You can also marshal an object as a subtree of an existing DOM + tree. To do this, you pass the Element object as the + second parameter, and the marshaller will marshal an object as a child + of this node.

StAX is also very convenient for doing this sort of things. You + can create XMLStreamWriter, write some stuff, and then + pass that to the marshaller. JAXB_FRAGMENT prevents the + marshaller from producing startDocument and + endDocument token. When doing this sub-tree marshaling to + DOM and StAX, Jakarta XML Binding can take advantage of available in-scope namespace + bindings.

Finally, you can marshal an object as a subtree into + ContentHandler, but it requires a fair amount of SAX + programming experience, and it goes beyond the scope of this + entry.

5.3.3. Marshalling a non-element

Another common use case is where you have an object that doesn't + have @XmlRootElement on it. Jakarta XML Binding allows you to marshal it + like this:

Example 80. Marshalling a non-element

marshaller.marshal( new JAXBElement(
+  new QName("","rootTag"),Point.class,new Point(...)));

This puts the <rootTag> element as the root element, + followed by the contents of the object, then </rootTag>. You can + actually use it with a class that has @XmlRootElement, + and that simply renames the root element name.

At the first glance the second Point.class + parameter may look redundant, but it's actually necessary to determine + if the marshaller will produce (infamous) + @xsi:type. In this example, both the class and the + instance are Point, so you won't see + @xsi:type. But if they are different, you'll see + it.

This can be also used to marshal a simple object, like + String or an integer.

Marshalling a non-element with + @xsi:type

marshaller.marshal( new JAXBElement(
+  new QName("","rootTag"),String.class,"foo bar"));

But unfortunately it cannot be + used to marshal objects like List or Map, as + they aren't handled as the first-class citizen in the Jakarta XML Binding + world.

5.3.4. Connecting to other XML APIs

Because of the Source and Result + support, Jakarta XML Binding objects can be easily marshalled into other XML APIs + that are not mentioned here. For example, dom4j has + DocumentResult that extends Result, so you + can do:

Example 81. Marshalling to dom4j

DocumentResult dr = new DocumentResult();
+marshaller.marshal( object, dr );
+o = dr.getDocument();

Similar mechanism is available for JDOM and XOM. This conversion + is much more efficient than first marshalling to + ByteArrayOutputStream and then read it back into these + DOMs. The same mechanism can be used to marshal to FastInfoset or send the + marshaled document to an XSLT engine (TransformerHandler.)

The other interesting connector is JAXBSource, + which wraps a marshaller and allows a Jakarta XML Binding object to be used as a + "source" of XML. Many XML APIs take Source as an input, + and now Jakarta XML Binding object can be passed to them directly.

For example, you can marshal a Jakarta XML Binding object and unmarshal it into + another JAXBContext like this:

Example 82. Loading into a different JAXBContext

JAXBContext context1 = ... ;
+JAXBContext context2 = ... ;
+
+context1.createUnmarshaller().unmarshal( new JAXBSource(context2,object) );

This amounts to looking at the same XML by using different + schema, and again this is much more efficient than going through + ByteArrayOutputStream.

5.4. Interaction between marshalling and DOM

Sometimes you may notice that Jakarta XML Binding is producing XML with seemingly + unnecessary namespace declarations. In this section, we'll discuss the + possible causes and how to resolve this.

5.4.1. Caused by DOM mapping

The #1 cause of extra namespace declarations is due to the DOM + mapping. This mainly happens because of a schema construct that forces + XJC to generate a property with DOM. This includes the use of wildcard + <xs:any/> (see more about this Mapping of <xs:any />), as well as xs:anyType + (which can also happen by omission, such as <xs:element + name="foo"/>, which is interpreted as <xs:element + name="foo" type="xs:anyType" />.

During unmarshalling, when a subtree of the input XML is + converted into XML, Jakarta XML Binding copies all the in-scope namespace bindings + active at that time to the root of the DOM element. So for example, + given the following Java class and XML, the DOM tree that the + child field will get will look like the following:

Example 83. Bean with wildcard

@XmlRootElement
+class Foo {
+  @XmlAnyElement
+  public Element child;
+}

Example 84. Instance with subtree matching wildcard

<foo xmlns:a="a" xmlns:b="b" xmlns:c="c">
+  <subtree xmlns:c="cc">
+    <data>a:xyz</data>
+  </subtree>
+</foo>

Example 85. DOM tree to be stored in Foo.child

<subtree xmlns:a="a" xmlns:b="b" xmlns:c="cc">
+    <data>a:xyz</data>
+  </subtree>

Note that the two namespace declarations are copied over, but + c is not because it's overridden. Also not that Jakarta XML Binding is + not touching the whitespace in document. This copying of namespace + declarations is necessary to preserve the infoset in the input + document. For example, if the <data> is a QName, its meaning + would change if Jakarta XML Binding unmarshaller doesn't copy it.

Now, imagine what happens when you marshal this back to XML. + Despite the fact that in this example neither b nor + c prefixes are in use, Jakarta XML Binding cannot delete them, because + it doesn't know if those attributes are significant to the application + or not. Therefore, this could end up producing XML with "extra + namespace declarations" like:

Example 86. DOM tree to be stored in Foo.child

<foo>
+  <subtree xmlns:a="a" xmlns:b="b" xmlns:c="cc">
+    <data>a:xyz</data>
+  </subtree>
+</foo>

Resolving this problem is not possible in the general case, but + sometimes one of the following strategy works:

  1. Sometimes schema author incorrectly assumes that + <xs:element name="foo"/> means + <xs:element name="foo" type="xs:string"/>, + because attribute declarations work somewhat like this. In + such a case, adding explicit type attribute + avoids the use of DOM, so things will work as expected.

  2. The wildcard processing mode " strict" + would force a typed binding, and thereby eliminate any DOM + mapping.

  3. You might be able to manulally go into the DOM tree and + remove unnecessary namespace declarations, if your application + knows what are necessary and what are not.

6. Schema Generation

6.1. Invoking schemagen programatically

Schemagen tools by default come in as CLI, ant task, and Maven + plugin. These interfaces allow you to invoke schemagen functionality from + your program.

6.1.1. At runtime

If the classes you'd like to generate schema from are already + available as java.lang.Class objects (meaning they are + already loaded and resolved in the current JVM), then the easiest way + to generate a schema is to use the Jakarta XML Binding API:

Example 87. Generate schema at runtime

File baseDir = new File(".");
+
+class MySchemaOutputResolver extends SchemaOutputResolver {
+    public Result createOutput( String namespaceUri, String suggestedFileName ) throws IOException {
+        return new StreamResult(new File(baseDir,suggestedFileName));
+    }
+}
+
+JAXBContext context = JAXBContext.newInstance(Foo.class, Bar.class, ...);
+context.generateSchema(new MySchemaOutputResolver());

6.1.2. CLI interface

The CLI + interface (public static int + com.sun.tools.jxc.SchemaGenerator.run(String[])) is the + easiest API to access. You can pass in all the schemagen command-line + arguments as a string array, and get the exit code as an int value. + Messages are sent to System.err and + System.out.

6.1.3. Ant interface

Ant task can be invoked very easily from a non-Ant program. The + schemagen ant task is defined in the + SchemaGenTask class,

6.1.4. Native Java API

The above two interfaces are built on top of externally + committed contracts, so they'll evolve only in a compatibile way. The + downside is that the amount of control you can exercise over them + would be limited.

So yet another approach to invoke schemagen is to use Eclipse Implementation of JAXB's + internal interfaces. But be warned that those interfaces are subject + to change in the future versions, despite our best effort to preserve + them. This is the API that the Eclipse Implementation of XML Web Services uses to generate schema + inside WSDL when they generate WSDL, so does some other web services + toolkits that work with the Eclipse Implementation of JAXB.

Most of those interfaces are defined and well-documented in + the com.sun.tools.xjc.api package. You can see how the schemagen + tools are eventually calling into this API at the + implementaion of SchemaGenerator class.

6.2. Generating Schema that you want

This section discusses how you can change the generated XML schema. + For changes that also affect the infoset (such as changing elements to + attributes, namespaces, etc.), refer to a different section "XML + layout and in-memory data layout".

6.2.1. Adding facets to datatypes

As of Eclipse Implementation of JAXB 4.0.0, currently no support for this, although there + has been several discussions in the users alias.

The Eclipse Implementation of JAXB project is currently lacking resources to attack this + problem, and therefore looking for volunteers to work on this project. + The basic idea would be to define enough annotations to cover the + basic constraint facets (such as length, enumerations, pattern, etc.) + The schema generator would have to be then extended to honor those + annotations and generate schemas accordingly.

Some users pointed out relevance of this to Jakarta Bean Validation. + If you are interested in picking up this task, let us know!

7. Deployment

7.1. Using Eclipse Implementation of JAXB with Maven

7.1.1. Maven coordinates for Eclipse Implementation of JAXB artifacts

  • jakarta.xml.bind:jakarta.xml.bind-api: API classes for Jakarta XML Binding. + Required to compile against Jakarta XML Binding.

  • org.glassfish.jaxb:jaxb-core: Contains sources required by XJC, + JXC and Runtime modules.

  • org.glassfish.jaxb:jaxb-runtime: Contains the main runtime used + for serialization and deserialization java objects to/from xml.

  • org.glassfish.jaxb:jaxb-xjc: Tool to generate Jakarta XML Binding java sources + from XML representation.

  • org.glassfish.jaxb:jaxb-jxc: Tool to generate XML schema from + Jakarta XML Binding java sources.

7.1.2. JAXB RI bundles

  • com.sun.xml.bind:jaxb-core: Contains sources required by XJC, + JXC and Runtime modules with dependencies.

  • com.sun.xml.bind:jaxb-impl: Eclipse Implementation of JAXB runtime jar.

  • com.sun.xml.bind:jaxb-xjc: Class generation tool jar.

  • com.sun.xml.bind:jaxb-jxc: Schema generation tool jar.

In contrast to org.glassfish.jaxb artifacts, these jars have all dependency classes included inside. +

7.1.3. Binary distribution

  • com.sun.xml.bind:jaxb-ri: Zip distribution containing tooling + scripts and all dependency jars in one archive.

7.1.4. Jakarta XML Binding API and Runtime

+ Minimum requirement to compile is jakarta.xml.bind-api.jar. If a client application is running on an environment + where Jakarta XML Binding + runtime is provided, jakarta.xml.bind-api.jar is all that is needed. +

Example 88. API only

+                <!-- API -->
+                <dependency>
+                    <groupId>jakarta.xml.bind</groupId>
+                    <artifactId>jakarta.xml.bind-api</artifactId>
+                    <version>4.0.0</version>
+                </dependency>


+ If client application needs to include the runtime, e.g. running standalone on Java SE + jaxb-impl should be also included. +

Example 89. API + Runtime

+                <!-- API -->
+                <dependency>
+                    <groupId>jakarta.xml.bind</groupId>
+                    <artifactId>jakarta.xml.bind-api</artifactId>
+                    <version>4.0.0</version>
+                </dependency>
+
+                <!-- Runtime -->
+                <dependency>
+                    <groupId>com.sun.xml.bind</groupId>
+                    <artifactId>jaxb-impl</artifactId>
+                    <version>4.0.0</version>
+                </dependency>


7.1.5. Using Eclipse Implementation of JAXB tools for java sources and XML schema generation

+ To generate Jakarta XML Binding classes from schema in Maven project, there are multiple community plugins + available: +

  • The most advanced and feature-full Maven plugin for XML Schema compilation: + highsource maven-jaxb2-plugin +

    Example 90. Using highsource maven-jaxb2-plugin

    +                <build>
    +                    <plugins>
    +                        <plugin>
    +                            <groupId>org.jvnet.jaxb2.maven2</groupId>
    +                            <artifactId>maven-jaxb2-plugin</artifactId>
    +                            <executions>
    +                                <execution>
    +                                    <goals>
    +                                        <goal>generate</goal>
    +                                    </goals>
    +                                </execution>
    +                            </executions>
    +                        </plugin>
    +                    </plugins>
    +                </build>


    + See the maven-jaxb2-plugin user guide for configuration details. +

  • A Maven plugin originating from MojoHaus which has been updated for Jakarta XML Binding 3+ by Evolved Binary: + MojoHaus jaxb-maven-plugin +

    Example 91. Using MojoHaus jaxb-maven-plugin

    +                <build>
    +                    <plugins>
    +                        <plugin>
    +                            <groupId>com.evolvedbinary.maven.mojohaus</groupId>
    +                            <artifactId>jaxb-maven-plugin</artifactId>
    +                            <executions>
    +                                <execution>
    +                                    <id>schemagen</id>
    +                                    <goals>
    +                                        <goal>schemagen</goal>
    +                                    </goals>
    +                                </execution>
    +                            </executions>
    +                        </plugin>
    +                    </plugins>
    +                </build>


    + See the MojoHaus jaxb-maven-plugin documentation for configuration details. +

  • A Maven plugin originating from java.net which has been updated for Jakarta XML Binding 3+ by Evolved Binary: + jvnet jaxb-maven-plugin +

    Example 92. Using jvnet jaxb-maven-plugin

    +                <build>
    +                    <plugins>
    +                        <plugin>
    +                            <groupId>com.evolvedbinary.maven.jvnet</groupId>
    +                            <artifactId>jaxb-maven-plugin</artifactId>
    +                            <executions>
    +                                <execution>
    +                                    <id>generate</id>
    +                                    <goals>
    +                                        <goal>generate</goal>
    +                                    </goals>
    +                                </execution>
    +                            </executions>
    +                        </plugin>
    +                    </plugins>
    +                </build>


    + See the jvnet jaxb-maven-plugin documentation for configuration details. +

+

+ Alternatively to community plugins, there are tooling artifacts jaxb-xjc and jaxb-jxc, + which can be used for + java from XML schema generation and vice versa. +

Example 93. Using Eclipse Implementation of JAXB tooling artifacts

+            <!-- Tooling dependencies -->
+            <dependency>
+                <groupId>com.sun.xml.bind</groupId>
+                <artifactId>jaxb-xjc</artifactId>
+                <version>4.0.0</version>
+            </dependency>
+            <dependency>
+                <groupId>com.sun.xml.bind</groupId>
+                <artifactId>jaxb-jxc</artifactId>
+                <version>4.0.0</version>
+            </dependency>
+
+            <!-- Invoke tooling API (Java 11) -->
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>exec-maven-plugin</artifactId>
+                    <!-- Generate java sources from schema -->
+                    <execution>
+                        <id>xjc</id>
+                        <goals>
+                            <goal>exec</goal>
+                        </goals>
+                        <configuration>
+                            <executable>java</executable>
+                            <arguments>
+                                <argument>--module-path</argument>
+                                <modulepath/>
+                                <argument>-m</argument>
+                                <argument>com.sun.tools.xjc</argument>
+                                <argument>-p</argument>
+                                <argument>com.example</argument>
+                                <argument>-d</argument>
+                                <argument>${project.build.directory}/generated-sources</argument>
+                                <argument>${project.build.directory}/classes/schema.xsd</argument>
+                            </arguments>
+                        </configuration>
+                    </execution>
+
+                    <!-- Generate XML Schema from sources -->
+                    <execution>
+                        <id>jxc</id>
+                        <goals>
+                            <goal>exec</goal>
+                        </goals>
+                        <configuration>
+                            <executable>java</executable>
+                            <arguments>
+                                <argument>--module-path</argument>
+                                <modulepath/>
+                                <argument>-m</argument>
+                                <argument>com.sun.tools.jxc</argument>
+                                <argument>-d</argument>
+                                <argument>${project.build.directory}/generated-sources</argument>
+                                <argument>${project.build.directory}/classes/com/example/Author.java</argument>
+                                <argument>${project.build.directory}/classes/com/example/Book.java</argument>
+                            </arguments>
+                            <longModulepath>false</longModulepath>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>


+ See also xml schema compiler usage.

schemagen and xjc command line scripts are available + only in the zip distribution.

7.2. Using Eclipse Implementation of JAXB on JPMS

Java SE 11 features JSR 376 Java Platform Module System. + Starting from version 2.3.2 Eclipse Implementation of JAXB supports JPMS and can be loaded and used from module path. + There are only a few things to be aware of. +

7.2.1. Eclipse Implementation of JAXB classes openness

+ Eclipse Implementation of JAXB does reflectively access private members of the class, so client application if loaded from module path + needs to "open" packages containing jaxb classes to Jakarta XML Binding. There are alternative Jakarta XML Binding implementations, + having different module names, Jakarta XML Binding requires pojo classes to be open only to API module. +

Example 94. JPMS module descriptor opening Jakarta XML Binding pojo classes to Jakarta XML Binding API

+//JPMS module descriptor
+module com.example.jaxbclasses {
+
+    //Jakarta XML Binding module name
+    requires jakarta.xml.bind;
+
+    //open pojo package to make accessing private members possible for Jakarta XML Binding.
+    opens com.example.jaxbclasses.pojos to jakarta.xml.bind;
+}


+ Jakarta XML Binding API will delegate openness to implementation module after resolving it with service discovery mechanism. +

+

Example 95. Eclipse Implementation of JAXB on JPMS Command line examples

+#Both client and Eclipse Implementation of JAXB on module path:
+$ java -m com.example.jaxbclasses/com.example.jaxb.Main --module-path jaxbclient.jar:jakarta.xml.bind-api.jar:jakarta.activation-api.jar:jaxb-core.jar:jaxb-impl.jar
+
+#Both client and Eclipse Implementation of JAXB on classpath:
+$ java com.example.jaxb.Main -cp jaxbclient.jar:jakarta.xml.bind-api.jar:jakarta.activation-api.jar:jaxb-core.jar:jaxb-impl.jar
+
+#Client on classpath, Eclipse Implementation of JAXB on module path:
+$ java com.example.jaxb.Main -cp jaxbclient.jar --module-path jakarta.xml.bind-api.jar:jakarta.activation-api.jar:jaxb-core.jar:jaxb-impl.jar --add-modules jakarta.xml.bind


+ Jakarta XML Binding API will delegate openness to implementation module after resolving it with service discovery mechanism. +

8. Other Miscellaneous Topics

8.1. Performance and thread-safety

The JAXBContext class is thread safe, but the Marshaller, + Unmarshaller, and Validator classes are not thread safe.

For example, suppose you have a multi-thread server application that + processes incoming XML documents by Jakarta XML Binding. In this case, for the best + performance you should have just one instance of JAXBContext in your whole + application like this:

Example 96. Singleton JAXBContext

class MyServlet extends HttpServlet {
+    static final JAXBContext context = initContext();
+
+    private static JAXBContext initContext() {
+        return JAXBContext.newInstance(Foo.class,Bar.class);
+    }
+}

And each time you need to unmarshal/marshal/validate a document. + Just create a new Unmarshaller/Marshaller/Validator from this context, + like this:

Example 97. Thread local Unmarshaller

    public void doGet( HttpServletRequest req, HttpServletResponse ) {
+        Unmarshaller u = context.createUnmarshaller();
+        u.unmarshal(...);
+    }

This is the simplest safe way to use the Eclipse Implementation of JAXB from multi-threaded + applications.

If you really care about the performance, and/or your application is + going to read a lot of small documents, then creating Unmarshaller could + be relatively an expensive operation. In that case, consider pooling + Unmarshaller objects. Different threads may reuse one Unmarshaller + instance, as long as you don't use one instance from two threads at the + same time.

8.2. Compiling DTD

The Eclipse Implementation of JAXB is shipped with an "experimental" DTD support, which + let's you compile XML DTDs. It is marked "experimental" not because the + feature is unstable nor unreliable, but rather because it's not a part of + the JAXB specification and therefore the level of commitment to + compatibility is lower.

Example 98. To compile a DTD, run the XJC binding compiler as + follows:

$ xjc.sh -dtd test.dtd

All the other command-line options of the XJC binding compiler can + be applied. Similarly, the XJC ant task supports DTD. The generated code + will be no different from what is generated from W3C XML Schema. You'll + use the same JAXB API to access the generated code, and it is portable in + the sense that it will run on any JAXB 2.0 implementation.

DTD long predates XML namespace, although people since then + developed various techniques to use XML namespaces in conjunction with + DTD. Because of this, XJC is currently unable to reverse-engineer the use + of XML namespace from DTD. If you compile DTDs that use those techniques, + you'd either manuallly modify the generated code, or you can try a tool + like Trang + that can convert DTD into XML Schema in ways that better preserves XML + namespaces.

8.2.1. Customizations

The customization syntax for DTD is roughly based on the + ver.0.21 working draft of the JAXB specification, which is available + at xml.coverpages.org. + The deviations from this document are:

  • The whitespace attribute of the + conversion element takes " + preserve", " replace", and " + collapse" instead of " preserve", " + normalize", and " collapse" as + specified in the document.

  • The interface customization just generates + marker interfaces with no method.

8.2.2. Compiling DTD from Maven

Example 99. The following POM snippest describes how to invoke XJC to + compile DTD from a Maven project:

<plugin>
+  <groupId>org.jvnet.jaxb2.maven2</groupId>
+  <artifactId>maven-jaxb2-plugin</artifactId>
+  <executions>
+    <execution>
+      <goals>
+        <goal>generate</goal>
+      </goals>
+      <configuration>
+        <!--  if you want to put DTD somewhere else
+        <schemaDirectory>src/main/jaxb</schemaDirectory>
+        -->
+        <extension>true</extension>
+        <schemaLanguage>DTD</schemaLanguage>
+        <schemaIncludes>
+          <schemaInclude>*.dtd</schemaInclude>
+        </schemaIncludes>
+        <bindingIncludes>
+          <bindingInclude>*.jaxb</bindingInclude>
+        </bindingIncludes>
+        <args>
+          <arg>-Xinject-listener-code</arg>
+        </args>
+      </configuration>
+    </execution>
+  </executions>
+  <dependencies>
+    <dependency>
+      <groupId>org.jvnet.jaxb2-commons</groupId>
+      <artifactId>property-listener-injector</artifactId>
+      <version>1.0</version>
+    </dependency>
+  </dependencies>
+</plugin>

Example 100. The dependencies section inside the plugin element can be + used to specify additional XJC plugins. If you'd like to use more + recent version of the Eclipse Implementation of JAXB, you can specify a dependency to XJC + here to do so, like this:

<dependency>
+  <groupId>com.sun.xml.bind</groupId>
+  <artifactId>jaxb-xjc</artifactId>
+  <version>4.0.0</version>
+</dependency>

8.3. Designing a client/server protocol in XML

Occasionally, people try to define a custom protocol that allows + multiple XML requests/responses to be sent over a single transport channel. + This section discusses the non-trivial interaction between XML and + sockets, and how you can design a protocol correctly.

XML1.0 requires a conforming parser to read the entire data till end + of the stream (because a parser needs to handle documents like + <root/><!-- post root comment -->). As a result, + a naive attempt to keep one OutputStream open and marshal + objects multiple times fails.

Example 101. One easy way to work around this limitation is to design your + protocol so that the data on the wire will look like the + following:

<conversation>
+  <!-- message 1 -->
+  <message>
+    ...
+  </message>
+
+  <!-- message 2 -->
+  <message>
+    ...
+  </message>
+
+  ...
+</conversation>

The <conversation> start tag is sent immediately after the + socket is opened. This works as a container to send multiple "messages", + and this is also an excellent opportunity to do the hand-shaking (e.g., + protocol-version='1.0' attribute.) Once the + <conversation> tag is written, multiple messages can be marshalled + as a tree into the channel, possibly with a large time lag in between. You + can use the Jakarta XML Binding marshaller to produce such message. When the sender wants + to disconnect the channel, it can do so by sending the + </conversation> end tag, followed by the socket + disconnection.

Of course, you can choose any tag names freely, and each message can + have different tag names.

The receiver would use the StAX API and use + XMLStreamReader to read this stream. You'd have to use this + to process the first <conversation> start tag. After that, every + time you call a Jakarta XML Binding unmarshaller, you'll get the next message.

For the concrete code, see the xml-channel example in + the Eclipse Implementation of JAXB distribution.

Tools

1. XJC

1.1. xjc Overview

Eclipse Implementation of JAXB also provides an Ant task to run the binding complier - + see the instructions for XJC Ant Task.

1.2. Launching xjc

The binding compiler can be launched using the appropriate + xjc shell script in the bin + directory for your platform.

  • Solaris/Linux

    % /path/to/jaxb/bin/xjc.sh -help
  • Windows

    > c:\path\to\jaxb\bin\xjc.bat -help

1.2.1. Execute the jaxb-xjc.jar JAR + File

If all else fails, you should be able to execute the + jaxb-xjc.jar file:

  • Solaris/Linux

    % java -jar $JAXB_HOME/lib/jaxb-xjc.jar -help
  • Windows

    > java -jar %JAXB_HOME%\lib\jaxb-xjc.jar -help

This is equivalent of running xjc.sh or + xjc.bat, and it allows you to set the JVM + parameters.

1.3. xjc Syntax

xjc [OPTION]... <schema file/URL/dir/jar> [-b <binding>...]

Usage: xjc [-options ...] <schema file/URL/dir/jar> ... [-b <bindinfo>] ...
+If dir is specified, all schema files in it will be compiled.
+If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.
+Options:
+  -nv                :  do not perform strict validation of the input schema(s)
+  -extension         :  allow vendor extensions - do not strictly follow the
+                        Compatibility Rules and App E.2 from the JAXB Spec
+  -b <file/dir>      :  specify external bindings files (each <file> must have its own -b)
+                        If a directory is given, **/*.xjb is searched
+  -d <dir>           :  generated files will go into this directory
+  -p <pkg>           :  specifies the target package
+  -httpproxy <proxy> :  set HTTP/HTTPS proxy. Format is [user[:password]@]proxyHost:proxyPort
+  -httpproxyfile <f> :  Works like -httpproxy but takes the argument in a file to protect password 
+  -classpath <arg>   :  specify where to find user class files
+  -catalog <file>    :  specify catalog files to resolve external entity references
+                        support TR9401, XCatalog, and OASIS XML Catalog format.
+  -readOnly          :  generated files will be in read-only mode
+  -npa               :  suppress generation of package level annotations (**/package-info.java)
+  -no-header         :  suppress generation of a file header with timestamp
+  -target (2.0|2.1)  :  behave like XJC 2.0 or 2.1 and generate code that doesn't use any 2.2 features.
+  -encoding <encoding> :  specify character encoding for generated source files
+  -enableIntrospection :  enable correct generation of Boolean getters/setters to enable Bean Introspection apis 
+  -disableXmlSecurity  :  disables XML security features when parsing XML documents 
+  -contentForWildcard  :  generates content property for types with multiple xs:any derived elements 
+  -xmlschema         :  treat input as W3C XML Schema (default)
+  -relaxng           :  treat input as RELAX NG (experimental,unsupported)
+  -relaxng-compact   :  treat input as RELAX NG compact syntax (experimental,unsupported)
+  -dtd               :  treat input as XML DTD (experimental,unsupported)
+  -wsdl              :  treat input as WSDL and compile schemas inside it (experimental,unsupported)
+  -verbose           :  be extra verbose
+  -quiet             :  suppress compiler output
+  -help              :  display this help message
+  -version           :  display version information
+  -fullversion       :  display full version information
+
+Extensions:
+  -Xinject-code      :  inject specified Java code fragments into the generated code
+  -Xlocator          :  enable source location support for generated code
+  -Xsync-methods     :  generate accessor methods with the 'synchronized' keyword
+  -mark-generated    :  mark the generated code as @javax.annotation.Generated
+  -episode           :  generate the episode file for separate compilation
+  -Xpropertyaccessors :  Use XmlAccessType PROPERTY instead of FIELD for generated classes

1.3.1. Summary of Command Line Options

-nv

By default, the XJC binding compiler performs + strict validation of the source schema before + processing it. Use this option to disable strict + schema validation. This does not mean that the binding + compiler will not perform any validation, it simply + means that it will perform less-strict + validation.

-extension

By default, the XJC binding compiler strictly + enforces the rules outlined in the Compatibility + chapter of the Jakarta XML Binding Specification. Appendix E.2 + defines a set of W3C XML Schema features that are not + completely supported by JAXB v1.0. In some cases, you + may be allowed to use them in the "-extension" mode + enabled by this switch. In the default (strict) mode, + you are also limited to using only the binding + customizations defined in the specification. By using + the "-extension" switch, you will be allowed to use + the Overview.

-b + <file>

Specify one or more external binding files to + process. (Each binding file must have it's own -b switch.) The syntax of the external + binding files is extremely flexible. You may have a + single binding file that contains customizations for + multiple schemas or you can break the customizations + into multiple bindings files:

xjc schema1.xsd schema2.xsd schema3.xsd -b bindings123.xjb
+xjc schema1.xsd schema2.xsd schema3.xsd -b bindings1.xjb -b bindings2.xjb -b bindings3.xjb

In addition, + the ordering of the schema files and binding files on + the command line does not matter.

-d + <dir>

By default, the XJC binding compiler will + generate the Java content classes in the current + directory. Use this option to specify an alternate + output directory. The output directory must already + exist, the XJC binding compiler will not create it for + you.

-encoding + <encoding>

Set the encoding name for generated sources, + such as EUC-JP or UTF-8. If -encoding is + not specified, the platform default encoding is + used.

-p + <pkg>

Specifying a target package via this + command-line option overrides any binding + customization for package name and the default package + name algorithm defined in the specification.

-httpproxy + <proxy>

Specify the HTTP/HTTPS proxy. The format is + [user[:password]@]proxyHost[:proxyPort]. The old -host and -port are still + supported by the RI for backwards compatibility, but + they have been deprecated.

-httpproxyfile + <f>

Same as the -httpproxy + <proxy> option, but it takes the + <proxy> parameter in a file, so that you can + protect the password (passing a password in the + argument list is not safe.)

-classpath + <arg>

Specify where to find client application class + files used by the <jxb:javaType> + and <xjc:superClass> + customizations.

-catalog + <file>

Specify catalog files to resolve external entity + references. Supports TR9401, XCatalog, and OASIS XML + Catalog format. Please read the XML Entity and URI + Resolvers document or the + catalog-resolver sample + application.

-readOnly

By default, the XJC binding compiler does not + write-protect the Java source files it generates. Use + this option to force the XJC binding compiler to mark + the generated Java sources read-only.

-npa

Supress the generation of package level + annotations into **/package-info.java. Using this + switch causes the generated code to internalize those + annotations into the other generated classes.

-no-header

Supress the generation of a file header comment + that includes some note and timestamp. Using this + makes the generated code more + diff-friendly.

-target (2.0|2.1)

Avoid generating code that relies on any JAXB + 2.1|2.2 features. This will allow the generated code to + run with JAXB 2.0 runtime (such as JavaSE 6.)

-xmlschema

treat input schemas as W3C XML Schema (default). + If you do not specify this switch, your input schemas + will be treated as W3C XML Schema.

-relaxng

Treat input schemas as RELAX NG (experimental, + unsupported). Support for RELAX NG schemas is provided + as a Overview.

-relaxng-compact

Treat input schemas as RELAX NG compact + syntax(experimental, unsupported). Support for RELAX + NG schemas is provided as a Overview.

-dtd

Treat input schemas as XML DTD (experimental, + unsupported). Support for RELAX NG schemas is provided + as a Overview.

-wsdl

Treat input as WSDL and compile schemas inside + it (experimental,unsupported).

-quiet

Suppress compiler output, such as progress + information and warnings..

-verbose

Be extra verbose, such as printing informational + messages or displaying stack traces upon some + errors..

-help

Display a brief summary of the compiler + switches.

-version

Display the compiler version information.

-fullversion

Display the compiler full version information.

<schema + file/URL/dir>

Specify one or more schema files to compile. If + you specify a directory, then xjc will scan it for all + schema files and compile them.

-Xlocator

This feature causes the generated code to expose + SAX Locator information about the source XML in the + Java bean instances after unmarshalling.

-Xsync-methods

This feature causes all of the generated method + signatures to include the synchronized keyword.

-mark-generated

This feature causes all of the generated code to + have + @Generated annotation.

-episode + <FILE>

Generate an episode file from this compilation, + so that other schemas that rely on this schema can be + compiled later and rely on classes that are generated + from this compilation. The generated episode file is + really just a Jakarta XML Binding customization file (but with vendor + extensions.)

-Xinject-code
-Xpropertyaccessors>

Annotate the @XmlAccessorType + of generated classes with XmlAccessType PROPERTY + instead of FIELD

1.3.2. Summary of Deprecated and Removed Command Line + Options

-host & + -port

These options have been deprecated and replaced + with the -httpproxy + option. For backwards compatibility, we will continue + to support these options, but they will no longer be + documented and may be removed from future + releases.

-use-runtime

Since the Jakarta XML Binding specification has defined a + portable runtime, it is no longer necessary for the + Eclipse Implementation of JAXB to generate **/impl/runtime packages. + Therefore, this switch is obsolete and has been + removed.

1.4. Compiler Restrictions

In general, it is safest to compile all related schemas as a + single unit with the same binding compiler switches.

Please keep the following list of restrictions in mind when + running xjc. Most of these issues only apply when compiling multiple + schemas with multiple invocations of xjc.

  • To compile multiple schemas at the same time, keep the + following precedence rules for the target Java package name in + mind:

    1. The -p command line option + takes the highest precedence.

    2. <jaxb:package> + customization

    3. If targetNamespace is declared, + apply targetNamespace -> Java + package name algorithm defined in the + specification.

    4. If no targetNamespace is + declared, use a hardcoded package named + "generated".

  • It is not legal to have more than one < + jaxb:schemaBindings> per namespace, so it is + impossible to have two schemas in the same target namespace + compiled into different Java packages.

  • All schemas being compiled into the same Java package + must be submitted to the XJC binding compiler at the same time + - they cannot be compiled independently and work as + expected.

  • Element substitution groups spread across multiple + schema files must be compiled at the same time.

1.5. Generated Resource Files

XJC produces a set of packages containing Java source files and + also jaxb.properties files, depending on the binding + options you used for compilation. When generated, + jaxb.properties files must be kept with the compiled + source code and made available on the runtime classpath of your client + applications:

2. XJC Ant Task

2.1. xjc Task Overview

The jaxb-xjc.jar file contains the + XJCTask.class file, which allows the XJC binding + compiler to be invoked from the Ant build tool. To + use XJCTask, include the following statement in + your build.xml file:

<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath>
+        <fileset dir="path/to/jaxb/lib" includes="*.jar"/>
+    </classpath>
+</taskdef>

This maps XJCTask to an Ant task named + xjc. For detailed examples of using this task, + refer to any of the build.xml files used by the Sample Apps.

2.2. xjc Task Attributes

2.2.1. Environment Variables

  • ANT_OPTS + - command-line arguments that should be passed to the JVM. + For example, you can define system properties or set the + maximum Java heap size here.

2.2.2. Parameter Attributes

xjc supports the following parameter + attributes.

AttributeDescriptionRequired

schema

A schema file to be compiled. A file + name (can be relative to the build script base + directory), or an URL.

This or nested < + schema> elements are + required.

binding

An external binding file that will be + applied to the schema file.

No

package

If specified, generated code will be + placed under this Java package. This option is + equivalent to the "-p" command-line + switch.

No

destdir

Generated code will be written under + this directory. If you specify + destdir="abc/def" and + package="org.acme", then files + are generated to + abc/def/org/acme.

Yes

disableXmlSecurity

Disable XML security features when parsing XML documents. + false by default.

No

encoding

Set the encoding name for generated + sources, such as EUC-JP or UTF-8. If it is not + specified, the platform default encoding is + used.

No

readonly

Generate Java source files in the + read-only mode if true is + specified. false by + default.

No

header

Generate a header in each generated + file indicating that this file is generated by such + and such version of Eclipse Implementation of JAXB when. + true by default.

No

extension

If set to true, the XJC + binding compiler will run in the extension mode. + Otherwise, it will run in the strict conformance + mode. Equivalent of the " + -extension" command line switch. + The default is + false.

No

catalog

Specify the catalog file to resolve + external entity references. Support TR9401, + XCatalog, and OASIS XML Catalog format. See the + catalog-resolver sample for details.

No

removeOldOutput

Used in pair with nested + <produces> elements. When + this attribute is specified as " yes", + the files pointed to by the + <produces> elements will be + all deleted before the XJC binding compiler + recompiles the source files. See the up-to-date + check section for details.

No

target

Specifies the runtime environment in + which the generated code is supposed to run. Expects 2.0 or 2.1 values. + This allows more up-to-date versions of XJC to be used for + developing applications that run on earlier JAXB + versions.

No, defaults to "2.2"

language

Specifies the schema language to + compile. Supported values are "WSDL", "XMLSCHEMA", + and "WSDL." Case insensitive.

No, defaults to + "XMLSCHEMA"

2.2.3. Nested Elements

xjc supports the following nested element + parameters.

2.2.3.1. schema

To compile more than one schema at the same time, use a + nested <schema> element, which has + the same syntax as + <fileset> .

2.2.3.2. binding

To specify more than one external binding file at the + same time, use a nested <binding> + element, which has the same syntax as + <fileset> .

2.2.3.3. classpath

To specify locations of the user-defined classes + necessary during the compilation (such as an user-defined type + that is used through a <javaType> + customization), use nested + <classpath> elements. For the syntax, + see "path-like + structure" .

2.2.3.4. arg

Additional command line arguments passed to the XJC. For + details about the syntax, see the + relevant section in the Ant manual. This nested element + can be used to specify various options not natively supported + in the xjc Ant task. For example, currently there + is no native support for the following xjc + command-line options:

  • -nv

  • -use-runtime

  • -schema

  • -dtd

  • -relaxng

  • -Xlocator

  • -Xsync-methods

To use any of these features from the + <xjc> Ant task, you must specify the + appropriate nested < arg> elements.

2.2.3.5. depends

Files specified with this nested element will be taken + into account when the XJC task does the up-to-date check. See + the up-to-date check section for details. For the syntax, see + + <fileset> .

2.2.3.6. produces

Files specified with this nested element will be taken + into account when the XJC task does the up-to-date check. See + the up-to-date check section for details. For the syntax, see + + <fileset> .

2.2.3.7. xmlcatalog

The xmlcatalog + element is used to resolve entities when parsing schema + documents.

2.3. Generated Resource Files

Please see the Generated Resource Files for more detail.

2.4. Up-to-date Check

By default, the XJC binding compiler always compiles the inputs. + However, with a little additional setting, it can compare timestamps + of the input files and output files and skip compilation if the files + are up-to-date.

Ideally, the program should be able to find out all the inputs + and outputs and compare their timestamps, but this is difficult and + time-consuming. So you have to tell the task input files and output + files manually by using nested <depends> and + <produces> elements. Basically, the XJC + binding compiler compares the timestamps specified by the + <depends> elements against those of the + <produces> set. If any one of the "depends" + file has a more recent timestamp than some of the files in the + "produces" set, it will compile the inputs. Otherwise it will skip the + compilation.

This will allow you to say, for example "if any of the + .xsd files in this directory are newer than the + .java files in that directory, recompile the + schema".

Files specified as the schema files and binding files are + automatically added to the "depends" set as well, but if those schemas + are including/importing other schemas, you have to use a nested + <depends> elements. No files are added to the + <produces> set, so you have to add all of + them manually.

A change in a schema or an external binding file often results + in a Java file that stops being generated. To avoid such an "orphan" + file, it is often desirable to isolate all the generated code into a + particular package and delete it before compiling a schema. This can + be done by using the removeOldOutput attribute. + This option allows you to remove all the files that match the + "produces" filesets before a compilation. Be careful when + you use this option so that you don't delete important + files.

2.5. Schema Language Support

This release of the Eclipse Implementation of JAXB includes experimental support for + RELAX NG, DTD, and WSDL. To compile anything other than W3C XML Schema + from the xjc Ant task, you must use the nested < + arg> element to specify the appropriate command line + switch, such as -dtd, -relaxng, or -wsdl. Otherwise, your input schemas will be treated as + W3C XML Schema and the binding compiler will fail.

2.6. xjc Examples

Compile myschema.xsd and place the generated + files under src/org/acme/foo:

<xjc schema="src/myschema.xsd" destdir="src" package="org.acme.foo"/>

Compile all XML Schema files in the src + directory and place the generated files under the appropriate packages + in the src directory:

<xjc destdir="src">
+    <schema dir="src" includes="*.xsd"/>
+</xjc>

Compile all XML Schema files in the src + directory together with binding files in the same directory and places + the generated files under the appropriate packages in the + src directory. This example assumes that binding + files contain package customizations. This example doesn't search + subdirectories of the src directory to look for + schema files.

<xjc destdir="src">
+    <schema dir="src" includes="*.xsd"/>
+    <binding dir="src" includes="*.xjb"/>
+</xjc>

Compile abc.xsd with an up-to-date check. + Compilation only happens when abc.xsd is newer than + any of the files in the src/org/acme/foo directory + (and its impl subdirectory). Files in these two + directories will be wiped away before a compilation, so + don't add your own code in those directories. + Note that the additional mkdir task is necessary + because Ant's fileset requires the directory specified by the + dir attribute to exist.

<mkdir dir="src/org/acme/foo"/>
+<xjc destdir="src" schema="abc.xsd" removeOldOutput="yes"
+     package="org.acme.foo">
+    <produces dir="src/org/acme/foo" includes="* impl/*"/>
+</xjc>

More complicated example of up-to-date check. In this example, + we assume that you have a large set of schema documents that reference + each other, with DTDs that describe the schema documents. An explicit + <depends> is necessary so that when you update one of the DTDs, + XJC will recompile your schema. But <depends> don't have to + re-specify all the schema files, because you've already done that via + <schema>.

<mkdir dir="src/org/acme/foo"/>
+<xjc destdir="src" removeOldOutput="yes"
+     package="org.acme.foo">
+    <schema dir="schema" includes="*.xsd"/>
+    <depends dir="schema" includes="*.dtd"/>
+    <produces dir="build/generated-src/org/acme/foo"
+              includes="**/*"/>
+</xjc>

Compile all XML Schema files in the src + directory and subdirectories, excluding files named + debug.xsd, and place the generated files under the + appropriate packages in the src directory. This + example also specifies the -nv option, which disables + the strict schema correctness checking:

<xjc destdir="src">
+    <schema dir="src" includes="**/*.xsd"
+            excludes="**/debug.xsd"/>
+    <arg value="-nv"/>
+</xjc>

If you depend on a proxy server to resolve the location of + imported or included schemas (as you might if you're behind a + firewall), you need to make the hostname and port number accessible to + the JVM hosting ant. Do this by setting the + environment variable ANT_OPTS to a string + containing the appropriate java options. For + example, from DOS:

> set ANT_OPTS=-Dhttp.proxyHost=webcache.east
+> set ANT_OPTS=%ANT_OPTS% -Dhttp.proxyPort=8080
+> ant

3. SchemaGen

3.1. schemagen Overview

The current schema generator can process either Java source + files or class files.

We also provide an Ant task to run the schema generator - see + the instructions for SchemaGen Ant Task.

3.2. Launching schemagen

The schema generator can be launched using the appropriate + schemagen shell script in the + bin directory for your platform.

If your java sources/classes reference other classes, they must + be accessable on your system CLASSPATH environment variable, or they + need to be given to the tool by using the -classpath/ + -cp options. Otherwise you will see errors when + generating your schema.

  • Solaris/Linux

    % path/to/jaxb/bin/schemagen.sh Foo.java Bar.java ...
    +Note: Writing schema1.xsd
  • Windows

    > path\to\jaxb\bin\schemagen.bat Foo.java Bar.java ...
    +Note: Writing schema1.xsd

3.3. schemagen Syntax

schemagen [OPTION]... <java files>

Usage: schemagen [-options ...] <java files> 
+
+Options: 
+    -d <path>             : specify where to place processor and javac generated class files
+    -cp <path>            : specify where to find user specified files
+    -classpath <path>     : specify where to find user specified files
+    -encoding <encoding>  : specify encoding to be used for annotation processing/javac invocation
+    -episode <file>       : generate episode file for separate compilation
+    -disableXmlSecurity   : disables XML security features when parsing XML documents
+    -version              : display version information
+    -fullversion          : display full version information
+    -help                 : display this usage message

3.3.1. Summary of Command Line Options

-d + <dir>

By default, the schema generator will + generate the content in the current + directory. Use this option to specify an alternate + output directory. The output directory must already + exist, the schema generator will not create it for + you.

-encoding + <encoding>

Set the encoding name for generated sources, + such as EUC-JP or UTF-8. If -encoding is + not specified, the platform default encoding is + used.

-classpath + <arg>

Specify where to find client application class + files.

-episode

Generates the "episode file", which is really + just a Jakarta XML Binding customization file (but with vendor + extensions). When people develop additional schemas that + depend on what this schemagen invocation produces, they can use this + episode file to have their generated code refer to + your classes.

-help

Display a brief summary of the generator + switches.

-version

Display the compiler version information.

-fullversion

Display the compiler full version information.

3.4. Generated Resource Files

The current schema generator simply creates a schema file for + each namespace referenced in your Java classes. There is no way to + control the name of the generated schema files at this time. Use SchemaGen Ant Task for + that purpose.

4. SchemaGen Ant Task

4.1. schemagen Task Overview

The jaxb-jxc.jar file contains the + SchemaGenTask.class file, which allows the schema + generator to be invoked from the Ant build tool. To + use SchemaGenTask, include the following statement + in your build.xml file:

<taskdef name="schemagen"
+         classname="com.sun.tools.jxc.SchemaGenTask">
+    <classpath>
+        <fileset dir="path/to/jaxb/lib" includes="*.jar"/>
+    </classpath>
+</taskdef>

This maps SchemaGenTask to an Ant task named + schemagen. For detailed examples of using this + task, refer to the build.xml files used by the java to + schema Sample Apps.

4.2. schemagen Task Attributes

4.2.1. Environment Variables

  • ANT_OPTS + - command-line arguments that should be passed to the JVM. + For example, you can define system properties or set the + maximum Java heap size here.

4.2.2. Parameter Attributes

schemagen supports most of the attributes + defined by the + javac task, plus the following parameter attributes.

AttributeDescriptionRequired

destdir

Base directory to place the generated + schema files

No

classpath

Works just like the nested + <classpath> element

No

episode

If specified, generate an episode file + in the specified name. For more about the episode + file, see -episode.

No

4.2.3. Nested Elements

xjc supports all the nested elements + defined by the + javac task, the following nested element parameters.

4.2.3.1. schema

Control the file name of the generated schema. This + element takes a mandatory namespace attribute and + a mandaotry file attribute. When this element is + present, the schema document generated for the specified + namespace will be placed in the specified file name.

The file name is interpreted as relative to the destdir + attribute. In the absence of the destdir attribute, file names + are relative to the project base directory. This element can + be specified multiple times.

4.2.3.2. classpath

A path-like + structure that represents the classpath. If your Java + sources/classes depend on other libraries, they need to be + available in the classpath.

4.3. schemagen Examples

Generate schema files from source files in the src + dir and place them in the build/schemas directory.

<schemagen srcdir="src" destdir="build/schemas">

Compile a portion of the source tree.

<schemagen destdir="build/schemas">
+    <src path="src"/>
+    <exclude name="Main.java"/>
+</schemagen>

Set schema file names.

<schemagen srcdir="src" destdir="build/schemas">
+    <schema namespace="http://myschema.acme.org/common"
+            file="myschema-common.xsd"/>
+    <schema namespace="http://myschema.acme.org/onion"
+            file="myschema-onion.xsd"/>
+</schemagen>

5. 3rd Party Tools

5.1. Maven JAXB Plugin

If you are using Maven, JAXB + jars are available in + the maven central repository.

5.2. XJC Plugins

Various people in the community have developed plugins for + XJC that you can use today. These plugins allow you to + enhance/alter the code generation of XJC in many different + ways.

5.3. RDBMS Persistence

Lexi has developed the + HyperJAXB3 + project for RDBMS persistence support for the Eclipse Implementation of JAXB.

Eclipse Implementation of JAXB Extensions

1. Overview

This page contains information about vendor-specific features + provided by the Eclipse Implementation of JAXB.

Runtime Properties

This document describes Eclipse Implementation of JAXB specific properties that + affect the way that the Jakarta XML Binding runtime library behaves.

XJC Customizations

This document describes additional binding + customizations that can be used to control the generated + source code.

DTD

This document describes the Eclipse Implementation of JAXB's experimental + support for W3C XML Schema features not currently described in + the Jakarta XML Binding Specification as well as support for other schema + languages (RELAX NG and DTD).

2. Runtime Properties

2.1. Marshaller Properties

The Eclipse Implementation of JAXB provides additional Marshaller properties that are + not defined by the Jakarta XML Binding specification. These properties allow you to + better control the marshalling process, but they only work with the + Eclipse Implementation of JAXB; they may not work with other Jakarta XML Binding providers.

2.1.2. Namespace Prefix Mapping

Property + name:org.glassfish.jaxb.namespacePrefixMapper
Type:org.glassfish.jaxb.runtime.marshaller.NamespacePrefixMapper
Default + value:

null

The Eclipse Implementation of JAXB provides a mechanism for users to control + declarations of namespace URIs and what prefixes they will be + bound to. This is the general procedure:

  1. The application developer provides an implementation + of + org.glassfish.jaxb.runtime.marshaller.NamespacePrefixMapper.

  2. This class is then set on the marshaller via the RI + specific property + org.glassfish.jaxb.namespacePrefixMapper.

  3. Each time the marshaller sees a URI, it performs a + callback on the mapper: "What prefix do you want for this + namespace URI?"

  4. If the mapper returns something, the marshaller will + try to use it.

The + org.glassfish.jaxb.runtime.marshaller.NamespacePrefixMapper + class has the following method that you need to implement:

/**
+ * Implemented by the user application to determine URI -> prefix
+ * mapping.
+ * 
+ * This is considered as an interface, though it's implemented
+ * as an abstract class to make it easy to add new methods in
+ * a future. 
+ * 
+ * @author
+ *     Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
+ */
+public abstract class NamespacePrefixMapper {
+
+    private static final String[] EMPTY_STRING = new String[0];
+
+    /**
+     * Returns a preferred prefix for the given namespace URI.
+     * 
+     * This method is intended to be overrided by a derived class.
+     *
+     * <p>
+     * As noted in the return value portion of the javadoc, there
+     * are several cases where the preference cannot be honored.
+     * Specifically, as of JAXB RI 2.0 and onward:
+     *
+     * <ol>
+     * <li>
+     * If the prefix returned is already in use as one of the in-scope
+     * namespace bindings. This is partly necessary for correctness
+     * (so that we don't unexpectedly change the meaning of QNames
+     * bound to {@link String}), partly to simplify the marshaller.
+     * <li>
+     * If the prefix returned is "" yet the current {@link JAXBContext}
+     * includes classes that use the empty namespace URI. This allows
+     * the JAXB RI to reserve the "" prefix for the empty namespace URI,
+     * which is the only possible prefix for the URI.
+     * This restriction is also to simplify the marshaller.
+     * </ol>
+     *
+     * @param namespaceUri
+     *      The namespace URI for which the prefix needs to be found.
+     *      Never be null. "" is used to denote the default namespace.
+     * @param suggestion
+     *      When the content tree has a suggestion for the prefix
+     *      to the given namespaceUri, that suggestion is passed as a
+     *      parameter. Typicall this value comes from the QName.getPrefix
+     *      to show the preference of the content tree. This parameter
+     *      may be null, and this parameter may represent an already
+     *      occupied prefix. 
+     * @param requirePrefix
+     *      If this method is expected to return non-empty prefix.
+     *      When this flag is true, it means that the given namespace URI
+     *      cannot be set as the default namespace.
+     * 
+     * @return
+     *      null if there's no prefered prefix for the namespace URI.
+     *      In this case, the system will generate a prefix for you.
+     * 
+     *      Otherwise the system will try to use the returned prefix,
+     *      but generally there's no guarantee if the prefix will be
+     *      actually used or not.
+     * 
+     *      return "" to map this namespace URI to the default namespace.
+     *      Again, there's no guarantee that this preference will be
+     *      honored.
+     * 
+     *      If this method returns "" when requirePrefix=true, the return
+     *      value will be ignored and the system will generate one.
+     * 
+     * @since JAXB 1.0.1
+     */
+    public abstract String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix);
+
+    /**
+     * Returns a list of namespace URIs that should be declared
+     * at the root element.
+     *
+     * <p>
+     * By default, the JAXB RI 1.0.x produces namespace declarations only when
+     * they are necessary, only at where they are used. Because of this
+     * lack of look-ahead, sometimes the marshaller produces a lot of
+     * namespace declarations that look redundant to human eyes. For example,
+     * <pre><xmp>
+     * <?xml version="1.0"?>
+     * <root>
+     *   <ns1:child xmlns:ns1="urn:foo"> ... </ns1:child>
+     *   <ns2:child xmlns:ns2="urn:foo"> ... </ns2:child>
+     *   <ns3:child xmlns:ns3="urn:foo"> ... </ns3:child>
+     *   ...
+     * </root>
+     * </xmp></pre>
+     *
+     * <p>
+     * The JAXB RI 2.x mostly doesn't exhibit this behavior any more,
+     * as it declares all statically known namespace URIs (those URIs
+     * that are used as element/attribute names in JAXB annotations),
+     * but it may still declare additional namespaces in the middle of
+     * a document, for example when (i) a QName as an attribute/element value
+     * requires a new namespace URI, or (ii) DOM nodes as a portion of an object
+     * tree requires a new namespace URI.
+     *
+     * <p>
+     * If you know in advance that you are going to use a certain set of
+     * namespace URIs, you can override this method and have the marshaller
+     * declare those namespace URIs at the root element.
+     *
+     * <p>
+     * For example, by returning <code>new String[]{"urn:foo"}</code>,
+     * the marshaller will produce:
+     * <pre><xmp>
+     * <?xml version="1.0"?>
+     * <root xmlns:ns1="urn:foo">
+     *   <ns1:child> ... </ns1:child>
+     *   <ns1:child> ... </ns1:child>
+     *   <ns1:child> ... </ns1:child>
+     *   ...
+     * </root>
+     * </xmp></pre>
+     * <p>
+     * To control prefixes assigned to those namespace URIs, use the
+     * {@link #getPreferredPrefix(String, String, boolean)} method. 
+     * 
+     * @return
+     *      A list of namespace URIs as an array of {@link String}s.
+     *      This method can return a length-zero array but not null.
+     *      None of the array component can be null. To represent
+     *      the empty namespace, use the empty string <code>""</code>.
+     * 
+     * @since
+     *      JAXB RI 1.0.2 
+     */
+    public String[] getPreDeclaredNamespaceUris() {
+        return EMPTY_STRING;
+    }
+
+    /**
+     * Similar to {@link #getPreDeclaredNamespaceUris()} but allows the
+     * (prefix,nsUri) pairs to be returned.
+     *
+     * <p>
+     * With {@link #getPreDeclaredNamespaceUris()}, applications who wish to control
+     * the prefixes as well as the namespaces needed to implement both
+     * {@link #getPreDeclaredNamespaceUris()} and {@link #getPreferredPrefix(String, String, boolean)}.
+     *
+     * <p>
+     * This version eliminates the needs by returning an array of pairs.
+     *
+     * @return
+     *      always return a non-null (but possibly empty) array. The array stores
+     *      data like (prefix1,nsUri1,prefix2,nsUri2,...) Use an empty string to represent
+     *      the empty namespace URI and the default prefix. Null is not allowed as a value
+     *      in the array.
+     *
+     * @since
+     *      JAXB RI 2.0 beta
+     */
+    public String[] getPreDeclaredNamespaceUris2() {
+        return EMPTY_STRING;
+    }
+
+    /**
+     * Returns a list of (prefix,namespace URI) pairs that represents
+     * namespace bindings available on ancestor elements (that need not be repeated
+     * by the JAXB RI.)
+     *
+     * <p>
+     * Sometimes JAXB is used to marshal an XML document, which will be
+     * used as a subtree of a bigger document. When this happens, it's nice
+     * for a JAXB marshaller to be able to use in-scope namespace bindings
+     * of the larger document and avoid declaring redundant namespace URIs.
+     *
+     * <p>
+     * This is automatically done when you are marshalling to {@link XMLStreamWriter},
+     * {@link XMLEventWriter}, {@link DOMResult}, or {@link Node}, because
+     * those output format allows us to inspect what's currently available
+     * as in-scope namespace binding. However, with other output format,
+     * such as {@link OutputStream}, the JAXB RI cannot do this automatically.
+     * That's when this method comes into play.
+     *
+     * <p>
+     * Namespace bindings returned by this method will be used by the JAXB RI,
+     * but will not be re-declared. They are assumed to be available when you insert
+     * this subtree into a bigger document.
+     *
+     * <p>
+     * It is <b>NOT</b> OK to return  the same binding, or give
+     * the receiver a conflicting binding information.
+     * It's a responsibility of the caller to make sure that this doesn't happen
+     * even if the ancestor elements look like:
+     * <pre><xmp>
+     *   <foo:abc xmlns:foo="abc">
+     *     <foo:abc xmlns:foo="def">
+     *       <foo:abc xmlns:foo="abc">
+     *         ... JAXB marshalling into here.
+     *       </foo:abc>
+     *     </foo:abc>
+     *   </foo:abc>
+     * </xmp></pre>
+     *
+     * @return
+     *      always return a non-null (but possibly empty) array. The array stores
+     *      data like (prefix1,nsUri1,prefix2,nsUri2,...) Use an empty string to represent
+     *      the empty namespace URI and the default prefix. Null is not allowed as a value
+     *      in the array.
+     *
+     * @since JAXB RI 2.0 beta
+     */
+    public String[] getContextualNamespaceDecls() {
+        return EMPTY_STRING;
+    }
+}

See the Sample Apps sample application for a detailed + example.

2.1.3. Indentation

Property + name:org.glassfish.jaxb.indentString
Type:java.lang.String
Default + value:

" " (four whitespaces)

This property controls the string used for the indentation + of XML. An element of depth k will be + indented by printing this string k times. + Note that the "jaxb.formatted.output" property + needs to be set to "true" for the formatting/indentation of the + output to occur. See the API documentation for + jakarta.xml.bind.Marshaller interface for + details of this property.

2.1.4. Character Escaping Control

Property + name:org.glassfish.jaxb.characterEscapeHandler
Type:org.glassfish.jaxb.core.marshaller.CharacterEscapeHandler
Default + value:

null

By default, the marshaller implementation of the Eclipse Implementation of JAXB + tries to escape characters so they can be safely represented in + the output encoding (by using Unicode numeric character references + of the form &#dddd;)

Unfortunately, due to various technical reasons, the default + behavior may not meet your expectations. If you need to handle + escaping more adroitly than the default manner, you can do so by + doing the following:

  1. Write a class that implements the + org.glassfish.jaxb.core.marshaller.CharacterEscapeHandler + interface.

  2. Create a new instance of it.

  3. Set that instance to the Marshaller by using this + property.

See the Sample Apps sample application for more + details.

2.1.5. XML Declaration Control

Property + name:org.glassfish.jaxb.xmlDeclaration
Type:boolean
Default + value:

true

This experimental JAXB RI 1.0.x property has been adopted as + a standard in Eclipse Implementation of JAXB. The Eclipse Implementation of JAXB will continue to support this + property, but client code should be using the Marshaller.JAXB_FRAGMENT + property instead. Please refer to the Marshaller + javadoc for a complete description of the behavior.

In Eclipse Implementation of JAXB, calling:

marshaller.setProperty("org.glassfish.jaxb.xmlDeclaration", true);

is equivalent to calling:

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

JAXB 1.0 generated code and clients will continue to work + exactly the same on the Jakarta XML Binding runtime as they did on the JAXB + 1.0 runtime.

Enabling fragment marshalling could be useful if you are + inserting the output of the XML into another XML.

2.1.6. XML Preamble Control

Property + name:org.glassfish.jaxb.xmlHeaders
Type:java.lang.String
Default + value:

null

This property allows you to specify an XML preamble + (<?xml ...> declaration) and any additional PIs, comments, + DOCTYPE declaration that follows it. This property takes effect + only when you are marshalling to OutputStream, + Writer, or StreamResult. Note that this + property interacts with the Marshaller.JAXB_FRAGMENT + property. If that property is untouched or set to false, then Eclipse Implementation of JAXB + would always write its XML preamble, so this property can be only + used to write PIs, comments, DOCTYPE, etc. On the other hand, if + it is set to true, then Jakarta XML Binding will not write its own XML preamble, + so this property may contain custom XML preamble.

2.1.7. Jaxb Annotation Control

Property + name:XmlAccessorFactory
Type:boolean
Default + value:

false

This property provides support for a custom + org.glassfish.jaxb.runtime.v2.runtime.reflect.Accessor implementation.  It + allows the user to control the access to class fields and + properties.

In Eclipse Implementation of JAXB, set the property to enable:

marshaller.setProperty("XmlAccessorFactory", true);

3. XJC Customizations

3.1. Customizations

The Eclipse Implementation of JAXB provides additional customizations that are not + defined by the Jakarta XML Binding specification. Note the following:

  • These features may only be used when the Eclipse Implementation of JAXB XJC + binding compiler is run in the -extension + mode.

  • All of the Eclipse Implementation of JAXB vendor extensions are defined in the + "http://java.sun.com/xml/ns/jaxb/xjc" + namespace.

  • The namespaces containing extension binding declarations + are specified to a Eclipse Implementation of JAXB processor by the occurrence of the + global attribute @jaxb:extensionBindingPrefixes + within an instance of <xs:schema> element. + The value of this attribute is a whitespace-separated list of + namespace prefixes. For more information, please refer to + section 6.1.1 of the Jakarta XML Binding Specification.

3.1.1. Index of Customizations

3.1.2. SCD Support

The Eclipse Implementation of JAXB supports the use of schema + component designator as a means of specifying the + customization target (of all standard Jakarta XML Binding customizations as well + as vendor extensions explained below.) To use this feature, use + the scd attribute on <bindings> element instead + of the schemaLocation and node + attributes.

<bindings xmlns:tns="http://example.com/myns"
+          xmlns="https://jakarta.ee/xml/ns/jaxb" version="3.0">
+    <bindings
+            ...
+            scd="tns:foo">
+        <!-- this customization applies to the global element declaration -->
+        <!-- 'foo' in the http://example.com/myns namespace -->
+        <class name="FooElement"/>
+    </bindings>
+    <bindings
+            ...
+            scd="~tns:bar">
+        <!-- this customization applies to the global type declaration -->
+        <!-- 'bar' in the http://example.com/myns namespace -->
+        <class name="BarType"/>
+    </bindings>
+</bindings>

Compared to the standard XPath based approach, SCD allows + more robust and concise way of identifying a target of a + customization. For more about SCD, refer to the scd example. Note + that SCD is a W3C working draft, and may change in the + future.

3.1.3. Extending a Common Super Class

The <xjc:superClass> customization allows + you to specify the fully qualified name of the Java class that is + to be used as the super class of all the generated implementation + classes. The <xjc:superClass> customization can + only occur within your <jaxb:globalBindings> + customization on the <xs:schema> + element:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    <xs:annotation>
+        <xs:appinfo>
+            <jaxb:globalBindings>
+                <xjc:superClass
+                        name="org.acme.RocketBooster"/>
+            </jaxb:globalBindings>
+        </xs:appinfo>
+    </xs:annotation>
+
+    ...
+
+</xs:schema>

In the sample above, the <xjc:superClass> + customization will cause all of the generated implementation + classes to extend the named class, + org.acme.RocketBooster.

3.1.4. Extending a Common Super Interface

The <xjc:superInterface> customization + allows you to specify the fully qualified name of the Java + interface that is to be used as the root interface of all the + generated interfaces. The <xjc:superInterface> + customization can only occur within your + <jaxb:globalBindings> customization on the + <xs:schema> element:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    <xs:annotation>
+        <xs:appinfo>
+            <jaxb:globalBindings>
+                <xjc:superInterface
+                        name="org.acme.RocketBooster"/>
+            </jaxb:globalBindings>
+        </xs:appinfo>
+    </xs:annotation>
+
+    ...
+
+</xs:schema>

In the sample above, the + <xjc:superInterface> customization will cause + all of the generated interfaces to extend the named interface, + org.acme.RocketBooster.

3.1.5. Enhanced <jaxb:javaType>

The <xjc:javaType> customization can be used just like + the standard <jaxb:javaType> customization, except that it + allows you to specify an XmlAdapter-derived + class, instead of parse&print method pair.

This customization can be used in all the places + <jaxb:javaType> is used, but nowhere else:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    ...
+
+    <xsd:simpleType name="LayerRate_T">
+        <xsd:annotation>
+            <xsd:appinfo>
+                <xjc:javaType name="org.acme.foo.LayerRate"
+                              adapter="org.acme.foo.LayerRateAdapter"/>
+            </xsd:appinfo>
+        </xsd:annotation>
+
+        ... gory simple type definition here ...
+
+    </xsd:simpleType>
+</xsd:schema>

In the above example, LayerRate_T simple type + is adapted by org.acme.foo.LayerRateAdapter, which + extends from XmlAdapter.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    <xsd:annotation>
+        <xsd:appinfo>
+            <jaxb:globalBindings>
+                <xjc:javaType name="org.acme.foo.MyDateType"
+                              xmlType="xsd:dateTime"
+                              adapter="org.acme.foo.MyAdapterImpl"/>
+            </jaxb:globalBindings>
+        </xsd:appinfo>
+    </xsd:annotation>
+
+    ...
+
+</xsd:schema>

In the above example, all the use of + xsd:dateTime type is adapter by + org.acme.foo.MyAdapterImpl to + org.acme.foo.MyDateType

3.1.6. Experimental simpler & better binding mode

This experimental binding mode can be enabled as a part of + the global binding. See below:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           jaxb:version="3.0">
+
+    <xs:annotation>
+        <xs:appinfo>
+            <jaxb:globalBindings generateValueClass="false">
+                <xjc:simple/>
+            </jaxb:globalBindings>
+        </xs:appinfo>
+    </xs:annotation>
+
+    ...
+
+</xs:schema>

When enabled, XJC produces Java source code that are more + concise and easier to use. Improvements include:

  1. Some content model definitions, such as + A,B,A, which used to cause an XJC compilation + error and required manual intervention, now compile out of + the box without any customization.

  2. Some content model definitions that used to bind to + a non-intuitive Java class now binds to a much better Java + class:

    <!-- schema -->
    +<xs:complexType name="foo">
    +    <xs:choice>
    +        <xs:sequence>
    +            <xs:element name="a" type="xs:int"/>
    +            <xs:element name="b" type="xs:int"/>
    +        </xs:sequence>
    +        <xs:sequence>
    +            <xs:element name="b" type="xs:int"/>
    +            <xs:element name="c" type="xs:int"/>
    +        </xs:sequence>
    +    </xs:choice>
    +</xs:complexType>
    // before
    +class Foo {
    +    List<JAXBElement<Integer>> content;
    +}
    +
    +// in <xjc:simple> binding
    +class Foo {
    +    Integer a;
    +    int b; // notice that b is effectively mandatory, hence primitive
    +    Integer c;
    +}
  3. When repetable elements are bound, the method name + will become plural.

    <!-- schema -->
    +<xs:complexType name="person">
    +    <xs:sequence>
    +        <xs:element name="child" type="xs:string"
    +                    maxOccurs="unbounded"/>
    +        <xs:element name="parent" type="xs:string"
    +                    maxOccurs="unbounded"/>
    +    </xs:sequence>
    +</xs:complexType>
    // before
    +public class Person {
    +    protected List<String> child;
    +    protected List<String> parent;
    +}
    +
    +// in <xjc:simple> binding
    +public class Person {
    +    protected List<String> children;
    +    protected List<String> parents;
    +}     

Once again, readers are warned that this is an experimental binding mode, and therefore + the binding is subject to change in future versions of the Eclipse Implementation of JAXB + without notice. Please send feedbacks on this binding to + jaxb-impl-dev@eclipse.org

3.1.7. Alternative Derivation-by-restriction Binding Mode

Normally, the Jakarta XML Binding specification requires that a + derivation-by-restriction be mapped to an inheritance betwee n two + Java classes. This is necessary to preserve the type hierarchy, + but one of the downsides is that the derived class does not really + provide easy-to-use properties that reflect the restricted content + model.

This experimental <xjc:treatRestrictionLikeNewType> + changes this behavior by not preserving the type inheritance to + Java. Instead, it generates two unrelated Java classes, both with + proper properties. For example, given the following schema:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+           jaxb:extensionBindingPrefixes="xjc"
+           xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+           jaxb:version="3.0"
+           elementFormDefault="qualified">
+
+    <xs:annotation>
+        <xs:appinfo>
+            <jaxb:globalBindings>
+                <xjc:treatRestrictionLikeNewType/>
+            </jaxb:globalBindings>
+        </xs:appinfo>
+    </xs:annotation>
+
+    <xs:complexType name="DerivedType">
+        <xs:complexContent>
+            <xs:restriction base="ResponseOptionType">
+                <xs:sequence>
+                    <xs:element name="foo" type="xs:string"/>
+                </xs:sequence>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+
+    <xs:complexType name="ResponseOptionType">
+        <xs:sequence>
+            <xs:element name="foo" type="xs:string"
+                        maxOccurs="unbounded"/>
+        </xs:sequence>
+    </xs:complexType>
+
+</xs:schema>

The generated Derived class will look like this + (comment and annotations removed for brevity):

public class DerivedType {
+    protected String foo;
+
+    public String getFoo() { return foo; }
+    public void setFoo(String value) { this.foo = value; }
+} 

In contrast, without this customization the + Derived class would look like the following:

public class DerivedType extends ResponseOptionType {
+
+    // it simply inherits List<String> ResponseOptionType.getFoo()
+
+}

3.1.8. Allow separate compilations to perform element + substitutions

In an attempt to make the generated code easier to use, the + Jakarta XML Binding specification sometimes choose bindings based on how certain + feature is used. One of them is element substitution feature. If + no actual element substitution happens in the schema, Jakarta XML Binding assumes + that the element is not used for substitution, and generates code + that assumes it.

Most of the time this is fine, but when you expect other + "extension" schemas to be compiled later on top of your base + schema, and if those extension schemas do element substitutions, + this binding causes a problem ( see + example.)

<xjc:substitutable> customization is a work around for + this issue. It explicitly tells XJC that a certain element is used + for element substitution head, even though no actual substitution + might be present in the current compilation. This customization + should be attached in the element declaration itself, like + this:

<xs:element name="Model" type="Model">
+    <xs:annotation>
+        <xs:appinfo>
+            <xjc:substitutable/>
+        </xs:appinfo>
+    </xs:annotation>
+</xs:element>

4. DTD

4.1. DTD

The Eclipse Implementation of JAXB is shipped with experimental DTD support, which lets + you compile XML DTDs.

To compile a DTD test.dtd, run the XJC + binding compiler as follows:

$ xjc.sh -dtd test.dtd

All the other command-line options of the XJC binding compiler + can be applied. Similarly, the xjc ant task supports + DTD. The generated code will be no different from what is generated + from W3C XML Schema. You'll use the same Jakarta XML Binding API to access the + generated code, and it is portable in the sense that it will run on + any Jakarta XML Binding implementation.

4.1.1. Customization

The customization syntax for DTD is roughly based on the + ver.0.21 working draft of the Jakarta XML Binding specification, which is + available at xml.coverpages.org. + The deviations from this document are:

  • The whitespace attribute of the + conversion element takes " + preserve", " replace", and " + collapse" instead of " + preserve"," normalize", and " + collapse" as specified in the + document.

  • The interface customization just + generates marker interfaces with no method.

5. Develop Plugins

This document describes how to write an XJC plugin to extend the + code generation of XJC.

5.1. What Can A Plugin Do?

An XJC plugin participates in the code generation from a schema. + It can define its own customizations that users can use to control it, + it can access the code that the Eclipse Implementation of JAXB generates, it can generate + additional classes/methods/fields/annotations/comments, and it can + also replace some of the pluggability points in the compilation + process, such as XML name -> Java name conversion.

As a show case of what a plugin can do, take a look at plugins hosted at + JAXB2-commons.

5.1.1. Quick Start

To write a plugin, do the following simple steps.

  1. Write a class, say, org.acme.MyPlugin + by extending com.sun.tools.xjc.Plugin. See + javadoc for how to implement methods.

  2. Write the name of your plugin class in a text file + and put it as + /META-INF/services/com.sun.tools.xjc.Plugin + in your jar file.

Users can then use your plugins by declaring an XJC ant task + with your jar files.

<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath>
+        <fileset dir="jaxb-ri/lib" includes="*.jar"/>
+        <fileset dir="your-plugin" includes="*.jar"/>
+    </classpath>
+</taskdef>

5.1.2. Resources

Although we will do our best to maintain the compatibility + of the interfaces, it is still subject to change at this + point.

Frequently Asked Questions

1. JAXB 2.0
Q: Which version of Java SE does Eclipse Implementation of JAXB 4.0.0 require?
Q: Can I run my existing JAXB 1.x/2.x applications on the + Eclipse Implementation of JAXB runtime?
Q: What if I want to port my JAXB 1.x/2.x application to Jakarta XML Binding runtime?
Q: Where are schemagen and xjc command line scripts available?
Q: Are the Jakarta XML Binding runtime API's thread safe?
Q: Why can't I cast the unmarshalled object into the + generated type.
Q: Which jar files do I need to distribute with my + application that uses the Eclipse Implementation of JAXB?
Q: How can I cause the Marshaller to + generate CDATA blocks?
Q: Can I access <xs:any/> as a DOM node?
Q: How do I find out which version of the Eclipse Implementation of JAXB I'm + using?

1. JAXB 2.0

Q:

Which version of Java SE does Eclipse Implementation of JAXB 4.0.0 require?

A:

Java SE 11 or higher.

Q:

Can I run my existing JAXB 1.x/2.x applications on the + Eclipse Implementation of JAXB runtime?

A:

This is not supported.

Q:

What if I want to port my JAXB 1.x/2.x application to Jakarta XML Binding runtime?

A:

You need to replace references to javax.xml.bind + package by jakarta.xml.bind package, recompile your schema + with the newer xjc and modify your application code to work with + the new bindings.

Q:

Where are schemagen and xjc command line scripts available?

A:

They are included only in the zip distribution.

Q:

Are the Jakarta XML Binding runtime API's thread safe?

A:

The Jakarta XML Binding Specification currently does not address + the thread safety of any of the runtime classes. In the + case of the Eclipse Implementation of JAXB, the + JAXBContext class is thread safe, but the + Marshaller, + Unmarshaller, and + Validator classes are not thread safe.

For example, suppose you have a multi-thread server + application that processes incoming XML documents by Jakarta XML Binding. + In this case, for the best performance you should have + just one instance of JAXBContext in + your whole application like this:

class MyServlet extends HttpServlet {
+    static final JAXBContext context = initContext();
+
+    private static JAXBContext initContext() {
+        return JAXBContext.newInstance("....", MyServlet.class.getClassLoader());
+    }
+}

And each time you need to unmarshal/marshal/validate + a document. Just create a new + Unmarshaller/Marshaller/Validator + from this context, like this:

public void doGet(HttpServletRequest req, HttpServletResponse resp) {
+    Unmarshaller u = context.createUnmarshaller();
+    u.unmarshal(...);
+}

This is the simplest safe way to use the Eclipse Implementation of JAXB + from multi-threaded applications.

If you really care about the performance, and/or + your application is going to read a lot of small + documents, then creating Unmarshaller + could be relatively an expensive operation. In that case, + consider pooling Unmarshaller objects. + Different threads may reuse one + Unmarshaller instance, as long as you + don't use one instance from two threads at the same + time.

Q:

Why can't I cast the unmarshalled object into the + generated type.

A:

When you invoke + JAXBContext.newInstance("aaa.bbb.ccc"), + it tries to load classes and resources using the same + classloader used to load the + JAXBContext class itself. This + classloader may be different from the classloader which + was used to load your application (see the picture Parent/Child classloader). In + this case, you'll see the above error. This problem is + often seen with application servers, Jakarta EE containers, Ant, + JUnit, and other applications that use sophisticated class + loading mechanisms.

Figure 1. Parent/Child classloader

Parent/Child classloader

With some applications, things get even more + complicated when the Jakarta XML Binding-generated code can be loaded by + either classloader. In this case, + JAXBContext.newInstance("aaa.bbb.ccc") + will work but the JVM ends up loading two copies of the + generated classes for each class loader. As a result, + unmarshalling works but an attempt to cast the returned + object into the expected type will fail, even though its + getClass().getName() returns the + expected name.

The solution for both situations is to pass your + curent class loader like this:

JAXBContext.newInstance("aaa.bbb.ccc", this.getClass().getClassLoader());

In general, if you are writing code that uses Jakarta XML Binding, + it is always better to explicitly pass in a class loader, + so that your code will work no matter where it is + deployed.

Q:

Which jar files do I need to distribute with my + application that uses the Eclipse Implementation of JAXB?

A:

+

+$JAXB_HOME/mod/jakarta.xml.bind-api.jar
+$JAXB_HOME/mod/jakarta.activation-api.jar
+$JAXB_HOME/mod/angus-activation.jar
+$JAXB_HOME/mod/jaxb-core.jar
+$JAXB_HOME/mod/jaxb-impl.jar

+

Q:

How can I cause the Marshaller to + generate CDATA blocks?

A:

This functionality is not available from Eclipse Implementation of JAXB + directly, but you can configure an Apache Xerces-J + XMLSerializer to produce + CDATA blocks. Please review the JaxbCDATASample.java + sample app for more detail.

Q:

Can I access <xs:any/> as a DOM node?

A:

In Eclipse Implementation of JAXB, <xs:any/> is handled correctly + without any customization.

  1. If it's strict, it will map + to Object or + List<Object> and when you + unmarshal documents, you'll get objects that map to + elements (such as JAXBElements or + classes that are annotated with + XmlRootElement).

  2. If it's skip, it will map + to org.w3c.dom.Element or + List<Element> and when you + unmarshal documents, you'll get DOM elements.

  3. If it's lax, it will map to + the same as with strict, and when + you unmarshal documents, you'll get either:

    1. JAXBElements

    2. classes that are annotated with + XmlRootElement

    3. DOM elements

Q:

How do I find out which version of the Eclipse Implementation of JAXB I'm + using?

A:

Run the following command

$ java -jar jaxb-xjc.jar -version

Alternatively, each Eclipse Implementation of JAXB jar has version information + in its META-INF/MANIFEST.MF, such as + this:

Manifest-Version: 1.0
+Specification-Title: Jakarta XML Binding
+Specification-Version: 4.0
+Specification-Vendor: Eclipse Foundation
+Implementation-Title: Eclipse Implementation of JAXB
+Implementation-Version: 4.0.0
+Implementation-Vendor: Eclipse Foundation
+Implementation-Vendor-Id: org.eclipse
+Build-Id: 2022-05-18 22:33
+Class-Path: jaxb-core.jar jaxb-impl.jar
\ No newline at end of file diff --git a/scripts/jaxb-ri/docs/release-documentation.pdf b/scripts/jaxb-ri/docs/release-documentation.pdf new file mode 100644 index 0000000..4e2b6b9 Binary files /dev/null and b/scripts/jaxb-ri/docs/release-documentation.pdf differ diff --git a/scripts/jaxb-ri/docs/style/documentation.css b/scripts/jaxb-ri/docs/style/documentation.css new file mode 100644 index 0000000..5a2ab22 --- /dev/null +++ b/scripts/jaxb-ri/docs/style/documentation.css @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2010, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* java.net branding */ + +body { + color: #333; +} + +/*Headings*/ + +.book h1, .chapter h1, .book h2, .chapter h2, .book h3, .chapter h3, .book h4, .chapter h4, .book h5, .chapter h5, .book h6 , .chapter h6 { + font-family: Arial,Helvetica,sans-serif !important; +} + +/* java.net branding */ + +.book h1 , .chapter h1 { + color: #E76F00; + font-size: 1.5em; + font-weight: bold; + margin: 0.67em 0; +} + +.book h2 , .chapter h2 { + background-color: transparent; + font-size: 1.4em; + color: #E76F00; +} + +.book h3 , .chapter h3 { + color: #E76F00; + font-size: 1.3em; + background-color: transparent; +} + +.book h4 , .chapter h4 { + margin-top: 0.3em; + margin-bottom: 0.3em; + font-size: 1.2em; +} + +.book h5 , .chapter h5 { + font-size: 1.1em; +} + +pre .co img { + height: auto !important; +} + +.literal { + font-size: inherit !important; +} + +.book .application, .chapter .application { + font-weight: bold; +} + +/*links*/ +.book a:link, .chapter a:link, .small a:link, .navheader a:link, .navfooter a:link { + color: #069 !important; + text-decoration: none; +} + +.book a:hover, .chapter a:hover, .small a:hover, .navheader a:hover, .navfooter a:hover { + color: #363 !important; + text-decoration: none; +} + +.book a:link.selfref, .chapter a:link.selfref, .book a:visited.selfref, .chapter a:visited.selfref, .small a:link.selfref, .small a:visited.selfref, .navheader a:link.selfref, .navheader a:visited.selfref, .navfooter a:link.selfref, .navfooter a:visited.selfref { + color: #363 !important; + text-decoration: none !important; +} + +.book a:visited, .chapter a:visited, .small a:visited, .navheader a:visited, .navfooter a:visited { + color: #003366; + text-decoration: none; +} + +/* java.net font styles */ + +body,.book th, .chapter th,.book td, .chapter td,.book p, .chapter p,.book li, .chapter li, .navheader th{ + font-family: lucida,arial,sans-serif !important; + background-color: #fff; +} + +body, .book input, .chapter input, .book select , .chapter select { + font-family: Verdana, Helvetica, Arial, sans-serif; +} + +.book code, .chapter code, .book pre , .chapter pre { + font-family: 'Andale Mono', Courier, monospace; +} + +body, .book pre, .chapter pre, .book code , .chapter code { + font-size: x-small; + voice-family: "\"}\""; + voice-family: inherit; + font-size: small; +} + +/* code highlight */ + +.book pre.programlisting , .chapter pre.programlisting { + background-color: rgb(255, 255, 224); + border-style: dashed; + border-width: 1px; + padding: 10px 10px 10px 10px; +} + +.book pre.programlisting .red, .chapter pre.programlisting .red { + font-weight: bold; + color: #f00; +} + +.book .qandaset .question p, .chapter .qandaset .question p { + font-weight: bold; +} + +.book .qandaset .answer td, .chapter .qandaset .answer td { + padding-bottom: 1em; +} + +.book img , .chapter img { + height: 100%; +} + +.book table , .chapter table { + border: none; + border-collapse: collapse; + font-size: inherit !important; +} + +.book .table , .chapter .table { + +} + +.book .table table , .chapter .table table { + border: 1px solid #000; +} + +.book .example-break , .chapter .example-break { + display: none; +} + +.book .note , .chapter .note { + padding: 1em; + border: 1px dashed black; + font-weight: normal; + text-transform: none; +} + +.book .note p , .chapter .note p { + margin: 0; + + font-style: italic; + font-size: 0.9em; + + color: #444; +} + +.book .note h3.title , .chapter .note h3.title { + margin: 0; +} + +.book dt , .chapter dt { + font-weight: normal !important; + padding: 0; +} + +.navheader tbody tr:last-child td:last-child, .navfooter tbody tr td:last-child { + text-align: right !important; +} + +.navheader tbody tr:last-child th, .navfooter tbody tr th { + text-align: center !important; +} + +.navheader tbody tr:last-child td:first-child, .navfooter tbody tr td:first-child { + text-align: left !important; +} + +.book dd , .chapter dd { + margin-left: 40px; +} + +span.Annotation {color: rgb(128, 128, 0); font-weight: normal;} +span.Comment {color: rgb(128, 128, 128); font-weight: normal;} +span.DocComment {color: rgb(150, 150, 150); font-weight: normal;} +span.String {color: rgb(0, 128, 0); font-weight: normal;} +span.EscString {color: rgb(206, 123, 0); font-weight: bold;} +span.Character {color: rgb(206, 123, 0); font-weight: normal;} +span.EscCharacter {color: rgb(206, 123, 0); font-weight: bold;} +span.Numeric {color: rgb(0, 0, 255); font-weight: normal;} +span.Identifier {color: black; font-weight: normal;} +span.PredefinedIdentifier {color: rgb(0,0,230); font-weight: normal;} +span.Type {color: black; font-weight: normal;} +span.ReservedWord {color: rgb(0, 0, 128); font-weight: normal;} +span.LibraryFunction {color: black; font-weight: normal;} +span.Include {color: rgb(0,155,0); font-weight: normal;} +span.Preprocessor {color: rgb(0,155,0); font-weight: normal;} +span.Braces {color: black; font-weight: normal;} +span.Symbol {color: black; font-weight: normal;} +span.FunctionHeader {color: black; font-weight: normal;} +span.FunctionHeaderName {color: black; font-weight: normal;} +span.FunctionHeaderArgs {color: black; font-weight: normal;} +span.RegEx {color: rgb(0,111,0); font-weight: bold;} +span.Text {color: rgb(206, 123, 0); font-weight: normal;} +span.Entity {color: black; font-weight: bold;} +span.Assignment {color: black; font-weight: normal;} +span.DependencyLine {color: black; font-weight: normal;} +span.DependencyTarget {color: black; font-weight: bold;} +span.DependencyContinuation {color: black; font-weight: bold;} +span.Continuation {color: black; font-weight: bold;} +span.Macro {color: rgb(0,153,0); font-weight: normal;} +span.IntMacro {color: rgb(0,153,0); font-weight: normal;} +span.EscVar {color: black; font-weight: bold;} +/* Special coloring for HTML tags */ +span.PredefinedIdentifier > span.Braces {color: rgb(0,0,230); font-weight: normal;} +span.PredefinedIdentifier > span.Identifier {color: rgb(0,153,0); font-weight: normal;} diff --git a/scripts/jaxb-ri/mod/angus-activation.jar b/scripts/jaxb-ri/mod/angus-activation.jar new file mode 100644 index 0000000..7bca6d9 Binary files /dev/null and b/scripts/jaxb-ri/mod/angus-activation.jar differ diff --git a/scripts/jaxb-ri/mod/jakarta.activation-api.jar b/scripts/jaxb-ri/mod/jakarta.activation-api.jar new file mode 100644 index 0000000..b125985 Binary files /dev/null and b/scripts/jaxb-ri/mod/jakarta.activation-api.jar differ diff --git a/scripts/jaxb-ri/mod/jakarta.xml.bind-api.jar b/scripts/jaxb-ri/mod/jakarta.xml.bind-api.jar new file mode 100644 index 0000000..b10d606 Binary files /dev/null and b/scripts/jaxb-ri/mod/jakarta.xml.bind-api.jar differ diff --git a/scripts/jaxb-ri/mod/jaxb-core.jar b/scripts/jaxb-ri/mod/jaxb-core.jar new file mode 100644 index 0000000..c9dddec Binary files /dev/null and b/scripts/jaxb-ri/mod/jaxb-core.jar differ diff --git a/scripts/jaxb-ri/mod/jaxb-impl.jar b/scripts/jaxb-ri/mod/jaxb-impl.jar new file mode 100644 index 0000000..20f9512 Binary files /dev/null and b/scripts/jaxb-ri/mod/jaxb-impl.jar differ diff --git a/scripts/jaxb-ri/mod/jaxb-jxc.jar b/scripts/jaxb-ri/mod/jaxb-jxc.jar new file mode 100644 index 0000000..6d93cfc Binary files /dev/null and b/scripts/jaxb-ri/mod/jaxb-jxc.jar differ diff --git a/scripts/jaxb-ri/mod/jaxb-xjc.jar b/scripts/jaxb-ri/mod/jaxb-xjc.jar new file mode 100644 index 0000000..d5158c4 Binary files /dev/null and b/scripts/jaxb-ri/mod/jaxb-xjc.jar differ diff --git a/scripts/jaxb-ri/samples/catalog-resolver/build.golden.regexp b/scripts/jaxb-ri/samples/catalog-resolver/build.golden.regexp new file mode 100644 index 0000000..69203b6 --- /dev/null +++ b/scripts/jaxb-ri/samples/catalog-resolver/build.golden.regexp @@ -0,0 +1,15 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] done + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/catalog-resolver/build.xml b/scripts/jaxb-ri/samples/catalog-resolver/build.xml new file mode 100644 index 0000000..c175d50 --- /dev/null +++ b/scripts/jaxb-ri/samples/catalog-resolver/build.xml @@ -0,0 +1,65 @@ + + + + + + This example demonstrates how to use the "-catalog" + compiler switch to handle references to schemas + in external web sites. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/catalog-resolver/catalog.cat b/scripts/jaxb-ri/samples/catalog-resolver/catalog.cat new file mode 100644 index 0000000..dbc534c --- /dev/null +++ b/scripts/jaxb-ri/samples/catalog-resolver/catalog.cat @@ -0,0 +1,40 @@ + + + + + + + + + \ No newline at end of file diff --git a/scripts/jaxb-ri/samples/catalog-resolver/readme.txt b/scripts/jaxb-ri/samples/catalog-resolver/readme.txt new file mode 100644 index 0000000..3b4c399 --- /dev/null +++ b/scripts/jaxb-ri/samples/catalog-resolver/readme.txt @@ -0,0 +1,27 @@ +Schemas, especially those which are developed by a standard body, often +contain references to external resources, such as +"http://www.w3.org/2001/xml.xsd" or "XMLSchema.dtd". + +To compile those schemas by XJC, you have to either modify a schema and +fix the references, or you have to make sure that the network connection +is available when you compile it. But both approaches are problematic. + +XJC has the "-catalog" option which turns on the use of catalog-based +entity resolver. This will allow you to essentially "redirect" references +to your local copies of resources without touching the schema files. + +Try this example without the internet connection to make sure +that the redirection is indeed happening. + +A brief description of the catalog file format can be found in +"catalog.cat" itself. For more detailed discussion about the entity +resolution and the format of the catalog files, see +http://wwws.sun.com/software/xml/developers/resolver/article/ + + +DEBUG TIPS +========== + +If you suspect that the catalog resolution is not happening +(for example, you see errors like UnknownHostException), then +use the -debug option of XJC. \ No newline at end of file diff --git a/scripts/jaxb-ri/samples/catalog-resolver/s4s/XMLSchema.dtd b/scripts/jaxb-ri/samples/catalog-resolver/s4s/XMLSchema.dtd new file mode 100644 index 0000000..b9330f3 --- /dev/null +++ b/scripts/jaxb-ri/samples/catalog-resolver/s4s/XMLSchema.dtd @@ -0,0 +1,414 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%xs-datatypes; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/catalog-resolver/s4s/datatypes.dtd b/scripts/jaxb-ri/samples/catalog-resolver/s4s/datatypes.dtd new file mode 100644 index 0000000..39a0869 --- /dev/null +++ b/scripts/jaxb-ri/samples/catalog-resolver/s4s/datatypes.dtd @@ -0,0 +1,216 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/catalog-resolver/sample.meta b/scripts/jaxb-ri/samples/catalog-resolver/sample.meta new file mode 100644 index 0000000..45b0719 --- /dev/null +++ b/scripts/jaxb-ri/samples/catalog-resolver/sample.meta @@ -0,0 +1,27 @@ + + + + + catalog resolver + + + + + + + + diff --git a/scripts/jaxb-ri/samples/catalog-resolver/test.xsd b/scripts/jaxb-ri/samples/catalog-resolver/test.xsd new file mode 100644 index 0000000..6611b3a --- /dev/null +++ b/scripts/jaxb-ri/samples/catalog-resolver/test.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/catalog-resolver/xml.xsd b/scripts/jaxb-ri/samples/catalog-resolver/xml.xsd new file mode 100644 index 0000000..0322258 --- /dev/null +++ b/scripts/jaxb-ri/samples/catalog-resolver/xml.xsd @@ -0,0 +1,97 @@ + + + + + + + + + See http://www.w3.org/XML/1998/namespace.html and + http://www.w3.org/TR/REC-xml for information about this namespace. + + + + + This schema defines attributes and an attribute group + suitable for use by + schemas wishing to allow xml:base, xml:lang or xml:space attributes + on elements they define. + + To enable this, such a schema must import this schema + for the XML namespace, e.g. as follows: + <schema . . .> + . . . + <import namespace="http://www.w3.org/XML/1998/namespace" + schemaLocation="http://www.w3.org/2001/03/xml.xsd"/> + + Subsequently, qualified reference to any of the attributes + or the group defined below will have the desired effect, e.g. + + <type . . .> + . . . + <attributeGroup ref="xml:specialAttrs"/> + + will define a type which will schema-validate an instance + element with any of those attributes + + + + + In keeping with the XML Schema WG's standard versioning + policy, this schema document will persist at + http://www.w3.org/2001/03/xml.xsd. + At the date of issue it can also be found at + http://www.w3.org/2001/xml.xsd. + The schema document at that URI may however change in the future, + in order to remain compatible with the latest version of XML Schema + itself. In other words, if the XML Schema namespace changes, the version + of this document at + http://www.w3.org/2001/xml.xsd will change + accordingly; the version at + http://www.w3.org/2001/03/xml.xsd will not change. + + + + + + In due course, we should install the relevant ISO 2- and 3-letter + codes as the enumerated possible values . . . + + + + + + + + + + + + + + + + See http://www.w3.org/TR/xmlbase/ for + information about this attribute. + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/character-escape/build.golden.regexp b/scripts/jaxb-ri/samples/character-escape/build.golden.regexp new file mode 100644 index 0000000..812055b --- /dev/null +++ b/scripts/jaxb-ri/samples/character-escape/build.golden.regexp @@ -0,0 +1,20 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] .* is not found and thus excluded from the dependency check + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"US\-ASCII\" standalone\=\"yes\"\?\> + \[java\] \G\ödel \& his friends\<\/e\> + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"US\-ASCII\" standalone\=\"yes\"\?\> + \[java\] \G\ödel \& his friends\<\/e\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/character-escape/build.xml b/scripts/jaxb-ri/samples/character-escape/build.xml new file mode 100644 index 0000000..35782e5 --- /dev/null +++ b/scripts/jaxb-ri/samples/character-escape/build.xml @@ -0,0 +1,68 @@ + + + + + This example shows how you can use the new JAXB RI Marshaller + property "org.glassfish.jaxb.characterEscapeHandler" to change + the default character escaping behavior. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/character-escape/readme.txt b/scripts/jaxb-ri/samples/character-escape/readme.txt new file mode 100644 index 0000000..5a36c46 --- /dev/null +++ b/scripts/jaxb-ri/samples/character-escape/readme.txt @@ -0,0 +1,2 @@ +This example shows how you can use a JAXB RI specific marshaller property +to change the default character escaping behavior. \ No newline at end of file diff --git a/scripts/jaxb-ri/samples/character-escape/sample.meta b/scripts/jaxb-ri/samples/character-escape/sample.meta new file mode 100644 index 0000000..db019f0 --- /dev/null +++ b/scripts/jaxb-ri/samples/character-escape/sample.meta @@ -0,0 +1,33 @@ + + + + + character-escape + This example shows how you can use the new JAXB RI Marshaller + property "org.glassfish.jaxb.characterEscapeHandler" to change + the default character escaping behavior. + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/character-escape/simple.xsd b/scripts/jaxb-ri/samples/character-escape/simple.xsd new file mode 100644 index 0000000..871a083 --- /dev/null +++ b/scripts/jaxb-ri/samples/character-escape/simple.xsd @@ -0,0 +1,16 @@ + + + + + + diff --git a/scripts/jaxb-ri/samples/character-escape/src/CustomCharacterEscapeHandler.java b/scripts/jaxb-ri/samples/character-escape/src/CustomCharacterEscapeHandler.java new file mode 100644 index 0000000..542b9cd --- /dev/null +++ b/scripts/jaxb-ri/samples/character-escape/src/CustomCharacterEscapeHandler.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.IOException; +import java.io.Writer; +import org.glassfish.jaxb.core.marshaller.CharacterEscapeHandler; + +public class CustomCharacterEscapeHandler implements CharacterEscapeHandler { + + /** + * Escape characters inside the buffer and send the output to the writer. + * + * @exception IOException + * if something goes wrong, IOException can be thrown to stop the + * marshalling process. + */ + public void escape( char[] buf, int start, int len, boolean isAttValue, Writer out ) throws IOException { + + for( int i=start; i + + + if( ch>0x7F ) { + // escape everything above ASCII to &#xXXXX; + out.write("&#x"); + out.write( Integer.toHexString(ch) ); + out.write(";"); + continue; + } + + // otherwise print normally + out.write(ch); + } + } +} diff --git a/scripts/jaxb-ri/samples/character-escape/src/Main.java b/scripts/jaxb-ri/samples/character-escape/src/Main.java new file mode 100644 index 0000000..1822477 --- /dev/null +++ b/scripts/jaxb-ri/samples/character-escape/src/Main.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBElement; +import jakarta.xml.bind.Marshaller; + +import org.glassfish.jaxb.core.marshaller.CharacterEscapeHandler; + +import simple.*; + +public class Main { + public static void main( String[] args ) throws Exception { + + // create JAXBContext for the primer.xsd + JAXBContext context = JAXBContext.newInstance(ObjectFactory.class); + ObjectFactory of = new ObjectFactory(); + + // \u00F6 is o with diaeresis + JAXBElement e = of.createE("G\u00F6del & his friends"); + + + // set up a normal marshaller + Marshaller marshaller = context.createMarshaller(); + marshaller.setProperty( "jaxb.encoding", "US-ASCII" ); + marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true ); + + // check out the console output + marshaller.marshal( e, System.out ); + + + // set up a marshaller with a custom character encoding handler + marshaller = context.createMarshaller(); + marshaller.setProperty( "jaxb.encoding", "US-ASCII" ); + marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true ); + marshaller.setProperty( + "org.glassfish.jaxb.characterEscapeHandler", + new CustomCharacterEscapeHandler() ); + + // check out the console output + marshaller.marshal( e, System.out ); + } + +} diff --git a/scripts/jaxb-ri/samples/character-escape/test.xml b/scripts/jaxb-ri/samples/character-escape/test.xml new file mode 100644 index 0000000..1ca19d6 --- /dev/null +++ b/scripts/jaxb-ri/samples/character-escape/test.xml @@ -0,0 +1,53 @@ + + + + + + + + Alice Smith + 123 Maple Street + Cambridge + MA + 12345 + + + Robert Smith + 8 Oak Avenue + Cambridge + MA + 12345 + + + + + + + + Lee Grant + 123 Maple Street + Cambridge + MA + 12345 + + + Stonewall Jackson + 8 Oak Avenue + Lexington + MA + 12345 + + + + + diff --git a/scripts/jaxb-ri/samples/class-resolver/build.golden.regexp b/scripts/jaxb-ri/samples/class-resolver/build.golden.regexp new file mode 100644 index 0000000..7da6dd1 --- /dev/null +++ b/scripts/jaxb-ri/samples/class-resolver/build.golden.regexp @@ -0,0 +1,12 @@ + +compile\: + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .+ + \[javac\] Compiling .+ source files to .+ + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] Foo\[a\=5\,b\=text\,c\=Bar\[x\=3\,y\=5\]\] + +BUILD SUCCESSFUL +Total time\: .+ seconds diff --git a/scripts/jaxb-ri/samples/class-resolver/build.xml b/scripts/jaxb-ri/samples/class-resolver/build.xml new file mode 100644 index 0000000..111e56e --- /dev/null +++ b/scripts/jaxb-ri/samples/class-resolver/build.xml @@ -0,0 +1,58 @@ + + + + + + This little DI-container-by-JAXB example demonstrates how one can avoid + passing in a list of classes upfront, and instead load classes lazily. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/class-resolver/def.xml b/scripts/jaxb-ri/samples/class-resolver/def.xml new file mode 100644 index 0000000..b3f4783 --- /dev/null +++ b/scripts/jaxb-ri/samples/class-resolver/def.xml @@ -0,0 +1,29 @@ + + + + + + + 5 + text + bar + + + + + + 3 + 5 + + + diff --git a/scripts/jaxb-ri/samples/class-resolver/sample.meta b/scripts/jaxb-ri/samples/class-resolver/sample.meta new file mode 100644 index 0000000..fc501c8 --- /dev/null +++ b/scripts/jaxb-ri/samples/class-resolver/sample.meta @@ -0,0 +1,25 @@ + + + + + ClassResolver + + + + + + + diff --git a/scripts/jaxb-ri/samples/class-resolver/src/Container.java b/scripts/jaxb-ri/samples/class-resolver/src/Container.java new file mode 100644 index 0000000..fa2a02e --- /dev/null +++ b/scripts/jaxb-ri/samples/class-resolver/src/Container.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Unmarshaller; +import jakarta.xml.bind.annotation.XmlAnyElement; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlID; +import jakarta.xml.bind.annotation.XmlIDREF; +import jakarta.xml.bind.annotation.XmlRootElement; + +import org.glassfish.jaxb.runtime.IDResolver; +import org.glassfish.jaxb.runtime.api.ClassResolver; + +/** + * Miniture DI container. + * + * @author Kohsuke Kawaguchi + */ +@XmlRootElement +public class Container { + @XmlElement(name="value") + private List values = new ArrayList(); + + private static class Value { + /** + * ID to identify {@link #value}. + */ + @XmlAttribute(required=true) + @XmlID + private String id; + + /** + * This annotation causes JAXB to trigger {@link ClassResolver} + * on this field. + */ + @XmlAnyElement(lax=true) + private Object value; + } + + public static Container load(File file) throws JAXBException { + Unmarshaller u = CONTEXT.createUnmarshaller(); + // register ClassResolver + u.setProperty(ClassResolver.class.getName(), new ClassResolverImpl()); + u.setProperty(IDResolver.class.getName(), new IDResolverImpl()); + return (Container)u.unmarshal(file); + } + + /** + * Informs JAXB lazily to use such and such class for unmarshalling. + */ + static final class ClassResolverImpl extends ClassResolver { + public Class resolveElementName(String nsUri, String localName) throws Exception { + // assume that element names look like + // + // and try to load that class. + if(nsUri.startsWith("java:")) { + String className = nsUri.substring(5)+'.'+localName; + // if an exception is thrown from here, it will be passed to + // ValidationEventHandler + return Class.forName(className); + } + + // returning null means 'I have no clue about this element' + return null; + } + } + + /** + * Notice that this example places the ID attribute on {@link Value}, + * not on the bean object ({@link Value#value}.) So we use + * a custom {@link IDResolver} so that {@link XmlIDREF} resolves + * into the {@link Value#value}. + */ + static final class IDResolverImpl extends IDResolver { + private final Map table = new HashMap(); + public void bind(String id, Object obj) { + table.put(id,obj); + } + + public Callable resolve(final String id, Class targetType) { + return new Callable() { + public Object call() throws Exception { + // if IDREF resolves to a Value object, + // use the inner value + Object o = table.get(id); + if(o instanceof Value) { + return ((Value)o).value; + } + return o; + } + }; + } + } + + + /** + * Gets the object for the ID. + */ + public Object get(String id) { + for (Value v : values) { + if(v.id.equals(id)) + return v.value; + } + return null; + } + + /** + * Note that this {@link JAXBContext} only knows about + * {@link Container}. + */ + private static final JAXBContext CONTEXT; + + static { + try { + CONTEXT = JAXBContext.newInstance(Container.class); + } catch (JAXBException e) { + // this is a deployment error + throw new Error(e); + } + } +} diff --git a/scripts/jaxb-ri/samples/class-resolver/src/Main.java b/scripts/jaxb-ri/samples/class-resolver/src/Main.java new file mode 100644 index 0000000..0561654 --- /dev/null +++ b/scripts/jaxb-ri/samples/class-resolver/src/Main.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.File; + +/** + * Miniture DI example. + */ +public class Main { + public static void main( String[] args ) throws Exception { + Container c = Container.load(new File("def.xml")); + System.out.println(c.get("foo")); + } +} diff --git a/scripts/jaxb-ri/samples/class-resolver/src/org/acme/Bar.java b/scripts/jaxb-ri/samples/class-resolver/src/org/acme/Bar.java new file mode 100644 index 0000000..924ea20 --- /dev/null +++ b/scripts/jaxb-ri/samples/class-resolver/src/org/acme/Bar.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.acme; + +/** + * @author Kohsuke Kawaguchi + */ +public class Bar { + // in this bean we bind properties, just to show that we can. + private int x,y; + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + public String toString() { + return "Bar[x="+x+",y="+y+"]"; + } + +} diff --git a/scripts/jaxb-ri/samples/class-resolver/src/org/acme/Foo.java b/scripts/jaxb-ri/samples/class-resolver/src/org/acme/Foo.java new file mode 100644 index 0000000..b718cc0 --- /dev/null +++ b/scripts/jaxb-ri/samples/class-resolver/src/org/acme/Foo.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.acme; + +import jakarta.xml.bind.annotation.XmlIDREF; + +/** + * @author Kohsuke Kawaguchi + */ +public class Foo { + // in this bean we bind fields, just to show that we can. + + public int a; + public String b; + + /** + * JAXB will inject the proper bean here as configured in XML. + */ + @XmlIDREF + public Object c; + + public String toString() { + return "Foo[a="+a+",b="+b+",c="+c+"]"; + } +} diff --git a/scripts/jaxb-ri/samples/class-resolver/src/org/acme/package-info.java b/scripts/jaxb-ri/samples/class-resolver/src/org/acme/package-info.java new file mode 100644 index 0000000..3a2a28c --- /dev/null +++ b/scripts/jaxb-ri/samples/class-resolver/src/org/acme/package-info.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +@XmlSchema(namespace="java:org.acme",elementFormDefault= QUALIFIED) +package org.acme; + +import static jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED; +import jakarta.xml.bind.annotation.XmlSchema; diff --git a/scripts/jaxb-ri/samples/create-marshal/build.golden.regexp b/scripts/jaxb-ri/samples/create-marshal/build.golden.regexp new file mode 100644 index 0000000..01055a5 --- /dev/null +++ b/scripts/jaxb-ri/samples/create-marshal/build.golden.regexp @@ -0,0 +1,50 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] .* is not found and thus excluded from the dependency check + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \Alice Smith\<\/name\> + \[java\] \123 Maple Street\<\/street\> + \[java\] \Cambridge\<\/city\> + \[java\] \MA\<\/state\> + \[java\] \12345\<\/zip\> + \[java\] \<\/shipTo\> + \[java\] \ + \[java\] \Robert Smith\<\/name\> + \[java\] \8 Oak Avenue\<\/street\> + \[java\] \Cambridge\<\/city\> + \[java\] \MA\<\/state\> + \[java\] \12345\<\/zip\> + \[java\] \<\/billTo\> + \[java\] \ + \[java\] \ + \[java\] \Nosferatu \- Special Edition \(1929\)\<\/productName\> + \[java\] \5\<\/quantity\> + \[java\] \19\.99\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \The Mummy \(1959\)\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \19\.98\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \Godzilla and Mothra\: Battle for Earth\/Godzilla vs\. King Ghidora\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \27\.95\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \<\/items\> + \[java\] \<\/purchaseOrder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/create-marshal/build.xml b/scripts/jaxb-ri/samples/create-marshal/build.xml new file mode 100644 index 0000000..b039d69 --- /dev/null +++ b/scripts/jaxb-ri/samples/create-marshal/build.xml @@ -0,0 +1,70 @@ + + + + + + This sample application demonstrates how to use the ObjectFactory + class to create a Java content tree from scratch and marshal it to + XML data. It also demonstrates how to add content to a JAXB List + property. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/create-marshal/po.xml b/scripts/jaxb-ri/samples/create-marshal/po.xml new file mode 100644 index 0000000..f3a10ae --- /dev/null +++ b/scripts/jaxb-ri/samples/create-marshal/po.xml @@ -0,0 +1,46 @@ + + + + + + Alice Smith + 123 Maple Street + Cambridge + MA + 12345 + + + Robert Smith + 8 Oak Avenue + Cambridge + MA + 12345 + + + + Nosferatu - Special Edition (1929) + 5 + 19.99 + + + The Mummy (1959) + 3 + 19.98 + + + Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora + 3 + 27.95 + + + diff --git a/scripts/jaxb-ri/samples/create-marshal/po.xsd b/scripts/jaxb-ri/samples/create-marshal/po.xsd new file mode 100644 index 0000000..641c17e --- /dev/null +++ b/scripts/jaxb-ri/samples/create-marshal/po.xsd @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/create-marshal/sample.meta b/scripts/jaxb-ri/samples/create-marshal/sample.meta new file mode 100644 index 0000000..55d79d5 --- /dev/null +++ b/scripts/jaxb-ri/samples/create-marshal/sample.meta @@ -0,0 +1,31 @@ + + + + + create-marshal (formerly SampleApp3) + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/create-marshal/src/Main.java b/scripts/jaxb-ri/samples/create-marshal/src/Main.java new file mode 100644 index 0000000..50734cd --- /dev/null +++ b/scripts/jaxb-ri/samples/create-marshal/src/Main.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.math.BigDecimal; +import java.util.GregorianCalendar; +import java.util.List; + +import jakarta.xml.bind.JAXB; +import jakarta.xml.bind.JAXBElement; + +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.datatype.DatatypeConfigurationException; + +// import java content classes generated by binding compiler +import primer.po.*; + +/* + * $Id: Main.java,v 1.2 2009-11-11 14:17:31 pavel_bucek Exp $ + */ + +public class Main { + + // This sample application demonstrates how to construct value classes + // and create a java content tree from scratch and marshal it + // to XML data + + public static void main( String[] args ) { + // create an empty PurchaseOrder + PurchaseOrderType po = new PurchaseOrderType(); + + // set the required orderDate attribute + po.setOrderDate( getDate() ); + + // create shipTo USAddress object + USAddress shipTo = createUSAddress( "Alice Smith", + "123 Maple Street", + "Cambridge", + "MA", + "12345" ); + + // set the required shipTo address + po.setShipTo( shipTo ); + + // create billTo USAddress object + USAddress billTo = createUSAddress( "Robert Smith", + "8 Oak Avenue", + "Cambridge", + "MA", + "12345" ); + + // set the requred billTo address + po.setBillTo( billTo ); + + // create an empty Items object + Items items = new Items(); + + // get a reference to the ItemType list + List itemList = items.getItem(); + + // start adding ItemType objects into it + itemList.add( createItem( "Nosferatu - Special Edition (1929)", + 5, + new BigDecimal( "19.99" ), + null, + null, + "242-NO" ) ); + itemList.add( createItem( "The Mummy (1959)", + 3, + new BigDecimal( "19.98" ), + null, + null, + "242-MU" ) ); + itemList.add( createItem( "Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora", + 3, + new BigDecimal( "27.95" ), + null, + null, + "242-GZ" ) ); + + // set the required Items list + po.setItems( items ); + + // create an element for marshalling + JAXBElement poElement = (new ObjectFactory()).createPurchaseOrder(po); + + // create a Marshaller and marshal to System.out + JAXB.marshal( poElement, System.out ); + } + + public static USAddress createUSAddress( String name, String street, + String city, String state, + String zip ) { + + // create an empty USAddress objects + USAddress address = new USAddress(); + + // set properties on it + address.setName( name ); + address.setStreet( street ); + address.setCity( city ); + address.setState( state ); + address.setZip( new BigDecimal( zip ) ); + + // return it + return address; + } + + public static Items.Item createItem( String productName, + int quantity, + BigDecimal price, + String comment, + XMLGregorianCalendar shipDate, + String partNum ) { + + // create an empty ItemType object + Items.Item item = new Items.Item(); + + // set properties on it + item.setProductName( productName ); + item.setQuantity( quantity ); + item.setUSPrice( price ); + item.setComment( comment ); + item.setShipDate( shipDate ); + item.setPartNum( partNum ); + + // return it + return item; + } + + + private static XMLGregorianCalendar getDate() { + try { + return DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar()); + } catch (DatatypeConfigurationException e) { + throw new Error(e); + } + } +} diff --git a/scripts/jaxb-ri/samples/cycle-recovery/build.golden.regexp b/scripts/jaxb-ri/samples/cycle-recovery/build.golden.regexp new file mode 100644 index 0000000..e2ed7fc --- /dev/null +++ b/scripts/jaxb-ri/samples/cycle-recovery/build.golden.regexp @@ -0,0 +1,19 @@ + +compile\: + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .+ + \[javac\] Compiling 2 source files to .+ + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \5\<\/id\> + \[java\] \Joe Chin\<\/name\> + \[java\] \ + \[java\] \5\<\/id\> + \[java\] \<\/parent\> + \[java\] \<\/person\> + +BUILD SUCCESSFUL +Total time\: [0-9]+ seconds diff --git a/scripts/jaxb-ri/samples/cycle-recovery/build.xml b/scripts/jaxb-ri/samples/cycle-recovery/build.xml new file mode 100644 index 0000000..6cfa14b --- /dev/null +++ b/scripts/jaxb-ri/samples/cycle-recovery/build.xml @@ -0,0 +1,58 @@ + + + + + + JAXB RI's vendor extension "CycleRecoverable" provides application a hook to handle + cycles in the object graph. Advanced. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/cycle-recovery/sample.meta b/scripts/jaxb-ri/samples/cycle-recovery/sample.meta new file mode 100644 index 0000000..303a1e2 --- /dev/null +++ b/scripts/jaxb-ri/samples/cycle-recovery/sample.meta @@ -0,0 +1,25 @@ + + + + + Application-driven cycle handling + + + + + + + diff --git a/scripts/jaxb-ri/samples/cycle-recovery/src/Main.java b/scripts/jaxb-ri/samples/cycle-recovery/src/Main.java new file mode 100644 index 0000000..e2bcb1b --- /dev/null +++ b/scripts/jaxb-ri/samples/cycle-recovery/src/Main.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; + +import org.glassfish.jaxb.runtime.CycleRecoverable; + +public class Main { + public static void main(String[] args) throws JAXBException { + // let's create an obvious cycle + Person p = new Person(); + p.id = 5; + p.name = "Joe Chin"; + p.parent = p; + + JAXBContext context = JAXBContext.newInstance(Person.class); + Marshaller m = context.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); + m.marshal(p,System.out); + } +} diff --git a/scripts/jaxb-ri/samples/cycle-recovery/src/Person.java b/scripts/jaxb-ri/samples/cycle-recovery/src/Person.java new file mode 100644 index 0000000..4daf00d --- /dev/null +++ b/scripts/jaxb-ri/samples/cycle-recovery/src/Person.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import jakarta.xml.bind.annotation.XmlRootElement; + +import org.glassfish.jaxb.runtime.CycleRecoverable; + +@XmlRootElement +public class Person implements CycleRecoverable { + + public int id; + + public String name; + + public Person parent; + + // this method is called by JAXB when a cycle is detected + public Person onCycleDetected(CycleRecoverable.Context context) { + // when a cycle is detected, let's just write out an ID + Person replacement = new Person(); + replacement.id = this.id; + return replacement; + } +} diff --git a/scripts/jaxb-ri/samples/datatypeconverter/build.golden.regexp b/scripts/jaxb-ri/samples/datatypeconverter/build.golden.regexp new file mode 100644 index 0000000..62250cc --- /dev/null +++ b/scripts/jaxb-ri/samples/datatypeconverter/build.golden.regexp @@ -0,0 +1,49 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \Alice Smith\<\/name\> + \[java\] \123 Maple Street\<\/street\> + \[java\] \Cambridge\<\/city\> + \[java\] \MA\<\/state\> + \[java\] \12345\<\/zip\> + \[java\] \<\/shipTo\> + \[java\] \ + \[java\] \John Bob\<\/name\> + \[java\] \242 Main Street\<\/street\> + \[java\] \Beverly Hills\<\/city\> + \[java\] \CA\<\/state\> + \[java\] \90210\<\/zip\> + \[java\] \<\/billTo\> + \[java\] \ + \[java\] \ + \[java\] \Nosferatu \- Special Edition \(1929\)\<\/productName\> + \[java\] \5\<\/quantity\> + \[java\] \16\.95\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \The Mummy \(1959\)\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \16\.94\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \Godzilla and Mothra\: Battle for Earth\/Godzilla vs\. King Ghidora\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \23\.70\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \<\/items\> + \[java\] \<\/purchaseOrder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/datatypeconverter/build.xml b/scripts/jaxb-ri/samples/datatypeconverter/build.xml new file mode 100644 index 0000000..894a096 --- /dev/null +++ b/scripts/jaxb-ri/samples/datatypeconverter/build.xml @@ -0,0 +1,69 @@ + + + + + + This sample application is very similar to the inline-customize sample + application (formerly SampleApp6), but illustrates an easier, but not + as robust, <jaxb:javaType> customization. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/datatypeconverter/po.xml b/scripts/jaxb-ri/samples/datatypeconverter/po.xml new file mode 100644 index 0000000..f3a10ae --- /dev/null +++ b/scripts/jaxb-ri/samples/datatypeconverter/po.xml @@ -0,0 +1,46 @@ + + + + + + Alice Smith + 123 Maple Street + Cambridge + MA + 12345 + + + Robert Smith + 8 Oak Avenue + Cambridge + MA + 12345 + + + + Nosferatu - Special Edition (1929) + 5 + 19.99 + + + The Mummy (1959) + 3 + 19.98 + + + Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora + 3 + 27.95 + + + diff --git a/scripts/jaxb-ri/samples/datatypeconverter/po.xsd b/scripts/jaxb-ri/samples/datatypeconverter/po.xsd new file mode 100644 index 0000000..e1a8ec8 --- /dev/null +++ b/scripts/jaxb-ri/samples/datatypeconverter/po.xsd @@ -0,0 +1,244 @@ + + + + + + jxb:globalBindings element documentation: + To illustrate all global controllable settings, listed all + attributes with their default values except for + @fixedAttributeAsConstantProperty and @collectionType. + + @fixedAttributeAsConstantProperty set to true indicates that + all fixed attributes should be bound to Java constants. By + default, fixed attributes are just mapped to either simple + or collection property, which ever is more appropriate. + + @collectionType set to java.util.Vector specifies that all + lists in the generated implementation classes should be represented + internally as vectors. + + If @typesafeEnumBase was set to"xsd:string", it is a global way to specify + that all simple type definitions deriving directly or indirectly + from "xsd:string" and having enumeration facets should be bound + to a typesafe enum. The typesafeEnumClass customization in simple + type definition of USState would be redundant with this suggested + change. If @typesafeEnumBase was set to empty string, "", no simple + type definitions would ever be bound to a typesafe enum class by + default binding. + + jxb:schemaBindings documentation: + child element jxb:package specifes a java package for the Java + representation generated for this schema. + + child element jxb:nameXmlTransform/jxb:elementName specifies that + all Java element interfaces generated should have "Element" + appended to names generated by default. For this schema, + customization results in element interfaces CommentElement and + PurchaseOrderElement being generated. Default binding would + generate element interface Comment and PurchaseOrderElement. + jxb:nameXmlTransform has children elements for the symbol space + typeName, anonymousTypeName and modelGroupName. + + + + + + Package level documentation for generated package primer.myPo.]]> + + + + + + + + + + + + + + + A <b>Purchase Order</b> consists of addresses and items. + + + + + + + + + + + + + + + + + + USAddress.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + JAXB customization documentation: + jaxb:property @generateIsSetMethod results in additional property + methods,isSetQuantity and unsetQuantity, being generated to + to be able to distinguish between schema defaulted value + and values occuring explicitly within an instance document. + + + + + + + + + By default, JAXB specification maps an xsd:positiveInteger to + a java.math.BigInteger. Since this simpleType is constrained to + be a value between 0..100, it is more natural for the Java + program to map this to a "short" Java datatype. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is a localized way to map this simple type definition + to a typesafe enum class. See jxb:globalBindings + @typesafeEnumBase above for a global way to accomplish this + for all simple type definitions similar to this one. + + + + + + + + + + + + + + + + Legal zip codes are limited to 5 digits, extended Zip Code not + supported. + + JAXB customization: jaxb:javaType binding declaration overrides + default binding of this type to a java.lang.Integer. The + constraint facets for this type restrict the valid values of this + type to easily fit within Java primitive datatype int. + + + Given the value range of an xsd:integer, it is mapped to + java.math.BigInteger by default. When one considers the + constaining facets for this type are between 10000..99999, + it is safe to bind this simple type directly to the + Java datatype "int" using the following customization. + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/datatypeconverter/sample.meta b/scripts/jaxb-ri/samples/datatypeconverter/sample.meta new file mode 100644 index 0000000..a18a910 --- /dev/null +++ b/scripts/jaxb-ri/samples/datatypeconverter/sample.meta @@ -0,0 +1,30 @@ + + + + + datatypeconverter (formerly SampleApp7) + customization. + ]]> + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/datatypeconverter/src/Main.java b/scripts/jaxb-ri/samples/datatypeconverter/src/Main.java new file mode 100644 index 0000000..6f0050e --- /dev/null +++ b/scripts/jaxb-ri/samples/datatypeconverter/src/Main.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBElement; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; + +// import java content classes generated by binding compiler +import primer.myPo.*; + +/* + * $Id: Main.java,v 1.1 2007-12-05 00:49:22 kohsuke Exp $ + */ +public class Main { + + // This sample application demonstrates how to modify a java content + // tree and marshal it back to a xml data. This example demonstrates + // customiation within the schema file, po.xsd, and the impact that these + // customizations have on the schema derived Java representation. + + public static void main( String[] args ) { + try { + // create a JAXBContext capable of handling classes generated into + // the primer.po package + JAXBContext jc = JAXBContext.newInstance( "primer.myPo" ); + + // create an Unmarshaller + Unmarshaller u = jc.createUnmarshaller(); + + // unmarshal a po instance document into a tree of Java content + // objects composed of classes from the primer.myPo package. + JAXBElement poe = + (JAXBElement)u.unmarshal( new FileInputStream( "po.xml" ) ); + POType po = (POType)poe.getValue(); + + // change the billto address + USAddress address = po.getBillTo(); + address.setToName( "John Bob" ); + address.setStreet( "242 Main Street" ); + address.setCity( "Beverly Hills" ); + address.setState(USState.CA); + address.setZipCode(90210); + + USState purchaseState = address.getState(); + ListIterator iter = po.getItems().getItem().listIterator(); + while( iter.hasNext()) { + + // update to 20% off sale price + Items.Item item = (Items.Item)iter.next(); + item.setPrice(item.getPrice().multiply(new BigDecimal("0.80"))); + + //Calculate sales tax for specific states + if (purchaseState == USState.MA) { + item.setPrice(item.getPrice().multiply(new BigDecimal("1.05"))); + } else if (purchaseState == USState.CA) { + item.setPrice(item.getPrice().multiply(new BigDecimal("1.06"))); + } + item.setPrice(item.getPrice().setScale(2, BigDecimal.ROUND_DOWN)); + } + + // create a Marshaller and marshal to a file + Marshaller m = jc.createMarshaller(); + m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); + m.marshal( poe, System.out ); + + } catch( JAXBException je ) { + je.printStackTrace(); + } catch( IOException ioe ) { + ioe.printStackTrace(); + } + } +} diff --git a/scripts/jaxb-ri/samples/dtd/build.golden.regexp b/scripts/jaxb-ri/samples/dtd/build.golden.regexp new file mode 100644 index 0000000..85f3e37 --- /dev/null +++ b/scripts/jaxb-ri/samples/dtd/build.golden.regexp @@ -0,0 +1,27 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \Kohsuke Kawaguchi\<\/name\> + \[java\] \kohsuke\.kawaguchi@sun\.com\<\/email\> + \[java\] \<\/nameCard\> + \[java\] \ + \[java\] \Ryan Shoemaker\<\/name\> + \[java\] \ryan\.shoemaker@sun\.com\<\/email\> + \[java\] \somewhere\<\/address\> + \[java\] \<\/nameCard\> + \[java\] \<\/nameCards\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/dtd/build.xml b/scripts/jaxb-ri/samples/dtd/build.xml new file mode 100644 index 0000000..7c43735 --- /dev/null +++ b/scripts/jaxb-ri/samples/dtd/build.xml @@ -0,0 +1,76 @@ + + + + + + This sample application illustrate some of the DTD support available in + the JAXB RI's extension mode. Please refer to the <a href="vendor.html> + Vendor Extensions</a> page for more detail. + + If you encounter "External parsing is disabled" error + please set system property enableExternalEntityProcessing=true + For example: + export ANT_OPTS="-DenableExternalEntityProcessing=true" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/dtd/nameCard.dtd b/scripts/jaxb-ri/samples/dtd/nameCard.dtd new file mode 100644 index 0000000..8b15088 --- /dev/null +++ b/scripts/jaxb-ri/samples/dtd/nameCard.dtd @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/scripts/jaxb-ri/samples/dtd/nameCard.jaxb b/scripts/jaxb-ri/samples/dtd/nameCard.jaxb new file mode 100644 index 0000000..1048430 --- /dev/null +++ b/scripts/jaxb-ri/samples/dtd/nameCard.jaxb @@ -0,0 +1,29 @@ + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/dtd/sample.meta b/scripts/jaxb-ri/samples/dtd/sample.meta new file mode 100644 index 0000000..9632a71 --- /dev/null +++ b/scripts/jaxb-ri/samples/dtd/sample.meta @@ -0,0 +1,34 @@ + + + + + dtd + + Vendor Extensions page for more detail. + ]]> + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/dtd/src/DTDSample.java b/scripts/jaxb-ri/samples/dtd/src/DTDSample.java new file mode 100644 index 0000000..2f0a3de --- /dev/null +++ b/scripts/jaxb-ri/samples/dtd/src/DTDSample.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.File; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; + +/** + * + * + * @author + * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) + */ +public class DTDSample { + + public static void main(String[] args) throws Exception { + // in this example, I skip the error check entirely + // for the sake of simplicity. In reality, you should + // do a better job of handling errors. + for( int i=0; i + + + + Kohsuke Kawaguchi + kohsuke.kawaguchi@sun.com + + + Ryan Shoemaker + ryan.shoemaker@sun.com +
somewhere
+
+
diff --git a/scripts/jaxb-ri/samples/element-substitution/build.golden.regexp b/scripts/jaxb-ri/samples/element-substitution/build.golden.regexp new file mode 100644 index 0000000..b3d1ba5 --- /dev/null +++ b/scripts/jaxb-ri/samples/element-substitution/build.golden.regexp @@ -0,0 +1,40 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] .* is not found and thus excluded from the dependency check + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] Unmarshalled xml element tag is\:\{http\:\/\/example\.org\}folder + \[java\] Processing headers\.\.\. + \[java\] OrderHeader info\:Order specfic comment + \[java\] InvoiceHeader info\:Invoice specfic comment + \[java\] BidHeader info\:Bid specfic comment + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \A comment\<\/generalComment\> + \[java\] \Order specfic comment\<\/orderInfo\> + \[java\] \<\/ns2\:orderHeaderE\> + \[java\] \ + \[java\] \A comment\<\/generalComment\> + \[java\] \Invoice specfic comment\<\/invoiceInfo\> + \[java\] \<\/ns2\:invoiceHeaderE\> + \[java\] \ + \[java\] \A comment\<\/generalComment\> + \[java\] \Bid specfic comment\<\/bidInfo\> + \[java\] \<\/ns2\:bidHeaderE\> + \[java\] \ + \[java\] \New Comment\<\/generalComment\> + \[java\] \New Invoice Info\<\/invoiceInfo\> + \[java\] \<\/ns2\:invoiceHeaderE\> + \[java\] \<\/ns2\:folder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/element-substitution/build.xml b/scripts/jaxb-ri/samples/element-substitution/build.xml new file mode 100644 index 0000000..bbd8282 --- /dev/null +++ b/scripts/jaxb-ri/samples/element-substitution/build.xml @@ -0,0 +1,69 @@ + + + + + + This sample application illustrates how W3C XML Schema substitution + groups are supported in JAXB RI's extension mode. Please refer to the + <a href="vendor.html">Vendor Extensions</a> page for more detail. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/element-substitution/folder.xml b/scripts/jaxb-ri/samples/element-substitution/folder.xml new file mode 100644 index 0000000..9a7dae3 --- /dev/null +++ b/scripts/jaxb-ri/samples/element-substitution/folder.xml @@ -0,0 +1,27 @@ + + + + + + A comment + Order specfic comment + + + A comment + Invoice specfic comment + + + A comment + Bid specfic comment + + diff --git a/scripts/jaxb-ri/samples/element-substitution/folder.xsd b/scripts/jaxb-ri/samples/element-substitution/folder.xsd new file mode 100644 index 0000000..f2b8d79 --- /dev/null +++ b/scripts/jaxb-ri/samples/element-substitution/folder.xsd @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/element-substitution/readme.txt b/scripts/jaxb-ri/samples/element-substitution/readme.txt new file mode 100644 index 0000000..4192484 --- /dev/null +++ b/scripts/jaxb-ri/samples/element-substitution/readme.txt @@ -0,0 +1,34 @@ +This sample app illustrates the use of element substitution (via substitution +groups). The schema, folder.xsd, defines an element named "folder" that can +contain a sequence of "document" elements. The schema also allows the "document" +elements to contain interchangeable "header" elements defined by a substitution +group. In the JAXB client code, you can see logic that iterates over all of +the "document" objects contained in the root "folder" and performs custom +processing depending on the type of the "header". + +Please note: + + o This example DOES NOT have anything to do with W3C XML Schema type substitution. + Element substitution and type substitution are commonly mistaken features in + schema - for a complete discussion of the differences, please refer to the + JAXB interest archive: + + https://javaee.groups.io/g/metro + + Support for type substitution will be available in the next public release of + the JAXB RI v1.0.2, which will be part of JWSDP v1.3. + + o Support for element substitution in the JAXB RI is only available in extension + mode which is enabled via the xjc commandline switch "-extension" or the xjc + ant task "extension" attribute. Please refer to the JAXB RI Release Notes + for complete information about running xjc: + + http://java.sun.com/webservices/docs/1.2/jaxb/xjc.html + + o Element substitution is currently supported in JAXB v1.0.1 (JWSDP v1.2), but + this sample application did not make it into the release. + + o JAXB v1.0.1 had a bug that would cause the marshaller to hang if the + substitution group had minOccurs > 1, but this has been fixed in JAXB v1.0.2 + + http://developer.java.sun.com/developer/bugParade/bugs/4889239.html \ No newline at end of file diff --git a/scripts/jaxb-ri/samples/element-substitution/sample.meta b/scripts/jaxb-ri/samples/element-substitution/sample.meta new file mode 100644 index 0000000..15d8d37 --- /dev/null +++ b/scripts/jaxb-ri/samples/element-substitution/sample.meta @@ -0,0 +1,32 @@ + + + + + element-substitution + Vendor Extensions page for more detail. + ]]> + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/element-substitution/src/Main.java b/scripts/jaxb-ri/samples/element-substitution/src/Main.java new file mode 100644 index 0000000..a8c1cb0 --- /dev/null +++ b/scripts/jaxb-ri/samples/element-substitution/src/Main.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.FileInputStream; +import java.io.IOException; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBElement; +import jakarta.xml.bind.JAXBIntrospector; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; + +// import java content classes generated by binding compiler +import org.example.*; + +/* + * $Id: Main.java,v 1.1 2007-12-05 00:49:23 kohsuke Exp $ + */ + +public class Main { + + // This sample application demonstrates how to modify a java content + // tree and marshal it back to a xml data + + public static void main( String[] args ) { + try { + // create a JAXBContext capable of handling classes generated into + // the org.example package + JAXBContext jc = JAXBContext.newInstance( "org.example" ); + + // create an Unmarshaller + Unmarshaller u = jc.createUnmarshaller(); + + // unmarshal a po instance document into a tree of Java content + // objects composed of classes from the primer.po package. + Object folderE = u.unmarshal( new FileInputStream( "folder.xml" ) ); + + // get XML content. + // normalize that unmarshal returns either JAXBElement OR + // class annotated with @XmlRootElement. + Folder folder = (Folder)(folderE instanceof JAXBElement ? + ((JAXBElement)folderE).getValue() : + folderE); + + JAXBIntrospector inspect = jc.createJAXBIntrospector(); + System.out.println("Unmarshalled xml element tag is:" + inspect.getElementName(folderE)); + + System.out.println("Processing headers..."); + ObjectFactory of = new ObjectFactory(); + for( JAXBElement hdrE : folder.getHeaderE()) { + Header hdr = hdrE.getValue(); + if (hdr instanceof OrderHeader) { + OrderHeader oh= (OrderHeader)hdr; + System.out.println("OrderHeader info:" + + oh.getOrderInfo()); + } else if (hdr instanceof InvoiceHeader) { + InvoiceHeader ih = (InvoiceHeader)hdr; + System.out.println("InvoiceHeader info:" + + ih.getInvoiceInfo()); + } else if (hdr instanceof BidHeader ) { + BidHeader bh= (BidHeader)hdr; + System.out.println("BidHeader info:" + + bh.getBidInfo()); + } + } + + InvoiceHeader ih = of.createInvoiceHeader(); + ih.setGeneralComment("New Comment"); + ih.setInvoiceInfo("New Invoice Info"); + JAXBElement newHdr = of.createInvoiceHeaderE(ih); + folder.getHeaderE().add(newHdr); + + // create a Marshaller and marshal to a file + Marshaller m = jc.createMarshaller(); + m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); + m.marshal( folderE, System.out ); + + } catch( JAXBException je ) { + je.printStackTrace(); + } catch( IOException ioe ) { + ioe.printStackTrace(); + } + } +} diff --git a/scripts/jaxb-ri/samples/external-customize/binding.xjb b/scripts/jaxb-ri/samples/external-customize/binding.xjb new file mode 100644 index 0000000..baed0c1 --- /dev/null +++ b/scripts/jaxb-ri/samples/external-customize/binding.xjb @@ -0,0 +1,88 @@ + + + + + + + + + Package level documentation for generated package primer.myPo.]]> + + + + + + + + + + A <b>Purchase Order</b> consists of addresses and items. + + + + + + USAddress.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/external-customize/build.golden.regexp b/scripts/jaxb-ri/samples/external-customize/build.golden.regexp new file mode 100644 index 0000000..62250cc --- /dev/null +++ b/scripts/jaxb-ri/samples/external-customize/build.golden.regexp @@ -0,0 +1,49 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \Alice Smith\<\/name\> + \[java\] \123 Maple Street\<\/street\> + \[java\] \Cambridge\<\/city\> + \[java\] \MA\<\/state\> + \[java\] \12345\<\/zip\> + \[java\] \<\/shipTo\> + \[java\] \ + \[java\] \John Bob\<\/name\> + \[java\] \242 Main Street\<\/street\> + \[java\] \Beverly Hills\<\/city\> + \[java\] \CA\<\/state\> + \[java\] \90210\<\/zip\> + \[java\] \<\/billTo\> + \[java\] \ + \[java\] \ + \[java\] \Nosferatu \- Special Edition \(1929\)\<\/productName\> + \[java\] \5\<\/quantity\> + \[java\] \16\.95\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \The Mummy \(1959\)\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \16\.94\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \Godzilla and Mothra\: Battle for Earth\/Godzilla vs\. King Ghidora\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \23\.70\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \<\/items\> + \[java\] \<\/purchaseOrder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/external-customize/build.xml b/scripts/jaxb-ri/samples/external-customize/build.xml new file mode 100644 index 0000000..d29ec33 --- /dev/null +++ b/scripts/jaxb-ri/samples/external-customize/build.xml @@ -0,0 +1,69 @@ + + + + + + This sample application is identical to the datatypeconverter sample + application (formerly SampleApp7) except that the binding customizations + are contained in an external binding file. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/external-customize/po.xml b/scripts/jaxb-ri/samples/external-customize/po.xml new file mode 100644 index 0000000..f3a10ae --- /dev/null +++ b/scripts/jaxb-ri/samples/external-customize/po.xml @@ -0,0 +1,46 @@ + + + + + + Alice Smith + 123 Maple Street + Cambridge + MA + 12345 + + + Robert Smith + 8 Oak Avenue + Cambridge + MA + 12345 + + + + Nosferatu - Special Edition (1929) + 5 + 19.99 + + + The Mummy (1959) + 3 + 19.98 + + + Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora + 3 + 27.95 + + + diff --git a/scripts/jaxb-ri/samples/external-customize/po.xsd b/scripts/jaxb-ri/samples/external-customize/po.xsd new file mode 100644 index 0000000..536449e --- /dev/null +++ b/scripts/jaxb-ri/samples/external-customize/po.xsd @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/external-customize/sample.meta b/scripts/jaxb-ri/samples/external-customize/sample.meta new file mode 100644 index 0000000..73e9392 --- /dev/null +++ b/scripts/jaxb-ri/samples/external-customize/sample.meta @@ -0,0 +1,30 @@ + + + + + external-customize (formerly SampleApp8) + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/external-customize/src/Main.java b/scripts/jaxb-ri/samples/external-customize/src/Main.java new file mode 100644 index 0000000..7f4e9f3 --- /dev/null +++ b/scripts/jaxb-ri/samples/external-customize/src/Main.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBElement; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; + +// import java content classes generated by binding compiler +import primer.myPo.*; + +/* + * $Id: Main.java,v 1.1 2007-12-05 00:49:24 kohsuke Exp $ + */ +public class Main { + + // This sample application demonstrates how to modify a java content + // tree and marshal it back to a xml data. This example demonstrates + // customiation within the schema file, po.xsd, and the impact that these + // customizations have on the schema derived Java representation. + + public static void main( String[] args ) { + try { + // create a JAXBContext capable of handling classes generated into + // the primer.po package + JAXBContext jc = JAXBContext.newInstance( "primer.myPo" ); + + // create an Unmarshaller + Unmarshaller u = jc.createUnmarshaller(); + + // unmarshal a po instance document into a tree of Java content + // objects composed of classes from the primer.myPo package. + JAXBElement poe = + (JAXBElement)u.unmarshal( new FileInputStream( "po.xml" ) ); + POType po = (POType)poe.getValue(); + + // change the billto address + USAddress address = po.getBillTo(); + address.setToName( "John Bob" ); + address.setStreet( "242 Main Street" ); + address.setCity( "Beverly Hills" ); + address.setState(USState.CA); + address.setZipCode(90210); + + USState purchaseState = address.getState(); + ListIterator iter = po.getItems().getItem().listIterator(); + while( iter.hasNext()) { + + // update to 20% off sale price + Items.Item item = (Items.Item)iter.next(); + item.setPrice(item.getPrice().multiply(new BigDecimal("0.80"))); + + //Calculate sales tax for specific states + if (purchaseState == USState.MA) { + item.setPrice(item.getPrice().multiply(new BigDecimal("1.05"))); + } else if (purchaseState == USState.CA) { + item.setPrice(item.getPrice().multiply(new BigDecimal("1.06"))); + } + item.setPrice(item.getPrice().setScale(2, BigDecimal.ROUND_DOWN)); + } + + // create a Marshaller and marshal to a file + Marshaller m = jc.createMarshaller(); + m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); + m.marshal( poe, System.out ); + + } catch( JAXBException je ) { + je.printStackTrace(); + } catch( IOException ioe ) { + ioe.printStackTrace(); + } + } +} diff --git a/scripts/jaxb-ri/samples/fix-collides/binding.xjb b/scripts/jaxb-ri/samples/fix-collides/binding.xjb new file mode 100644 index 0000000..69c872d --- /dev/null +++ b/scripts/jaxb-ri/samples/fix-collides/binding.xjb @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/fix-collides/build.golden.regexp b/scripts/jaxb-ri/samples/fix-collides/build.golden.regexp new file mode 100644 index 0000000..a842310 --- /dev/null +++ b/scripts/jaxb-ri/samples/fix-collides/build.golden.regexp @@ -0,0 +1,21 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \34\<\/foo\> + \[java\] \35\<\/Class\> + \[java\] \2149\<\/zip\> + \[java\] \<\/FooBar\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/fix-collides/build.xml b/scripts/jaxb-ri/samples/fix-collides/build.xml new file mode 100644 index 0000000..2a22792 --- /dev/null +++ b/scripts/jaxb-ri/samples/fix-collides/build.xml @@ -0,0 +1,71 @@ + + + + + + Another binding customization example that illustrates how to resolve + name conflicts. Running this sample without the binding file will + result in name collisions (see readme.txt) . Running "ant" will use + the binding customizations to resolve the name conflicts while + compiling the schema. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/fix-collides/example.xml b/scripts/jaxb-ri/samples/fix-collides/example.xml new file mode 100644 index 0000000..3b1800c --- /dev/null +++ b/scripts/jaxb-ri/samples/fix-collides/example.xml @@ -0,0 +1,18 @@ + + + + 34 + 35 + 02149 + + diff --git a/scripts/jaxb-ri/samples/fix-collides/example.xsd b/scripts/jaxb-ri/samples/fix-collides/example.xsd new file mode 100644 index 0000000..98b3a9c --- /dev/null +++ b/scripts/jaxb-ri/samples/fix-collides/example.xsd @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/fix-collides/readme.txt b/scripts/jaxb-ri/samples/fix-collides/readme.txt new file mode 100644 index 0000000..3a7bd70 --- /dev/null +++ b/scripts/jaxb-ri/samples/fix-collides/readme.txt @@ -0,0 +1,27 @@ + +This sample illustrates how to resolve naming collisions for Schema +to Java databinding. JAXB schema annotations are used to +customize the XSD to Java databinding to resolve the naming collisions. + +When this example is compiled without the binding file, +the following errors are generated. + + [xjc] [ERROR] Property name "Class" is reserved by java.lang.Object. + [xjc] line 19 of file:fix-collides/example +.xsd + [xjc] [ERROR] Property "Zip" is already defined. + [xjc] line 20 of file:fix-collides/example +.xsd + [xjc] [ERROR] The following location is relevant to the above error + [xjc] line 22 of file:fix-collides/example +.xsd + +The ant task for this sample includes the binding file, binding.xjb, +that contains JAXB schema annotations that resolve the name +collisions that occur in this sample. The naming collisions occur +as part of databinding since XML Schema defines 6 unique namespaces +and these are being mapped into one unique namespace within Java +program elements. The JAXB specification details additional +reasons for naming collisions in Appendix Section D.2 "Collisions and +Conflicts". + diff --git a/scripts/jaxb-ri/samples/fix-collides/sample.meta b/scripts/jaxb-ri/samples/fix-collides/sample.meta new file mode 100644 index 0000000..2cdbb7e --- /dev/null +++ b/scripts/jaxb-ri/samples/fix-collides/sample.meta @@ -0,0 +1,33 @@ + + + + + fix-collides (formerly part of SampleApp9) + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/fix-collides/src/Main.java b/scripts/jaxb-ri/samples/fix-collides/src/Main.java new file mode 100644 index 0000000..4b2ca82 --- /dev/null +++ b/scripts/jaxb-ri/samples/fix-collides/src/Main.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.FileInputStream; +import java.io.IOException; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; + +// import java content classes generated by binding compiler +import example.*; + +/* + * $Id: Main.java,v 1.2 2009-11-11 14:17:30 pavel_bucek Exp $ + */ + +public class Main { + + // This sample application demonstrates how to modify a collection + // in a java content tree and marshal it back to xml data + + public static void main( String[] args ) { + try { + // create a JAXBContext capable of handling classes generated into + // the example package + JAXBContext jc = JAXBContext.newInstance( "example" ); + + // create an Unmarshaller + Unmarshaller u = jc.createUnmarshaller(); + + // unmarshal a FooBar instance document into a tree of Java content + // objects composed of classes from the example package. + Object fbe = u.unmarshal( new FileInputStream( "example.xml" ) ); + + // create a Marshaller and marshal to a file + Marshaller m = jc.createMarshaller(); + m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); + m.marshal( fbe, System.out ); + + } catch( JAXBException je ) { + je.printStackTrace(); + } catch( IOException ioe ) { + ioe.printStackTrace(); + } + } +} diff --git a/scripts/jaxb-ri/samples/inline-customize/build.golden.regexp b/scripts/jaxb-ri/samples/inline-customize/build.golden.regexp new file mode 100644 index 0000000..b77cff1 --- /dev/null +++ b/scripts/jaxb-ri/samples/inline-customize/build.golden.regexp @@ -0,0 +1,50 @@ + +compile\: + \[mkdir\] Created dir\: .* + \[javac\] Compiling 1 source file to .* + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \Alice Smith\<\/name\> + \[java\] \123 Maple Street\<\/street\> + \[java\] \Cambridge\<\/city\> + \[java\] \MA\<\/state\> + \[java\] \12345\<\/zip\> + \[java\] \<\/shipTo\> + \[java\] \ + \[java\] \John Bob\<\/name\> + \[java\] \242 Main Street\<\/street\> + \[java\] \Beverly Hills\<\/city\> + \[java\] \CA\<\/state\> + \[java\] \90210\<\/zip\> + \[java\] \<\/billTo\> + \[java\] \ + \[java\] \ + \[java\] \Nosferatu \- Special Edition \(1929\)\<\/productName\> + \[java\] \5\<\/quantity\> + \[java\] \16\.95\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \The Mummy \(1959\)\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \16\.94\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \Godzilla and Mothra\: Battle for Earth\/Godzilla vs\. King Ghidora\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \23\.70\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \<\/items\> + \[java\] \<\/purchaseOrder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/inline-customize/build.xml b/scripts/jaxb-ri/samples/inline-customize/build.xml new file mode 100644 index 0000000..02e5e0f --- /dev/null +++ b/scripts/jaxb-ri/samples/inline-customize/build.xml @@ -0,0 +1,77 @@ + + + + + + This sample application demonstrates how to customize the default + binding produced by the XJC binding compiler. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/inline-customize/po.xml b/scripts/jaxb-ri/samples/inline-customize/po.xml new file mode 100644 index 0000000..f3a10ae --- /dev/null +++ b/scripts/jaxb-ri/samples/inline-customize/po.xml @@ -0,0 +1,46 @@ + + + + + + Alice Smith + 123 Maple Street + Cambridge + MA + 12345 + + + Robert Smith + 8 Oak Avenue + Cambridge + MA + 12345 + + + + Nosferatu - Special Edition (1929) + 5 + 19.99 + + + The Mummy (1959) + 3 + 19.98 + + + Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora + 3 + 27.95 + + + diff --git a/scripts/jaxb-ri/samples/inline-customize/po.xsd b/scripts/jaxb-ri/samples/inline-customize/po.xsd new file mode 100644 index 0000000..4860f34 --- /dev/null +++ b/scripts/jaxb-ri/samples/inline-customize/po.xsd @@ -0,0 +1,235 @@ + + + + + + jxb:globalBindings element documentation: + To illustrate all global controllable settings, listed all + attributes with their default values except for @collectionType. + + @fixedAttributeAsConstantProperty set to true indicates that + all fixed attributes should be bound to Java constants. By + default, fixed attributes are just mapped to either simple + or collection property, which ever is more appropriate. + + @collectionType set to java.util.Vector specifies that all + lists in the generated implementation classes should be represented + internally as vectors. + + If @typesafeEnumBase was set to"xsd:string", it is a global way to specify + that all simple type definitions deriving directly or indirectly + from "xsd:string" and having enumeration facets should be bound + to a typesafe enum. The typesafeEnumClass customization in simple + type definition of USState would be redundant with this suggested + change. If @typesafeEnumBase was set to empty string, "", no simple + type definitions would ever be bound to a typesafe enum class by + default binding. + + jxb:schemaBindings documentation: + child element jxb:package specifes a java package for the Java + representation generated for this schema. + + child element jxb:nameXmlTransform/jxb:elementName specifies that + all Java element interfaces generated should have "Element" + appended to names generated by default. For this schema, + customization results in element interfaces CommentElement and + PurchaseOrderElement being generated. Default binding would + generate element interface Comment and PurchaseOrder. + jxb:nameXmlTransform has children elements for the symbol space + typeName, anonymousTypeName and modelGroupName. + + + + + + + Package level documentation for generated package primer.myPo.]]> + + + + + + + + + + + + + + + + A <b>Purchase Order</b> consists of addresses and items. + + + + + + + + + + + + + + + + + + + + USAddress.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + JAXB customization documentation: + jaxb:property @generateIsSetMethod results in additional property + methods,isSetQuantity and unsetQuantity, being generated to + to be able to distinguish between schema defaulted value + and values occuring explicitly within an instance document. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is a localized way to map this simple type definition + to a typesafe enum class. See jxb:globalBindings + @typesafeEnumBase above for a global way to accomplish this + for all simple type definitions similar to this one. + + + + + + + + + + + + + + + + Legal zip codes are limited to 5 digits, extended Zip Code not + supported. + + JAXB customization: jaxb:javaType binding declaration overrides + default binding of this type to a java.lang.Integer. The + constraint facets for this type restrict the valid values of this + type to easily fit within Java primitive datatype int. + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/inline-customize/sample.meta b/scripts/jaxb-ri/samples/inline-customize/sample.meta new file mode 100644 index 0000000..4e485fd --- /dev/null +++ b/scripts/jaxb-ri/samples/inline-customize/sample.meta @@ -0,0 +1,35 @@ + + + + + inline-customize (formerly SampleApp6) + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/inline-customize/src/Main.java b/scripts/jaxb-ri/samples/inline-customize/src/Main.java new file mode 100644 index 0000000..c3b8ae7 --- /dev/null +++ b/scripts/jaxb-ri/samples/inline-customize/src/Main.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBElement; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; + +// import java content classes generated by binding compiler +import primer.myPo.*; + +/* + * $Id: Main.java,v 1.1 2007-12-05 00:49:25 kohsuke Exp $ + */ + +public class Main { + + // This sample application demonstrates how to modify a java content + // tree and marshal it back to a xml data. This example demonstrates + // customiation within the schema file, po.xsd, and the impact that these + // customizations have on the schema derived Java representation. + + public static void main( String[] args ) { + try { + // create a JAXBContext capable of handling classes generated into + // the primer.po package + JAXBContext jc = JAXBContext.newInstance( "primer.myPo" ); + + // create an Unmarshaller + Unmarshaller u = jc.createUnmarshaller(); + + // unmarshal a po instance document into a tree of Java content + // objects composed of classes from the primer.myPo package. + JAXBElement poe = + (JAXBElement)u.unmarshal( new FileInputStream( "po.xml" ) ); + POType po = (POType)poe.getValue(); + + // change the billto address + USAddress address = po.getBillTo(); + address.setToName( "John Bob" ); + address.setStreet( "242 Main Street" ); + address.setCity( "Beverly Hills" ); + address.setState(USState.CA); + address.setZipCode( 90210); + + USState purchaseState = address.getState(); + ListIterator iter = po.getItems().getItem().listIterator(); + while( iter.hasNext()) { + + // update to 20% off sale price + Items.Item item = (Items.Item)iter.next(); + item.setPrice(item.getPrice().multiply(new BigDecimal("0.80"))); + + //Calculate sales tax for specific states + if (purchaseState == USState.MA) { + item.setPrice(item.getPrice().multiply(new BigDecimal("1.05"))); + } else if (purchaseState == USState.CA) { + item.setPrice(item.getPrice().multiply(new BigDecimal("1.06"))); + } + item.setPrice(item.getPrice().setScale(2, BigDecimal.ROUND_DOWN)); + } + + // create a Marshaller and marshal to a file + Marshaller m = jc.createMarshaller(); + m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); + m.marshal( poe, System.out ); + + } catch( JAXBException je ) { + je.printStackTrace(); + } catch( IOException ioe ) { + ioe.printStackTrace(); + } + } +} diff --git a/scripts/jaxb-ri/samples/inline-customize/src/primer/MyDatatypeConverter.java b/scripts/jaxb-ri/samples/inline-customize/src/primer/MyDatatypeConverter.java new file mode 100644 index 0000000..fc8de59 --- /dev/null +++ b/scripts/jaxb-ri/samples/inline-customize/src/primer/MyDatatypeConverter.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package primer; + +import java.math.BigInteger; +import jakarta.xml.bind.DatatypeConverter; + +public class MyDatatypeConverter { + + public static short parseIntegerToShort(String value) { + BigInteger result = DatatypeConverter.parseInteger(value); + return (short)(result.intValue()); + } + + public static String printShortToInteger(short value) { + BigInteger result = BigInteger.valueOf(value); + return DatatypeConverter.printInteger(result); + } + + public static int parseIntegerToInt(String value) { + BigInteger result = DatatypeConverter.parseInteger(value); + return result.intValue(); + } + + public static String printIntToInteger(int value) { + BigInteger result = BigInteger.valueOf(value); + return DatatypeConverter.printInteger(result); + } +}; diff --git a/scripts/jaxb-ri/samples/j2s-create-marshal/build.golden.regexp b/scripts/jaxb-ri/samples/j2s-create-marshal/build.golden.regexp new file mode 100644 index 0000000..44cdef4 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-create-marshal/build.golden.regexp @@ -0,0 +1,44 @@ + +compile\: + \[echo\] Generating schemas\.\.\. + \[mkdir\] Created dir\: .* +\[schemagen\] Generating schema from \d+ source files + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \John Doe\<\/name\> + \[java\] \Sr\. Widget Designer\<\/title\> + \[java\] \Acme\, Inc\.\<\/company\> + \[java\] \ + \[java\] \123 Widget Way\<\/street\> + \[java\] \Anytown\<\/city\> + \[java\] \MA\<\/state\> + \[java\] \12345\<\/zip\> + \[java\] \<\/address\> + \[java\] \123\.456\.7890\<\/phone\> + \[java\] \123\.456\.7891\<\/fax\> + \[java\] \John\.Doe@Acme\.ORG\<\/email\> + \[java\] \<\/businessCard\> + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \John Doe\<\/name\> + \[java\] \Sr\. Widget Designer\<\/title\> + \[java\] \Acme\, Inc\.\<\/company\> + \[java\] \ + \[java\] \123 Widget Way\<\/street\> + \[java\] \Anytown\<\/city\> + \[java\] \MA\<\/state\> + \[java\] \12345\<\/zip\> + \[java\] \<\/address\> + \[java\] \123\.456\.7890\<\/phone\> + \[java\] \123\.456\.7891\<\/fax\> + \[java\] \John\.Doe@Acme\.ORG\<\/email\> + \[java\] \<\/businessCard\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/j2s-create-marshal/build.xml b/scripts/jaxb-ri/samples/j2s-create-marshal/build.xml new file mode 100644 index 0000000..1d93b67 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-create-marshal/build.xml @@ -0,0 +1,69 @@ + + + + + + This sample application demonstrates marshalling, unmarshalling and + unmarshal validation with existing Java classes annotated with + JAXB annotations. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-create-marshal/readme.txt b/scripts/jaxb-ri/samples/j2s-create-marshal/readme.txt new file mode 100644 index 0000000..f462cc7 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-create-marshal/readme.txt @@ -0,0 +1,10 @@ +This example illustrates java to schema databinding. +It demonstrates marshalling and unmarshalling of JAXB annotated +classes. Additionally, it demonstrates how to enable JAXP 1.3 +validation at unmarshal time using a schema file generated +from the JAXB mapped classes. + +The schema file, bc.xsd, was generated with the following commands: +% schemagen src/cardfile/*.java +% cp schema1.xsd bc.xsd + diff --git a/scripts/jaxb-ri/samples/j2s-create-marshal/sample.meta b/scripts/jaxb-ri/samples/j2s-create-marshal/sample.meta new file mode 100644 index 0000000..491aa39 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-create-marshal/sample.meta @@ -0,0 +1,28 @@ + + + + + Java to Schema Binding + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-create-marshal/src/Main.java b/scripts/jaxb-ri/samples/j2s-create-marshal/src/Main.java new file mode 100644 index 0000000..dfa0275 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-create-marshal/src/Main.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.File; +import java.io.FileOutputStream; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; +import cardfile.BusinessCard; +import cardfile.Address; +import jakarta.xml.bind.ValidationEvent; +import jakarta.xml.bind.util.ValidationEventCollector; +import jakarta.xml.bind.ValidationEventLocator; +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import javax.xml.validation.SchemaFactory; +import javax.xml.validation.Schema; +import org.xml.sax.SAXException; + +public class Main { + public static void main(String[] args) throws Exception { + final File f = new File("bcard.xml"); + + // Illustrate two methods to create JAXBContext for j2s binding. + // (1) by root classes newInstance(Class ...) + JAXBContext context1 = JAXBContext.newInstance(BusinessCard.class); + + // (2) by package, requires jaxb.index file in package cardfile. + // newInstance(String packageNames) + JAXBContext context2 = JAXBContext.newInstance("cardfile"); + + Marshaller m = context1.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + m.marshal(getCard(), System.out); + + // illustrate optional unmarshal validation. + Marshaller m2 = context1.createMarshaller(); + m2.marshal(getCard(), new FileOutputStream(f)); + Unmarshaller um = context2.createUnmarshaller(); + um.setSchema(getSchema("schema1.xsd")); + Object bce = um.unmarshal(f); + m.marshal(bce, System.out); + } + + /** returns a JAXP 1.3 schema by parsing the specified resource. */ + static Schema getSchema(String schemaResourceName) throws SAXException { + SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); + try { + return sf.newSchema(Main.class.getResource(schemaResourceName)); + } catch (SAXException se) { + // this can only happen if there's a deployment error and the resource is missing. + throw se; + } + } + + private static BusinessCard getCard() { + return new BusinessCard("John Doe", "Sr. Widget Designer", "Acme, Inc.", + new Address(null, "123 Widget Way", "Anytown", "MA", (short) 12345), "123.456.7890", + null, "123.456.7891", "John.Doe@Acme.ORG"); + } +} diff --git a/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/Address.java b/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/Address.java new file mode 100644 index 0000000..d5917a3 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/Address.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package cardfile; + +import jakarta.xml.bind.annotation.*; + +@XmlType +public class Address { + + private String name; + private String street; + private String city; + private String state; + private short zip; + + public Address() {} + + public Address(String name, String street, String city, String state, short zip) { + this.name = name; + this.street = street; + this.city = city; + this.state = state; + this.zip = zip; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public short getZip() { + return zip; + } + + public void setZip(short zip) { + this.zip = zip; + } + + public String toString() { + StringBuilder s = new StringBuilder(); + if(name!=null) s.append(name).append('\n'); + s.append(street).append('\n').append(city).append(", ").append(state).append(" ").append(zip); + return s.toString(); + } +} diff --git a/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/BusinessCard.java b/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/BusinessCard.java new file mode 100644 index 0000000..eb34ec4 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/BusinessCard.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package cardfile; + +import jakarta.xml.bind.annotation.*; + +@XmlRootElement +public class BusinessCard { + + private String name; + private String title; + private String company; + private Address address; + private String phone; + private String cellPhone; + private String fax; + private String email; + + public BusinessCard() {} + + public BusinessCard(String name, String title, String company, Address address, + String phone, String cellPhone, String fax, String email) { + this.name = name; + this.title = title; + this.company = company; + this.address = address; + this.phone = phone; + this.cellPhone = cellPhone; + this.fax = fax; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public String getFax() { + return fax; + } + + public void setFax(String fax) { + this.fax = fax; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getCellPhone() { + return cellPhone; + } + + public void setCellPhone(String cellPhone) { + this.cellPhone = cellPhone; + } + + public String toString() { + StringBuilder s = new StringBuilder(); + if(name!=null) s.append(name).append('\n'); + if(title!=null) s.append(title).append('\n'); + if(company!=null) s.append(company).append('\n'); + if(address!=null) s.append(address.toString()).append('\n'); + if(phone!=null) s.append("phone: ").append(phone).append('\n'); + if(cellPhone!=null) s.append("cell: ").append(cellPhone).append('\n'); + if(fax!=null) s.append("fax: ").append(fax).append('\n'); + if(email!=null) s.append(email).append('\n'); + return s.toString(); + } +} diff --git a/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/jaxb.index b/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/jaxb.index new file mode 100644 index 0000000..a400130 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/jaxb.index @@ -0,0 +1,2 @@ +BusinessCard +Address diff --git a/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/package-info.java b/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/package-info.java new file mode 100644 index 0000000..bde5671 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-create-marshal/src/cardfile/package-info.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +@XmlAccessorType(FIELD) +package cardfile; + +import jakarta.xml.bind.annotation.XmlAccessorType; +import static jakarta.xml.bind.annotation.XmlAccessType.FIELD; diff --git a/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/build.golden.regexp b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/build.golden.regexp new file mode 100644 index 0000000..2b5387d --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/build.golden.regexp @@ -0,0 +1,31 @@ + +compile\: + \[echo\] Generating schemas\.\.\. + \[mkdir\] Created dir\: .* +\[schemagen\] Generating schema from 3 source files + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling 4 source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \Robert Smith\<\/name\> + \[java\] \8 Oak Avenue\<\/street\> + \[java\] \Old Town\<\/city\> + \[java\] \PA\<\/state\> + \[java\] \95819\<\/zip\> + \[java\] \<\/billTo\> + \[java\] \ + \[java\] \Robert Smith\<\/name\> + \[java\] \8 Oak Avenue\<\/street\> + \[java\] \Old Town\<\/city\> + \[java\] \PA\<\/state\> + \[java\] \95819\<\/zip\> + \[java\] \<\/shipTo\> + \[java\] \<\/purchaseOrder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/build.xml b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/build.xml new file mode 100644 index 0000000..8b457b5 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/build.xml @@ -0,0 +1,70 @@ + + + + + + This sample application demonstrates the use of mapping annotations + @XmlAccessorOrder and @XmlType.propOrder in Java classes for ordering + properties and fields in Java to schema bindings. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/readme.txt b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/readme.txt new file mode 100644 index 0000000..cb6e3d8 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/readme.txt @@ -0,0 +1,119 @@ +-- Ordering of properties/fields + +-- Synopsis + This sample demonstrates the use of annotations @XmlAccessorOrder + and @XmlType.propOrder to dictate the order in which XML content + is marshalled/unmarshaled by a Java type. + + + +-- Details + +Java to Schema maps a JavaBean's properties and fields +to an XML Schema type. The class elements are mapped +to either an XML Schema complex type or an XML Schema simple +type. The default element order for a generated schema type +is currently unspecified, because Java reflection does not +impose a return order. Lack of reliable element ordering +impacts application portability. Two annotations for defining +schema element ordering are provided for applications that +wish to remain portable across JAXB Providers, @XmlAccessorOrder +and @XmlType.propOrder. + + +-- @XmlAccessorOrder + +@XmlAccessorOrder annotation imposes one of two element ordering +algorithms, XmlAccessOrder.UNDEFINED or XmlAccessOrder.ALPHABETICAL. +XmlAccessOrder.UNDEFINED is the default setting. The order is dependent +on the system's reflection implementation. XmlAccessOrder.ALPHABETICAL +orders the elements in lexicographic order as determined by +java.lang.String.CompareTo(String anotherString). + +@XmlAccessorOrder can be defined for annotation type ElementType.PACKAGE +or on a class object. When @XmlAccessorOrder is defined on a package, the +scope of the formatting rule is active for every class in the package. +When defined on a class the rule is active on the contents of that class. + +There can be multiple @XmlAccessorOrder annotations within a package. +The order of precedence is the inner most (class) annotation +takes precedence over the outter annotation. For example if +@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) is defined on a package +and @XmlAccessorOrder(XmlAccessOrder.UNDEFINED) is defined on a class +in that package the contents of the generated schema type for the class +would be in an unspecified order and the contents of the generated schema +type for evey other class in the package would be alphabetical order. + + + +-- @XmlType.propOrder + +@XmlType can be defined for a class. The annotation element propOrder() +in @XmlType allows the specification of the content order in the generated +schema type. When @XmlType.propOrder is used on a class to specify content +order, all public properties and public fields in the class must be specified +in the parameter list. Any public property or field not desired in the parameter +list must be annotated with @XmlAttribute or @XmlTransient. + +The default content order for @XmlType.propOrder is {} or {""}; not active. +In such cases the active @XmlAccessorOrder annotation takes precedence. When +class content order is specified by @XmlType.propOrder, it takes precedence +over any active @XmlAccessorOrder annotation on the class or package. If +@XmlAccessorOrder and @XmlType.propOrder(A, B, ...) annotations are specified +on a class, the propOrder always takes precedence no matter the order of +the annontation statements. For example in CODE A below the @XmlAccessorOrder +annotation preceeds @XmlType.propOrder and in CODE B @XmlType.propOrder preceeds +@XmlAccessorOrder. In both scenarios propOrder takes precedence and the identical +schema content is generated. + + + CODE A: + @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) + @XmlType(propOrder={"name", "city"}) + public class USAddress { + : + public String getCity() {return city;} + public void setCity(String city) {this.city = city;} + + public String getName() {return name;} + public void setName(String name) {this.name = name;} + : + } + + + CODE B: + @XmlType(propOrder={"name", "city"}) + @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) + public class USAddress { + : + public String getCity() {return city;} + public void setCity(String city) {this.city = city;} + + public String getName() {return name;} + public void setName(String name) {this.name = name;} + : + } + + + SCHEMA GENERATE + + + + + + + + +-- Code example + +The purchase order code example demonstrates the affects of schema content +ordering using @XmlAccessorOrder annotation at the package and class level, +and @XmlType.propOrder on a class. + +Class package-info.java defines @XmlAccessorOrder to be ALPHABETICAL for +the package. The public fields shipTo and billTo in class PurchaseOrderType +will be affected in the generated schema content order by this rule. Class +USAddress defines @XmlType.propOrder on the class. This demonstates user +defined property order superseding ALPHABETICAL order in the generated schema. + +The generated schema file can be found in directory schemas. diff --git a/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/sample.meta b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/sample.meta new file mode 100644 index 0000000..10e75cf --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/sample.meta @@ -0,0 +1,30 @@ + + + + + Ordering Properties and Fieldes in Java to Schema Bindings + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/Main.java b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/Main.java new file mode 100644 index 0000000..a359e3b --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/Main.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: Main.java,v 1.2 2009-11-11 14:17:33 pavel_bucek Exp $ + */ + + +import java.io.File; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; +import address.USAddress; +import address.PurchaseOrderType; + +public class Main { + public static void main(String[] args) throws Exception { + final File f = new File("po.xml"); + + // A Ship to type + USAddress shipto = new USAddress("Alice Smith", "123 Maple Street", + "Mill Valley", "CA", 90952); + + // A bill to type + USAddress billto = new USAddress("Robert Smith", "8 Oak Avenue", + "Old Town", "PA", 95819); + + // A purchaseOrder + PurchaseOrderType po = new PurchaseOrderType(); + po.billTo = billto; + po.shipTo = billto; + + // Demonstates shipping and billing data printed in the property + // order defined by the propOrder annotation element in class + // USAddress. + JAXBContext jc = JAXBContext.newInstance(PurchaseOrderType.class); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + m.marshal(po, System.out); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/address/PurchaseOrderType.java b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/address/PurchaseOrderType.java new file mode 100644 index 0000000..340f732 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/address/PurchaseOrderType.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: PurchaseOrderType.java,v 1.1 2007-12-05 00:49:27 kohsuke Exp $ + */ + + +package address; + +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name="purchaseOrder") +@XmlType(name="PurchaseOrderType") +public class PurchaseOrderType { + + public USAddress shipTo; + public USAddress billTo; + + public String toString() { + StringBuilder s = new StringBuilder(); + s.append("Ship To: "); + s.append(shipTo.toString()).append('\n'); + s.append("Bill To: "); + return s.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/address/USAddress.java b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/address/USAddress.java new file mode 100644 index 0000000..c273a89 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/address/USAddress.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: USAddress.java,v 1.1 2007-12-05 00:49:27 kohsuke Exp $ + */ + +package address; + +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlTransient; + +@XmlType(propOrder={"name", "street", "city" , "state", "zip"}) +public class USAddress { + + private String city; + private String name; + private String state; + private String street; + private int zip; + @XmlTransient public int sessionID; + + /** + * The zero arg constructor is used by JAXB Unmarshaller to create + * an instance of this type. + */ + + public USAddress() {} + + public USAddress(String name, String street, String city, String state, int zip) { + this.name = name; + this.street = street; + this.city = city; + this.state = state; + this.zip = zip; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public int getZip() { + return zip; + } + + public void setZip(int zip) { + this.zip = zip; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String toString() { + StringBuilder s = new StringBuilder(); + if(name!=null) s.append(name).append('\n'); + s.append(street).append('\n').append(city).append(", ").append(state).append(" ").append(zip); + return s.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/address/package-info.java b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/address/package-info.java new file mode 100644 index 0000000..32f3964 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAccessorOrder/src/address/package-info.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) +package address; + +import jakarta.xml.bind.annotation.XmlAccessorOrder; +import jakarta.xml.bind.annotation.XmlAccessOrder; diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/build.golden.regexp b/scripts/jaxb-ri/samples/j2s-xmlAdapter/build.golden.regexp new file mode 100644 index 0000000..e8bdf29 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/build.golden.regexp @@ -0,0 +1,29 @@ + +compile\: + \[echo\] Generating schemas\.\.\. + \[mkdir\] Created dir\: .* +\[schemagen\] Generating schema from 3 source files + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling 5 source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] KitchenWorldBasket\: + \[java\] key\: 288 value\: wooden spoon + \[java\] key\: 289 value\: salt and pepper shakers in yellow + \[java\] key\: 9027 value\: glasstop stove in black + \[java\] key\: 10424 value\: backsplash kit in black + + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \wooden spoon\<\/entry\> + \[java\] \salt and pepper shakers in yellow\<\/entry\> + \[java\] \glasstop stove in black\<\/entry\> + \[java\] \backsplash kit in black\<\/entry\> + \[java\] \<\/basket\> + \[java\] \<\/kitchenWorldBasket\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/build.xml b/scripts/jaxb-ri/samples/j2s-xmlAdapter/build.xml new file mode 100644 index 0000000..c04050c --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/build.xml @@ -0,0 +1,71 @@ + + + + + + This sample application demonstrates the use of interface XmlAdapter + and annotation XmlJavaTypeAdapter for custom marshaling/unmarshaling + XML content into/out of a Java type. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/readme.txt b/scripts/jaxb-ri/samples/j2s-xmlAdapter/readme.txt new file mode 100644 index 0000000..90b800d --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/readme.txt @@ -0,0 +1,121 @@ +-- Adapters for customized marshaling/unmarshaling + +-- Synopsis + This sample demonstrates the use of interface XmlAdapter + and annotation @XmlJavaTypeAdapter to provided a custom + mapping of XML content into and out of a HashMap (field) + that uses an 'int' as the key and a 'string' as the value. + + + +-- Details +Interface XmlAdapter and annotation @XmlJavaTypeAdapter are provided +for special processing of datatypes during the unmarshalling/marshalling +process. There are a variety of XML datatypes for which the representation +does not map easily into Java (e.g.,xs:DateTime and xs:Duration), and Java +types which do not map conveniently into XML representations for example +implementations of java.util.Collection (e.g., List) and java.util.Map +(e.g., HashMap) or for non-JavaBean classes. It is for these cases that +XmlAdapter and @XmlJavaTypeAdapter are provided. They provide a portable +mechanism for reading/writing XML content into and out of Java applications. + + +The XmlAdapter interface defines the methods for data reading/writing. + +/* + * ValueType - Java class that provides an XML representation + * of the data. It is the object that is used for + * marshalling and unmarshalling. + * + * BoundType - Java class that is used to process XML content. + */ +public abstract class XmlAdapter { + // Do-nothing constructor for the derived classes. + protected XmlAdapter() {} + + // Convert a value type to a bound type. + public abstract BoundType unmarshal(ValueType v); + + // Convert a bound type to a value type. + public abstract ValueType marshal(BoundType v); +} + + +Annotation @XmlJavaTypeAdapter is used to associate a particular +XmlAdapter implementation with a Target type, PACKAGE,FIELD, +METHOD,TYPE,or PARAMETER. + + +-- Example + This example demonstrates an XmlAdapter for mapping XML content + into and out of a (custom) HashMap. The HashMap object, basket + in class KitchenWorldBasket, uses a key of type 'int' and a value + of type 'String'. We want these datatypes to be reflected in the + XML content that is read and written. The XML content should + look like this. + + + glasstop stove in black + wooden spoon + + + + The default schema generated for Java type HashMap does not reflect + the desired format. + + + + + + + + + + + + + + + + + In the default HashMap schema, key and value are both elements and are + of datatype anyType. The XML content would look like this. + + + + 9027 + glasstop stove in black + + + 288 + wooden spoon + + + + To resolve this issue two Java classes were written that reflect the + needed schema format for unmarshalling/marshalling the content, + PurchaseList and PartEntry. Here is the XML schema generated for these + classes. + + + + + + + + + + + + + + + + + Class AdapterPurchaseListToHashMap implements the XmlAdapter interface. + In class KitchenWorldBasket @XmlJavaTypeAdapter is to used to pair + AdapterPurchaseListToHashMap with field HashMap basket. This pairing will + cause AdapterPurchaseListToHashMap's marshal/unmarshal method to be called + for any corresponding marshal/unmarshal action on KitchenWorldBasket. + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/sample.meta b/scripts/jaxb-ri/samples/j2s-xmlAdapter/sample.meta new file mode 100644 index 0000000..dc136b8 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/sample.meta @@ -0,0 +1,32 @@ + + + + + Adapters for custom marshaling/unmarshaling XML content + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/Main.java b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/Main.java new file mode 100644 index 0000000..5c05849 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/Main.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: Main.java,v 1.1 2007-12-05 00:49:28 kohsuke Exp $ + */ + + +import java.io.File; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; +import shoppingCart.KitchenWorldBasket; + +public class Main { + public static void main(String[] args) throws Exception { + JAXBContext jc = JAXBContext.newInstance(KitchenWorldBasket.class); + Unmarshaller u = jc.createUnmarshaller(); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + try { + KitchenWorldBasket kwBasket = (KitchenWorldBasket)u.unmarshal(new File("src/shoppingCartData.xml")); + + // Demonstrate adapter's unmarshal integrated data into HashMap properly + System.out.println(kwBasket.toString()); + + // Demonstate adapter's marshal writes the data properly + m.marshal(kwBasket, System.out); + } catch(jakarta.xml.bind.UnmarshalException e){ + System.out.println("Main: " + e); + } + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/AdapterPurchaseListToHashMap.java b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/AdapterPurchaseListToHashMap.java new file mode 100644 index 0000000..ac0abc3 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/AdapterPurchaseListToHashMap.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: AdapterPurchaseListToHashMap.java,v 1.1 2007-12-05 00:49:28 kohsuke Exp $ + */ + + +package shoppingCart; + +import java.util.HashMap; +import java.util.TreeMap; +import java.util.Iterator; +import jakarta.xml.bind.annotation.adapters.XmlAdapter; + +/* + * + * PurchaseList - ValueType + * HashMap - BoundType + */ +public class AdapterPurchaseListToHashMap extends XmlAdapter { + public AdapterPurchaseListToHashMap(){} + + // Convert a value type to a bound type. + // read xml content and put into Java class. + public HashMap unmarshal(PurchaseList v){ + HashMap aHashMap = new HashMap(); + int cnt = v.entry.size(); + for(int i=0; i < cnt; i++){ + PartEntry tmpE = (PartEntry)v.entry.get(i); + aHashMap.put(new Integer(tmpE.key), tmpE.value); + } + return aHashMap; + } + + // Convert a bound type to a value type. + // write Java content into class that generates desired XML + public PurchaseList marshal(HashMap v){ + PurchaseList pList = new PurchaseList(); + // For QA consistency order the output. + TreeMap tMap = new TreeMap(v); + for(Iterator i=tMap.keySet().iterator(); i.hasNext();){ + Integer tmpI = (Integer)i.next(); + pList.entry.add(new PartEntry(tmpI.intValue(), (String)tMap.get(tmpI))); + } + return pList; + } +} diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/KitchenWorldBasket.java b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/KitchenWorldBasket.java new file mode 100644 index 0000000..73465f9 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/KitchenWorldBasket.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: KitchenWorldBasket.java,v 1.1 2007-12-05 00:49:28 kohsuke Exp $ + */ + +package shoppingCart; + +import java.util.HashMap; +import java.util.TreeMap; +import java.util.Iterator; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import jakarta.xml.bind.annotation.XmlType; + +@XmlRootElement +@XmlType(name="KitchenWorldBasketType") +public class KitchenWorldBasket { + @XmlJavaTypeAdapter(AdapterPurchaseListToHashMap.class) + HashMap basket = new HashMap(); + + public KitchenWorldBasket(){} + public String toString(){ + StringBuilder buf = new StringBuilder(); + buf.append("KitchenWorldBasket:\n"); + + // For QA consistency order the output. + TreeMap tMap = new TreeMap(basket); + for(Iterator i=tMap.keySet().iterator(); i.hasNext();){ + Integer key = (Integer)i.next(); + buf.append("key: " + key.toString() + "\tvalue: " + tMap.get(key) +"\n"); + } + return buf.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/PartEntry.java b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/PartEntry.java new file mode 100644 index 0000000..5893189 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/PartEntry.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: PartEntry.java,v 1.1 2007-12-05 00:49:28 kohsuke Exp $ + */ + + +package shoppingCart; + +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlValue; + +public class PartEntry { + @XmlValue public String value; + @XmlAttribute public int key; + + public PartEntry(){} + public PartEntry(int tKey, String tValue){ + key = tKey; + value = tValue; + } + public String toString(){ + return "key=" + key +" value=" + value; + } +} + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/PurchaseList.java b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/PurchaseList.java new file mode 100644 index 0000000..0d10f38 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCart/PurchaseList.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: PurchaseList.java,v 1.1 2007-12-05 00:49:28 kohsuke Exp $ + */ + +package shoppingCart; + +import java.util.List; +import java.util.Vector; +import java.util.HashMap; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlType; + +@XmlRootElement +@XmlType(name="PurchaseListType") +public class PurchaseList { + //- this must be a public field for the adapter to function + //- When it is public the generated xml uses the variable name + //- as the element tag. + //- If the entry is not public the generic identifier is used + //- as the element tag. Settter/getter methods would be + //- needed. + public List entry; + + public PurchaseList(){ + entry = new Vector(); + } + + public String toString() { + StringBuilder buf = new StringBuilder(); + int cnt = entry.size(); + for(int i=0; i < cnt; i++){ + buf.append(entry.get(i).toString()); + buf.append("\n"); + } + return buf.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCartData.xml b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCartData.xml new file mode 100644 index 0000000..3827d3a --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAdapter/src/shoppingCartData.xml @@ -0,0 +1,21 @@ + + + + + + glasstop stove in black + backsplash kit in black + wooden spoon + salt and pepper shakers in yellow + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAttribute/build.golden.regexp b/scripts/jaxb-ri/samples/j2s-xmlAttribute/build.golden.regexp new file mode 100644 index 0000000..0235eb1 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAttribute/build.golden.regexp @@ -0,0 +1,27 @@ + +compile\: + \[echo\] Generating schemas\.\.\. + \[mkdir\] Created dir\: .* +\[schemagen\] Generating schema from 3 source files + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling 4 source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \Mill Valley\<\/city\> + \[java\] \Alice Smith\<\/name\> + \[java\] \123 Maple Street\<\/street\> + \[java\] \<\/shipTo\> + \[java\] \ + \[java\] \Old Town\<\/city\> + \[java\] \Robert Smith\<\/name\> + \[java\] \8 Oak Avenue\<\/street\> + \[java\] \<\/billTo\> + \[java\] \<\/purchaseOrder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/j2s-xmlAttribute/build.xml b/scripts/jaxb-ri/samples/j2s-xmlAttribute/build.xml new file mode 100644 index 0000000..9d69e50 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAttribute/build.xml @@ -0,0 +1,70 @@ + + + + + + This sample application demonstrates the use of annotation + @XmlAttribute for defining Java properties and fields as + XML attributes. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAttribute/readme.txt b/scripts/jaxb-ri/samples/j2s-xmlAttribute/readme.txt new file mode 100644 index 0000000..47bf2d7 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAttribute/readme.txt @@ -0,0 +1,44 @@ +-- @XmlAttribute Usage + +-- Synopsis + This sample demonstrates the use of annotation @XmlAttribute + to define a property or field to be treated as an XML attribute. + + +-- Details + +Annotation @XmlAttribute maps a field or JavaBean property +to an XML attribute. The following rules are imposed. + + * A static final field is mapped to a XML fixed attribute + * When the field or property is a collection type, the items + of the collection type must map to a schema simple type. + * When the field or property is other than a collection type, + the type must map to a schema simple type. + +When following the JavaBean programming paradigm a propery is +defined by a 'get' and 'set' prefix on a field name. + + int zip; + public int getZip(){return zip;} + public void setZip(int z){zip=z;} + +Within a bean class the user has the choice of setting the +@XmlAttribute on one of three components, the field, the setter method, +or the getter method. If @XmlAttribute is set on the field then the +setter method will need to be renamed otherwise there will be a naming +conflict at compile time. If @XmlAttribute is set on one of the methods, +then it must be set on either the setter or getter method but not both. + + +-- Example + +The example shows @XmlAttribute used on a static final field, on a field +rather than on one of the corresponding bean methods, on a bean property +(method), and on a field that is other than a collection type. In class +USAddress, fields, country and zip are tagged as attributes. The setZip +method was disabled to avoid the compile error. Property state was +tagged as an attribute on the setter method. The getter method could have +been used instead. In class PurchaseOrderType, field cCardVendor is a +non-collection type. It meets the requirment of being a simple type. It +is an enum type. diff --git a/scripts/jaxb-ri/samples/j2s-xmlAttribute/sample.meta b/scripts/jaxb-ri/samples/j2s-xmlAttribute/sample.meta new file mode 100644 index 0000000..c31648e --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAttribute/sample.meta @@ -0,0 +1,30 @@ + + + + + @XmlAttribute used to define properties and fields as XML Attributes + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/Main.java b/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/Main.java new file mode 100644 index 0000000..ba95e18 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/Main.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; + +import static address.CreditCardVendor.AMERICANEXPRESS; +import address.PurchaseOrderType; +import address.USAddress; + +public class Main { + public static void main(String[] args) throws Exception { + // A Ship to type + USAddress shipto = new USAddress("Alice Smith", "123 Maple Street", + "Mill Valley", "CA", 90952); + + // A bill to type + USAddress billto = new USAddress("Robert Smith", "8 Oak Avenue", + "Old Town", "PA", 95819); + + // A purchaseOrder + PurchaseOrderType po = new PurchaseOrderType(); + po.billTo = billto; + po.shipTo = shipto; + po.cCardVendor = AMERICANEXPRESS; + + // Demonstates shipping and billing data printed in the property + // order defined by the propOrder annotation element in class + // USAddress. + JAXBContext jc = JAXBContext.newInstance(PurchaseOrderType.class); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + m.marshal(po, System.out); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/address/CreditCardVendor.java b/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/address/CreditCardVendor.java new file mode 100644 index 0000000..544b5ca --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/address/CreditCardVendor.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package address; + +/** + * Valid credit card vendor + */ +public enum CreditCardVendor{ + VISA, + AMERICANEXPRESS, + DISCOVER +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/address/PurchaseOrderType.java b/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/address/PurchaseOrderType.java new file mode 100644 index 0000000..571cb5a --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/address/PurchaseOrderType.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package address; + +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlAttribute; + +@XmlRootElement(name="purchaseOrder") +@XmlType(name="PurchaseOrderType") +public class PurchaseOrderType { + + public USAddress shipTo; + public USAddress billTo; + @XmlAttribute + public CreditCardVendor cCardVendor; + + public String toString() { + StringBuilder s = new StringBuilder(); + s.append("Ship To: ").append(shipTo).append('\n'); + s.append("Bill To: ").append(billTo).append('\n'); + s.append("Card: ").append(cCardVendor).append('\n'); + return s.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/address/USAddress.java b/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/address/USAddress.java new file mode 100644 index 0000000..2b1c802 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlAttribute/src/address/USAddress.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package address; + +import jakarta.xml.bind.annotation.XmlAttribute; + +public class USAddress { + + private String city; + private String name; + private String state; + private String street; + @XmlAttribute private int zip; + @XmlAttribute static final String country = "USA"; + + /** + * The zero arg constructor is used by JAXB Unmarshaller to create + * an instance of this type. + */ + public USAddress() {} + + public USAddress(String name, String street, String city, String state, int zip) { + this.name = name; + this.street = street; + this.city = city; + this.state = state; + this.zip = zip; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public int getZip() { + return zip; + } +/*** + public void setZip(int zip) { + this.zip = zip; + } +***/ + public String getState() { + return state; + } + + @XmlAttribute + public void setState(String state) { + this.state = state; + } + + public String toString() { + StringBuilder s = new StringBuilder(); + if(name!=null) s.append(name).append('\n'); + s.append(street).append('\n').append(city).append(", ").append(state).append(" ").append(zip); + return s.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlRootElement/build.golden.regexp b/scripts/jaxb-ri/samples/j2s-xmlRootElement/build.golden.regexp new file mode 100644 index 0000000..dcf5acd --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlRootElement/build.golden.regexp @@ -0,0 +1,31 @@ + +compile\: + \[echo\] Generating schemas\.\.\. + \[mkdir\] Created dir\: .* +\[schemagen\] Generating schema from 3 source files + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling 4 source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \Mill Valley\<\/city\> + \[java\] \Alice Smith\<\/name\> + \[java\] \CA\<\/state\> + \[java\] \123 Maple Street\<\/street\> + \[java\] \90952\<\/zip\> + \[java\] \<\/shipTo\> + \[java\] \ + \[java\] \Old Town\<\/city\> + \[java\] \Robert Smith\<\/name\> + \[java\] \PA\<\/state\> + \[java\] \8 Oak Avenue\<\/street\> + \[java\] \95819\<\/zip\> + \[java\] \<\/billTo\> + \[java\] \<\/ns2:purchaseOrder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/j2s-xmlRootElement/build.xml b/scripts/jaxb-ri/samples/j2s-xmlRootElement/build.xml new file mode 100644 index 0000000..b563d01 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlRootElement/build.xml @@ -0,0 +1,69 @@ + + + + + + This sample application demonstrates the use of annotation + @XmlRootElement to define a class to be an XML element. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlRootElement/readme.txt b/scripts/jaxb-ri/samples/j2s-xmlRootElement/readme.txt new file mode 100644 index 0000000..a70ea1e --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlRootElement/readme.txt @@ -0,0 +1,24 @@ +-- @XmlRootElement Usage + +-- Synopsis + This sample demonstrates the use of annotation @XmlRootElement + to define an XML element name for the XML schema type of the + corresponding class. + + +-- Details + +Annotation @XmlRootElement maps a class or an enum type to +an XML element. At least one element definition is needed +per (top level) Java type used for unmarshalling/marshaling. +Without it there is no starting location for XML content +processing. + +Annotation @XmlRootElement uses the class name as the default element +name. The user can change the default name with the annotation attribute +name. The specified name will be used as the element name and the type +name. It is common schema practice for the element name and type name to +be different. Annotation @XmlType can be used to set the element type name. + +The namespace attribute of @XmlRootElement enables the defining +of a namespace for the element. diff --git a/scripts/jaxb-ri/samples/j2s-xmlRootElement/sample.meta b/scripts/jaxb-ri/samples/j2s-xmlRootElement/sample.meta new file mode 100644 index 0000000..9631a21 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlRootElement/sample.meta @@ -0,0 +1,29 @@ + + + + + Defining XML elements via @XmlRootElement + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/Main.java b/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/Main.java new file mode 100644 index 0000000..4d0eaa5 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/Main.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; + +import address.PurchaseOrderType; +import address.USAddress; + +public class Main { + public static void main(String[] args) throws Exception { + // A Ship to type + USAddress shipto = new USAddress("Alice Smith", "123 Maple Street", + "Mill Valley", "CA", 90952); + + // A bill to type + USAddress billto = new USAddress("Robert Smith", "8 Oak Avenue", + "Old Town", "PA", 95819); + + // A purchaseOrder + PurchaseOrderType po = new PurchaseOrderType(); + po.billTo = billto; + po.shipTo = shipto; + + // Demonstates shipping and billing data printed in the property + // order defined by the propOrder annotation element in class + // USAddress. + JAXBContext jc = JAXBContext.newInstance(PurchaseOrderType.class); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + m.marshal(po, System.out); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/address/CreditCardVendor.java b/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/address/CreditCardVendor.java new file mode 100644 index 0000000..1938a2c --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/address/CreditCardVendor.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package address; + +import jakarta.xml.bind.annotation.XmlRootElement; + +/** + * Valid credit card vendor + */ +@XmlRootElement(name="ccv") +public enum CreditCardVendor{ + VISA, + AMERICANEXPRESS, + DISCOVER +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/address/PurchaseOrderType.java b/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/address/PurchaseOrderType.java new file mode 100644 index 0000000..85d3969 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/address/PurchaseOrderType.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package address; + +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlType; + +@XmlRootElement(name="purchaseOrder",namespace="http://www.example.com/MYPO1") +@XmlType(name="PurchaseOrderType") +public class PurchaseOrderType { + + public USAddress shipTo; + public USAddress billTo; + public CreditCardVendor creditCardVendor; + + public String toString() { + StringBuilder s = new StringBuilder(); + s.append("Ship To: "); + s.append(shipTo.toString()).append('\n'); + s.append("Bill To: "); + return s.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/address/USAddress.java b/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/address/USAddress.java new file mode 100644 index 0000000..0e3d8fa --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlRootElement/src/address/USAddress.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package address; + +import jakarta.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(namespace="http://www.example.com/MYPO1") +public class USAddress { + + private String city; + private String name; + private String state; + private String street; + private int zip; + + /** + * The zero arg constructor is used by JAXB Unmarshaller to create + * an instance of this type. + */ + + public USAddress() {} + + public USAddress(String name, String street, String city, String state, int zip) { + this.name = name; + this.street = street; + this.city = city; + this.state = state; + this.zip = zip; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public int getZip() { + return zip; + } + + public void setZip(int zip) { + this.zip = zip; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String toString() { + StringBuilder s = new StringBuilder(); + if(name!=null) s.append(name).append('\n'); + s.append(street).append('\n').append(city).append(", ").append(state).append(" ").append(zip); + return s.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlSchemaType/build.golden.regexp b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/build.golden.regexp new file mode 100644 index 0000000..4fa3ebd --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/build.golden.regexp @@ -0,0 +1,21 @@ + +compile\: + \[echo\] Generating schemas\.\.\. + \[mkdir\] Created dir\: .* +\[schemagen\] Generating schema from 2 source files + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling 3 source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \2005\-11\-05\<\/shipDate\> + \[java\] \\-\-11\-03\<\/orderDate\> + \[java\] \\-\-12\-05\<\/deliveryDate\> + \[java\] \P0Y0M7D0T51M02\.01S\<\/trackingDuration\> + \[java\] \<\/trackingOrder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/j2s-xmlSchemaType/build.xml b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/build.xml new file mode 100644 index 0000000..4c7ac98 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/build.xml @@ -0,0 +1,71 @@ + + + + + + This sample application demonstrates the use of annotation + @XmlSchemaType to customize the mapping of a property or field to + an XML built-in type. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlSchemaType/readme.txt b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/readme.txt new file mode 100644 index 0000000..4ddef91 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/readme.txt @@ -0,0 +1,32 @@ +-- @XmlSchemaType Usage + +-- Synopsis + This sample demonstrates the use of annotation @XmlSchemaType + to customize the mapping of a property or field to an XML built-in + type. + + +-- Details +@XmlSchemaType can be used to map a Java type to one of the XML +built-in types. This annotation is most useful in mapping a Java +type to one of the nine date/time primitive datatypes. + +When @XmlSchemaType is defined at the package level the identification +requires both the XML built-in type name and the corresponding Java +type class. A @XmlSchemaType definition on a field or property takes +precedence over a package definition. + +-- Example +The example shows @XmlSchemaType being used at the package level, +on a field and on a property. File TrackingOrder has two fields +orderDate and deliveryDate which are defined to be of type +XMLGregorianCalendar. The generated schema will define these elements +to be of XML build-in type gMonthDay. This relationship was defined +on the package in file package-info.java. Field shipDate in file +TrackingOrder is also defined to be of type XMLGregorianCalendar, +however the @XmlSchemaType statements overrides the package definition +and specifies the field to be of type date. Property method +getTrackingDuration defines the schema element to be defined as +primitive type duration and not Java type String. + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlSchemaType/sample.meta b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/sample.meta new file mode 100644 index 0000000..f362ab8 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/sample.meta @@ -0,0 +1,31 @@ + + + + + Annotation @XmlSchemaType is used to customize the mapping of a + property or field to an XML built-in type. + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/Main.java b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/Main.java new file mode 100644 index 0000000..68f9b07 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/Main.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: Main.java,v 1.1 2007-12-05 00:49:30 kohsuke Exp $ + */ + + +import java.io.File; +import java.io.FileOutputStream; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; +import address.TrackingOrder; + +public class Main { + public static void main(String[] args) throws Exception { + JAXBContext jc = JAXBContext.newInstance(TrackingOrder.class); + Unmarshaller u = jc.createUnmarshaller(); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + try { + TrackingOrder tOrder = (TrackingOrder)u.unmarshal(new File("src/trackingData.xml")); + m.marshal(tOrder, System.out); + } catch(jakarta.xml.bind.UnmarshalException e){ + System.out.println("Main: " + e); + } + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/address/TrackingOrder.java b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/address/TrackingOrder.java new file mode 100644 index 0000000..2ec37d9 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/address/TrackingOrder.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: TrackingOrder.java,v 1.1 2007-12-05 00:49:30 kohsuke Exp $ + */ + + +package address; + +import javax.xml.datatype.XMLGregorianCalendar; +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlSchemaType; + +@XmlRootElement +@XmlType(name="TrackingOrderType") +public class TrackingOrder { + String trackingDuration; + + @XmlSchemaType(name="date") + XMLGregorianCalendar shipDate; + @XmlElement XMLGregorianCalendar orderDate; + @XmlElement XMLGregorianCalendar deliveryDate; + + @XmlSchemaType(name="duration") + public String getTrackingDuration(){ + return trackingDuration; + } + public void setTrackingDuration( String d){ + trackingDuration = d; + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/address/package-info.java b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/address/package-info.java new file mode 100644 index 0000000..8d7752c --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/address/package-info.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +@XmlSchemaType(name="gMonthDay", type=javax.xml.datatype.XMLGregorianCalendar.class) +package address; + +import jakarta.xml.bind.annotation.XmlSchemaType; diff --git a/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/trackingData.xml b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/trackingData.xml new file mode 100644 index 0000000..1f06977 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlSchemaType/src/trackingData.xml @@ -0,0 +1,20 @@ + + + + + 2005-11-05 + 2005-11-03 + 2005-12-05 + P0Y0M7D0T51M02.01S + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlType/build.golden.regexp b/scripts/jaxb-ri/samples/j2s-xmlType/build.golden.regexp new file mode 100644 index 0000000..6497a4c --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlType/build.golden.regexp @@ -0,0 +1,21 @@ + +compile\: + \[echo\] Generating schemas\.\.\. + \[mkdir\] Created dir\: .* +\[schemagen\] Generating schema from 3 source files + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling 4 source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] Ship To\: Robert Ore + \[java\] 24798 Cherry Avenue + \[java\] Old Town\, PA 95819 + \[java\] Bill To\: Carol Sandwig + \[java\] 8 Indi St + \[java\] New Town\, MO 28591 + + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/j2s-xmlType/build.xml b/scripts/jaxb-ri/samples/j2s-xmlType/build.xml new file mode 100644 index 0000000..8b457b5 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlType/build.xml @@ -0,0 +1,70 @@ + + + + + + This sample application demonstrates the use of mapping annotations + @XmlAccessorOrder and @XmlType.propOrder in Java classes for ordering + properties and fields in Java to schema bindings. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlType/readme.txt b/scripts/jaxb-ri/samples/j2s-xmlType/readme.txt new file mode 100644 index 0000000..319eb47 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlType/readme.txt @@ -0,0 +1,74 @@ +-- @XmlType Usage + +-- Synopsis + This sample demonstrates the use of annotation @XmlType + + +-- Details + +Annotation @XmlType maps a class or an enum type to a XML Schema type. + +A class must have either a public zero arg constructor or a static zero arg +factory method in order to be mapped by this annotation. One of these methods +is used during unmarshalling to create an instance of the class. The factory +method may reside within in a factory class or the existing class. There is +an order of presedence as to which method is used for unmarshalling. + + * If a factory class is identified in the annotation, a corresponding + factory method in that class must also be identified and that method + will be used. + + * If a factory method is identified in the annotation but no + factory class is identified then the factory method must reside + in the current class. The factory method is used even if there + is a public zero arg constructor method present. + + * If no factory method is identified in the annotation then the + class must contain a public zero arg constructor method. + + +-- Example + + In this example a factory class provides zero arg factory methods + for several classes. The XmlType annotation on class OrderContext + references the factory class. The unmarshaller will use the + identified factroy method in this class. + + public class OrderFormsFactory { + public OrderContext newOrderInstance() { + return new OrderContext(); + } + + public PurchaseOrderType newPurchaseOrderType() { + return new newPurchaseOrderType(); + } + + } + + @XmlType(name="oContext", factoryClass="OrderFormsFactory", + factoryMethod="newOrderInstance") + public class OrderContext { + + public OrderContext(){ ..... } + } + + + + In this example a factory method is defined in a class which + also contains a standard class constructure. Because the + factoryMethod value is define and no factoryClass is defined + The factory method newOrderInstance is used during unmarshalling. + + @XmlType(name="oContext", factoryMethod="newOrderInstance") + public class OrderContext { + + public OrderContext(){ ..... } + + public OrderContext newOrderInstance() { + return new OrderContext(); + } + + } + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlType/sample.meta b/scripts/jaxb-ri/samples/j2s-xmlType/sample.meta new file mode 100644 index 0000000..38aeeb7 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlType/sample.meta @@ -0,0 +1,30 @@ + + + + + Ordering Properties and Fieldes in Java to Schema Bindings + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/j2s-xmlType/src/Main.java b/scripts/jaxb-ri/samples/j2s-xmlType/src/Main.java new file mode 100644 index 0000000..0bc3dbb --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlType/src/Main.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: Main.java,v 1.2 2009-11-11 14:17:30 pavel_bucek Exp $ + */ + + +import java.io.File; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; +import address.USAddress; +import address.PurchaseOrderType; + +public class Main { + public static void main(String[] args) throws Exception { + + // Demonstates shipping and billing data printed in the property + // order defined by the propOrder annotation element in class + // USAddress. + JAXBContext jc = JAXBContext.newInstance(PurchaseOrderType.class); + Unmarshaller u = jc.createUnmarshaller(); + try { + PurchaseOrderType poType = (PurchaseOrderType)u.unmarshal(new + File("src/testData.xml")); + System.out.println(poType.toString()); + } catch(jakarta.xml.bind.UnmarshalException e){ + System.out.println("Main: " + e); + } + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlType/src/address/PurchaseOrderType.java b/scripts/jaxb-ri/samples/j2s-xmlType/src/address/PurchaseOrderType.java new file mode 100644 index 0000000..cdadde5 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlType/src/address/PurchaseOrderType.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: PurchaseOrderType.java,v 1.1 2007-12-05 00:49:32 kohsuke Exp $ + */ + + +package address; + +import java.util.List; +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name="purchaseOrder") +@XmlType(name="PurchaseOrderType") +public class PurchaseOrderType { + + public USAddress shipTo; + public USAddress billTo; + + public String toString() { + StringBuilder s = new StringBuilder(); + s.append("Ship To: "); + s.append(shipTo.toString()).append('\n'); + s.append("Bill To: "); + s.append(billTo.toString()).append('\n'); + return s.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlType/src/address/USAddress.java b/scripts/jaxb-ri/samples/j2s-xmlType/src/address/USAddress.java new file mode 100644 index 0000000..186b642 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlType/src/address/USAddress.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: USAddress.java,v 1.1 2007-12-05 00:49:32 kohsuke Exp $ + */ + +package address; + +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name="uSAddress") +@XmlType(name="USAddressType", factoryClass=address.USAddressFactory.class, + factoryMethod="getUSAddress") +public class USAddress { + + private String city; + private String name; + private String state; + private String street; + private int zip; + private USAddress _instance = null; + + public USAddress(String name, String street, String city, String state, int zip) { + this.name = name; + this.street = street; + this.city = city; + this.state = state; + this.zip = zip; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public int getZip() { + return zip; + } + + public void setZip(int zip) { + this.zip = zip; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String toString() { + StringBuilder s = new StringBuilder(); + if(name!=null) s.append(name).append('\n'); + s.append(street).append('\n').append(city).append(", ").append(state).append(" ").append(zip); + return s.toString(); + } +} + diff --git a/scripts/jaxb-ri/samples/j2s-xmlType/src/address/USAddressFactory.java b/scripts/jaxb-ri/samples/j2s-xmlType/src/address/USAddressFactory.java new file mode 100644 index 0000000..c4368a1 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlType/src/address/USAddressFactory.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * $Id: USAddressFactory.java,v 1.1 2007-12-05 00:49:32 kohsuke Exp $ + */ + +package address; + +public class USAddressFactory { + public static USAddress getUSAddress(){ + return new USAddress("Mark Baker", "23 Elm St", + "Dayton", "OH", 90952); + } +} diff --git a/scripts/jaxb-ri/samples/j2s-xmlType/src/testData.xml b/scripts/jaxb-ri/samples/j2s-xmlType/src/testData.xml new file mode 100644 index 0000000..e0e1715 --- /dev/null +++ b/scripts/jaxb-ri/samples/j2s-xmlType/src/testData.xml @@ -0,0 +1,30 @@ + + + + + + Robert Ore + 24798 Cherry Avenue + PA + Old Town + 95819 + + + Carol Sandwig + 8 Indi St + MO + New Town + 28591 + + + diff --git a/scripts/jaxb-ri/samples/locator-support/build.golden.regexp b/scripts/jaxb-ri/samples/locator-support/build.golden.regexp new file mode 100644 index 0000000..3a6c61b --- /dev/null +++ b/scripts/jaxb-ri/samples/locator-support/build.golden.regexp @@ -0,0 +1,16 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] .* is not found and thus excluded from the dependency check + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] done + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/locator-support/build.xml b/scripts/jaxb-ri/samples/locator-support/build.xml new file mode 100644 index 0000000..c6d7365 --- /dev/null +++ b/scripts/jaxb-ri/samples/locator-support/build.xml @@ -0,0 +1,60 @@ + + + + + + This sample shows how to use the new non-standard locator support. By + following the instructions in the readme.txt file, you can cause all of + the generated impl classes to implement a new interface that provides + more information about error locations. When a ValidationEvent happens + on your content tree, simply retrieve the object and cast it down to + <tt>com.sun.xml.bind.extra.Locatable</tt>. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/locator-support/po.xsd b/scripts/jaxb-ri/samples/locator-support/po.xsd new file mode 100644 index 0000000..fc2a3ee --- /dev/null +++ b/scripts/jaxb-ri/samples/locator-support/po.xsd @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/locator-support/poInput.xml b/scripts/jaxb-ri/samples/locator-support/poInput.xml new file mode 100644 index 0000000..f3a10ae --- /dev/null +++ b/scripts/jaxb-ri/samples/locator-support/poInput.xml @@ -0,0 +1,46 @@ + + + + + + Alice Smith + 123 Maple Street + Cambridge + MA + 12345 + + + Robert Smith + 8 Oak Avenue + Cambridge + MA + 12345 + + + + Nosferatu - Special Edition (1929) + 5 + 19.99 + + + The Mummy (1959) + 3 + 19.98 + + + Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora + 3 + 27.95 + + + diff --git a/scripts/jaxb-ri/samples/locator-support/readme.txt b/scripts/jaxb-ri/samples/locator-support/readme.txt new file mode 100644 index 0000000..6917df6 --- /dev/null +++ b/scripts/jaxb-ri/samples/locator-support/readme.txt @@ -0,0 +1,14 @@ +** UNSUPPORTED ** THIS FUNCTIONALITY MAY BE REMOVED IN FUTURE. + +This example shows how to use the JAXB RI locator extension. + +This extension changes the generated code in the following way: + + - Each generated impl class will now implement "org.glassfish.jaxb.core.Locatable" + (contained in jaxb-core.jar) + + - This interface allows you to obtain an "org.xml.sax.Locator" object, + which indicates the source location where an object is unmarshalled from. + +To enable this extension, you have to specify the "-Xlocator" switch on +the command line. diff --git a/scripts/jaxb-ri/samples/locator-support/sample.meta b/scripts/jaxb-ri/samples/locator-support/sample.meta new file mode 100644 index 0000000..2e0bd3f --- /dev/null +++ b/scripts/jaxb-ri/samples/locator-support/sample.meta @@ -0,0 +1,33 @@ + + + + + locator-support + com.sun.xml.bind.extra.Locatable. + ]]> + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/locator-support/src/Locatable.java b/scripts/jaxb-ri/samples/locator-support/src/Locatable.java new file mode 100644 index 0000000..d732d01 --- /dev/null +++ b/scripts/jaxb-ri/samples/locator-support/src/Locatable.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * @(#)$Id: Locatable.java,v 1.1 2007-12-05 00:49:32 kohsuke Exp $ + */ +package com.sun.xml.bind.extra; + +import org.xml.sax.Locator; + +/** + * Optional interface implemented by JAXB objects to expose + * location information from which an object is unmarshalled. + * + * @author + * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) + */ +public interface Locatable { + /** + * @return + * null if the location information is unavaiable, + * or otherwise return a immutable valid {@link Locator} + * object. + */ + Locator sourceLocation(); +} diff --git a/scripts/jaxb-ri/samples/modify-marshal/build.golden.regexp b/scripts/jaxb-ri/samples/modify-marshal/build.golden.regexp new file mode 100644 index 0000000..fc5df1e --- /dev/null +++ b/scripts/jaxb-ri/samples/modify-marshal/build.golden.regexp @@ -0,0 +1,50 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] .* is not found and thus excluded from the dependency check + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \Alice Smith\<\/name\> + \[java\] \123 Maple Street\<\/street\> + \[java\] \Cambridge\<\/city\> + \[java\] \MA\<\/state\> + \[java\] \12345\<\/zip\> + \[java\] \<\/shipTo\> + \[java\] \ + \[java\] \John Bob\<\/name\> + \[java\] \242 Main Street\<\/street\> + \[java\] \Beverly Hills\<\/city\> + \[java\] \CA\<\/state\> + \[java\] \90210\<\/zip\> + \[java\] \<\/billTo\> + \[java\] \ + \[java\] \ + \[java\] \Nosferatu \- Special Edition \(1929\)\<\/productName\> + \[java\] \5\<\/quantity\> + \[java\] \19\.99\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \The Mummy \(1959\)\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \19\.98\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \ + \[java\] \Godzilla and Mothra\: Battle for Earth\/Godzilla vs\. King Ghidora\<\/productName\> + \[java\] \3\<\/quantity\> + \[java\] \27\.95\<\/USPrice\> + \[java\] \<\/item\> + \[java\] \<\/items\> + \[java\] \<\/purchaseOrder\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/modify-marshal/build.xml b/scripts/jaxb-ri/samples/modify-marshal/build.xml new file mode 100644 index 0000000..8c0b9df --- /dev/null +++ b/scripts/jaxb-ri/samples/modify-marshal/build.xml @@ -0,0 +1,68 @@ + + + + + + This sample application demonstrates how to modify a java content tree + and marshal it back to XML data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/modify-marshal/po.xml b/scripts/jaxb-ri/samples/modify-marshal/po.xml new file mode 100644 index 0000000..f3a10ae --- /dev/null +++ b/scripts/jaxb-ri/samples/modify-marshal/po.xml @@ -0,0 +1,46 @@ + + + + + + Alice Smith + 123 Maple Street + Cambridge + MA + 12345 + + + Robert Smith + 8 Oak Avenue + Cambridge + MA + 12345 + + + + Nosferatu - Special Edition (1929) + 5 + 19.99 + + + The Mummy (1959) + 3 + 19.98 + + + Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora + 3 + 27.95 + + + diff --git a/scripts/jaxb-ri/samples/modify-marshal/po.xsd b/scripts/jaxb-ri/samples/modify-marshal/po.xsd new file mode 100644 index 0000000..641c17e --- /dev/null +++ b/scripts/jaxb-ri/samples/modify-marshal/po.xsd @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/modify-marshal/sample.meta b/scripts/jaxb-ri/samples/modify-marshal/sample.meta new file mode 100644 index 0000000..8b478d1 --- /dev/null +++ b/scripts/jaxb-ri/samples/modify-marshal/sample.meta @@ -0,0 +1,29 @@ + + + + + modify-marshal (formerly SampleApp2) + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/modify-marshal/src/Main.java b/scripts/jaxb-ri/samples/modify-marshal/src/Main.java new file mode 100644 index 0000000..a620213 --- /dev/null +++ b/scripts/jaxb-ri/samples/modify-marshal/src/Main.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigDecimal; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBElement; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; + +// import java content classes generated by binding compiler +import primer.po.*; + +/* + * $Id: Main.java,v 1.1 2007-12-05 00:49:33 kohsuke Exp $ + */ + +public class Main { + + // This sample application demonstrates how to modify a java content + // tree and marshal it back to a xml data + + public static void main( String[] args ) { + try { + // create a JAXBContext capable of handling classes generated into + // the primer.po package + JAXBContext jc = JAXBContext.newInstance( "primer.po" ); + + // create an Unmarshaller + Unmarshaller u = jc.createUnmarshaller(); + + // unmarshal a po instance document into a tree of Java content + // objects composed of classes from the primer.po package. + JAXBElement poe = + (JAXBElement)u.unmarshal( new FileInputStream( "po.xml" ) ); + PurchaseOrderType po = (PurchaseOrderType)poe.getValue(); + + // change the billto address + USAddress address = po.getBillTo(); + address.setName( "John Bob" ); + address.setStreet( "242 Main Street" ); + address.setCity( "Beverly Hills" ); + address.setState( "CA" ); + address.setZip( new BigDecimal( "90210" ) ); + + // create a Marshaller and marshal to a file + Marshaller m = jc.createMarshaller(); + m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); + m.marshal( poe, System.out ); + + } catch( JAXBException je ) { + je.printStackTrace(); + } catch( IOException ioe ) { + ioe.printStackTrace(); + } + } +} diff --git a/scripts/jaxb-ri/samples/namespace-prefix/bar.xsd b/scripts/jaxb-ri/samples/namespace-prefix/bar.xsd new file mode 100644 index 0000000..31698e7 --- /dev/null +++ b/scripts/jaxb-ri/samples/namespace-prefix/bar.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/namespace-prefix/build.golden.regexp b/scripts/jaxb-ri/samples/namespace-prefix/build.golden.regexp new file mode 100644 index 0000000..06856df --- /dev/null +++ b/scripts/jaxb-ri/samples/namespace-prefix/build.golden.regexp @@ -0,0 +1,30 @@ + +compile\: + \[echo\] Compiling the schema\.\.\. + \[mkdir\] Created dir\: .* + \[xjc\] .* is not found and thus excluded from the dependency check + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[xjc\] .* is not found and thus excluded from the dependency check + \[xjc\] Compiling .* + \[xjc\] Writing output to .* + \[echo\] Compiling the java source files\.\.\. + \[mkdir\] Created dir\: .* + \[javac\] Compiling \d+ source files to .* + +run\: + \[echo\] Running the sample application\.\.\. + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ + \[java\] \xyz\:someQName\<\/b\:bar2\> + \[java\] \<\/foo1\> + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \ + \[java\] \ns5\:someQName\<\/b\:bar2\> + \[java\] \<\/foo1\> + \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\> + \[java\] \someQName\<\/ns5\:foo2\> + +BUILD SUCCESSFUL +Total time\: .* diff --git a/scripts/jaxb-ri/samples/namespace-prefix/build.xml b/scripts/jaxb-ri/samples/namespace-prefix/build.xml new file mode 100644 index 0000000..a8d1aea --- /dev/null +++ b/scripts/jaxb-ri/samples/namespace-prefix/build.xml @@ -0,0 +1,75 @@ + + + + + + This sample application demonstrates how to use the new JAXB RI + Marshaller property "org.glassfish.jaxb.namespacePrefixMapper" to + customize the namespace prefixes generated during marshalling. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/namespace-prefix/foo.xsd b/scripts/jaxb-ri/samples/namespace-prefix/foo.xsd new file mode 100644 index 0000000..86a3662 --- /dev/null +++ b/scripts/jaxb-ri/samples/namespace-prefix/foo.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/namespace-prefix/sample.meta b/scripts/jaxb-ri/samples/namespace-prefix/sample.meta new file mode 100644 index 0000000..b72abde --- /dev/null +++ b/scripts/jaxb-ri/samples/namespace-prefix/sample.meta @@ -0,0 +1,35 @@ + + + + + namespace-prefix + + + + + + + + + + + + + + + + diff --git a/scripts/jaxb-ri/samples/namespace-prefix/src/NamespacePrefixMapperImpl.java b/scripts/jaxb-ri/samples/namespace-prefix/src/NamespacePrefixMapperImpl.java new file mode 100644 index 0000000..67d7bff --- /dev/null +++ b/scripts/jaxb-ri/samples/namespace-prefix/src/NamespacePrefixMapperImpl.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import org.glassfish.jaxb.runtime.marshaller.NamespacePrefixMapper; + +class NamespacePrefixMapperImpl extends NamespacePrefixMapper { + + /** + * Returns a preferred prefix for the given namespace URI. + * + * This method is intended to be overrided by a derived class. + * + * @param namespaceUri + * The namespace URI for which the prefix needs to be found. + * Never be null. "" is used to denote the default namespace. + * @param suggestion + * When the content tree has a suggestion for the prefix + * to the given namespaceUri, that suggestion is passed as a + * parameter. Typicall this value comes from the QName.getPrefix + * to show the preference of the content tree. This parameter + * may be null, and this parameter may represent an already + * occupied prefix. + * @param requirePrefix + * If this method is expected to return non-empty prefix. + * When this flag is true, it means that the given namespace URI + * cannot be set as the default namespace. + * + * @return + * null if there's no prefered prefix for the namespace URI. + * In this case, the system will generate a prefix for you. + * + * Otherwise the system will try to use the returned prefix, + * but generally there's no guarantee if the prefix will be + * actually used or not. + * + * return "" to map this namespace URI to the default namespace. + * Again, there's no guarantee that this preference will be + * honored. + * + * If this method returns "" when requirePrefix=true, the return + * value will be ignored and the system will generate one. + */ + public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) { + // I want this namespace to be mapped to "xsi" + if( "http://www.w3.org/2001/XMLSchema-instance".equals(namespaceUri) ) + return "xsi"; + + // I want the namespace foo to be the default namespace. + if( "http://www.example.com/foo".equals(namespaceUri) ) + return ""; + + // and the namespace bar will use "b". + if( "http://www.example.com/bar".equals(namespaceUri) ) + return "b"; + + // otherwise I don't care. Just use the default suggestion, whatever it may be. + return suggestion; + } + + + + /** + * Returns a list of namespace URIs that should be declared + * at the root element. + *

+ * By default, the JAXB RI produces namespace declarations only when + * they are necessary, only at where they are used. Because of this + * lack of look-ahead, sometimes the marshaller produces a lot of + * namespace declarations that look redundant to human eyes. For example, + *


+     * <?xml version="1.0"?>
+     * <root>
+     *   <ns1:child xmlns:ns1="urn:foo"> ... </ns1:child>
+     *   <ns2:child xmlns:ns2="urn:foo"> ... </ns2:child>
+     *   <ns3:child xmlns:ns3="urn:foo"> ... </ns3:child>
+     *   ...
+     * </root>
+     * <xmp></pre>
+     * <p>
+     * If you know in advance that you are going to use a certain set of
+     * namespace URIs, you can override this method and have the marshaller
+     * declare those namespace URIs at the root element.
+     * <p>
+     * For example, by returning <code>new String[]{"urn:foo"}</code>,
+     * the marshaller will produce:
+     * <pre><xmp>
+     * <?xml version="1.0"?>
+     * <root xmlns:ns1="urn:foo">
+     *   <ns1:child> ... </ns1:child>
+     *   <ns1:child> ... </ns1:child>
+     *   <ns1:child> ... </ns1:child>
+     *   ...
+     * </root>
+     * <xmp></pre>
+     * <p>
+     * To control prefixes assigned to those namespace URIs, use the
+     * {@link #getPreferredPrefix} method.
+     *
+     * @return
+     *      A list of namespace URIs as an array of {@link String}s.
+     *      This method can return a length-zero array but not null.
+     *      None of the array component can be null. To represent
+     *      the empty namespace, use the empty string <code>""</code>.
+     *
+     * @since
+     *      JAXB RI 1.0.2
+     */
+    public String[] getPreDeclaredNamespaceUris() {
+        return new String[] { "urn:abc", "urn:def" };
+    }
+}
diff --git a/scripts/jaxb-ri/samples/namespace-prefix/src/PrefixExample.java b/scripts/jaxb-ri/samples/namespace-prefix/src/PrefixExample.java
new file mode 100644
index 0000000..2014dc6
--- /dev/null
+++ b/scripts/jaxb-ri/samples/namespace-prefix/src/PrefixExample.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.File;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.Marshaller;
+import jakarta.xml.bind.PropertyException;
+
+
+/**
+ * This example shows you how you can change the way
+ * the marshaller assigns prefixes to namespace URIs.
+ * 
+ * @author
+ *     Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
+ */
+public class PrefixExample {
+    
+    public static void main( String[] args ) throws Exception {
+        // in this example, I skip the error check entirely
+        // for the sake of simplicity. In reality, you should
+        // do a better job of handling errors.
+        for( int i=0; i<args.length; i++ )
+            test(args[i]);      // run through all the files one by one.
+    }
+    
+    private static void test( String fileName ) throws Exception {
+        JAXBContext context = JAXBContext.newInstance("foo:bar"); 
+        
+        // unmarshal a file specified by the command line argument
+        Object o = context.createUnmarshaller().unmarshal(new File(fileName));
+        
+        Marshaller marshaller = context.createMarshaller();
+        
+        // to specify the URI->prefix mapping, you'll need to provide an
+        // implementation of NamespaecPrefixMapper, which determines the
+        // prefixes used for marshalling.
+        // 
+        // you specify this as a property of Marshaller to
+        // tell the marshaller to consult your mapper
+        // to assign a prefix for a namespace.
+        try {
+            marshaller.setProperty("org.glassfish.jaxb.namespacePrefixMapper",new NamespacePrefixMapperImpl());
+        } catch( PropertyException e ) {
+            // if the JAXB provider doesn't recognize the prefix mapper,
+            // it will throw this exception. Since being unable to specify
+            // a human friendly prefix is not really a fatal problem,
+            // you can just continue marshalling without failing
+            ;
+        }
+        
+        // make the output indented. It looks nicer on screen.
+        // this is a JAXB standard property, so it should work with any JAXB impl.
+        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
+        
+        // print it out to the console since we are just testing the behavior.
+        marshaller.marshal( o, System.out );
+    }
+}
diff --git a/scripts/jaxb-ri/samples/namespace-prefix/test1.xml b/scripts/jaxb-ri/samples/namespace-prefix/test1.xml
new file mode 100644
index 0000000..66cd3e0
--- /dev/null
+++ b/scripts/jaxb-ri/samples/namespace-prefix/test1.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<foo1 xmlns="http://www.example.com/foo" xmlns:b="http://www.example.com/bar">
+	<b:bar1 />
+	<b:bar2 xmlns:xyz="someNamespace">xyz:someQName</b:bar2>
+</foo1>
diff --git a/scripts/jaxb-ri/samples/namespace-prefix/test2.xml b/scripts/jaxb-ri/samples/namespace-prefix/test2.xml
new file mode 100644
index 0000000..f68de94
--- /dev/null
+++ b/scripts/jaxb-ri/samples/namespace-prefix/test2.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<foo1 xmlns="http://www.example.com/foo" xmlns:b="http://www.example.com/bar">
+	<!-- a nasty corner case -->
+	<b:bar2 xmlns="anotherNamespace">someQName</b:bar2>
+</foo1>
diff --git a/scripts/jaxb-ri/samples/namespace-prefix/test3.xml b/scripts/jaxb-ri/samples/namespace-prefix/test3.xml
new file mode 100644
index 0000000..362a680
--- /dev/null
+++ b/scripts/jaxb-ri/samples/namespace-prefix/test3.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<f:foo2 xmlns:f="http://www.example.com/foo" xmlns="">
+	someQName
+</f:foo2>
diff --git a/scripts/jaxb-ri/samples/partial-unmarshalling/Primer.xsd b/scripts/jaxb-ri/samples/partial-unmarshalling/Primer.xsd
new file mode 100644
index 0000000..616d2d6
--- /dev/null
+++ b/scripts/jaxb-ri/samples/partial-unmarshalling/Primer.xsd
@@ -0,0 +1,81 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+
+  <xsd:element name="purchaseOrders">
+    <xsd:complexType>
+      <xsd:sequence>
+        <xsd:element ref="purchaseOrder" minOccurs="0" maxOccurs="unbounded"/>
+      </xsd:sequence>
+    </xsd:complexType>
+  </xsd:element>
+
+
+  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
+
+  <xsd:element name="comment" type="xsd:string"/>
+
+  <xsd:complexType name="PurchaseOrderType">
+    <xsd:sequence>
+      <xsd:element name="shipTo" type="USAddress"/>
+      <xsd:element name="billTo" type="USAddress"/>
+      <xsd:element ref="comment" minOccurs="0"/>
+      <xsd:element name="items" type="Items"/>
+    </xsd:sequence>
+    <xsd:attribute name="orderDate" type="xsd:date"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="USAddress">
+    <xsd:sequence>
+      <xsd:element name="name" type="xsd:string"/>
+      <xsd:element name="street" type="xsd:string"/>
+      <xsd:element name="city" type="xsd:string"/>
+      <xsd:element name="state" type="xsd:string"/>
+      <xsd:element name="zip" type="xsd:decimal"/>
+    </xsd:sequence>
+    <xsd:attribute name="country" type="xsd:NMTOKEN"
+                   fixed="US"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="Items">
+    <xsd:sequence>
+      <xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
+        <xsd:complexType>
+          <xsd:sequence>
+            <xsd:element name="productName" type="xsd:string"/>
+            <xsd:element name="quantity">
+              <xsd:simpleType>
+                <xsd:restriction base="xsd:positiveInteger">
+                  <xsd:maxExclusive value="100"/>
+                </xsd:restriction>
+              </xsd:simpleType>
+            </xsd:element>
+            <xsd:element name="USPrice" type="xsd:decimal"/>
+            <xsd:element ref="comment" minOccurs="0"/>
+            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
+          </xsd:sequence>
+          <xsd:attribute name="partNum" type="SKU" use="required"/>
+        </xsd:complexType>
+      </xsd:element>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <!-- Stock Keeping Unit, a code for identifying products -->
+  <xsd:simpleType name="SKU">
+    <xsd:restriction base="xsd:string">
+      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
+    </xsd:restriction>
+  </xsd:simpleType>
+
+</xsd:schema>
+
diff --git a/scripts/jaxb-ri/samples/partial-unmarshalling/build.golden.regexp b/scripts/jaxb-ri/samples/partial-unmarshalling/build.golden.regexp
new file mode 100644
index 0000000..8dd3b7b
--- /dev/null
+++ b/scripts/jaxb-ri/samples/partial-unmarshalling/build.golden.regexp
@@ -0,0 +1,18 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] this order will be shipped to Alice Smith
+     \[java\] this order will be shipped to Lee Grant
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/partial-unmarshalling/build.xml b/scripts/jaxb-ri/samples/partial-unmarshalling/build.xml
new file mode 100644
index 0000000..a3b2b1c
--- /dev/null
+++ b/scripts/jaxb-ri/samples/partial-unmarshalling/build.xml
@@ -0,0 +1,69 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+        In this example, the input document will be unmarshalled a small chunk 
+        at a time, instead of unmarshalling the whole document at once.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc schema="Primer.xsd" package="primer" destdir="gen-src">
+      <produces dir="gen-src/primer" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+      <arg value="test.xml" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="partial-unmarshalling" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/partial-unmarshalling/readme.txt b/scripts/jaxb-ri/samples/partial-unmarshalling/readme.txt
new file mode 100644
index 0000000..1dbbcda
--- /dev/null
+++ b/scripts/jaxb-ri/samples/partial-unmarshalling/readme.txt
@@ -0,0 +1,9 @@
+In this example, the input document will be unmarshalled a small chunk at 
+a time, instead of unmarshalling the whole document at once. This reduces
+the memory consumption and speeds up the turn around time.
+
+The point of this example is to illustrate that JAXB allows the application
+to intervene the unmarshalling process. This example can be used not only
+for partial unmarshalling, but also for things like skipping a part of
+a document or including other documents.
+Writing an XMLFilter, as we did in this example, is one way to do this.
diff --git a/scripts/jaxb-ri/samples/partial-unmarshalling/sample.meta b/scripts/jaxb-ri/samples/partial-unmarshalling/sample.meta
new file mode 100644
index 0000000..68efd57
--- /dev/null
+++ b/scripts/jaxb-ri/samples/partial-unmarshalling/sample.meta
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0">
+    <title>partial-unmarshalling</title>
+    <description><![CDATA[
+        In this example, the input document will be unmarshalled a small chunk 
+        at a time, instead of unmarshalling the whole document at once.
+    ]]></description>
+        
+    <readme/>
+    
+    <project>
+        <xjc schema="Primer.xsd" package="primer"/>
+        
+        <javadoc/>
+        
+        <java mainClass="Main">
+            <arg value="test.xml"/>
+        </java>
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/partial-unmarshalling/src/Main.java b/scripts/jaxb-ri/samples/partial-unmarshalling/src/Main.java
new file mode 100644
index 0000000..8456b59
--- /dev/null
+++ b/scripts/jaxb-ri/samples/partial-unmarshalling/src/Main.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.File;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBElement;
+import javax.xml.parsers.SAXParserFactory;
+
+import org.xml.sax.XMLReader;
+
+/*
+ * @(#)$Id: Main.java,v 1.1 2007-12-05 00:49:34 kohsuke Exp $
+ */
+
+public class Main {
+    public static void main( String[] args ) throws Exception {
+        
+        // create JAXBContext for the primer.xsd
+        JAXBContext context = JAXBContext.newInstance("primer");
+        
+        // create a new XML parser
+        SAXParserFactory factory = SAXParserFactory.newInstance();
+        factory.setNamespaceAware(true);
+        XMLReader reader = factory.newSAXParser().getXMLReader();
+        
+        // prepare a Splitter
+        Splitter splitter = new Splitter(context);
+        
+        // connect two components
+        reader.setContentHandler(splitter);
+        
+        for( int i=0; i<args.length; i++ ) {
+            // parse all the documents specified via the command line.
+            // note that XMLReader expects an URL, not a file name.
+            // so we need conversion.
+            reader.parse(new File(args[i]).toURI().toURL().toExternalForm());
+        }
+    }
+
+}
diff --git a/scripts/jaxb-ri/samples/partial-unmarshalling/src/Splitter.java b/scripts/jaxb-ri/samples/partial-unmarshalling/src/Splitter.java
new file mode 100644
index 0000000..cba5d48
--- /dev/null
+++ b/scripts/jaxb-ri/samples/partial-unmarshalling/src/Splitter.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.util.Enumeration;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBElement;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Unmarshaller;
+import jakarta.xml.bind.UnmarshallerHandler;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+import org.xml.sax.helpers.NamespaceSupport;
+import org.xml.sax.helpers.XMLFilterImpl;
+
+import primer.PurchaseOrderType;
+
+/*
+ * @(#)$Id: Splitter.java,v 1.1 2007-12-05 00:49:34 kohsuke Exp $
+ */
+ 
+/**
+ * This object implements XMLFilter and monitors the incoming SAX
+ * events. Once it hits a purchaseOrder element, it creates a new
+ * unmarshaller and unmarshals one purchase order.
+ * 
+ * <p>
+ * Once finished unmarshalling it, we will process it, then move
+ * on to the next purchase order.
+ */
+public class Splitter extends XMLFilterImpl {
+    
+    public Splitter( JAXBContext context ) {
+        this.context = context;
+    }
+    
+    /**
+     * We will create unmarshallers from this context.
+     */
+    private final JAXBContext context;
+    
+    
+    public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
+        throws SAXException {
+            
+        if( depth!= 0 ) {
+            // we are in the middle of forwarding events.
+            // continue to do so.
+            depth++;
+            super.startElement(namespaceURI, localName, qName, atts);
+            return;
+        }
+        
+        if( namespaceURI.equals("") && localName.equals("purchaseOrder") ) {
+            // start a new unmarshaller
+            Unmarshaller unmarshaller;
+            try {
+                unmarshaller = context.createUnmarshaller();
+            } catch( JAXBException e ) {
+                // there's no way to recover from this error.
+                // we will abort the processing.
+                throw new SAXException(e);
+            }
+            unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
+            
+            // set it as the content handler so that it will receive
+            // SAX events from now on.
+            setContentHandler(unmarshallerHandler);
+            
+            // fire SAX events to emulate the start of a new document.
+            unmarshallerHandler.startDocument();
+            unmarshallerHandler.setDocumentLocator(locator);
+            
+            Enumeration e = namespaces.getPrefixes();
+            while( e.hasMoreElements() ) {
+                String prefix = (String)e.nextElement();
+                String uri = namespaces.getURI(prefix);
+                
+                unmarshallerHandler.startPrefixMapping(prefix,uri);
+            }
+            String defaultURI = namespaces.getURI("");
+            if( defaultURI!=null )
+                unmarshallerHandler.startPrefixMapping("",defaultURI);
+
+            super.startElement(namespaceURI, localName, qName, atts);
+            
+            // count the depth of elements and we will know when to stop.
+            depth=1;
+        }
+    }
+    
+    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
+        
+        // forward this event
+        super.endElement(namespaceURI, localName, qName);
+        
+        if( depth!=0 ) {
+            depth--;
+            if( depth==0 ) {
+                // just finished sending one chunk.
+                
+                // emulate the end of a document.
+                Enumeration e = namespaces.getPrefixes();
+                while( e.hasMoreElements() ) {
+                    String prefix = (String)e.nextElement();
+                    unmarshallerHandler.endPrefixMapping(prefix);
+                }
+                String defaultURI = namespaces.getURI("");
+                if( defaultURI!=null )
+                    unmarshallerHandler.endPrefixMapping("");
+                unmarshallerHandler.endDocument();
+                
+                // stop forwarding events by setting a dummy handler.
+                // XMLFilter doesn't accept null, so we have to give it something,
+                // hence a DefaultHandler, which does nothing.
+                setContentHandler(new DefaultHandler());
+                
+                // then retrieve the fully unmarshalled object
+                try {
+                    JAXBElement<PurchaseOrderType> result = 
+			(JAXBElement<PurchaseOrderType>)unmarshallerHandler.getResult();
+                    
+                    // process this new purchase order
+                    process(result.getValue());
+                } catch( JAXBException je ) {
+                    // error was found during the unmarshalling.
+                    // you can either abort the processing by throwing a SAXException,
+                    // or you can continue processing by returning from this method.
+                    System.err.println("unable to process an order at line "+
+                        locator.getLineNumber() );
+                    return;
+                }
+                
+                unmarshallerHandler = null;
+            }
+        }
+    }
+    
+    public void process( PurchaseOrderType order ) {
+        System.out.println("this order will be shipped to "
+            + order.getShipTo().getName() );
+    }
+    
+    /**
+     * Remembers the depth of the elements as we forward
+     * SAX events to a JAXB unmarshaller.
+     */
+    private int depth;
+    
+    /**
+     * Reference to the unmarshaller which is unmarshalling
+     * an object.
+     */
+    private UnmarshallerHandler unmarshallerHandler;
+
+
+    /**
+     * Keeps a reference to the locator object so that we can later
+     * pass it to a JAXB unmarshaller.
+     */
+    private Locator locator;
+    public void setDocumentLocator(Locator locator) {
+        super.setDocumentLocator(locator);
+        this.locator = locator;
+    }
+
+
+    /**
+     * Used to keep track of in-scope namespace bindings.
+     * 
+     * For JAXB unmarshaller to correctly unmarshal documents, it needs
+     * to know all the effective namespace declarations.
+     */
+    private NamespaceSupport namespaces = new NamespaceSupport();
+    
+    public void startPrefixMapping(String prefix, String uri) throws SAXException {
+        namespaces.pushContext();
+        namespaces.declarePrefix(prefix,uri);
+        
+        super.startPrefixMapping(prefix, uri);
+    }
+
+    public void endPrefixMapping(String prefix) throws SAXException {
+        namespaces.popContext();
+        
+        super.endPrefixMapping(prefix);
+    }
+}
diff --git a/scripts/jaxb-ri/samples/partial-unmarshalling/test.xml b/scripts/jaxb-ri/samples/partial-unmarshalling/test.xml
new file mode 100644
index 0000000..1ca19d6
--- /dev/null
+++ b/scripts/jaxb-ri/samples/partial-unmarshalling/test.xml
@@ -0,0 +1,53 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<purchaseOrders>
+  <!-- 1st -->
+  <purchaseOrder orderDate="1999-10-20">
+    <shipTo country="US">
+      <name>Alice Smith</name>
+      <street>123 Maple Street</street>
+      <city>Cambridge</city>
+      <state>MA</state>
+      <zip>12345</zip>
+    </shipTo>
+    <billTo country="US">
+      <name>Robert Smith</name>
+      <street>8 Oak Avenue</street>
+      <city>Cambridge</city>
+      <state>MA</state>
+      <zip>12345</zip>
+    </billTo>
+    <items/>
+  </purchaseOrder>
+
+  <!-- 2nd -->
+  <purchaseOrder orderDate="1999-10-20">
+    <shipTo country="US">
+      <name>Lee Grant</name>
+      <street>123 Maple Street</street>
+      <city>Cambridge</city>
+      <state>MA</state>
+      <zip>12345</zip>
+    </shipTo>
+    <billTo country="US">
+      <name>Stonewall Jackson</name>
+      <street>8 Oak Avenue</street>
+      <city>Lexington</city>
+      <state>MA</state>
+      <zip>12345</zip>
+    </billTo>
+    <items/>
+  </purchaseOrder>
+</purchaseOrders>
+
diff --git a/scripts/jaxb-ri/samples/pull-parser/build.golden.regexp b/scripts/jaxb-ri/samples/pull-parser/build.golden.regexp
new file mode 100644
index 0000000..29b6049
--- /dev/null
+++ b/scripts/jaxb-ri/samples/pull-parser/build.golden.regexp
@@ -0,0 +1,19 @@
+
+jar\-check\:
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] the e\-mail address is jane@acme\.org
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/pull-parser/build.xml b/scripts/jaxb-ri/samples/pull-parser/build.xml
new file mode 100644
index 0000000..bee9403
--- /dev/null
+++ b/scripts/jaxb-ri/samples/pull-parser/build.xml
@@ -0,0 +1,88 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+      This sample app demonstrates how a pull-parser can
+      be used with JAXB to increase the flexibility of processing.
+  </description>
+
+  <property name="jaxb.home" value="../.." />
+  <mkdir dir="lib"/>
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <!--additional jar files for this sample-->
+    <fileset dir="lib" includes="*.jar" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--
+    Check if the necessary jar files are properly installed.
+  -->
+  <target name="jar-check">
+    <available file="lib/sjsxp.jar" property="sjsxp.jar-present" />
+    <fail unless="sjsxp.jar-present">
+Please download sjsxp.jar from the web and place it in the lib directory.
+
+Alternatively download from maven central:
+mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get -DremoteRepositories=http://download.java.net/maven/2 \
+-Dartifact=com.sun.xml.stream:sjsxp:LATEST -Ddest=./lib/sjsxp.jar
+
+    </fail>
+  </target>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files" depends="jar-check">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc schema="contact.xsd" package="contact" destdir="gen-src">
+      <produces dir="gen-src/contact" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+      <arg value="Jane Smith" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="pull parser based unmarshalling" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/pull-parser/contact.xml b/scripts/jaxb-ri/samples/pull-parser/contact.xml
new file mode 100644
index 0000000..0d6531c
--- /dev/null
+++ b/scripts/jaxb-ri/samples/pull-parser/contact.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<addressBook>
+  <!-- list of contacts -->
+
+  <contact>
+    <name>John Doe</name>
+    <email>john@acme.com</email>
+  </contact>
+  <contact>
+    <name>Jane Smith</name>
+    <email>jane@acme.org</email>
+  </contact>
+
+  <!-- more extra records -->
+  <contact>
+    <name>Bob Cole</name>
+    <email>bob@acme.net</email>
+  </contact>
+</addressBook>
diff --git a/scripts/jaxb-ri/samples/pull-parser/contact.xsd b/scripts/jaxb-ri/samples/pull-parser/contact.xsd
new file mode 100644
index 0000000..25633b3
--- /dev/null
+++ b/scripts/jaxb-ri/samples/pull-parser/contact.xsd
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:element name="addressBook">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element ref="contact" maxOccurs="unbounded"/>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+
+  <xs:element name="contact">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element name="name" type="xs:string"/>
+        <xs:element name="email" type="xs:string"/>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+
+</xs:schema>
diff --git a/scripts/jaxb-ri/samples/pull-parser/readme.txt b/scripts/jaxb-ri/samples/pull-parser/readme.txt
new file mode 100644
index 0000000..c207b6f
--- /dev/null
+++ b/scripts/jaxb-ri/samples/pull-parser/readme.txt
@@ -0,0 +1,2 @@
+This sample shows how you can combine a pull-parser with JAXB to
+process XML in more flexible way.
diff --git a/scripts/jaxb-ri/samples/pull-parser/sample.meta b/scripts/jaxb-ri/samples/pull-parser/sample.meta
new file mode 100644
index 0000000..d39ed23
--- /dev/null
+++ b/scripts/jaxb-ri/samples/pull-parser/sample.meta
@@ -0,0 +1,34 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0.2">
+    <title>pull parser based unmarshalling</title>
+    <description><![CDATA[
+      This sample app demonstrates how a pull-parser can
+      be used with JAXB to increase the flexibility of processing.
+    ]]></description>
+        
+    <readme/>
+
+    <project>
+        <depends>
+          <jar name="sjsxp.jar" from="http://java.sun.com"/>
+        </depends>
+        <xjc schema="contact.xsd" package="contact" />
+        <javadoc/>
+        <java mainClass="Main">
+            <arg value="Jane Smith" />
+        </java>
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/pull-parser/src/Main.java b/scripts/jaxb-ri/samples/pull-parser/src/Main.java
new file mode 100644
index 0000000..de7f7ed
--- /dev/null
+++ b/scripts/jaxb-ri/samples/pull-parser/src/Main.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.Unmarshaller;
+import java.io.FileReader;
+
+import javax.xml.stream.*;
+import static javax.xml.stream.XMLStreamConstants.*;
+import contact.Contact;
+
+/*
+ * Use is subject to the license terms.
+ */
+
+/**
+ * 
+ * 
+ * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
+ */
+public class Main {
+
+    public static void main(String[] args) throws Exception {
+        
+        String nameToLookFor = args[0];
+        
+        JAXBContext jaxbContext = JAXBContext.newInstance("contact"); 
+        Unmarshaller um = jaxbContext.createUnmarshaller();
+
+        // set up a parser
+	XMLInputFactory xmlif = XMLInputFactory.newInstance();
+	XMLStreamReader xmlr = 
+	    xmlif.createXMLStreamReader(new FileReader("contact.xml"));
+ 
+	// move to the root element and check its name.
+        xmlr.nextTag(); 
+        xmlr.require(START_ELEMENT, null, "addressBook");
+
+        xmlr.nextTag(); // move to the first <contact> element.
+        while (xmlr.getEventType() == START_ELEMENT) {
+
+            // unmarshall one <contact> element into a JAXB Contact object
+	    xmlr.require(START_ELEMENT, null, "contact");
+            Contact contact = (Contact) um.unmarshal(xmlr);
+            if( contact.getName().equals(nameToLookFor)) {
+                // we found what we wanted to find. show it and quit now.
+                System.out.println("the e-mail address is "+contact.getEmail());
+                return;
+            }
+            if (xmlr.getEventType() == CHARACTERS) {
+                xmlr.next(); // skip the whitespace between <contact>s.
+	    }
+        }
+        System.out.println("Unable to find "+nameToLookFor);
+    }
+}
diff --git a/scripts/jaxb-ri/samples/relaxng/build.golden.regexp b/scripts/jaxb-ri/samples/relaxng/build.golden.regexp
new file mode 100644
index 0000000..8f05da3
--- /dev/null
+++ b/scripts/jaxb-ri/samples/relaxng/build.golden.regexp
@@ -0,0 +1,18 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<add\>\<neg\>\<number\>3\<\/number\>\<\/neg\>\<sub\>\<number\>2\<\/number\>\<number\>5\<\/number\>\<\/sub\>\<\/add\>
+
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/relaxng/build.xml b/scripts/jaxb-ri/samples/relaxng/build.xml
new file mode 100644
index 0000000..2d6f80e
--- /dev/null
+++ b/scripts/jaxb-ri/samples/relaxng/build.xml
@@ -0,0 +1,58 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+    This example shows how you can use experimental RELAX NG support.
+
+    Please be warned that this feature is experimental, and therefore
+    not suitable for the production purpose. A future version of JAXB RI
+    can change the way it handles RELAX NG, or even drop the support for it.
+
+    That said, everything is basically the same as XML Schema ---
+    except that you are using RELAX NG as the source schema.
+
+    See http://relaxng.org/ for more information about RELAX NG.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <!--additional jar files for this sample-->
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+    </java>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/relaxng/formula.rng b/scripts/jaxb-ri/samples/relaxng/formula.rng
new file mode 100644
index 0000000..8188a28
--- /dev/null
+++ b/scripts/jaxb-ri/samples/relaxng/formula.rng
@@ -0,0 +1,87 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<!--
+  This example demonstrates how customizations can be used to modify
+  the generated code.
+  
+  This schema describes a parse tree of a formula like
+  
+  5+(3-2) =
+                <add>
+                  <num>5</num>
+                  <sub>
+                    <num>3</num>
+                    <num>2</num>
+                  </sub>
+                </add>
+-->
+<grammar xmlns="http://relaxng.org/ns/structure/1.0"
+         datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes"
+         xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+         xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+         jaxb:extensionBindingPrefixes="xjc"
+         jaxb:version="3.0">
+  
+  <jaxb:schemaBindings>
+    <jaxb:package name="formula"/>
+  </jaxb:schemaBindings>
+  
+  <start>
+    <ref name="expression"/>
+  </start>
+  
+  <define name="expression">
+    <!--
+      Generate the Expression interface so that all the operators
+      derive from this interface.
+    -->
+    <xjc:interface />
+    
+    <choice>
+      <element name="add">
+        <ref name="binaryExpression">
+          <xjc:super /><!-- Add will extend BinaryExpression -->
+        </ref>
+      </element>
+      <element name="sub">
+        <ref name="binaryExpression">
+          <xjc:super />
+        </ref>
+      </element>
+      <element name="neg">
+        <ref name="unaryExpression">
+          <xjc:super />
+        </ref>
+      </element>
+      <element name="number">
+        <data type="int"/>
+      </element>
+    </choice>
+  </define>
+  
+  <define name="binaryExpression">
+    
+    <!-- change the property name to lhs and rhs respectively. -->
+    <ref name="expression">
+      <jaxb:property name="lhs"/>
+    </ref>
+    <ref name="expression">
+      <jaxb:property name="rhs"/>
+    </ref>
+  </define>
+  
+  <define name="unaryExpression">
+    <ref name="expression"/>
+  </define>
+</grammar>
diff --git a/scripts/jaxb-ri/samples/relaxng/readme.txt b/scripts/jaxb-ri/samples/relaxng/readme.txt
new file mode 100644
index 0000000..d978c60
--- /dev/null
+++ b/scripts/jaxb-ri/samples/relaxng/readme.txt
@@ -0,0 +1,10 @@
+This example shows how you can use experimental RELAX NG support.
+
+Please be warned that this feature is experimental, and therefore
+not suitable for the production purpose. A future version of JAXB RI
+can change the way it handles RELAX NG, or even drop the support for it.
+
+That said, everything is basically the same as XML Schema ---
+except that you are using RELAX NG as the source schema.
+
+See http://relaxng.org/ for more information about RELAX NG.
\ No newline at end of file
diff --git a/scripts/jaxb-ri/samples/relaxng/sample.meta b/scripts/jaxb-ri/samples/relaxng/sample.meta
new file mode 100644
index 0000000..4333cda
--- /dev/null
+++ b/scripts/jaxb-ri/samples/relaxng/sample.meta
@@ -0,0 +1,34 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0" exclude="true">
+    <title>relaxng</title>
+    
+    <description><![CDATA[
+			This example shows how you can use experimental RELAX NG support.
+    ]]></description>
+    
+    <readme/>
+    
+    <project>
+        <xjc schema="formula.rng">
+            <arg value="-relaxng" />
+        </xjc>
+        
+        <javadoc/>
+        
+        <java mainClass="RELAXNGExample">
+            <arg value="test.xml"/>
+        </java>
+    </project>
+</sample>
diff --git a/scripts/jaxb-ri/samples/relaxng/src/RELAXNGExample.java b/scripts/jaxb-ri/samples/relaxng/src/RELAXNGExample.java
new file mode 100644
index 0000000..bef8822
--- /dev/null
+++ b/scripts/jaxb-ri/samples/relaxng/src/RELAXNGExample.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.File;
+
+import jakarta.xml.bind.JAXBContext;
+
+/**
+ * 
+ * 
+ * @author
+ *     Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
+ */
+public class RELAXNGExample {
+
+    public static void main(String[] args) throws Exception {
+        // in this example, I skip the error check entirely
+        // for the sake of simplicity. In reality, you should
+        // do a better job of handling errors.
+        for( int i=0; i<args.length; i++ ) {
+            test(args[i]);
+        }
+    }
+    
+    private static void test( String fileName ) throws Exception {
+        
+        // there's really nothing special about the code generated
+        // from RELAX NG. So I'll just do the basic operation
+        // to show that it actually feels exactly the same no matter
+        // what schema language you use.
+        
+        JAXBContext context = JAXBContext.newInstance("formula");
+        
+        // unmarshal a file. Just like you've always been doing.
+        Object o = context.createUnmarshaller().unmarshal(new File(fileName)); 
+        
+        // valdiate it. Again, the same procedure regardless of the schema language
+        context.createValidator().validate(o);
+        
+        // marshal it. Nothing new.
+        context.createMarshaller().marshal(o,System.out);
+    }
+}
diff --git a/scripts/jaxb-ri/samples/relaxng/test.xml b/scripts/jaxb-ri/samples/relaxng/test.xml
new file mode 100644
index 0000000..4f233d9
--- /dev/null
+++ b/scripts/jaxb-ri/samples/relaxng/test.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<!--  -3 + (2-5) -->
+<add>
+	<neg><number>3</number></neg>
+	<sub>
+		<number>2</number>
+		<number>5</number>
+	</sub>
+</add>
diff --git a/scripts/jaxb-ri/samples/spec-samples/j2s/class-propOrder-complextype/USAddress.java b/scripts/jaxb-ri/samples/spec-samples/j2s/class-propOrder-complextype/USAddress.java
new file mode 100644
index 0000000..3561aa5
--- /dev/null
+++ b/scripts/jaxb-ri/samples/spec-samples/j2s/class-propOrder-complextype/USAddress.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+/**
+ *  Illustrates the use of
+ *  @jakarta.xml.bind.annotation.XmlType.propOrder() to customize the
+ *  ordering of properties.
+ *
+ *  $Id: USAddress.java,v 1.1 2007-12-05 00:49:36 kohsuke Exp $
+ * 
+ *  Author: Sekhar Vajjhala
+ */  
+
+import jakarta.xml.bind.annotation.XmlType;
+
+@XmlType(propOrder={"name", "street", "city", "state",  "zip"})
+public class USAddress {
+    private java.math.BigDecimal zip;
+    private String name;
+    private String street;
+    private String city;
+    private String state;
+
+
+    String getName() {
+	return name;
+    };
+
+    void setName(String name) {
+	this.name = name;
+    }
+ 
+    String getStreet() {
+	return street;
+    }
+
+    void setStreet(String street) {
+	this.street = street;
+    };
+
+    String getCity() {
+	return city;
+    }; 
+
+    void setCity(String city) {
+	this.city = city;
+    }
+
+    String getState() {
+	return state;
+    }
+
+    void setState(String state) {
+	this.state = state;
+    }
+
+     java.math.BigDecimal getZip() {
+	 return zip;
+     }
+
+     void setZip(java.math.BigDecimal zip) {
+	 this.zip = zip;
+     }
+ }
diff --git a/scripts/jaxb-ri/samples/spec-samples/j2s/class-simpletype/Foo.java b/scripts/jaxb-ri/samples/spec-samples/j2s/class-simpletype/Foo.java
new file mode 100644
index 0000000..079bd2e
--- /dev/null
+++ b/scripts/jaxb-ri/samples/spec-samples/j2s/class-simpletype/Foo.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+/*
+ *  $Id: Foo.java,v 1.1 2007-12-05 00:49:36 kohsuke Exp $
+ *  Author: Sekhar Vajjhala  
+ */  
+
+/**
+ * Map a class with a single property that has been marked with
+ * @XmlValue to simple schema type.
+ */
+import jakarta.xml.bind.annotation.XmlValue;
+ 
+public class Foo {
+    /**
+     * @XmlValue can only be used on a property whose type (int in
+     * this case) is mapped to a simple schema type.
+     */
+    @XmlValue 
+    public int bar;
+}
diff --git a/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/build.xml b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/build.xml
new file mode 100644
index 0000000..dbc8e80
--- /dev/null
+++ b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/build.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <property name="jaxb.home" value="../../../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <!--additional jar files for this sample-->
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+    </java>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/Address.java b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/Address.java
new file mode 100644
index 0000000..a227c0f
--- /dev/null
+++ b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/Address.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+/**
+ *  Author: Sekhar Vajjhala
+ *
+ *  $Id: Address.java,v 1.1 2007-12-05 00:49:36 kohsuke Exp $
+ */  
+
+public class Address {
+    public String name;
+    public String street;
+    public String city;
+}
+
+
+
diff --git a/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/Main.java b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/Main.java
new file mode 100644
index 0000000..c74eb7b
--- /dev/null
+++ b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/Main.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+/**
+ *  Author: Sekhar Vajjhala
+ *
+ *  $Id: Main.java,v 1.1 2007-12-05 00:49:36 kohsuke Exp $
+ */  
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Marshaller;
+
+public class Main {
+    
+    public static void main( String[] args ) {
+        try {
+            /**
+             * Create a JAXBContext passing it a list of classes to be
+             * marshalled.
+             */
+            JAXBContext jc = JAXBContext.newInstance(PurchaseOrder.class, USAddress.class, Address.class);
+            
+            // create a USAddress 
+            USAddress addr = new USAddress();
+            addr.name   = "Alice Smith";
+            addr.street = "123 Maple Street";
+            addr.city   = "Mill Valley";
+            addr.state  = "CA";
+            addr.zip    = 90952;
+
+            // create a po type;
+            PurchaseOrder po = new PurchaseOrder();
+            po.shipTo = addr;
+
+            // create a Marshaller
+            Marshaller m = jc.createMarshaller();
+            m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
+
+            // marshall the address
+            System.out.println(".... Marshal USAddress ....");
+            m.marshal(addr, System.out );
+            /**
+             * OBSERVATIONS:
+             * a. the following print statement needed since Marshaller
+             *    output does not contain a terminating new line
+             *    character.
+             */
+            System.out.println("");
+
+            /**
+             * Marshall the purchase order. 
+             *
+             * OBSERVATIONS:
+             * a. Initially, I forgot to add the PurchaseOrder to
+             *    the list of classes in JAXBContext. So, when passed
+             *    to the marshal method, this resulted in an
+             *    exception.
+             *         Exception in thread "main"
+             *             java.lang.IllegalArgumentException: PurchaseOrder nor
+             *             any of its super class is known to this context
+             *
+             *    I knew "not being known to this context" means that
+             *    the class has to be specified in the
+             *    JAXBContext. Would a newbie JAXB 2.0 be able to
+             *    figure that out ?
+             *
+             * b. If a type is not known at runtime, then an
+             *    alternative to throwing an exception is to
+             *    use reflection to marshal the type. Castor uses this
+             *    approach. 
+             */
+	    
+            System.out.println(".... Marshal PurchaseOrder (USAddress type with xsi type)....");
+            m.marshal(po, System.out );
+            // following print statement needed to insert a new line character.
+            System.out.println("");
+         } catch( JAXBException je ) {
+            je.printStackTrace();
+         }
+    }
+}    
diff --git a/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/PurchaseOrder.java b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/PurchaseOrder.java
new file mode 100644
index 0000000..b74d094
--- /dev/null
+++ b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/PurchaseOrder.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+/**
+ *  Author: Sekhar Vajjhala
+ *
+ *  $Id: PurchaseOrder.java,v 1.1 2007-12-05 00:49:37 kohsuke Exp $
+ */
+
+import jakarta.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement
+public class PurchaseOrder {
+
+    /**
+     * NOTE: Address is used instead of USAddress or UKAddress since
+     * the intent of this sample is to demonstrate the use of xsi type
+     */
+    public Address shipTo;
+    public Address billTo;
+}
+
diff --git a/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/UKAddress.java b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/UKAddress.java
new file mode 100644
index 0000000..9c040ca
--- /dev/null
+++ b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/UKAddress.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+/**
+ *  Author: Sekhar Vajjhala
+ *
+ *  $Id: UKAddress.java,v 1.1 2007-12-05 00:49:37 kohsuke Exp $
+ */  
+
+public class UKAddress extends Address {
+    public String exportcode;
+}
diff --git a/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/USAddress.java b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/USAddress.java
new file mode 100644
index 0000000..c887933
--- /dev/null
+++ b/scripts/jaxb-ri/samples/spec-samples/runtime/derivedtype/src/USAddress.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+/**
+ *  Author: Sekhar Vajjhala
+ *
+ *  $Id: USAddress.java,v 1.1 2007-12-05 00:49:37 kohsuke Exp $
+ */  
+
+import jakarta.xml.bind.annotation.XmlRootElement;
+
+/**
+ * NOTES: If @XmlRootElement is not present, and an attempt is made to
+ * marshal the type, then the marshalled output is:
+ *
+ *     <xml:name>Alice Smith</xml:name>
+ *     <xml:street>123 Maple Street</xml:street>
+ *     <xml:city>Mill Valley</xml:city>
+ *     <xml:state>CA</xml:state>
+ *     <xml:zip>90952</xml:zip>
+ *
+ * In other words, the type is marshaled.
+ *
+ * OBSERVATIONS:
+ * a. At first I did not notice the xml: prefix.
+ * b. For a few seconds I was puzzled why xml:prefix was being output.
+ *    Note, I did not run schemagen.sh to generate the schema. I
+ *    was interested in only going from java -> XML representation.
+ * 
+ *    Why is there a xml: prefix ? 
+ *
+ * c. A few seconds later I realized that this was because I was
+ *    was attempting to marshal a type. Although the use of xml:prefix
+ *    Since I am closely involved with JAXB 2.0, I was able to figure
+ *    this out. I am not sure whether that this would be obvious to a
+ *    user trying out JAXB 2.0 for the first time.
+ *
+ * d. I accidentally put a @XmlElement instead of @XmlRootElement on
+ *    the USAddress type. I got the message 
+ * 
+ *        USAddress.java:3: annotation type not applicable to this kind of declaration
+ *        @XmlElement
+ *        ^
+ *    Of course, I knew @XmlRootElement not @XmlElement must be
+ *    used. However, that would not be immediately obvious to a new
+ *    JAXB 2.0 user. An output of annotations possible on a program
+ *    element might be more helpful.
+ *
+ *    But the above error message is generated from javac not the JAXB 2.0
+ *    runtime. Hence, there is not much that the JAXB 2.0 runtime can
+ *    do about the error message. Such errors can be caught by a
+ *    consistency checker run as a pre-processor.
+ * 
+ * e. After I put a @XmlRootElement on the type, I got the expected
+ *    output:
+ *
+ *        <usAddress>
+ *            <name>Alice Smith</name>
+ *            <street>123 Maple Street</street>
+ *            <city>Mill Valley</city>
+ *            <state>CA</state>
+ *            <zip>90952</zip>
+ *        </usAddress>
+ *
+ */
+
+@XmlRootElement
+public class USAddress extends Address {
+    public String state;
+    public int zip;
+}
+
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/Primer.xsd b/scripts/jaxb-ri/samples/streaming-unmarshalling/Primer.xsd
new file mode 100644
index 0000000..b633a43
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/Primer.xsd
@@ -0,0 +1,82 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+
+
+  <xsd:element name="purchaseOrders">
+    <xsd:complexType>
+      <xsd:sequence>
+        <xsd:element ref="purchaseOrder" minOccurs="0" maxOccurs="unbounded"/>
+      </xsd:sequence>
+    </xsd:complexType>
+  </xsd:element>
+
+
+  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
+
+  <xsd:element name="comment" type="xsd:string"/>
+
+  <xsd:complexType name="PurchaseOrderType">
+    <xsd:sequence>
+      <xsd:element name="shipTo" type="USAddress"/>
+      <xsd:element name="billTo" type="USAddress"/>
+      <xsd:element ref="comment" minOccurs="0"/>
+      <xsd:element name="items" type="Items"/>
+    </xsd:sequence>
+    <xsd:attribute name="orderDate" type="xsd:date"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="USAddress">
+    <xsd:sequence>
+      <xsd:element name="name" type="xsd:string"/>
+      <xsd:element name="street" type="xsd:string"/>
+      <xsd:element name="city" type="xsd:string"/>
+      <xsd:element name="state" type="xsd:string"/>
+      <xsd:element name="zip" type="xsd:decimal"/>
+    </xsd:sequence>
+    <xsd:attribute name="country" type="xsd:NMTOKEN"
+                   fixed="US"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="Items">
+    <xsd:sequence>
+      <xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
+        <xsd:complexType>
+          <xsd:sequence>
+            <xsd:element name="productName" type="xsd:string"/>
+            <xsd:element name="quantity">
+              <xsd:simpleType>
+                <xsd:restriction base="xsd:positiveInteger">
+                  <xsd:maxExclusive value="100"/>
+                </xsd:restriction>
+              </xsd:simpleType>
+            </xsd:element>
+            <xsd:element name="USPrice" type="xsd:decimal"/>
+            <xsd:element ref="comment" minOccurs="0"/>
+            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
+          </xsd:sequence>
+          <xsd:attribute name="partNum" type="SKU" use="required"/>
+        </xsd:complexType>
+      </xsd:element>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <!-- Stock Keeping Unit, a code for identifying products -->
+  <xsd:simpleType name="SKU">
+    <xsd:restriction base="xsd:string">
+      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
+    </xsd:restriction>
+  </xsd:simpleType>
+
+</xsd:schema>
+
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/build.golden.regexp b/scripts/jaxb-ri/samples/streaming-unmarshalling/build.golden.regexp
new file mode 100644
index 0000000..6729050
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/build.golden.regexp
@@ -0,0 +1,13 @@
+
+compile\:
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .+
+    \[javac\] Compiling 6 source files to .+
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] this order will be shipped to Alice Smith
+     \[java\] this order will be shipped to Lee Grant
+
+BUILD SUCCESSFUL
+Total time\: .+ seconds
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/build.xml b/scripts/jaxb-ri/samples/streaming-unmarshalling/build.xml
new file mode 100644
index 0000000..db5e6b5
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/build.xml
@@ -0,0 +1,59 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+        This example illustrates a different approach to the streaming unmarshalling,
+        which is suitable for processing a large document.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+      <arg value="test.xml" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="Streaming Unmarshalling w/o StAX" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/readme.txt b/scripts/jaxb-ri/samples/streaming-unmarshalling/readme.txt
new file mode 100644
index 0000000..730a8cb
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/readme.txt
@@ -0,0 +1,16 @@
+This example is similar in purpose to the partial-unmarshalling sample: it allows
+access to single purchase order objects before the whole input document is
+unmarshalled. This reduces the memory consumption and speeds up the turn around
+time.
+
+While the partial-unmarshalling sample feeds the input document piecemeal to the
+unmarshaller this sample works notification style. Instead of storing all purchase
+orders in the parent object, a listener is called for each child. The listener
+logic and installation can be found in the classes primer.PurchaseOrders and Main.
+
+This approach is in some ways more flexible than StAX, as the boundary of the
+chunking does not have to necessarily correspond with the schema element definition
+boundary. The downside of this is that it requires some manual modifications to
+the generated Java source files.
+
+(Contributed by Matthias Ernst)
\ No newline at end of file
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/sample.meta b/scripts/jaxb-ri/samples/streaming-unmarshalling/sample.meta
new file mode 100644
index 0000000..26296e5
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/sample.meta
@@ -0,0 +1,28 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="2.1">
+    <title>Streaming Unmarshalling w/o StAX</title>
+    <description><![CDATA[
+        This example illustrates a different approach to the streaming unmarshalling,
+        which is suitable for processing a large document.
+    ]]></description>
+    
+    <project>
+        <javadoc/>
+        <java mainClass="Main">
+            <arg value="test.xml"/>
+        </java>
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/src/Main.java b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/Main.java
new file mode 100644
index 0000000..5e83c08
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/Main.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import org.xml.sax.XMLReader;
+import primer.PurchaseOrderType;
+import primer.PurchaseOrders;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.Unmarshaller;
+import javax.xml.parsers.SAXParserFactory;
+import java.io.File;
+
+/*
+ * @(#)$Id: Main.java,v 1.1 2007-12-05 00:49:38 kohsuke Exp $
+ */
+
+public class Main {
+    public static void main( String[] args ) throws Exception {
+        
+        // create JAXBContext for the primer.xsd
+        JAXBContext context = JAXBContext.newInstance("primer");
+
+        Unmarshaller unmarshaller = context.createUnmarshaller();
+
+        // purchase order notification callback
+        final PurchaseOrders.Listener orderListener = new PurchaseOrders.Listener() {
+            public void handlePurchaseOrder(PurchaseOrders purchaseOrders, PurchaseOrderType purchaseOrder) {
+                System.out.println("this order will be shipped to "
+                        + purchaseOrder.getShipTo().getName());
+            }
+        };
+
+        // install the callback on all PurchaseOrders instances
+        unmarshaller.setListener(new Unmarshaller.Listener() {
+            public void beforeUnmarshal(Object target, Object parent) {
+                if(target instanceof PurchaseOrders) {
+                    ((PurchaseOrders)target).setPurchaseOrderListener(orderListener);
+                }
+            }
+
+            public void afterUnmarshal(Object target, Object parent) {
+                if(target instanceof PurchaseOrders) {
+                    ((PurchaseOrders)target).setPurchaseOrderListener(null);
+                }
+            }
+        });
+
+        // create a new XML parser
+        SAXParserFactory factory = SAXParserFactory.newInstance();
+        factory.setNamespaceAware(true);
+        XMLReader reader = factory.newSAXParser().getXMLReader();
+        reader.setContentHandler(unmarshaller.getUnmarshallerHandler());
+
+        for (String arg : args) {
+            // parse all the documents specified via the command line.
+            // note that XMLReader expects an URL, not a file name.
+            // so we need conversion.
+            reader.parse(new File(arg).toURI().toString());
+        }
+    }
+}
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/Items.java b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/Items.java
new file mode 100644
index 0000000..f9661a2
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/Items.java
@@ -0,0 +1,298 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.2-b01-fcs 
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
+// Any modifications to this file will be lost upon recompilation of the source schema. 
+// Generated on: 2006.08.29 at 09:53:40 AM CEST 
+//
+
+
+package primer;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import jakarta.xml.bind.annotation.XmlAccessType;
+import jakarta.xml.bind.annotation.XmlAccessorType;
+import jakarta.xml.bind.annotation.XmlAttribute;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlType;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+
+/**
+ * <p>Java class for Items complex type.
+ * 
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ * 
+ * <pre>
+ * &lt;complexType name="Items">
+ *   &lt;complexContent>
+ *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       &lt;sequence>
+ *         &lt;element name="item" maxOccurs="unbounded" minOccurs="0">
+ *           &lt;complexType>
+ *             &lt;complexContent>
+ *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 &lt;sequence>
+ *                   &lt;element name="productName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   &lt;element name="quantity">
+ *                     &lt;simpleType>
+ *                       &lt;restriction base="{http://www.w3.org/2001/XMLSchema}positiveInteger">
+ *                         &lt;maxExclusive value="100"/>
+ *                       &lt;/restriction>
+ *                     &lt;/simpleType>
+ *                   &lt;/element>
+ *                   &lt;element name="USPrice" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
+ *                   &lt;element ref="{}comment" minOccurs="0"/>
+ *                   &lt;element name="shipDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
+ *                 &lt;/sequence>
+ *                 &lt;attribute name="partNum" use="required" type="{}SKU" />
+ *               &lt;/restriction>
+ *             &lt;/complexContent>
+ *           &lt;/complexType>
+ *         &lt;/element>
+ *       &lt;/sequence>
+ *     &lt;/restriction>
+ *   &lt;/complexContent>
+ * &lt;/complexType>
+ * </pre>
+ * 
+ * 
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "Items", propOrder = {
+    "item"
+})
+public class Items {
+
+    protected List<Item> item;
+
+    /**
+     * Gets the value of the item property.
+     * 
+     * <p>
+     * This accessor method returns a reference to the live list,
+     * not a snapshot. Therefore any modification you make to the
+     * returned list will be present inside the JAXB object.
+     * This is why there is not a <CODE>set</CODE> method for the item property.
+     * 
+     * <p>
+     * For example, to add a new item, do as follows:
+     * <pre>
+     *    getItem().add(newItem);
+     * </pre>
+     * 
+     * 
+     * <p>
+     * Objects of the following type(s) are allowed in the list
+     * {@link primer.Items.Item }
+     * 
+     * 
+     */
+    public List<Item> getItem() {
+        if (item == null) {
+            item = new ArrayList<Item>();
+        }
+        return this.item;
+    }
+
+
+    /**
+     * <p>Java class for anonymous complex type.
+     * 
+     * <p>The following schema fragment specifies the expected content contained within this class.
+     * 
+     * <pre>
+     * &lt;complexType>
+     *   &lt;complexContent>
+     *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       &lt;sequence>
+     *         &lt;element name="productName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         &lt;element name="quantity">
+     *           &lt;simpleType>
+     *             &lt;restriction base="{http://www.w3.org/2001/XMLSchema}positiveInteger">
+     *               &lt;maxExclusive value="100"/>
+     *             &lt;/restriction>
+     *           &lt;/simpleType>
+     *         &lt;/element>
+     *         &lt;element name="USPrice" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
+     *         &lt;element ref="{}comment" minOccurs="0"/>
+     *         &lt;element name="shipDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
+     *       &lt;/sequence>
+     *       &lt;attribute name="partNum" use="required" type="{}SKU" />
+     *     &lt;/restriction>
+     *   &lt;/complexContent>
+     * &lt;/complexType>
+     * </pre>
+     * 
+     * 
+     */
+    @XmlAccessorType(XmlAccessType.FIELD)
+    @XmlType(name = "", propOrder = {
+        "productName",
+        "quantity",
+        "usPrice",
+        "comment",
+        "shipDate"
+    })
+    public static class Item {
+
+        @XmlElement(required = true)
+        protected String productName;
+        protected int quantity;
+        @XmlElement(name = "USPrice", required = true)
+        protected BigDecimal usPrice;
+        protected String comment;
+        protected XMLGregorianCalendar shipDate;
+        @XmlAttribute(required = true)
+        protected String partNum;
+
+        /**
+         * Gets the value of the productName property.
+         * 
+         * @return
+         *     possible object is
+         *     {@link String }
+         *     
+         */
+        public String getProductName() {
+            return productName;
+        }
+
+        /**
+         * Sets the value of the productName property.
+         * 
+         * @param value
+         *     allowed object is
+         *     {@link String }
+         *     
+         */
+        public void setProductName(String value) {
+            this.productName = value;
+        }
+
+        /**
+         * Gets the value of the quantity property.
+         * 
+         */
+        public int getQuantity() {
+            return quantity;
+        }
+
+        /**
+         * Sets the value of the quantity property.
+         * 
+         */
+        public void setQuantity(int value) {
+            this.quantity = value;
+        }
+
+        /**
+         * Gets the value of the usPrice property.
+         * 
+         * @return
+         *     possible object is
+         *     {@link java.math.BigDecimal }
+         *     
+         */
+        public BigDecimal getUSPrice() {
+            return usPrice;
+        }
+
+        /**
+         * Sets the value of the usPrice property.
+         * 
+         * @param value
+         *     allowed object is
+         *     {@link java.math.BigDecimal }
+         *     
+         */
+        public void setUSPrice(BigDecimal value) {
+            this.usPrice = value;
+        }
+
+        /**
+         * Gets the value of the comment property.
+         * 
+         * @return
+         *     possible object is
+         *     {@link String }
+         *     
+         */
+        public String getComment() {
+            return comment;
+        }
+
+        /**
+         * Sets the value of the comment property.
+         * 
+         * @param value
+         *     allowed object is
+         *     {@link String }
+         *     
+         */
+        public void setComment(String value) {
+            this.comment = value;
+        }
+
+        /**
+         * Gets the value of the shipDate property.
+         * 
+         * @return
+         *     possible object is
+         *     {@link javax.xml.datatype.XMLGregorianCalendar }
+         *     
+         */
+        public XMLGregorianCalendar getShipDate() {
+            return shipDate;
+        }
+
+        /**
+         * Sets the value of the shipDate property.
+         * 
+         * @param value
+         *     allowed object is
+         *     {@link javax.xml.datatype.XMLGregorianCalendar }
+         *     
+         */
+        public void setShipDate(XMLGregorianCalendar value) {
+            this.shipDate = value;
+        }
+
+        /**
+         * Gets the value of the partNum property.
+         * 
+         * @return
+         *     possible object is
+         *     {@link String }
+         *     
+         */
+        public String getPartNum() {
+            return partNum;
+        }
+
+        /**
+         * Sets the value of the partNum property.
+         * 
+         * @param value
+         *     allowed object is
+         *     {@link String }
+         *     
+         */
+        public void setPartNum(String value) {
+            this.partNum = value;
+        }
+
+    }
+
+}
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/ObjectFactory.java b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/ObjectFactory.java
new file mode 100644
index 0000000..f5caf45
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/ObjectFactory.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.2-b01-fcs 
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
+// Any modifications to this file will be lost upon recompilation of the source schema. 
+// Generated on: 2006.08.29 at 09:53:40 AM CEST 
+//
+
+
+package primer;
+
+import jakarta.xml.bind.JAXBElement;
+import jakarta.xml.bind.annotation.XmlElementDecl;
+import jakarta.xml.bind.annotation.XmlRegistry;
+import javax.xml.namespace.QName;
+
+
+/**
+ * This object contains factory methods for each 
+ * Java content interface and Java element interface 
+ * generated in the primer package. 
+ * <p>An ObjectFactory allows you to programatically 
+ * construct new instances of the Java representation 
+ * for XML content. The Java representation of XML 
+ * content can consist of schema derived interfaces 
+ * and classes representing the binding of schema 
+ * type definitions, element declarations and model 
+ * groups.  Factory methods for each of these are 
+ * provided in this class.
+ * 
+ */
+@XmlRegistry
+public class ObjectFactory {
+
+    private final static QName _PurchaseOrder_QNAME = new QName("", "purchaseOrder");
+    private final static QName _Comment_QNAME = new QName("", "comment");
+
+    /**
+     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: primer
+     * 
+     */
+    public ObjectFactory() {
+    }
+
+    /**
+     * Create an instance of {@link PurchaseOrders }
+     * 
+     */
+    public PurchaseOrders createPurchaseOrders() {
+        return new PurchaseOrders();
+    }
+
+    /**
+     * Create an instance of {@link primer.Items.Item }
+     * 
+     */
+    public Items.Item createItemsItem() {
+        return new Items.Item();
+    }
+
+    /**
+     * Create an instance of {@link USAddress }
+     * 
+     */
+    public USAddress createUSAddress() {
+        return new USAddress();
+    }
+
+    /**
+     * Create an instance of {@link PurchaseOrderType }
+     * 
+     */
+    public PurchaseOrderType createPurchaseOrderType() {
+        return new PurchaseOrderType();
+    }
+
+    /**
+     * Create an instance of {@link primer.Items }
+     * 
+     */
+    public Items createItems() {
+        return new Items();
+    }
+
+    /**
+     * Create an instance of {@link jakarta.xml.bind.JAXBElement }{@code <}{@link PurchaseOrderType }{@code >}}
+     * 
+     */
+    @XmlElementDecl(namespace = "", name = "purchaseOrder")
+    public JAXBElement<PurchaseOrderType> createPurchaseOrder(PurchaseOrderType value) {
+        return new JAXBElement<PurchaseOrderType>(_PurchaseOrder_QNAME, PurchaseOrderType.class, null, value);
+    }
+
+    /**
+     * Create an instance of {@link jakarta.xml.bind.JAXBElement }{@code <}{@link String }{@code >}}
+     * 
+     */
+    @XmlElementDecl(namespace = "", name = "comment")
+    public JAXBElement<String> createComment(String value) {
+        return new JAXBElement<String>(_Comment_QNAME, String.class, null, value);
+    }
+
+}
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/PurchaseOrderType.java b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/PurchaseOrderType.java
new file mode 100644
index 0000000..071adc4
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/PurchaseOrderType.java
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.2-b01-fcs 
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
+// Any modifications to this file will be lost upon recompilation of the source schema. 
+// Generated on: 2006.08.29 at 09:53:40 AM CEST 
+//
+
+
+package primer;
+
+import jakarta.xml.bind.annotation.XmlAccessType;
+import jakarta.xml.bind.annotation.XmlAccessorType;
+import jakarta.xml.bind.annotation.XmlAttribute;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlType;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+
+/**
+ * <p>Java class for PurchaseOrderType complex type.
+ * 
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ * 
+ * <pre>
+ * &lt;complexType name="PurchaseOrderType">
+ *   &lt;complexContent>
+ *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       &lt;sequence>
+ *         &lt;element name="shipTo" type="{}USAddress"/>
+ *         &lt;element name="billTo" type="{}USAddress"/>
+ *         &lt;element ref="{}comment" minOccurs="0"/>
+ *         &lt;element name="items" type="{}Items"/>
+ *       &lt;/sequence>
+ *       &lt;attribute name="orderDate" type="{http://www.w3.org/2001/XMLSchema}date" />
+ *     &lt;/restriction>
+ *   &lt;/complexContent>
+ * &lt;/complexType>
+ * </pre>
+ * 
+ * 
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "PurchaseOrderType", propOrder = {
+    "shipTo",
+    "billTo",
+    "comment",
+    "items"
+})
+public class PurchaseOrderType {
+
+    @XmlElement(required = true)
+    protected USAddress shipTo;
+    @XmlElement(required = true)
+    protected USAddress billTo;
+    protected String comment;
+    @XmlElement(required = true)
+    protected Items items;
+    @XmlAttribute
+    protected XMLGregorianCalendar orderDate;
+
+    /**
+     * Gets the value of the shipTo property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link USAddress }
+     *     
+     */
+    public USAddress getShipTo() {
+        return shipTo;
+    }
+
+    /**
+     * Sets the value of the shipTo property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link USAddress }
+     *     
+     */
+    public void setShipTo(USAddress value) {
+        this.shipTo = value;
+    }
+
+    /**
+     * Gets the value of the billTo property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link USAddress }
+     *     
+     */
+    public USAddress getBillTo() {
+        return billTo;
+    }
+
+    /**
+     * Sets the value of the billTo property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link USAddress }
+     *     
+     */
+    public void setBillTo(USAddress value) {
+        this.billTo = value;
+    }
+
+    /**
+     * Gets the value of the comment property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getComment() {
+        return comment;
+    }
+
+    /**
+     * Sets the value of the comment property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setComment(String value) {
+        this.comment = value;
+    }
+
+    /**
+     * Gets the value of the items property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link primer.Items }
+     *     
+     */
+    public Items getItems() {
+        return items;
+    }
+
+    /**
+     * Sets the value of the items property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link primer.Items }
+     *     
+     */
+    public void setItems(Items value) {
+        this.items = value;
+    }
+
+    /**
+     * Gets the value of the orderDate property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link javax.xml.datatype.XMLGregorianCalendar }
+     *     
+     */
+    public XMLGregorianCalendar getOrderDate() {
+        return orderDate;
+    }
+
+    /**
+     * Sets the value of the orderDate property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link javax.xml.datatype.XMLGregorianCalendar }
+     *     
+     */
+    public void setOrderDate(XMLGregorianCalendar value) {
+        this.orderDate = value;
+    }
+
+}
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/PurchaseOrders.java b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/PurchaseOrders.java
new file mode 100644
index 0000000..c405440
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/PurchaseOrders.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.2-b01-fcs 
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
+// Any modifications to this file will be lost upon recompilation of the source schema. 
+// Generated on: 2006.08.29 at 09:53:40 AM CEST 
+//
+
+
+package primer;
+
+import java.util.ArrayList;
+import java.util.List;
+import jakarta.xml.bind.annotation.XmlAccessType;
+import jakarta.xml.bind.annotation.XmlAccessorType;
+import jakarta.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for anonymous complex type.
+ * 
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ * 
+ * <pre>
+ * &lt;complexType>
+ *   &lt;complexContent>
+ *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       &lt;sequence>
+ *         &lt;element ref="{}purchaseOrder" maxOccurs="unbounded" minOccurs="0"/>
+ *       &lt;/sequence>
+ *     &lt;/restriction>
+ *   &lt;/complexContent>
+ * &lt;/complexType>
+ * </pre>
+ * 
+ * 
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "", propOrder = {
+    "purchaseOrder"
+})
+@XmlRootElement(name = "purchaseOrders")
+public class PurchaseOrders {
+
+    /**
+     * This list is not a real list; instead it will notify a listener whenever
+     * JAXB has unmarshalled the next purchase order.
+     */
+    protected List<PurchaseOrderType> purchaseOrder;
+
+    /**
+     * Install a listener for purchase orders on this object. If l is null, the listener
+     * is removed again.
+     */
+    public void setPurchaseOrderListener(final Listener l) {
+        purchaseOrder = (l == null) ? null : new ArrayList<PurchaseOrderType>() {
+            public boolean add(PurchaseOrderType o) {
+                l.handlePurchaseOrder(PurchaseOrders.this, o);
+                return false;
+            }
+        };
+    }
+
+    /**
+     * This listener is invoked every time a new purchase order is unmarshalled.
+     */
+    public static interface Listener {
+        void handlePurchaseOrder(PurchaseOrders purchaseOrders, PurchaseOrderType purchaseOrder);
+    }
+}
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/USAddress.java b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/USAddress.java
new file mode 100644
index 0000000..b326abe
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/src/primer/USAddress.java
@@ -0,0 +1,227 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.2-b01-fcs 
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
+// Any modifications to this file will be lost upon recompilation of the source schema. 
+// Generated on: 2006.08.29 at 09:53:40 AM CEST 
+//
+
+
+package primer;
+
+import java.math.BigDecimal;
+import jakarta.xml.bind.annotation.XmlAccessType;
+import jakarta.xml.bind.annotation.XmlAccessorType;
+import jakarta.xml.bind.annotation.XmlAttribute;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlType;
+import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter;
+import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+
+
+/**
+ * <p>Java class for USAddress complex type.
+ * 
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ * 
+ * <pre>
+ * &lt;complexType name="USAddress">
+ *   &lt;complexContent>
+ *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       &lt;sequence>
+ *         &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         &lt;element name="street" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         &lt;element name="city" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         &lt;element name="state" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         &lt;element name="zip" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
+ *       &lt;/sequence>
+ *       &lt;attribute name="country" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" fixed="US" />
+ *     &lt;/restriction>
+ *   &lt;/complexContent>
+ * &lt;/complexType>
+ * </pre>
+ * 
+ * 
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "USAddress", propOrder = {
+    "name",
+    "street",
+    "city",
+    "state",
+    "zip"
+})
+public class USAddress {
+
+    @XmlElement(required = true)
+    protected String name;
+    @XmlElement(required = true)
+    protected String street;
+    @XmlElement(required = true)
+    protected String city;
+    @XmlElement(required = true)
+    protected String state;
+    @XmlElement(required = true)
+    protected BigDecimal zip;
+    @XmlAttribute
+    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
+    protected String country;
+
+    /**
+     * Gets the value of the name property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * Sets the value of the name property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setName(String value) {
+        this.name = value;
+    }
+
+    /**
+     * Gets the value of the street property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getStreet() {
+        return street;
+    }
+
+    /**
+     * Sets the value of the street property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setStreet(String value) {
+        this.street = value;
+    }
+
+    /**
+     * Gets the value of the city property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getCity() {
+        return city;
+    }
+
+    /**
+     * Sets the value of the city property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setCity(String value) {
+        this.city = value;
+    }
+
+    /**
+     * Gets the value of the state property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getState() {
+        return state;
+    }
+
+    /**
+     * Sets the value of the state property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setState(String value) {
+        this.state = value;
+    }
+
+    /**
+     * Gets the value of the zip property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link java.math.BigDecimal }
+     *     
+     */
+    public BigDecimal getZip() {
+        return zip;
+    }
+
+    /**
+     * Sets the value of the zip property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link java.math.BigDecimal }
+     *     
+     */
+    public void setZip(BigDecimal value) {
+        this.zip = value;
+    }
+
+    /**
+     * Gets the value of the country property.
+     * 
+     * @return
+     *     possible object is
+     *     {@link String }
+     *     
+     */
+    public String getCountry() {
+        if (country == null) {
+            return "US";
+        } else {
+            return country;
+        }
+    }
+
+    /**
+     * Sets the value of the country property.
+     * 
+     * @param value
+     *     allowed object is
+     *     {@link String }
+     *     
+     */
+    public void setCountry(String value) {
+        this.country = value;
+    }
+
+}
diff --git a/scripts/jaxb-ri/samples/streaming-unmarshalling/test.xml b/scripts/jaxb-ri/samples/streaming-unmarshalling/test.xml
new file mode 100644
index 0000000..1ca19d6
--- /dev/null
+++ b/scripts/jaxb-ri/samples/streaming-unmarshalling/test.xml
@@ -0,0 +1,53 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<purchaseOrders>
+  <!-- 1st -->
+  <purchaseOrder orderDate="1999-10-20">
+    <shipTo country="US">
+      <name>Alice Smith</name>
+      <street>123 Maple Street</street>
+      <city>Cambridge</city>
+      <state>MA</state>
+      <zip>12345</zip>
+    </shipTo>
+    <billTo country="US">
+      <name>Robert Smith</name>
+      <street>8 Oak Avenue</street>
+      <city>Cambridge</city>
+      <state>MA</state>
+      <zip>12345</zip>
+    </billTo>
+    <items/>
+  </purchaseOrder>
+
+  <!-- 2nd -->
+  <purchaseOrder orderDate="1999-10-20">
+    <shipTo country="US">
+      <name>Lee Grant</name>
+      <street>123 Maple Street</street>
+      <city>Cambridge</city>
+      <state>MA</state>
+      <zip>12345</zip>
+    </shipTo>
+    <billTo country="US">
+      <name>Stonewall Jackson</name>
+      <street>8 Oak Avenue</street>
+      <city>Lexington</city>
+      <state>MA</state>
+      <zip>12345</zip>
+    </billTo>
+    <items/>
+  </purchaseOrder>
+</purchaseOrders>
+
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/build.golden.regexp b/scripts/jaxb-ri/samples/subgroup-extend/build.golden.regexp
new file mode 100644
index 0000000..2c94e4c
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/build.golden.regexp
@@ -0,0 +1,87 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] Process references using polymorphic method
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+     \[java\] \[1\]
+     \[java\] Origin\=BOSTON
+     \[java\] Destination\=SAN FRANCISCO
+     \[java\] Flight Number\: 195
+     \[java\] Meal\: breakfast
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<plane xmlns\=\"http\:\/\/example\.org\"\>
+     \[java\]     \<origin xmlns\=\"\"\>BOSTON\<\/origin\>
+     \[java\]     \<destination xmlns\=\"\"\>SAN FRANCISCO\<\/destination\>
+     \[java\]     \<flightNumber xmlns\=\"\"\>195\<\/flightNumber\>
+     \[java\]     \<meal xmlns\=\"\"\>breakfast\<\/meal\>
+     \[java\] \<\/plane\>
+
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+     \[java\] \[2\]
+     \[java\] Origin\=SAN FRANCISCO
+     \[java\] Destination\=SAN FRANCISCO
+     \[java\] Rental Agency\:Hertz
+     \[java\] Rate Per Hour\:2
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<auto xmlns\=\"http\:\/\/example\.org\"\>
+     \[java\]     \<origin xmlns\=\"\"\>SAN FRANCISCO\<\/origin\>
+     \[java\]     \<destination xmlns\=\"\"\>SAN FRANCISCO\<\/destination\>
+     \[java\]     \<rentalAgency xmlns\=\"\"\>Hertz\<\/rentalAgency\>
+     \[java\]     \<ratePerHour xmlns\=\"\"\>2\<\/ratePerHour\>
+     \[java\] \<\/auto\>
+
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+     \[java\] \[3\]
+     \[java\] Origin\=BOSTON
+     \[java\] Destination\=NEW YORK
+     \[java\] Track\: 9
+     \[java\] Schedule# 805
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<train xmlns\=\"http\:\/\/example\.org\"\>
+     \[java\]     \<origin xmlns\=\"\"\>BOSTON\<\/origin\>
+     \[java\]     \<destination xmlns\=\"\"\>NEW YORK\<\/destination\>
+     \[java\]     \<track xmlns\=\"\"\>9\<\/track\>
+     \[java\]     \<dailyScheduleNumber xmlns\=\"\"\>805\<\/dailyScheduleNumber\>
+     \[java\] \<\/train\>
+
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<itinerary xmlns\=\"http\:\/\/example\.org\"\>
+     \[java\]     \<plane\>
+     \[java\]         \<origin xmlns\=\"\"\>BOSTON\<\/origin\>
+     \[java\]         \<destination xmlns\=\"\"\>SAN FRANCISCO\<\/destination\>
+     \[java\]         \<flightNumber xmlns\=\"\"\>195\<\/flightNumber\>
+     \[java\]         \<meal xmlns\=\"\"\>breakfast\<\/meal\>
+     \[java\]     \<\/plane\>
+     \[java\]     \<auto\>
+     \[java\]         \<origin xmlns\=\"\"\>SAN FRANCISCO\<\/origin\>
+     \[java\]         \<destination xmlns\=\"\"\>SAN FRANCISCO\<\/destination\>
+     \[java\]         \<rentalAgency xmlns\=\"\"\>Hertz\<\/rentalAgency\>
+     \[java\]         \<ratePerHour xmlns\=\"\"\>2\<\/ratePerHour\>
+     \[java\]     \<\/auto\>
+     \[java\]     \<train\>
+     \[java\]         \<origin xmlns\=\"\"\>BOSTON\<\/origin\>
+     \[java\]         \<destination xmlns\=\"\"\>NEW YORK\<\/destination\>
+     \[java\]         \<track xmlns\=\"\"\>9\<\/track\>
+     \[java\]         \<dailyScheduleNumber xmlns\=\"\"\>805\<\/dailyScheduleNumber\>
+     \[java\]     \<\/train\>
+     \[java\] \<\/itinerary\>
+
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/build.xml b/scripts/jaxb-ri/samples/subgroup-extend/build.xml
new file mode 100644
index 0000000..a956ffd
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/build.xml
@@ -0,0 +1,60 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+    This example shows how the use of the jxb:implClass customization and
+    substitution groups can be used to inject virtual functions into the
+    derived Java hierarchy. It compares two equivalent ways of achieving
+    the same processing, but one is much simpler than the other (search for
+    the "enlightened" boolean flag in the code).
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="gen-src" />
+    <pathelement path="classes" />
+    <!--additional jar files for this sample-->
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc extension="true" schema="itinerary.xsd" package="extend" destdir="gen-src">
+      <produces dir="gen-src/extend" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+    </java>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/itinerary.xml b/scripts/jaxb-ri/samples/subgroup-extend/itinerary.xml
new file mode 100644
index 0000000..612ecc4
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/itinerary.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<e:itinerary xmlns="" xmlns:e="http://example.org">
+  <e:plane>
+    <origin>BOSTON</origin>
+    <destination>SAN FRANCISCO</destination>
+    <flightNumber>195</flightNumber>
+    <meal>breakfast</meal>
+  </e:plane>
+  <e:auto>
+    <origin>SAN FRANCISCO</origin>
+    <destination>SAN FRANCISCO</destination>
+    <rentalAgency>Hertz</rentalAgency>
+    <ratePerHour>2</ratePerHour>
+  </e:auto>
+  <e:train>
+    <origin>BOSTON</origin>
+    <destination>NEW YORK</destination>
+    <track>9</track>
+    <dailyScheduleNumber>805</dailyScheduleNumber>
+  </e:train>
+</e:itinerary>
+
+
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/itinerary.xsd b/scripts/jaxb-ri/samples/subgroup-extend/itinerary.xsd
new file mode 100644
index 0000000..84ec30d
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/itinerary.xsd
@@ -0,0 +1,114 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+            targetNamespace="http://example.org"
+            xmlns:e="http://example.org"
+            xmlns:jxb="https://jakarta.ee/xml/ns/jaxb"
+            jxb:version="3.0">
+  <xsd:annotation>
+    <xsd:appinfo>
+      <jxb:globalBindings generateIsSetMethod="true"/>
+    </xsd:appinfo>
+  </xsd:annotation>
+
+  <!-- type derivation hierarchy
+
+               TravelType
+               /     |    \
+       PlaneType AutoType  TrainType
+  -->
+
+  <xsd:complexType name="TravelType">
+    <xsd:annotation>
+      <xsd:appinfo>
+        <jxb:class implClass="extend.TravelTypeExtend"/>
+      </xsd:appinfo>
+    </xsd:annotation>
+    <xsd:sequence>
+      <xsd:element name="origin" type="xsd:string"/>
+      <xsd:element name="destination" type="xsd:string"/>
+    </xsd:sequence>
+  </xsd:complexType>
+  <xsd:complexType name="PlaneType">
+    <xsd:annotation>
+      <xsd:appinfo>
+        <jxb:class implClass="extend.PlaneTypeExtend"/>
+      </xsd:appinfo>
+    </xsd:annotation>
+    <xsd:complexContent>
+      <xsd:extension base="e:TravelType">
+        <xsd:sequence>
+          <xsd:element name="flightNumber" type="xsd:int"/>
+          <xsd:element name="meal" type="xsd:string"/>
+        </xsd:sequence>
+      </xsd:extension>
+    </xsd:complexContent>
+  </xsd:complexType>
+
+  <xsd:complexType name="AutoType">
+    <xsd:annotation>
+      <xsd:appinfo>
+        <jxb:class implClass="extend.AutoTypeExtend"/>
+      </xsd:appinfo>
+    </xsd:annotation>
+    <xsd:complexContent>
+      <xsd:extension base="e:TravelType">
+        <xsd:sequence>
+          <xsd:element name="rentalAgency" type="e:RentalCompany"/>
+          <xsd:element name="ratePerHour" type="xsd:int"/>
+        </xsd:sequence>
+      </xsd:extension>
+    </xsd:complexContent>
+  </xsd:complexType>
+  <xsd:complexType name="TrainType">
+    <xsd:annotation>
+      <xsd:appinfo>
+        <jxb:class implClass="extend.TrainTypeExtend"/>
+      </xsd:appinfo>
+    </xsd:annotation>
+    <xsd:complexContent>
+      <xsd:extension base="e:TravelType">
+        <xsd:sequence>
+          <xsd:element name="track" type="xsd:int"/>
+          <xsd:element name="dailyScheduleNumber" type="xsd:int"/>
+        </xsd:sequence>
+      </xsd:extension>
+    </xsd:complexContent>
+  </xsd:complexType>
+
+  <xsd:simpleType name="RentalCompany">
+    <xsd:restriction base="xsd:NCName">
+      <xsd:enumeration value="Avis"/>
+      <xsd:enumeration value="Hertz"/>
+      <xsd:enumeration value="RentAWreck"/>
+    </xsd:restriction>
+  </xsd:simpleType>
+
+  <!-- Create the substitution group with head element "e:travel". -->
+  <xsd:element name="travel" type="e:TravelType"/>
+  <xsd:element name="plane" type="e:PlaneType"
+               substitutionGroup="e:travel"/>
+  <xsd:element name="auto" type="e:AutoType"
+               substitutionGroup="e:travel"/>
+  <xsd:element name="train" type="e:TrainType"
+               substitutionGroup="e:travel"/>
+
+  <xsd:element name="itinerary">
+    <xsd:complexType>
+      <xsd:sequence>
+        <xsd:element ref="e:travel" maxOccurs="unbounded"/>
+        <!-- much other stuff -->
+      </xsd:sequence>
+    </xsd:complexType>
+  </xsd:element>
+</xsd:schema>
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/sample.meta b/scripts/jaxb-ri/samples/subgroup-extend/sample.meta
new file mode 100644
index 0000000..dbca44b
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/sample.meta
@@ -0,0 +1,34 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0.2" exclude="true">
+    <title>subgroup-extend</title>
+    
+    <description><![CDATA[
+        This example shows how the use of the jxb:implClass customization and 
+        substitution groups can be used to inject virtual functions into the 
+        derived Java hierarchy. It compares two equivalent ways of achieving 
+        the same processing, but one is much simpler than the other (search for 
+        the "enlightened" boolean flag in the code).
+    ]]></description>
+    
+    <readme/>
+    
+    <project>
+        <xjc extension="true" schema="itinerary.xsd" package="org.example"/>
+        
+        <javadoc/>
+        
+        <java mainClass="Main"/>
+    </project>
+</sample>
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/src/Main.java b/scripts/jaxb-ri/samples/subgroup-extend/src/Main.java
new file mode 100644
index 0000000..3b54b26
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/src/Main.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.FileInputStream;
+import java.io.IOException;
+
+import jakarta.xml.bind.JAXBElement;
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Marshaller;
+import jakarta.xml.bind.Unmarshaller;
+
+// import java content classes generated by binding compiler
+import extend.*;
+
+/*
+ * $Id: Main.java,v 1.1 2007-12-05 00:49:39 kohsuke Exp $
+ */
+ 
+public class Main {
+    // This sample application demonstrates how to modify a java content
+    // tree and marshal it back to a xml data
+    
+    public static void main( String[] args ) {
+	final boolean enlightened = true;
+
+        try {
+            // create a JAXBContext capable of handling classes generated into
+            // the org.example package
+            JAXBContext jc = JAXBContext.newInstance( "extend" );
+            
+            // create an Unmarshaller
+            Unmarshaller u = jc.createUnmarshaller();
+            
+            // unmarshal a po instance document into a tree of Java content
+            // objects composed of classes from the primer.po package.
+            Itinerary it = 
+                (Itinerary)u.unmarshal( new FileInputStream( "itinerary.xml" ) );
+
+            ObjectFactory of = new ObjectFactory();
+	        java.util.Iterator iter = it.getTravel().listIterator();
+
+            if (enlightened) {
+	            System.out.println("Process references using polymorphic method");
+            } else {
+	            System.out.println("Process references using forest of if-then-else :(");
+            }
+	    for(int i=1; iter.hasNext(); i++) {
+	        // Travel Entry Header
+ 	        System.out.println("****************************");
+		    System.out.println("[" + i + "]");
+
+	        // Process travel entry
+            JAXBElement jxbe = (JAXBElement)iter.next();
+   	        TravelType travel = (TravelType)jxbe.getValue();
+	        if (enlightened) {
+	          ((TravelTypeExtend)travel).printTravelSummary();
+
+                  Marshaller m = jc.createMarshaller();
+                  m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
+                  m.marshal( of.createTravel(travel), System.out );
+
+                } else {
+		  // Proceed down the forest of Ifs-then-elses.
+  	          System.out.println("Origin=" + travel.getOrigin());
+	          System.out.println("Destination=" + travel.getDestination());
+		  if (travel instanceof PlaneType) {
+	             PlaneType planet= (PlaneType)travel;
+	             System.out.println("Flight Number: " +
+					 planet.getFlightNumber());
+	             System.out.println("Meal: " + planet.getMeal());
+
+                  } else if (travel instanceof AutoType) {
+	             AutoType auto= (AutoType)travel;
+	             System.out.println("Rental Agency:" + auto.getRentalAgency());
+   	             System.out.println("Rate Per Hour:" + auto.getRatePerHour());
+                  } else if (travel instanceof TrainType) {
+	             TrainType train= (TrainType)travel;
+                     System.out.println("Track: " + train.getTrack());
+                     System.out.println("Schedule# " + 
+				train.getDailyScheduleNumber());
+                  }
+               }
+              // Travel Entry footer
+              System.out.println("****************************");
+	        System.out.println();
+            }
+
+            // create a Marshaller and marshal to a file
+            Marshaller m = jc.createMarshaller();
+            m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
+            m.marshal( it, System.out );
+            
+        } catch( JAXBException je ) {
+            je.printStackTrace();
+        } catch( IOException ioe ) {
+            ioe.printStackTrace();
+        }
+    }
+}
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/src/extend/AutoTypeExtend.java b/scripts/jaxb-ri/samples/subgroup-extend/src/extend/AutoTypeExtend.java
new file mode 100644
index 0000000..c2b5b09
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/src/extend/AutoTypeExtend.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+package extend;
+
+public class AutoTypeExtend extends AutoType {
+    public void printTravelSummary() {
+	super.printTravelSummary();
+	System.out.println("Rental Agency:" + getRentalAgency());
+	System.out.println("Rate Per Hour:" + getRatePerHour());
+    }
+}
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/src/extend/PlaneTypeExtend.java b/scripts/jaxb-ri/samples/subgroup-extend/src/extend/PlaneTypeExtend.java
new file mode 100644
index 0000000..e5de0ed
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/src/extend/PlaneTypeExtend.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+package extend;
+
+public class PlaneTypeExtend extends PlaneType {
+    public void printTravelSummary() {
+	super.printTravelSummary();
+	System.out.println("Flight Number: " + getFlightNumber());
+	System.out.println("Meal: " + getMeal());
+    }
+}
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/src/extend/TrainTypeExtend.java b/scripts/jaxb-ri/samples/subgroup-extend/src/extend/TrainTypeExtend.java
new file mode 100644
index 0000000..10e971b
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/src/extend/TrainTypeExtend.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+package extend;
+
+public class TrainTypeExtend extends TrainType {
+    public void printTravelSummary() {
+	super.printTravelSummary();
+        System.out.println("Track: " + getTrack());
+        System.out.println("Schedule# " + getDailyScheduleNumber());
+    }
+}
diff --git a/scripts/jaxb-ri/samples/subgroup-extend/src/extend/TravelTypeExtend.java b/scripts/jaxb-ri/samples/subgroup-extend/src/extend/TravelTypeExtend.java
new file mode 100644
index 0000000..96e4584
--- /dev/null
+++ b/scripts/jaxb-ri/samples/subgroup-extend/src/extend/TravelTypeExtend.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+package extend;
+
+public class TravelTypeExtend extends TravelType {
+    public void printTravelSummary() {
+	System.out.println("Origin=" + getOrigin());
+	System.out.println("Destination=" + getDestination());
+    }
+}
diff --git a/scripts/jaxb-ri/samples/synchronized-methods/build.golden.regexp b/scripts/jaxb-ri/samples/synchronized-methods/build.golden.regexp
new file mode 100644
index 0000000..3a6c61b
--- /dev/null
+++ b/scripts/jaxb-ri/samples/synchronized-methods/build.golden.regexp
@@ -0,0 +1,16 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] done
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/synchronized-methods/build.xml b/scripts/jaxb-ri/samples/synchronized-methods/build.xml
new file mode 100644
index 0000000..4efb0cf
--- /dev/null
+++ b/scripts/jaxb-ri/samples/synchronized-methods/build.xml
@@ -0,0 +1,67 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+      This sample shows how to use the new non-standard synchronized
+      method support. By following the instructions in the readme.txt,
+      you can cause all of the generated impl class methods signatures
+      to contain the "synchronized" keyword.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc extension="true" schema="po.xsd" package="primer.myPo" destdir="gen-src">
+      <arg value="-Xsync-methods" />
+      <produces dir="gen-src/primer.myPo" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="done" />
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="Generating synchronized methods" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/synchronized-methods/po.xsd b/scripts/jaxb-ri/samples/synchronized-methods/po.xsd
new file mode 100644
index 0000000..fc2a3ee
--- /dev/null
+++ b/scripts/jaxb-ri/samples/synchronized-methods/po.xsd
@@ -0,0 +1,70 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+            xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+            jaxb:version="3.0">
+
+  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
+  <xsd:element name="comment" type="xsd:string"/>
+  <xsd:complexType name="PurchaseOrderType">
+    <xsd:sequence>
+      <xsd:element name="shipTo" type="USAddress"/>
+      <xsd:element name="billTo" type="USAddress"/>
+      <xsd:element ref="comment" minOccurs="0"/>
+      <xsd:element name="items" type="Items"/>
+    </xsd:sequence>
+    <xsd:attribute name="orderDate" type="xsd:date"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="USAddress">
+    <xsd:sequence>
+      <xsd:element name="name" type="xsd:string"/>
+      <xsd:element name="street" type="xsd:string"/>
+      <xsd:element name="city" type="xsd:string"/>
+      <xsd:element name="state" type="xsd:string"/>
+      <xsd:element name="zip" type="xsd:decimal"/>
+    </xsd:sequence>
+    <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="Items">
+    <xsd:sequence>
+      <xsd:element name="item" minOccurs="1" maxOccurs="unbounded">
+        <xsd:complexType>
+          <xsd:sequence>
+            <xsd:element name="productName" type="xsd:string"/>
+            <xsd:element name="quantity">
+              <xsd:simpleType>
+                <xsd:restriction base="xsd:positiveInteger">
+                  <xsd:maxExclusive value="100"/>
+                </xsd:restriction>
+              </xsd:simpleType>
+            </xsd:element>
+            <xsd:element name="USPrice" type="xsd:decimal"/>
+            <xsd:element ref="comment" minOccurs="0"/>
+            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
+          </xsd:sequence>
+          <xsd:attribute name="partNum" type="SKU" use="required"/>
+        </xsd:complexType>
+      </xsd:element>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <!-- Stock Keeping Unit, a code for identifying products -->
+  <xsd:simpleType name="SKU">
+    <xsd:restriction base="xsd:string">
+      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
+    </xsd:restriction>
+  </xsd:simpleType>
+
+</xsd:schema>
diff --git a/scripts/jaxb-ri/samples/synchronized-methods/poInput.xml b/scripts/jaxb-ri/samples/synchronized-methods/poInput.xml
new file mode 100644
index 0000000..f3a10ae
--- /dev/null
+++ b/scripts/jaxb-ri/samples/synchronized-methods/poInput.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<purchaseOrder orderDate="1999-10-20">
+  <shipTo country="US">
+    <name>Alice Smith</name>
+    <street>123 Maple Street</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+  </shipTo>
+  <billTo country="US">
+    <name>Robert Smith</name>
+    <street>8 Oak Avenue</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+  </billTo>
+  <items>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-MU">
+      <productName>The Mummy (1959)</productName>
+      <quantity>3</quantity>
+      <USPrice>19.98</USPrice>
+    </item>
+    <item partNum="242-GZ">
+      <productName>Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora</productName>
+      <quantity>3</quantity>
+      <USPrice>27.95</USPrice>
+    </item>
+  </items>
+</purchaseOrder>
diff --git a/scripts/jaxb-ri/samples/synchronized-methods/readme.txt b/scripts/jaxb-ri/samples/synchronized-methods/readme.txt
new file mode 100644
index 0000000..ecdac8d
--- /dev/null
+++ b/scripts/jaxb-ri/samples/synchronized-methods/readme.txt
@@ -0,0 +1,10 @@
+** UNSUPPORTED ** THIS FUNCTIONALITY MAY BE REMOVED IN FUTURE.
+
+This example shows how to use the JAXB RI synchronized method extension.
+
+This extension changes the generated code in the following way:
+
+  - Each generated method will have the "synchronized" keyword.
+  
+To enable this extension, you have to specify the "-Xsync-methods" switch
+on the command line.
diff --git a/scripts/jaxb-ri/samples/synchronized-methods/sample.meta b/scripts/jaxb-ri/samples/synchronized-methods/sample.meta
new file mode 100644
index 0000000..96e9ee4
--- /dev/null
+++ b/scripts/jaxb-ri/samples/synchronized-methods/sample.meta
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0.1">
+    <title>Generating synchronized methods</title>
+    <description><![CDATA[
+      This sample shows how to use the new non-standard synchronized
+      method support. By following the instructions in the readme.txt,
+      you can cause all of the generated impl class methods signatures
+      to contain the "synchronized" keyword.
+    ]]></description>
+        
+    <project>
+        <xjc extension="true" schema="po.xsd" package="primer.myPo">
+            <arg value="-Xsync-methods" />
+        </xjc>
+        <javadoc/>
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/type-substitution/address.xsd b/scripts/jaxb-ri/samples/type-substitution/address.xsd
new file mode 100644
index 0000000..9e249e4
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/address.xsd
@@ -0,0 +1,76 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+        <!-- Addresses for International Purchase Order schema, address.xsd -->
+
+<schema targetNamespace="http://www.example.com/IPO"
+        xmlns="http://www.w3.org/2001/XMLSchema"
+        xmlns:ipo="http://www.example.com/IPO">
+
+  <complexType name="Address">
+    <sequence>
+      <element name="name" type="string"/>
+      <element name="street" type="string"/>
+      <element name="city" type="string"/>
+    </sequence>
+  </complexType>
+
+  <complexType name="USAddress">
+    <complexContent>
+      <extension base="ipo:Address">
+        <sequence>
+          <element name="state" type="ipo:USState"/>
+          <element name="zip" type="positiveInteger"/>
+        </sequence>
+      </extension>
+    </complexContent>
+  </complexType>
+
+  <complexType name="UKAddress">
+    <complexContent>
+      <extension base="ipo:Address">
+        <sequence>
+          <element name="postcode" type="ipo:UKPostcode"/>
+        </sequence>
+        <attribute name="exportCode" type="positiveInteger" fixed="1"/>
+      </extension>
+    </complexContent>
+  </complexType>
+
+  <!-- other Address derivations for more countries -->
+
+  <simpleType name="USState">
+    <restriction base="string">
+      <enumeration value="AK"/>
+      <enumeration value="AL"/>
+      <enumeration value="AR"/>
+      <enumeration value="PA"/>
+      <enumeration value="MA"/>
+      <!-- and so on ... -->
+    </restriction>
+  </simpleType>
+
+  <!-- simple type definition for UKPostcode -->
+  <simpleType name="Postcode">
+    <restriction base="string">
+      <length value="7" fixed="true"/>
+    </restriction>
+  </simpleType>
+
+  <simpleType name="UKPostcode">
+    <restriction base="ipo:Postcode">
+      <pattern value="[A-Z]{2}\d\s\d[A-Z]{2}"/>
+    </restriction>
+  </simpleType>
+
+</schema>
+
diff --git a/scripts/jaxb-ri/samples/type-substitution/build.golden.regexp b/scripts/jaxb-ri/samples/type-substitution/build.golden.regexp
new file mode 100644
index 0000000..01175e9
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/build.golden.regexp
@@ -0,0 +1,128 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] Original Purchase Order
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<ns2\:purchaseOrder xmlns\:ns2\=\"http\:\/\/www\.example\.com\/IPO\" orderDate\=\"1999\-12\-01\"\>
+     \[java\]     \<shipTo xmlns\:xsi\=\"http\:\/\/www\.w3\.org\/2001\/XMLSchema\-instance\" xsi\:type\=\"ns2\:UKAddress\" exportCode\=\"1\"\>
+     \[java\]         \<name\>Helen Zoe\<\/name\>
+     \[java\]         \<street\>47 Eden Street\<\/street\>
+     \[java\]         \<city\>Cambridge\<\/city\>
+     \[java\]         \<postcode\>CB1 1JR\<\/postcode\>
+     \[java\]     \<\/shipTo\>
+     \[java\]     \<billTo xmlns\:xsi\=\"http\:\/\/www\.w3\.org\/2001\/XMLSchema\-instance\" xsi\:type\=\"ns2\:USAddress\"\>
+     \[java\]         \<name\>Robert Smith\<\/name\>
+     \[java\]         \<street\>8 Oak Avenue\<\/street\>
+     \[java\]         \<city\>Old Town\<\/city\>
+     \[java\]         \<state\>PA\<\/state\>
+     \[java\]         \<zip\>95819\<\/zip\>
+     \[java\]     \<\/billTo\>
+     \[java\]     \<items\>
+     \[java\]         \<item partNum\=\"833\-AA\"\>
+     \[java\]             \<productName\>Lapis necklace\<\/productName\>
+     \[java\]             \<quantity\>1\<\/quantity\>
+     \[java\]             \<USPrice\>99\.95\<\/USPrice\>
+     \[java\]             \<ns2\:comment\>Want this for the holidays\!\<\/ns2\:comment\>
+     \[java\]             \<shipDate\>1999\-12\-05\<\/shipDate\>
+     \[java\]         \<\/item\>
+     \[java\]     \<\/items\>
+     \[java\] \<\/ns2\:purchaseOrder\>
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+     \[java\] Return Merchandise\. Ship and Bill address reversed\.
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<ns2\:purchaseOrder xmlns\:ns2\=\"http\:\/\/www\.example\.com\/IPO\" orderDate\=\"1999\-12\-01\"\>
+     \[java\]     \<shipTo xmlns\:xsi\=\"http\:\/\/www\.w3\.org\/2001\/XMLSchema\-instance\" xsi\:type\=\"ns2\:USAddress\"\>
+     \[java\]         \<name\>Robert Smith\<\/name\>
+     \[java\]         \<street\>8 Oak Avenue\<\/street\>
+     \[java\]         \<city\>Old Town\<\/city\>
+     \[java\]         \<state\>PA\<\/state\>
+     \[java\]         \<zip\>95819\<\/zip\>
+     \[java\]     \<\/shipTo\>
+     \[java\]     \<billTo xmlns\:xsi\=\"http\:\/\/www\.w3\.org\/2001\/XMLSchema\-instance\" xsi\:type\=\"ns2\:UKAddress\" exportCode\=\"1\"\>
+     \[java\]         \<name\>Helen Zoe\<\/name\>
+     \[java\]         \<street\>47 Eden Street\<\/street\>
+     \[java\]         \<city\>Cambridge\<\/city\>
+     \[java\]         \<postcode\>CB1 1JR\<\/postcode\>
+     \[java\]     \<\/billTo\>
+     \[java\]     \<items\>
+     \[java\]         \<item partNum\=\"833\-AA\"\>
+     \[java\]             \<productName\>Lapis necklace\<\/productName\>
+     \[java\]             \<quantity\>1\<\/quantity\>
+     \[java\]             \<USPrice\>99\.95\<\/USPrice\>
+     \[java\]             \<ns2\:comment\>Want this for the holidays\!\<\/ns2\:comment\>
+     \[java\]             \<shipDate\>1999\-12\-05\<\/shipDate\>
+     \[java\]         \<\/item\>
+     \[java\]     \<\/items\>
+     \[java\] \<\/ns2\:purchaseOrder\>
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+     \[java\] Tax Exempt Purchase Order composed within Application\.
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<ns2\:purchaseOrder xmlns\:ns2\=\"http\:\/\/www\.example\.com\/IPO\" xmlns\:xsi\=\"http\:\/\/www\.w3\.org\/2001\/XMLSchema\-instance\" xsi\:type\=\"ns2\:USTaxExemptPurchaseOrderType\" orderDate\=\"1999\-12\-01\"\>
+     \[java\]     \<shipTo xsi\:type\=\"ns2\:USAddress\"\>
+     \[java\]         \<name\>Robert Smith\<\/name\>
+     \[java\]         \<street\>8 Oak Avenue\<\/street\>
+     \[java\]         \<city\>Old Town\<\/city\>
+     \[java\]         \<state\>PA\<\/state\>
+     \[java\]         \<zip\>95819\<\/zip\>
+     \[java\]     \<\/shipTo\>
+     \[java\]     \<billTo xsi\:type\=\"ns2\:USAddress\"\>
+     \[java\]         \<name\>Robert Smith\<\/name\>
+     \[java\]         \<street\>8 Oak Avenue\<\/street\>
+     \[java\]         \<city\>Old Town\<\/city\>
+     \[java\]         \<state\>PA\<\/state\>
+     \[java\]         \<zip\>95819\<\/zip\>
+     \[java\]     \<\/billTo\>
+     \[java\]     \<items\>
+     \[java\]         \<item partNum\=\"833\-AA\"\>
+     \[java\]             \<productName\>Lapis necklace\<\/productName\>
+     \[java\]             \<quantity\>1\<\/quantity\>
+     \[java\]             \<USPrice\>99\.95\<\/USPrice\>
+     \[java\]             \<ns2\:comment\>Want this for the holidays\!\<\/ns2\:comment\>
+     \[java\]             \<shipDate\>1999\-12\-05\<\/shipDate\>
+     \[java\]         \<\/item\>
+     \[java\]     \<\/items\>
+     \[java\]     \<taxExemptId\>charity007\<\/taxExemptId\>
+     \[java\] \<\/ns2\:purchaseOrder\>
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+     \[java\] US Tax exempt id\: charity44987
+     \[java\] Tax Exempt Purchase Order
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<ns2\:purchaseOrder xmlns\:ns2\=\"http\:\/\/www\.example\.com\/IPO\" xmlns\:xsi\=\"http\:\/\/www\.w3\.org\/2001\/XMLSchema\-instance\" xsi\:type\=\"ns2\:USTaxExemptPurchaseOrderType\" orderDate\=\"1999\-12\-01\"\>
+     \[java\]     \<shipTo xsi\:type\=\"ns2\:USAddress\"\>
+     \[java\]         \<name\>Jimmy Fund\<\/name\>
+     \[java\]         \<street\>Lansdowne Street\<\/street\>
+     \[java\]         \<city\>Boston\<\/city\>
+     \[java\]         \<state\>MA\<\/state\>
+     \[java\]         \<zip\>95819\<\/zip\>
+     \[java\]     \<\/shipTo\>
+     \[java\]     \<billTo xsi\:type\=\"ns2\:USAddress\"\>
+     \[java\]         \<name\>Jimmy Fund\<\/name\>
+     \[java\]         \<street\>Lansdowne Street\<\/street\>
+     \[java\]         \<city\>Boston\<\/city\>
+     \[java\]         \<state\>MA\<\/state\>
+     \[java\]         \<zip\>95819\<\/zip\>
+     \[java\]     \<\/billTo\>
+     \[java\]     \<items\>
+     \[java\]         \<item partNum\=\"833\-AA\"\>
+     \[java\]             \<productName\>Brochures\<\/productName\>
+     \[java\]             \<quantity\>10000\<\/quantity\>
+     \[java\]             \<USPrice\>99\.95\<\/USPrice\>
+     \[java\]             \<ns2\:comment\>\<\/ns2\:comment\>
+     \[java\]             \<shipDate\>1999\-12\-05\<\/shipDate\>
+     \[java\]         \<\/item\>
+     \[java\]     \<\/items\>
+     \[java\]     \<taxExemptId\>charity44987\<\/taxExemptId\>
+     \[java\] \<\/ns2\:purchaseOrder\>
+     \[java\] \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+
+BUILD SUCCESSFUL
+Total time\: .* seconds
diff --git a/scripts/jaxb-ri/samples/type-substitution/build.xml b/scripts/jaxb-ri/samples/type-substitution/build.xml
new file mode 100644
index 0000000..9e8738d
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/build.xml
@@ -0,0 +1,72 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+      This sample app demonstrates type substitution using
+      the W3C XML Schema Part 0: Primer international purchase order schema.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc catalog="catalog.cat" destdir="gen-src">
+      <schema dir=".">
+        <include name="ipo.xsd" />
+        <include name="ustaxexemptpo.xsd" />
+      </schema>
+      <produces dir="gen-src" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="Type substitutoin support" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/type-substitution/catalog.cat b/scripts/jaxb-ri/samples/type-substitution/catalog.cat
new file mode 100644
index 0000000..79a9419
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/catalog.cat
@@ -0,0 +1,37 @@
+<!--
+    Copyright (c) 2005, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+-->
+
+<!--
+  sample catalog file.
+  
+  double hyphens are used to begin and end a comment section.
+  
+  
+  SYSTEM "<reference>" "<actualLocation>" will define a simple
+  redirection. Whenever XJC tries to load a file from <reference>,
+  this statement will redirect it to <actualLocation>.
+  <refence> needs to be an absolute URI, and <actualLocation> can
+  be relative to the catalog file itself.
+  
+  PUBLIC "<publicId>" "<actualLocation>" will define a mapping
+  from public ID to its actual location. This is only used in
+  conjunction with DTD.
+-->
+
+<!DOCTYPE catalog>
+
+    <catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"
+         prefer="system">
+
+    <system
+           systemId="http://www.example.com/schemas/address.xsd"
+           uri="address.xsd" />
+
+</catalog>
\ No newline at end of file
diff --git a/scripts/jaxb-ri/samples/type-substitution/ipo.xml b/scripts/jaxb-ri/samples/type-substitution/ipo.xml
new file mode 100644
index 0000000..224356c
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/ipo.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<ipo:purchaseOrder
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xmlns:ipo="http://www.example.com/IPO"
+        orderDate="1999-12-01">
+
+  <shipTo exportCode="1" xsi:type="ipo:UKAddress">
+    <name>Helen Zoe</name>
+    <street>47 Eden Street</street>
+    <city>Cambridge</city>
+    <postcode>CB1 1JR</postcode>
+  </shipTo>
+
+  <billTo xsi:type="ipo:USAddress">
+    <name>Robert Smith</name>
+    <street>8 Oak Avenue</street>
+    <city>Old Town</city>
+    <state>PA</state>
+    <zip>95819</zip>
+  </billTo>
+
+  <items>
+    <item partNum="833-AA">
+      <productName>Lapis necklace</productName>
+      <quantity>1</quantity>
+      <USPrice>99.95</USPrice>
+      <ipo:comment>Want this for the holidays!</ipo:comment>
+      <shipDate>1999-12-05</shipDate>
+    </item>
+  </items>
+</ipo:purchaseOrder>
diff --git a/scripts/jaxb-ri/samples/type-substitution/ipo.xsd b/scripts/jaxb-ri/samples/type-substitution/ipo.xsd
new file mode 100644
index 0000000..51a7480
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/ipo.xsd
@@ -0,0 +1,63 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<schema targetNamespace="http://www.example.com/IPO"
+        xmlns="http://www.w3.org/2001/XMLSchema"
+        xmlns:ipo="http://www.example.com/IPO">
+
+  <!-- include address constructs -->
+  <include schemaLocation="address.xsd"/>
+
+  <element name="purchaseOrder" type="ipo:PurchaseOrderType"/>
+
+  <element name="comment" type="string"/>
+
+  <complexType name="PurchaseOrderType">
+    <sequence>
+      <element name="shipTo" type="ipo:Address"/>
+      <element name="billTo" type="ipo:Address"/>
+      <element ref="ipo:comment" minOccurs="0"/>
+      <element name="items" type="ipo:Items"/>
+    </sequence>
+    <attribute name="orderDate" type="date"/>
+  </complexType>
+
+  <complexType name="Items">
+    <sequence>
+      <element name="item" minOccurs="0" maxOccurs="unbounded">
+        <complexType>
+          <sequence>
+            <element name="productName" type="string"/>
+            <element name="quantity">
+              <simpleType>
+                <restriction base="positiveInteger">
+                  <maxExclusive value="100"/>
+                </restriction>
+              </simpleType>
+            </element>
+            <element name="USPrice" type="decimal"/>
+            <element ref="ipo:comment" minOccurs="0"/>
+            <element name="shipDate" type="date" minOccurs="0"/>
+          </sequence>
+          <attribute name="partNum" type="ipo:SKU" use="required"/>
+        </complexType>
+      </element>
+    </sequence>
+  </complexType>
+
+  <simpleType name="SKU">
+    <restriction base="string">
+      <pattern value="\d{3}-[A-Z]{2}"/>
+    </restriction>
+  </simpleType>
+
+</schema>
diff --git a/scripts/jaxb-ri/samples/type-substitution/sample.meta b/scripts/jaxb-ri/samples/type-substitution/sample.meta
new file mode 100644
index 0000000..e968983
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/sample.meta
@@ -0,0 +1,32 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0.2">
+    <title>Type substitutoin support</title>
+    <description><![CDATA[
+      This sample app demonstrates type substitution using
+      the W3C XML Schema Part 0: Primer international purchase order schema.
+    ]]></description>
+        
+    <project>
+        <xjc catalog="catalog.cat">
+          <schema dir=".">
+             <include name="ipo.xsd"/>
+             <include name="ustaxexemptpo.xsd"/>
+          </schema>
+        </xjc>
+        <javadoc/>
+        <java mainClass="Main" />
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/type-substitution/src/Main.java b/scripts/jaxb-ri/samples/type-substitution/src/Main.java
new file mode 100644
index 0000000..7c579e0
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/src/Main.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.FileInputStream;
+import java.io.IOException;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBElement;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Marshaller;
+import jakarta.xml.bind.Unmarshaller;
+
+// import java content classes generated by binding compiler
+import com.example.ipo.*;
+
+/*
+ * $Id: Main.java,v 1.2 2009-11-11 14:17:31 pavel_bucek Exp $
+ */
+ 
+public class Main {
+    
+    // This sample application demonstrates type substitution using
+    // using schema example at http://www.w3.org/TR/xmlschema-0/#UseDerivInInstDocs.
+    
+    public static void main( String[] args ) {
+        try {
+            // create a JAXBContext capable of handling classes generated into
+            // the com.example.ipo package.
+            JAXBContext jc = JAXBContext.newInstance( "com.example.ipo" );
+            
+            // create an Unmarshaller
+            Unmarshaller u = jc.createUnmarshaller();
+            
+            // unmarshal a po instance document into a tree of Java content
+            // objects composed of classes from the "com.example.ipo" package
+            JAXBElement<PurchaseOrderType>  poe = 
+                (JAXBElement<PurchaseOrderType>)u.unmarshal( new FileInputStream( "ipo.xml" ) );
+	    PurchaseOrderType po = poe.getValue();
+
+            // create a Marshaller and marshal to a file
+	    System.out.println("Original Purchase Order");
+            Marshaller m = jc.createMarshaller();
+            m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
+            m.marshal( poe, System.out );
+	    System.out.println("******************************************************");
+
+            // Process a return. Reverse purchase order addresses.
+            Address billToAddress = po.getBillTo();
+            Address shipToAddress = po.getShipTo();
+	    po.setBillTo(shipToAddress);
+	    po.setShipTo(billToAddress);
+
+	    System.out.println("Return Merchandise. Ship and Bill address reversed.");
+            m.marshal( poe, System.out );
+	    System.out.println("******************************************************");
+
+	    /*********************************************************************/
+	    // Illustrate setting a type substitution on a jakarta.xml.bind.Element instance.
+
+            USTaxExemptPurchaseOrderType uspo = 
+		new ObjectFactory().createUSTaxExemptPurchaseOrderType();
+	    uspo.setShipTo(billToAddress);
+	    uspo.setBillTo(billToAddress);
+            uspo.setTaxExemptId("charity007");
+            uspo.setOrderDate(po.getOrderDate());
+            uspo.setComment(po.getComment());
+
+	    Items items = new ObjectFactory().createItems();
+	    items.getItem().addAll(po.getItems().getItem());
+	    uspo.setItems(items);
+	    
+            //PurchaseOrder element type in schema is "PurchaseOrderType".
+            //Set it to an instance of type "USTaxExemptPurchaseOrderType" that
+            //extends (derives using XML terminology) from "PurchaseOrderType".
+	    poe.setValue(uspo);
+	    System.out.println("Tax Exempt Purchase Order composed within Application.");
+            m.marshal( poe, System.out );
+	    System.out.println("******************************************************");
+
+	    /*********************************************************************/
+	    // Unmarshal and manipulate a global element that has a document specifed 
+            // type substitution. (@xsi:type specified on element in instance document.)
+
+            // unmarshal an instance document that identifies derived type 
+	    // "ipo:USTaxExemptPurchaseOrder" for global root element <ipo:purchaseOrder>. 
+            poe = (JAXBElement<PurchaseOrderType>)u.unmarshal( new FileInputStream( "ustaxexemptpo.xml" ) );
+
+            // Access data added to element <ipo:purchaseOrder> via type substitution.
+            // All data added by derivation by extension from the element's original
+            // type specified in the schema must be accessed through this unwrapping
+            // of the element.
+            PurchaseOrderType pot = poe.getValue();
+            if (poe.isTypeSubstituted() && 
+		pot instanceof USTaxExemptPurchaseOrderType) {
+		USTaxExemptPurchaseOrderType taxexemptpo = (USTaxExemptPurchaseOrderType)pot;
+		System.out.println("US Tax exempt id: " + taxexemptpo.getTaxExemptId());
+	    }
+
+            // create a Marshaller and marshal to a file
+	    System.out.println("Tax Exempt Purchase Order");
+            m.marshal( poe, System.out );
+	    System.out.println("******************************************************");
+
+            
+        } catch( JAXBException je ) {
+            je.printStackTrace();
+        } catch( IOException ioe ) {
+            ioe.printStackTrace();
+        } catch(Exception e) {
+	    e.printStackTrace();
+	}
+    }
+}
diff --git a/scripts/jaxb-ri/samples/type-substitution/ustaxexemptpo.xml b/scripts/jaxb-ri/samples/type-substitution/ustaxexemptpo.xml
new file mode 100644
index 0000000..67a8ec0
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/ustaxexemptpo.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<ipo:purchaseOrder xsi:type="ipo:USTaxExemptPurchaseOrderType"
+                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+                   xmlns:ipo="http://www.example.com/IPO"
+                   orderDate="1999-12-01">
+
+  <shipTo xsi:type="ipo:USAddress">
+    <name>Jimmy Fund</name>
+    <street>Lansdowne Street</street>
+    <city>Boston</city>
+    <state>MA</state>
+    <zip>95819</zip>
+  </shipTo>
+
+  <billTo xsi:type="ipo:USAddress">
+    <name>Jimmy Fund</name>
+    <street>Lansdowne Street</street>
+    <city>Boston</city>
+    <state>MA</state>
+    <zip>95819</zip>
+  </billTo>
+
+  <items>
+    <item partNum="833-AA">
+      <productName>Brochures</productName>
+      <quantity>10000</quantity>
+      <USPrice>99.95</USPrice>
+      <ipo:comment></ipo:comment>
+      <shipDate>1999-12-05</shipDate>
+    </item>
+  </items>
+  <taxExemptId>charity44987</taxExemptId>
+</ipo:purchaseOrder>
diff --git a/scripts/jaxb-ri/samples/type-substitution/ustaxexemptpo.xsd b/scripts/jaxb-ri/samples/type-substitution/ustaxexemptpo.xsd
new file mode 100644
index 0000000..02afb8b
--- /dev/null
+++ b/scripts/jaxb-ri/samples/type-substitution/ustaxexemptpo.xsd
@@ -0,0 +1,27 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<schema targetNamespace="http://www.example.com/IPO"
+        xmlns="http://www.w3.org/2001/XMLSchema"
+        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+        xmlns:ipo="http://www.example.com/IPO">
+  <include schemaLocation="ipo.xsd"/>
+  <complexType name="USTaxExemptPurchaseOrderType">
+    <complexContent>
+      <extension base="ipo:PurchaseOrderType">
+        <sequence>
+          <element name="taxExemptId" type="xsd:string"/>
+        </sequence>
+      </extension>
+    </complexContent>
+  </complexType>
+</schema>
diff --git a/scripts/jaxb-ri/samples/unmarshal-read/build.golden.regexp b/scripts/jaxb-ri/samples/unmarshal-read/build.golden.regexp
new file mode 100644
index 0000000..c7c73cd
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-read/build.golden.regexp
@@ -0,0 +1,25 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] Ship the following items to\: 
+     \[java\] 	Alice Smith
+     \[java\] 	123 Maple Street
+     \[java\] 	Cambridge\, MA 12345
+     \[java\] 	US
+
+     \[java\] 	5 copies of \"Nosferatu \- Special Edition \(1929\)\"
+     \[java\] 	3 copies of \"The Mummy \(1959\)\"
+     \[java\] 	3 copies of \"Godzilla and Mothra\: Battle for Earth\/Godzilla vs\. King Ghidora\"
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/unmarshal-read/build.xml b/scripts/jaxb-ri/samples/unmarshal-read/build.xml
new file mode 100644
index 0000000..5844f09
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-read/build.xml
@@ -0,0 +1,68 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+      This sample application demonstrates how to unmarshal an instance document
+      into a Java content tree and access data contained within it.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc schema="po.xsd" package="primer.po" destdir="gen-src">
+      <produces dir="gen-src/primer.po" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="Using unmarshaller (formerly SampleApp1)" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/unmarshal-read/po.xml b/scripts/jaxb-ri/samples/unmarshal-read/po.xml
new file mode 100644
index 0000000..f3a10ae
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-read/po.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<purchaseOrder orderDate="1999-10-20">
+  <shipTo country="US">
+    <name>Alice Smith</name>
+    <street>123 Maple Street</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+  </shipTo>
+  <billTo country="US">
+    <name>Robert Smith</name>
+    <street>8 Oak Avenue</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+  </billTo>
+  <items>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-MU">
+      <productName>The Mummy (1959)</productName>
+      <quantity>3</quantity>
+      <USPrice>19.98</USPrice>
+    </item>
+    <item partNum="242-GZ">
+      <productName>Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora</productName>
+      <quantity>3</quantity>
+      <USPrice>27.95</USPrice>
+    </item>
+  </items>
+</purchaseOrder>
diff --git a/scripts/jaxb-ri/samples/unmarshal-read/po.xsd b/scripts/jaxb-ri/samples/unmarshal-read/po.xsd
new file mode 100644
index 0000000..641c17e
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-read/po.xsd
@@ -0,0 +1,67 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
+  <xsd:element name="comment" type="xsd:string"/>
+  <xsd:complexType name="PurchaseOrderType">
+    <xsd:sequence>
+      <xsd:element name="shipTo" type="USAddress"/>
+      <xsd:element name="billTo" type="USAddress"/>
+      <xsd:element ref="comment" minOccurs="0"/>
+      <xsd:element name="items" type="Items"/>
+    </xsd:sequence>
+    <xsd:attribute name="orderDate" type="xsd:date"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="USAddress">
+    <xsd:sequence>
+      <xsd:element name="name" type="xsd:string"/>
+      <xsd:element name="street" type="xsd:string"/>
+      <xsd:element name="city" type="xsd:string"/>
+      <xsd:element name="state" type="xsd:string"/>
+      <xsd:element name="zip" type="xsd:decimal"/>
+    </xsd:sequence>
+    <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="Items">
+    <xsd:sequence>
+      <xsd:element name="item" minOccurs="1" maxOccurs="unbounded">
+        <xsd:complexType>
+          <xsd:sequence>
+            <xsd:element name="productName" type="xsd:string"/>
+            <xsd:element name="quantity">
+              <xsd:simpleType>
+                <xsd:restriction base="xsd:positiveInteger">
+                  <xsd:maxExclusive value="100"/>
+                </xsd:restriction>
+              </xsd:simpleType>
+            </xsd:element>
+            <xsd:element name="USPrice" type="xsd:decimal"/>
+            <xsd:element ref="comment" minOccurs="0"/>
+            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
+          </xsd:sequence>
+          <xsd:attribute name="partNum" type="SKU" use="required"/>
+        </xsd:complexType>
+      </xsd:element>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <!-- Stock Keeping Unit, a code for identifying products -->
+  <xsd:simpleType name="SKU">
+    <xsd:restriction base="xsd:string">
+      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
+    </xsd:restriction>
+  </xsd:simpleType>
+
+</xsd:schema>
diff --git a/scripts/jaxb-ri/samples/unmarshal-read/sample.meta b/scripts/jaxb-ri/samples/unmarshal-read/sample.meta
new file mode 100644
index 0000000..f49a7a7
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-read/sample.meta
@@ -0,0 +1,27 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0">
+    <title>Using unmarshaller (formerly SampleApp1)</title>
+    <description><![CDATA[
+      This sample application demonstrates how to unmarshal an instance document
+      into a Java content tree and access data contained within it.
+    ]]></description>
+        
+    <project>
+        <xjc schema="po.xsd" package="primer.po"/>
+        <javadoc/>
+        <java mainClass="Main" />
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/unmarshal-read/src/Main.java b/scripts/jaxb-ri/samples/unmarshal-read/src/Main.java
new file mode 100644
index 0000000..9a452bb
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-read/src/Main.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBElement;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Unmarshaller;
+
+// import java content classes generated by binding compiler
+import primer.po.*;
+
+/*
+ * $Id: Main.java,v 1.1 2007-12-05 00:49:46 kohsuke Exp $
+ */
+ 
+public class Main {
+    
+    // This sample application demonstrates how to unmarshal an instance
+    // document into a Java content tree and access data contained within it.
+    
+    public static void main( String[] args ) {
+        try {
+            // create a JAXBContext capable of handling classes generated into
+            // the primer.po package
+            JAXBContext jc = JAXBContext.newInstance( "primer.po" );
+            
+            // create an Unmarshaller
+            Unmarshaller u = jc.createUnmarshaller();
+            
+            // unmarshal a po instance document into a tree of Java content
+            // objects composed of classes from the primer.po package.
+            JAXBElement<?> poElement = 
+		(JAXBElement<?>)u.unmarshal( new FileInputStream( "po.xml" ) );
+            PurchaseOrderType po = (PurchaseOrderType)poElement.getValue();
+                
+	    
+            // examine some of the content in the PurchaseOrder
+            System.out.println( "Ship the following items to: " );
+            
+            // display the shipping address
+            USAddress address = po.getShipTo();
+            displayAddress( address );
+            
+            // display the items
+            Items items = po.getItems();
+            displayItems( items );
+            
+        } catch( JAXBException je ) {
+            je.printStackTrace();
+        } catch( IOException ioe ) {
+            ioe.printStackTrace();
+        }
+    }
+    
+    public static void displayAddress( USAddress address ) {
+        // display the address
+        System.out.println( "\t" + address.getName() );
+        System.out.println( "\t" + address.getStreet() ); 
+        System.out.println( "\t" + address.getCity() +
+                            ", " + address.getState() + 
+                            " "  + address.getZip() ); 
+        System.out.println( "\t" + address.getCountry() + "\n"); 
+    }
+    
+    public static void displayItems( Items items ) {
+        // the items object contains a List of primer.po.ItemType objects
+        List itemTypeList = items.getItem();
+
+                
+        // iterate over List
+        for( Iterator iter = itemTypeList.iterator(); iter.hasNext(); ) {
+            Items.Item item = (Items.Item)iter.next(); 
+            System.out.println( "\t" + item.getQuantity() +
+                                " copies of \"" + item.getProductName() +
+                                "\"" ); 
+        }
+    }
+}
diff --git a/scripts/jaxb-ri/samples/unmarshal-validate/build.golden.regexp b/scripts/jaxb-ri/samples/unmarshal-validate/build.golden.regexp
new file mode 100644
index 0000000..8e44394
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-validate/build.golden.regexp
@@ -0,0 +1,64 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] NOTE\: This sample is working correctly if you see validation errors\!\!
+     \[java\] Line\:Col\[7\:14\]\:http\:\/\/www\.w3\.org\/TR\/xml\-schema\-1#cvc\-complex\-type\.2\.4\.a\?zip\&\{\"\"\:state\}
+     \[java\] Line\:Col\[14\:14\]\:http\:\/\/www\.w3\.org\/TR\/xml\-schema\-1#cvc\-complex\-type\.2\.4\.a\?zip\&\{\"\"\:state\}
+     \[java\] Line\:Col\[19\:30\]\:http\:\/\/www\.w3\.org\/TR\/xml\-schema\-1#cvc\-minInclusive\-valid\?\-1\&1\&null
+     \[java\] Line\:Col\[19\:30\]\:http\:\/\/www\.w3\.org\/TR\/xml\-schema\-1#cvc\-type\.3\.1\.3\?quantity\&\-1
+     \[java\] Line\:Col\[24\:30\]\:http\:\/\/www\.w3\.org\/TR\/xml\-schema\-1#cvc\-minInclusive\-valid\?\-2\&1\&null
+     \[java\] Line\:Col\[24\:30\]\:http\:\/\/www\.w3\.org\/TR\/xml\-schema\-1#cvc\-type\.3\.1\.3\?quantity\&\-2
+     \[java\] Line\:Col\[32\:12\]\:http\:\/\/www\.w3\.org\/TR\/xml\-schema\-1#cvc\-complex\-type\.4\?item\&partNum
+     \[java\] Line\:Col\[33\:17\]\:http\:\/\/www\.w3\.org\/TR\/xml\-schema\-1#cvc\-complex\-type\.2\.4\.a\?quantity\&\{\"\"\:productName\}
+
+     \[java\] Still able to marshal invalid document
+     \[java\] \<\?xml version\=\"1\.0\" encoding\=\"UTF\-8\" standalone\=\"yes\"\?\>
+     \[java\] \<purchaseOrder orderDate\=\"1999\-10\-20\"\>
+     \[java\]     \<shipTo country\=\"US\"\>
+     \[java\]         \<name\>Alice Smith\<\/name\>
+     \[java\]         \<street\>123 Maple Street\<\/street\>
+     \[java\]         \<city\>Cambridge\<\/city\>
+     \[java\]         \<state\>MA\<\/state\>
+     \[java\]         \<zip\>12345\<\/zip\>
+     \[java\]     \<\/shipTo\>
+     \[java\]     \<billTo country\=\"US\"\>
+     \[java\]         \<name\>Robert Smith\<\/name\>
+     \[java\]         \<street\>8 Oak Avenue\<\/street\>
+     \[java\]         \<city\>Cambridge\<\/city\>
+     \[java\]         \<zip\>12345\<\/zip\>
+     \[java\]     \<\/billTo\>
+     \[java\]     \<items\>
+     \[java\]         \<item partNum\=\"242\-NO\"\>
+     \[java\]             \<productName\>Nosferatu \- Special Edition \(1929\)\<\/productName\>
+     \[java\]             \<quantity\>\-1\<\/quantity\>
+     \[java\]             \<USPrice\>19\.99\<\/USPrice\>
+     \[java\]         \<\/item\>
+     \[java\]         \<item partNum\=\"242\-MU\"\>
+     \[java\]             \<productName\>The Mummy \(1959\)\<\/productName\>
+     \[java\]             \<quantity\>\-2\<\/quantity\>
+     \[java\]             \<USPrice\>19\.98\<\/USPrice\>
+     \[java\]         \<\/item\>
+     \[java\]         \<item partNum\=\"242\-GZ\"\>
+     \[java\]             \<productName\>Godzilla and Mothra\: Battle for Earth\/Godzilla vs\. King Ghidora\<\/productName\>
+     \[java\]             \<quantity\>3\<\/quantity\>
+     \[java\]             \<USPrice\>27\.95\<\/USPrice\>
+     \[java\]         \<\/item\>
+     \[java\]         \<item\>
+     \[java\]             \<productName\>Godzilla and Mothra\: Battle for Earth\/Godzilla vs\. King Ghidora\<\/productName\>
+     \[java\]             \<quantity\>3\<\/quantity\>
+     \[java\]         \<\/item\>
+     \[java\]     \<\/items\>
+     \[java\] \<\/purchaseOrder\>
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/unmarshal-validate/build.xml b/scripts/jaxb-ri/samples/unmarshal-validate/build.xml
new file mode 100644
index 0000000..5817205
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-validate/build.xml
@@ -0,0 +1,68 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+			This sample application demonstrates how to enable
+			validation during the unmarshal operations.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc schema="po.xsd" package="primer.po" destdir="gen-src">
+      <produces dir="gen-src/primer.po" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="validating unmarshaller (formerly SampleApp4)" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/unmarshal-validate/po.xml b/scripts/jaxb-ri/samples/unmarshal-validate/po.xml
new file mode 100644
index 0000000..40fc1d8
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-validate/po.xml
@@ -0,0 +1,49 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<purchaseOrder orderDate="1999-10-20">
+  <shipTo country="US">
+    <name>Alice Smith</name>
+    <street>123 Maple Street</street>
+    <city>Cambridge</city>
+    <zip>12345</zip>
+    <state>MA</state>
+  </shipTo>
+  <billTo country="US">
+    <name>Robert Smith</name>
+    <street>8 Oak Avenue</street>
+    <city>Cambridge</city>
+    <zip>12345</zip>
+  </billTo>
+  <items>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>-1</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-MU">
+      <productName>The Mummy (1959)</productName>
+      <quantity>-2</quantity>
+      <USPrice>19.98</USPrice>
+    </item>
+    <item partNum="242-GZ">
+      <productName>Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora</productName>
+      <quantity>3</quantity>
+      <USPrice>27.95</USPrice>
+    </item>
+    <item>
+      <quantity>3</quantity>
+      <productName>Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora</productName>
+    </item>
+  </items>
+</purchaseOrder>
diff --git a/scripts/jaxb-ri/samples/unmarshal-validate/po.xsd b/scripts/jaxb-ri/samples/unmarshal-validate/po.xsd
new file mode 100644
index 0000000..641c17e
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-validate/po.xsd
@@ -0,0 +1,67 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
+  <xsd:element name="comment" type="xsd:string"/>
+  <xsd:complexType name="PurchaseOrderType">
+    <xsd:sequence>
+      <xsd:element name="shipTo" type="USAddress"/>
+      <xsd:element name="billTo" type="USAddress"/>
+      <xsd:element ref="comment" minOccurs="0"/>
+      <xsd:element name="items" type="Items"/>
+    </xsd:sequence>
+    <xsd:attribute name="orderDate" type="xsd:date"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="USAddress">
+    <xsd:sequence>
+      <xsd:element name="name" type="xsd:string"/>
+      <xsd:element name="street" type="xsd:string"/>
+      <xsd:element name="city" type="xsd:string"/>
+      <xsd:element name="state" type="xsd:string"/>
+      <xsd:element name="zip" type="xsd:decimal"/>
+    </xsd:sequence>
+    <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="Items">
+    <xsd:sequence>
+      <xsd:element name="item" minOccurs="1" maxOccurs="unbounded">
+        <xsd:complexType>
+          <xsd:sequence>
+            <xsd:element name="productName" type="xsd:string"/>
+            <xsd:element name="quantity">
+              <xsd:simpleType>
+                <xsd:restriction base="xsd:positiveInteger">
+                  <xsd:maxExclusive value="100"/>
+                </xsd:restriction>
+              </xsd:simpleType>
+            </xsd:element>
+            <xsd:element name="USPrice" type="xsd:decimal"/>
+            <xsd:element ref="comment" minOccurs="0"/>
+            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
+          </xsd:sequence>
+          <xsd:attribute name="partNum" type="SKU" use="required"/>
+        </xsd:complexType>
+      </xsd:element>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <!-- Stock Keeping Unit, a code for identifying products -->
+  <xsd:simpleType name="SKU">
+    <xsd:restriction base="xsd:string">
+      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
+    </xsd:restriction>
+  </xsd:simpleType>
+
+</xsd:schema>
diff --git a/scripts/jaxb-ri/samples/unmarshal-validate/sample.meta b/scripts/jaxb-ri/samples/unmarshal-validate/sample.meta
new file mode 100644
index 0000000..7871641
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-validate/sample.meta
@@ -0,0 +1,29 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0">
+    <title>validating unmarshaller (formerly SampleApp4)</title>
+    <description><![CDATA[
+			This sample application demonstrates how to enable
+			validation during the unmarshal operations.
+    ]]></description>
+        
+    <readme/>
+    
+    <project>
+        <xjc schema="po.xsd" package="primer.po"/>
+        <javadoc/>
+        <java mainClass="Main" />
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/unmarshal-validate/src/Main.java b/scripts/jaxb-ri/samples/unmarshal-validate/src/Main.java
new file mode 100644
index 0000000..d027fd1
--- /dev/null
+++ b/scripts/jaxb-ri/samples/unmarshal-validate/src/Main.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.File;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Marshaller;
+import jakarta.xml.bind.UnmarshalException;
+import jakarta.xml.bind.Unmarshaller;
+import jakarta.xml.bind.ValidationEvent;
+import jakarta.xml.bind.ValidationEventHandler;
+import jakarta.xml.bind.ValidationEventLocator;
+
+import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Schema;
+
+// import java content classes generated by binding compiler
+import primer.po.*;
+
+/*
+ * $Id: Main.java,v 1.2 2009-11-11 14:17:31 pavel_bucek Exp $
+ */
+ 
+public class Main {
+    
+    // This sample application demonstrates how to enable validation during
+    // the unmarshal operations. 
+    
+    public static void main( String[] args ) {
+        try {
+            // create a JAXBContext capable of handling classes generated into
+            // the primer.po package
+            JAXBContext jc = JAXBContext.newInstance( "primer.po" );
+            
+            // create an Unmarshaller
+            Unmarshaller u = jc.createUnmarshaller();
+
+            SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
+            try {
+                Schema schema = sf.newSchema(new File("po.xsd"));
+                u.setSchema(schema);
+                u.setEventHandler(
+                    new ValidationEventHandler() {
+                        // allow unmarshalling to continue even if there are errors
+                        public boolean handleEvent(ValidationEvent ve) {
+                            // ignore warnings
+                            if (ve.getSeverity() != ValidationEvent.WARNING) {
+                                ValidationEventLocator vel = ve.getLocator();
+                                System.out.println("Line:Col[" + vel.getLineNumber() +
+                                    ":" + vel.getColumnNumber() +
+                                    "]:" + ve.getMessage());
+                            }
+                            return true;
+                        }
+                    }
+                );
+            } catch (org.xml.sax.SAXException se) {
+                System.out.println("Unable to validate due to following error.");
+                se.printStackTrace();
+            }
+            
+            // unmarshal an invalid po instance document into a tree of Java
+            // content objects composed of classes from the primer.po package.
+            System.out.println("NOTE: This sample is working correctly if you see validation errors!!");
+            Object poe = 
+                u.unmarshal( new File( "po.xml" ) );
+
+            // even though document was determined to be invalid unmarshalling,
+            // marshal out result.
+            System.out.println("");
+            System.out.println("Still able to marshal invalid document");
+            Marshaller m = jc.createMarshaller();
+            m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
+            m.marshal(poe, System.out);
+        } catch( UnmarshalException ue ) {
+            // The JAXB specification does not mandate how the JAXB provider
+            // must behave when attempting to unmarshal invalid XML data.  In
+            // those cases, the JAXB provider is allowed to terminate the 
+            // call to unmarshal with an UnmarshalException.
+            System.out.println( "Caught UnmarshalException" );
+        } catch( JAXBException je ) {
+            je.printStackTrace();
+        }
+    }
+}
diff --git a/scripts/jaxb-ri/samples/updateablePartialBind/build.golden.regexp b/scripts/jaxb-ri/samples/updateablePartialBind/build.golden.regexp
new file mode 100644
index 0000000..b0b8746
--- /dev/null
+++ b/scripts/jaxb-ri/samples/updateablePartialBind/build.golden.regexp
@@ -0,0 +1,37 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling 8 source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] Using binder to perform xpath that returns JAXB objects
+     \[java\] Ship Address found by xpath
+     \[java\] 	Alice Smith
+     \[java\] 	123 Maple Street
+     \[java\] 	Cambridge\, MA 12345
+     \[java\] 	US
+
+     \[java\] Bill Address found by xpath
+     \[java\] 	Robert Smith
+     \[java\] 	8 Oak Avenue
+     \[java\] 	Cambridge\, MA 12345
+     \[java\] 	US
+
+     \[java\] items over \$25 found by xpath
+     \[java\] 	5 copies of \"Nosferatu \- Colorized \(1929\)\" price\= 25\.00
+     \[java\] 	3 copies of \"Godzilla and Mothra\: Battle for Earth\/Godzilla vs\. King Ghidora\" price\= 25\.00
+     \[java\] 	5 copies of \"Nosferatu \- Colorized \(1929\)\" price\= 25\.00
+     \[java\] Completed jaxbXpath
+
+     \[java\] Updateable partial binding allowing for schema evolution and preservations of comments in XML document
+     \[java\] Wrote updated DOM representation to file\: processedpo\.xml
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/updateablePartialBind/build.xml b/scripts/jaxb-ri/samples/updateablePartialBind/build.xml
new file mode 100644
index 0000000..c59afb5
--- /dev/null
+++ b/scripts/jaxb-ri/samples/updateablePartialBind/build.xml
@@ -0,0 +1,69 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+      This sample application demonstrates how to partially map a DOM tree
+      to JAXB (using JAXP 1.3 XPath), modify JAXB mapped instance and then update modifications back to
+      the DOM tree.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc schema="po.xsd" package="binder" destdir="gen-src">
+      <produces dir="gen-src/binder" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="UpdateablePartialBinding" fork="true">
+      <classpath refid="classpath" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="Updateable Partial Binding using Binder" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/updateablePartialBind/po.xml b/scripts/jaxb-ri/samples/updateablePartialBind/po.xml
new file mode 100644
index 0000000..d8d0e51
--- /dev/null
+++ b/scripts/jaxb-ri/samples/updateablePartialBind/po.xml
@@ -0,0 +1,105 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<purchaseOrder orderDate="1999-10-20" xmlns:pd="http://example.com">
+  <!-- XML comments preserved by binder -->
+  <shipTo country="US" schemaEvolveAddedAttribute="foo">
+    <name>Alice Smith</name>
+    <street>123 Maple Street</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+    <schemaEvolveAddedElement>42</schemaEvolveAddedElement>
+  </shipTo>
+  <billTo country="US" schemaEvolveAddedAttribute="bar">
+    <name>Robert Smith</name>
+    <street>8 Oak Avenue</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+    <schemaEvolveAddedElement>49</schemaEvolveAddedElement>
+  </billTo>
+  <items>
+    <!-- list of items: XML comments preserved by binder -->
+    <item partNum="243-NO">
+      <productName>Nosferatu - Colorized (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>25.00</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-GZ">
+      <productName>Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora</productName>
+      <quantity>3</quantity>
+      <USPrice>25.00</USPrice>
+    </item>
+    <item partNum="242-MU">
+      <productName>The Mummy (1959)</productName>
+      <quantity>3</quantity>
+      <USPrice>19.98</USPrice>
+    </item>
+    <item partNum="243-NO">
+      <productName>Nosferatu - Colorized (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>25.00</USPrice>
+    </item>
+  </items>
+</purchaseOrder>
diff --git a/scripts/jaxb-ri/samples/updateablePartialBind/po.xsd b/scripts/jaxb-ri/samples/updateablePartialBind/po.xsd
new file mode 100644
index 0000000..1ec4b0d
--- /dev/null
+++ b/scripts/jaxb-ri/samples/updateablePartialBind/po.xsd
@@ -0,0 +1,101 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            jxb:version="3.0"
+            xmlns:jxb="https://jakarta.ee/xml/ns/jaxb"
+        >
+  <xsd:annotation>
+    <xsd:appinfo>
+      <!-- this line causes Items.item to bind to Java class Items.ItemType -->
+      <!-- comment out next line an Items.item binds correctly to Java class Items.Item -->
+      <!--  <jxb:schemaBindings/>  -->
+    </xsd:appinfo>
+  </xsd:annotation>
+  <xsd:element name="purchaseOrder" type="PurchaseOrderType" nillable="true"/>
+  <xsd:element name="comment" type="xsd:string"/>
+  <xsd:complexType name="PurchaseOrderType">
+    <xsd:sequence>
+      <xsd:element name="shipTo" type="USAddress"/>
+      <xsd:element name="billTo" type="USAddress"/>
+      <xsd:element ref="comment" minOccurs="0"/>
+      <xsd:element name="items" type="Items"/>
+    </xsd:sequence>
+    <xsd:attribute name="orderDate" type="xsd:date"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="USAddress">
+    <xsd:sequence>
+      <xsd:element name="name" type="xsd:string"/>
+      <xsd:element name="street" type="xsd:string"/>
+      <xsd:element name="city" type="xsd:string"/>
+      <xsd:element name="state" type="xsd:string"/>
+      <xsd:element name="zip" type="xsd:decimal"/>
+    </xsd:sequence>
+    <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="Items">
+    <xsd:sequence>
+      <xsd:element name="item" minOccurs="1" maxOccurs="unbounded">
+        <xsd:complexType>
+          <xsd:sequence>
+            <xsd:element name="productName" type="xsd:string"/>
+            <xsd:element name="quantity">
+              <xsd:simpleType>
+                <xsd:restriction base="xsd:positiveInteger">
+                  <xsd:maxExclusive value="100"/>
+                </xsd:restriction>
+              </xsd:simpleType>
+            </xsd:element>
+            <xsd:element name="USPrice" type="xsd:string">
+              <xsd:annotation>
+                <xsd:appinfo>
+                  <jxb:property>
+                    <jxb:baseType>
+                      <jxb:javaType name="java.math.BigDecimal"/>
+                    </jxb:baseType>
+                  </jxb:property>
+                </xsd:appinfo>
+              </xsd:annotation>
+            </xsd:element>
+
+            <xsd:element ref="comment" minOccurs="0"/>
+
+            <xsd:element name="shipDate" type="xsd:string" minOccurs="0"/>
+
+          </xsd:sequence>
+          <xsd:attribute name="partNum" type="SKU" use="required"/>
+        </xsd:complexType>
+      </xsd:element>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <!-- Stock Keeping Unit, a code for identifying products -->
+  <xsd:simpleType name="SKU">
+    <xsd:restriction base="xsd:string">
+      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
+    </xsd:restriction>
+  </xsd:simpleType>
+
+  <xsd:complexType name="base" mixed="true">
+  </xsd:complexType>
+
+  <xsd:complexType name="derive" mixed="true">
+    <xsd:sequence>
+      <xsd:element name="aMarkupTag"/>
+    </xsd:sequence>
+  </xsd:complexType>
+
+
+</xsd:schema>
diff --git a/scripts/jaxb-ri/samples/updateablePartialBind/readme.txt b/scripts/jaxb-ri/samples/updateablePartialBind/readme.txt
new file mode 100644
index 0000000..ce9e513
--- /dev/null
+++ b/scripts/jaxb-ri/samples/updateablePartialBind/readme.txt
@@ -0,0 +1,29 @@
+This example illustrates the jakarta.xml.bind.Binder use cases mentioned in Section 4.8.1 of JAXB 2.0 Specification.
+
+- Updateable Partial Binding
+
+The application receives an XML document that follows a later version of the schema than the application is aware 
+of. The parts of the schema that the application needs to read and/or modify have not changed. Thus, the 
+document can be read into an infoset preserving representation, such as DOM, only bind the part of the 
+document that it does still have the correct schema for into the JAXB Java representation of the fragment of the 
+document using Binder.unmarshal from the DOM to the JAXB view. Modify the partial Java representation of the 
+document and then synchronize the modified parts of the Java representation back to the DOM view using 
+Binder.updateXML method. 
+
+In this sample's xml document, elements and attributes are
+added to the shipTo/billTo elements that are not modified by the application. 
+The new children elements and attributes introduced by schema evolution are 
+preserved by updateable partial binding. Also note that XML comments that are 
+typically lost by unmarshal/marshal roundtrip are not lost by using this technique.
+
+- XPATH navigation
+
+Given that binder maintains a relationship between XML infoset view of document and JAXB representation, one can 
+use JAXP 1.3 XPATH on the XML infoset view and use the binder's associative mapping to get from the infoset node 
+to JAXB representation. XPath is used in this example to identify the DOM nodes to bind to JAXB objects.
+
+
+Note that JAXP 1.3 DOM L3 Load/Save  and XPath usage were adapted from JAXP 1.3 Samples.
+
+
+
diff --git a/scripts/jaxb-ri/samples/updateablePartialBind/sample.meta b/scripts/jaxb-ri/samples/updateablePartialBind/sample.meta
new file mode 100644
index 0000000..1cd3ee9
--- /dev/null
+++ b/scripts/jaxb-ri/samples/updateablePartialBind/sample.meta
@@ -0,0 +1,28 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="2.0">
+    <title>Updateable Partial Binding using Binder</title>
+    <description><![CDATA[
+      This sample application demonstrates how to partially map a DOM tree
+      to JAXB (using JAXP 1.3 XPath), modify JAXB mapped instance and then update modifications back to
+      the DOM tree.
+    ]]></description>
+        
+    <project>
+        <xjc schema="po.xsd" package="binder"/>
+        <javadoc/>
+        <java mainClass="UpdateablePartialBinding" />
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/updateablePartialBind/src/UpdateablePartialBinding.java b/scripts/jaxb-ri/samples/updateablePartialBind/src/UpdateablePartialBinding.java
new file mode 100644
index 0000000..e48963f
--- /dev/null
+++ b/scripts/jaxb-ri/samples/updateablePartialBind/src/UpdateablePartialBinding.java
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Collections;
+
+import jakarta.xml.bind.Binder;
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBElement;
+import jakarta.xml.bind.JAXBException;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+import binder.*;
+
+/**
+ * Illustrate Binder use cases from JAXB 2.0 specification.
+ */
+public class UpdateablePartialBinding {
+    public static void main(String[] args) throws Exception {
+        File input = new File("po.xml");
+        File output = new File("processedpo.xml");
+
+        // create a JAXBContext capable of handling classes generated into
+        // the binder package
+        JAXBContext jc = JAXBContext.newInstance("binder");
+
+        // Load XML document into DOM
+        Document doc = loadDocument(input);
+
+        System.out.println("Using binder to perform xpath that returns JAXB objects");
+        xpathUsingBinder(jc.createBinder(), doc);
+        System.out.println("Completed jaxbXpath");
+        System.out.println();
+
+        System.out.println("Updateable partial binding allowing for schema evolution and preservations of comments in XML document");
+        updateablePartialBind(jc.createBinder(), doc);
+
+        saveDocument(doc, output);
+        System.out.println("Wrote updated DOM representation to file: " + output);
+
+    }
+
+    /**
+     * JAXB xpath implemented leveraging Binder and JAXP 1.3 XPath.
+     * 
+     * KNOWN Limitations: 
+     * xpath resolving to an XML attribute can not work since Binder.getJAXBNode() only works for Element, not Attribute.
+     */
+    static public class JAXBXpath {
+        private final Document document;
+        private final Binder<Node> binder;
+        private Object jaxbRootObject;
+
+        public Document getDocument() {
+            return document;
+        }
+
+        public Binder getBinder() {
+            return binder;
+        }
+
+        public Object getJaxbRootObject() {
+            return jaxbRootObject;
+        }
+
+        public JAXBXpath(org.w3c.dom.Document doc, Binder<Node> b) throws JAXBException {
+            binder = b;
+            document = doc;
+            // bind entire DOM document to JAXB
+            jaxbRootObject = binder.unmarshal(document);
+        }
+
+        /**
+         * @param xpathExpr can match zero, one or more nodes in document.
+         * @return List of JAXB objects matching xpathExpr.
+         */
+        private List<Object> evaluateToMany(String xpathExpr) {
+            List<Object> resultList = new ArrayList<Object>();
+            for( Node node : xpath(document, xpathExpr) ) {
+                resultList.add(binder.getJAXBNode(node));
+            }
+            return resultList;
+        }
+
+        /**
+	 * Return JAXB object representing first match of <code>xpathExpr</code> over {@link getDocument()}
+         * @param xpathExpr should only match one node in document.
+         * @return JAXB object matching xpathExpr.
+         */
+        private Object evaluate(String xpathExpr) {
+            List<Node> nodes = xpath(document, xpathExpr);
+            if(nodes.size()>0)
+                return binder.getJAXBNode(nodes.get(0));
+            else
+                return null;
+        }
+    }
+
+    static public void xpathUsingBinder(Binder<Node> binder, Document doc) throws JAXBException {
+        JAXBXpath jaxbXpath = new JAXBXpath(doc, binder);
+
+        //use xpath over DOM to find specific JAXB bound objects.
+        System.out.println("Ship Address found by xpath");
+        displayAddress((USAddress)
+                jaxbXpath.evaluate("/purchaseOrder/shipTo"));
+
+        System.out.println("Bill Address found by xpath");
+        displayAddress((USAddress)
+                jaxbXpath.evaluate("/purchaseOrder/billTo"));
+
+        System.out.println("items over $25 found by xpath");
+        for (Object item : jaxbXpath.evaluateToMany(".//item[USPrice>=25.00]")) {
+            displayItem((Items.Item) item);
+        }
+    }
+
+    public static void displayAddress(USAddress address) {
+        // display the address
+        System.out.println("\t" + address.getName());
+        System.out.println("\t" + address.getStreet());
+        System.out.printf("\t%1s, %2s %3s\n",
+                address.getCity(), address.getState(), address.getZip());
+        System.out.println("\t" + address.getCountry() + "\n");
+    }
+
+    public static void displayItem(Items.Item item) {
+        String result =
+                "\t" + item.getQuantity() +
+                        " copies of \"" + item.getProductName() +
+                        "\"" + " price= " + item.getUSPrice().toString();
+        if (item.getComment() != null) {
+            result += " comment: " + item.getComment();
+        }
+        System.out.println(result);
+    }
+
+
+    static public void updateablePartialBind(Binder<Node> binder, Document doc) throws JAXBException {
+
+        // Partially bind XML document to Java.
+        // Only Nodes matching XPath are bound to JAXB objects.
+        // Binder retains association between DOM and JAXB views.
+        for( Node node : xpath(doc, "//item[USPrice>=25.00]") ) {
+            // Unmarshal by declared type since element Item corresponds with a local element declaration in schema.
+            // Partial Bind DOM Element"item" to instance of JAXB mapped binder.Items.Item class
+            JAXBElement<Items.Item> itemE = binder.unmarshal(node, Items.Item.class);
+            binder.Items.Item item = itemE.getValue();
+
+            // Modify in Java
+            item.setComment("qualifies for free shipping");
+
+            // Sync changes made in Java back to XML document
+	    binder.updateXML(item);
+        }
+
+        // Add $2 shipping per item under $25.
+        for( Node node : xpath(doc, "//item[USPrice<25.00]") ) {
+            // Unmarshal by declared type since element Item corresponds with a local element declaration in schema.
+            // Partial Bind DOM Element"item" to instance of JAXB mapped binder.Items.Item class
+            JAXBElement<Items.Item> itemE =
+                    binder.unmarshal(node, Items.Item.class);
+            binder.Items.Item item = itemE.getValue();
+
+            // Modify in Java
+            item.setUSPrice(item.getUSPrice().add(new BigDecimal("2.00")));
+
+            // Sync changes made in Java back to XML document
+            binder.updateXML(item);
+        }
+    }
+
+
+    static Document loadDocument(File input) throws IOException, SAXException {
+        try {
+            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+            dbf.setNamespaceAware(true);
+            return dbf.newDocumentBuilder().parse(input);
+        } catch (ParserConfigurationException e) {
+            throw new Error(e); // impossible
+        }
+    }
+
+    static public void saveDocument(Document document, File output) throws TransformerException, IOException {
+        Transformer t = TransformerFactory.newInstance().newTransformer();
+        t.transform(new DOMSource(document),new StreamResult(new FileOutputStream(output)));
+    }
+
+
+    static List<Node> xpath(Document document, String xpathExpression) {
+        // create XPath
+        XPathFactory xpf = XPathFactory.newInstance();
+        XPath xpath = xpf.newXPath();
+
+        try {
+            List<Node> result = new ArrayList<Node>();
+            NodeList nl = (NodeList) xpath.evaluate(xpathExpression, document, XPathConstants.NODESET);
+            for( int i=0; i<nl.getLength(); i++ )
+                result.add(nl.item(i));
+            return result;
+        } catch (XPathExpressionException e) {
+            e.printStackTrace();
+            return Collections.emptyList();
+        }
+
+    }
+}
diff --git a/scripts/jaxb-ri/samples/vendor-extensions/build.golden.regexp b/scripts/jaxb-ri/samples/vendor-extensions/build.golden.regexp
new file mode 100644
index 0000000..cec042a
--- /dev/null
+++ b/scripts/jaxb-ri/samples/vendor-extensions/build.golden.regexp
@@ -0,0 +1,22 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] unmarshalling from \"poInput\.xml\"\.\.\.
+     \[java\] Demo superclass override of toString\(\) method for all schema\-derived JAXB classes purchaseOrderType\.toString\(\)\=demoOfToString
+     \[java\] serializing content tree to \"po\.ser\"\.\.\.
+     \[java\] deserializing content tree from \"po\.ser\"\.\.\.
+     \[java\] marshalling to \"poMarshalled\.xml\"\.\.\.
+     \[java\] test complete\.
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/vendor-extensions/build.xml b/scripts/jaxb-ri/samples/vendor-extensions/build.xml
new file mode 100644
index 0000000..66d2867
--- /dev/null
+++ b/scripts/jaxb-ri/samples/vendor-extensions/build.xml
@@ -0,0 +1,69 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+			This example demonstrates how to use 
+			&lt;xjc:superClass&gt; vendor extensions provided by Sun's JAXB RI,
+			as well as &lt;jaxb:serializable&gt; customization.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc extension="true" schema="po.xsd" package="primer.myPo" destdir="gen-src">
+      <produces dir="gen-src/primer.myPo" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="RI-specific customizations" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/vendor-extensions/po.xsd b/scripts/jaxb-ri/samples/vendor-extensions/po.xsd
new file mode 100644
index 0000000..8c752b5
--- /dev/null
+++ b/scripts/jaxb-ri/samples/vendor-extensions/po.xsd
@@ -0,0 +1,80 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+            xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
+            xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
+            jaxb:version="3.0"
+            jaxb:extensionBindingPrefixes="xjc">
+  <xsd:annotation>
+    <xsd:appinfo>
+      <jaxb:globalBindings>
+        <jaxb:serializable uid="1"/>
+        <xjc:superClass name="primer.BaseClass"/>
+      </jaxb:globalBindings>
+    </xsd:appinfo>
+  </xsd:annotation>
+
+  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
+  <xsd:element name="comment" type="xsd:string"/>
+  <xsd:complexType name="PurchaseOrderType">
+    <xsd:sequence>
+      <xsd:element name="shipTo" type="USAddress"/>
+      <xsd:element name="billTo" type="USAddress"/>
+      <xsd:element ref="comment" minOccurs="0"/>
+      <xsd:element name="items" type="Items"/>
+    </xsd:sequence>
+    <xsd:attribute name="orderDate" type="xsd:date"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="USAddress">
+    <xsd:sequence>
+      <xsd:element name="name" type="xsd:string"/>
+      <xsd:element name="street" type="xsd:string"/>
+      <xsd:element name="city" type="xsd:string"/>
+      <xsd:element name="state" type="xsd:string"/>
+      <xsd:element name="zip" type="xsd:decimal"/>
+    </xsd:sequence>
+    <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="Items">
+    <xsd:sequence>
+      <xsd:element name="item" minOccurs="1" maxOccurs="unbounded">
+        <xsd:complexType>
+          <xsd:sequence>
+            <xsd:element name="productName" type="xsd:string"/>
+            <xsd:element name="quantity">
+              <xsd:simpleType>
+                <xsd:restriction base="xsd:positiveInteger">
+                  <xsd:maxExclusive value="100"/>
+                </xsd:restriction>
+              </xsd:simpleType>
+            </xsd:element>
+            <xsd:element name="USPrice" type="xsd:decimal"/>
+            <xsd:element ref="comment" minOccurs="0"/>
+            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
+          </xsd:sequence>
+          <xsd:attribute name="partNum" type="SKU" use="required"/>
+        </xsd:complexType>
+      </xsd:element>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <!-- Stock Keeping Unit, a code for identifying products -->
+  <xsd:simpleType name="SKU">
+    <xsd:restriction base="xsd:string">
+      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
+    </xsd:restriction>
+  </xsd:simpleType>
+
+</xsd:schema>
diff --git a/scripts/jaxb-ri/samples/vendor-extensions/poInput.xml b/scripts/jaxb-ri/samples/vendor-extensions/poInput.xml
new file mode 100644
index 0000000..f3a10ae
--- /dev/null
+++ b/scripts/jaxb-ri/samples/vendor-extensions/poInput.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<purchaseOrder orderDate="1999-10-20">
+  <shipTo country="US">
+    <name>Alice Smith</name>
+    <street>123 Maple Street</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+  </shipTo>
+  <billTo country="US">
+    <name>Robert Smith</name>
+    <street>8 Oak Avenue</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+  </billTo>
+  <items>
+    <item partNum="242-NO">
+      <productName>Nosferatu - Special Edition (1929)</productName>
+      <quantity>5</quantity>
+      <USPrice>19.99</USPrice>
+    </item>
+    <item partNum="242-MU">
+      <productName>The Mummy (1959)</productName>
+      <quantity>3</quantity>
+      <USPrice>19.98</USPrice>
+    </item>
+    <item partNum="242-GZ">
+      <productName>Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora</productName>
+      <quantity>3</quantity>
+      <USPrice>27.95</USPrice>
+    </item>
+  </items>
+</purchaseOrder>
diff --git a/scripts/jaxb-ri/samples/vendor-extensions/sample.meta b/scripts/jaxb-ri/samples/vendor-extensions/sample.meta
new file mode 100644
index 0000000..3da6498
--- /dev/null
+++ b/scripts/jaxb-ri/samples/vendor-extensions/sample.meta
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0">
+    <title>RI-specific customizations</title>
+    <description><![CDATA[
+			This example demonstrates how to use 
+			<xjc:superClass> vendor extensions provided by Sun's JAXB RI,
+			as well as <jaxb:serializable> customization.
+    ]]></description>
+        
+    <readme/>
+    
+    <project>
+        <xjc extension="true" schema="po.xsd" package="primer.myPo"/>
+        <javadoc/>
+        <java mainClass="Main" />
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/vendor-extensions/src/BaseClass.java b/scripts/jaxb-ri/samples/vendor-extensions/src/BaseClass.java
new file mode 100644
index 0000000..30c8cb1
--- /dev/null
+++ b/scripts/jaxb-ri/samples/vendor-extensions/src/BaseClass.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+package primer;
+
+
+/**
+ * This is the superclass vendor extension
+ * that have this class as their super class
+ */
+
+
+public class BaseClass {
+    public String toString() {
+	return "demoOfToString";
+    }
+}
+
diff --git a/scripts/jaxb-ri/samples/vendor-extensions/src/Main.java b/scripts/jaxb-ri/samples/vendor-extensions/src/Main.java
new file mode 100644
index 0000000..9426b3f
--- /dev/null
+++ b/scripts/jaxb-ri/samples/vendor-extensions/src/Main.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.*;
+
+import jakarta.xml.bind.*;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
+
+import org.xml.sax.SAXException;
+
+// import java content classes generated by binding compiler
+import primer.myPo.*;
+
+/*
+ * $Id: Main.java,v 1.1 2007-12-05 00:49:48 kohsuke Exp $
+ */
+public class Main {
+    
+    // This sample application demonstrates how to modify a java content
+    // tree and marshal it back to a xml data. This example demonstrates
+    // customiation within the schema file, po.xsd, and the impact that these 
+    // customizations have on the schema derived Java representation.
+    
+/*
+      XML --> Unmarshal -->Serialize
+       |                        |
+       ?=                       |
+       |                        v
+      XML <-- Marshal <--Deserialize
+*/
+
+    public static void main( String[] args ) {
+        final String INPUT_XML_FILE="poInput.xml";
+	final String SERIALIZE_FILE="po.ser";
+        final String DESERIALIZED_XML="poMarshalled.xml";
+        SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
+
+        try {
+            Schema schema = sf.newSchema(new File("po.xsd"));
+            JAXBContext jc = JAXBContext.newInstance("primer.myPo");
+            Unmarshaller unmarshaller = jc.createUnmarshaller();
+            unmarshaller.setSchema(schema);
+            Marshaller marshaller = jc.createMarshaller();
+            marshaller.setSchema(schema);
+            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT ,
+                   new Boolean(true));
+            System.out.println( "unmarshalling from \"" + INPUT_XML_FILE + "\"..." );
+            Object po = unmarshaller.unmarshal(new File(INPUT_XML_FILE));
+            PurchaseOrderType pot = (PurchaseOrderType)((JAXBElement)po).getValue();
+	    System.out.println("Demo superclass override of toString() method for all schema-derived JAXB classes purchaseOrderType.toString()=" + pot.toString());
+
+            System.out.println( "serializing content tree to \"" + SERIALIZE_FILE + "\"..." );
+            FileOutputStream out = new FileOutputStream(SERIALIZE_FILE);
+            ObjectOutputStream objOut = new ObjectOutputStream(out);
+            objOut.writeObject(po);
+            objOut.flush();
+	    out.close();
+
+            System.out.println( "deserializing content tree from \"" + SERIALIZE_FILE + "\"..." );
+            FileInputStream in = new FileInputStream(SERIALIZE_FILE);
+            ObjectInputStream objIn = new ObjectInputStream(in);
+            po=objIn.readObject();
+
+            System.out.println( "marshalling to \"" + DESERIALIZED_XML + "\"..." );
+            FileOutputStream mout = 
+		new FileOutputStream(DESERIALIZED_XML);
+            marshaller.marshal(po, mout);
+	    in.close();
+	    mout.close();
+
+            System.out.println( "test complete." );
+        } catch( JAXBException je ) {
+            je.printStackTrace();
+        } catch( SAXException se ) {
+            se.printStackTrace();
+        } catch( IOException ioe ) {
+            ioe.printStackTrace();
+        } catch ( ClassNotFoundException cnfe) {
+            cnfe.printStackTrace();
+        }
+    }
+}
+
diff --git a/scripts/jaxb-ri/samples/xml-channel/build.golden.regexp b/scripts/jaxb-ri/samples/xml-channel/build.golden.regexp
new file mode 100644
index 0000000..e038a42
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-channel/build.golden.regexp
@@ -0,0 +1,30 @@
+
+jar-check:
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] accepted a connection from a client
+     \[java\] Message\: message 1
+     \[java\] Message\: message 2
+     \[java\] Message\: message 3
+     \[java\] Message\: message 4
+     \[java\] Message\: message 5
+     \[java\] Message\: message 6
+     \[java\] Message\: message 7
+     \[java\] Message\: message 8
+     \[java\] Message\: message 9
+     \[java\] Message\: message 10
+     \[java\] Bye\!
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/xml-channel/build.xml b/scripts/jaxb-ri/samples/xml-channel/build.xml
new file mode 100644
index 0000000..8e53ea7
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-channel/build.xml
@@ -0,0 +1,87 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+      This example demonstrates how one can use one communication channel
+      (such as a socket) to send multiple XML messages, and how it can be
+      combined with JAXB.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <mkdir dir="lib"/>
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <!--additional jar files for this sample-->
+    <fileset dir="lib" includes="*.jar" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--
+    Check if the necessary jar files are properly installed.
+  -->
+  <target name="jar-check">
+    <available file="lib/sjsxp.jar" property="sjsxp.jar-present" />
+    <fail unless="sjsxp.jar-present">
+      Please download sjsxp.jar from the web and place it in the lib directory.
+
+      Alternatively download from maven central:
+      mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get -DremoteRepositories=http://download.java.net/maven/2 \
+      -Dartifact=com.sun.xml.stream:sjsxp:LATEST -Ddest=./lib/sjsxp.jar
+
+    </fail>
+  </target>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files" depends="jar-check">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc schema="message.xsd" package="message" destdir="gen-src">
+      <produces dir="gen-src/message" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Test" fork="true">
+      <classpath refid="classpath" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="XML message passing via socket" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/xml-channel/message.xsd b/scripts/jaxb-ri/samples/xml-channel/message.xsd
new file mode 100644
index 0000000..3f898aa
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-channel/message.xsd
@@ -0,0 +1,16 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+  <xsd:element name="message" type="xsd:string"/>
+</xsd:schema>
+
diff --git a/scripts/jaxb-ri/samples/xml-channel/readme.txt b/scripts/jaxb-ri/samples/xml-channel/readme.txt
new file mode 100644
index 0000000..a3e2400
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-channel/readme.txt
@@ -0,0 +1,39 @@
+This example demonstrates how one can use one communication channel
+(such as a socket) to send multiple XML messages, and how it can be
+combined with JAXB.
+
+XML1.0 requires a conforming parser to read the entire data till end
+of the stream (because a parser needs to handle documents like
+<root/><!-- post root comment -->). As a result, a naive attempt to
+keep one OutputStream open and marshal objects multiple times fails.
+
+This example shows you how to work around this limitation. In this
+example, the data on the wire will look like the following:
+
+<conversation>
+  <!-- message 1 -->
+  <message>
+    ...
+  </message>
+
+  <!-- message 2 -->
+  <message>
+    ...
+  </message>
+
+  ...
+</conversation>
+
+The <conversation> start tag is sent immediately after the socket
+is opened. This works as a container to send multiple "messages",
+and this is also an excellent opportunity to do the hand-shaking
+(e.g., protocol-version='1.0' attribute.)
+
+Once the <conversation> tag is written, multiple "documents" can
+be marshalled as a tree into the channel, possibility with a large
+time lag in between. In this example, each message is written by
+one marshaller invocation.
+
+When the client wants to disconnect the channel, it can do so by
+sending the </conversation> end tag, followed by the socket
+disconnection. 
\ No newline at end of file
diff --git a/scripts/jaxb-ri/samples/xml-channel/sample.meta b/scripts/jaxb-ri/samples/xml-channel/sample.meta
new file mode 100644
index 0000000..564dfd9
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-channel/sample.meta
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0">
+    <title>XML message passing via socket</title>
+    <description><![CDATA[
+      This example demonstrates how one can use one communication channel
+      (such as a socket) to send multiple XML messages, and how it can be
+      combined with JAXB.
+    ]]></description>
+        
+    <readme/>
+    
+    <project>
+        <depends>
+          <jar name="sjsxp.jar" from="http://java.sun.com"/>
+        </depends>
+        <xjc schema="message.xsd" package="message"/>
+        <javadoc/>
+        <java mainClass="Test" />
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/xml-channel/src/Test.java b/scripts/jaxb-ri/samples/xml-channel/src/Test.java
new file mode 100644
index 0000000..d4c6497
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-channel/src/Test.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+/**
+ * 
+ * 
+ * @author
+ *     Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
+ */
+public class Test {
+
+    public static Object lock = new Object();
+    public static boolean ready = false;
+    
+    public static void main(String[] args) throws Exception {
+        // launch the server
+        new Thread(new TestServer()).start();
+
+        // wait for the server to become ready
+        while( !ready ) {
+            synchronized( lock ) {
+                lock.wait(1000);
+            }
+        }
+        
+        // reset the flag
+        ready = false;
+        
+        // run the client
+        new TestClient().run();
+
+        // wait for the server to finish processing data  
+        // from the client 
+        while( !ready ) {
+            synchronized( lock ) {
+                lock.wait(1000);
+            }
+        }
+
+        System.exit(0);
+    }
+}
diff --git a/scripts/jaxb-ri/samples/xml-channel/src/TestClient.java b/scripts/jaxb-ri/samples/xml-channel/src/TestClient.java
new file mode 100644
index 0000000..e1da706
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-channel/src/TestClient.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.net.Socket;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBElement;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Marshaller;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.stream.XMLStreamException;
+
+import message.*;
+
+/**
+ * Test client.
+ * 
+ * @author
+ *     Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
+ */
+public class TestClient implements Runnable {
+
+    private ObjectFactory of;
+    private Marshaller marshaller;
+
+    public TestClient() {
+        try {
+	    JAXBContext jc = JAXBContext.newInstance("message");
+	    marshaller = jc.createMarshaller();
+        marshaller.setProperty(Marshaller.JAXB_FRAGMENT,true);
+	    of = new ObjectFactory();
+        } catch( JAXBException e ) {
+            e.printStackTrace(); // impossible
+        }
+    }
+    
+    public void run() {
+        try {
+            // create a socket connection and start conversation
+            Socket socket = new Socket("localhost",38247);
+            XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(socket.getOutputStream());
+
+            // write the dummy start tag
+            xsw.writeStartDocument();
+            xsw.writeStartElement("conversation");
+
+            for( int i=1; i<=10; i++ ) {
+                Thread.sleep(1000);
+                sendMessage(xsw,"message "+i);
+            }
+
+            Thread.sleep(1000);
+
+            xsw.writeEndElement();
+            xsw.writeEndDocument();
+            xsw.close();
+        } catch( Exception e ) {
+            e.printStackTrace();
+        }
+    }
+    
+    private void sendMessage( XMLStreamWriter xsw, String msg ) throws JAXBException, XMLStreamException {
+        JAXBElement<String> m = of.createMessage(msg);
+        marshaller.marshal(m,xsw);
+        xsw.flush();    // send it now
+    }
+}
diff --git a/scripts/jaxb-ri/samples/xml-channel/src/TestServer.java b/scripts/jaxb-ri/samples/xml-channel/src/TestServer.java
new file mode 100644
index 0000000..89ce075
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-channel/src/TestServer.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.Socket;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBElement;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Unmarshaller;
+import javax.xml.stream.XMLEventReader;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+
+/**
+ * Server program that displays the messages sent from clients.
+ * 
+ * @author
+ *     Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
+ */
+public class TestServer implements Runnable {
+
+    private final XMLInputFactory xif;
+
+    public TestServer() {
+        this.xif = XMLInputFactory.newInstance();
+    }
+
+
+    public void run() {
+        try {
+            ServerSocket ss = new ServerSocket(38247);
+            JAXBContext context = JAXBContext.newInstance("message");
+
+            // notify test driver that we are ready to accept
+            synchronized( Test.lock ) {
+                Test.ready = true;
+                Test.lock.notifyAll();
+            }
+            
+            while(true) {
+                new Worker(ss.accept(),context).start();
+            }
+        } catch( Exception e ) {
+            e.printStackTrace();
+        }
+        die();
+    }
+    
+    class Worker extends Thread {
+        private final XMLEventReader xer;
+        private final Unmarshaller unmarshaller;
+        
+        Worker( Socket socket, JAXBContext context ) throws IOException, JAXBException, XMLStreamException {
+            System.out.println("accepted a connection from a client");
+            synchronized(TestServer.this) {
+                xer = xif.createXMLEventReader(socket.getInputStream());
+            }
+            this.unmarshaller = context.createUnmarshaller();
+        }
+        
+        public void run() {
+            try {
+                xer.nextEvent();    // read the start document
+                xer.nextTag(); // get to the first <conversation> tag, and skip
+
+                while( xer.peek().isStartElement() ) {
+                    // unmarshal a new object
+                    JAXBElement<String> msg = (JAXBElement<String>)unmarshaller.unmarshal(xer);
+                    System.out.println("Message: "+ msg.getValue());
+                }
+                System.out.println("Bye!");
+                xer.close();
+
+                die();
+            } catch( Exception e ) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    private void die() {
+        // notify the driver that we are done processing
+        synchronized( Test.lock ) {
+            Test.ready = true;
+            Test.lock.notifyAll();
+        }
+    }
+}
diff --git a/scripts/jaxb-ri/samples/xml-stylesheet/Primer.xsd b/scripts/jaxb-ri/samples/xml-stylesheet/Primer.xsd
new file mode 100644
index 0000000..fe6431d
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-stylesheet/Primer.xsd
@@ -0,0 +1,72 @@
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+
+  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
+
+  <xsd:element name="comment" type="xsd:string"/>
+
+  <xsd:complexType name="PurchaseOrderType">
+    <xsd:sequence>
+      <xsd:element name="shipTo" type="USAddress"/>
+      <xsd:element name="billTo" type="USAddress"/>
+      <xsd:element ref="comment" minOccurs="0"/>
+      <xsd:element name="items" type="Items"/>
+    </xsd:sequence>
+    <xsd:attribute name="orderDate" type="xsd:date"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="USAddress">
+    <xsd:sequence>
+      <xsd:element name="name" type="xsd:string"/>
+      <xsd:element name="street" type="xsd:string"/>
+      <xsd:element name="city" type="xsd:string"/>
+      <xsd:element name="state" type="xsd:string"/>
+      <xsd:element name="zip" type="xsd:decimal"/>
+    </xsd:sequence>
+    <xsd:attribute name="country" type="xsd:NMTOKEN"
+                   fixed="US"/>
+  </xsd:complexType>
+
+  <xsd:complexType name="Items">
+    <xsd:sequence>
+      <xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
+        <xsd:complexType>
+          <xsd:sequence>
+            <xsd:element name="productName" type="xsd:string"/>
+            <xsd:element name="quantity">
+              <xsd:simpleType>
+                <xsd:restriction base="xsd:positiveInteger">
+                  <xsd:maxExclusive value="100"/>
+                </xsd:restriction>
+              </xsd:simpleType>
+            </xsd:element>
+            <xsd:element name="USPrice" type="xsd:decimal"/>
+            <xsd:element ref="comment" minOccurs="0"/>
+            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
+          </xsd:sequence>
+          <xsd:attribute name="partNum" type="SKU" use="required"/>
+        </xsd:complexType>
+      </xsd:element>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <!-- Stock Keeping Unit, a code for identifying products -->
+  <xsd:simpleType name="SKU">
+    <xsd:restriction base="xsd:string">
+      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
+    </xsd:restriction>
+  </xsd:simpleType>
+
+</xsd:schema>
+
diff --git a/scripts/jaxb-ri/samples/xml-stylesheet/build.golden.regexp b/scripts/jaxb-ri/samples/xml-stylesheet/build.golden.regexp
new file mode 100644
index 0000000..a96b2fb
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-stylesheet/build.golden.regexp
@@ -0,0 +1,19 @@
+
+compile\:
+     \[echo\] Compiling the schema\.\.\.
+    \[mkdir\] Created dir\: .*
+      \[xjc\] .* is not found and thus excluded from the dependency check
+      \[xjc\] Compiling .*
+      \[xjc\] Writing output to .*
+     \[echo\] Compiling the java source files\.\.\.
+    \[mkdir\] Created dir\: .*
+    \[javac\] Compiling \d+ source files to .*
+
+run\:
+     \[echo\] Running the sample application\.\.\.
+     \[java\] \<\?xml version\='1\.0'\?\>
+     \[java\] \<\?xml\-stylesheet type\='text\/xsl' href\='foobar\.xsl' \?\>
+     \[java\] \<purchaseOrder orderDate\=\"1999\-10\-20\"\>\<shipTo country\=\"US\"\>\<name\>Alice Smith\<\/name\>\<street\>123 Maple Street\<\/street\>\<city\>Cambridge\<\/city\>\<state\>MA\<\/state\>\<zip\>12345\<\/zip\>\<\/shipTo\>\<billTo country\=\"US\"\>\<name\>Robert Smith\<\/name\>\<street\>8 Oak Avenue\<\/street\>\<city\>Cambridge\<\/city\>\<state\>MA\<\/state\>\<zip\>12345\<\/zip\>\<\/billTo\>\<items\/\>\<\/purchaseOrder\>
+
+BUILD SUCCESSFUL
+Total time\: .*
diff --git a/scripts/jaxb-ri/samples/xml-stylesheet/build.xml b/scripts/jaxb-ri/samples/xml-stylesheet/build.xml
new file mode 100644
index 0000000..212ce89
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-stylesheet/build.xml
@@ -0,0 +1,70 @@
+<?xml version="1.0" standalone="yes"?>
+<!--
+
+    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<project basedir="." default="run">
+  <description>
+        A common customization need for the marshalling output is
+        about introducing extra processing instruction and/or DOCTYPE declaration.
+        This example demonstrates how such modification can be done easily.
+    </description>
+  <property name="jaxb.home" value="../.." />
+  <path id="classpath">
+    <pathelement path="src" />
+    <pathelement path="classes" />
+    <pathelement path="schemas" />
+    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
+  </path>
+  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
+    <classpath refid="classpath" />
+  </taskdef>
+
+  <!--compile Java source files-->
+  <target name="compile" description="Compile all Java source files">
+    <echo message="Compiling the schema..." />
+    <mkdir dir="gen-src" />
+    <xjc schema="Primer.xsd" package="primer" destdir="gen-src">
+      <produces dir="gen-src/primer" includes="**/*.java" />
+    </xjc>
+    <echo message="Compiling the java source files..." />
+    <mkdir dir="classes" />
+    <javac destdir="classes" debug="on">
+      <src path="src" />
+      <src path="gen-src" />
+      <classpath refid="classpath" />
+    </javac>
+  </target>
+
+  <target name="run" depends="compile" description="Run the sample app">
+    <echo message="Running the sample application..." />
+    <java classname="Main" fork="true">
+      <classpath refid="classpath" />
+      <arg value="test.xml" />
+    </java>
+  </target>
+
+  <target name="javadoc" description="Generates javadoc" depends="compile">
+    <echo message="Generating javadoc..." />
+    <mkdir dir="docs/api" />
+    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="Marshalling output customization" useexternalfile="yes">
+      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
+    </javadoc>
+  </target>
+
+  <target name="clean" description="Deletes all the generated artifacts.">
+    <delete dir="docs/api" />
+    <delete dir="gen-src" />
+    <delete dir="schemas" />
+    <delete dir="classes" />
+  </target>
+</project>
+
diff --git a/scripts/jaxb-ri/samples/xml-stylesheet/readme.txt b/scripts/jaxb-ri/samples/xml-stylesheet/readme.txt
new file mode 100644
index 0000000..2e61963
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-stylesheet/readme.txt
@@ -0,0 +1,15 @@
+This example demonstrates how the behavior of the marshalling process 
+can be customized.
+
+In this example, an <?xml-stylesheet ... ?> processing instruction is 
+inserted into the marshalled document. This is done by using a custom 
+XMLFilter and have it receive marshalled XML document, before it's 
+actually formatted into text.
+
+This technique is useful when the change you need to make to the 
+marshalled document is relatively small. To do a full-blown 
+transformation, you should consider XSLT.
+
+Note: This sample application requires that you add xalan.jar to your
+classpath.  Please use the version of Xalan released with the version
+of JAXP bundled with the JWSDP.
\ No newline at end of file
diff --git a/scripts/jaxb-ri/samples/xml-stylesheet/sample.meta b/scripts/jaxb-ri/samples/xml-stylesheet/sample.meta
new file mode 100644
index 0000000..ceb55f0
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-stylesheet/sample.meta
@@ -0,0 +1,32 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 2017, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<sample since="1.0">
+    <title>Marshalling output customization</title>
+    <description><![CDATA[
+        A common customization need for the marshalling output is
+        about introducing extra processing instruction and/or DOCTYPE declaration.
+        This example demonstrates how such modification can be done easily.
+    ]]></description>
+        
+    <project>
+        <xjc schema="Primer.xsd" package="primer"/>
+        
+        <javadoc/>
+        
+        <java mainClass="Main">
+            <arg value="test.xml"/>
+        </java>
+    </project>
+    
+</sample>
diff --git a/scripts/jaxb-ri/samples/xml-stylesheet/src/Main.java b/scripts/jaxb-ri/samples/xml-stylesheet/src/Main.java
new file mode 100644
index 0000000..36c3c32
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-stylesheet/src/Main.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0, which is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+import java.io.File;
+
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBElement;
+import jakarta.xml.bind.Marshaller;
+
+import primer.PurchaseOrderType;
+
+/*
+ * @(#)$Id: Main.java,v 1.2 2009-11-11 14:17:28 pavel_bucek Exp $
+ */
+
+public class Main {
+    public static void main( String[] args ) throws Exception {
+        
+        // create JAXBContext for the primer.xsd
+        JAXBContext context = JAXBContext.newInstance("primer");
+        
+        // unmarshal a document, just to marshal it back again.
+        JAXBElement poe = (JAXBElement)context.createUnmarshaller().unmarshal(
+            new File(args[0]));
+        // we don't need to check the return value, because the unmarshal
+        // method should haven thrown an exception if anything went wrong.
+	PurchaseOrderType po = (PurchaseOrderType)poe.getValue();
+        
+        
+        // Here's the real meat.
+        // we configure marshaller not to print out xml decl,
+        // we then print out XML decl plus stylesheet header on our own,
+        // then have the marshaller print the real meat.
+        
+        System.out.println("<?xml version='1.0'?>");
+        System.out.println("<?xml-stylesheet type='text/xsl' href='foobar.xsl' ?>");
+        // if you need to put DOCTYPE decl, it can be easily done here.
+        
+        // create JAXB marshaller.
+        Marshaller m = context.createMarshaller();
+        // configure it
+        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
+        // marshal
+        m.marshal(poe,System.out);
+    }
+
+}
diff --git a/scripts/jaxb-ri/samples/xml-stylesheet/test.xml b/scripts/jaxb-ri/samples/xml-stylesheet/test.xml
new file mode 100644
index 0000000..678fc71
--- /dev/null
+++ b/scripts/jaxb-ri/samples/xml-stylesheet/test.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0"?>
+<!--
+
+    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Distribution License v. 1.0, which is available at
+    http://www.eclipse.org/org/documents/edl-v10.php.
+
+    SPDX-License-Identifier: BSD-3-Clause
+
+-->
+
+<purchaseOrder orderDate="1999-10-20">
+  <shipTo country="US">
+    <name>Alice Smith</name>
+    <street>123 Maple Street</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+  </shipTo>
+  <billTo country="US">
+    <name>Robert Smith</name>
+    <street>8 Oak Avenue</street>
+    <city>Cambridge</city>
+    <state>MA</state>
+    <zip>12345</zip>
+  </billTo>
+  <items/>
+</purchaseOrder>
+
diff --git a/scripts/opos/ngrok.sh b/scripts/opos/ngrok.sh
index e69de29..4c2e83a 100644
--- a/scripts/opos/ngrok.sh
+++ b/scripts/opos/ngrok.sh
@@ -0,0 +1,8 @@
+# configurations
+
+ngrok config add-authtoken "<token>"
+code ~/Library/Application Support/ngrok/ngrok.yml
+
+# expose app outside
+ngrok http http://localhost:8080
+